Skip to content

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

TypeScript

fix(Popover): a dialog popover starts focus on an enabled tab stop (#10503)

Cindy Zhanga4eca16907f4
diff --git a/.changeset/popover-entry-skips-disabled.md b/.changeset/popover-entry-skips-disabled.md
new file mode 100644
index 0000000000..290eb8ff23
--- /dev/null
+++ b/.changeset/popover-entry-skips-disabled.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A dialog Popover starts focus on its first enabled tab stop. It skips a disabled control, lets an element that holds `tabindex="-1"` yield to a later tab stop, and starts on its labelled surface when every control is disabled. Before, a DateInput or DateTimeInput calendar whose range starts in the shown month opened on the disabled Previous month button. Now it opens on Next month, or, in a one-month range, on the selected day, else today, else the first enabled day. Disabled controls stay reachable by Tab.
+
+@cixzhang
diff --git a/packages/core/src/DateInput/DateInput.test.tsx b/packages/core/src/DateInput/DateInput.test.tsx
index ae31438d5b..bfbf34e099 100644
--- a/packages/core/src/DateInput/DateInput.test.tsx
+++ b/packages/core/src/DateInput/DateInput.test.tsx
@@ -1719,6 +1719,77 @@ describe('DateInput', () => {
expect(calendarGrid()).toBeNull();
}
});
+
+ it('opens on the day grid, not a disabled month button, when the range is one month', async () => {
+ // The range is one month, so both month buttons are disabled.
+ render(
+ <DateInput
+ label="Date"
+ min="2026-04-01"
+ max="2026-04-30"
+ onChange={() => {}}
+ />,
+ );
+ fireEvent.click(getButton('Open calendar'));
+ const grid = await waitFor(() => {
+ const found = document.querySelector('[role="grid"]');
+ expect(found).not.toBeNull();
+ return found!;
+ });
+ const tabStop = grid.querySelector('button[tabindex="0"]');
+ await waitFor(() => {
+ expect(tabStop).toHaveFocus();
+ });
+ expect(getButton('Previous month')).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ expect(getButton('Next month')).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it("opens on the selected day, the grid's Tab stop", async () => {
+ render(
+ <DateInput
+ label="Date"
+ value="2026-04-06"
+ min="2026-04-01"
+ max="2026-04-30"
+ onChange={() => {}}
+ />,
+ );
+ fireEvent.click(getButton('Open calendar'));
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-04-06',
+ );
+ });
+ expect(document.activeElement).toHaveAttribute('tabindex', '0');
+ });
+
+ it("opens on today when it is in range and nothing is selected, the grid's Tab stop", async () => {
+ vi.useFakeTimers({toFake: ['Date']});
+ vi.setSystemTime(new Date(2026, 3, 20, 12));
+ try {
+ render(
+ <DateInput
+ label="Date"
+ min="2026-04-01"
+ max="2026-04-30"
+ onChange={() => {}}
+ />,
+ );
+ fireEvent.click(getButton('Open calendar'));
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-04-20',
+ );
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
describe('weekStartsOn', () => {
diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx
index 7f3ae3236d..f34532f27a 100644
--- a/packages/core/src/Popover/Popover.test.tsx
+++ b/packages/core/src/Popover/Popover.test.tsx
@@ -1072,6 +1072,85 @@ describe('Popover', () => {
);
});
+ it('starts focus on the first enabled control, skipping a disabled one', async () => {
+ render(
+ <Popover
+ content={
+ <>
+ <button type="button" aria-disabled="true">
+ Earlier
+ </button>
+ <button type="button">Later</button>
+ </>
+ }
+ label="Pages">
+ <button type="button">Open pages</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open pages'}), {
+ detail: 1,
+ });
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'Later', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
+ it('starts focus on a roving tab stop, not an earlier member that holds tabindex -1', async () => {
+ render(
+ <Popover
+ content={
+ <div role="toolbar" aria-label="Formatting">
+ <button type="button" tabIndex={-1}>
+ Bold
+ </button>
+ <button type="button" tabIndex={0}>
+ Italic
+ </button>
+ </div>
+ }
+ label="Format">
+ <button type="button">Open format</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open format'}), {
+ detail: 1,
+ });
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'Italic', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
+ it('starts focus on the labelled surface when every control is disabled, and Tab still reaches them', async () => {
+ const user = userEvent.setup();
+ render(
+ <Popover
+ content={
+ <button type="button" aria-disabled="true">
+ Earlier
+ </button>
+ }
+ label="Pages">
+ <button type="button">Open pages</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open pages'}));
+ await waitFor(() =>
+ expect(
+ screen.getByRole('dialog', {name: 'Pages', hidden: true}),
+ ).toHaveFocus(),
+ );
+
+ await user.tab();
+
+ expect(
+ screen.getByRole('button', {name: 'Earlier', hidden: true}),
+ ).toHaveFocus();
+ });
+
it('keeps the fallback close button reachable by Tab', async () => {
const user = userEvent.setup();
render(
diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx
index af4fde1fe8..576d14996c 100644
--- a/packages/core/src/Popover/Popover.tsx
+++ b/packages/core/src/Popover/Popover.tsx
@@ -61,7 +61,11 @@ import {matchesMediaQuery, watchMediaQuery} from '../utils/coarsePointer';
import type {BaseProps} from '../BaseProps';
import {FALLBACK_CLOSE_SELECTOR, usePopoverInternal} from './usePopover';
import {usePopoverSurfaceMotion} from './PopoverTouch';
-import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
+import {
+ FOCUSABLE_SELECTOR,
+ isDisabledWithin,
+ preferTabStops,
+} from '../hooks/focusableSelector';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {layerViewportInset} from '../Layer/layerViewportInset.stylex';
@@ -645,12 +649,12 @@ export function Popover({
sheetPanelRef.current = panel;
setSheetPanelAttached(panel != null);
}, []);
- // Focus enters the sheet at each opening as it enters the anchored popover
- // (FR2): a caller's `[data-autofocus]`, else the first genuine content
- // control (never the injected fallback close, never BottomSheet's own
- // scroll area), else that scroll area: the sheet's labelled surface, which
- // paints the shared focus ring under the keyboard. It runs a frame after
- // BottomSheet presents the dialog; BottomSheet is unchanged.
+ // Focus enters the sheet at each opening, as in the anchored popover (FR2).
+ // A caller's `[data-autofocus]` wins. Else the first enabled tab stop in the
+ // content takes focus: never the injected fallback close or BottomSheet's
+ // own scroll area. Else the scroll area does: it is the sheet's labelled
+ // surface and shows the keyboard focus ring. This runs a frame after
+ // BottomSheet presents the dialog.
useEffect(() => {
if (!isSheetOpen || !isSheetPanelAttached) {
return;
@@ -675,15 +679,18 @@ export function Popover({
}
const target =
sheetPanel.querySelector<HTMLElement>('[data-autofocus]') ??
- Array.from(
- sheetPanel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
- ).find(
- element =>
- // BottomSheet's scroll area is the panel's own child; content
- // sits inside it.
- element.parentElement !== sheetPanel &&
- element.closest(FALLBACK_CLOSE_SELECTOR) == null,
- );
+ preferTabStops(
+ Array.from(
+ sheetPanel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
+ ).filter(
+ element =>
+ // BottomSheet's scroll area is the panel's own child; content
+ // sits inside it.
+ element.parentElement !== sheetPanel &&
+ element.closest(FALLBACK_CLOSE_SELECTOR) == null &&
+ !isDisabledWithin(element, sheetPanel),
+ ),
+ )[0];
if (target != null) {
target.focus({preventScroll: true});
return;
diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx
index c277707e44..282131ff5c 100644
--- a/packages/core/src/Popover/usePopover.tsx
+++ b/packages/core/src/Popover/usePopover.tsx
@@ -30,7 +30,11 @@ import {
shadowVars,
} from '../theme/tokens.stylex';
import {Button} from '../Button';
-import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
+import {
+ FOCUSABLE_SELECTOR,
+ isDisabledWithin,
+ preferTabStops,
+} from '../hooks/focusableSelector';
import {rtlStyles} from '../utils';
import {useDevWarning} from '../hooks/useDevWarning';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
@@ -66,9 +70,15 @@ function attemptFocus(element: HTMLElement): boolean {
}
function focusFirstContentControl(container: HTMLElement): boolean {
- const focusable = Array.from(
- container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
- ).filter(element => element.closest(FALLBACK_CLOSE_SELECTOR) == null);
+ const focusable = preferTabStops(
+ Array.from(
+ container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
+ ).filter(
+ element =>
+ element.closest(FALLBACK_CLOSE_SELECTOR) == null &&
+ !isDisabledWithin(element, container),
+ ),
+ );
for (const element of focusable) {
if (attemptFocus(element)) {
return true;
diff --git a/packages/core/src/hooks/focusableSelector.ts b/packages/core/src/hooks/focusableSelector.ts
index 99e1481e01..b73dafac02 100644
--- a/packages/core/src/hooks/focusableSelector.ts
+++ b/packages/core/src/hooks/focusableSelector.ts
@@ -3,7 +3,7 @@
/**
* @file focusableSelector.ts
* @input None (a plain CSS selector string constant)
- * @output Exports FOCUSABLE_SELECTOR
+ * @output Exports FOCUSABLE_SELECTOR, isDisabledWithin and preferTabStops
* @position Internal utility; the canonical CSS selector for focusable
* elements, shared by focus-management hooks (e.g. useFocusTrap) so the
* selector isn't duplicated across components/hooks. Not exported from the
@@ -23,3 +23,31 @@
*/
export const FOCUSABLE_SELECTOR =
'button:not([disabled]), a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), [contenteditable]:not([contenteditable="false"]), audio[controls], video[controls], iframe, details > summary:first-child';
+
+/**
+ * Whether `element` is disabled inside `container`: it, or an ancestor up to
+ * `container`, has `aria-disabled="true"`. Popover skips such an element when
+ * it picks initial focus. Tab still reaches it.
+ */
+export function isDisabledWithin(
+ element: Element,
+ container: Element,
+): boolean {
+ const disabled = element.closest('[aria-disabled="true"]');
+ return disabled != null && container.contains(disabled);
+}
+
+/**
+ * `elements` with tab stops first, each group in document order. Inside a
+ * composite widget with a roving tab stop (a grid, a toolbar), the member
+ * that holds `tabindex="0"` comes before the members that hold `-1`.
+ */
+export function preferTabStops<T extends Element>(
+ elements: ReadonlyArray<T>,
+): T[] {
+ const isTabStop = (element: T) => element.getAttribute('tabindex') !== '-1';
+ return [
+ ...elements.filter(isTabStop),
+ ...elements.filter(element => !isTabStop(element)),
+ ];
+}