An open source design system that's fully customizable and agent ready
TypeScript
fix(Calendar): hardening — a11y, keyboard nav, date constraints (#837)
Joey8cd8f2607193
diff --git a/apps/storybook/stories/Calendar.stories.tsx b/apps/storybook/stories/Calendar.stories.tsxindex 9a687d333f..84f13bec2c 100644--- a/apps/storybook/stories/Calendar.stories.tsx+++ b/apps/storybook/stories/Calendar.stories.tsx@@ -103,6 +103,22 @@ export const TwoMonthsRangeSelection: Story = {},};+export const MinMaxBoundary: Story = {+ render: () => {+ const [value, setValue] = useState<ISODateString | undefined>(undefined);+ return (+ <XDSCalendar+ mode="single"+ min={'2026-01-10' as ISODateString}+ max={'2026-03-20' as ISODateString}+ value={value}+ onChange={val => setValue(val)}+ focusDate={'2026-01-01' as ISODateString}+ />+ );+ },+};+export const WithDateConstraints: Story = {render: () => {const [value, setValue] = useState<ISODateString | undefined>(undefined);diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjsindex 0962d92b2a..4ddcc73816 100644--- a/packages/core/src/Calendar/Calendar.doc.mjs+++ b/packages/core/src/Calendar/Calendar.doc.mjs@@ -11,6 +11,12 @@ export const docs = {'Locale Options: weekStartsOn for configurable first day of week','Week Numbers: Optional ISO week number column','Controlled/Uncontrolled: Supports both patterns via value/defaultValue',+ 'Keyboard: Escape cancels in-progress range selection',+ 'A11y: day name headers use role="columnheader", day buttons expose data-date attribute',+ 'A11y: outside days are aria-disabled and not clickable even when visible',+ 'A11y: selected date receives roving tabindex priority over today',+ 'Nav buttons auto-disable when min/max boundary is within the current month',+ 'Motion: day cell transitions respect prefers-reduced-motion',],examples: [{@@ -126,6 +132,12 @@ export const docs = {'ISODateString type: `${number}${number}${number}${number}-${number}${number}-${number}${number}`','DayOfWeek type: 0 | 1 | 2 | 3 | 4 | 5 | 6','DateRange interface: { start: ISODateString; end: ISODateString }',+ 'Day buttons render a data-date="YYYY-MM-DD" attribute for testing and scripting',+ 'Roving tabindex priority: selected date > today > first enabled day',+ 'In range mode, pressing Escape resets the pending start date without firing onChange',+ 'Previous/next month buttons become disabled when the current view contains the min or max date',+ 'Outside days (adjacent month) are rendered with aria-disabled="true" and ignore clicks',+ 'Day cell transitions are suppressed under @media (prefers-reduced-motion: reduce)',],};@@ -141,6 +153,12 @@ export const docsZh = {'区域选项:weekStartsOn 可配置每周的起始日','周数:可选的 ISO 周数列','受控/非受控:通过 value/defaultValue 支持两种模式',+ '键盘:Escape 取消正在进行的范围选择',+ '无障碍:星期名称使用 role="columnheader",日期按钮暴露 data-date 属性',+ '无障碍:外部日期设为 aria-disabled 且不可点击',+ '无障碍:选中日期获得漫游 tabindex 优先级',+ '导航按钮在 min/max 边界所在月份时自动禁用',+ '动效:日期单元格过渡遵循 prefers-reduced-motion',],examples: [{@@ -256,6 +274,12 @@ export const docsZh = {'ISODateString 类型:`${number}${number}${number}${number}-${number}${number}-${number}${number}`','DayOfWeek 类型:0 | 1 | 2 | 3 | 4 | 5 | 6','DateRange 接口:{ start: ISODateString; end: ISODateString }',+ '日期按钮渲染 data-date="YYYY-MM-DD" 属性,用于测试和脚本',+ '漫游 tabindex 优先级:选中日期 > 今天 > 第一个启用日期',+ '范围模式下按 Escape 重置待选起始日期,不触发 onChange',+ '上/下月按钮在当前视图包含 min 或 max 日期时禁用',+ '外部日期(相邻月份)以 aria-disabled="true" 渲染且忽略点击',+ '日期单元格过渡在 @media (prefers-reduced-motion: reduce) 下被抑制',],};@@ -269,11 +293,20 @@ export const docsDense = {'weekStartsOn for configurable first day of week','optional ISO week number column','controlled/uncontrolled via value/defaultValue',+ 'Escape cancels in-progress range selection',+ 'a11y: columnheader on day names, data-date on buttons, outside days aria-disabled',+ 'selected date gets roving tabindex priority; nav buttons disable at min/max boundary',+ 'prefers-reduced-motion suppresses day cell transitions',],notes: ['ISODateString type: YYYY-MM-DD template literal','DayOfWeek type: 0|1|2|3|4|5|6','DateRange: { start: ISODateString; end: ISODateString }',+ 'data-date attr on day buttons for testing/scripting',+ 'tabindex priority: selected > today > first enabled',+ 'Escape in range mode resets start, no onChange fired',+ 'prev/next buttons disabled when view contains min/max',+ 'outside days: aria-disabled + click ignored',],propDescriptions: {mode: 'selection mode',diff --git a/packages/core/src/Calendar/XDSCalendar.test.tsx b/packages/core/src/Calendar/XDSCalendar.test.tsxindex 9622ebf95b..a23933b69d 100644--- a/packages/core/src/Calendar/XDSCalendar.test.tsx+++ b/packages/core/src/Calendar/XDSCalendar.test.tsx@@ -300,4 +300,129 @@ describe('XDSCalendar', () => {screen.getByRole('button', {name: 'Next month'}),).toBeInTheDocument();});++ // ─── Bug Regression Tests ───────────────────────────────────++ it('day buttons have data-date attribute with ISO string', () => {+ render(<XDSCalendar focusDate="2026-01-01" />);++ const day15 = getDayButton(15);+ expect(day15).toHaveAttribute('data-date', '2026-01-15');+ });++ it('ArrowDown moves focus +7 days, not to same day in next month', async () => {+ const user = userEvent.setup();+ const handleFocusChange = vi.fn();++ render(+ <XDSCalendar+ focusDate="2026-01-01"+ onFocusDateChange={handleFocusChange}+ />,+ );++ // Focus Jan 28+ const day28 = getDayButton(28);+ await user.click(day28);+ day28.querySelector('button')?.focus();++ // Press ArrowDown — should move to Feb 4 (+7 days), not Feb 28+ await user.keyboard('{ArrowDown}');++ // After navigation, Feb 4 should be focused+ const focusedElement = document.activeElement;+ expect(focusedElement).toHaveAttribute('data-date', '2026-02-04');+ });++ it('prev button is disabled when focusDate month contains min', () => {+ render(<XDSCalendar focusDate="2026-01-01" min="2026-01-15" />);++ const prevButton = screen.getByRole('button', {name: 'Previous month'});+ expect(prevButton).toBeDisabled();+ });++ it('next button is disabled when focusDate month contains max', () => {+ render(<XDSCalendar focusDate="2026-01-01" max="2026-01-15" />);++ const nextButton = screen.getByRole('button', {name: 'Next month'});+ expect(nextButton).toBeDisabled();+ });++ it('outside days are not clickable when hasOutsideDays is true', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();++ render(+ <XDSCalendar+ focusDate="2026-01-01"+ hasOutsideDays+ onChange={handleChange}+ />,+ );++ // January 2026 starts on Thursday, so Dec 28-31 are outside days+ // Find an outside day button (December day visible in January grid)+ const outsideDays = screen.getAllByRole('gridcell').filter(cell => {+ const button = cell.querySelector('button');+ return button?.getAttribute('aria-disabled') === 'true';+ });++ // Click the first outside day+ if (outsideDays[0]) {+ const button = outsideDays[0].querySelector('button');+ if (button) await user.click(button);+ }++ expect(handleChange).not.toHaveBeenCalled();+ });++ it('Escape cancels range selection in progress', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();++ render(+ <XDSCalendar+ mode="range"+ onChange={handleChange}+ focusDate="2026-01-01"+ />,+ );++ // Click start date to begin range selection+ const day10 = getDayButton(10);+ await user.click(day10);++ // Press Escape to cancel+ await user.keyboard('{Escape}');++ // Click another date — should start a NEW range, not complete the old one+ const day20 = getDayButton(20);+ await user.click(day20);++ // onChange should NOT have been called (no range completed)+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('day name headers have role="columnheader"', () => {+ render(<XDSCalendar focusDate="2026-01-01" />);++ const columnHeaders = screen.getAllByRole('columnheader');+ expect(columnHeaders.length).toBe(7);++ // Verify they contain day name abbreviations+ const dayNames = columnHeaders.map(h => h.textContent);+ expect(dayNames).toEqual(['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']);+ });++ it('button inside gridcell does not duplicate role="gridcell"', () => {+ render(<XDSCalendar focusDate="2026-01-01" />);++ const gridcells = screen.getAllByRole('gridcell');+ for (const cell of gridcells) {+ const button = cell.querySelector('button');+ if (button) {+ expect(button).not.toHaveAttribute('role', 'gridcell');+ }+ }+ });});diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsxindex 6cc4d2f02f..1b529da5df 100644--- a/packages/core/src/Calendar/XDSCalendar.tsx+++ b/packages/core/src/Calendar/XDSCalendar.tsx@@ -13,7 +13,6 @@* - /apps/storybook/stories/Calendar.stories.tsx (storybook stories)*/-import {useState,useMemo,@@ -285,6 +284,31 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {return visibleMonths.map(m => formatter.format(m)).join(' – ');}, [visibleMonths, numberOfMonths]);+ // Determine if prev/next navigation is possible based on min/max+ const canNavigatePrevious = useMemo(() => {+ if (!min) return true;+ const minDate = parseISO(min);+ // Can't go back if min is in the current focus month+ return (+ minDate.getFullYear() < baseMonth.getFullYear() ||+ (minDate.getFullYear() === baseMonth.getFullYear() &&+ minDate.getMonth() < baseMonth.getMonth())+ );+ }, [min, baseMonth]);++ const canNavigateNext = useMemo(() => {+ if (!max) return true;+ const maxDate = parseISO(max);+ // Check against the last visible month, not just baseMonth+ const lastVisibleMonth = new Date(baseMonth);+ lastVisibleMonth.setMonth(baseMonth.getMonth() + numberOfMonths - 1);+ return (+ maxDate.getFullYear() > lastVisibleMonth.getFullYear() ||+ (maxDate.getFullYear() === lastVisibleMonth.getFullYear() &&+ maxDate.getMonth() > lastVisibleMonth.getMonth())+ );+ }, [max, baseMonth, numberOfMonths]);+// Navigation handlersconst navigateMonth = useCallback((delta: number, focusedDate?: ISODateString, offset?: number) => {@@ -309,6 +333,22 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {[baseMonth, onFocusDateChange],);+ // Escape key handler to cancel range selection+ const handleCalendarKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (+ mode === 'range' &&+ rangeSelectionStart !== null &&+ e.key === 'Escape'+ ) {+ setRangeSelectionStart(null);+ e.preventDefault();+ e.stopPropagation();+ }+ },+ [mode, rangeSelectionStart],+ );+// Day click handlerconst handleDayClick = useCallback((date: Date) => {@@ -355,6 +395,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {className,style,)}+ onKeyDown={handleCalendarKeyDown}{...rest}>{/* Header with navigation */}<div {...stylex.props(calendarStyles.header)}>@@ -363,6 +404,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {variant="ghost"icon={<XDSIcon icon="chevronLeft" size="sm" color="inherit" />}onClick={() => navigateMonth(-1)}+ isDisabled={!canNavigatePrevious}/><span {...stylex.props(calendarStyles.monthYearLabel)}>@@ -374,6 +416,7 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {variant="ghost"icon={<XDSIcon icon="chevronRight" size="sm" color="inherit" />}onClick={() => navigateMonth(1)}+ isDisabled={!canNavigateNext}/></div>@@ -478,12 +521,21 @@ function MonthGrid({dateConstraints,});+ // Parse selected date for roving tabindex priority+ const selectedDateForTabindex = useMemo(() => {+ if (mode === 'single' && value && typeof value === 'string') {+ return parseISO(value as ISODateString);+ }+ return null;+ }, [mode, value]);+const {isTabbable} = useCalendarRovingTabindex({days,today,year,month: monthIndex,isDateDisabled,+ selectedDate: selectedDateForTabindex,});// Helper to get the focused date from the currently focused element@@ -635,7 +687,10 @@ function MonthGrid({/>)}{dayNames.map((name, i) => (- <div key={i} {...stylex.props(monthGridStyles.dayName)}>+ <div+ key={i}+ role="columnheader"+ {...stylex.props(monthGridStyles.dayName)}>{name}</div>))}@@ -736,6 +791,9 @@ function DayCell({return <div {...stylex.props(dayCellStyles.cell)} />;}+ // Outside days should not be clickable even when visible+ const effectivelyDisabled = isDisabled || isOutside;+const isToday = isSameDay(date, today);const isSelected =mode === 'single' && selectedDate && isSameDay(date, selectedDate);@@ -805,20 +863,21 @@ function DayCell({<buttontype="button"role="gridcell"+ data-date={day.iso}aria-label={formatAccessibleDate(date)}aria-selected={isSelected || isInRange || undefined}- aria-disabled={isDisabled || undefined}+ aria-disabled={effectivelyDisabled || undefined}disabled={isDisabled}tabIndex={isTabbableDay ? 0 : -1}- onClick={() => !isDisabled && onDayClick(date)}- onMouseEnter={() => !isDisabled && onDayHover(date)}+ onClick={() => !effectivelyDisabled && onDayClick(date)}+ onMouseEnter={() => !effectivelyDisabled && onDayHover(date)}onMouseLeave={() => onDayHover(null)}{...mergeProps(xdsClassName('calendar-day', {selected:isSelected || isRangeStart || isRangeEnd ? 'selected' : null,today: isToday ? 'today' : null,- disabled: isDisabled ? 'disabled' : null,+ disabled: effectivelyDisabled ? 'disabled' : null,'in-range': isInRange ? 'in-range' : null,}),stylex.props(@@ -837,8 +896,8 @@ function DayCell({dayCellStyles.daySelected,(isSelected || isRangeStart || isRangeEnd) &&dayCellTheme.daySelected,- isDisabled && dayCellStyles.dayDisabled,- isDisabled && dayCellTheme.dayDisabled,+ effectivelyDisabled && dayCellStyles.dayDisabled,+ effectivelyDisabled && dayCellTheme.dayDisabled,),)}>{dayNumber}diff --git a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.tsindex 444b648b27..b7f0615c65 100644--- a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts+++ b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts@@ -10,7 +10,6 @@* - /packages/core/src/Calendar/hooks/index.ts*/-import {useMemo} from 'react';import type {ISODateString} from '../XDSCalendar';import type {CalendarDay} from './useCalendarDays';@@ -29,6 +28,8 @@ export interface UseCalendarRovingTabindexOptions {month: number;/** Function to check if a date is disabled */isDateDisabled: (date: Date) => boolean;+ /** Currently selected date (if any) */+ selectedDate?: Date | null;}/**@@ -80,20 +81,29 @@ function dateToISO(date: Date): ISODateString {export function useCalendarRovingTabindex(options: UseCalendarRovingTabindexOptions,): UseCalendarRovingTabindexReturn {- const {days, today, year, month, isDateDisabled} = options;+ const {days, today, year, month, isDateDisabled, selectedDate} = options;// Determine which day should be tabbableconst tabbableDate = useMemo(() => {- // Check if today is in this month+ // Priority 1: Selected date if visible in this month and enabled+ if (selectedDate) {+ const isSelectedInMonth =+ selectedDate.getFullYear() === year &&+ selectedDate.getMonth() === month;+ if (isSelectedInMonth && !isDateDisabled(selectedDate)) {+ return dateToISO(selectedDate);+ }+ }++ // Priority 2: Today if visible in this month and enabledconst isTodayInMonth =today.getFullYear() === year && today.getMonth() === month;- // If today is in this month and enabled, use itif (isTodayInMonth && !isDateDisabled(today)) {return dateToISO(today);}- // Otherwise, find first enabled day in this month+ // Priority 3: First enabled day in this monthfor (const day of days) {if (!day.isOutside && !isDateDisabled(day.date)) {return day.iso;@@ -101,7 +111,7 @@ export function useCalendarRovingTabindex(}return null;- }, [days, today, year, month, isDateDisabled]);+ }, [days, today, year, month, isDateDisabled, selectedDate]);// Check if a specific date is tabbableconst isTabbable = useMemo(() => {diff --git a/packages/core/src/Calendar/styles.ts b/packages/core/src/Calendar/styles.tsindex 8f92095d3a..234e751996 100644--- a/packages/core/src/Calendar/styles.ts+++ b/packages/core/src/Calendar/styles.ts@@ -51,6 +51,17 @@ export const calendarStyles = stylex.create({display: 'flex',gap: spacingVars['--spacing-4'],},+ srOnly: {+ position: 'absolute',+ width: '1px',+ height: '1px',+ padding: 0,+ margin: '-1px',+ overflow: 'hidden',+ clip: 'rect(0, 0, 0, 0)',+ whiteSpace: 'nowrap',+ borderWidth: 0,+ },navIcon: {width: spacingVars['--spacing-4'],height: spacingVars['--spacing-4'],@@ -191,7 +202,10 @@ export const dayCellStyles = stylex.create({padding: 0,position: 'relative',zIndex: 1,- transitionProperty: 'background-color, color',+ transitionProperty: {+ default: 'background-color, color',+ '@media (prefers-reduced-motion: reduce)': 'none',+ },transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],// Expand hit target by 2px on each side to prevent gaps