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
22 changes: 17 additions & 5 deletions src/components/Menu/Menu.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as React from 'react';
import {
AccessibilityInfo,
Dimensions,
findNodeHandle,
Keyboard,
Platform,
Pressable,
Expand Down Expand Up @@ -122,10 +124,13 @@ const getKeyboardHeight = (fallback: number) =>
const DEFAULT_ELEVATION: Elevation = 2;
const DEFAULT_MODE = 'elevated';

const focusFirstDOMNode = (
const focusFirstNode = (
el: React.ComponentRef<typeof View> | null | undefined
) => {
if (el && Platform.OS === 'web') {
if (!el) {
return;
}
if (Platform.OS === 'web') {
// When in the browser, we want to focus the first focusable item on toggle
// For example, when menu is shown, focus the first item in the menu
// And when menu is dismissed, send focus back to the button to resume tabbing
Expand All @@ -135,6 +140,13 @@ const focusFirstDOMNode = (
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
)?.focus();
}
return;
}
// On native, move the screen reader focus to the menu when it opens and
// back to the anchor when it closes, matching the web behavior above.
const node = findNodeHandle(el);
if (node) {
AccessibilityInfo.setAccessibilityFocus(node);
}
};

Expand Down Expand Up @@ -314,7 +326,7 @@ const Menu = ({
}

isShownRef.current = true;
focusFirstDOMNode(menuRef.current);
focusFirstNode(menuRef.current);
});

const handleHideAnimationFinished = useLatestCallback((finished: boolean) => {
Expand All @@ -325,7 +337,7 @@ const Menu = ({
setMenuLayout({ width: 0, height: 0 });
setRendered(false);
isShownRef.current = false;
focusFirstDOMNode(anchorRef.current);
focusFirstNode(anchorRef.current);
});

const show = React.useCallback(async () => {
Expand Down Expand Up @@ -673,7 +685,7 @@ const Menu = ({
>
{isCoordinate(anchor) ? null : anchor}
{rendered ? (
<Portal>
<Portal modal={visible}>
<Pressable
aria-label={dismissAccessibilityLabel}
role="button"
Expand Down
163 changes: 163 additions & 0 deletions src/components/__tests__/Menu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,29 @@
jest,
} from '@jest/globals';
import { act, screen, waitFor } from '@testing-library/react-native';
import * as Reanimated from 'react-native-reanimated';

import PaperProvider from '../../core/PaperProvider';
import { render } from '../../test-utils';
import { LightTheme } from '../../theme/schemes';
import type { Elevation } from '../../theme/types';
import Button from '../Button/Button';
import Menu from '../Menu/Menu';
import Portal from '../Portal/Portal';

jest.mock('react-native-reanimated', () => {
const ReanimatedModule = jest.requireActual<
typeof import('react-native-reanimated')
>('react-native-reanimated');

return {
__esModule: true,
...ReanimatedModule,
default: ReanimatedModule.default,
withTiming: jest.fn(ReanimatedModule.withTiming),
};
});

describe('web focus', () => {
const PAST_ANIMATION_MS = 300;
const focus = jest.fn();
Expand Down Expand Up @@ -152,6 +167,40 @@
expect(tree).toMatchSnapshot();
});

it('hides content behind an open menu from screen readers until it closes', async () => {
const PAST_ANIMATION_MS = 300;

const makeMenu = (visible: boolean) => (
<Portal.Host>
<Menu
visible={visible}
onDismiss={jest.fn()}
anchor={<Button mode="outlined">Open menu</Button>}
>
<Menu.Item onPress={jest.fn()} title="Undo" />
<Menu.Item onPress={jest.fn()} title="Redo" />
</Menu>
</Portal.Host>
);

const { rerender, toJSON } = await render(makeMenu(false));

const rootProps = () => {
const json = toJSON();
return json && !Array.isArray(json) ? json.props : {};

Check failure on line 190 in src/components/__tests__/Menu.test.tsx

View workflow job for this annotation

GitHub Actions / Lint

Do not read TestInstance props directly. Prefer user-visible assertions
};

expect(rootProps()['aria-hidden']).toBeUndefined();

await rerender(makeMenu(true));
await act(() => jest.advanceTimersByTime(PAST_ANIMATION_MS));
expect(rootProps()['aria-hidden']).toBe(true);

await rerender(makeMenu(false));
await act(() => jest.advanceTimersByTime(PAST_ANIMATION_MS));
expect(rootProps()['aria-hidden']).toBeUndefined();
});

const ViewPrototype: ComponentRef<typeof View> = View.prototype;

const elevations: Elevation[] = [0, 1, 2, 3, 4, 5];
Expand Down Expand Up @@ -457,3 +506,117 @@
dimensionsSpy.mockRestore();
}
});

it('scales in again when reopened at the same anchor', async () => {
const testID = 'reopened-menu';
const measureSpy = jest
.spyOn(ViewPrototype, 'measureInWindow')
.mockImplementation((fn) => fn(100, 100, 80, 32));

function makeMenu(visible: boolean) {
return (
<Portal.Host>
<Menu
visible={visible}
onDismiss={jest.fn()}
anchor={<Button mode="outlined">Open menu</Button>}
testID={testID}
>
<Menu.Item onPress={jest.fn()} title="Undo" />
</Menu>
</Portal.Host>
);
}

const openAndSample = async () => {
await act(async () => {
await screen.rerender(makeMenu(true));
});
await act(() => jest.advanceTimersByTimeAsync(100));
const style = Reanimated.getAnimatedStyle(screen.getByTestId(testID));
await act(() => jest.advanceTimersByTimeAsync(500));
return style;
};

try {
await render(makeMenu(false));

const firstOpen = await openAndSample();
// Partway through the first open, the menu is still growing.
expect(firstOpen).not.toMatchObject({
transform: [{ scaleX: 1 }, { scaleY: 1 }],
});

await act(async () => {
await screen.rerender(makeMenu(false));
});
await act(() => jest.advanceTimersByTimeAsync(500));
expect(screen.queryByTestId(testID)).toBeNull();

const secondOpen = await openAndSample();
expect(secondOpen).toEqual(firstOpen);
} finally {
measureSpy.mockRestore();
}
});

it.each([
{ reduceMotion: 'off', duration: 250 },
{ reduceMotion: 'on', duration: 0 },
] as const)(
'opens and closes in $duration ms when reduceMotion is "$reduceMotion"',
async ({ reduceMotion, duration }) => {
const withTiming = jest.mocked(Reanimated.withTiming);
const durations = () =>
withTiming.mock.calls.map(([, config]) => config?.duration);
const measureSpy = jest
.spyOn(ViewPrototype, 'measureInWindow')
.mockImplementation((fn) => fn(100, 100, 80, 32));

function makeMenu(visible: boolean) {
return (
<PaperProvider reduceMotion={reduceMotion}>
<Menu
visible={visible}
onDismiss={jest.fn()}
anchor={<Button mode="outlined">Open menu</Button>}
>
<Menu.Item onPress={jest.fn()} title="Undo" />
</Menu>
</PaperProvider>
);
}

try {
const { rerender } = await render(makeMenu(false));
// Earlier tests can leave a menu waiting for an animation frame to open.
await act(async () => {
await jest.runOnlyPendingTimersAsync();
});
withTiming.mockClear();

await act(async () => {
await rerender(makeMenu(true));
// Menu waits a tick for Portal refs to be up-to-date.
await Promise.resolve();
});
// The open animation starts on the next animation frame.
await act(async () => {
await jest.advanceTimersByTimeAsync(50);
});

// Width, height and opacity.
expect(durations()).toEqual([duration, duration, duration]);

withTiming.mockClear();
await act(async () => {
await rerender(makeMenu(false));
await Promise.resolve();
});

expect(durations()).toEqual([duration]);
} finally {
measureSpy.mockRestore();
}
}
);
3 changes: 3 additions & 0 deletions src/components/__tests__/__snapshots__/Menu.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ exports[`renders not visible menu 1`] = `
exports[`renders visible menu 1`] = `
<>
<View
aria-hidden={true}
collapsable={false}
pointerEvents="box-none"
style={
Expand Down Expand Up @@ -883,6 +884,7 @@ exports[`renders visible menu 1`] = `
exports[`respects anchorPosition bottom 1`] = `
<>
<View
aria-hidden={true}
collapsable={false}
pointerEvents="box-none"
style={
Expand Down Expand Up @@ -1554,6 +1556,7 @@ exports[`respects anchorPosition bottom 1`] = `
exports[`uses the default anchorPosition of top 1`] = `
<>
<View
aria-hidden={true}
collapsable={false}
pointerEvents="box-none"
style={
Expand Down
Loading