Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions components/dash-core-components/src/fragments/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,16 @@ const Dropdown = (props: DropdownProps) => {
const positioningContainerRef = useRef<HTMLDivElement>(null);
const canClearValues = clearable && !disabled && !!sanitizedValues.length;

const setFocusTargetTabIndex = (
button: HTMLButtonElement,
tabIndex: number
) => {
const dummyInput = button.previousElementSibling;
if (dummyInput instanceof HTMLElement) {
dummyInput.tabIndex = tabIndex;
}
};

const popover = (
<Popover.Root open={isOpen} onOpenChange={handleOpenChange}>
{/* Safari skips <button> in the Tab order; this hidden
Expand All @@ -431,7 +441,6 @@ const Dropdown = (props: DropdownProps) => {
aria-hidden="true"
onFocus={e => {
if (e.relatedTarget !== dropdownContainerRef.current) {
e.currentTarget.tabIndex = -1;
dropdownContainerRef.current?.focus();
}
}}
Expand All @@ -446,13 +455,13 @@ const Dropdown = (props: DropdownProps) => {
disabled={disabled}
type="button"
tabIndex={-1}
onBlur={e => {
const dummyInput =
e.currentTarget.previousElementSibling;
if (dummyInput instanceof HTMLElement) {
dummyInput.tabIndex = 0;
}
}}
onFocus={e => setFocusTargetTabIndex(e.currentTarget, -1)}
onBlur={e =>
setFocusTargetTabIndex(
e.currentTarget,
disabled ? -1 : 0
)
}
onKeyDown={e => {
if (['ArrowDown', 'Enter'].includes(e.key)) {
e.preventDefault();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,71 @@ def shift_tab():
assert dash_duo.get_logs() == []


def test_a11y012d_shift_tab_after_escape_or_enter(dash_duo):
"""Shift+Tab after closing a clicked dropdown with Escape or Enter should
move focus to the previous element rather than trapping on the focus target."""
from dash.html import Button as HtmlButton

def send_keys(key):
actions = ActionChains(dash_duo.driver)
actions.send_keys(key)
actions.perform()

def shift_tab():
actions = ActionChains(dash_duo.driver)
actions.key_down(Keys.SHIFT).send_keys(Keys.TAB).key_up(Keys.SHIFT)
actions.perform()

app = Dash(__name__)
app.layout = Div(
[
HtmlButton("before", id="before"),
Dropdown(
id="dd",
options=["Apple", "Banana"],
),
HtmlButton("after", id="after"),
Div(id="output"),
]
)

@app.callback(Output("output", "children"), Input("dd", "value"))
def update_output(value):
return f"Selected: {value}"

dash_duo.start_server(app)
dash_duo.wait_for_element("#dd")

# Click dropdown, press Escape, then Shift+Tab should reach #before
dash_duo.find_element("#dd").click()
dash_duo.wait_for_element(".dash-dropdown-options")
send_keys(Keys.ESCAPE)
with pytest.raises(TimeoutException):
dash_duo.wait_for_element(".dash-dropdown-options", timeout=0.25)
shift_tab()
until(
lambda: dash_duo.driver.execute_script("return document.activeElement.id;")
== "before",
timeout=2,
)

# Click dropdown, pick an option with Enter, then Shift+Tab should reach #before
dash_duo.find_element("#dd").click()
dash_duo.wait_for_element(".dash-dropdown-options")
send_keys(Keys.ARROW_DOWN)
sleep(0.1)
send_keys(Keys.ENTER)
dash_duo.wait_for_text_to_equal("#output", "Selected: Apple")
shift_tab()
until(
lambda: dash_duo.driver.execute_script("return document.activeElement.id;")
== "before",
timeout=2,
)

assert dash_duo.get_logs() == []


def test_a11y013_enter_on_search_after_reopen_selects_correctly(dash_duo):
def send_keys(key):
actions = ActionChains(dash_duo.driver)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import React from 'react';
import {fireEvent, render, screen, waitFor} from '@testing-library/react';
import Dropdown from '../../../src/components/Dropdown';

const options = [
{label: 'Apple', value: 'apple'},
{label: 'Banana', value: 'banana'},
];

async function findDropdownElements(container: HTMLElement) {
const trigger = await waitFor(() => {
const button = container.querySelector('button.dash-dropdown');
expect(button).toBeInstanceOf(HTMLButtonElement);
return button as HTMLButtonElement;
});
const focusTarget = container.querySelector('.dash-dropdown-focus-target');
expect(focusTarget).toBeInstanceOf(HTMLInputElement);
return {
trigger,
focusTarget: focusTarget as HTMLInputElement,
};
}

describe('Dropdown focus target', () => {
it('removes focus target from tab order when trigger button is focused directly and restores it on blur', async () => {
const {container} = render(
<div>
<button type="button">Before</button>
<Dropdown
id="test-dropdown"
options={options}
setProps={jest.fn()}
/>
<button type="button">After</button>
</div>
);

const {trigger, focusTarget} = await findDropdownElements(container);
expect(focusTarget.tabIndex).toBe(0);

// Simulates clicking the trigger or Radix returning focus after Escape/selection.
fireEvent.focus(trigger);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fireEvent.focus only calls the handler. It doesn't show that a real Shift+Tab skips the hidden input. These assertions would pass even if the browser chose where focus goes after the blur restores tabIndex=0, and that ordering is what this bug is about. Can you add an integration test in tests/integration/dropdown/test_a11y.py next to test_a11y012c? Click the dropdown, press Escape, Shift+Tab, then assert document.activeElement.id == "before". A second case that picks an option with Enter before the Shift+Tab would cover the other path in the issue. That test should fail on dev and pass here.

expect(focusTarget.tabIndex).toBe(-1);

// Moving focus out restores the focus target so Safari Tab navigation still works.
fireEvent.blur(trigger);
expect(focusTarget.tabIndex).toBe(0);
});

it('keeps focus target untabbable when disabled', async () => {
const {container} = render(
<Dropdown
id="disabled-dropdown"
options={options}
disabled
setProps={jest.fn()}
/>
);

const {trigger, focusTarget} = await findDropdownElements(container);
expect(focusTarget.tabIndex).toBe(-1);

fireEvent.focus(trigger);
expect(focusTarget.tabIndex).toBe(-1);

fireEvent.blur(trigger);
expect(focusTarget.tabIndex).toBe(-1);
});

it('delegates focus from focus target to trigger button when entering from another element', async () => {
const {container} = render(
<div>
<button type="button">Before</button>
<Dropdown
id="tab-dropdown"
options={options}
setProps={jest.fn()}
/>
</div>
);

const beforeButton = screen.getByRole('button', {name: 'Before'});
const {trigger, focusTarget} = await findDropdownElements(container);

fireEvent.focus(focusTarget, {relatedTarget: beforeButton});

expect(focusTarget.tabIndex).toBe(-1);
expect(document.activeElement).toBe(trigger);
});
});