Skip to content

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

TypeScript

fix(DateRangeInput): preserve semantic range state (#7297)

Cindy Zhang0d8dadb0d815
diff --git a/.changeset/daterangeinput-audit-semantics.md b/.changeset/daterangeinput-audit-semantics.md
new file mode 100644
index 0000000000..f9cf3ac797
--- /dev/null
+++ b/.changeset/daterangeinput-audit-semantics.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Calendar now accepts null as an explicit controlled empty value. DateRangeInput announces required state through a valid button description, keeps pending values in its accessible name, and clears Calendar selection without reviving the previous range.
+
+@cixzhang @AKnassa @korkt-kim
diff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.json
index 0eb5b01fe6..9bc8abe296 100644
--- a/.github/a11y-baseline.json
+++ b/.github/a11y-baseline.json
@@ -283,11 +283,6 @@
"impact": "serious",
"helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"
},
- {
- "key": "DateRangeInput::Required::aria-allowed-attr",
- "impact": "critical",
- "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/aria-allowed-attr?application=playwright"
- },
{
"key": "FileInput::All Variations::color-contrast",
"impact": "serious",
diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjs
index 796ff44955..a5004da6b3 100644
--- a/packages/core/src/Calendar/Calendar.doc.mjs
+++ b/packages/core/src/Calendar/Calendar.doc.mjs
@@ -34,8 +34,8 @@ export const docs = {
},
{
name: 'value',
- type: 'ISODateString | DateRange',
- description: 'Controlled selected value.',
+ type: 'ISODateString | DateRange | null',
+ description: 'Controlled selected value. Use null for no selection; omit value or pass undefined for uncontrolled mode.',
},
{
name: 'defaultValue',
@@ -148,7 +148,7 @@ export const docsZh = {
},
props: [
{name: 'mode', type: "'single' | 'range'", description: '选择模式。', default: "'single'"},
- {name: 'value', type: 'ISODateString | DateRange', description: '受控选中值。'},
+ {name: 'value', type: 'ISODateString | DateRange | null', description: '受控选中值。null 表示没有选中值;省略或传入 undefined 为非受控模式。'},
{name: 'defaultValue', type: 'ISODateString | DateRange', description: '非受控默认值。'},
{name: 'onChange', type: 'Function', description: '选择回调函数。'},
{name: 'numberOfMonths', type: '1 | 2', description: '显示的月份数量。', default: '1'},
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index ddb40e035e..80b7cfe798 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -19,8 +19,7 @@ import {
} from '../__tests__/forcedColors';
import * as stylex from '@stylexjs/stylex';
import {Calendar} from './Calendar';
-import type {CalendarHandle} from './Calendar';
-import type {ISODateString} from './Calendar';
+import type {CalendarHandle, ISODateString, DateRange} from './Calendar';
import {calendarStyles} from './styles';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
@@ -220,6 +219,64 @@ describe('Calendar', () => {
expect(handleChange).toHaveBeenCalledWith('2026-01-15', expect.any(Date));
});
+ it('keeps null single selection empty until the parent accepts a date', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const calendar = (value: ISODateString | null) => (
+ <Calendar
+ value={value}
+ onChange={onChange}
+ defaultValue="2026-01-10"
+ focusDate="2026-01-01"
+ />
+ );
+ const {rerender} = render(calendar(null));
+ expect(screen.queryAllByRole('gridcell', {selected: true})).toHaveLength(0);
+
+ const day15 = getDayButton(15);
+ await user.click(day15);
+ expect(onChange).toHaveBeenCalledWith('2026-01-15', expect.any(Date));
+ expect(screen.queryAllByRole('gridcell', {selected: true})).toHaveLength(0);
+
+ rerender(calendar('2026-01-15'));
+ expect(screen.getByRole('gridcell', {selected: true})).toContainElement(
+ day15,
+ );
+
+ rerender(calendar(null));
+ expect(screen.queryAllByRole('gridcell', {selected: true})).toHaveLength(0);
+ });
+
+ it('keeps null range selection controlled while allowing two-click selection', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const calendar = (value: DateRange | null) => (
+ <Calendar
+ mode="range"
+ value={value}
+ onChange={onChange}
+ defaultValue={{start: '2026-01-10', end: '2026-01-12'}}
+ focusDate="2026-01-01"
+ />
+ );
+ const {rerender} = render(calendar(null));
+ expect(screen.queryAllByRole('gridcell', {selected: true})).toHaveLength(0);
+
+ await user.click(getDayButton(15));
+ await user.click(getDayButton(17));
+ expect(onChange).toHaveBeenCalledWith({
+ start: '2026-01-15',
+ end: '2026-01-17',
+ });
+ expect(screen.queryAllByRole('gridcell', {selected: true})).toHaveLength(0);
+
+ rerender(calendar({start: '2026-01-15', end: '2026-01-17'}));
+ expect(screen.getAllByRole('gridcell', {selected: true})).toHaveLength(3);
+
+ rerender(calendar(null));
+ expect(screen.queryAllByRole('gridcell', {selected: true})).toHaveLength(0);
+ });
+
// ─── Navigation ──────────────────────────────────────────────
it('navigates to previous month', async () => {
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index a3f433f1aa..e3cafe444c 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -188,8 +188,8 @@ interface CalendarSingleProps extends CalendarBaseProps {
/** Selection mode */
mode?: 'single';
- /** Selected date in ISO format (YYYY-MM-DD) */
- value?: ISODateString;
+ /** Selected date in ISO format (YYYY-MM-DD), or null for controlled empty state */
+ value?: ISODateString | null;
/** Default value for uncontrolled mode */
defaultValue?: ISODateString;
@@ -202,8 +202,8 @@ interface CalendarRangeProps extends CalendarBaseProps {
/** Selection mode */
mode: 'range';
- /** Selected date range */
- value?: DateRange;
+ /** Selected date range, or null for controlled empty state */
+ value?: DateRange | null;
/** Default value for uncontrolled mode */
defaultValue?: DateRange;
@@ -282,7 +282,8 @@ export function Calendar({ref, ...props}: CalendarProps) {
const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);
// Determine effective value
- const effectiveValue = value !== undefined ? value : internalValue;
+ const effectiveValue =
+ (value !== undefined ? value : internalValue) ?? undefined;
// Focus date state (which month is visible). Falls back to today, clamped
// into the min/max window so a window that doesn't contain today doesn't
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
index 0d2817c235..f6e9d4e7cf 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
@@ -9,6 +9,7 @@
* SYNC: When DateRangeInput.tsx changes, update tests to match new behavior
*/
+import {useState} from 'react';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -121,7 +122,7 @@ describe('DateRangeInput', () => {
expect(screen.getByText('Range')).toBeInTheDocument();
});
- it('sets aria-required when isRequired is true', () => {
+ it('announces required state from a valid button description', () => {
render(
<DateRangeInput
label="Range"
@@ -131,13 +132,17 @@ describe('DateRangeInput', () => {
/>,
);
const trigger = getButton(/Range/);
- expect(trigger).toHaveAttribute('aria-required', 'true');
+ expect(trigger).not.toHaveAttribute('aria-required');
+ const describedBy = trigger.getAttribute('aria-describedby');
+ expect(describedBy).not.toBeNull();
+ expect(document.getElementById(describedBy!)).toHaveTextContent('Required');
});
- it('does not set aria-required when isRequired is false', () => {
+ it('does not add a required description when isRequired is false', () => {
render(<DateRangeInput label="Range" value={null} onChange={() => {}} />);
const trigger = getButton(/Range/);
expect(trigger).not.toHaveAttribute('aria-required');
+ expect(trigger).not.toHaveAttribute('aria-describedby');
});
it('disables trigger when isDisabled is true', () => {
@@ -171,6 +176,31 @@ describe('DateRangeInput', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'false');
});
+ it('keeps the optimistic range in the trigger name while saving', async () => {
+ const optimisticRange = {
+ start: '2026-03-01',
+ end: '2026-03-07',
+ } as const;
+ render(
+ <DateRangeInput
+ label="Range"
+ value={null}
+ onChange={() => {}}
+ changeAction={async () => new Promise(() => {})}
+ presets={[{label: 'Last 7 days', getRange: () => optimisticRange}]}
+ />,
+ );
+ const trigger = getButton(/^Range:/);
+
+ fireEvent.click(getButton('Open calendar'));
+ fireEvent.click(getButton('Last 7 days'));
+
+ await waitFor(() => {
+ expect(trigger).toHaveTextContent(/Mar.*1.*Mar.*7/);
+ });
+ expect(trigger).toHaveAccessibleName(/Range:.*Mar.*1.*Mar.*7/);
+ });
+
it('renders status icon for error status', () => {
render(
<DateRangeInput
@@ -258,6 +288,38 @@ describe('DateRangeInput', () => {
});
describe('hasClear', () => {
+ it('shows no selected calendar days after clearing', async () => {
+ const user = userEvent.setup();
+ function ControlledDateRangeInput() {
+ const [controlledValue, setControlledValue] =
+ useState<DateRange | null>({
+ start: '2026-01-01',
+ end: '2026-01-03',
+ });
+ return (
+ <DateRangeInput
+ label="Range"
+ value={controlledValue}
+ onChange={setControlledValue}
+ min="2026-01-01"
+ max="2026-01-31"
+ numberOfMonths={1}
+ />
+ );
+ }
+ render(<ControlledDateRangeInput />);
+
+ await user.click(getButton('Open calendar'));
+ await user.click(getButton(/January 15, 2026/));
+ await user.click(getButton(/January 16, 2026/));
+ await user.click(getButton('Clear Range'));
+ await user.click(getButton('Open calendar'));
+
+ expect(
+ screen.queryAllByRole('gridcell', {selected: true, hidden: true}),
+ ).toHaveLength(0);
+ });
+
it('shows clear button when hasClear is true and value exists', () => {
const range: DateRange = {
start: '2026-03-15',
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsx
index fb429c840c..b6ae06ddd8 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx
@@ -4,7 +4,7 @@
/**
* @file DateRangeInput.tsx
- * @input Uses React, Field, Calendar (range mode), usePopover
+ * @input Uses React, Field, Calendar (range mode), VisuallyHidden, usePopover
* @output Exports DateRangeInput component, DateRangeInputProps
* @position Core implementation; consumed by index.ts, tested by DateRangeInput.test.tsx
*
@@ -47,6 +47,7 @@ import {
} from '../Field';
import {Icon} from '../Icon';
import {Spinner} from '../Spinner';
+import {VisuallyHidden} from '../VisuallyHidden';
import {
Calendar,
type ISODateString,
@@ -503,6 +504,7 @@ export function DateRangeInput({
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
+ const requiredID = useId();
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
@@ -537,6 +539,9 @@ export function DateRangeInput({
// The tooltip variant renders no message box; describe the input by the
// tooltip's content instead so the status is still announced.
statusTooltipDescribedBy,
+ // A button cannot carry aria-required. Mirror the input-family pattern
+ // by describing it with localized, visually hidden required text.
+ isEffectivelyRequired ? requiredID : null,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
]
.filter(Boolean)
@@ -599,7 +604,7 @@ export function DateRangeInput({
[fireChange],
);
- const triggerAriaLabel = value
+ const triggerAriaLabel = optimisticValue
? `${label}: ${displayValue}`
: `${label}: ${placeholder}`;
@@ -690,7 +695,6 @@ export function DateRangeInput({
aria-disabled={showsDisabledMessage ? 'true' : undefined}
aria-label={triggerAriaLabel}
aria-describedby={ariaDescribedBy}
- aria-required={isEffectivelyRequired ? 'true' : undefined}
aria-invalid={status?.type === 'error' ? 'true' : undefined}
aria-busy={isBusy || undefined}
aria-expanded={popover.isOpen}
@@ -713,6 +717,11 @@ export function DateRangeInput({
{isBusy && <Spinner size="sm" />}
{statusIcon}
</div>
+ {isEffectivelyRequired && (
+ <VisuallyHidden id={requiredID}>
+ {t('@astryx.field.required')}
+ </VisuallyHidden>
+ )}
{popover.render(
<div {...stylex.props(styles.popoverLayout)}>
{presets && presets.length > 0 && (
@@ -762,7 +771,7 @@ export function DateRangeInput({
)}
<Calendar
mode="range"
- value={value ?? undefined}
+ value={optimisticValue}
onChange={handleRangeSelect}
min={min}
max={max}