Skip to content
Merged
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
26 changes: 21 additions & 5 deletions src/hooks/useAccessibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,28 @@ export default function useAccessibility({
};

const focusMenu = (options?: FocusOptions) => {
if (overlayRef.current?.focus) {
overlayRef.current.focus(options);
focusMenuRef.current = true;
return true;
const overlay = overlayRef?.current;
if (!overlay?.focus) {
return false;
}
return false;

const activeElement = document.activeElement;
overlay.focus(options);
if (document.activeElement === activeElement) {
for (const selector of ['[role="menu"]', '[tabindex]']) {
const focusTarget = overlay.querySelector?.(
selector,
) as HTMLElement | null;
focusTarget?.focus(options);
if (document.activeElement !== activeElement) {
break;
}
}
}

const focused = document.activeElement !== activeElement;
focusMenuRef.current = focused;
return focused;
};

const handleKeyDown = (event) => {
Expand Down
145 changes: 101 additions & 44 deletions tests/basic.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -492,13 +492,63 @@ describe('dropdown', () => {

// Focus menu with Tab
window.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 9 })); // Tab
expect(document.activeElement).toHaveClass('rc-menu');
fireEvent.keyDown(document.activeElement, {
key: 'ArrowDown',
keyCode: 40,
});
await sleep(50);
expect(document.activeElement).toHaveTextContent('one');

// Close menu with Tab
window.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 9 })); // Tab
fireEvent.keyDown(document.activeElement, { key: 'Tab', keyCode: 9 });
await sleep(200);
expect(document.activeElement.className).toContain('my-button');
});

it.each(['missing', 'unfocusable'])(
'focuses a tab target when the wrapped menu is %s',
async (menuState) => {
jest.useFakeTimers();
try {
const { container, baseElement } = render(
<Dropdown
trigger={['click']}
overlay={
<div>
{menuState === 'unfocusable' && <div role="menu" />}
<button tabIndex={0} className="custom-target">
action
</button>
</div>
}
>
<button className="my-button">open</button>
</Dropdown>,
);
const trigger =
container.querySelector<HTMLButtonElement>('.my-button');
trigger.focus();
fireEvent.click(trigger);
await waitForTime();

const event = new KeyboardEvent('keydown', {
keyCode: 9,
cancelable: true,
});
act(() => {
window.dispatchEvent(event);
});
expect(document.activeElement).toBe(
baseElement.querySelector('.custom-target'),
);
expect(event.defaultPrevented).toBe(true);
} finally {
jest.useRealTimers();
}
},
);

it('support Menu expandIcon', async () => {
const props = {
overlay: (
Expand Down Expand Up @@ -584,50 +634,57 @@ describe('dropdown', () => {
jest.useRealTimers();
});

it('should support autoFocus', async () => {
jest.useFakeTimers();
const focusSpy = jest.spyOn(HTMLElement.prototype, 'focus');
it.each(['direct', 'wrapped'])(
'should support autoFocus for a %s menu',
async (mode) => {
jest.useFakeTimers();
const focusSpy = jest.spyOn(HTMLElement.prototype, 'focus');

try {
const overlay = (
<Menu>
<MenuItem key="1">
<span className="my-menuitem">one</span>
</MenuItem>
<MenuItem key="2">two</MenuItem>
</Menu>
);
const { container } = render(
<Dropdown autoFocus trigger={['click']} overlay={overlay}>
<button className="my-button">open</button>
</Dropdown>,
);
const trigger = container.querySelector('.my-button');

// Open menu
fireEvent.click(trigger);

await waitForTime();

expect(
container
.querySelector('.rc-dropdown')
.classList.contains('rc-dropdown-hidden'),
).toBeFalsy();
expect(document.activeElement.className).toContain('menu');
expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });

// Close menu with Tab
window.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 9 })); // Tab

await waitForTime();

expect(document.activeElement.className).toContain('my-button');
} finally {
focusSpy.mockRestore();
jest.useRealTimers();
}
});
try {
const overlay = (
<Menu>
<MenuItem key="1">
<span className="my-menuitem">one</span>
</MenuItem>
<MenuItem key="2">two</MenuItem>
</Menu>
);
const { container } = render(
<Dropdown
autoFocus
trigger={['click']}
overlay={mode === 'wrapped' ? <div>{overlay}</div> : overlay}
>
<button className="my-button">open</button>
</Dropdown>,
);
const trigger = container.querySelector('.my-button');

// Open menu
fireEvent.click(trigger);

await waitForTime();

expect(
container
.querySelector('.rc-dropdown')
.classList.contains('rc-dropdown-hidden'),
).toBeFalsy();
expect(document.activeElement.className).toContain('menu');
expect(focusSpy).toHaveBeenLastCalledWith({ preventScroll: true });

// Close menu with Tab
window.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 9 })); // Tab

await waitForTime();

expect(document.activeElement.className).toContain('my-button');
} finally {
focusSpy.mockRestore();
jest.useRealTimers();
}
},
);

it('children cannot be given ref should not throw', () => {
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
Expand Down
30 changes: 30 additions & 0 deletions tests/useAccessibility.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { act, renderHook } from '@testing-library/react';
import useAccessibility from '../src/hooks/useAccessibility';

it('closes without consuming Tab when the overlay ref is omitted', () => {
const trigger = document.createElement('button');
document.body.appendChild(trigger);
const onOpenChange = jest.fn();
const { unmount } = renderHook(() =>
useAccessibility({
open: true,
triggerRef: { current: trigger },
onOpenChange,
}),
);
try {
const event = new KeyboardEvent('keydown', {
keyCode: 9,
cancelable: true,
});
act(() => {
window.dispatchEvent(event);
});
expect(event.defaultPrevented).toBe(false);
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(document.activeElement).toBe(trigger);
} finally {
unmount();
trigger.remove();
}
});
Loading