An open source design system that's fully customizable and agent ready
TypeScript
fix(useFocusTrap): a modal's first and last Tab stops count a radio group once, as the browser does (#10304)
Cindy Zhangbd6df76da172
diff --git a/.changeset/focus-region-radio-group-tab-stop.md b/.changeset/focus-region-radio-group-tab-stop.mdnew file mode 100644index 0000000000..511fdfe3b0--- /dev/null+++ b/.changeset/focus-region-radio-group-tab-stop.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Dialog, CommandPalette, BottomSheet, Lightbox, Drawer, MobileNav, Popover: Tab no longer escapes a modal through a radio group. The browser gives a same-name group of native radios one Tab stop: its checked radio, or, when none is checked, its first moving forward and its last moving backward. The focus region now finds its first and last stops the same way. Before, Tab from a group's checked radio left the modal for the browser's toolbar when the group ended the modal and that radio was not last in it, and Shift+Tab did the same when a group started it. Reported by @duytbp.++@cixzhangdiff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex 3e1f442d37..36df17e1fd 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -5031,3 +5031,64 @@ describe('BottomSheet focus region (Dialog DEC-2)', () => {expect(fireEvent.keyDown(only, {key: 'Tab'})).toBe(true);});});++// A same-name native radio group is one Tab stop: its checked radio, or its+// first when none is checked. Medium is checked and is neither first nor last.+function SizeRadios({name}: {name: string}) {+ return (+ <fieldset>+ <legend>Size</legend>+ <input type="radio" name={name} value="s" aria-label="Small" />+ <input+ type="radio"+ name={name}+ value="m"+ aria-label="Medium"+ defaultChecked+ />+ <input type="radio" name={name} value="l" aria-label="Large" />+ </fieldset>+ );+}++function expectRadioGroupEndsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const first = screen.getByRole('button', {name: 'First', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab'})).toBe(false);+ expect(first).toHaveFocus();+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(medium).toHaveFocus();+}++function expectRadioGroupStartsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const last = screen.getByRole('button', {name: 'Last', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(last).toHaveFocus();+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);+ expect(medium).toHaveFocus();+}++describe('BottomSheet focus region: a radio group is one Tab stop', () => {+ it('wraps Tab from the checked radio of a group that ends the sheet', () => {+ render(+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">+ <button type="button">First</button>+ <SizeRadios name="size" />+ </BottomSheet>,+ );+ expectRadioGroupEndsTheCycle();+ });++ it('wraps Shift+Tab from the checked radio of a group that starts the sheet', () => {+ render(+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">+ <SizeRadios name="size" />+ <button type="button">Last</button>+ </BottomSheet>,+ );+ expectRadioGroupStartsTheCycle();+ });+});diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsxindex 8764f7e8ea..a331844720 100644--- a/packages/core/src/Dialog/Dialog.test.tsx+++ b/packages/core/src/Dialog/Dialog.test.tsx@@ -2170,3 +2170,64 @@ describe('Dialog focus region (DEC-2)', () => {expect(fireEvent.keyDown(only, {key: 'Tab'})).toBe(true);});});++// A same-name native radio group is one Tab stop: its checked radio, or its+// first when none is checked. Medium is checked and is neither first nor last.+function SizeRadios({name}: {name: string}) {+ return (+ <fieldset>+ <legend>Size</legend>+ <input type="radio" name={name} value="s" aria-label="Small" />+ <input+ type="radio"+ name={name}+ value="m"+ aria-label="Medium"+ defaultChecked+ />+ <input type="radio" name={name} value="l" aria-label="Large" />+ </fieldset>+ );+}++function expectRadioGroupEndsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const first = screen.getByRole('button', {name: 'First', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab'})).toBe(false);+ expect(first).toHaveFocus();+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(medium).toHaveFocus();+}++function expectRadioGroupStartsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const last = screen.getByRole('button', {name: 'Last', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(last).toHaveFocus();+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);+ expect(medium).toHaveFocus();+}++describe('Dialog focus region: a radio group is one Tab stop', () => {+ it('wraps Tab from the checked radio of a group that ends the dialog', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}} aria-label="Visit">+ <button type="button">First</button>+ <SizeRadios name="size" />+ </Dialog>,+ );+ expectRadioGroupEndsTheCycle();+ });++ it('wraps Shift+Tab from the checked radio of a group that starts the dialog', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}} aria-label="Visit">+ <SizeRadios name="size" />+ <button type="button">Last</button>+ </Dialog>,+ );+ expectRadioGroupStartsTheCycle();+ });+});diff --git a/packages/core/src/Drawer/Drawer.test.tsx b/packages/core/src/Drawer/Drawer.test.tsxindex d8d535c7a2..1fdd708847 100644--- a/packages/core/src/Drawer/Drawer.test.tsx+++ b/packages/core/src/Drawer/Drawer.test.tsx@@ -1448,3 +1448,64 @@ describe('Drawer without a scrim, opened from the keyboard', () => {}});});++// A same-name native radio group is one Tab stop: its checked radio, or its+// first when none is checked. Medium is checked and is neither first nor last.+function SizeRadios({name}: {name: string}) {+ return (+ <fieldset>+ <legend>Size</legend>+ <input type="radio" name={name} value="s" aria-label="Small" />+ <input+ type="radio"+ name={name}+ value="m"+ aria-label="Medium"+ defaultChecked+ />+ <input type="radio" name={name} value="l" aria-label="Large" />+ </fieldset>+ );+}++function expectRadioGroupEndsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const first = screen.getByRole('button', {name: 'First', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab'})).toBe(false);+ expect(first).toHaveFocus();+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(medium).toHaveFocus();+}++function expectRadioGroupStartsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const last = screen.getByRole('button', {name: 'Last', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(last).toHaveFocus();+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);+ expect(medium).toHaveFocus();+}++describe('Drawer focus region: a radio group is one Tab stop', () => {+ it('wraps Tab from the checked radio of a group that ends the drawer', () => {+ render(+ <Drawer isOpen onOpenChange={() => {}} label="Details">+ <button type="button">First</button>+ <SizeRadios name="size" />+ </Drawer>,+ );+ expectRadioGroupEndsTheCycle();+ });++ it('wraps Shift+Tab from the checked radio of a group that starts the drawer', () => {+ render(+ <Drawer isOpen onOpenChange={() => {}} label="Details">+ <SizeRadios name="size" />+ <button type="button">Last</button>+ </Drawer>,+ );+ expectRadioGroupStartsTheCycle();+ });+});diff --git a/packages/core/src/DropdownMenu/menuRegionStops.ts b/packages/core/src/DropdownMenu/menuRegionStops.tsindex 438c4dcc24..4abb8dcfde 100644--- a/packages/core/src/DropdownMenu/menuRegionStops.ts+++ b/packages/core/src/DropdownMenu/menuRegionStops.ts@@ -16,7 +16,7 @@* wrap at either end.*/import type React from 'react';-import {getFocusableElements} from '../hooks/useFocusTrap';+import {collapseRadioGroups, getFocusableElements} from '../hooks/useFocusTrap';/*** The elements Tab reaches inside a header or footer region, in order. Hidden@@ -57,53 +57,6 @@ function isInsideHiddenWrapper(return false;}-/**- * Collapse each named radio group to the one Tab stop a browser gives it: the- * focused radio, else the checked one, else the first radio moving forward or- * the last moving backward. The stop takes the group's first position.- */-function collapseRadioGroups(- elements: HTMLElement[],- active: Element | null,- isBackward: boolean,-): HTMLElement[] {- const groups = new Map<string, HTMLInputElement[]>();- const groupKey = (el: HTMLElement): string | null =>- el instanceof HTMLInputElement &&- el.getAttribute('type') === 'radio' &&- el.name !== ''- ? `${el.form?.id ?? ''}\u0000${el.name}`- : null;- for (const el of elements) {- const key = groupKey(el);- if (key != null) {- const members = groups.get(key) ?? [];- members.push(el as HTMLInputElement);- groups.set(key, members);- }- }- const placed = new Set<string>();- const result: HTMLElement[] = [];- for (const el of elements) {- const key = groupKey(el);- if (key == null) {- result.push(el);- continue;- }- if (placed.has(key)) {- continue;- }- placed.add(key);- const members = groups.get(key) ?? [];- const stop =- members.find(radio => radio === active) ??- members.find(radio => radio.checked) ??- (isBackward ? members[members.length - 1] : members[0]);- result.push(stop);- }- return result;-}-/*** Move focus to a Tab stop in the dialog. Reports whether focus actually* arrived, so a caller can fall back to the menu instead of stranding focus on@@ -140,7 +93,6 @@ export function moveRegionsTab(const cycle = collapseRadioGroups([...tabbablesIn(header), menu, ...tabbablesIn(footer)],active,- event.shiftKey,);if (cycle.length === 1) {// Nothing else to reach: focus stays in the menu. From a flyout that hasdiff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsxindex d08862973f..1de6e0491f 100644--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx@@ -3448,14 +3448,19 @@ describe('MultiSelector search affordances', () => {await user.type(search, 'ap');expect(search).toHaveFocus();- // Forward-tab lands on the clear (✕) button and the popup stays open, so- // the affordance is keyboard-reachable rather than being skipped when the- // input's Tab dismisses the popup.- await user.tab();+ // The clear (✕) button is the next Tab stop after the input, the focus+ // region leaves the input's Tab to the browser, and the popup stays open+ // when focus moves there, so the affordance is keyboard-reachable rather+ // than skipped by the input's Tab dismissing the popup.const clear = screen.getByRole('button', {name: 'Clear Search options',hidden: true,});+ expect(+ search.compareDocumentPosition(clear) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(fireEvent.keyDown(search, {key: 'Tab'})).toBe(true);+ act(() => clear.focus());expect(clear).toHaveFocus();expect(trigger).toHaveAttribute('aria-expanded', 'true');});diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsxindex f8cdfe8ed1..a746e0bd62 100644--- a/packages/core/src/Selector/Selector.test.tsx+++ b/packages/core/src/Selector/Selector.test.tsx@@ -3855,16 +3855,19 @@ describe('Selector search focus ring', () => {await waitForSearchFocus();const search = screen.getByRole('combobox', {hidden: true});await user.type(search, 'a');+ const clear = screen.getByRole('button', {+ name: 'Clear Search options',+ hidden: true,+ });- await user.tab();- expect(- screen.getByRole('button', {- name: 'Clear Search options',- hidden: true,- }),- ).toHaveFocus();+ // Tab and Shift+Tab between the input and the clear button are the+ // browser's own moves; the focus region leaves both alone.+ expect(fireEvent.keyDown(search, {key: 'Tab'})).toBe(true);+ act(() => clear.focus());+ expect(clear).toHaveFocus();- await user.tab({shift: true});+ expect(fireEvent.keyDown(clear, {key: 'Tab', shiftKey: true})).toBe(true);+ act(() => search.focus());expect(search).toHaveFocus();expect(field()).toHaveAttribute('data-keyboard-focus', 'true');});@@ -4067,14 +4070,19 @@ describe('Selector search affordances', () => {await user.type(search, 'ap');expect(search).toHaveFocus();- // Forward-tab lands on the clear (✕) button and the popup stays open, so- // the affordance is keyboard-reachable rather than being skipped when the- // input's Tab dismisses the popup.- await user.tab();+ // The clear (✕) button is the next Tab stop after the input, the focus+ // region leaves the input's Tab to the browser, and the popup stays open+ // when focus moves there, so the affordance is keyboard-reachable rather+ // than skipped by the input's Tab dismissing the popup.const clear = screen.getByRole('button', {name: 'Clear Search options',hidden: true,});+ expect(+ search.compareDocumentPosition(clear) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(fireEvent.keyDown(search, {key: 'Tab'})).toBe(true);+ act(() => clear.focus());expect(clear).toHaveFocus();expect(trigger).toHaveAttribute('aria-expanded', 'true');});diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsxindex 05003bc074..27f12516a2 100644--- a/packages/core/src/hooks/useFocusTrap.test.tsx+++ b/packages/core/src/hooks/useFocusTrap.test.tsx@@ -845,3 +845,171 @@ describe('useFocusTrap in a second document', () => {expect(prev).toHaveFocus();});});++// A same-name native radio group is one Tab stop: its checked radio, or its+// first when none is checked. Medium is checked and is neither first nor last.+function SizeRadios({name}: {name: string}) {+ return (+ <fieldset>+ <legend>Size</legend>+ <input type="radio" name={name} value="s" aria-label="Small" />+ <input+ type="radio"+ name={name}+ value="m"+ aria-label="Medium"+ defaultChecked+ />+ <input type="radio" name={name} value="l" aria-label="Large" />+ </fieldset>+ );+}++function expectRadioGroupEndsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const first = screen.getByRole('button', {name: 'First', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab'})).toBe(false);+ expect(first).toHaveFocus();+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(medium).toHaveFocus();+}++function expectRadioGroupStartsTheCycle() {+ const medium = screen.getByRole('radio', {name: 'Medium', hidden: true});+ const last = screen.getByRole('button', {name: 'Last', hidden: true});+ medium.focus();+ expect(fireEvent.keyDown(medium, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(last).toHaveFocus();+ expect(fireEvent.keyDown(last, {key: 'Tab'})).toBe(false);+ expect(medium).toHaveFocus();+}++describe('useFocusTrap radio-group Tab stops', () => {+ it("ends the cycle at a trailing group's checked radio", () => {+ render(+ <Trap>+ <button type="button">First</button>+ <SizeRadios name="size" />+ </Trap>,+ );+ expectRadioGroupEndsTheCycle();+ });++ it("starts the cycle at a leading group's checked radio", () => {+ render(+ <Trap>+ <SizeRadios name="size" />+ <button type="button">Last</button>+ </Trap>,+ );+ expectRadioGroupStartsTheCycle();+ });++ it("uses a group's first radio when none is checked", () => {+ render(+ <Trap>+ <button type="button">First</button>+ <fieldset>+ <legend>Plan</legend>+ <input type="radio" name="plan" value="a" aria-label="Basic" />+ <input type="radio" name="plan" value="b" aria-label="Pro" />+ </fieldset>+ </Trap>,+ );+ const basic = screen.getByRole('radio', {name: 'Basic'});+ basic.focus();+ expect(fireEvent.keyDown(basic, {key: 'Tab'})).toBe(false);+ expect(screen.getByRole('button', {name: 'First'})).toHaveFocus();+ });++ it("wraps Shift+Tab onto an unchecked trailing group's last radio", () => {+ render(+ <Trap>+ <button type="button">First</button>+ <fieldset>+ <legend>Plan</legend>+ <input type="radio" name="plan" value="a" aria-label="Basic" />+ <input type="radio" name="plan" value="b" aria-label="Pro" />+ </fieldset>+ </Trap>,+ );+ const first = screen.getByRole('button', {name: 'First'});+ first.focus();+ // Entering a group with nothing checked backward lands on its last radio,+ // as the browser does.+ expect(fireEvent.keyDown(first, {key: 'Tab', shiftKey: true})).toBe(false);+ expect(screen.getByRole('radio', {name: 'Pro'})).toHaveFocus();+ });++ it('keeps a checked radio at its own place when a control sits between the radios', () => {+ // A RadioList whose first option's description holds a link builds this+ // shape: the checked radio, not the link, is the region's last stop.+ render(+ <Trap>+ <button type="button">First</button>+ <input type="radio" name="tier" aria-label="Basic" />+ <button type="button">Basic details</button>+ <input type="radio" name="tier" aria-label="Pro" defaultChecked />+ </Trap>,+ );+ const pro = screen.getByRole('radio', {name: 'Pro'});+ const details = screen.getByRole('button', {name: 'Basic details'});+ pro.focus();+ expect(fireEvent.keyDown(pro, {key: 'Tab'})).toBe(false);+ expect(screen.getByRole('button', {name: 'First'})).toHaveFocus();+ // From the control between the radios, Tab goes on to the checked radio.+ details.focus();+ expect(fireEvent.keyDown(details, {key: 'Tab'})).toBe(true);+ });++ it('keeps every radio of an unchecked group split by a control a stop', () => {+ render(+ <Trap>+ <button type="button">First</button>+ <input type="radio" name="tier" aria-label="Basic" />+ <button type="button">Basic details</button>+ <input type="radio" name="tier" aria-label="Pro" />+ </Trap>,+ );+ const details = screen.getByRole('button', {name: 'Basic details'});+ details.focus();+ // Pro is still ahead of the control, so Tab is left to the browser.+ expect(fireEvent.keyDown(details, {key: 'Tab'})).toBe(true);+ const pro = screen.getByRole('radio', {name: 'Pro'});+ pro.focus();+ expect(fireEvent.keyDown(pro, {key: 'Tab'})).toBe(false);+ expect(screen.getByRole('button', {name: 'First'})).toHaveFocus();+ });++ it('keeps each unnamed radio its own Tab stop', () => {+ render(+ <Trap>+ <button type="button">First</button>+ <input type="radio" aria-label="One" defaultChecked />+ <input type="radio" aria-label="Two" />+ </Trap>,+ );+ const one = screen.getByRole('radio', {name: 'One'});+ one.focus();+ // "Two" is still ahead, so Tab is left to the browser.+ expect(fireEvent.keyDown(one, {key: 'Tab'})).toBe(true);+ });++ it('treats same-name radios in different forms as different groups', () => {+ render(+ <Trap>+ <button type="button">First</button>+ <form aria-label="A">+ <input type="radio" name="x" aria-label="A1" defaultChecked />+ </form>+ <form aria-label="B">+ <input type="radio" name="x" aria-label="B1" defaultChecked />+ </form>+ </Trap>,+ );+ const a1 = screen.getByRole('radio', {name: 'A1'});+ a1.focus();+ expect(fireEvent.keyDown(a1, {key: 'Tab'})).toBe(true);+ });+});diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex 62c4adaa7b..3f25c3b104 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -132,6 +132,61 @@ export function getFocusableElements(container: HTMLElement): HTMLElement[] {).filter(isVisiblyFocusable);}+/**+ * The name of a named native radio, or null for any other element and for an+ * unnamed radio, which is its own Tab stop.+ */+function radioNameOf(el: Element): string | null {+ if (!el.matches('input[type="radio"][name]')) {+ return null;+ }+ return (el as HTMLInputElement).name || null;+}++/**+ * Whether two radios are one group: the same name and the same form owner (or+ * both with no form).+ */+function isSameRadioGroup(a: Element, b: Element): boolean {+ const name = radioNameOf(a);+ return (+ name != null &&+ name === radioNameOf(b) &&+ (a as HTMLInputElement).form === (b as HTMLInputElement).form+ );+}++/**+ * Drop the radios the browser skips for Tab, leaving every other element, and+ * each kept radio, at its own place. In a named group the browser stops only at+ * the focused radio, else the checked one; a group with nothing checked keeps+ * every radio, so a forward entry reaches its first and a backward entry its+ * last.+ *+ * Exported for menus that walk their own Tab stops (DropdownMenu's header and+ * footer), so they skip radios exactly as the focus region does.+ */+export function collapseRadioGroups(+ elements: HTMLElement[],+ active: Element | null,+): HTMLElement[] {+ return elements.filter(el => {+ if (radioNameOf(el) == null) {+ return true;+ }+ if (active != null && isSameRadioGroup(el, active)) {+ return el === active;+ }+ return (+ (el as HTMLInputElement).checked ||+ !elements.some(+ other =>+ isSameRadioGroup(el, other) && (other as HTMLInputElement).checked,+ )+ );+ });+}+/*** The document a trap lives in: its container's. An app that renders into a* same-origin iframe or a Document Picture-in-Picture window through a portal@@ -376,8 +431,13 @@ export function useFocusRegionContainment(return;}- const first = focusable[0];- const last = focusable[focusable.length - 1];+ // jsdom groups a selector list by selector, not in document order.+ const stops = collapseRadioGroups(+ [...focusable].sort((a, b) => (precedes(a, b) ? -1 : 1)),+ active,+ );+ const first = stops[0];+ const last = stops[stops.length - 1];if (doc.activeElement === container) {// Programmatic initial focus can sit on the trap container itself