Skip to content

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

TypeScript

XDSCalendar (#62)

Cindy Zhang75be57558853
diff --git a/.context/proposals/xds-calendar.md b/.context/proposals/xds-calendar.md
new file mode 100644
index 0000000000..d5ae1ac898
--- /dev/null
+++ b/.context/proposals/xds-calendar.md
@@ -0,0 +1,677 @@
+# 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/Button.stories.tsx b/apps/storybook/stories/Button.stories.tsx
index bdbb772958..bdc30c205f 100644
--- a/apps/storybook/stories/Button.stories.tsx
+++ b/apps/storybook/stories/Button.stories.tsx
@@ -1,11 +1,16 @@
-import type { Meta, StoryObj } from '@storybook/react';
-import { XDSButton } from '@xds/core/Button';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSButton} from '@xds/core/Button';
+import {Cog6ToothIcon, TrashIcon} from '@heroicons/react/24/outline';
const meta: Meta<typeof XDSButton> = {
title: 'Core/XDSButton',
component: XDSButton,
tags: ['autodocs'],
argTypes: {
+ label: {
+ control: 'text',
+ description: 'Accessible label (required)',
+ },
variant: {
control: 'select',
options: ['primary', 'secondary', 'ghost', 'destructive'],
@@ -27,68 +32,123 @@ type Story = StoryObj<typeof XDSButton>;
export const Primary: Story = {
args: {
+ label: 'Primary Button',
variant: 'primary',
- children: 'Primary Button',
},
};
export const Secondary: Story = {
args: {
+ label: 'Secondary Button',
variant: 'secondary',
- children: 'Secondary Button',
},
};
export const Ghost: Story = {
args: {
+ label: 'Ghost Button',
variant: 'ghost',
- children: 'Ghost Button',
},
};
export const Destructive: Story = {
args: {
+ label: 'Delete',
variant: 'destructive',
- children: 'Delete',
},
};
export const Loading: Story = {
args: {
+ label: 'Loading...',
variant: 'primary',
loading: true,
- children: 'Loading...',
},
};
export const Disabled: Story = {
args: {
+ label: 'Disabled',
variant: 'primary',
disabled: true,
- children: 'Disabled',
},
};
+export const IconOnly: Story = {
+ render: () => (
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton
+ label="Settings"
+ variant="ghost"
+ icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}
+ />
+ <XDSButton
+ label="Delete"
+ variant="destructive"
+ icon={<TrashIcon style={{width: 16, height: 16}} />}
+ />
+ </div>
+ ),
+};
+
+export const IconWithText: Story = {
+ render: () => (
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton
+ label="Settings"
+ variant="secondary"
+ icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}>
+ Settings
+ </XDSButton>
+ <XDSButton
+ label="Delete"
+ variant="destructive"
+ icon={<TrashIcon style={{width: 16, height: 16}} />}>
+ Delete
+ </XDSButton>
+ </div>
+ ),
+};
+
export const AllVariants: Story = {
render: () => (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', maxWidth: '600px' }}>
- <div style={{ display: 'flex', gap: '12px' }}>
- <XDSButton variant="primary">Primary</XDSButton>
- <XDSButton variant="secondary">Secondary</XDSButton>
- <XDSButton variant="ghost">Ghost</XDSButton>
- <XDSButton variant="destructive">Destructive</XDSButton>
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ maxWidth: '600px',
+ }}>
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton label="Primary" variant="primary" />
+ <XDSButton label="Secondary" variant="secondary" />
+ <XDSButton label="Ghost" variant="ghost" />
+ <XDSButton label="Destructive" variant="destructive" />
+ </div>
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton label="Loading..." variant="primary" loading />
+ <XDSButton label="Loading..." variant="secondary" loading />
+ <XDSButton label="Loading..." variant="ghost" loading />
+ <XDSButton label="Loading..." variant="destructive" loading />
</div>
- <div style={{ display: 'flex', gap: '12px' }}>
- <XDSButton variant="primary" loading>Loading...</XDSButton>
- <XDSButton variant="secondary" loading>Loading...</XDSButton>
- <XDSButton variant="ghost" loading>Loading...</XDSButton>
- <XDSButton variant="destructive" loading>Loading...</XDSButton>
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton label="Disabled" variant="primary" disabled />
+ <XDSButton label="Disabled" variant="secondary" disabled />
+ <XDSButton label="Disabled" variant="ghost" disabled />
+ <XDSButton label="Disabled" variant="destructive" disabled />
</div>
- <div style={{ display: 'flex', gap: '12px' }}>
- <XDSButton variant="primary" disabled>Disabled</XDSButton>
- <XDSButton variant="secondary" disabled>Disabled</XDSButton>
- <XDSButton variant="ghost" disabled>Disabled</XDSButton>
- <XDSButton variant="destructive" disabled>Disabled</XDSButton>
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton
+ label="Settings"
+ variant="ghost"
+ icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}
+ />
+ <XDSButton
+ label="Settings"
+ variant="secondary"
+ icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}>
+ Settings
+ </XDSButton>
</div>
</div>
),
diff --git a/apps/storybook/stories/Calendar.stories.tsx b/apps/storybook/stories/Calendar.stories.tsx
new file mode 100644
index 0000000000..9a687d333f
--- /dev/null
+++ b/apps/storybook/stories/Calendar.stories.tsx
@@ -0,0 +1,237 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ XDSCalendar,
+ type ISODateString,
+ type DateRange,
+} from '@xds/core/Calendar';
+
+const meta: Meta<typeof XDSCalendar> = {
+ title: 'Core/XDSCalendar',
+ component: XDSCalendar,
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSCalendar>;
+
+export const Default: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="single"
+ value={value}
+ onChange={val => setValue(val)}
+ />
+ );
+ },
+};
+
+export const WithSelectedDate: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString>('2026-01-15');
+ return (
+ <XDSCalendar
+ mode="single"
+ value={value}
+ onChange={val => setValue(val)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const RangeSelection: Story = {
+ render: () => {
+ const [value, setValue] = useState<DateRange | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="range"
+ value={value}
+ onChange={range => setValue(range)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const RangeWithValue: Story = {
+ render: () => {
+ const [value, setValue] = useState<DateRange>({
+ start: '2026-01-10',
+ end: '2026-01-20',
+ });
+ return (
+ <XDSCalendar
+ mode="range"
+ value={value}
+ onChange={range => setValue(range)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const TwoMonths: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="single"
+ numberOfMonths={2}
+ value={value}
+ onChange={val => setValue(val)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const TwoMonthsRangeSelection: Story = {
+ render: () => {
+ const [value, setValue] = useState<DateRange | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="range"
+ numberOfMonths={2}
+ value={value}
+ onChange={range => setValue(range)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const WithDateConstraints: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="single"
+ min={'2026-01-10' as ISODateString}
+ max={'2026-01-25' as ISODateString}
+ value={value}
+ onChange={val => setValue(val)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const WeekdaysOnly: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ const isWeekday = (date: Date) => {
+ const day = date.getDay();
+ return day !== 0 && day !== 6;
+ };
+ return (
+ <XDSCalendar
+ mode="single"
+ dateConstraints={[isWeekday]}
+ value={value}
+ onChange={val => setValue(val)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const WithWeekNumbers: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="single"
+ hasWeekNumbers
+ value={value}
+ onChange={val => setValue(val)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const MondayStart: Story = {
+ render: () => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return (
+ <XDSCalendar
+ mode="single"
+ weekStartsOn={1}
+ value={value}
+ onChange={val => setValue(val)}
+ focusDate="2026-01-01"
+ />
+ );
+ },
+};
+
+export const AllVariations: Story = {
+ render: () => {
+ const [singleValue, setSingleValue] = useState<ISODateString | undefined>(
+ undefined,
+ );
+ const [rangeValue, setRangeValue] = useState<DateRange | undefined>(
+ undefined,
+ );
+ const [constrainedValue, setConstrainedValue] = useState<
+ ISODateString | undefined
+ >(undefined);
+
+ const isWeekday = (date: Date) => {
+ const day = date.getDay();
+ return day !== 0 && day !== 6;
+ };
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: '32px'}}>
+ <div>
+ <h3 style={{marginBottom: '8px'}}>Single Date Selection</h3>
+ <XDSCalendar
+ mode="single"
+ value={singleValue}
+ onChange={val => setSingleValue(val)}
+ focusDate="2026-01-01"
+ />
+ <p style={{marginTop: '8px', fontSize: '14px', color: '#666'}}>
+ Selected: {singleValue ?? 'None'}
+ </p>
+ </div>
+
+ <div>
+ <h3 style={{marginBottom: '8px'}}>Range Selection (Two Months)</h3>
+ <XDSCalendar
+ mode="range"
+ numberOfMonths={2}
+ value={rangeValue}
+ onChange={range => setRangeValue(range)}
+ focusDate="2026-01-01"
+ />
+ <p style={{marginTop: '8px', fontSize: '14px', color: '#666'}}>
+ Range:{' '}
+ {rangeValue
+ ? `${rangeValue.start} to ${rangeValue.end}`
+ : 'None selected'}
+ </p>
+ </div>
+
+ <div>
+ <h3 style={{marginBottom: '8px'}}>Weekdays Only with Week Numbers</h3>
+ <XDSCalendar
+ mode="single"
+ hasWeekNumbers
+ dateConstraints={[isWeekday]}
+ value={constrainedValue}
+ onChange={val => setConstrainedValue(val)}
+ focusDate="2026-01-01"
+ />
+ <p style={{marginTop: '8px', fontSize: '14px', color: '#666'}}>
+ Selected: {constrainedValue ?? 'None'}
+ </p>
+ </div>
+ </div>
+ );
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index 5ce4c639f8..724ebde4e0 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -29,6 +29,11 @@
"import": "./dist/Button/index.mjs",
"require": "./dist/Button/index.js"
},
+ "./Calendar": {
+ "types": "./dist/Calendar/index.d.ts",
+ "import": "./dist/Calendar/index.mjs",
+ "require": "./dist/Calendar/index.js"
+ },
"./CheckboxInput": {
"types": "./dist/CheckboxInput/index.d.ts",
"import": "./dist/CheckboxInput/index.mjs",
diff --git a/packages/core/src/Button/XDSButton.test.tsx b/packages/core/src/Button/XDSButton.test.tsx
index 4b3d7119c7..99d94f4611 100644
--- a/packages/core/src/Button/XDSButton.test.tsx
+++ b/packages/core/src/Button/XDSButton.test.tsx
@@ -13,38 +13,63 @@ import userEvent from '@testing-library/user-event';
import {XDSButton} from './XDSButton';
describe('XDSButton', () => {
- it('renders children correctly', () => {
- render(<XDSButton>Click me</XDSButton>);
+ it('renders label as visible text', () => {
+ render(<XDSButton label="Click me" />);
expect(screen.getByRole('button', {name: 'Click me'})).toBeInTheDocument();
});
+ it('renders children instead of label when provided', () => {
+ render(<XDSButton label="Accessible name">Custom content</XDSButton>);
+ const button = screen.getByRole('button');
+ expect(button).toHaveTextContent('Custom content');
+ });
+
it('renders with different variants', () => {
- const {rerender} = render(<XDSButton variant="primary">Primary</XDSButton>);
+ const {rerender} = render(<XDSButton label="Primary" variant="primary" />);
expect(screen.getByRole('button')).toBeInTheDocument();
- rerender(<XDSButton variant="secondary">Secondary</XDSButton>);
+ rerender(<XDSButton label="Secondary" variant="secondary" />);
expect(screen.getByRole('button')).toBeInTheDocument();
- rerender(<XDSButton variant="ghost">Ghost</XDSButton>);
+ rerender(<XDSButton label="Ghost" variant="ghost" />);
expect(screen.getByRole('button')).toBeInTheDocument();
- rerender(<XDSButton variant="destructive">Destructive</XDSButton>);
+ rerender(<XDSButton label="Destructive" variant="destructive" />);
expect(screen.getByRole('button')).toBeInTheDocument();
});
+ it('renders icon-only button with aria-label', () => {
+ render(
+ <XDSButton label="Settings" icon={<span data-testid="icon">⚙</span>} />,
+ );
+ const button = screen.getByRole('button', {name: 'Settings'});
+ expect(button).toHaveAttribute('aria-label', 'Settings');
+ expect(screen.getByTestId('icon')).toBeInTheDocument();
+ });
+
+ it('renders icon with text when both icon and children provided', () => {
+ render(
+ <XDSButton label="Settings" icon={<span data-testid="icon">⚙</span>}>
+ Settings
+ </XDSButton>,
+ );
+ const button = screen.getByRole('button');
+ expect(button).not.toHaveAttribute('aria-label');
+ expect(button).toHaveTextContent('Settings');
+ expect(screen.getByTestId('icon')).toBeInTheDocument();
+ });
+
it('shows loading state with spinner', () => {
- render(<XDSButton loading>Submit</XDSButton>);
+ render(<XDSButton label="Submit" loading />);
const button = screen.getByRole('button');
// Button should be disabled when loading
expect(button).toBeDisabled();
- // Children text should still be present (but visually hidden)
- expect(button).toHaveTextContent('Submit');
});
it('handles click events', async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
- render(<XDSButton onClick={handleClick}>Click me</XDSButton>);
+ render(<XDSButton label="Click me" onClick={handleClick} />);
await user.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
@@ -53,11 +78,7 @@ describe('XDSButton', () => {
it('does not fire click when disabled', async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
- render(
- <XDSButton disabled onClick={handleClick}>
- Click me
- </XDSButton>,
- );
+ render(<XDSButton label="Click me" disabled onClick={handleClick} />);
await user.click(screen.getByRole('button'));
expect(handleClick).not.toHaveBeenCalled();
@@ -66,11 +87,7 @@ describe('XDSButton', () => {
it('does not fire click when loading', async () => {
const user = userEvent.setup();
const handleClick = vi.fn();
- render(
- <XDSButton loading onClick={handleClick}>
- Click me
- </XDSButton>,
- );
+ render(<XDSButton label="Click me" loading onClick={handleClick} />);
await user.click(screen.getByRole('button'));
expect(handleClick).not.toHaveBeenCalled();
@@ -78,7 +95,7 @@ describe('XDSButton', () => {
it('forwards ref correctly', () => {
const ref = vi.fn();
- render(<XDSButton ref={ref}>Test</XDSButton>);
+ render(<XDSButton label="Test" ref={ref} />);
expect(ref).toHaveBeenCalledWith(expect.any(HTMLButtonElement));
});
});
diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsx
index bdb723d4a4..cd86d2a340 100644
--- a/packages/core/src/Button/XDSButton.tsx
+++ b/packages/core/src/Button/XDSButton.tsx
@@ -63,6 +63,10 @@ const styles = stylex.create({
':active': null,
},
},
+ iconOnly: {
+ aspectRatio: '1 / 1',
+ paddingInline: spacingVars['--spacing-2'],
+ },
});
/**
@@ -74,7 +78,7 @@ const styles = stylex.create({
const variants = stylex.create({
primary: {
backgroundColor: colorVars['--color-accent'],
- color: 'white',
+ color: colorVars['--color-text-on-media'],
backgroundImage: {
default: null,
':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
@@ -125,7 +129,7 @@ const variants = stylex.create({
},
destructive: {
backgroundColor: colorVars['--color-negative'],
- color: 'white',
+ color: colorVars['--color-text-on-media'],
backgroundImage: {
default: null,
':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
@@ -161,7 +165,15 @@ declare module '../theme/types' {
}
}
-export interface XDSButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
+export interface XDSButtonProps extends Omit<
+ ButtonHTMLAttributes<HTMLButtonElement>,
+ 'children'
+> {
+ /**
+ * Accessible label for the button (required for accessibility).
+ * Used as visible text, or as aria-label for icon-only buttons.
+ */
+ label: string;
/**
* The visual style variant of the button.
* @default 'secondary'
@@ -173,9 +185,15 @@ export interface XDSButtonProps extends ButtonHTMLAttributes<HTMLButtonElement>
*/
loading?: boolean;
/**
- * Content to render inside the button.
+ * Icon element to render in the button.
+ * If provided without children, button becomes icon-only (square).
*/
- children: ReactNode;
+ icon?: ReactNode;
+ /**
+ * Optional visible content. If omitted and icon is provided,
+ * button becomes icon-only with label used as aria-label.
+ */
+ children?: ReactNode;
}
/**
@@ -203,9 +221,9 @@ const loadingStyles = stylex.create({
animationIterationCount: 'infinite',
},
spinnerLight: {
- borderTopColor: 'white',
- borderLeftColor: 'white',
- borderBottomColor: 'white',
+ borderTopColor: colorVars['--color-icon-on-media'],
+ borderLeftColor: colorVars['--color-icon-on-media'],
+ borderBottomColor: colorVars['--color-icon-on-media'],
borderRightColor: 'transparent',
},
spinnerDark: {
@@ -225,18 +243,28 @@ const loadingStyles = stylex.create({
*
* @example
* ```tsx
- * <XDSButton>Click me</XDSButton>
- * <XDSButton variant="primary">Primary action</XDSButton>
- * <XDSButton variant="destructive">Delete</XDSButton>
+ * <XDSButton label="Click me" />
+ * <XDSButton label="Primary action" variant="primary" />
+ * <XDSButton label="Delete" variant="destructive" />
+ * <XDSButton label="Settings" icon={<GearIcon />} />
* ```
*/
export const XDSButton = forwardRef<HTMLButtonElement, XDSButtonProps>(
(
- {variant = 'secondary', loading = false, disabled, children, ...props},
+ {
+ label,
+ variant = 'secondary',
+ loading = false,
+ icon,
+ disabled,
+ children,
+ ...props
+ },
ref,
) => {
const isDisabled = disabled || loading;
const useLightSpinner = variant === 'primary' || variant === 'destructive';
+ const isIconOnly = icon != null && children == null;
// Get theme context for component-level overrides (optional)
const themeContext = useContext(ThemeContext);
@@ -247,10 +275,12 @@ export const XDSButton = forwardRef<HTMLButtonElement, XDSButtonProps>(
<button
ref={ref}
disabled={isDisabled}
+ aria-label={isIconOnly ? label : undefined}
{...stylex.props(
styles.base,
variants[variant],
themeVariantOverride,
+ isIconOnly && styles.iconOnly,
isDisabled && styles.disabled,
loading && loadingStyles.loading,
)}
@@ -265,7 +295,8 @@ export const XDSButton = forwardRef<HTMLButtonElement, XDSButtonProps>(
)}
/>
)}
- {children}
+ {icon}
+ {children ?? (isIconOnly ? null : label)}
</button>
);
},
diff --git a/packages/core/src/Calendar/README.md b/packages/core/src/Calendar/README.md
new file mode 100644
index 0000000000..05600032ef
--- /dev/null
+++ b/packages/core/src/Calendar/README.md
@@ -0,0 +1,81 @@
+# /packages/core/src/Calendar
+
+XDSCalendar component for date selection with single and range modes.
+
+## Features
+
+- **Selection Modes**: `single` (default) and `range`
+- **Multi-Month Display**: Show 1 or 2 months side by side
+- **Date Constraints**: `min`, `max`, and custom `dateConstraints` functions
+- **Locale Options**: `weekStartsOn` for configurable first day of week
+- **Week Numbers**: Optional ISO week number column
+- **Controlled/Uncontrolled**: Supports both patterns via `value`/`defaultValue`
+
+## Usage
+
+```tsx
+import { XDSCalendar } from '@xds/core/Calendar';
+
+// Single date selection
+<XDSCalendar
+ 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)}
+/>
+
+// Two months with constraints
+<XDSCalendar
+ numberOfMonths={2}
+ min="2026-01-01"
+ max="2026-12-31"
+ weekStartsOn={1}
+/>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| ------------------- | ------------------------------------ | ---------- | ------------------------------ |
+| mode | `'single' \| 'range'` | `'single'` | Selection mode |
+| value | `ISODateString \| DateRange` | — | Controlled selected value |
+| defaultValue | `ISODateString \| DateRange` | — | Uncontrolled default value |
+| onChange | `Function` | — | Selection callback |
+| numberOfMonths | `1 \| 2` | `1` | Number of months to display |
+| min | `ISODateString` | — | Minimum selectable date |
+| max | `ISODateString` | — | Maximum selectable date |
+| dateConstraints | `Array<(date: Date) => boolean>` | — | Custom constraint functions |
+| focusDate | `ISODateString` | — | Controlled visible month |
+| onFocusDateChange | `(focusDate: ISODateString) => void` | — | Navigation callback |
+| hasOutsideDays | `boolean` | `true` | Show days from adjacent months |
+| hasWeekNumbers | `boolean` | `false` | Show ISO week numbers |
+| hasVariableRowCount | `boolean` | `false` | Variable vs fixed 6-row grid |
+| weekStartsOn | `0-6` | `0` | First day of week (0=Sunday) |
+
+## Types
+
+```typescript
+type ISODateString =
+ `${number}${number}${number}${number}-${number}${number}-${number}${number}`;
+
+type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
+
+interface DateRange {
+ start: ISODateString;
+ end: ISODateString;
+}
+```
+
+## Files
+
+| File | Role | Purpose |
+| -------------------- | ------ | ------------------------ |
+| XDSCalendar.tsx | Core | Component implementation |
+| XDSCalendar.test.tsx | Test | Unit tests |
+| index.ts | Export | Public API exports |
+| README.md | Docs | This documentation |
diff --git a/packages/core/src/Calendar/XDSCalendar.test.tsx b/packages/core/src/Calendar/XDSCalendar.test.tsx
new file mode 100644
index 0000000000..02e91b7ce8
--- /dev/null
+++ b/packages/core/src/Calendar/XDSCalendar.test.tsx
@@ -0,0 +1,297 @@
+/**
+ * @file XDSCalendar.test.tsx
+ * @input Uses vitest, @testing-library/react
+ * @output Test suite for XDSCalendar component
+ * @position Tests for XDSCalendar.tsx
+ *
+ * SYNC: When XDSCalendar.tsx changes, update tests accordingly
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSCalendar} from './XDSCalendar';
+
+describe('XDSCalendar', () => {
+ // ─── Basic Rendering ─────────────────────────────────────────
+
+ it('renders current month by default', () => {
+ render(<XDSCalendar />);
+
+ const today = new Date();
+ const formatter = new Intl.DateTimeFormat(undefined, {
+ year: 'numeric',
+ month: 'long',
+ });
+ const expectedLabel = formatter.format(today);
+
+ expect(screen.getByText(expectedLabel)).toBeInTheDocument();
+ });
+
+ it('displays day names', () => {
+ render(<XDSCalendar />);
+
+ expect(screen.getByText('Su')).toBeInTheDocument();
+ expect(screen.getByText('Mo')).toBeInTheDocument();
+ expect(screen.getByText('Tu')).toBeInTheDocument();
+ expect(screen.getByText('We')).toBeInTheDocument();
+ expect(screen.getByText('Th')).toBeInTheDocument();
+ expect(screen.getByText('Fr')).toBeInTheDocument();
+ expect(screen.getByText('Sa')).toBeInTheDocument();
+ });
+
+ it('displays correct number of day cells', () => {
+ render(<XDSCalendar />);
+
+ // 6 rows * 7 days = 42 cells (default fixed row count)
+ const buttons = screen.getAllByRole('gridcell');
+ expect(buttons.length).toBe(42);
+ });
+
+ // ─── Selection ───────────────────────────────────────────────
+
+ it('highlights selected date', () => {
+ render(<XDSCalendar value="2026-01-15" focusDate="2026-01-01" />);
+
+ const day15 = screen.getByRole('gridcell', {name: '15'});
+ expect(day15).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('calls onChange when date is selected', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+
+ render(<XDSCalendar onChange={handleChange} focusDate="2026-01-01" />);
+
+ const day15 = screen.getByRole('gridcell', {name: '15'});
+ await user.click(day15);
+
+ expect(handleChange).toHaveBeenCalledTimes(1);
+ expect(handleChange).toHaveBeenCalledWith('2026-01-15', expect.any(Date));
+ });
+
+ // ─── Navigation ──────────────────────────────────────────────
+
+ it('navigates to previous month', async () => {
+ const user = userEvent.setup();
+
+ render(<XDSCalendar focusDate="2026-02-01" />);
+
+ // Verify we start on February
+ expect(screen.getByText('February 2026')).toBeInTheDocument();
+
+ const prevButton = screen.getByRole('button', {name: 'Previous month'});
+ await user.click(prevButton);
+
+ expect(screen.getByText('January 2026')).toBeInTheDocument();
+ });
+
+ it('navigates to next month', async () => {
+ const user = userEvent.setup();
+
+ render(<XDSCalendar focusDate="2026-01-01" />);
+
+ // Verify we start on January
+ expect(screen.getByText('January 2026')).toBeInTheDocument();
+
+ const nextButton = screen.getByRole('button', {name: 'Next month'});
+ await user.click(nextButton);
+
+ expect(screen.getByText('February 2026')).toBeInTheDocument();
+ });
+
+ it('calls onFocusDateChange when navigating', async () => {
+ const user = userEvent.setup();
+ const handleFocusChange = vi.fn();
+
+ render(
+ <XDSCalendar
+ focusDate="2026-01-01"
+ onFocusDateChange={handleFocusChange}
+ />,
+ );
+
+ const nextButton = screen.getByRole('button', {name: 'Next month'});
+ await user.click(nextButton);
+
+ expect(handleFocusChange).toHaveBeenCalledWith('2026-02-01');
+ });
+
+ // ─── Date Constraints ────────────────────────────────────────
+
+ 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'));
+ expect(day5).toBeDisabled();
+
+ const day15 = screen.getByRole('gridcell', {name: '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'});
+ expect(day25).toBeDisabled();
+
+ const day15 = screen.getByRole('gridcell', {name: '15'});
+ expect(day15).not.toBeDisabled();
+ });
+
+ it('respects custom dateConstraints', () => {
+ // Only allow weekdays
+ const isWeekday = (date: Date) => {
+ const day = date.getDay();
+ return day !== 0 && day !== 6;
+ };
+
+ render(
+ <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'),
+ );
+ expect(sunday).toBeDisabled();
+ });
+
+ // ─── Multi-Month ─────────────────────────────────────────────
+
+ it('renders two months when numberOfMonths={2}', () => {
+ render(<XDSCalendar numberOfMonths={2} focusDate="2026-01-01" />);
+
+ // The header shows both months
+ expect(screen.getByText(/January 2026.*February 2026/)).toBeInTheDocument();
+ });
+
+ it('navigation advances both months together', async () => {
+ const user = userEvent.setup();
+
+ render(<XDSCalendar numberOfMonths={2} focusDate="2026-01-01" />);
+
+ const nextButton = screen.getByRole('button', {name: 'Next month'});
+ await user.click(nextButton);
+
+ expect(screen.getByText(/February 2026.*March 2026/)).toBeInTheDocument();
+ });
+
+ // ─── Display Options ─────────────────────────────────────────
+
+ it('shows week numbers when hasWeekNumbers is true', () => {
+ render(<XDSCalendar hasWeekNumbers focusDate="2026-01-01" />);
+
+ // Look for week number cells - they should be in the grid but not buttons
+ // Week numbers for January 2026 include week 1, 2, 3, 4, 5
+ const weekNumberCells = screen.getAllByText(/^[1-5]$/);
+ // Should have more than just day numbers (week numbers add extra cells)
+ expect(weekNumberCells.length).toBeGreaterThan(5);
+ });
+
+ it('respects weekStartsOn option', () => {
+ render(<XDSCalendar weekStartsOn={1} />);
+
+ // First day name should be Monday
+ const dayNames = screen.getAllByText(/^(Mo|Tu|We|Th|Fr|Sa|Su)$/);
+ expect(dayNames[0]).toHaveTextContent('Mo');
+ });
+
+ // ─── Range Mode ──────────────────────────────────────────────
+
+ it('supports range selection mode', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+
+ render(
+ <XDSCalendar
+ mode="range"
+ onChange={handleChange}
+ focusDate="2026-01-01"
+ />,
+ );
+
+ // Click start date
+ const day10 = screen.getByRole('gridcell', {name: '10'});
+ await user.click(day10);
+
+ // Click end date
+ const day15 = screen.getByRole('gridcell', {name: '15'});
+ await user.click(day15);
+
+ expect(handleChange).toHaveBeenCalledWith({
+ start: '2026-01-10',
+ end: '2026-01-15',
+ });
+ });
+
+ it('handles reverse range selection (end before start)', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+
+ render(
+ <XDSCalendar
+ mode="range"
+ onChange={handleChange}
+ focusDate="2026-01-01"
+ />,
+ );
+
+ // Click later date first
+ const day20 = screen.getByRole('gridcell', {name: '20'});
+ await user.click(day20);
+
+ // Click earlier date
+ const day10 = screen.getByRole('gridcell', {name: '10'});
+ await user.click(day10);
+
+ // Should swap to ensure start <= end
+ expect(handleChange).toHaveBeenCalledWith({
+ start: '2026-01-10',
+ end: '2026-01-20',
+ });
+ });
+
+ it('highlights range when value is provided', () => {
+ render(
+ <XDSCalendar
+ mode="range"
+ value={{start: '2026-01-10', end: '2026-01-15'}}
+ focusDate="2026-01-01"
+ />,
+ );
+
+ const day10 = screen.getByRole('gridcell', {name: '10'});
+ const day12 = screen.getByRole('gridcell', {name: '12'});
+ const day15 = screen.getByRole('gridcell', {name: '15'});
+
+ expect(day10).toHaveAttribute('aria-selected', 'true');
+ expect(day12).toHaveAttribute('aria-selected', 'true');
+ expect(day15).toHaveAttribute('aria-selected', 'true');
+ });
+
+ // ─── Accessibility ───────────────────────────────────────────
+
+ it('has accessible grid structure', () => {
+ render(<XDSCalendar focusDate="2026-01-01" />);
+
+ expect(screen.getByRole('grid')).toBeInTheDocument();
+ expect(screen.getAllByRole('row').length).toBeGreaterThan(0);
+ expect(screen.getAllByRole('gridcell').length).toBeGreaterThan(0);
+ });
+
+ it('has navigation buttons with accessible labels', () => {
+ render(<XDSCalendar />);
+
+ expect(
+ screen.getByRole('button', {name: 'Previous month'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Next month'}),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
new file mode 100644
index 0000000000..509715d702
--- /dev/null
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -0,0 +1,894 @@
+/**
+ * @file XDSCalendar.tsx
+ * @input Uses React useState, useMemo, useCallback, forwardRef
+ * @output Exports XDSCalendar component and related types
+ * @position Core implementation; consumed by index.ts, tested by XDSCalendar.test.tsx
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Calendar/README.md (props table, features, implementation notes)
+ * - /packages/core/src/Calendar/XDSCalendar.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/Calendar/index.ts (exports if types change)
+ * - /apps/storybook/stories/Calendar.stories.tsx (storybook stories)
+ */
+
+import {
+ forwardRef,
+ useState,
+ useMemo,
+ useCallback,
+ 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';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+/**
+ * ISO 8601 date string in YYYY-MM-DD format.
+ * Example: "2026-01-28"
+ */
+export type ISODateString =
+ `${number}${number}${number}${number}-${number}${number}-${number}${number}`;
+
+/** Day of week: 0 = Sunday through 6 = Saturday */
+export type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
+
+/** Date range with start and end dates */
+export interface DateRange {
+ start: ISODateString;
+ end: ISODateString;
+}
+
+// ─── Base Props (shared across all modes) ─────────────────────
+
+interface XDSCalendarBaseProps extends Omit<
+ HTMLAttributes<HTMLDivElement>,
+ 'onChange' | 'defaultValue'
+> {
+ /** Number of months to display (default: 1) */
+ numberOfMonths?: 1 | 2;
+
+ /** 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>;
+
+ /**
+ * 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;
+
+ /**
+ * 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;
+
+// =============================================================================
+// 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
+// =============================================================================
+
+export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
+ (props, ref) => {
+ const {
+ mode = 'single',
+ value,
+ defaultValue,
+ onChange,
+ numberOfMonths = 1,
+ min,
+ max,
+ dateConstraints,
+ focusDate: focusDateProp,
+ onFocusDateChange,
+ hasOutsideDays = true,
+ hasWeekNumbers = false,
+ hasVariableRowCount = false,
+ weekStartsOn = 0,
+ ...rest
+ } = props;
+
+ // Today's date (memoized)
+ const today = useMemo(() => new Date(), []);
+
+ // Internal state for uncontrolled mode
+ const [internalValue, setInternalValue] = useState<
+ ISODateString | DateRange | undefined
+ >(defaultValue);
+
+ // Range selection in progress (first click made, waiting for second)
+ const [rangeSelectionStart, setRangeSelectionStart] =
+ useState<ISODateString | null>(null);
+
+ // Hovered date for range preview
+ const [hoveredDate, setHoveredDate] = useState<ISODateString | null>(null);
+
+ // Determine effective value
+ const effectiveValue = value !== undefined ? value : internalValue;
+
+ // Focus date state (which month is visible)
+ const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
+ if (focusDateProp) return parseISO(focusDateProp);
+ if (effectiveValue) {
+ if (typeof effectiveValue === 'string') {
+ return parseISO(effectiveValue);
+ } else {
+ return parseISO(effectiveValue.start);
+ }
+ }
+ return new Date();
+ });
+
+ // Use controlled focusDate if callback is provided, otherwise use internal state
+ 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]);
+
+ // Navigation handlers
+ const navigateMonth = useCallback(
+ (delta: number) => {
+ const newDate = new Date(baseMonth);
+ newDate.setMonth(baseMonth.getMonth() + delta);
+ const newISO = dateToISO(newDate);
+
+ if (onFocusDateChange) {
+ onFocusDateChange(newISO);
+ } else {
+ setInternalFocusDate(newDate);
+ }
+ },
+ [baseMonth, onFocusDateChange],
+ );
+
+ // Day click handler
+ const handleDayClick = useCallback(
+ (date: Date) => {
+ const iso = dateToISO(date);
+
+ if (mode === 'single') {
+ setInternalValue(iso);
+ (onChange as XDSCalendarSingleProps['onChange'])?.(iso, date);
+ } else {
+ // Range mode
+ if (rangeSelectionStart === null) {
+ // First click - start the range
+ setRangeSelectionStart(iso);
+ } else {
+ // Second click - complete the range
+ const startDate = parseISO(rangeSelectionStart);
+ let start: ISODateString;
+ let end: ISODateString;
+
+ // Ensure start <= end
+ if (date < startDate) {
+ start = iso;
+ end = rangeSelectionStart;
+ } else {
+ start = rangeSelectionStart;
+ end = iso;
+ }
+
+ const range: DateRange = {start, end};
+ setInternalValue(range);
+ setRangeSelectionStart(null);
+ (onChange as XDSCalendarRangeProps['onChange'])?.(range);
+ }
+ }
+ },
+ [mode, onChange, rangeSelectionStart],
+ );
+
+ return (
+ <div ref={ref} {...stylex.props(styles.calendar)} {...rest}>
+ {/* Header with navigation */}
+ <div {...stylex.props(styles.header)}>
+ <XDSButton
+ label="Previous month"
+ variant="ghost"
+ icon={<ChevronLeftIcon {...stylex.props(styles.navIcon)} />}
+ onClick={() => navigateMonth(-1)}
+ />
+
+ <span {...stylex.props(styles.monthYearLabel)}>{monthYearLabel}</span>
+
+ <XDSButton
+ label="Next month"
+ variant="ghost"
+ icon={<ChevronRightIcon {...stylex.props(styles.navIcon)} />}
+ onClick={() => navigateMonth(1)}
+ />
+ </div>
+
+ {/* Month grids */}
+ <div {...stylex.props(styles.monthsContainer)}>
+ {visibleMonths.map((month, index) => (
+ <MonthGrid
+ key={`${month.getFullYear()}-${month.getMonth()}`}
+ month={month}
+ value={effectiveValue}
+ mode={mode}
+ rangeSelectionStart={rangeSelectionStart}
+ hoveredDate={hoveredDate}
+ min={min}
+ max={max}
+ dateConstraints={dateConstraints}
+ hasOutsideDays={hasOutsideDays}
+ hasWeekNumbers={hasWeekNumbers}
+ hasVariableRowCount={hasVariableRowCount}
+ weekStartsOn={weekStartsOn}
+ onDayClick={handleDayClick}
+ onDayHover={date => setHoveredDate(date ? dateToISO(date) : null)}
+ today={today}
+ />
+ ))}
+ </div>
+ </div>
+ );
+ },
+);
+
+XDSCalendar.displayName = 'XDSCalendar';
diff --git a/packages/core/src/Calendar/index.ts b/packages/core/src/Calendar/index.ts
new file mode 100644
index 0000000000..d244025e16
--- /dev/null
+++ b/packages/core/src/Calendar/index.ts
@@ -0,0 +1,16 @@
+/**
+ * @file index.ts
+ * @input Imports XDSCalendar component and types from XDSCalendar.tsx
+ * @output Exports XDSCalendar, XDSCalendarProps, ISODateString, DayOfWeek, DateRange
+ * @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
+ */
+
+export {XDSCalendar} from './XDSCalendar';
+export type {
+ XDSCalendarProps,
+ ISODateString,
+ DayOfWeek,
+ DateRange,
+} from './XDSCalendar';
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
index a7894b6b1a..6e5814bcf7 100644
--- a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
@@ -84,14 +84,14 @@ const styles = stylex.create({
},
checkmark: {
display: 'none',
- fill: 'white',
+ fill: colorVars['--color-icon-on-media'],
},
checkmarkVisible: {
display: 'block',
},
indeterminateMark: {
display: 'none',
- backgroundColor: 'white',
+ backgroundColor: colorVars['--color-icon-on-media'],
borderRadius: 1,
},
indeterminateMarkVisible: {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index cae46e559b..26b467bdb4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -10,6 +10,7 @@
// Components
export * from './Avatar';
export * from './Button';
+export * from './Calendar';
export * from './CheckboxInput';
export * from './Field';
export * from './Icon';
diff --git a/packages/core/src/theme/defaultTheme.stylex.ts b/packages/core/src/theme/defaultTheme.stylex.ts
index cefb6b17dc..46868f28c1 100644
--- a/packages/core/src/theme/defaultTheme.stylex.ts
+++ b/packages/core/src/theme/defaultTheme.stylex.ts
@@ -70,12 +70,14 @@ const colorRaw = {
'--color-text-disabled': 'light-dark(#A4B0BC, #6F747C)',
'--color-text-link': 'light-dark(#0064E0, #3E9EFB)',
'--color-text-placeholder': 'light-dark(#4E606F, #AAAFB5)',
+ '--color-text-on-media': 'light-dark(#FFFFFF, #FFFFFF)',
// Icon
'--color-icon-primary': 'light-dark(#0A1317, #DFE2E5)',
'--color-icon-secondary': 'light-dark(#4E606F, #AAAFB5)',
'--color-icon-tertiary': 'light-dark(#748695, #8C939B)',
'--color-icon-disabled': 'light-dark(#A4B0BC, #6F747C)',
+ '--color-icon-on-media': 'light-dark(#FFFFFF, #FFFFFF)',
// Surface variants
'--color-card': 'light-dark(#FFFFFF, #1F1F22)',
diff --git a/packages/core/src/theme/neutralTheme.stylex.ts b/packages/core/src/theme/neutralTheme.stylex.ts
index 8330a52a4a..e68bb1e18b 100644
--- a/packages/core/src/theme/neutralTheme.stylex.ts
+++ b/packages/core/src/theme/neutralTheme.stylex.ts
@@ -74,12 +74,14 @@ const colorRaw = {
'--color-text-disabled': 'light-dark(oklch(0.708 0 0), oklch(0.439 0 0))',
'--color-text-link': 'light-dark(oklch(0.205 0 0), oklch(0.922 0 0))',
'--color-text-placeholder': 'light-dark(oklch(0.556 0 0), oklch(0.556 0 0))',
+ '--color-text-on-media': 'light-dark(oklch(1 0 0), oklch(1 0 0))',
// Icon
'--color-icon-primary': 'light-dark(oklch(0.145 0 0), oklch(0.985 0 0))',
'--color-icon-secondary': 'light-dark(oklch(0.556 0 0), oklch(0.708 0 0))',
'--color-icon-tertiary': 'light-dark(oklch(0.708 0 0), oklch(0.556 0 0))',
'--color-icon-disabled': 'light-dark(oklch(0.708 0 0), oklch(0.439 0 0))',
+ '--color-icon-on-media': 'light-dark(oklch(1 0 0), oklch(1 0 0))',
// Surface variants
'--color-card': 'light-dark(oklch(1 0 0), oklch(0.205 0 0))',
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index 1f0a9dda06..ece09da7a6 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -31,12 +31,14 @@ export const colorRaw = {
'--color-text-disabled': '#A4B0BC',
'--color-text-link': '#0064E0',
'--color-text-placeholder': '#4E606F',
+ '--color-text-on-media': '#FFFFFF',
// Icon
'--color-icon-primary': '#0A1317',
'--color-icon-secondary': '#4E606F',
'--color-icon-tertiary': '#748695',
'--color-icon-disabled': '#A4B0BC',
+ '--color-icon-on-media': '#FFFFFF',
// Surface variants
'--color-card': '#FFFFFF',