Skip to content

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

TypeScript

feat(DateRangeInput): add maxRangeSpan/minRangeSpan to constrain range size (#5145)

freddymeta1cd52d97d7a0
diff --git a/.changeset/daterange-max-span.md b/.changeset/daterange-max-span.md
new file mode 100644
index 0000000000..ea0c60ed75
--- /dev/null
+++ b/.changeset/daterange-max-span.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateRangeInput / Calendar: add `maxRangeSpan` and `minRangeSpan` to constrain the size of a selected range. Once a start date is picked, days outside the allowed window are disabled — e.g. `maxRangeSpan={7}` keeps the range within a 7-day window of the start.
+
+@freddymeta
diff --git a/apps/storybook/stories/Calendar.stories.tsx b/apps/storybook/stories/Calendar.stories.tsx
index f1caa6930d..9dddb990f9 100644
--- a/apps/storybook/stories/Calendar.stories.tsx
+++ b/apps/storybook/stories/Calendar.stories.tsx
@@ -72,6 +72,37 @@ export const RangeWithValue: Story = {
},
};
+export const RangeWithMaxSpan: Story = {
+ render: () => {
+ const [value, setValue] = useState<DateRange | undefined>(undefined);
+ return (
+ <Calendar
+ mode="range"
+ value={value}
+ onChange={range => setValue(range)}
+ focusDate="2026-01-01"
+ maxRangeSpan={7}
+ />
+ );
+ },
+};
+
+export const RangeWithSpanBounds: Story = {
+ render: () => {
+ const [value, setValue] = useState<DateRange | undefined>(undefined);
+ return (
+ <Calendar
+ mode="range"
+ value={value}
+ onChange={range => setValue(range)}
+ focusDate="2026-01-01"
+ minRangeSpan={2}
+ maxRangeSpan={14}
+ />
+ );
+ },
+};
+
export const TwoMonths: Story = {
render: () => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
diff --git a/apps/storybook/stories/DateRangeInput.stories.tsx b/apps/storybook/stories/DateRangeInput.stories.tsx
index dab2bc9d08..4ae6cf1a63 100644
--- a/apps/storybook/stories/DateRangeInput.stories.tsx
+++ b/apps/storybook/stories/DateRangeInput.stories.tsx
@@ -149,6 +149,31 @@ export const WithMinMax: Story = {
},
};
+export const MaxRangeSpan: Story = {
+ render: args => {
+ const [value, setValue] = useState<DateRange | null>(null);
+ return <DateRangeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Reporting period',
+ maxRangeSpan: 7,
+ description: 'Pick a start date, then any end within a 7-day window',
+ },
+};
+
+export const RangeSpanBounds: Story = {
+ render: args => {
+ const [value, setValue] = useState<DateRange | null>(null);
+ return <DateRangeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Stay',
+ minRangeSpan: 2,
+ maxRangeSpan: 30,
+ description: 'At least 2 and at most 30 days',
+ },
+};
+
export const Optional: Story = {
render: args => {
const [value, setValue] = useState<DateRange | null>(null);
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index d52e0d14b3..7446617197 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -323,6 +323,10 @@
"defaultMessage": "Selected range: {start} to {end}.",
"description": "Screen-reader announcement after the second pick completes a Calendar range selection. `{start}` and `{end}` are localized full dates in chronological order."
},
+ "@astryx.calendar.rangeClearedAnnounce": {
+ "defaultMessage": "Cleared start date {date}. Select a start date.",
+ "description": "Screen-reader announcement when the user clicks the in-progress range start again, which clears it instead of completing a zero-length range. `{date}` is the localized full date."
+ },
"@astryx.carousel.label": {
"defaultMessage": "Carousel",
"description": "Screen-reader-only fallback name for a horizontally-scrolling row of items. If \"carousel\" is unfamiliar in your locale, prefer the standard term (e.g. \"slider\")."
diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjs
index 022c007d71..577717a794 100644
--- a/packages/core/src/Calendar/Calendar.doc.mjs
+++ b/packages/core/src/Calendar/Calendar.doc.mjs
@@ -68,6 +68,18 @@ export const docs = {
type: 'Array<(date: Date) => boolean>',
description: 'Custom constraint functions.',
},
+ {
+ name: 'maxRangeSpan',
+ type: 'number',
+ description:
+ 'Range mode: max days a range may span, both endpoints counted (7 = a 7-day window). Caps the window from the picked start; before a start is picked every day stays selectable.',
+ },
+ {
+ name: 'minRangeSpan',
+ type: 'number',
+ description:
+ 'Range mode: min days a range must span, both endpoints counted (2 forbids a single-day range). Default 1.',
+ },
{
name: 'focusDate',
type: 'ISODateString',
@@ -142,6 +154,8 @@ export const docsZh = {
{name: 'min', type: 'ISODateString', description: '可选择的最早日期。'},
{name: 'max', type: 'ISODateString', description: '可选择的最晚日期。'},
{name: 'dateConstraints', type: 'Array<(date: Date) => boolean>', description: '自定义约束函数。'},
+ {name: 'maxRangeSpan', type: 'number', description: '范围模式:范围最多可跨越的天数,含首尾两端(7 = 7 天窗口)。选定起始日后限制窗口大小。'},
+ {name: 'minRangeSpan', type: 'number', description: '范围模式:范围最少需跨越的天数,含首尾两端(2 表示禁止单日范围)。默认为 1。'},
{name: 'focusDate', type: 'ISODateString', description: '受控可见月份。'},
{name: 'onFocusDateChange', type: '(focusDate: ISODateString) => void', description: '导航回调函数。'},
{name: 'handleRef', type: 'React.Ref<CalendarHandle>', description: '日历导航的命令式句柄,包括 navigateTo()。'},
@@ -205,6 +219,8 @@ export const docsDense = {
min: 'minimum selectable date',
max: 'maximum selectable date',
dateConstraints: 'custom constraint fns',
+ maxRangeSpan: 'range mode: max days a range may span, both ends counted (7 = 7-day window)',
+ minRangeSpan: 'range mode: min days a range must span, both ends counted (default 1)',
focusDate: 'controlled visible month',
onFocusDateChange: 'navigation callback',
handleRef: 'imperative navigation handle',
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index 9eb83c7d6e..312ad4ac41 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -236,6 +236,102 @@ describe('Calendar', () => {
expect(sunday).toBeDisabled();
});
+ it('caps the end date to maxRangeSpan once a start is picked', async () => {
+ const user = userEvent.setup();
+
+ render(<Calendar mode="range" focusDate="2026-01-01" maxRangeSpan={7} />);
+
+ // Before a start is picked every day is selectable.
+ expect(getDayButton(20)).not.toBeDisabled();
+
+ // Pick Jan 10 as the start. A 7-day window spans Jan 4–16 (start ± 6).
+ await user.click(getDayButton(10));
+
+ expect(getDayButton(16)).not.toBeDisabled(); // 6 days after — the edge
+ expect(getDayButton(17)).toBeDisabled(); // 7 days after — beyond the cap
+ expect(getDayButton(4)).not.toBeDisabled(); // 6 days before — symmetric
+ expect(getDayButton(3)).toBeDisabled(); // 7 days before — beyond the cap
+ });
+
+ it('enforces minRangeSpan once a start is picked', async () => {
+ const user = userEvent.setup();
+
+ render(<Calendar mode="range" focusDate="2026-01-01" minRangeSpan={3} />);
+
+ // Pick Jan 10. A 3-day minimum forbids ends closer than 2 days away.
+ await user.click(getDayButton(10));
+
+ // The picked start itself stays enabled — it is the active selection
+ // anchor, not an unreachable end.
+ expect(getDayButton(10)).not.toBeDisabled();
+ expect(getDayButton(11)).toBeDisabled(); // 1 day apart — too short
+ expect(getDayButton(12)).not.toBeDisabled(); // 3-day span — allowed
+ expect(getDayButton(8)).not.toBeDisabled(); // 3-day span the other way
+ expect(getDayButton(9)).toBeDisabled(); // 2-day span — too short
+ });
+
+ it('clears the in-progress start when the anchor is clicked again', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+
+ render(
+ <Calendar
+ mode="range"
+ focusDate="2026-01-01"
+ onChange={handleChange}
+ minRangeSpan={3}
+ />,
+ );
+
+ // Pick Jan 10 as the start, then click it again.
+ await user.click(getDayButton(10));
+ await user.click(getDayButton(10));
+
+ // No zero-length range is committed…
+ expect(handleChange).not.toHaveBeenCalled();
+
+ // …and the start is cleared: the days that minRangeSpan disabled around
+ // the old anchor are selectable again, so a new start can be placed there.
+ expect(getDayButton(11)).not.toBeDisabled();
+ expect(getDayButton(9)).not.toBeDisabled();
+ });
+
+ it('does not apply range-span constraints in single mode', async () => {
+ const user = userEvent.setup();
+
+ render(<Calendar focusDate="2026-01-01" maxRangeSpan={7} />);
+
+ // A picked single date must not disable far-away days.
+ await user.click(getDayButton(10));
+ expect(getDayButton(25)).not.toBeDisabled();
+ });
+
+ it('keeps a controlled value that is wider than maxRangeSpan (selection-only)', () => {
+ // The span constraint governs which days are pickable, not validation of
+ // an already-set value — so a 15-day value under a 7-day cap stays
+ // rendered and is never silently rewritten.
+ render(
+ <Calendar
+ mode="range"
+ value={{start: '2026-01-05', end: '2026-01-20'}}
+ focusDate="2026-01-01"
+ maxRangeSpan={7}
+ />,
+ );
+
+ // No selection is in progress (both endpoints are set), so no anchor →
+ // every day is pickable and both endpoints render selected.
+ expect(getDayButton(20)).not.toBeDisabled();
+ expect(getDayButton(5).closest('[role="gridcell"]')).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ expect(getDayButton(20).closest('[role="gridcell"]')).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ });
+
// ─── Multi-Month ─────────────────────────────────────────────
it('renders two months when numberOfMonths={2}', () => {
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index e5643ef78b..96b22456ca 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -120,6 +120,25 @@ interface CalendarBaseProps extends Omit<
*/
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+ /**
+ * Range mode only. Maximum number of days a selected range may span,
+ * counting both endpoints — `maxRangeSpan={7}` allows a 7-day window
+ * (start + 6 days). Once a start date is picked, days beyond this distance
+ * from it are disabled in either direction; before a start is picked every
+ * otherwise-valid day stays selectable. Use for rolling windows like "at
+ * most a week from the chosen day". For fixed calendar bounds use min/max.
+ */
+ maxRangeSpan?: number;
+
+ /**
+ * Range mode only. Minimum number of days a selected range must span,
+ * counting both endpoints — `minRangeSpan={2}` forbids a single-day range.
+ * Once a start date is picked, days closer than this to it are disabled —
+ * except the start itself, which stays selectable as the active anchor.
+ * Defaults to 1 (a same-day start and end is allowed).
+ */
+ minRangeSpan?: number;
+
/**
* Controlled focus date (which month is visible).
* If not provided, defaults to selected date or today.
@@ -211,6 +230,8 @@ export function Calendar({ref, ...props}: CalendarProps) {
min,
max,
dateConstraints,
+ maxRangeSpan,
+ minRangeSpan,
focusDate: focusDateProp,
onFocusDateChange,
hasOutsideDays = true,
@@ -425,6 +446,23 @@ export function Calendar({ref, ...props}: CalendarProps) {
} else {
// Second click - complete the range
const startPd = plainDateFromISO(rangeSelectionStart);
+
+ // Clicking the anchor again clears the in-progress start rather than
+ // committing a zero-length range. This is also the escape hatch when
+ // `minRangeSpan` disables the days around the anchor: without it the
+ // anchor would be the only clickable day left and the start could
+ // never be moved. `minRangeSpan` leaves the anchor itself enabled
+ // precisely so this toggle stays reachable.
+ if (plainDateIsEqual(date, startPd)) {
+ setRangeSelectionStart(null);
+ announce(
+ t('@astryx.calendar.rangeClearedAnnounce', {
+ date: plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY),
+ }),
+ );
+ return;
+ }
+
let start: ISODateString;
let end: ISODateString;
@@ -528,6 +566,8 @@ export function Calendar({ref, ...props}: CalendarProps) {
min={min}
max={max}
dateConstraints={dateConstraints}
+ maxRangeSpan={maxRangeSpan}
+ minRangeSpan={minRangeSpan}
hasOutsideDays={hasOutsideDays}
hasWeekNumbers={hasWeekNumbers}
hasVariableRowCount={hasVariableRowCount}
@@ -567,6 +607,8 @@ interface MonthGridProps {
min?: ISODateString;
max?: ISODateString;
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+ maxRangeSpan?: number;
+ minRangeSpan?: number;
hasOutsideDays: boolean;
hasWeekNumbers: boolean;
hasVariableRowCount: boolean;
@@ -589,6 +631,8 @@ function MonthGrid({
min,
max,
dateConstraints,
+ maxRangeSpan,
+ minRangeSpan,
hasOutsideDays,
hasWeekNumbers,
hasVariableRowCount,
@@ -611,10 +655,21 @@ function MonthGrid({
hasVariableRowCount,
});
+ const rangeAnchor = useMemo(
+ () =>
+ mode === 'range' && rangeSelectionStart
+ ? plainDateFromISO(rangeSelectionStart)
+ : null,
+ [mode, rangeSelectionStart],
+ );
+
const {isDateDisabled} = useCalendarConstraints({
min,
max,
dateConstraints,
+ maxRangeSpan,
+ minRangeSpan,
+ rangeAnchor,
});
// Parse selected date for roving tabindex priority
diff --git a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
index 595094364d..67b37963ea 100644
--- a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
@@ -20,6 +20,7 @@ import {
plainDateToDate,
plainDateIsBefore,
plainDateIsAfter,
+ plainDateDiffDays,
} from '../../utils/plainDate';
/**
@@ -35,6 +36,25 @@ export interface UseCalendarConstraintsOptions {
* Date is disabled if ANY function returns false.
*/
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+ /**
+ * Maximum number of days a range may span, counting both endpoints
+ * (a value of 7 allows a 7-day window). In range mode, once a start is
+ * picked, dates further than this from it are disabled. No effect until a
+ * range anchor exists.
+ */
+ maxRangeSpan?: number;
+ /**
+ * Minimum number of days a range must span, counting both endpoints
+ * (a value of 2 forbids a single-day range). In range mode, once a start
+ * is picked, dates closer than this to it are disabled.
+ */
+ minRangeSpan?: number;
+ /**
+ * The in-progress range start (first click, awaiting the second). Span
+ * constraints are measured from this date. Null when no selection is
+ * underway.
+ */
+ rangeAnchor?: PlainDate | null;
}
/**
@@ -53,13 +73,15 @@ export interface UseCalendarConstraintsReturn {
* Hook for managing calendar date validation constraints.
*
* Provides a function to check if a date is disabled based on
- * min/max bounds and custom constraint functions.
+ * min/max bounds, range-span bounds, and custom constraint functions.
*
* @example
* ```
* const {isDateDisabled} = useCalendarConstraints({
* min: '2026-01-01',
* max: '2026-12-31',
+ * maxRangeSpan: 7, // once a start is picked, cap the window at 7 days
+ * rangeAnchor, // the in-progress start (null before the first click)
* dateConstraints: [
* (date) => date.getDay() !== 0, // No Sundays (receives native Date)
* ],
@@ -74,7 +96,8 @@ export interface UseCalendarConstraintsReturn {
export function useCalendarConstraints(
options: UseCalendarConstraintsOptions,
): UseCalendarConstraintsReturn {
- const {min, max, dateConstraints} = options;
+ const {min, max, dateConstraints, maxRangeSpan, minRangeSpan, rangeAnchor} =
+ options;
// Parse min/max dates
const minDate = useMemo(() => (min ? plainDateFromISO(min) : null), [min]);
@@ -93,6 +116,27 @@ export function useCalendarConstraints(
return true;
}
+ // Range-span bounds, measured from the in-progress start. Spans count
+ // both endpoints (a span of 7 spans a 7-day window), so the reachable
+ // distance from the anchor is `span - 1` days in either direction. Only
+ // active once a start is picked — before that, every day stays pickable.
+ if (rangeAnchor) {
+ const distance = Math.abs(plainDateDiffDays(rangeAnchor, date));
+ if (maxRangeSpan != null && distance > maxRangeSpan - 1) {
+ return true;
+ }
+ // The anchor itself (distance 0) is never disabled by minRangeSpan —
+ // it is the picked start, and disabling it would render the active
+ // selection start as aria-disabled to keyboard and screen-reader users.
+ if (
+ minRangeSpan != null &&
+ distance > 0 &&
+ distance < minRangeSpan - 1
+ ) {
+ return true;
+ }
+ }
+
// Check custom constraints (convert to Date for public API compatibility)
if (dateConstraints) {
for (const constraint of dateConstraints) {
@@ -104,7 +148,14 @@ export function useCalendarConstraints(
return false;
},
- [minDate, maxDate, dateConstraints],
+ [
+ minDate,
+ maxDate,
+ dateConstraints,
+ maxRangeSpan,
+ minRangeSpan,
+ rangeAnchor,
+ ],
);
return {
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs
index 2dc21fd8f6..2451ae75b0 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs
+++ b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs
@@ -98,6 +98,18 @@ export const docs = {
type: 'Array<(date: Date) => boolean>',
description: 'Custom constraint functions to disable specific dates.',
},
+ {
+ name: 'maxRangeSpan',
+ type: 'number',
+ description:
+ 'Maximum days a selected range may span, counting both endpoints (`7` = a 7-day window, start + 6). Once a start is picked, days beyond this distance are disabled so the range cannot stretch past the cap. Rolling window relative to the start — for fixed calendar bounds use `min`/`max`. Constrains selection only; it never rewrites a `value` already wider than the cap (flag that with `status`).',
+ },
+ {
+ name: 'minRangeSpan',
+ type: 'number',
+ description:
+ 'Minimum days a selected range must span, counting both endpoints (`2` forbids a single-day range). Once a start is picked, days closer than this are disabled. Defaults to 1 (same-day start and end allowed).',
+ },
{
name: 'presets',
type: 'Array<DateRangePreset>',
@@ -313,6 +325,10 @@ export const docsDense = {
min: 'min selectable date: ISODateString template literal type (YYYY-MM-DD); use string literal or cast `as ISODateString`',
max: 'max selectable date: ISODateString template literal type (YYYY-MM-DD); use string literal or cast `as ISODateString`',
dateConstraints: 'custom constraint fns to disable dates',
+ maxRangeSpan:
+ 'max days a range may span, both endpoints counted (7 = a 7-day window); caps the window from the picked start. Selection-only; does not rewrite an over-wide value',
+ minRangeSpan:
+ 'min days a range must span, both endpoints counted (2 forbids a single-day range); default 1',
presets: 'preset ranges as quick-select options',
hasClear: 'clear button when range is set (default true)',
placeholder: 'placeholder when empty',
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
index de4902e98f..e84050aba0 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When DateRangeInput.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeEach} from 'vitest';
+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';
@@ -712,3 +712,83 @@ describe('DateRangeInput disabled theme state', () => {
expect(root).not.toHaveAttribute('data-disabled');
});
});
+
+describe('DateRangeInput range-span forwarding', () => {
+ // Pin "today" so the popover opens on a known month and the day buttons we
+ // query are guaranteed to render.
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-05T12:00:00Z'));
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // The calendar renders in the top layer; jsdom keeps day buttons in the DOM
+ // but role queries skip them, so reach them by their machine-readable
+ // data-date (ISO) attribute — the same approach Calendar's own tests use.
+ const dayButton = (iso: string): HTMLButtonElement | null =>
+ document.querySelector<HTMLButtonElement>(`button[data-date="${iso}"]`);
+
+ it('forwards maxRangeSpan so the window caps after a start is picked', () => {
+ render(
+ <DateRangeInput
+ label="Reporting period"
+ value={null}
+ onChange={() => {}}
+ maxRangeSpan={7}
+ />,
+ );
+
+ fireEvent.click(getButton('Open calendar'));
+
+ // Before a start is picked, a far-off day is selectable.
+ expect(dayButton('2026-01-20')).not.toBeDisabled();
+
+ fireEvent.click(dayButton('2026-01-10') as HTMLButtonElement);
+
+ // A 7-day window spans start ± 6 days: Jan 16 is the edge, Jan 17 is out.
+ expect(dayButton('2026-01-16')).not.toBeDisabled();
+ expect(dayButton('2026-01-17')).toBeDisabled();
+ });
+
+ it('disables a preset whose range violates the span cap', () => {
+ const presets = [
+ {
+ label: 'Last 3 days',
+ getRange: (): DateRange => ({
+ start: '2026-01-08',
+ end: '2026-01-10',
+ }),
+ },
+ {
+ label: 'Last 30 days',
+ getRange: (): DateRange => ({
+ start: '2025-12-12',
+ end: '2026-01-10',
+ }),
+ },
+ ];
+ const handleChange = vi.fn();
+ render(
+ <DateRangeInput
+ label="Reporting period"
+ value={null}
+ onChange={handleChange}
+ maxRangeSpan={7}
+ presets={presets}
+ />,
+ );
+
+ fireEvent.click(getButton('Open calendar'));
+
+ // The 3-day preset fits the 7-day cap; the 30-day preset can't be committed.
+ const withinCap = getButton('Last 3 days');
+ const overCap = getButton('Last 30 days');
+ expect(withinCap).not.toBeDisabled();
+ expect(overCap).toBeDisabled();
+
+ fireEvent.click(overCap);
+ expect(handleChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsx
index 2498835b78..e50bc3c1a4 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx
@@ -22,6 +22,7 @@ import {
plainDateFromISO,
plainDateToday,
plainDateFormat,
+ plainDateDiffDays,
DATE_FORMAT_SHORT,
DATE_FORMAT_SHORT_WITH_YEAR,
} from '../utils/plainDate';
@@ -162,6 +163,11 @@ const styles = stylex.create({
backgroundColor: colorVars['--color-accent-muted'],
color: colorVars['--color-accent'],
},
+ presetButtonDisabled: {
+ color: colorVars['--color-text-disabled'],
+ cursor: 'not-allowed',
+ backgroundColor: 'transparent',
+ },
});
const sizeStyles = stylex.create({
@@ -202,6 +208,34 @@ function isRangeEqual(a: DateRange | null, b: DateRange | null): boolean {
return a.start === b.start && a.end === b.end;
}
+// A preset that would land outside the span bounds is disabled rather than
+// allowed to override them: the cap is authoritative, so an out-of-window
+// preset stays visible (discoverable) but non-committable, mirroring how the
+// calendar disables out-of-window days. Spans count both endpoints.
+function isRangeWithinSpan(
+ range: DateRange,
+ maxRangeSpan: number | undefined,
+ minRangeSpan: number | undefined,
+): boolean {
+ if (maxRangeSpan == null && minRangeSpan == null) {
+ return true;
+ }
+ const span =
+ Math.abs(
+ plainDateDiffDays(
+ plainDateFromISO(range.start),
+ plainDateFromISO(range.end),
+ ),
+ ) + 1;
+ if (maxRangeSpan != null && span > maxRangeSpan) {
+ return false;
+ }
+ if (minRangeSpan != null && span < minRangeSpan) {
+ return false;
+ }
+ return true;
+}
+
export interface DateRangeInputProps extends Omit<
BaseProps,
'onChange' | 'defaultValue'
@@ -304,6 +338,30 @@ export interface DateRangeInputProps extends Omit<
*/
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+ /**
+ * Maximum number of days the selected range may span, counting both
+ * endpoints — `maxRangeSpan={7}` allows a 7-day window (start + 6 days).
+ * Once a start date is picked, days beyond this distance from it are
+ * disabled, so the user can't stretch the range past the cap. Use for
+ * rolling windows like "at most a week from the chosen day"; for fixed
+ * calendar bounds use `min`/`max`.
+ *
+ * This constrains selection only — it never rewrites a `value` that is
+ * already wider than the cap. Surface such a value with `status` if you
+ * need to flag it. A `preset` whose range violates the cap is disabled
+ * (shown but not committable) rather than allowed to override it.
+ */
+ maxRangeSpan?: number;
+
+ /**
+ * Minimum number of days the selected range must span, counting both
+ * endpoints — `minRangeSpan={2}` forbids a single-day range. Once a start
+ * date is picked, days closer than this to it are disabled — except the
+ * start itself, which stays selectable as the active anchor. Defaults to 1
+ * (a same-day start and end is allowed).
+ */
+ minRangeSpan?: number;
+
/**
* Preset date ranges shown as quick-select options beside the calendar.
*/
@@ -397,6 +455,8 @@ export function DateRangeInput({
min,
max,
dateConstraints,
+ maxRangeSpan,
+ minRangeSpan,
presets,
hasClear = true,
placeholder: placeholderFromProps,
@@ -644,6 +704,11 @@ export function DateRangeInput({
{presets.map(preset => {
const presetRange = preset.getRange();
const isActive = isRangeEqual(value, presetRange);
+ const isPresetDisabled = !isRangeWithinSpan(
+ presetRange,
+ maxRangeSpan,
+ minRangeSpan,
+ );
return (
<button
key={preset.label}
@@ -654,11 +719,13 @@ export function DateRangeInput({
// marked with aria-current (not aria-selected, a listbox
// concept that contradicted the Tab interaction) (forms-5).
aria-current={isActive ? 'true' : undefined}
+ disabled={isPresetDisabled}
onClick={() => handlePresetClick(preset)}
{...stylex.props(
focusOutlineStyles.focusVisible,
styles.presetButton,
isActive && styles.presetButtonActive,
+ isPresetDisabled && styles.presetButtonDisabled,
)}>
{preset.label}
</button>
@@ -673,6 +740,8 @@ export function DateRangeInput({
min={min}
max={max}
dateConstraints={dateConstraints}
+ maxRangeSpan={maxRangeSpan}
+ minRangeSpan={minRangeSpan}
numberOfMonths={numberOfMonths}
weekStartsOn={weekStartsOn}
/>
diff --git a/packages/core/src/utils/plainDate.test.ts b/packages/core/src/utils/plainDate.test.ts
index 4a3cc298c9..ea3407579b 100644
--- a/packages/core/src/utils/plainDate.test.ts
+++ b/packages/core/src/utils/plainDate.test.ts
@@ -13,6 +13,7 @@ import {
plainDateDayOfWeek,
plainDateAddMonths,
plainDateAddDays,
+ plainDateDiffDays,
plainDateToInstant,
plainDateFromInstant,
plainDateIsBefore,
@@ -312,6 +313,55 @@ describe('plainDateAddDays', () => {
});
});
+describe('plainDateDiffDays', () => {
+ it('counts whole days forward', () => {
+ expect(
+ plainDateDiffDays(
+ {year: 2026, month: 1, day: 10},
+ {year: 2026, month: 1, day: 17},
+ ),
+ ).toBe(7);
+ });
+
+ it('is negative when the second date is earlier', () => {
+ expect(
+ plainDateDiffDays(
+ {year: 2026, month: 1, day: 10},
+ {year: 2026, month: 1, day: 3},
+ ),
+ ).toBe(-7);
+ });
+
+ it('is zero for the same day', () => {
+ expect(
+ plainDateDiffDays(
+ {year: 2026, month: 6, day: 15},
+ {year: 2026, month: 6, day: 15},
+ ),
+ ).toBe(0);
+ });
+
+ it('counts across month and year boundaries', () => {
+ expect(
+ plainDateDiffDays(
+ {year: 2025, month: 12, day: 30},
+ {year: 2026, month: 1, day: 2},
+ ),
+ ).toBe(3);
+ });
+
+ it('ignores DST — every calendar day counts once across a spring-forward', () => {
+ // US DST 2026 begins Mar 8. The gap Mar 7 → Mar 9 is two calendar days
+ // even though one of them is 23 hours long.
+ expect(
+ plainDateDiffDays(
+ {year: 2026, month: 3, day: 7},
+ {year: 2026, month: 3, day: 9},
+ ),
+ ).toBe(2);
+ });
+});
+
describe('plainDateToInstant / plainDateFromInstant', () => {
it('converts a PlainDate to midnight in the requested timezone', () => {
expect(
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
index acdece6372..800878f8c8 100644
--- a/packages/core/src/utils/plainDate.ts
+++ b/packages/core/src/utils/plainDate.ts
@@ -88,6 +88,18 @@ export function plainDateAddDays(pd: PlainDate, n: number): PlainDate {
return plainDateFromDate(d);
}
+/**
+ * Whole calendar days from `a` to `b`, ignoring time of day. Positive when
+ * `b` is after `a`, negative when before. Uses UTC midnight so DST shifts
+ * never add or drop a day.
+ */
+export function plainDateDiffDays(a: PlainDate, b: PlainDate): number {
+ const msPerDay = 24 * 60 * 60 * 1000;
+ const aUTC = Date.UTC(a.year, a.month - 1, a.day);
+ const bUTC = Date.UTC(b.year, b.month - 1, b.day);
+ return Math.round((bUTC - aUTC) / msPerDay);
+}
+
/**
* The wall-clock fields an instant reads as in a given zone.
*