diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index e8e5ec373a..3bc3cd5c8f 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -1765,7 +1765,7 @@ screen.getByTestId('compose', { includeHiddenElements: true }); `FAB.Menu` replaces `FAB.Group`. It takes `expanded` and `onDismiss` instead of `open` and `onStateChange`, the main button's props move into `trigger`, and `actions` are now `items`, 2 to 6 of them. Items take `icon`, `label`, `onPress`, `aria-label` and `testID`: the color, style and size props of an action were removed, and so were `backdropColor`, `fabStyle` and the long-press props. -`FAB.Menu` has no backdrop and doesn't close on a tap outside it. It closes when the user presses its close button or an item, which calls `onDismiss`. +`FAB.Menu` has no backdrop and doesn't close on a tap outside it. It calls `onDismiss` when the user presses its close button or an item, presses Escape (web), uses the hardware back button (Android) or the screen reader escape gesture (iOS), or when the trigger is hidden while the menu is open. ```diff - void; /** - * Accessibility label for the trigger FAB. + * Accessibility label for the trigger FAB. On web it also names the open + * menu, so set it when the trigger shows only an icon. Without it, the + * trigger has no accessible name, and the web menu is not exposed as a + * `menu`: its items are buttons. */ 'aria-label'?: string; testID?: string; @@ -82,7 +98,10 @@ export type MenuProps = { */ expanded: boolean; /** - * Called when the user taps the close button or taps an item. + * Called when the menu should close: the user taps the close button or an + * item, presses Escape (web), the hardware back button (Android) or performs + * the screen reader escape gesture (iOS). It is also called when the trigger + * is hidden while the menu is open. */ onDismiss: () => void; /** @@ -147,6 +166,19 @@ const getItemsVariant = (triggerVariant: Variant): Variant => { // fixed delay per index. const STAGGER_MS = 30; +// Room the items scroll view keeps around the items, so it doesn't clip the +// hover shadow. It stays as wide as it was when the focus ring was drawn +// outside the items, so they don't move. Taps in this margin don't reach the +// content below on Android, so keep it small. +const { thickness: FOCUS_RING_THICKNESS, outerOffset: FOCUS_RING_OFFSET } = + tokens.md.sys.state.focusIndicator; +const FOCUS_RING_FOOTPRINT = FOCUS_RING_OFFSET + FOCUS_RING_THICKNESS; +const ITEMS_SCROLL_INSET = FOCUS_RING_FOOTPRINT + 4; + +// The state layer of an item replaces the hover tint of `TouchableRipple`, +// which is only there on web. +const webNoHoverTint: ViewStyle = { backgroundColor: 'transparent' }; + type AnimatedItemProps = { expanded: boolean; index: number; @@ -167,54 +199,34 @@ const AnimatedItem = ({ children, }: AnimatedItemProps) => { const reduceMotion = useReduceMotion(); - // Initial values match the resting state for the current `expanded` prop so - // first mount doesn't animate unexpectedly. - const scaleX = useSharedValue(expanded ? 1 : 0); - const alpha = useSharedValue(expanded ? 1 : 0); + const { duration, easing } = theme.motion; - React.useEffect(() => { - const target = expanded ? 1 : 0; - // Bottom-up on open, top-down on close (matches Compose). - const delay = expanded - ? (itemCount - 1 - index) * STAGGER_MS - : index * STAGGER_MS; + // Bottom-up on open, top-down on close (matches Compose). + const staggerIndex = expanded ? itemCount - 1 - index : index; - if (reduceMotion) { - scaleX.value = target; - alpha.value = target; - return; - } - scaleX.value = withDelay( - delay, - withSpring(target, { - ...toRawSpring(theme.motion.spring.fast.spatial), - reduceMotion: ReduceMotion.Never, - }), - ReduceMotion.Never - ); - alpha.value = withDelay( - delay, - withSpring(target, { - ...toRawSpring(theme.motion.spring.fast.effects), - reduceMotion: ReduceMotion.Never, - }), - ReduceMotion.Never - ); - }, [expanded, index, itemCount, theme, reduceMotion, scaleX, alpha]); + // Reduced motion keeps the opacity fade but drops the horizontal scale and + // the stagger. + const transitionStyle: AnimatedStyle = { + transitionProperty: ['opacity', 'transform'], + transitionDuration: [duration.short2, reduceMotion ? 0 : duration.short4], + transitionDelay: reduceMotion ? 0 : staggerIndex * STAGGER_MS, + transitionTimingFunction: cubicBezier(...easing.standard), + }; // Only scaleX and opacity animate. Layout height stays at the item's // natural size — the items container is absolutely positioned above the // trigger, so this fixed height never affects the trigger's position. - const animStyle = useAnimatedStyle(() => ({ - transform: [{ scaleX: scaleX.value }], - opacity: alpha.value, - })); + const stateStyle: AnimatedStyle = { + opacity: expanded ? 1 : 0, + transform: [{ scaleX: expanded ? 1 : 0 }], + }; return ( void; + /** + * Called with the item's index and its node when it mounts and unmounts. + */ + registerRef: ( + index: number, + node: React.ComponentRef | null + ) => void; onPress: (e: GestureResponderEvent) => void; + /** + * Whether the item sits in a `role="menu"` on the web, which makes it a + * `menuitem`. Otherwise it is a button. + */ + inMenu: boolean; /** * Accessibility label. Falls back to `label`. */ @@ -240,16 +278,23 @@ type ItemProps = { /** * A single FAB Menu item. Visually a tonal pill with an icon and a label, - * but it is not a floating action button: no shadow, no enter/exit scaling - * of its own (the surrounding `AnimatedItem` handles entrance), and its - * shape and dimensions come from the menu spec rather than FAB tokens. + * but it is not a floating action button: no enter/exit scaling of its own + * (the surrounding `AnimatedItem` handles entrance), and its shape and + * dimensions come from the menu spec rather than FAB tokens. It follows the + * FAB's state elevation and state layers. */ const MenuItem = ({ icon, label, variant, theme, + expanded, + index, + tabbable, + onFocusItem, + registerRef, onPress, + inMenu, 'aria-label': ariaLabel, testID, }: ItemProps) => { @@ -258,6 +303,33 @@ const MenuItem = ({ MenuTokens.listItem; const borderRadius = resolveCornerRadius(theme, shape); + const [hovered, setHovered] = React.useState(false); + const [focused, setFocused] = React.useState(false); + + // Items stay mounted while collapsed. Drop their interaction state with the + // menu, otherwise a pointer left over an item shows its state layer again on + // the next open. + React.useEffect(() => { + if (!expanded) { + setHovered(false); + setFocused(false); + } + }, [expanded]); + + // The press is left to the ripple of `TouchableRipple`: a flat layer for it + // would stack on the ripple, and show with the ripple effect turned off. + const interaction: Interaction = focused + ? 'focus' + : hovered + ? 'hover' + : 'enabled'; + const stateLayerStyle: AnimatedStyle = { + backgroundColor: colors.content, + opacity: STATE_LAYER_OPACITY[interaction], + transitionProperty: 'opacity', + transitionDuration: theme.motion.duration.short2, + }; + // `scope: 'within'`: the ring belongs on the pill below, not the inner // `TouchableRipple` that actually receives focus. // @@ -274,39 +346,88 @@ const MenuItem = ({ 'within' ); + // React Native Web presses on Space only for `role="button"`, and the item is + // a `menuitem` in a web menu. A button needs no help, and would press twice. + const { keyHandlers: spaceKeyHandlers, onBlur: handleSpaceKeyBlur } = + useSpaceKeyPress({ onPress }); + + const itemRef = React.useCallback( + (node: React.ComponentRef | null) => registerRef(index, node), + [registerRef, index] + ); + return ( - - - - - + { + focusTarget.onFocus?.(e); + setFocused(isKeyboardFocusEvent(e)); + onFocusItem(index); + }} + onBlur={(e) => { + handleSpaceKeyBlur(e); + focusTarget.onBlur?.(); + setFocused(false); + }} + {...(inMenu ? spaceKeyHandlers : null)} + onHoverIn={() => setHovered(true)} + onHoverOut={() => setHovered(false)} + role={inMenu ? 'menuitem' : 'button'} + aria-label={ariaLabel ?? label} + // `aria-hidden` and `pointerEvents` don't take collapsed items + // out of the tab order. An open menu has one tab stop, as the + // menu pattern asks, and the arrow keys move it. + focusable={expanded} + tabIndex={expanded && (Platform.OS !== 'web' || tabbable) ? 0 : -1} + style={[ + { borderRadius }, + ...focusTarget.style, + // The state layer replaces the hover tint of TouchableRipple. + Platform.OS === 'web' ? webNoHoverTint : null, + ]} + testID={testID} + > + + + + ); }; @@ -325,12 +446,18 @@ type MorphingTriggerProps = { alignment: 'start' | 'center' | 'end'; onPress?: (e: GestureResponderEvent) => void; disabled?: boolean; + /** + * Whether the open menu is exposed as a `menu`, which the trigger then + * announces. Otherwise it says nothing about a popup. + */ + hasMenuPopup: boolean; /** * Accessibility label for the trigger button. */ 'aria-label'?: string; theme: InternalTheme; testID?: string; + ref?: React.Ref>; }; const MorphingTrigger = ({ @@ -346,9 +473,11 @@ const MorphingTrigger = ({ alignment, onPress, disabled, + hasMenuPopup, 'aria-label': ariaLabel, theme, testID, + ref, }: MorphingTriggerProps) => { const reduceMotion = useReduceMotion(); @@ -415,23 +544,28 @@ const MorphingTrigger = ({ [closedBorderRadius, openBorderRadius] ); - const openPlaneStyle = useAnimatedStyle(() => ({ - opacity: 1 - progress.value, - })); - const closePlaneStyle = useAnimatedStyle(() => ({ - opacity: progress.value, - })); + // The morph itself (size, corner, icon position) is the spring above. The + // color and icon cross-fades are effects, so they are CSS transitions. + const fadeTransition: AnimatedStyle = { + transitionProperty: 'opacity', + transitionDuration: theme.motion.duration.short3, + transitionTimingFunction: cubicBezier(...theme.motion.easing.standard), + }; + const openPlaneStyle: AnimatedStyle = { + opacity: expanded ? 0 : 1, + }; + const closePlaneStyle: AnimatedStyle = { + opacity: expanded ? 1 : 0, + }; const openIconAnimStyle = useAnimatedStyle(() => { const offset = (widthShared.value - closedIconSize) / 2; return { - opacity: 1 - progress.value, transform: [{ translateX: offset }, { translateY: offset }], }; }); const closeIconAnimStyle = useAnimatedStyle(() => { const offset = (widthShared.value - openIconSize) / 2; return { - opacity: progress.value, transform: [{ translateX: offset }, { translateY: offset }], }; }); @@ -467,7 +601,10 @@ const MorphingTrigger = ({ onPress={onPress} disabled={disabled} aria-label={ariaLabel} + aria-expanded={expanded} + aria-haspopup={hasMenuPopup ? 'menu' : undefined} testID={testID} + buttonRef={ref} widthShared={widthShared} heightShared={heightShared} borderRadiusShared={borderRadiusShared} @@ -482,6 +619,7 @@ const MorphingTrigger = ({ styles.colorPlane, { backgroundColor: triggerColors.container }, openPlaneStyle, + fadeTransition, ]} /> @@ -497,18 +636,22 @@ const MorphingTrigger = ({ > - + + + - + + + @@ -521,9 +664,12 @@ const MorphingTrigger = ({ * items appear stacked above and the trigger morphs into the spec'd close * button (`shape: 'full'`, 56 dp, saturated role color). * - * No visual backdrop and no outside-tap dismiss — that matches the MD3 spec - * and lets the user keep interacting with the content underneath. Dismiss - * via the close button or by tapping an item. + * There is no visual scrim, and pressing outside the menu does not close it. + * Pressing the close button or an item, pressing Escape (web), the hardware + * back button (Android) or the screen reader escape gesture (iOS) calls + * `onDismiss`. Focus moves to the first item when the menu opens and returns to + * the trigger when it closes. On web, the items are one tab stop: the arrow + * keys, Home and End move focus between them. * * ## Usage * ```tsx @@ -567,12 +713,153 @@ const Menu = ({ const effectiveExpanded = triggerVisible && expanded; + // On web the open menu is named after the trigger. An unnamed `role="menu"` + // is announced with no context, so without a label the items stay buttons. + const triggerLabel = trigger['aria-label']; + const isMenu = Platform.OS === 'web' && !!triggerLabel; + + // A hidden trigger closes the menu, so tell the parent. Otherwise `expanded` + // stays true, and the menu opens again by itself when the trigger comes back. + const dismissWhenTriggerHides = useLatestCallback(onDismiss); + + React.useEffect(() => { + if (expanded && !triggerVisible) { + dismissWhenTriggerHides(); + } + }, [expanded, triggerVisible, dismissWhenTriggerHides]); + + // Back (Android) and Escape (web) go through the overlay stack, so that a + // menu opened from a modal closes first and the modal stays. + useOverlayDismiss({ + enabled: effectiveExpanded, + dismissable: true, + onDismiss, + }); + + const triggerRef = React.useRef>(null); + const scrollRef = React.useRef>(null); + const itemRefs = React.useRef<(React.ComponentRef | null)[]>([]); + const itemsRef = React.useRef>(null); + const firstItemRef = React.useRef | null>( + null + ); + + const [containerHeight, setContainerHeight] = React.useState(); + // The item that is the menu's one tab stop on web. The arrow keys move it. + const [activeIndex, setActiveIndex] = React.useState(0); + + React.useEffect(() => { + if (!effectiveExpanded) { + setActiveIndex(0); + } + }, [effectiveExpanded]); + + const registerItemRef = React.useCallback( + (index: number, node: React.ComponentRef | null) => { + itemRefs.current[index] = node; + + if (index === 0) { + firstItemRef.current = node; + } + }, + [] + ); + const handleItemPress = (item: MenuItemProps) => (e: GestureResponderEvent) => { item.onPress(e); onDismiss(); }; + // Focus moves to the first item when the menu opens, and back to the trigger + // when it closes. + const { focusInitialTarget, restoreFocus } = useOverlayFocus({ + visible: effectiveExpanded, + containerRef: itemsRef, + initialFocusRef: firstItemRef, + restoreFocusRef: triggerRef, + }); + + const reduceMotion = useReduceMotion(); + const { duration } = theme.motion; + + // Transparent views are not in the accessibility tree, so on iOS and Android + // focus waits for the first item to fade in: the items stagger, and the first + // one is the last to start. A browser can focus an item right away. + const focusDelay = + Platform.OS === 'web' + ? 0 + : reduceMotion + ? duration.short2 + : (items.length - 1) * STAGGER_MS + duration.short4; + + React.useEffect(() => { + if (!effectiveExpanded) { + return undefined; + } + + const timeout = setTimeout(focusInitialTarget, focusDelay); + + return () => clearTimeout(timeout); + }, [effectiveExpanded, focusInitialTarget, focusDelay]); + + React.useEffect(() => { + if (!effectiveExpanded) { + restoreFocus(); + } + }, [effectiveExpanded, restoreFocus]); + + // A long list scrolls, so start from the first item every time it opens. + React.useEffect(() => { + if (effectiveExpanded) { + scrollRef.current?.scrollTo({ y: 0, animated: false }); + } + }, [effectiveExpanded]); + + // Arrow keys, Home and End move focus between the items. The close button is + // outside the menu, so they leave it alone. Dismissing the menu is left to + // `useOverlayDismiss` above. + React.useEffect(() => { + if ( + Platform.OS !== 'web' || + !('document' in global) || + !effectiveExpanded + ) { + return undefined; + } + + const onKeyDown = (e: KeyboardEvent) => { + // Something else, such as a dialog on top, already handled the key. + if (e.defaultPrevented) { + return; + } + + if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { + return; + } + + // Items are in visual order, top to bottom. Each ref is the focusable + // element itself. A `tabindex` of -1 still takes focus from a script. + const stops = itemRefs.current.flatMap((node) => + node instanceof HTMLElement ? [node] : [] + ); + const current = stops.findIndex((el) => el === document.activeElement); + const next = getNextStopIndex(e.key, current, stops.length); + + if (current === -1 || next === null) { + return; + } + + e.preventDefault(); + + stops[next].focus(); + }; + + document.addEventListener('keydown', onKeyDown); + + return () => document.removeEventListener('keydown', onKeyDown); + }, [effectiveExpanded]); + const flexAlign: 'flex-start' | 'center' | 'flex-end' = alignment === 'start' ? 'flex-start' @@ -592,21 +879,50 @@ const Menu = ({ const triggerSlotSize = Tokens.sizes[size].container; + const paddingBottom = insets.bottom + 16; + // Space left above the trigger. The scroll inset is added back because the + // scroll view reserves room for the shadow and focus ring of every item. + const itemsMaxHeight = + containerHeight === undefined + ? undefined + : Math.max( + 0, + containerHeight - + insets.top - + paddingBottom - + triggerSlotSize - + MenuTokens.spacing.closeToLastItem + ) + + ITEMS_SCROLL_INSET * 2; + + // Only the items take touches, so taps next to them in the scroll view's + // margin reach the content below. When collapsed, nothing does. Android + // doesn't scroll with `box-none`. + const itemsPointerEvents = !effectiveExpanded + ? styles.pointerEventsNone + : Platform.OS === 'android' + ? null + : styles.pointerEventsBoxNone; + return ( setContainerHeight(e.nativeEvent.layout.height)} + // The screen reader escape gesture (iOS). + onAccessibilityEscape={effectiveExpanded ? onDismiss : undefined} testID={testID} > - {items.map((item, index) => { - const isLast = index === items.length - 1; - return ( - - + {items.map((item, index) => { + const isLast = index === items.length - 1; + return ( + - - ); - })} + transformOrigin={itemTransformOrigin} + marginBottom={isLast ? 0 : MenuTokens.spacing.betweenItems} + > + + + ); + })} + >; + /** + * Ref to the pressable inside the shell, the element that receives focus. + */ + buttonRef?: React.Ref>; }; /** @@ -214,6 +222,7 @@ const Shell = ({ 'aria-selected': ariaSelected, 'aria-busy': ariaBusy, 'aria-expanded': ariaExpanded, + 'aria-haspopup': ariaHasPopup, labelMaxFontSizeMultiplier, labelAnimatedStyle, background, @@ -227,11 +236,28 @@ const Shell = ({ testID, theme: themeOverrides, ref, + buttonRef, }: ShellProps) => { const theme = useInternalTheme(themeOverrides); const [hovered, setHovered] = React.useState(false); const [pressed, setPressed] = React.useState(false); - const touchableRef = React.useRef>(null); + const touchableRef = React.useRef | null>( + null + ); + // The touchable is the element the web focus handling below looks at, and + // the one `buttonRef` hands to the caller, so a single ref feeds both. + const setTouchableRef = React.useCallback( + (node: React.ComponentRef | null) => { + touchableRef.current = node; + + if (typeof buttonRef === 'function') { + buttonRef(node); + } else if (buttonRef) { + buttonRef.current = node; + } + }, + [buttonRef] + ); const previousFocusedElement = React.useRef(null); const hoveredRef = React.useRef(false); const pressingRef = React.useRef(false); @@ -443,7 +469,7 @@ const Shell = ({ > {overlay} diff --git a/src/components/FAB/tokens.ts b/src/components/FAB/tokens.ts index b83c18edf0..0ffddba907 100644 --- a/src/components/FAB/tokens.ts +++ b/src/components/FAB/tokens.ts @@ -1,3 +1,4 @@ +import { tokens } from '../../theme/tokens'; import type { ColorRole, Elevation, @@ -97,6 +98,8 @@ const closeButton = { shape: 'full', } as const; +export type Interaction = keyof typeof stateElevation; + const listItem = { height: 56, shape: 'full', @@ -104,6 +107,14 @@ const listItem = { leading: 24, trailing: 24, iconLabelGap: 8, + labelTypescale: 'titleMedium' satisfies TypescaleKey, + // Items are tonal, so they sit flat and lift on hover like tonal buttons. + elevation: { + enabled: 0, + hover: 1, + focus: 0, + pressed: 0, + } as const satisfies Record, } as const; const spacing = { @@ -116,3 +127,11 @@ export const MenuTokens = { listItem, spacing, }; + +const stateOpacity = tokens.md.sys.state.opacity; +export const STATE_LAYER_OPACITY = { + enabled: 0, + hover: stateOpacity.hovered, + focus: stateOpacity.focused, + pressed: stateOpacity.pressed, +} as const satisfies Record; diff --git a/src/components/FAB/utils.ts b/src/components/FAB/utils.ts index 9c1a0eb72d..b85af9a88c 100644 --- a/src/components/FAB/utils.ts +++ b/src/components/FAB/utils.ts @@ -82,3 +82,28 @@ export const getDimensions = ({ labelTypescale: spec.labelTypescale, }; }; + +/** + * Where keyboard focus goes inside the open menu. Arrow keys wrap around, + * Home and End jump to the first and last item. + * + * @returns The index to focus, or `null` for a key that doesn't move focus. + */ +export const getNextStopIndex = ( + key: string, + current: number, + count: number +): number | null => { + switch (key) { + case 'Home': + return 0; + case 'End': + return count - 1; + case 'ArrowDown': + return (current + 1) % count; + case 'ArrowUp': + return (current - 1 + count) % count; + default: + return null; + } +}; diff --git a/src/components/__tests__/FABMenu.test.tsx b/src/components/__tests__/FABMenu.test.tsx index 40a455132e..e796836204 100644 --- a/src/components/__tests__/FABMenu.test.tsx +++ b/src/components/__tests__/FABMenu.test.tsx @@ -1,11 +1,37 @@ -import { expect, it, jest } from '@jest/globals'; -import { fireEvent, userEvent } from '@testing-library/react-native'; +import { + AccessibilityInfo, + BackHandler as RNBackHandler, + Platform, +} from 'react-native'; + +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + jest, +} from '@jest/globals'; +import { act, fireEvent, userEvent } from '@testing-library/react-native'; +import color from 'color'; import * as Reanimated from 'react-native-reanimated'; import PaperProvider from '../../core/PaperProvider'; import { render, screen } from '../../test-utils'; +import { LightTheme } from '../../theme/schemes'; +import { tokens } from '../../theme/tokens'; import FAB from '../FAB'; import type { MenuItemProps } from '../FAB/Menu'; +import * as rippleUtils from '../TouchableRipple/utils'; + +type BackHandlerStatic = typeof RNBackHandler & { + mockPressBack(): void; + exitApp: jest.Mock<() => void>; +}; + +// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion +const BackHandler = RNBackHandler as BackHandlerStatic; jest.mock('react-native-reanimated', () => { const ReanimatedModule = jest.requireActual< @@ -16,7 +42,6 @@ jest.mock('react-native-reanimated', () => { __esModule: true, ...ReanimatedModule, default: ReanimatedModule.default, - withDelay: jest.fn(ReanimatedModule.withDelay), withSpring: jest.fn(ReanimatedModule.withSpring), }; }); @@ -87,7 +112,7 @@ it('keeps the trigger mounted across opening and closing without trigger.onPress expect(closed).not.toBeDisabled(); }); -it('keeps the opening springs and item stagger on with reduceMotion="off" whatever the device setting', async () => { +it('keeps the trigger morph spring on with reduceMotion="off" whatever the device setting', async () => { const { rerender } = await render( ); jest.mocked(Reanimated.withSpring).mockClear(); - jest.mocked(Reanimated.withDelay).mockClear(); await rerender( @@ -112,28 +136,13 @@ it('keeps the opening springs and item stagger on with reduceMotion="off" whatev ); - // Scale and alpha for each of the two items, then the trigger's morph + // The items fade and scale with CSS transitions, so the trigger's morph is + // the only spring left. expect( jest .mocked(Reanimated.withSpring) .mock.calls.map(([, config]) => config?.reduceMotion) - ).toEqual([ - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - ]); - expect( - jest - .mocked(Reanimated.withDelay) - .mock.calls.map(([, , reduceMotion]) => reduceMotion) - ).toEqual([ - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - Reanimated.ReduceMotion.Never, - ]); + ).toEqual([Reanimated.ReduceMotion.Never]); }); it('renders FAB.Menu with 6 items', async () => { @@ -219,6 +228,57 @@ it('renders FAB.Menu not expanded when trigger is not visible', async () => { expect(tree).toMatchSnapshot(); }); +it('leaves the press of an item to the ripple, which the settings can turn off', async () => { + await render( + + + + ); + const item = screen.getByTestId('item-0'); + const stateLayer = screen.getByTestId('item-0-state-layer'); + + expect(stateLayer).toHaveStyle({ opacity: 0 }); + + // The layer does show for a state the ripple has no part in. + await fireEvent(item, 'hoverIn'); + + expect(stateLayer).not.toHaveStyle({ opacity: 0 }); + + await fireEvent(item, 'hoverOut'); + await fireEvent(item, 'pressIn'); + + expect(stateLayer).toHaveStyle({ opacity: 0 }); +}); + +it('presses an item with a ripple in its content color', async () => { + const spy = jest.spyOn(rippleUtils, 'getTouchableRippleColors'); + + await render( + + ); + + expect(spy).toHaveBeenCalledWith( + expect.objectContaining({ + rippleColor: color(String(LightTheme.colors.onPrimaryContainer)) + .alpha(tokens.md.sys.state.opacity.pressed) + .rgb() + .string(), + }) + ); + + spy.mockRestore(); +}); + it('calls item onPress when menu item is pressed', async () => { const onItemPress = jest.fn(); await render( @@ -288,3 +348,509 @@ it('calls onDismiss when trigger is pressed while menu is open', async () => { await userEvent.press(screen.getByTestId('fab-shell')); expect(onDismiss).toHaveBeenCalledTimes(1); }); + +it('exposes the expanded state on the trigger', async () => { + const { rerender } = await render( + + ); + expect(screen.getByTestId('fab-shell')).toBeCollapsed(); + + await rerender( + + ); + expect(screen.getByTestId('fab-shell')).toBeExpanded(); +}); + +it('renders item labels with the title medium typescale', async () => { + await render( + + ); + expect(screen.getByText('Send email')).toHaveStyle({ fontSize: 16 }); +}); + +it('hides collapsed items from assistive technology and exposes expanded ones', async () => { + const { rerender } = await render( + + ); + expect(screen.queryByRole('button', { name: 'Send email' })).toBeNull(); + + await rerender( + + ); + expect(screen.getByRole('button', { name: 'Send email' })).toBeOnTheScreen(); +}); + +describe('dismissing the menu', () => { + beforeEach(() => { + BackHandler.exitApp.mockClear(); + }); + + it('calls onDismiss when the back button is pressed while open', async () => { + const onDismiss = jest.fn(); + await render( + + ); + + await act(() => { + BackHandler.mockPressBack(); + }); + + expect(onDismiss).toHaveBeenCalledTimes(1); + expect(BackHandler.exitApp).not.toHaveBeenCalled(); + }); + + it('leaves the back button to the screen while closed', async () => { + const onDismiss = jest.fn(); + await render( + + ); + + await act(() => { + BackHandler.mockPressBack(); + }); + + expect(onDismiss).not.toHaveBeenCalled(); + expect(BackHandler.exitApp).toHaveBeenCalledTimes(1); + }); + + it('stops taking the back button once it closes', async () => { + const onDismiss = jest.fn(); + const { rerender } = await render( + + ); + + await rerender( + + ); + await act(() => { + BackHandler.mockPressBack(); + }); + + expect(onDismiss).not.toHaveBeenCalled(); + }); + + it('calls onDismiss on the screen reader escape gesture while open', async () => { + const onDismiss = jest.fn(); + await render( + + ); + + await fireEvent(screen.getByTestId('menu'), 'accessibilityEscape'); + + expect(onDismiss).toHaveBeenCalledTimes(1); + }); + + it('ignores the screen reader escape gesture while closed', async () => { + const onDismiss = jest.fn(); + await render( + + ); + + await fireEvent(screen.getByTestId('menu'), 'accessibilityEscape'); + + expect(onDismiss).not.toHaveBeenCalled(); + }); + + describe('on the web', () => { + let platform: { restore(): void }; + let keyDownListeners = new Set<(event: unknown) => void>(); + // The arrow keys listen in the bubble phase, after the page's own handlers. + let arrowKeyListeners = new Set<(event: unknown) => void>(); + + beforeAll(() => { + platform = jest.replaceProperty(Platform, 'OS', 'web'); + + // There is no DOM under the React Native preset, so the test supplies + // what the menu and its overlay handling touch. + Object.defineProperty(global, 'HTMLElement', { + configurable: true, + value: class {}, + }); + Object.defineProperty(global, 'document', { + configurable: true, + value: { + activeElement: null, + addEventListener: ( + type: string, + listener: (event: unknown) => void, + capture?: boolean + ) => { + if (type === 'keydown' && capture === true) { + keyDownListeners.add(listener); + } else if (type === 'keydown') { + arrowKeyListeners.add(listener); + } + }, + removeEventListener: ( + _type: string, + listener: (event: unknown) => void + ) => { + keyDownListeners.delete(listener); + arrowKeyListeners.delete(listener); + }, + }, + }); + }); + + afterAll(() => { + platform.restore(); + delete (global as { document?: unknown }).document; + delete (global as { HTMLElement?: unknown }).HTMLElement; + }); + + beforeEach(() => { + keyDownListeners = new Set(); + arrowKeyListeners = new Set(); + }); + + const pressEscape = async () => { + const event = { + key: 'Escape', + isComposing: false, + defaultPrevented: false, + }; + + await act(() => { + keyDownListeners.forEach((listener) => listener(event)); + // The overlay waits until the key has been through the page. + jest.advanceTimersByTime(1); + }); + }; + + it('calls onDismiss when Escape is pressed while open', async () => { + const onDismiss = jest.fn(); + await render( + + ); + + await pressEscape(); + + expect(onDismiss).toHaveBeenCalledTimes(1); + }); + + it('presses a focused item with Space', async () => { + const onItemPress = jest.fn<(event?: unknown) => void>(); + const onDismiss = jest.fn(); + await render( + + ); + const item = screen.getByTestId('item-0'); + const space = { nativeEvent: { key: ' ' }, preventDefault: jest.fn() }; + + await fireEvent(item, 'keyDown', space); + + // Pressed on release, as with Enter. + expect(onItemPress).not.toHaveBeenCalled(); + + await fireEvent(item, 'keyUp', space); + + expect(space.preventDefault).toHaveBeenCalled(); + expect(onItemPress).toHaveBeenCalledTimes(1); + expect(onDismiss).toHaveBeenCalledTimes(1); + }); + + it('makes the items menu items when the trigger has a label', async () => { + await render( + + ); + + expect(screen.getByTestId('trigger')).toHaveProp('aria-haspopup', 'menu'); + expect(screen.getByTestId('item-0')).toHaveProp('role', 'menuitem'); + expect(screen.getByTestId('item-1')).toHaveProp('role', 'menuitem'); + }); + + it('leaves items as buttons when the trigger has no label', async () => { + await render( + + ); + + expect(screen.getByTestId('trigger')).not.toHaveProp('aria-haspopup'); + expect(screen.getByTestId('item-0')).toHaveProp('role', 'button'); + }); + + it('keeps one item in the tab order and moves it with focus', async () => { + await render( + + ); + + expect(screen.getByTestId('item-0')).toHaveProp('tabIndex', 0); + expect(screen.getByTestId('item-1')).toHaveProp('tabIndex', -1); + + await fireEvent(screen.getByTestId('item-1'), 'focus', { + nativeEvent: {}, + }); + + expect(screen.getByTestId('item-0')).toHaveProp('tabIndex', -1); + expect(screen.getByTestId('item-1')).toHaveProp('tabIndex', 0); + }); + + it('listens for the arrow keys only while open', async () => { + const menu = (expanded: boolean) => ( + + ); + const { rerender } = await render(menu(false)); + + expect(arrowKeyListeners.size).toBe(0); + + await rerender(menu(true)); + + expect(arrowKeyListeners.size).toBe(1); + + await rerender(menu(false)); + + expect(arrowKeyListeners.size).toBe(0); + }); + + it('leaves the arrow keys to the page when focus is outside the items', async () => { + await render( + + ); + const event = { + key: 'ArrowDown', + defaultPrevented: false, + preventDefault: jest.fn(), + }; + + arrowKeyListeners.forEach((listener) => listener(event)); + + expect(event.preventDefault).not.toHaveBeenCalled(); + }); + + it('ignores Escape while closed', async () => { + const onDismiss = jest.fn(); + await render( + + ); + + await pressEscape(); + + expect(onDismiss).not.toHaveBeenCalled(); + }); + }); +}); + +describe('hiding the trigger', () => { + const renderMenu = (visible: boolean, onDismiss = jest.fn()) => ( + + ); + + it('dismisses an open menu, so the parent does not keep it open', async () => { + const onDismiss = jest.fn(); + const { rerender } = await render(renderMenu(true, onDismiss)); + + expect(onDismiss).not.toHaveBeenCalled(); + + await rerender(renderMenu(false, onDismiss)); + + expect(onDismiss).toHaveBeenCalledTimes(1); + }); + + it('does not dismiss a menu that is closed', async () => { + const onDismiss = jest.fn(); + + await render( + + ); + + expect(onDismiss).not.toHaveBeenCalled(); + }); +}); + +describe('moving focus', () => { + const sendAccessibilityEvent = jest.mocked( + AccessibilityInfo.sendAccessibilityEvent + ); + + const renderMenu = (expanded: boolean) => ( + + ); + + // The screen reader is sent to an element, which the test can only tell + // apart by the `testID` it was given. + const focusedElement = (testID: string) => + expect.objectContaining({ + props: expect.objectContaining({ testID }), + }); + + beforeEach(() => { + sendAccessibilityEvent.mockClear(); + }); + + it('moves the screen reader to the first item once the items have faded in', async () => { + await render(renderMenu(true)); + + // The items stagger in, and transparent views are not in the + // accessibility tree. + expect(sendAccessibilityEvent).not.toHaveBeenCalled(); + + await act(() => { + jest.advanceTimersByTime(1000); + }); + + expect(sendAccessibilityEvent).toHaveBeenCalledTimes(1); + expect(sendAccessibilityEvent).toHaveBeenCalledWith( + focusedElement('item-0'), + 'focus' + ); + }); + + it('moves the screen reader into the menu each time it opens', async () => { + const { rerender } = await render(renderMenu(false)); + + await act(() => { + jest.advanceTimersByTime(1000); + }); + + expect(sendAccessibilityEvent).not.toHaveBeenCalled(); + + await rerender(renderMenu(true)); + await act(() => { + jest.advanceTimersByTime(1000); + }); + + expect(sendAccessibilityEvent).toHaveBeenCalledTimes(1); + }); + + it('sends the screen reader back to the trigger when it closes', async () => { + const { rerender } = await render(renderMenu(true)); + + await act(() => { + jest.advanceTimersByTime(1000); + }); + sendAccessibilityEvent.mockClear(); + + await rerender(renderMenu(false)); + await act(() => { + jest.advanceTimersByTime(1); + }); + + expect(sendAccessibilityEvent).toHaveBeenCalledTimes(1); + expect(sendAccessibilityEvent).toHaveBeenCalledWith( + focusedElement('trigger'), + 'focus' + ); + }); + + it('leaves the screen reader alone when it closes before it moved any in', async () => { + const { rerender } = await render(renderMenu(true)); + + await rerender(renderMenu(false)); + await act(() => { + jest.advanceTimersByTime(1000); + }); + + expect(sendAccessibilityEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/src/components/__tests__/FABUtils.test.tsx b/src/components/__tests__/FABUtils.test.tsx index d5bb8b87f0..95c5fab31b 100644 --- a/src/components/__tests__/FABUtils.test.tsx +++ b/src/components/__tests__/FABUtils.test.tsx @@ -1,7 +1,7 @@ import { describe, expect, it } from '@jest/globals'; import { DarkTheme, LightTheme } from '../../theme/schemes'; -import { getDimensions, resolveColors } from '../FAB/utils'; +import { getDimensions, getNextStopIndex, resolveColors } from '../FAB/utils'; describe('resolveColors', () => { it.each([false, true])( @@ -183,3 +183,31 @@ describe('getDimensions', () => { expect(dims.trailing).toBe(24); }); }); + +describe('getNextStopIndex', () => { + it('moves down and wraps from the last item to the first', () => { + expect(getNextStopIndex('ArrowDown', 0, 3)).toBe(1); + expect(getNextStopIndex('ArrowDown', 2, 3)).toBe(0); + }); + + it('moves up and wraps from the first item to the last', () => { + expect(getNextStopIndex('ArrowUp', 2, 3)).toBe(1); + expect(getNextStopIndex('ArrowUp', 0, 3)).toBe(2); + }); + + it('jumps to the first item with Home and to the last with End', () => { + expect(getNextStopIndex('Home', 2, 3)).toBe(0); + expect(getNextStopIndex('End', 0, 3)).toBe(2); + }); + + it('stays on the only item', () => { + expect(getNextStopIndex('ArrowDown', 0, 1)).toBe(0); + expect(getNextStopIndex('ArrowUp', 0, 1)).toBe(0); + expect(getNextStopIndex('End', 0, 1)).toBe(0); + }); + + it('leaves other keys alone', () => { + expect(getNextStopIndex('Tab', 0, 3)).toBeNull(); + expect(getNextStopIndex('a', 0, 3)).toBeNull(); + }); +}); diff --git a/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap b/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap index 000987e5bf..0ff04ba1f9 100644 --- a/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap +++ b/src/components/__tests__/__snapshots__/FABMenu.test.tsx.snap @@ -2,6 +2,7 @@ exports[`renders FAB.Menu closed 1`] = ` - - + + - + - Send email - + + + + Send email + + + + - - - - + - + - Set reminder - + + + + Set reminder + + + + - + @@ -531,6 +786,7 @@ exports[`renders FAB.Menu closed 1`] = ` { "opacity": 0, }, + {}, ] } /> @@ -540,7 +796,7 @@ exports[`renders FAB.Menu closed 1`] = ` "busy": undefined, "checked": undefined, "disabled": true, - "expanded": undefined, + "expanded": false, "selected": undefined, } } @@ -599,7 +855,6 @@ exports[`renders FAB.Menu closed 1`] = ` "top": 0, }, { - "opacity": 1, "transform": [ { "translateX": 16, @@ -612,35 +867,47 @@ exports[`renders FAB.Menu closed 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + + @@ -707,6 +985,7 @@ exports[`renders FAB.Menu closed 1`] = ` exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` - - + + - + - Send email - + + + + Send email + + + + - - - - + - + - Set reminder - + + + + Set reminder + + + + - + @@ -1237,6 +1770,7 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` { "opacity": 0, }, + {}, ] } /> @@ -1246,7 +1780,7 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` "busy": undefined, "checked": undefined, "disabled": true, - "expanded": undefined, + "expanded": false, "selected": undefined, } } @@ -1306,7 +1840,6 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` "top": 0, }, { - "opacity": 1, "transform": [ { "translateX": 16, @@ -1319,35 +1852,47 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + + @@ -1414,6 +1970,8 @@ exports[`renders FAB.Menu not expanded when trigger is not visible 1`] = ` exports[`renders FAB.Menu open 1`] = ` - - + + { + "borderBottomEndRadius": undefined, + "borderBottomLeftRadius": undefined, + "borderBottomRightRadius": undefined, + "borderBottomStartRadius": undefined, + "borderCurve": "continuous", + "borderEndEndRadius": undefined, + "borderEndStartRadius": undefined, + "borderRadius": 9999, + "borderStartEndRadius": undefined, + "borderStartStartRadius": undefined, + "borderTopEndRadius": undefined, + "borderTopLeftRadius": undefined, + "borderTopRightRadius": undefined, + "borderTopStartRadius": undefined, + }, + { + "shadowColor": "rgba(0, 0, 0, 1)", + "shadowOffset": { + "height": 0, + "width": 0, + }, + "shadowOpacity": 0, + "shadowRadius": 0, + }, + ] + } + > + - + - Send email - + + + + Send email + + + + - - - - + - + - Set reminder - + + + + Set reminder + + + + - + @@ -1943,6 +2755,7 @@ exports[`renders FAB.Menu open 1`] = ` { "opacity": 1, }, + {}, ] } /> @@ -1952,7 +2765,7 @@ exports[`renders FAB.Menu open 1`] = ` "busy": undefined, "checked": undefined, "disabled": false, - "expanded": undefined, + "expanded": true, "selected": undefined, } } @@ -2011,7 +2824,6 @@ exports[`renders FAB.Menu open 1`] = ` "top": 0, }, { - "opacity": 0, "transform": [ { "translateX": 16, @@ -2024,35 +2836,47 @@ exports[`renders FAB.Menu open 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + + @@ -2119,6 +2954,8 @@ exports[`renders FAB.Menu open 1`] = ` exports[`renders FAB.Menu with 6 items 1`] = ` - - + + - + - Item 1 - + + + + Item 1 + + + + - - - - + - + - Item 2 - + + + + Item 2 + + + + - - - - + - + - Item 3 - + + + + Item 3 + + + + - - - - + - + - Item 4 - + + + + Item 4 + + + + - - - - + - + - Item 5 - + + + + Item 5 + + + + - - - - + - + - Item 6 - + + + + Item 6 + + + + - + @@ -3256,6 +4787,7 @@ exports[`renders FAB.Menu with 6 items 1`] = ` { "opacity": 1, }, + {}, ] } /> @@ -3265,7 +4797,7 @@ exports[`renders FAB.Menu with 6 items 1`] = ` "busy": undefined, "checked": undefined, "disabled": false, - "expanded": undefined, + "expanded": true, "selected": undefined, } } @@ -3324,7 +4856,6 @@ exports[`renders FAB.Menu with 6 items 1`] = ` "top": 0, }, { - "opacity": 0, "transform": [ { "translateX": 16, @@ -3337,35 +4868,47 @@ exports[`renders FAB.Menu with 6 items 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + + @@ -3432,6 +4986,8 @@ exports[`renders FAB.Menu with 6 items 1`] = ` exports[`renders FAB.Menu with center alignment 1`] = ` - - + + - + - Send email - + + + + Send email + + + + - - - - + - + - Set reminder - + + + + Set reminder + + + + - + @@ -3962,6 +5772,7 @@ exports[`renders FAB.Menu with center alignment 1`] = ` { "opacity": 1, }, + {}, ] } /> @@ -3971,7 +5782,7 @@ exports[`renders FAB.Menu with center alignment 1`] = ` "busy": undefined, "checked": undefined, "disabled": false, - "expanded": undefined, + "expanded": true, "selected": undefined, } } @@ -4030,7 +5841,6 @@ exports[`renders FAB.Menu with center alignment 1`] = ` "top": 0, }, { - "opacity": 0, "transform": [ { "translateX": 16, @@ -4043,35 +5853,47 @@ exports[`renders FAB.Menu with center alignment 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + + @@ -4138,6 +5971,8 @@ exports[`renders FAB.Menu with center alignment 1`] = ` exports[`renders FAB.Menu with items having icons 1`] = ` - - + - - email - + /> - + - Send email - + + + email + + + + Send email + + + + - - - - - - bell - + /> - + - Set reminder - + + + bell + + + + Set reminder + + + + - + @@ -4727,6 +6814,7 @@ exports[`renders FAB.Menu with items having icons 1`] = ` { "opacity": 1, }, + {}, ] } /> @@ -4736,7 +6824,7 @@ exports[`renders FAB.Menu with items having icons 1`] = ` "busy": undefined, "checked": undefined, "disabled": false, - "expanded": undefined, + "expanded": true, "selected": undefined, } } @@ -4795,7 +6883,6 @@ exports[`renders FAB.Menu with items having icons 1`] = ` "top": 0, }, { - "opacity": 0, "transform": [ { "translateX": 16, @@ -4808,35 +6895,47 @@ exports[`renders FAB.Menu with items having icons 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + + @@ -4903,6 +7013,8 @@ exports[`renders FAB.Menu with items having icons 1`] = ` exports[`renders FAB.Menu with start alignment 1`] = ` - - + + - + - Send email - + + + + Send email + + + + - - - - + - + - Set reminder - + + + + Set reminder + + + + - + @@ -5432,6 +7798,7 @@ exports[`renders FAB.Menu with start alignment 1`] = ` { "opacity": 1, }, + {}, ] } /> @@ -5441,7 +7808,7 @@ exports[`renders FAB.Menu with start alignment 1`] = ` "busy": undefined, "checked": undefined, "disabled": false, - "expanded": undefined, + "expanded": true, "selected": undefined, } } @@ -5500,7 +7867,6 @@ exports[`renders FAB.Menu with start alignment 1`] = ` "top": 0, }, { - "opacity": 0, "transform": [ { "translateX": 16, @@ -5513,35 +7879,47 @@ exports[`renders FAB.Menu with start alignment 1`] = ` ] } > - - plus - + + plus + + - - close - + + close + +