An open source design system that's fully customizable and agent ready
TypeScript
fix(DateRangeInput): presets stack above the calendar when they don't fit (#9588)
Cindy Zhang546aaa0bca7d
diff --git a/.changeset/daterangeinput-preset-reflow.md b/.changeset/daterangeinput-preset-reflow.mdnew file mode 100644index 0000000000..1577dac7b7--- /dev/null+++ b/.changeset/daterangeinput-preset-reflow.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] DateRangeInput: with `presets`, the popover overflowed a phone-width screen. The calendar was cut off on the right, so the Saturday column and the end of a selected range were hidden, and on screens under about 364 px Next month was out of reach too. Now, when the presets and a one-month calendar do not fit side by side, the presets stack above the calendar, and the calendar and its navigation stay inside the popover. On a short screen the popover's content scrolls. Where the presets fit beside a one-month calendar, the layout does not change.++@cixzhangdiff --git a/docs/specs/components/DateRangeInput/DateRangeInput.spec.md b/docs/specs/components/DateRangeInput/DateRangeInput.spec.mdindex 142dc7613b..7fa8d3b706 100644--- a/docs/specs/components/DateRangeInput/DateRangeInput.spec.md+++ b/docs/specs/components/DateRangeInput/DateRangeInput.spec.md@@ -14,6 +14,7 @@ verified_by:[packages/core/src/DateRangeInput/DateRangeInput.test.tsx,packages/core/src/theme/themingTargets.test.ts,+ packages/core/src/DateRangeInput/__tests__/DateRangeInputReflow.interaction.browser.spec.ts,scripts/check-knowledge.mjs,]modules: []@@ -21,7 +22,7 @@ families: [family:input-fields, family:overlay-dismissal]design_specs: []architecture: [architecture:component-theming-surface]contributing: []-system_specs: []+system_specs: [spec:AST-020]---# DateRangeInput component contract@@ -30,7 +31,7 @@ system_specs: []DateRangeInput presents one controlled date range through a labeled field surface.Its trigger opens a Calendar-backed Popover and may include a list of quick-select-presets beside that calendar.+presets beside that calendar, or above it when the two do not fit side by side.## Compatibility and migration@@ -72,12 +73,13 @@ preset-list anatomy and its additive theming surface.## Behavioral and layout contract-| ID | Candidate invariant | Basis | Review state |-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | -------------------------- |-| FR1 | DateRangeInput MUST present the controlled `value` and emit range changes without maintaining a competing selected range. | Current source, docs, and focused tests | Verified current behavior |-| FR2 | When presets are present, each preset remains an independent button in one labeled group; the applied preset reflects current state and a preset whose endpoint violates `min`, `max`, or `dateConstraints`, or whose range violates `minRangeSpan` or `maxRangeSpan`, reflects disabled state. | Current source, accessibility comments, and focused tests | Verified current behavior |-| FR3 | The preset group and each preset button expose stable theme targets; selected and disabled are states of the preset-button target rather than separate targets. | `architecture:component-theming-surface`; #5417 demand | Approved additive contract |-| FR4 | Adding theme targets MUST NOT change the Popover, Calendar, button, focus, or selection semantics those elements already own. | Composition boundary and compatibility goal | Approved additive contract |+| ID | Candidate invariant | Basis | Review state |+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------- |+| FR1 | DateRangeInput MUST present the controlled `value` and emit range changes without maintaining a competing selected range. | Current source, docs, and focused tests | Verified current behavior |+| FR2 | When presets are present, each preset remains an independent button in one labeled group; the applied preset reflects current state and a preset whose endpoint violates `min`, `max`, or `dateConstraints`, or whose range violates `minRangeSpan` or `maxRangeSpan`, reflects disabled state. | Current source, accessibility comments, and focused tests | Verified current behavior |+| FR3 | The preset group and each preset button expose stable theme targets; selected and disabled are states of the preset-button target rather than separate targets. | `architecture:component-theming-surface`; #5417 demand | Approved additive contract |+| FR4 | Adding theme targets MUST NOT change the Popover, Calendar, button, focus, or selection semantics those elements already own. | Composition boundary and compatibility goal | Approved additive contract |+| FR5 | When the preset group and a one-month calendar do not fit side by side in the layer, the preset group stacks above the calendar, and every month grid and the month navigation stay inside the layer (`spec:AST-020` FR1, WCAG 2.2 SC 1.4.10). Visual order matches DOM order. When they fit, the presets stay beside the calendar. When the content is taller than the layer's viewport cap, it scrolls inside the layer. | `spec:AST-020` FR1; 390 px, 390 × 664 px and 440 px reflow checks | Verified current behavior |### Allowed variation@@ -172,11 +174,12 @@ No new performance or resource constraint is introduced.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------ |-| FR1, FR2, AR1–AR3 | `DateRangeInput.test.tsx`; disabled-preset focusability (AR3) pending conformance | no match, applied preset, endpoint-invalid preset, span-invalid preset | Semantics or state attributes disappear | `audit:DateRangeInput/presets` |-| FR3, FR4 | `DateRangeInput.test.tsx`, `themingTargets.test.ts`, generated probe theme | group target, selected button, disabled button | Target class/state is missing, undocumented, or placed on the wrong element | `audit:DateRangeInput/theming` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | all documented anatomy | Target ownership or anatomy names drift | `audit:DateRangeInput/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------ |+| FR1, FR2, AR1–AR3 | `DateRangeInput.test.tsx`; disabled-preset focusability (AR3) pending conformance | no match, applied preset, endpoint-invalid preset, span-invalid preset | Semantics or state attributes disappear | `audit:DateRangeInput/presets` |+| FR3, FR4 | `DateRangeInput.test.tsx`, `themingTargets.test.ts`, generated probe theme | group target, selected button, disabled button | Target class/state is missing, undocumented, or placed on the wrong element | `audit:DateRangeInput/theming` |+| FR5 | `DateRangeInputReflow.interaction.browser.spec.ts` | 390 px page with presets and two months; desktop page | The calendar or its navigation crosses the layer edge, or the presets leave the calendar's side at desktop width | `audit:DateRangeInput/reflow` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | all documented anatomy | Target ownership or anatomy names drift | `audit:DateRangeInput/theming` |## Decision logdiff --git a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjsindex e31644e455..313d0ab3fe 100644--- a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs+++ b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs@@ -115,7 +115,7 @@ export const docs = {name: 'presets',type: 'Array<DateRangePreset>',description:- 'Preset ranges shown as quick-select options beside the calendar. A preset is disabled when either endpoint violates min, max, or dateConstraints, or when its span violates minRangeSpan or maxRangeSpan.',+ 'Preset ranges shown as quick-select options beside the calendar, or above it when the two do not fit side by side. A preset is disabled when either endpoint violates min, max, or dateConstraints, or when its span violates minRangeSpan or maxRangeSpan.',},{name: 'hasClear',@@ -277,7 +277,8 @@ export const docs = {{name: 'Preset sidebar',required: false,- description: 'A list of preset range options beside the calendar.',+ description:+ 'A list of preset range options beside the calendar, or above it when the two do not fit side by side.',},{name: 'Preset button',diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsxindex 80021c5f8e..725ded6637 100644--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx@@ -88,6 +88,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/DateRangeInput/DateRangeInput.generated';+import {layerViewportInset} from '../Layer/layerViewportInset.stylex';registerEnglishFallback(english);@@ -160,8 +161,28 @@ const styles = stylex.create({iconButtonDisabled: {cursor: 'default',},+ // The popover content scrolls inside the layer's block cap, so a stacked+ // calendar stays reachable on a short screen.+ popoverScroll: {+ overflowY: 'auto',+ overscrollBehavior: 'contain',+ maxBlockSize: stylex.firstThatWorks(+ `calc(${layerViewportInset.maxBlockSize})`,+ `calc(${layerViewportInset.maxBlockSizeFallback})`,+ ),+ },+ // When the presets and a one-month calendar do not fit side by side, the+ // row wraps and the presets stack above the calendar, in DOM order. The+ // preset group draws a divider on its inline end and its block end. A+ // negative margin moves each divider 1 border width past the group's margin+ // box, and this row clips at its edges. Thus only the divider between the+ // two parts shows: the inline-end one side by side, the block-end one when+ // stacked. The row clips, not the scroller, so the overhang is never+ // scrollable overflow.popoverLayout: {display: 'flex',+ flexWrap: 'wrap',+ overflow: 'clip',},presetSidebar: {display: 'flex',@@ -171,8 +192,26 @@ const styles = stylex.create({borderInlineEndWidth: borderVars['--border-width'],borderInlineEndStyle: 'solid',borderInlineEndColor: colorVars['--color-border-emphasized'],+ borderBlockEndWidth: borderVars['--border-width'],+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: colorVars['--color-border-emphasized'],+ marginInlineEnd: `calc(-1 * ${borderVars['--border-width']})`,+ marginBlockEnd: `calc(-1 * ${borderVars['--border-width']})`,+ // Alone on its line, the group fills the line, so its inline-end divider+ // reaches the clipped edge.+ flexGrow: 1,minWidth: 140,},+ calendarPane: {+ // Gives back the border width the preset group's margin takes, so the+ // calendar keeps its side-by-side position.+ marginInlineStart: borderVars['--border-width'],+ // The row wraps on the calendar's one-month width, and the calendar then+ // takes the free space, so its months sit in a row where they fit. The+ // large factor keeps the preset group at its own width beside it.+ flexBasis: 'min-content',+ flexGrow: 1_000_000,+ },presetButton: {display: 'block',width: '100%',@@ -805,79 +844,86 @@ export function DateRangeInput({</VisuallyHidden>)}{popover.render(- <div {...stylex.props(styles.popoverLayout)}>- {presets && presets.length > 0 && (- <div- role="group"- aria-label={t('@astryx.dateRangeInput.presetDateRanges')}- {...mergeProps(- themeProps('date-range-input-presets'),- stylex.props(styles.presetSidebar),- )}>- {presets.map(preset => {- const presetRange = preset.getRange();- const isActive = isRangeEqual(value, presetRange);- const isPresetDisabled =- isDisabled ||- !isRangeWithinSpan(presetRange, maxRangeSpan, minRangeSpan) ||- isDateDisabled(plainDateFromISO(presetRange.start)) ||- isDateDisabled(plainDateFromISO(presetRange.end));- return (- <button- key={preset.label}- type="button"- // These presets are independent action buttons navigated by- // Tab, not a single-tab-stop listbox — so they are a labeled- // group of buttons, and the currently-applied preset is- // marked with aria-current (not aria-selected, a listbox- // concept that contradicted the Tab interaction) (forms-5).- aria-current={isActive ? 'true' : undefined}- // Focusable while disabled (AR3, spec:AST-085 FR1).- aria-disabled={isPresetDisabled || undefined}- aria-describedby={- showsDisabledMessage- ? disabledMessageTooltip.describedBy- : undefined- }- onClick={() => {- if (!isPresetDisabled) {- handleRangeSelect(presetRange);+ <div {...stylex.props(styles.popoverScroll)}>+ <div {...stylex.props(styles.popoverLayout)}>+ {presets && presets.length > 0 && (+ <div+ role="group"+ aria-label={t('@astryx.dateRangeInput.presetDateRanges')}+ {...mergeProps(+ themeProps('date-range-input-presets'),+ stylex.props(styles.presetSidebar),+ )}>+ {presets.map(preset => {+ const presetRange = preset.getRange();+ const isActive = isRangeEqual(value, presetRange);+ const isPresetDisabled =+ isDisabled ||+ !isRangeWithinSpan(+ presetRange,+ maxRangeSpan,+ minRangeSpan,+ ) ||+ isDateDisabled(plainDateFromISO(presetRange.start)) ||+ isDateDisabled(plainDateFromISO(presetRange.end));+ return (+ <button+ key={preset.label}+ type="button"+ // These presets are independent action buttons navigated by+ // Tab, not a single-tab-stop listbox — so they are a labeled+ // group of buttons, and the currently-applied preset is+ // marked with aria-current (not aria-selected, a listbox+ // concept that contradicted the Tab interaction) (forms-5).+ aria-current={isActive ? 'true' : undefined}+ // Focusable while disabled (AR3, spec:AST-085 FR1).+ aria-disabled={isPresetDisabled || undefined}+ aria-describedby={+ showsDisabledMessage+ ? disabledMessageTooltip.describedBy+ : undefined}- }}- {...mergeProps(- themeProps('date-range-input-preset', {- selected: isActive ? 'selected' : null,- disabled: isPresetDisabled ? 'disabled' : null,- }),- stylex.props(- focusOutlineStyles.focusVisible,- styles.presetButton,- isActive && styles.presetButtonActive,- isPresetDisabled && styles.presetButtonDisabled,- ),- )}>- {preset.label}- </button>- );- })}- </div>- )}- {/* The layer renders its children open or closed, so mount the+ onClick={() => {+ if (!isPresetDisabled) {+ handleRangeSelect(presetRange);+ }+ }}+ {...mergeProps(+ themeProps('date-range-input-preset', {+ selected: isActive ? 'selected' : null,+ disabled: isPresetDisabled ? 'disabled' : null,+ }),+ stylex.props(+ focusOutlineStyles.focusVisible,+ styles.presetButton,+ isActive && styles.presetButtonActive,+ isPresetDisabled && styles.presetButtonDisabled,+ ),+ )}>+ {preset.label}+ </button>+ );+ })}+ </div>+ )}+ {/* The layer renders its children open or closed, so mount thecalendar only while it is open. */}- {popover.isOpen && (- <Calendar- mode="range"- value={optimisticValue}- onChange={handleRangeSelect}- min={min}- max={max}- dateConstraints={dateConstraints}- maxRangeSpan={maxRangeSpan}- minRangeSpan={minRangeSpan}- numberOfMonths={numberOfMonths}- weekStartsOn={weekStartsOn}- />- )}+ {popover.isOpen && (+ <Calendar+ mode="range"+ value={optimisticValue}+ onChange={handleRangeSelect}+ min={min}+ max={max}+ dateConstraints={dateConstraints}+ maxRangeSpan={maxRangeSpan}+ minRangeSpan={minRangeSpan}+ numberOfMonths={numberOfMonths}+ weekStartsOn={weekStartsOn}+ xstyle={presets && presets.length > 0 && styles.calendarPane}+ />+ )}+ </div></div>,{placement: 'below', alignment: 'start'},)}diff --git a/packages/core/src/DateRangeInput/__tests__/DateRangeInputReflow.interaction.browser.spec.ts b/packages/core/src/DateRangeInput/__tests__/DateRangeInputReflow.interaction.browser.spec.tsnew file mode 100644index 0000000000..acc47b0548--- /dev/null+++ b/packages/core/src/DateRangeInput/__tests__/DateRangeInputReflow.interaction.browser.spec.ts@@ -0,0 +1,152 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DateRangeInputReflow.interaction.browser.spec.ts+ * @input Storybook story core-daterangeinput--with-presets-and-value+ * @output In a real browser: on a 390 px wide page the preset group stacks+ * above the calendar, and every month grid and the month navigation stay+ * inside the layer; on a short phone screen the layer stays on screen and+ * its content scrolls to the last month; where the presets fit beside a+ * one-month calendar (440 px) and on a desktop page they stay beside it,+ * with nothing in the popover scrolling.+ * @position DateRangeInput reflow evidence (WCAG 1.4.10), run in the Chromium+ * interaction lane; jsdom has no layout.+ */++import {expect, test, type Locator, type Page} from '@playwright/test';+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++type Box = {left: number; top: number; right: number; bottom: number};++async function boxOf(locator: Locator): Promise<Box> {+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('element has no layout box');+ }+ return {+ left: box.x,+ top: box.y,+ right: box.x + box.width,+ bottom: box.y + box.height,+ };+}++function expectInside(inner: Box, outer: Box) {+ expect(inner.left).toBeGreaterThanOrEqual(outer.left - 0.5);+ expect(inner.right).toBeLessThanOrEqual(outer.right + 0.5);+ expect(inner.top).toBeGreaterThanOrEqual(outer.top - 0.5);+ expect(inner.bottom).toBeLessThanOrEqual(outer.bottom + 0.5);+}++/** Whether anything in the popover scrolls (a scrollbar on classic-scrollbar+ * systems). */+async function hasScrollableOverflow(layer: Locator): Promise<boolean> {+ return layer.evaluate(root =>+ [root, ...Array.from(root.querySelectorAll('*'))].some(node => {+ const style = getComputedStyle(node);+ const scrolls = /auto|scroll/.test(style.overflowX + style.overflowY);+ return (+ scrolls &&+ (node.scrollHeight > node.clientHeight + 0.5 ||+ node.scrollWidth > node.clientWidth + 0.5)+ );+ }),+ );+}++async function openPicker(page: Page) {+ await openStory(+ page,+ storybook(),+ 'core-daterangeinput--with-presets-and-value',+ );+ const trigger = page.locator('[aria-haspopup]').first();+ await trigger.waitFor();+ await trigger.click();+ const presets = page.getByRole('group', {name: /preset/i});+ await presets.waitFor();+ const layer = page.getByRole('dialog');+ return {presets, layer, grids: layer.getByRole('grid')};+}++test.describe('on a 390 px wide page', () => {+ test.use({+ isMobile: false,+ hasTouch: false,+ viewport: {width: 390, height: 844},+ });++ test('the presets stack above the calendar, which stays inside the layer', async ({+ page,+ }) => {+ const {presets, layer, grids} = await openPicker(page);+ const layerBox = await boxOf(layer);+ const presetBox = await boxOf(presets);+ const gridCount = await grids.count();+ expect(gridCount).toBeGreaterThan(0);+ for (let index = 0; index < gridCount; index++) {+ const gridBox = await boxOf(grids.nth(index));+ expectInside(gridBox, layerBox);+ expect(presetBox.bottom).toBeLessThanOrEqual(gridBox.top + 0.5);+ }+ const nextMonth = layer.getByRole('button', {name: /next/i});+ expectInside(await boxOf(nextMonth), layerBox);+ });+});++test.describe('on a short phone screen, 390 by 664 px', () => {+ test.use({+ isMobile: false,+ hasTouch: false,+ viewport: {width: 390, height: 664},+ });++ test('the layer stays on screen and scrolls to the last month', async ({+ page,+ }) => {+ const {layer, grids} = await openPicker(page);+ const layerBox = await boxOf(layer);+ expect(layerBox.top).toBeGreaterThanOrEqual(0);+ expect(layerBox.bottom).toBeLessThanOrEqual(664);+ const lastGrid = grids.last();+ await lastGrid.evaluate(grid => grid.scrollIntoView({block: 'end'}));+ expectInside(await boxOf(lastGrid), layerBox);+ });+});++test.describe('where the presets fit beside one month, 440 px', () => {+ test.use({+ isMobile: false,+ hasTouch: false,+ viewport: {width: 440, height: 800},+ });++ test('the presets stay beside the calendar', async ({page}) => {+ const {presets, layer, grids} = await openPicker(page);+ const presetBox = await boxOf(presets);+ const gridBox = await boxOf(grids.first());+ expect(presetBox.right).toBeLessThanOrEqual(gridBox.left + 0.5);+ expectInside(gridBox, await boxOf(layer));+ expect(await hasScrollableOverflow(layer)).toBe(false);+ });+});++test.describe('on a desktop page', () => {+ test.use({+ isMobile: false,+ hasTouch: false,+ viewport: {width: 1024, height: 768},+ });++ test('the presets stay beside the calendar', async ({page}) => {+ const {presets, layer, grids} = await openPicker(page);+ const presetBox = await boxOf(presets);+ const gridBox = await boxOf(grids.first());+ expect(presetBox.right).toBeLessThanOrEqual(gridBox.left + 0.5);+ expect(presetBox.top).toBeLessThan(gridBox.top);+ // The divider's clipped overhang is never scrollable overflow.+ expect(await hasScrollableOverflow(layer)).toBe(false);+ });+});