diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md
index 155a18f11d..e769af1633 100644
--- a/docs/6.x/docs/guides/migration.md
+++ b/docs/6.x/docs/guides/migration.md
@@ -622,6 +622,19 @@ Showing and hiding use the `standardDecelerate` and `standardAccelerate` easing
### Tooltip
+The trigger is now a render function. Spread the props it receives onto the trigger element, so the tooltip can attach its handlers and accessibility props without cloning the element:
+
+```diff
+-
+-
+-
++
++ {(props) => (
++
++ )}
++
+```
+
`Tooltip` no longer reads positioning styles such as `position: 'absolute'` from the `style` of the wrapped element. Apply them to a parent `View` wrapping the `Tooltip` instead.
e.g.:
@@ -632,11 +645,52 @@ e.g.:
-
+
+
-+
++ {(props) => }
+
+
```
+The tooltip now follows the Material Design 3 plain tooltip:
+
+- It uses the `inverseSurface` container and `inverseOnSurface` text in the `bodySmall` type style, instead of `onSurface` and `surface` in `labelLarge`.
+- It has 8dp horizontal padding, a 24dp minimum height and a 40dp minimum width, and long titles wrap onto up to three lines at a 320dp width, instead of being cut to one line.
+- It fades in and out, and appears 4dp away from the trigger, below it or above it when there's no room. It keeps at least 8dp from the left and right screen edges, and from the top one when it's too tall for either side.
+- In right-to-left layouts it is placed from the trailing edge.
+
+On web, the tooltip also opens when the trigger gets keyboard focus, and the trigger is described by the tooltip through `aria-describedby`. On iOS and Android, the trigger gets the title as its `accessibilityHint`. For a trigger without a visible label, such as an icon button, set `titleAsAriaLabel` so the title becomes its `aria-label` on every platform instead.
+
+`Tooltip.Rich` is new. It shows an optional title, supporting text and action buttons, and uses the same render function for its trigger. Pressing the trigger toggles the tooltip, so the trigger's own `onPress` replaces it. Use a trigger without an `onPress`, or call both:
+
+```tsx
+ (
+
+ )}
+>
+ {(props) => (
+ {
+ props.onPress?.();
+ handleInfoPress();
+ }}
+ />
+ )}
+
+```
+
+While a rich tooltip is open on iOS and Android, a press on another rich tooltip's trigger only switches the tooltips, so that trigger's own `onPress` doesn't run.
+
+On iOS and Android, its trigger gets the title and the text content as its `accessibilityHint`. Give an icon-only trigger its own `aria-label`.
+
+A rich tooltip closes on a press outside it, on a press on an action that calls `dismiss`, on another press on the trigger, when the screen size changes and on the VoiceOver escape gesture on iOS. The Android back button isn't taken by the tooltip, so it still goes back. On web it opens on hover and on keyboard focus, and closes on Escape and when the pointer or the focus leaves both the trigger and the tooltip. The down arrow key on the trigger moves focus into the actions, and focus that was in the tooltip goes back to the trigger when it closes.
+
### Surface
- The `elevation` prop no longer accepts a React Native `Animated.Value`. Any `elevation` changes are animated automatically.
diff --git a/docs/component-docs.config.ts b/docs/component-docs.config.ts
index 73ebb3b3b2..1553c7fb5d 100644
--- a/docs/component-docs.config.ts
+++ b/docs/component-docs.config.ts
@@ -146,6 +146,10 @@ const pages = {
},
Tooltip: {
Tooltip: 'Tooltip/Tooltip',
+ TooltipRich: {
+ source: 'Tooltip/RichTooltip',
+ title: 'Tooltip.Rich',
+ },
},
TouchableRipple: {
TouchableRipple: 'TouchableRipple/TouchableRipple',
diff --git a/docs/src/data/themeColors.ts b/docs/src/data/themeColors.ts
index b04ea8c7e7..c2b68516c3 100644
--- a/docs/src/data/themeColors.ts
+++ b/docs/src/data/themeColors.ts
@@ -371,8 +371,15 @@ export const themeColors = {
},
Tooltip: {
'-': {
- backgroundColor: 'theme.colors.onSurface',
- textColor: 'theme.colors.surface',
+ backgroundColor: 'theme.colors.inverseSurface',
+ textColor: 'theme.colors.inverseOnSurface',
+ },
+ },
+ 'Tooltip.Rich': {
+ '-': {
+ backgroundColor: 'theme.colors.surfaceContainer',
+ 'title textColor': 'theme.colors.onSurfaceVariant',
+ textColor: 'theme.colors.onSurfaceVariant',
},
},
};
diff --git a/example/src/Examples/TooltipExample.tsx b/example/src/Examples/TooltipExample.tsx
index aebff5d51c..917f2e4646 100644
--- a/example/src/Examples/TooltipExample.tsx
+++ b/example/src/Examples/TooltipExample.tsx
@@ -1,11 +1,12 @@
import * as React from 'react';
-import { Platform, StyleSheet, View, Image } from 'react-native';
+import { Linking, Platform, StyleSheet, View, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import {
Appbar,
Avatar,
Banner,
+ Button,
Chip,
FAB,
IconButton,
@@ -43,18 +44,29 @@ const TooltipExample = () => {
navigation.setOptions({
header: () => (
-
- navigation.goBack()} />
+
+ {(props) => (
+ navigation.goBack()}
+ />
+ )}
-
- {}} />
+
+ {(props) => (
+ {}} />
+ )}
-
- {}} />
+
+ {(props) => (
+ {}} />
+ )}
-
- {}} />
+
+ {(props) => (
+ {}} />
+ )}
),
@@ -78,87 +90,161 @@ const TooltipExample = () => {
- {}}
- />
+ {(props) => (
+ {}}
+ />
+ )}
))}
-
- setTextAlign('left')}
- />
+
+ {(props) => (
+ setTextAlign('left')}
+ />
+ )}
-
- setTextAlign('center')}
- />
+
+ {(props) => (
+ setTextAlign('center')}
+ />
+ )}
-
- setTextAlign('right')}
- />
+
+ {(props) => (
+ setTextAlign('right')}
+ />
+ )}
-
+ {(props) => }
-
- }
- >
- John Doe
-
+ {(props) => (
+
+ }
+ >
+ John Doe
+
+ )}
-
- (
-
- )}
- />
-
+ {(props) => (
+
+ (
+
+ )}
+ />
+
+ )}
+
+
+ (
+ <>
+
+
+ >
+ )}
+ >
+ {(props) => (
+
+ )}
+
+
+ {(props) => (
+
+ )}
+
+ (
+
+ )}
+ >
+ {(props) => (
+
+ )}
+
+
+
-
- {}} />
+
+ {(props) => {}} />}
>
diff --git a/src/components/FAB/FAB.tsx b/src/components/FAB/FAB.tsx
index 961dfdd16b..dbb8d23b0a 100644
--- a/src/components/FAB/FAB.tsx
+++ b/src/components/FAB/FAB.tsx
@@ -3,8 +3,10 @@ import { View } from 'react-native';
import type {
ColorValue,
GestureResponderEvent,
+ NativeSyntheticEvent,
PressableAndroidRippleConfig,
StyleProp,
+ TargetedEvent,
ViewStyle,
} from 'react-native';
@@ -57,6 +59,14 @@ export type Props = {
* The number of milliseconds a user must touch the element before executing `onLongPress`.
*/
delayLongPress?: number;
+ /**
+ * Function to execute when the element receives focus.
+ */
+ onFocus?: (e: NativeSyntheticEvent) => void;
+ /**
+ * Function to execute when the element loses focus.
+ */
+ onBlur?: (e: NativeSyntheticEvent) => void;
/**
* Accessibility label. Falls back to nothing if unset.
*/
@@ -78,6 +88,10 @@ export type Props = {
* Indicates whether the element's controlled content is expanded.
*/
'aria-expanded'?: boolean;
+ /**
+ * Id of the element that describes this one, e.g. a tooltip.
+ */
+ 'aria-describedby'?: string;
/**
* Type of background drawable to display the feedback (Android).
* https://reactnative.dev/docs/pressable#rippleconfig
@@ -137,6 +151,8 @@ const FAB = ({
onLongPress,
onPressOut,
delayLongPress,
+ onFocus,
+ onBlur,
containerColor,
contentColor,
'aria-label': ariaLabel,
@@ -144,6 +160,7 @@ const FAB = ({
'aria-selected': ariaSelected,
'aria-busy': ariaBusy,
'aria-expanded': ariaExpanded,
+ 'aria-describedby': ariaDescribedBy,
background,
style,
testID,
@@ -160,6 +177,8 @@ const FAB = ({
onLongPress={onLongPress}
onPressOut={onPressOut}
delayLongPress={delayLongPress}
+ onFocus={onFocus}
+ onBlur={onBlur}
containerColor={containerColor}
contentColor={contentColor}
aria-label={ariaLabel}
@@ -167,6 +186,7 @@ const FAB = ({
aria-selected={ariaSelected}
aria-busy={ariaBusy}
aria-expanded={ariaExpanded}
+ aria-describedby={ariaDescribedBy}
background={background}
style={style}
testID={testID}
diff --git a/src/components/FAB/Shell.tsx b/src/components/FAB/Shell.tsx
index 748a3a5dcc..6a1fc8d710 100644
--- a/src/components/FAB/Shell.tsx
+++ b/src/components/FAB/Shell.tsx
@@ -3,8 +3,10 @@ import { Platform, StyleSheet, View } from 'react-native';
import type {
ColorValue,
GestureResponderEvent,
+ NativeSyntheticEvent,
PressableAndroidRippleConfig,
StyleProp,
+ TargetedEvent,
ViewStyle,
} from 'react-native';
@@ -95,6 +97,14 @@ export type ShellProps = {
* The number of milliseconds a user must touch the element before executing `onLongPress`.
*/
delayLongPress?: number;
+ /**
+ * Function to execute when the element receives focus.
+ */
+ onFocus?: (e: NativeSyntheticEvent) => void;
+ /**
+ * Function to execute when the element loses focus.
+ */
+ onBlur?: (e: NativeSyntheticEvent) => void;
/**
* Whether the shell can't be pressed. Turns a control off without removing
* `onPress`, which would render another element and remount the content.
@@ -121,6 +131,10 @@ export type ShellProps = {
* Indicates whether the element's controlled content is expanded.
*/
'aria-expanded'?: boolean;
+ /**
+ * Id of the element that describes this one, e.g. a tooltip.
+ */
+ 'aria-describedby'?: string;
/**
* Indicates that the element opens a popup, such as a menu.
*/
@@ -216,12 +230,15 @@ const Shell = ({
onLongPress,
onPressOut,
delayLongPress,
+ onFocus,
+ onBlur,
disabled,
'aria-label': ariaLabel = label,
'aria-checked': ariaChecked,
'aria-selected': ariaSelected,
'aria-busy': ariaBusy,
'aria-expanded': ariaExpanded,
+ 'aria-describedby': ariaDescribedBy,
'aria-haspopup': ariaHasPopup,
labelMaxFontSizeMultiplier,
labelAnimatedStyle,
@@ -501,16 +518,25 @@ const Shell = ({
previous instanceof HTMLElement ? previous : null;
}
focusTarget.onFocus?.(event);
+ onFocus?.(event);
}
: undefined
}
- onBlur={focusTarget.onBlur}
+ onBlur={
+ onBlur
+ ? (event) => {
+ focusTarget.onBlur?.();
+ onBlur(event);
+ }
+ : focusTarget.onBlur
+ }
aria-label={ariaLabel}
role={isWebImage ? 'img' : 'button'}
aria-checked={ariaChecked}
aria-selected={ariaSelected}
aria-busy={ariaBusy}
aria-expanded={ariaExpanded}
+ aria-describedby={ariaDescribedBy}
aria-haspopup={ariaHasPopup}
testID={testID}
style={[children ? styles.fill : null, ...focusTarget.style]}
diff --git a/src/components/Tooltip/RichTooltip.tsx b/src/components/Tooltip/RichTooltip.tsx
new file mode 100644
index 0000000000..37714d3a8e
--- /dev/null
+++ b/src/components/Tooltip/RichTooltip.tsx
@@ -0,0 +1,471 @@
+import * as React from 'react';
+import { View, StyleSheet, Platform, Pressable } from 'react-native';
+import type {
+ GestureResponderEvent,
+ NativeSyntheticEvent,
+ ViewStyle,
+} from 'react-native';
+
+import Reanimated from 'react-native-reanimated';
+import useLatestCallback from 'use-latest-callback';
+
+import {
+ useHideOnDimensionsChange,
+ useTimeout,
+ useTooltipFade,
+ useTriggerHover,
+} from './hooks';
+import type { TooltipHostElement } from './hooks';
+import {
+ forwardPressToTriggerAt,
+ refreshRichTriggers,
+ registerRichTrigger,
+ releaseSingletonSlot,
+ subscribeToTriggerRefresh,
+ takeSingletonSlot,
+ unregisterRichTrigger,
+} from './registry';
+import { Tokens } from './tokens';
+import { useRichTooltipFocus } from './useRichTooltipFocus';
+import { getActiveElement, getTooltipPosition } from './utils';
+import { useLocale } from '../../core/locale';
+import { useInternalTheme } from '../../core/theming';
+import type { ThemeProp } from '../../theme/types';
+import Portal from '../Portal/Portal';
+import Surface from '../Surface';
+import Text from '../Typography/Text';
+
+const AnimatedSurface = Reanimated.createAnimatedComponent(Surface);
+
+/**
+ * Props passed to the `children` render function. Spread them onto the trigger
+ * element (and merge with your own handlers when you have them).
+ */
+export type TooltipRichTriggerProps = {
+ onPress?: () => void;
+ onFocus?: () => void;
+ onBlur?: () => void;
+ onKeyDown?: (event: NativeSyntheticEvent<{ key: string }>) => void;
+ accessibilityHint?: string;
+ 'aria-describedby'?: string;
+ 'aria-haspopup'?: 'dialog';
+ 'aria-expanded'?: boolean;
+ 'aria-controls'?: string;
+};
+
+export type Props = {
+ /**
+ * Render function returning the trigger element. The provided props wire the
+ * tooltip's show/hide behavior and must be spread onto the returned element:
+ *
+ * ```js
+ *
+ * {(props) => }
+ *
+ * ```
+ */
+ children: (props: TooltipRichTriggerProps) => React.ReactElement;
+ /**
+ * Optional subhead shown above the content.
+ */
+ title?: string;
+ /**
+ * Supporting body text. A string is rendered with the `bodyMedium` type
+ * style; pass an element to compose inline links or custom content.
+ */
+ content: string | React.ReactElement;
+ /**
+ * Render function for the action buttons (and/or links) shown in a row below
+ * the content. Call `dismiss` from an action to hide the tooltip:
+ *
+ * ```js
+ * actions={({ dismiss }) => (
+ *
+ * )}
+ * ```
+ */
+ actions?: (props: { dismiss: () => void }) => React.ReactNode;
+ /**
+ * Called whenever the tooltip closes, whichever way it was dismissed: an
+ * outside tap, re-pressing the trigger, an action calling `dismiss`, the
+ * pointer or focus leaving (web), Escape (web), the VoiceOver escape gesture
+ * (iOS), the screen size changing, or another tooltip, plain or rich, taking
+ * its place. It is not called when the component unmounts with the tooltip
+ * still open.
+ */
+ onDismiss?: () => void;
+ /**
+ * The number of milliseconds a user must hover the element before showing
+ * the tooltip (web only).
+ */
+ enterTouchDelay?: number;
+ /**
+ * The number of milliseconds after the pointer or the focus leaves both the
+ * trigger and the tooltip before hiding it (web only).
+ */
+ leaveTouchDelay?: number;
+ /**
+ * Specifies the largest possible scale the title font can reach.
+ */
+ titleMaxFontSizeMultiplier?: number;
+ /**
+ * Specifies the largest possible scale the content font can reach.
+ */
+ contentMaxFontSizeMultiplier?: number;
+ /**
+ * TestID used for testing purposes. Applied to the tooltip.
+ */
+ testID?: string;
+ /**
+ * TestID used for testing purposes. Applied to the backdrop that closes the
+ * tooltip on a press outside it (iOS and Android).
+ */
+ overlayTestID?: string;
+ /**
+ * @optional
+ */
+ theme?: ThemeProp;
+};
+
+/**
+ * Rich tooltips display informative text along with an optional subhead and
+ * action buttons. Unlike plain tooltips they are persistent and interactive:
+ * tap the element to toggle the tooltip, then tap outside or an action to
+ * dismiss it.
+ *
+ * On web they open on hover and on keyboard focus, and Escape closes them.
+ * The down arrow key on the trigger moves focus into the actions, and focus
+ * that was in the tooltip goes back to the trigger when Escape or an action
+ * closes it.
+ *
+ * ## Usage
+ * ```js
+ * import * as React from 'react';
+ * import { Button, IconButton, Tooltip } from 'react-native-paper';
+ *
+ * const MyComponent = () => (
+ * (
+ *
+ * )}
+ * >
+ * {(props) => }
+ *
+ * );
+ *
+ * export default MyComponent;
+ * ```
+ */
+const RichTooltip = ({
+ children,
+ title,
+ content,
+ actions,
+ onDismiss,
+ enterTouchDelay = 100,
+ leaveTouchDelay = 1500,
+ titleMaxFontSizeMultiplier,
+ contentMaxFontSizeMultiplier,
+ testID,
+ overlayTestID,
+ theme: themeOverrides,
+}: Props) => {
+ const theme = useInternalTheme(themeOverrides);
+ const { direction } = useLocale();
+ const [visible, setVisible] = React.useState(false);
+ const {
+ rendered,
+ measurement,
+ fadeStyle,
+ fadeDuration,
+ onLayout,
+ childrenWrapperRef,
+ } = useTooltipFade(theme, visible);
+ const tooltipId = React.useId();
+ const titleId = React.useId();
+ const contentId = React.useId();
+ const tooltipRef = React.useRef(null);
+ const wasVisibleRef = React.useRef(visible);
+ const showTimer = useTimeout();
+ const hideTimer = useTimeout();
+ const hasActions = actions != null;
+
+ const dismissFromSlot = React.useCallback(() => setVisible(false), []);
+
+ const show = React.useCallback(() => {
+ showTimer.clear();
+ hideTimer.clear();
+ takeSingletonSlot(dismissFromSlot);
+ refreshRichTriggers();
+ setVisible(true);
+ }, [showTimer, hideTimer, dismissFromSlot]);
+
+ React.useEffect(() => {
+ if (!visible) {
+ return undefined;
+ }
+ return () => releaseSingletonSlot(dismissFromSlot);
+ }, [visible, dismissFromSlot]);
+
+ const hide = React.useCallback(() => {
+ showTimer.clear();
+ hideTimer.clear();
+ setVisible(false);
+ }, [showTimer, hideTimer]);
+
+ const scheduleHide = React.useCallback(() => {
+ showTimer.clear();
+ hideTimer.schedule(() => {
+ // Web: hiding would drop focus that is inside the tooltip, so it stays
+ // open until that focus leaves or Escape closes it
+ const focused = getActiveElement();
+ if (focused != null && tooltipRef.current?.contains?.(focused)) {
+ return;
+ }
+ setVisible(false);
+ }, leaveTouchDelay);
+ }, [showTimer, hideTimer, leaveTouchDelay]);
+
+ useHideOnDimensionsChange(hide);
+
+ // Report every dismissal from one place rather than calling the prop from
+ // each path that hides the tooltip, so a future close path can't miss it
+ React.useEffect(() => {
+ if (wasVisibleRef.current && !visible) {
+ onDismiss?.();
+ }
+ wasVisibleRef.current = visible;
+ }, [visible, onDismiss]);
+
+ const { hoveringRef, consumeTouchFocus, wrapperProps } = useTriggerHover({
+ wrapperRef: childrenWrapperRef,
+ onEnter: (isTouch) => {
+ // a tap also fires a press, which toggles the tooltip
+ if (isTouch) {
+ return;
+ }
+ hideTimer.clear();
+ showTimer.schedule(show, enterTouchDelay);
+ },
+ onLeave: scheduleHide,
+ });
+
+ const {
+ triggerProps: focusTriggerProps,
+ onTooltipKeyDown,
+ hideAndRestoreFocus,
+ isOpenedByFocus,
+ } = useRichTooltipFocus({
+ visible,
+ hasActions,
+ tooltipRef,
+ triggerRef: childrenWrapperRef,
+ show,
+ hide,
+ scheduleHide,
+ consumeTouchFocus,
+ });
+
+ // On web a press on the hovered or keyboard-focused trigger keeps the
+ // tooltip open, as the hover or the focus already opened it.
+ const handlePress = useLatestCallback(() => {
+ if (
+ Platform.OS === 'web' &&
+ visible &&
+ (hoveringRef.current || isOpenedByFocus())
+ ) {
+ showTimer.clear();
+ hideTimer.clear();
+ } else if (visible) {
+ hide();
+ } else {
+ show();
+ }
+ });
+
+ const description =
+ typeof content === 'string'
+ ? [title, content].filter(Boolean).join('. ')
+ : title;
+
+ // A tooltip can't hold focusable content, so with actions it's a non-modal
+ // dialog (WAI-ARIA APG tooltip pattern). Either way the trigger is described
+ // by the title and content only, without the action labels.
+ const triggerProps: TooltipRichTriggerProps =
+ Platform.OS === 'web'
+ ? {
+ onPress: handlePress,
+ ...focusTriggerProps,
+ 'aria-describedby': [title ? titleId : null, contentId]
+ .filter(Boolean)
+ .join(' '),
+ ...(hasActions && {
+ 'aria-haspopup': 'dialog',
+ 'aria-expanded': visible,
+ 'aria-controls': tooltipId,
+ }),
+ }
+ : { onPress: handlePress, accessibilityHint: description };
+
+ // Web only: keep the tooltip open while the pointer or the focus travels from
+ // the trigger into the tooltip, and re-schedule the hide once it leaves. A
+ // plain `View` carries these — a `Pressable` would be focusable and merge its
+ // children into one accessibility element on iOS, so the title, the content
+ // and the actions would stop being reachable on their own. React Native Web's
+ // `View` ignores `onHoverIn`/`onHoverOut`, so pointer events are used instead.
+ const tooltipInteractionProps =
+ Platform.OS === 'web'
+ ? {
+ onPointerEnter: hideTimer.clear,
+ onPointerLeave: scheduleHide,
+ onFocus: hideTimer.clear,
+ onBlur: scheduleHide,
+ onKeyDown: onTooltipKeyDown,
+ }
+ : {};
+
+ const [triggerId] = React.useState(() => Symbol());
+
+ const updateTriggerRegistration = React.useCallback(() => {
+ if (Platform.OS === 'web') return;
+ childrenWrapperRef.current?.measure(
+ (_x, _y, width, height, pageX, pageY) => {
+ registerRichTrigger(triggerId, {
+ rect: { x: pageX, y: pageY, width, height },
+ onPress: handlePress,
+ });
+ }
+ );
+ }, [childrenWrapperRef, triggerId, handlePress]);
+
+ React.useEffect(() => {
+ return () => {
+ unregisterRichTrigger(triggerId);
+ };
+ }, [triggerId]);
+
+ React.useEffect(() => {
+ return subscribeToTriggerRefresh(updateTriggerRegistration);
+ }, [updateTriggerRegistration]);
+
+ const handleBackdropPress = ({
+ nativeEvent: { pageX, pageY },
+ }: GestureResponderEvent) => {
+ if (!forwardPressToTriggerAt(pageX, pageY)) {
+ hide();
+ }
+ };
+
+ return (
+ <>
+ {rendered && (
+
+
+
+
+
+ {title ? (
+
+ {title}
+
+ ) : null}
+ {typeof content === 'string' ? (
+
+ {content}
+
+ ) : (
+ {content}
+ )}
+ {actions ? (
+
+ {actions({ dismiss: hideAndRestoreFocus })}
+
+ ) : null}
+
+
+
+
+ )}
+
+ {children(triggerProps)}
+
+ >
+ );
+};
+
+RichTooltip.displayName = 'Tooltip.Rich';
+
+const styles = StyleSheet.create({
+ container: {
+ alignSelf: 'flex-start',
+ maxWidth: Tokens.rich.maxWidth,
+ },
+ surface: {
+ paddingHorizontal: Tokens.rich.paddingHorizontal,
+ paddingTop: Tokens.rich.paddingTop,
+ paddingBottom: Tokens.rich.paddingBottom,
+ rowGap: Tokens.rich.gap,
+ },
+ actions: {
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ },
+ // RN types `cursor` as 'auto' | 'pointer', but RN Web accepts any CSS cursor
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
+ pressContainer: {
+ alignSelf: 'flex-start',
+ ...(Platform.OS === 'web' && { cursor: 'default' }),
+ } as ViewStyle,
+});
+
+export default RichTooltip;
diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx
index cfdc52bf96..279ff2d046 100644
--- a/src/components/Tooltip/Tooltip.tsx
+++ b/src/components/Tooltip/Tooltip.tsx
@@ -1,28 +1,52 @@
import * as React from 'react';
-import {
- Dimensions,
- View,
- StyleSheet,
- Platform,
- Pressable,
-} from 'react-native';
-import type { LayoutChangeEvent, ViewStyle } from 'react-native';
+import { Platform, Pressable, StyleSheet, View } from 'react-native';
+import type { ViewStyle } from 'react-native';
+
+import Animated from 'react-native-reanimated';
+import {
+ useHideOnDimensionsChange,
+ useTimeout,
+ useTooltipFade,
+ useTriggerHover,
+} from './hooks';
+import { releaseSingletonSlot, takeSingletonSlot } from './registry';
+import { Tokens } from './tokens';
import { getTooltipPosition } from './utils';
-import type { Measurement, TooltipChildProps } from './utils';
+import { useLocale } from '../../core/locale';
import { useInternalTheme } from '../../core/theming';
import type { ThemeProp } from '../../theme/types';
-import { addEventListener } from '../../utils/addEventListener';
+import { useOverlayDismiss } from '../../utils/useOverlayDismiss';
import Portal from '../Portal/Portal';
import Text from '../Typography/Text';
+/**
+ * Props passed to the `children` render function. Spread them onto the trigger
+ * element (and merge with your own handlers when you have them).
+ */
+export type TooltipTriggerProps = {
+ onLongPress?: () => void;
+ onPressOut?: () => void;
+ delayLongPress?: number;
+ onFocus?: () => void;
+ onBlur?: () => void;
+ 'aria-label'?: string;
+ 'aria-describedby'?: string;
+ accessibilityHint?: string;
+};
+
export type Props = {
/**
- * Tooltip reference element.
+ * Render function returning the trigger element. The provided props wire the
+ * tooltip's show/hide behavior and must be spread onto the returned element:
*
- * Positioning styles such as `position: 'absolute'` should be applied to a parent `View` wrapping the `Tooltip` instead of the element.
+ * ```js
+ *
+ * {(props) => {}} />}
+ *
+ * ```
*/
- children: React.ReactElement;
+ children: (props: TooltipTriggerProps) => React.ReactElement;
/**
* The number of milliseconds a user must touch the element before showing the tooltip.
*/
@@ -35,10 +59,20 @@ export type Props = {
* Tooltip title
*/
title: string;
+ /**
+ * Uses the title as the trigger's accessible name instead of its description.
+ * Set it for a trigger without a visible label, such as an icon button. Leave
+ * it off when the trigger has its own name, or the title replaces it.
+ */
+ titleAsAriaLabel?: boolean;
/**
* Specifies the largest possible scale a title font can reach.
*/
titleMaxFontSizeMultiplier?: number;
+ /**
+ * TestID used for testing purposes. Applied to the tooltip.
+ */
+ testID?: string;
/**
* @optional
*/
@@ -50,14 +84,16 @@ export type Props = {
*
* Plain tooltips, when activated, display a text label identifying an element, such as a description of its function. Tooltips should include only short, descriptive text and avoid restating visible UI text.
*
+ * For tooltips with a title, supporting text and action buttons, see `Tooltip.Rich`.
+ *
* ## Usage
* ```js
* import * as React from 'react';
* import { IconButton, Tooltip } from 'react-native-paper';
*
* const MyComponent = () => (
- *
- * {}} />
+ *
+ * {(props) => {}} />}
*
* );
*
@@ -69,178 +105,150 @@ const Tooltip = ({
enterTouchDelay = 500,
leaveTouchDelay = 1500,
title,
+ titleAsAriaLabel = false,
theme: themeOverrides,
titleMaxFontSizeMultiplier,
- ...rest
+ testID,
}: Props) => {
const theme = useInternalTheme(themeOverrides);
+ const { direction } = useLocale();
const [visible, setVisible] = React.useState(false);
+ const { rendered, measurement, fadeStyle, onLayout, childrenWrapperRef } =
+ useTooltipFade(theme, visible);
+ const tooltipId = React.useId();
+ const showTimer = useTimeout();
+ const hideTimer = useTimeout();
- const [measurement, setMeasurement] = React.useState({
- children: {},
- tooltip: {},
- measured: false,
- });
- const showTooltipTimer = React.useRef[]>([]);
- const hideTooltipTimer = React.useRef[]>([]);
-
- const childrenWrapperRef =
- React.useRef>(null);
- const touched = React.useRef(false);
-
- const isValidChild = React.useMemo(
- () => React.isValidElement(children),
- [children]
- );
-
- React.useEffect(() => {
- return () => {
- if (showTooltipTimer.current.length) {
- showTooltipTimer.current.forEach((t) => clearTimeout(t));
- showTooltipTimer.current = [];
- }
+ const hide = React.useCallback(() => setVisible(false), []);
- if (hideTooltipTimer.current.length) {
- hideTooltipTimer.current.forEach((t) => clearTimeout(t));
- hideTooltipTimer.current = [];
- }
- };
- }, []);
+ useHideOnDimensionsChange(hide);
React.useEffect(() => {
- const subscription = addEventListener(Dimensions, 'change', () =>
- setVisible(false)
- );
+ if (!visible) {
+ return undefined;
+ }
+ return () => releaseSingletonSlot(hide);
+ }, [visible, hide]);
- return () => subscription.remove();
- }, []);
+ // Web: Escape closes it, as focus alone keeps it open
+ useOverlayDismiss({
+ enabled: visible && Platform.OS === 'web',
+ dismissable: true,
+ onDismiss: hide,
+ });
- const handleTouchStart = React.useCallback(() => {
- if (hideTooltipTimer.current.length) {
- hideTooltipTimer.current.forEach((t) => clearTimeout(t));
- hideTooltipTimer.current = [];
- }
+ const show = React.useCallback(() => {
+ showTimer.clear();
+ hideTimer.clear();
+ takeSingletonSlot(hide);
+ setVisible(true);
+ }, [showTimer, hideTimer, hide]);
+ const handleTouchStart = () => {
if (Platform.OS === 'web') {
- const id = setTimeout(() => {
- touched.current = true;
- setVisible(true);
- }, enterTouchDelay);
- showTooltipTimer.current.push(id);
+ hideTimer.clear();
+ showTimer.schedule(show, enterTouchDelay);
} else {
- touched.current = true;
- setVisible(true);
- }
- }, [enterTouchDelay]);
-
- const handleTouchEnd = React.useCallback(() => {
- touched.current = false;
- if (showTooltipTimer.current.length) {
- showTooltipTimer.current.forEach((t) => clearTimeout(t));
- showTooltipTimer.current = [];
+ show();
}
+ };
- const id = setTimeout(() => {
- setVisible(false);
- setMeasurement({ children: {}, tooltip: {}, measured: false });
- }, leaveTouchDelay);
- hideTooltipTimer.current.push(id);
- }, [leaveTouchDelay]);
+ const handleTouchEnd = () => {
+ showTimer.clear();
+ hideTimer.schedule(hide, leaveTouchDelay);
+ };
- const handlePress = React.useCallback(() => {
- if (touched.current) {
- return null;
- }
- if (!isValidChild) return null;
- const props =
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
- children.props as TooltipChildProps;
- if (props.disabled) return null;
- return props.onPress?.();
- }, [children.props, isValidChild]);
+ const { hoveringRef, consumeTouchFocus, wrapperProps } = useTriggerHover({
+ wrapperRef: childrenWrapperRef,
+ onEnter: handleTouchStart,
+ onLeave: handleTouchEnd,
+ });
- const handleHoverIn = React.useCallback(() => {
- handleTouchStart();
- if (isValidChild) {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
- (children.props as TooltipChildProps).onHoverIn?.();
+ // Web: releasing a click on the hovered trigger mustn't hide the tooltip
+ // the hover opened; the pointer leaving does
+ const handlePressOut = () => {
+ if (Platform.OS === 'web' && hoveringRef.current) {
+ return;
}
- }, [children.props, handleTouchStart, isValidChild]);
-
- const handleHoverOut = React.useCallback(() => {
handleTouchEnd();
- if (isValidChild) {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
- (children.props as TooltipChildProps).onHoverOut?.();
- }
- }, [children.props, handleTouchEnd, isValidChild]);
-
- const handleOnLayout = ({ nativeEvent: { layout } }: LayoutChangeEvent) => {
- childrenWrapperRef.current?.measure(
- (_x, _y, width, height, pageX, pageY) => {
- setMeasurement({
- children: { pageX, pageY, height, width },
- tooltip: { ...layout },
- measured: true,
- });
- }
- );
};
- const mobilePressProps = {
- onPress: handlePress,
- onLongPress: () => handleTouchStart(),
- onPressOut: () => handleTouchEnd(),
+ const triggerProps: TooltipTriggerProps = {
+ // on web too, so touchscreen users can still show it
+ onLongPress: handleTouchStart,
+ onPressOut: handlePressOut,
delayLongPress: enterTouchDelay,
- };
-
- const webPressProps = {
- onHoverIn: handleHoverIn,
- onHoverOut: handleHoverOut,
+ ...(Platform.OS === 'web'
+ ? {
+ // keyboard focus shows it without the hover delay; a tap's focus
+ // doesn't, as a long-press shows it on touch
+ onFocus: () => {
+ if (!consumeTouchFocus()) show();
+ },
+ onBlur: handleTouchEnd,
+ }
+ : {}),
+ ...(titleAsAriaLabel
+ ? { 'aria-label': title }
+ : Platform.OS === 'web'
+ ? { 'aria-describedby': tooltipId }
+ : { accessibilityHint: title }),
};
return (
<>
- {visible && (
+ {rendered && (
-
{title}
-
+
)}
-
- {React.cloneElement(children, {
- ...rest,
- ...(Platform.OS === 'web' ? webPressProps : mobilePressProps),
- })}
-
+ {Platform.OS === 'web' ? (
+
+ {children(triggerProps)}
+
+ ) : (
+
+ {children(triggerProps)}
+
+ )}
>
);
};
@@ -251,15 +259,11 @@ const styles = StyleSheet.create({
tooltip: {
alignSelf: 'flex-start',
justifyContent: 'center',
- paddingHorizontal: 16,
- height: 32,
- maxHeight: 32,
- },
- visible: {
- opacity: 1,
- },
- hidden: {
- opacity: 0,
+ paddingHorizontal: Tokens.plain.paddingHorizontal,
+ paddingVertical: Tokens.plain.paddingVertical,
+ minHeight: Tokens.plain.minHeight,
+ minWidth: Tokens.plain.minWidth,
+ maxWidth: Tokens.plain.maxWidth,
},
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
pressContainer: {
diff --git a/src/components/Tooltip/hooks.ts b/src/components/Tooltip/hooks.ts
new file mode 100644
index 0000000000..edf1926bcb
--- /dev/null
+++ b/src/components/Tooltip/hooks.ts
@@ -0,0 +1,248 @@
+import * as React from 'react';
+import { Dimensions, Platform, View } from 'react-native';
+import type { LayoutChangeEvent, PointerEvent } from 'react-native';
+
+import { cubicBezier } from 'react-native-reanimated';
+import useLatestCallback from 'use-latest-callback';
+
+import { Tokens } from './tokens';
+import { isPointerInside } from './utils';
+import type { Measurement } from './utils';
+import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext';
+import type { InternalTheme } from '../../theme/types';
+import { addEventListener } from '../../utils/addEventListener';
+
+// Scheduling replaces the pending timeout
+export const useTimeout = () => {
+ const timer = React.useRef | null>(null);
+
+ const clear = React.useCallback(() => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ timer.current = null;
+ }
+ }, []);
+
+ const schedule = React.useCallback(
+ (callback: () => void, delay: number) => {
+ clear();
+ timer.current = setTimeout(() => {
+ timer.current = null;
+ callback();
+ }, delay);
+ },
+ [clear]
+ );
+
+ React.useEffect(() => clear, [clear]);
+
+ return React.useMemo(() => ({ schedule, clear }), [schedule, clear]);
+};
+
+type TriggerHoverOptions = {
+ wrapperRef: React.RefObject;
+ onEnter: (isTouch: boolean) => void;
+ onLeave: () => void;
+};
+
+/**
+ * Web only: hover over the trigger's wrapper, through pointer events, as
+ * React Native Web's `View` ignores `onHoverIn`/`onHoverOut` and its
+ * `Pressable` hover flickers.
+ */
+export const useTriggerHover = ({
+ wrapperRef,
+ onEnter,
+ onLeave,
+}: TriggerHoverOptions) => {
+ // a non-touch pointer sits on the trigger
+ const hoveringRef = React.useRef(false);
+ // a tap focuses the trigger, and that focus mustn't open the tooltip the way
+ // keyboard focus does
+ const touchingRef = React.useRef(false);
+
+ // true once, for the focus that follows a tap
+ const consumeTouchFocus = () => {
+ const wasTouch = touchingRef.current;
+ touchingRef.current = false;
+ return wasTouch;
+ };
+
+ const onPointerEnter = useLatestCallback((e: PointerEvent) => {
+ const isTouch = e.nativeEvent.pointerType === 'touch';
+ hoveringRef.current = !isTouch;
+ onEnter(isTouch);
+ });
+
+ const onPointerLeave = useLatestCallback((e: PointerEvent) => {
+ if (isPointerInside(wrapperRef.current, e.nativeEvent)) {
+ return;
+ }
+ hoveringRef.current = false;
+ onLeave();
+ });
+
+ const wrapperProps =
+ Platform.OS === 'web'
+ ? {
+ onPointerDown: (e: PointerEvent) => {
+ touchingRef.current = e.nativeEvent.pointerType === 'touch';
+ },
+ // a touch that turns into a scroll ends without a focus or a press
+ onPointerCancel: () => {
+ touchingRef.current = false;
+ },
+ onPointerEnter,
+ onPointerLeave,
+ }
+ : {};
+
+ return {
+ hoveringRef,
+ consumeTouchFocus,
+ wrapperProps,
+ };
+};
+
+// After a resize or rotation the position no longer matches the trigger
+export const useHideOnDimensionsChange = (hide: () => void) => {
+ React.useEffect(() => {
+ const subscription = addEventListener(Dimensions, 'change', hide);
+
+ return () => subscription.remove();
+ }, [hide]);
+};
+
+export type TooltipHostElement = React.ComponentRef & {
+ getBoundingClientRect?(): DOMRect;
+ contains?(node: unknown): boolean;
+};
+
+const NO_SCROLL = { x: 0, y: 0 };
+
+const UNMEASURED: Measurement = {
+ children: { pageX: 0, pageY: 0, width: 0, height: 0 },
+ tooltip: { x: 0, y: 0, width: 0, height: 0 },
+ scroll: NO_SCROLL,
+ measured: false,
+};
+
+/**
+ * Fades both tooltip variants in and out. Keeps the tooltip mounted through the
+ * exit fade and transparent until it is measured, so it never flashes at the
+ * wrong position.
+ */
+export const useTooltipFade = (theme: InternalTheme, visible: boolean) => {
+ const reduceMotion = useReduceMotion();
+ const [rendered, setRendered] = React.useState(false);
+ const [measurement, setMeasurement] = React.useState(UNMEASURED);
+ const childrenWrapperRef = React.useRef(null);
+ // The trigger measurement and tooltip layout are each obtained via async
+ // native calls that can complete in either order. Both refs are written by
+ // whichever side fires first; the second side checks whether the other is
+ // already available and, if so, completes the combined measurement.
+ const childrenMeasurement = React.useRef(
+ null
+ );
+ const tooltipLayout = React.useRef(null);
+ const scroll = React.useRef(NO_SCROLL);
+
+ const enterDuration = reduceMotion
+ ? 0
+ : theme.motion.duration[Tokens.motion.enter.duration];
+ const exitDuration = reduceMotion
+ ? 0
+ : theme.motion.duration[Tokens.motion.exit.duration];
+
+ if (visible && !rendered) {
+ setRendered(true);
+ }
+
+ // Measure the trigger synchronously once the tooltip is requested, instead
+ // of waiting for the tooltip's `onLayout` to do it. (The tooltip itself
+ // lives in a `Portal`, so its own size still comes from its layout below.)
+ React.useLayoutEffect(() => {
+ if (!rendered || !visible) {
+ return;
+ }
+
+ childrenWrapperRef.current?.measure(
+ (_x, _y, width, height, pageX, pageY) => {
+ childrenMeasurement.current = { pageX, pageY, width, height };
+ scroll.current =
+ Platform.OS === 'web'
+ ? { x: window.scrollX ?? 0, y: window.scrollY ?? 0 }
+ : NO_SCROLL;
+ if (tooltipLayout.current) {
+ setMeasurement({
+ children: childrenMeasurement.current,
+ tooltip: tooltipLayout.current,
+ scroll: scroll.current,
+ measured: true,
+ });
+ }
+ }
+ );
+ }, [rendered, visible]);
+
+ React.useEffect(() => {
+ if (!rendered || visible) {
+ return;
+ }
+
+ const id = setTimeout(() => {
+ setRendered(false);
+ setMeasurement(UNMEASURED);
+ childrenMeasurement.current = null;
+ tooltipLayout.current = null;
+ }, exitDuration);
+
+ return () => clearTimeout(id);
+ }, [rendered, visible, exitDuration]);
+
+ const onLayout = ({ nativeEvent: { layout } }: LayoutChangeEvent) => {
+ // Positioning the tooltip causes another onLayout with different x/y but
+ // the same dimensions. Only its size affects our position calculation, so
+ // ignore that second event instead of rebuilding the animated native layer
+ // while it is fading in (which can move it by one physical pixel on
+ // Android).
+ if (
+ tooltipLayout.current?.width === layout.width &&
+ tooltipLayout.current?.height === layout.height
+ ) {
+ return;
+ }
+
+ const nextLayout = { ...layout, x: 0, y: 0 };
+ tooltipLayout.current = nextLayout;
+ if (!childrenMeasurement.current) {
+ return;
+ }
+
+ setMeasurement({
+ children: childrenMeasurement.current,
+ tooltip: nextLayout,
+ scroll: scroll.current,
+ measured: true,
+ });
+ };
+
+ const fadeDuration = visible ? enterDuration : exitDuration;
+ const fadeStyle = {
+ opacity: visible && measurement.measured ? 1 : 0,
+ transitionProperty: 'opacity',
+ transitionDuration: `${fadeDuration}ms`,
+ transitionTimingFunction: visible
+ ? cubicBezier(...theme.motion.easing[Tokens.motion.enter.easing])
+ : cubicBezier(...theme.motion.easing[Tokens.motion.exit.easing]),
+ };
+
+ return {
+ rendered,
+ measurement,
+ fadeStyle,
+ fadeDuration,
+ onLayout,
+ childrenWrapperRef,
+ };
+};
diff --git a/src/components/Tooltip/index.tsx b/src/components/Tooltip/index.tsx
new file mode 100644
index 0000000000..f5fa880a6b
--- /dev/null
+++ b/src/components/Tooltip/index.tsx
@@ -0,0 +1,6 @@
+import RichTooltip from './RichTooltip';
+import TooltipBase from './Tooltip';
+
+const Tooltip = Object.assign(TooltipBase, { Rich: RichTooltip });
+
+export default Tooltip;
diff --git a/src/components/Tooltip/registry.ts b/src/components/Tooltip/registry.ts
new file mode 100644
index 0000000000..eb0e379e5e
--- /dev/null
+++ b/src/components/Tooltip/registry.ts
@@ -0,0 +1,66 @@
+import type { LayoutRectangle } from 'react-native';
+
+import { isWithinRect } from './utils';
+
+// Ensures only one tooltip is visible at a time
+let dismissCurrentTooltip: (() => void) | null = null;
+
+export const takeSingletonSlot = (dismiss: () => void) => {
+ dismissCurrentTooltip?.();
+ dismissCurrentTooltip = dismiss;
+};
+
+export const releaseSingletonSlot = (dismiss: () => void) => {
+ if (dismissCurrentTooltip === dismiss) {
+ dismissCurrentTooltip = null;
+ }
+};
+
+// Mobile backdrop hit-forwarding: each RichTooltip registers its trigger's
+// screen rect so the backdrop can forward presses that land on another trigger
+// rather than consuming them. This allows one-tap switching between tooltips.
+type RichTriggerEntry = {
+ rect: LayoutRectangle;
+ onPress: () => void;
+};
+
+const richTriggerRegistry = new Map();
+
+export const registerRichTrigger = (
+ id: symbol,
+ entry: RichTriggerEntry
+): void => {
+ richTriggerRegistry.set(id, entry);
+};
+
+export const unregisterRichTrigger = (id: symbol): void => {
+ richTriggerRegistry.delete(id);
+};
+
+// Returns true if a registered trigger was hit and pressed (caller should NOT
+// also call hide() in this case — the singleton dismisses the current tooltip).
+export const forwardPressToTriggerAt = (
+ pageX: number,
+ pageY: number
+): boolean => {
+ for (const { rect, onPress } of richTriggerRegistry.values()) {
+ if (isWithinRect(pageX, pageY, rect)) {
+ onPress();
+ return true;
+ }
+ }
+ return false;
+};
+
+// When a rich tooltip opens, every registered trigger re-measures itself so
+// scroll-invalidated coordinates are refreshed before the backdrop is used.
+const triggerRefreshCallbacks = new Set<() => void>();
+
+export const subscribeToTriggerRefresh = (cb: () => void): (() => void) => {
+ triggerRefreshCallbacks.add(cb);
+ return () => triggerRefreshCallbacks.delete(cb);
+};
+
+export const refreshRichTriggers = () => {
+ triggerRefreshCallbacks.forEach((cb) => cb());
+};
diff --git a/src/components/Tooltip/tokens.ts b/src/components/Tooltip/tokens.ts
new file mode 100644
index 0000000000..2e299017b0
--- /dev/null
+++ b/src/components/Tooltip/tokens.ts
@@ -0,0 +1,49 @@
+/**
+ * Plain tooltip - short text on an inverse-surface container, wrapping onto
+ * more lines past the max width.
+ * https://m3.material.io/components/tooltips/specs#1e6d4d8a
+ */
+const plain = {
+ container: 'inverseSurface',
+ content: 'inverseOnSurface',
+ shape: 'extraSmall',
+ minHeight: 24,
+ minWidth: 40,
+ maxWidth: 320,
+ // the 56dp max height at the default font size
+ maxLines: 3,
+ paddingHorizontal: 8,
+ paddingVertical: 4,
+ typescale: 'bodySmall',
+} as const;
+
+/**
+ * Rich tooltip — an optional subhead, supporting text and action buttons on a
+ * surface-container container at elevation level 2.
+ * https://m3.material.io/components/tooltips/specs#8e6cf915
+ */
+const rich = {
+ container: 'surfaceContainer',
+ title: 'onSurfaceVariant',
+ content: 'onSurfaceVariant',
+ shape: 'medium',
+ elevation: 2,
+ maxWidth: 320,
+ paddingHorizontal: 16,
+ paddingTop: 12,
+ paddingBottom: 8,
+ titleTypescale: 'titleSmall',
+ contentTypescale: 'bodyMedium',
+ gap: 4,
+} as const;
+
+/**
+ * Fade transition on show/hide. Keys are resolved against `theme.motion` at
+ * runtime: enter decelerates in, exit accelerates out, per the M3 motion spec.
+ */
+const motion = {
+ enter: { duration: 'short3', easing: 'standardDecelerate' },
+ exit: { duration: 'short2', easing: 'standardAccelerate' },
+} as const;
+
+export const Tokens = { plain, rich, motion };
diff --git a/src/components/Tooltip/useRichTooltipFocus.ts b/src/components/Tooltip/useRichTooltipFocus.ts
new file mode 100644
index 0000000000..cf7f3e6b23
--- /dev/null
+++ b/src/components/Tooltip/useRichTooltipFocus.ts
@@ -0,0 +1,170 @@
+import * as React from 'react';
+import { Platform } from 'react-native';
+import type { NativeSyntheticEvent } from 'react-native';
+
+import { useTimeout } from './hooks';
+import type { TooltipHostElement } from './hooks';
+import { getActiveElement } from './utils';
+import { useOverlayDismiss } from '../../utils/useOverlayDismiss';
+import { focusIntoContainer, getTabbables } from '../../utils/useOverlayFocus';
+
+type Options = {
+ visible: boolean;
+ hasActions: boolean;
+ tooltipRef: React.RefObject;
+ triggerRef: React.RefObject;
+ show: () => void;
+ hide: () => void;
+ scheduleHide: () => void;
+ consumeTouchFocus: () => boolean;
+};
+
+/**
+ * Web only: keyboard and focus handling of `Tooltip.Rich`.
+ */
+export const useRichTooltipFocus = ({
+ visible,
+ hasActions,
+ tooltipRef,
+ triggerRef,
+ show,
+ hide,
+ scheduleHide,
+ consumeTouchFocus,
+}: Options) => {
+ // the trigger's keyboard focus opened the tooltip
+ const focusOpenedRef = React.useRef(false);
+ // set while dismiss is returning focus to the trigger
+ const refocusAfterDismissRef = React.useRef(false);
+ const focusTimer = useTimeout();
+
+ React.useEffect(() => {
+ if (!visible) {
+ focusOpenedRef.current = false;
+ }
+ }, [visible]);
+
+ // Focus inside the tooltip would be lost on unmount, so it goes back to the
+ // trigger; focus elsewhere stays put
+ const hideAndRestoreFocus = () => {
+ const focused = Platform.OS === 'web' ? getActiveElement() : null;
+ const hadFocus =
+ focused != null &&
+ (tooltipRef.current?.contains?.(focused) ||
+ triggerRef.current?.contains?.(focused));
+
+ hide();
+ // set before focusing, as the trigger's focus event would reopen the
+ // tooltip; cleared if the browser refused the focus
+ refocusAfterDismissRef.current = Boolean(hadFocus);
+ if (hadFocus && !focusIntoContainer(triggerRef.current)) {
+ refocusAfterDismissRef.current = false;
+ }
+ };
+
+ // Ignores the focus that dismissing causes, and the focus a tap gives the
+ // trigger, as the press that follows toggles the tooltip
+ const onFocus = () => {
+ const isTouchFocus = consumeTouchFocus();
+ if (refocusAfterDismissRef.current || isTouchFocus) {
+ refocusAfterDismissRef.current = false;
+ return;
+ }
+ focusOpenedRef.current = true;
+ show();
+ };
+
+ const onBlur = () => {
+ refocusAfterDismissRef.current = false;
+ focusOpenedRef.current = false;
+ scheduleHide();
+ };
+
+ // The portal puts the tooltip at the end of the document, out of `Tab`
+ // order, so `ArrowDown` moves focus into the actions once it has mounted
+ const onKeyDown = (event: NativeSyntheticEvent<{ key: string }>) => {
+ if (hasActions && event.nativeEvent.key === 'ArrowDown') {
+ // keeps the page from scrolling before focus moves
+ event.preventDefault();
+ show();
+ focusTimer.schedule(() => focusIntoContainer(tooltipRef.current), 0);
+ }
+ };
+
+ // Out of `Tab` order in the portal, `Tab` past the tooltip's last element
+ // goes on from the trigger, and `Shift+Tab` past its first goes back to it
+ const onTooltipKeyDown = (
+ event: NativeSyntheticEvent<{ key: string; shiftKey?: boolean }>
+ ) => {
+ const tooltip: unknown = tooltipRef.current;
+ const trigger: unknown = triggerRef.current;
+ if (
+ event.nativeEvent.key !== 'Tab' ||
+ !(tooltip instanceof HTMLElement) ||
+ !(trigger instanceof HTMLElement)
+ ) {
+ return;
+ }
+
+ const inside = getTabbables(tooltip);
+ const focused = getActiveElement();
+
+ if (event.nativeEvent.shiftKey) {
+ if (focused === inside[0]) {
+ event.preventDefault();
+ focusIntoContainer(trigger);
+ }
+ return;
+ }
+
+ if (focused === inside[inside.length - 1]) {
+ const page = getTabbables(document).filter(
+ (element) => !tooltip.contains(element)
+ );
+ const lastInTrigger = page
+ .map((element) => trigger.contains(element))
+ .lastIndexOf(true);
+ const next = lastInTrigger === -1 ? undefined : page[lastInTrigger + 1];
+ if (next) {
+ event.preventDefault();
+ next.focus();
+ }
+ }
+ };
+
+ // The backdrop lets pointer events through, so a press outside closes the
+ // tooltip here; blur misses triggers a tap doesn't focus, as in Safari
+ React.useEffect(() => {
+ if (Platform.OS !== 'web' || !visible || !('document' in global)) {
+ return;
+ }
+
+ const handlePointerDown = ({ target }: { target: EventTarget | null }) => {
+ if (
+ tooltipRef.current?.contains?.(target) ||
+ triggerRef.current?.contains?.(target)
+ ) {
+ return;
+ }
+ hide();
+ };
+
+ document.addEventListener('pointerdown', handlePointerDown);
+
+ return () => document.removeEventListener('pointerdown', handlePointerDown);
+ }, [visible, hide, tooltipRef, triggerRef]);
+
+ // The back button is left to the screen, as the tooltip isn't modal
+ useOverlayDismiss({
+ enabled: visible && Platform.OS === 'web',
+ dismissable: true,
+ onDismiss: hideAndRestoreFocus,
+ });
+
+ return {
+ triggerProps: { onFocus, onBlur, onKeyDown },
+ onTooltipKeyDown,
+ hideAndRestoreFocus,
+ isOpenedByFocus: () => focusOpenedRef.current,
+ };
+};
diff --git a/src/components/Tooltip/utils.ts b/src/components/Tooltip/utils.ts
index 97116f7fac..978252025c 100644
--- a/src/components/Tooltip/utils.ts
+++ b/src/components/Tooltip/utils.ts
@@ -1,6 +1,8 @@
-import { Dimensions } from 'react-native';
+import { Dimensions, PixelRatio, Platform } from 'react-native';
import type { LayoutRectangle } from 'react-native';
+import type { Direction } from '../../core/locale';
+
type ChildrenMeasurement = {
width: number;
height: number;
@@ -11,24 +13,24 @@ type ChildrenMeasurement = {
type TooltipLayout = LayoutRectangle;
export type Measurement = {
+ // viewport coordinates, as `measure` reports them
children: ChildrenMeasurement;
tooltip: TooltipLayout;
+ // Web only: page scroll when measured, as the portal sits at the document
+ // origin
+ scroll: { x: number; y: number };
measured: boolean;
};
-export type TooltipChildProps = {
- disabled?: boolean;
- onPress?: () => void;
- onHoverIn?: () => void;
- onHoverOut?: () => void;
-};
+const EDGE_MARGIN = 8;
+const ANCHOR_GAP = 4;
/**
* Return true when the tooltip center x-coordinate relative to the wrapped element is negative.
* The tooltip will be placed at the starting x-coordinate from the wrapped element.
*/
const overflowLeft = (center: number): boolean => {
- return center < 0;
+ return center < EDGE_MARGIN;
};
/**
@@ -38,7 +40,7 @@ const overflowLeft = (center: number): boolean => {
const overflowRight = (center: number, tooltipWidth: number): boolean => {
const { width: layoutWidth } = Dimensions.get('window');
- return center + tooltipWidth > layoutWidth;
+ return center + tooltipWidth > layoutWidth - EDGE_MARGIN;
};
/**
@@ -52,7 +54,7 @@ const overflowBottom = (
): boolean => {
const { height: layoutHeight } = Dimensions.get('window');
- return childrenY + childrenHeight + tooltipHeight > layoutHeight;
+ return childrenY + childrenHeight + ANCHOR_GAP + tooltipHeight > layoutHeight;
};
const getTooltipXPosition = (
@@ -66,10 +68,23 @@ const getTooltipXPosition = (
? childrenX + (childrenWidth - tooltipWidth) / 2
: childrenX;
- if (overflowLeft(center)) return childrenX;
-
- if (overflowRight(center, tooltipWidth))
- return childrenX + childrenWidth - tooltipWidth;
+ if (overflowLeft(center)) {
+ // a tooltip wider than the room on either side of the trigger must still
+ // keep clear of the right edge
+ const { width: layoutWidth } = Dimensions.get('window');
+ return Math.max(
+ EDGE_MARGIN,
+ Math.min(childrenX, layoutWidth - tooltipWidth - EDGE_MARGIN)
+ );
+ }
+
+ if (overflowRight(center, tooltipWidth)) {
+ const { width: layoutWidth } = Dimensions.get('window');
+ return Math.min(
+ childrenX + childrenWidth - tooltipWidth,
+ layoutWidth - tooltipWidth - EDGE_MARGIN
+ );
+ }
return center;
};
@@ -78,21 +93,62 @@ const getTooltipYPosition = (
{ pageY: childrenY, height: childrenHeight }: ChildrenMeasurement,
{ height: tooltipHeight }: TooltipLayout
): number => {
+ // A tooltip too tall for either side stays on screen over the trigger
if (overflowBottom(childrenY, childrenHeight, tooltipHeight))
- return childrenY - tooltipHeight;
+ return Math.max(EDGE_MARGIN, childrenY - ANCHOR_GAP - tooltipHeight);
+
+ return childrenY + childrenHeight + ANCHOR_GAP;
+};
+
+export const isWithinRect = (
+ pointX: number,
+ pointY: number,
+ { x, y, width, height }: LayoutRectangle
+): boolean =>
+ pointX >= x && pointX <= x + width && pointY >= y && pointY <= y + height;
+
+type PointerPosition = { clientX: number; clientY: number };
+
+// Web only: null where there is no document
+export const getActiveElement = (): Element | null =>
+ 'document' in global ? document.activeElement : null;
+
+/**
+ * Web only: pointer leave also fires spuriously, e.g. when the tooltip mounts
+ * in the portal, so a leave is only real once the pointer is outside the
+ * element's bounds.
+ */
+export const isPointerInside = (
+ element: { getBoundingClientRect?(): DOMRect } | null,
+ { clientX, clientY }: PointerPosition
+): boolean => {
+ const rect = element?.getBoundingClientRect?.();
- return childrenY + childrenHeight;
+ return rect !== undefined && isWithinRect(clientX, clientY, rect);
};
-export const getTooltipPosition = ({
- children,
- tooltip,
- measured,
-}: Measurement): { left?: number; top?: number } => {
+export const getTooltipPosition = (
+ { children, tooltip, scroll, measured }: Measurement,
+ direction: Direction = 'ltr'
+): { left?: number; top?: number } => {
if (!measured) return {};
- return {
- left: getTooltipXPosition(children, tooltip),
- top: getTooltipYPosition(children, tooltip),
- };
+ let left = getTooltipXPosition(children, tooltip);
+ const top = getTooltipYPosition(children, tooltip);
+
+ if (direction === 'rtl') {
+ // `measure` reports the physical left edge, but in RTL the tooltip starts
+ // at the right one: native resolves `left` from it, and on web the tooltip
+ // isn't absolutely positioned, so `left` offsets it from there.
+ const trailingOffset =
+ Dimensions.get('window').width - tooltip.width - left;
+ left = Platform.OS === 'web' ? -trailingOffset : trailingOffset;
+ }
+
+ return Platform.OS === 'web'
+ ? { left: left + scroll.x, top: top + scroll.y }
+ : {
+ left: PixelRatio.roundToNearestPixel(left),
+ top: PixelRatio.roundToNearestPixel(top),
+ };
};
diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx
index 28c927d95a..1f34cbd6ab 100644
--- a/src/components/__tests__/Appbar/Appbar.test.tsx
+++ b/src/components/__tests__/Appbar/Appbar.test.tsx
@@ -125,7 +125,9 @@ describe('Appbar context', () => {
await render(
-
+ {(props) => (
+
+ )}
@@ -613,15 +615,18 @@ describe('Appbar layout', () => {
-
- (
- {String(color)}
- )}
- aria-label="Menu"
- onPress={() => {}}
- />
-
+ {(props) => (
+
+ (
+ {String(color)}
+ )}
+ aria-label="Menu"
+ onPress={() => {}}
+ />
+
+ )}
);
diff --git a/src/components/__tests__/FAB.test.tsx b/src/components/__tests__/FAB.test.tsx
index 8eb91a1efa..8d4d3ae9fb 100644
--- a/src/components/__tests__/FAB.test.tsx
+++ b/src/components/__tests__/FAB.test.tsx
@@ -10,7 +10,7 @@ import {
it,
jest,
} from '@jest/globals';
-import { fireEvent, userEvent } from '@testing-library/react-native';
+import { fireEvent, userEvent, waitFor } from '@testing-library/react-native';
import * as Reanimated from 'react-native-reanimated';
import { getAnimatedStyle } from 'react-native-reanimated';
@@ -190,7 +190,14 @@ it('shows Tooltip when FAB is long pressed', async () => {
await render(
- {}} />
+ {(props) => (
+ {}}
+ />
+ )}
);
@@ -648,6 +655,8 @@ describe('on web', () => {
get activeElement() {
return activeElement;
},
+ addEventListener: () => {},
+ removeEventListener: () => {},
},
});
Object.defineProperty(View.prototype, 'matches', {
@@ -727,6 +736,37 @@ describe('on web', () => {
return { blur, hide: () => rerender(fab(false)) };
};
+ it('shows Tooltip when FAB gets keyboard focus', async () => {
+ await render(
+
+
+ {(props) => (
+ {}}
+ />
+ )}
+
+
+ );
+ const fab = screen.getByRole('button', { name: 'Add item' });
+
+ await act(async () => {
+ await fireEvent(fab, 'focus', { nativeEvent: {} });
+ });
+ expect(screen.getByText('Press Me')).toBeOnTheScreen();
+ expect(fab).toHaveProp('aria-describedby', expect.any(String));
+
+ await act(async () => {
+ await fireEvent(fab, 'blur');
+ });
+ await waitFor(() =>
+ expect(screen.queryByText('Press Me')).not.toBeOnTheScreen()
+ );
+ });
+
it.each(['icon', 'extended'] as const)(
'keeps the %s FAB at rest on focus, changes its elevation while hovered and restores it while pressed',
async (type) => {
diff --git a/src/components/__tests__/Tooltip.test.tsx b/src/components/__tests__/Tooltip.test.tsx
index f143109d9b..bc5e6fe7d1 100644
--- a/src/components/__tests__/Tooltip.test.tsx
+++ b/src/components/__tests__/Tooltip.test.tsx
@@ -1,65 +1,95 @@
import React from 'react';
-import { Dimensions, Text, View, Platform } from 'react-native';
+import {
+ BackHandler as RNBackHandler,
+ Dimensions,
+ Text,
+ View,
+ Platform,
+ Pressable,
+} from 'react-native';
import type { ViewProps } from 'react-native';
import {
afterAll,
afterEach,
beforeAll,
+ beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals';
-import { act, fireEvent, userEvent } from '@testing-library/react-native';
+import {
+ act,
+ fireEvent,
+ isHiddenFromAccessibility,
+ userEvent,
+} from '@testing-library/react-native';
import PaperProvider from '../../core/PaperProvider';
-import { render } from '../../test-utils';
-import Tooltip from '../Tooltip/Tooltip';
+import { render, screen } from '../../test-utils';
+import { LightTheme } from '../../theme/schemes';
+import * as overlayFocus from '../../utils/useOverlayFocus';
+import TooltipCompound from '../Tooltip';
+import * as registry from '../Tooltip/registry';
+import { releaseSingletonSlot, takeSingletonSlot } from '../Tooltip/registry';
+import Tooltip, { type TooltipTriggerProps } from '../Tooltip/Tooltip';
const ViewPrototype: React.ComponentRef = View.prototype;
-const mockedRemoveEventListener = jest.fn();
+// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
+const BackHandler = RNBackHandler as typeof RNBackHandler & {
+ mockPressBack(): void;
+ exitApp: jest.Mock<() => void>;
+};
+
+const initialDimensions = {
+ window: Dimensions.get('window'),
+ screen: Dimensions.get('screen'),
+};
+
+const changeScreenSize = async () => {
+ await act(() => {
+ Dimensions.set({
+ window: { width: 400, height: 800, scale: 2, fontScale: 1 },
+ screen: { width: 400, height: 800, scale: 2, fontScale: 1 },
+ });
+ });
+};
+
+afterEach(() => {
+ Dimensions.set(initialDimensions);
+});
-jest.mock('../../utils/addEventListener', () => ({
- addEventListener: () => ({
- remove: mockedRemoveEventListener,
- }),
-}));
+// What react-native-web passes to pointer handlers for a mouse
+const mousePointer = {
+ nativeEvent: { pointerType: 'mouse', clientX: 0, clientY: 0 },
+};
const DummyComponent = ({
ref,
...props
-}: ViewProps & {
- ref?: React.RefObject | null>;
-}) => (
-
+}: ViewProps &
+ TooltipTriggerProps & {
+ ref?: React.RefObject | null>;
+ }) => (
+
dummy component
);
describe('Tooltip', () => {
- const getTrigger = (
- getByText: Awaited>['getByText']
- ) => {
- const trigger = getByText('dummy component', {
- includeHiddenElements: true,
- }).parent;
-
- if (!trigger) {
- throw new Error('Expected Tooltip trigger wrapper');
- }
+ const getTrigger = () =>
+ screen.getByTestId('trigger', { includeHiddenElements: true });
- return trigger;
- };
+ const getTooltipContainer = () => screen.getByTestId('tooltip');
- const runTimers = async (ms?: number) => {
- await act(() => {
- if (ms === undefined) {
- jest.runOnlyPendingTimers();
- } else {
- jest.advanceTimersByTime(ms);
- }
+ // Advancing async lets the timer callbacks' state updates flush and re-render
+ // (a sync `act` doesn't under the async renderer). Default to a large step
+ // that drains every pending tooltip timer.
+ const runTimers = async (ms = 1000) => {
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(ms);
});
};
@@ -68,8 +98,9 @@ describe('Tooltip', () => {
measure = {}
) => {
const defaultProps = {
- children: ,
+ children: (props: TooltipTriggerProps) => ,
title: 'some tooltip text',
+ testID: 'tooltip',
...propOverrides,
};
@@ -96,6 +127,14 @@ describe('Tooltip', () => {
return { wrapper };
};
+ // `userEvent.setup()` coordinates the press gestures with the fake timers so
+ // its `act()` scopes don't overlap the tooltip's own timer-driven updates
+ // (overlapping act() calls corrupt the renderer across tests).
+ let user: ReturnType;
+ beforeEach(() => {
+ user = userEvent.setup();
+ });
+
describe('Mobile', () => {
beforeAll(() => {
Platform.OS = 'android';
@@ -103,80 +142,188 @@ describe('Tooltip', () => {
afterAll(() => {
jest.clearAllMocks();
});
- describe('Unmount', () => {
- beforeAll(() => {
- jest.spyOn(global, 'clearTimeout');
- });
- afterEach(() => {
- jest.clearAllMocks();
- });
-
- it('removes hideTooltipTimer when the component unmounts', async () => {
+ describe('screen size change', () => {
+ it('hides the tooltip when the screen size changes', async () => {
const {
- wrapper: { getByText, unmount },
- } = await setup({ enterTouchDelay: 5000 });
+ wrapper: { findByText, queryByText },
+ } = await setup({ leaveTouchDelay: 5000 });
- await fireEvent(getTrigger(getByText), 'pressOut');
+ await user.longPress(getTrigger());
+ await findByText('some tooltip text');
- await unmount();
+ await changeScreenSize();
+ await runTimers();
- expect(global.clearTimeout).toHaveBeenCalledTimes(1);
+ expect(queryByText('some tooltip text')).toBeNull();
});
+ });
- it('removes Dimensions listener when the component unmount', async () => {
+ describe('longPress', () => {
+ it('stays open when the user presses the component again before it hides', async () => {
const {
- wrapper: { getByText, findByText, unmount },
- } = await setup();
+ wrapper: { getByText },
+ } = await setup({ leaveTouchDelay: 2000 });
- await userEvent.longPress(getTrigger(getByText));
+ const trigger = getTrigger();
+ // The release schedules the hide, which pressing again cancels
+ await user.longPress(trigger);
+ await runTimers(500);
+ await user.longPress(trigger);
+ await runTimers(1500);
- await findByText('some tooltip text');
+ expect(getByText('some tooltip text')).toBeOnTheScreen();
+ });
+ });
- await unmount();
+ describe('anchor that ignores the trigger props', () => {
+ it('shows the tooltip on long press as the wrapper handles it', async () => {
+ jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 220, 200));
+
+ // An anchor like `Avatar.Text` never receives the handlers, so the
+ // wrapper has to keep handling the long press for it.
+ const { findByText } = await render(
+
+
+ {() => (
+
+ dummy component
+
+ )}
+
+
+ );
+
+ await user.longPress(getTrigger());
+
+ expect(await findByText('some tooltip text')).toBeTruthy();
+ });
+ });
+
+ describe('consumer handlers', () => {
+ it('forwards the gesture event to the onPress written by the consumer', async () => {
+ const onPress = jest.fn();
+ await setup({
+ children: (props: TooltipTriggerProps) => (
+
+ dummy component
+
+ ),
+ });
+
+ // The trigger props are spread onto the consumer's element, so its own
+ // handler runs with the real event instead of being called without one
+ await user.press(getTrigger());
- expect(mockedRemoveEventListener).toHaveBeenCalled();
+ expect(onPress).toHaveBeenCalledTimes(1);
+ expect(onPress).toHaveBeenCalledWith(
+ expect.objectContaining({ nativeEvent: expect.anything() })
+ );
});
});
- describe('longPress', () => {
- beforeAll(() => {
- jest.spyOn(global, 'clearTimeout');
+ describe('accessibility', () => {
+ it('describes the trigger with the title so it is announceable', async () => {
+ await setup();
+
+ expect(getTrigger()).toHaveProp(
+ 'accessibilityHint',
+ 'some tooltip text'
+ );
+
+ await user.longPress(getTrigger());
+
+ expect(getTooltipContainer()).toHaveProp('role', 'tooltip');
});
- afterEach(() => {
- jest.clearAllMocks();
+
+ it("doesn't merge the trigger into its wrapper", async () => {
+ await setup();
+
+ expect(getTrigger().parent).toHaveProp('accessible', false);
});
- it('clears the hide timer when the user start pressing the component again', async () => {
- jest.spyOn(global, 'clearTimeout');
+ it('keeps the label the consumer writes after the spread', async () => {
+ await setup({
+ children: (props: TooltipTriggerProps) => (
+
+ ),
+ });
- const {
- wrapper: { getByText },
- } = await setup();
+ expect(getTrigger()).toHaveAccessibleName('Own label');
+ expect(getTrigger()).toHaveProp(
+ 'accessibilityHint',
+ 'some tooltip text'
+ );
+ });
- const trigger = getTrigger(getByText);
- await userEvent.longPress(trigger);
- await userEvent.longPress(trigger);
+ it('names the trigger with the title when titleAsAriaLabel is set', async () => {
+ await setup({ titleAsAriaLabel: true });
- expect(global.clearTimeout).toHaveBeenCalledTimes(1);
+ expect(getTrigger()).toHaveAccessibleName('some tooltip text');
+ expect(getTrigger()).not.toHaveProp('accessibilityHint');
});
});
describe('pressOut', () => {
it('hides the tooltip when the user stop pressing the component', async () => {
const {
- wrapper: { queryByText, getByText, findByText },
+ wrapper: { queryByText, findByText },
} = await setup({ enterTouchDelay: 50, leaveTouchDelay: 100 });
- await userEvent.longPress(getTrigger(getByText));
+ // `longPress` includes the release (pressOut), which schedules the hide.
+ await user.longPress(getTrigger());
await findByText('some tooltip text');
+ await runTimers(); // leaveTouchDelay → schedules the exit fade
await runTimers();
expect(queryByText('some tooltip text')).not.toBeOnTheScreen();
});
});
+ describe('MD3 styling', () => {
+ it('renders an inverseSurface container with inverseOnSurface text', async () => {
+ const {
+ wrapper: { getByText, findByText },
+ } = await setup();
+
+ await user.longPress(getTrigger());
+
+ await findByText('some tooltip text');
+
+ expect(getTooltipContainer()).toHaveStyle({
+ backgroundColor: LightTheme.colors.inverseSurface,
+ });
+
+ expect(getByText('some tooltip text')).toHaveStyle({
+ color: LightTheme.colors.inverseOnSurface,
+ });
+ });
+ });
+
+ describe('fade animation', () => {
+ it('stays mounted through the exit fade before unmounting', async () => {
+ const {
+ wrapper: { queryByText, getByText, findByText },
+ } = await setup({ leaveTouchDelay: 0 });
+
+ // `longPress` includes the release (pressOut), which schedules the hide.
+ await user.longPress(getTrigger());
+
+ await findByText('some tooltip text');
+
+ await runTimers(0); // leaveTouchDelay (0) elapses → exit fade starts
+
+ // Still mounted while fading out so the animation can play.
+ expect(getByText('some tooltip text')).toBeTruthy();
+
+ await runTimers(); // exit fade duration elapses → unmounts
+ expect(queryByText('some tooltip text')).toBeNull();
+ });
+ });
+
describe('Tooltip position', () => {
const LAYOUT_WIDTH = 360;
const LAYOUT_HEIGHT = 705;
@@ -195,10 +342,10 @@ describe('Tooltip', () => {
describe('When it does not overflow', () => {
it('centers the tooltip in the middle of the children component', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup();
- await userEvent.longPress(getTrigger(getByText));
+ await user.longPress(getTrigger());
const tooltip = await findByText('some tooltip text');
await fireEvent(tooltip, 'layout', {
@@ -207,24 +354,25 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
+ expect(getTooltipContainer()).toHaveStyle({
left: 210, // pageX (220) + (width (80) - TOOLTIP_WIDTH (100)) / 2 = 210
- top: 250, // pageY (200) + height (50)
+ top: 254, // pageY (200) + height (50) + ANCHOR_GAP (4)
});
});
it('anchors the tooltip to the wrapper when the child is absolutely positioned', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({
- children: (
+ children: (props: TooltipTriggerProps) => (
),
});
- await userEvent.longPress(getTrigger(getByText));
+ await userEvent.longPress(getTrigger());
const tooltip = await findByText('some tooltip text');
await fireEvent(tooltip, 'layout', {
@@ -233,9 +381,42 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
+ expect(getTooltipContainer()).toHaveStyle({
left: 210,
- top: 250,
+ top: 254,
+ });
+ });
+ });
+
+ describe('When the locale is RTL', () => {
+ it('mirrors the position to the trailing edge', async () => {
+ jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 220, 200));
+
+ const { findByText } = await render(
+
+
+ {(props: TooltipTriggerProps) => }
+
+
+ );
+
+ await user.longPress(getTrigger());
+
+ const tooltip = await findByText('some tooltip text');
+ await fireEvent(tooltip, 'layout', {
+ nativeEvent: {
+ layout: { width: TOOLTIP_WIDTH, height: TOOLTIP_HEIGHT },
+ },
+ });
+
+ // `measure` reports the physical left edge, while native resolves
+ // `left` from the leading (right) edge in RTL, so what the tooltip
+ // needs is its distance to the trailing edge.
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 50, // LAYOUT_WIDTH (360) - TOOLTIP_WIDTH (100) - left (210)
+ top: 254,
});
});
});
@@ -243,10 +424,10 @@ describe('Tooltip', () => {
describe('When it overflows to left', () => {
it('renders the tooltip with the right placement', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({}, { pageX: 0 }); // Component starting at the starting 0 X coord
- await userEvent.longPress(getTrigger(getByText));
+ await user.longPress(getTrigger());
const tooltip = await findByText('some tooltip text');
await fireEvent(tooltip, 'layout', {
@@ -255,9 +436,27 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
- left: 0, // Tooltip renders starting from children's x coord
- top: 250,
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 8, // Math.max(EDGE_MARGIN=8, pageX=0)
+ top: 254,
+ });
+ });
+
+ it('keeps a wide tooltip clear of the right edge', async () => {
+ const {
+ wrapper: { findByText },
+ } = await setup({}, { pageX: 60 });
+
+ await user.longPress(getTrigger());
+
+ const tooltip = await findByText('some tooltip text');
+ await fireEvent(tooltip, 'layout', {
+ nativeEvent: { layout: { width: 320, height: TOOLTIP_HEIGHT } },
+ });
+
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 32, // LAYOUT_WIDTH (360) - width (320) - EDGE_MARGIN (8)
+ top: 254,
});
});
});
@@ -265,10 +464,10 @@ describe('Tooltip', () => {
describe('When it overflows to right', () => {
it('renders the tooltip with the right placement', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({}, { pageX: 900, width: 150 }); // Component close to the screen limit
- await userEvent.longPress(getTrigger(getByText));
+ await user.longPress(getTrigger());
const tooltip = await findByText('some tooltip text');
await fireEvent(tooltip, 'layout', {
@@ -277,20 +476,37 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
- left: 950, // pageX (900) + width (150) - 100 (TOOLTIP_WIDTH) // Tooltip is placed from right to left without going offscreen
- top: 250,
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 252, // Math.min(950, LAYOUT_WIDTH(360) - TOOLTIP_WIDTH(100) - EDGE_MARGIN(8))
+ top: 254,
+ });
+ });
+ });
+
+ describe('When it is too tall for either side', () => {
+ it('keeps the tooltip on screen at the top edge', async () => {
+ const {
+ wrapper: { findByText },
+ } = await setup({}, { pageY: 60, height: 50 });
+
+ await user.longPress(getTrigger());
+
+ const tooltip = await findByText('some tooltip text');
+ await fireEvent(tooltip, 'layout', {
+ nativeEvent: { layout: { width: TOOLTIP_WIDTH, height: 700 } },
});
+
+ expect(getTooltipContainer()).toHaveStyle({ top: 8 }); // EDGE_MARGIN
});
});
describe('When it overflows to bottom', () => {
it('renders the tooltip with the right placement', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({}, { pageY: 600, height: 50 });
- await userEvent.longPress(getTrigger(getByText));
+ await user.longPress(getTrigger());
const tooltip = await findByText('some tooltip text');
await fireEvent(tooltip, 'layout', {
@@ -299,9 +515,31 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 210,
+ top: 496, // pageY (600) - ANCHOR_GAP (4) - TOOLTIP_HEIGHT (100): placed above the component
+ });
+ });
+
+ it('snaps the tooltip position to the physical pixel grid', async () => {
+ const {
+ wrapper: { findByText },
+ } = await setup(
+ {},
+ { pageX: 220.2, pageY: 600.2, width: 80, height: 50 }
+ );
+
+ await user.longPress(getTrigger());
+
+ await fireEvent(await findByText('some tooltip text'), 'layout', {
+ nativeEvent: {
+ layout: { width: 100.1, height: 100.1 },
+ },
+ });
+
+ expect(getTooltipContainer()).toHaveStyle({
left: 210,
- top: 500, // pageY (600) - TOOLTIP_HEIGHT (100) // Tooltip is placed at the top of the component,
+ top: 496,
});
});
});
@@ -312,93 +550,207 @@ describe('Tooltip', () => {
beforeAll(() => {
Platform.OS = 'web';
});
- describe('Unmount', () => {
- beforeAll(() => {
- jest.spyOn(global, 'clearTimeout');
- });
- afterEach(() => {
- jest.clearAllMocks();
- });
- it('removes showTooltipTimer when the component unmounts', async () => {
+ describe('screen size change', () => {
+ it('hides the tooltip when the screen size changes', async () => {
const {
- wrapper: { getByText, unmount },
- } = await setup({ enterTouchDelay: 5000 });
+ wrapper: { findByText, queryByText },
+ } = await setup();
- await fireEvent(getTrigger(getByText), 'hoverIn');
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ await runTimers(500);
+ await findByText('some tooltip text');
- await unmount();
+ await changeScreenSize();
+ await runTimers();
- expect(global.clearTimeout).toHaveBeenCalledTimes(1);
+ expect(queryByText('some tooltip text')).toBeNull();
});
+ });
- it('removes hideTooltipTimer when the component unmounts', async () => {
+ describe('hoverIn', () => {
+ it('stays open when the pointer comes back before it hides', async () => {
const {
- wrapper: { getByText, unmount },
- } = await setup({ enterTouchDelay: 5000 });
+ wrapper: { getByText },
+ } = await setup({ enterTouchDelay: 100, leaveTouchDelay: 1000 });
- await fireEvent(getTrigger(getByText), 'hoverOut');
+ const trigger = getTrigger();
+ await fireEvent(trigger, 'pointerEnter', mousePointer);
+ await runTimers(100);
+ await fireEvent(trigger, 'pointerLeave', mousePointer);
+ await runTimers(500);
+ await fireEvent(trigger, 'pointerEnter', mousePointer);
+ await runTimers(800);
- await unmount();
+ expect(getByText('some tooltip text')).toBeOnTheScreen();
+ });
+
+ it('shows once when the pointer enters twice without leaving', async () => {
+ const {
+ wrapper: { queryByText },
+ } = await setup({ enterTouchDelay: 500, leaveTouchDelay: 0 });
+
+ const trigger = getTrigger();
+ await fireEvent(trigger, 'pointerEnter', mousePointer);
+ await runTimers(300);
+ await fireEvent(trigger, 'pointerEnter', mousePointer);
+ await act(async () => {
+ await fireEvent(trigger, 'pointerLeave', mousePointer);
+ });
+ await runTimers();
- expect(global.clearTimeout).toHaveBeenCalledTimes(1);
+ expect(queryByText('some tooltip text')).toBeNull();
});
+ });
- it('removes Dimensions listener when the component unmount', async () => {
+ describe('hoverOut', () => {
+ it('hides the tooltip when the user stops hovering the component', async () => {
const {
- wrapper: { getByText, findByText, unmount },
- } = await setup();
+ wrapper: { queryByText, findByText },
+ } = await setup({ enterTouchDelay: 50, leaveTouchDelay: 0 });
- await fireEvent(getTrigger(getByText), 'hoverIn');
- await runTimers(500);
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ await runTimers(50);
await findByText('some tooltip text');
- await unmount();
+ // Settle the pointer-leave in its own act() so its state update can't
+ // escape act and corrupt the renderer, then drain the fade-out timers.
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerLeave', mousePointer);
+ });
+ await runTimers(); // leaveTouchDelay → schedules the exit fade
+ await runTimers();
- expect(mockedRemoveEventListener).toHaveBeenCalled();
+ expect(queryByText('some tooltip text')).not.toBeOnTheScreen();
});
});
- describe('hoverIn', () => {
- beforeAll(() => {
- jest.spyOn(global, 'clearTimeout');
- });
- afterEach(() => {
- jest.clearAllMocks();
+ describe('click', () => {
+ it('stays open when the hovered trigger is clicked', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup({ enterTouchDelay: 0, leaveTouchDelay: 0 });
+ const trigger = getTrigger();
+
+ await act(async () => {
+ await fireEvent(trigger, 'pointerEnter', {
+ nativeEvent: { pointerType: 'mouse' },
+ });
+ });
+ await runTimers(0);
+ await act(async () => {
+ await fireEvent(trigger, 'pressOut');
+ });
+ await runTimers();
+
+ expect(getByText('some tooltip text')).toBeOnTheScreen();
});
+ });
+
+ describe('keyboard focus', () => {
+ it('shows the tooltip on focus and hides it on blur', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ enterTouchDelay: 500, leaveTouchDelay: 0 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ expect(getByText('some tooltip text')).toBeOnTheScreen();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'blur');
+ });
+ await runTimers(); // leaveTouchDelay → schedules the exit fade
+ await runTimers();
- it('clears the hide timer when the user start hovering the component again', async () => {
- jest.spyOn(global, 'clearTimeout');
+ expect(queryByText('some tooltip text')).not.toBeOnTheScreen();
+ });
+ it("doesn't show the tooltip for the focus a tap gives the trigger", async () => {
const {
- wrapper: { getByText },
+ wrapper: { queryByText },
} = await setup();
- const trigger = getTrigger(getByText);
- await fireEvent(trigger, 'hoverIn');
- await fireEvent(trigger, 'hoverOut');
- await fireEvent(trigger, 'hoverIn');
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerDown', {
+ nativeEvent: { pointerType: 'touch' },
+ });
+ await fireEvent(getTrigger(), 'focus');
+ });
+
+ expect(queryByText('some tooltip text')).toBeNull();
+ });
+
+ it('hides the tooltip on Escape while the trigger keeps focus', async () => {
+ const listeners: Array<
+ (event: { key: string; defaultPrevented: boolean }) => void
+ > = [];
+ Reflect.defineProperty(globalThis, 'document', {
+ value: {
+ addEventListener: (
+ type: string,
+ listener: (event: {
+ key: string;
+ defaultPrevented: boolean;
+ }) => void
+ ) => {
+ if (type === 'keydown') listeners.push(listener);
+ },
+ removeEventListener: () => {},
+ },
+ configurable: true,
+ writable: true,
+ });
+
+ try {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ leaveTouchDelay: 0 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ expect(getByText('some tooltip text')).toBeOnTheScreen();
- expect(global.clearTimeout).toHaveBeenCalledTimes(2);
+ await act(() => {
+ listeners.forEach((listener) =>
+ listener({ key: 'Escape', defaultPrevented: false })
+ );
+ });
+ await runTimers();
+ await runTimers();
+
+ expect(queryByText('some tooltip text')).not.toBeOnTheScreen();
+ } finally {
+ Reflect.deleteProperty(globalThis, 'document');
+ }
});
});
- describe('hoverOut', () => {
- it('hides the tooltip when the user stops hovering the component', async () => {
- const {
- wrapper: { queryByText, getByText, findByText },
- } = await setup({ enterTouchDelay: 50, leaveTouchDelay: 0 });
+ describe('accessibility', () => {
+ it('describes the trigger with the tooltip so it is announced', async () => {
+ await setup({ enterTouchDelay: 0 });
- await fireEvent(getTrigger(getByText), 'hoverIn');
- await runTimers(50);
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ });
+ await runTimers(0);
- await findByText('some tooltip text');
+ // The id comes from `useId`, so the link is checked by reading it back.
+ // eslint-disable-next-line no-restricted-syntax -- cross-check the link
+ const describedBy = getTrigger().props['aria-describedby'];
- await fireEvent(getTrigger(getByText), 'hoverOut');
- await runTimers();
+ expect(describedBy).toEqual(expect.any(String));
+ expect(getTooltipContainer()).toHaveProp('nativeID', describedBy);
+ });
- expect(queryByText('some tooltip text')).not.toBeOnTheScreen();
+ it('names the trigger with the title when titleAsAriaLabel is set', async () => {
+ await setup({ titleAsAriaLabel: true });
+
+ expect(getTrigger()).toHaveAccessibleName('some tooltip text');
+ expect(getTrigger()).not.toHaveProp('aria-describedby');
});
});
@@ -420,10 +772,10 @@ describe('Tooltip', () => {
describe('When it does not overflow', () => {
it('centers the tooltip in the middle of the children component', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup();
- await fireEvent(getTrigger(getByText), 'hoverIn');
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
await runTimers(500);
const tooltip = await findByText('some tooltip text');
@@ -433,9 +785,42 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
+ expect(getTooltipContainer()).toHaveStyle({
left: 210, // pageX (220) + (width (80) - TOOLTIP_WIDTH (100)) / 2 = 210
- top: 250, // pageY (200) + height (50)
+ top: 254, // pageY (200) + height (50) + ANCHOR_GAP (4)
+ });
+ });
+ });
+
+ describe('When the locale is RTL', () => {
+ it('offsets the tooltip from the trailing edge where RTL places it', async () => {
+ jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 220, 200));
+
+ const { findByText } = await render(
+
+
+ {(props: TooltipTriggerProps) => }
+
+
+ );
+
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ await runTimers(500);
+
+ const tooltip = await findByText('some tooltip text');
+ await fireEvent(tooltip, 'layout', {
+ nativeEvent: {
+ layout: { width: TOOLTIP_WIDTH, height: TOOLTIP_HEIGHT },
+ },
+ });
+
+ // `left` is physical on web, but the tooltip starts at the right
+ // edge in RTL, so it moves left by its distance to that edge
+ expect(getTooltipContainer()).toHaveStyle({
+ left: -50, // -(LAYOUT_WIDTH (360) - TOOLTIP_WIDTH (100) - left (210))
+ top: 254,
});
});
});
@@ -443,10 +828,10 @@ describe('Tooltip', () => {
describe('When it overflows to left', () => {
it('renders the tooltip with the right placement', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({}, { pageX: 0 }); // Component starting at the starting 0 X coord
- await fireEvent(getTrigger(getByText), 'hoverIn');
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
await runTimers(500);
const tooltip = await findByText('some tooltip text');
@@ -456,9 +841,9 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
- left: 0, // Tooltip renders starting from children's x coord
- top: 250,
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 8, // Math.max(EDGE_MARGIN=8, pageX=0)
+ top: 254,
});
});
});
@@ -466,10 +851,10 @@ describe('Tooltip', () => {
describe('When it overflows to right', () => {
it('renders the tooltip with the right placement', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({}, { pageX: 900, width: 150 }); // Component close to the screen limit
- await fireEvent(getTrigger(getByText), 'hoverIn');
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
await runTimers(500);
const tooltip = await findByText('some tooltip text');
@@ -479,9 +864,9 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
- left: 950, // pageX (900) + width (150) - 100 (TOOLTIP_WIDTH) // Tooltip is placed from right to left without going offscreen
- top: 250,
+ expect(getTooltipContainer()).toHaveStyle({
+ left: 252, // Math.min(950, LAYOUT_WIDTH(360) - TOOLTIP_WIDTH(100) - EDGE_MARGIN(8))
+ top: 254,
});
});
});
@@ -489,10 +874,10 @@ describe('Tooltip', () => {
describe('When it overflows to bottom', () => {
it('renders the tooltip with the right placement', async () => {
const {
- wrapper: { getByText, findByText },
+ wrapper: { findByText },
} = await setup({}, { pageY: 600, height: 50 });
- await fireEvent(getTrigger(getByText), 'hoverIn');
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
await runTimers(500);
const tooltip = await findByText('some tooltip text');
@@ -502,12 +887,1119 @@ describe('Tooltip', () => {
},
});
- expect(tooltip.parent).toHaveStyle({
+ expect(getTooltipContainer()).toHaveStyle({
left: 210,
- top: 500, // pageY (600) - TOOLTIP_HEIGHT (100) // Tooltip is placed at the top of the component,
+ top: 496, // pageY (600) - ANCHOR_GAP (4) - TOOLTIP_HEIGHT (100): placed above the component
+ });
+ });
+ });
+
+ describe('When the page is scrolled', () => {
+ afterEach(() => {
+ Reflect.deleteProperty(window, 'scrollY');
+ });
+
+ it('stays below the trigger and moves with the page', async () => {
+ Reflect.defineProperty(window, 'scrollY', {
+ value: 1000,
+ configurable: true,
+ });
+ const {
+ wrapper: { findByText },
+ } = await setup();
+
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ await runTimers(500);
+
+ const tooltip = await findByText('some tooltip text');
+ await fireEvent(tooltip, 'layout', {
+ nativeEvent: {
+ layout: { width: TOOLTIP_WIDTH, height: TOOLTIP_HEIGHT },
+ },
+ });
+
+ // `measure` is relative to the viewport, the portal to the document
+ expect(getTooltipContainer()).toHaveStyle({ top: 1254 });
+ });
+ });
+
+ describe('When it is too tall for either side', () => {
+ it('keeps the tooltip on screen at the top edge', async () => {
+ const {
+ wrapper: { findByText },
+ } = await setup({}, { pageY: 60, height: 50 });
+
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ await runTimers(500);
+
+ const tooltip = await findByText('some tooltip text');
+ await fireEvent(tooltip, 'layout', {
+ nativeEvent: { layout: { width: TOOLTIP_WIDTH, height: 700 } },
});
+
+ expect(getTooltipContainer()).toHaveStyle({ top: 8 }); // EDGE_MARGIN
});
});
});
});
});
+
+describe('Tooltip.Rich', () => {
+ const getTrigger = () => screen.getByTestId('trigger');
+
+ // The backdrop is hidden from screen readers
+ const getBackdrop = () =>
+ screen.getByTestId('rich-backdrop', { includeHiddenElements: true });
+
+ const runTimers = async (ms = 1000) => {
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(ms);
+ });
+ };
+
+ let user: ReturnType;
+ beforeEach(() => {
+ user = userEvent.setup();
+ });
+
+ const setup = async (
+ propOverrides?: Partial>
+ ) => {
+ jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 220, 200));
+
+ const wrapper = await render(
+
+
+ {(props) => }
+
+
+ );
+
+ return { wrapper };
+ };
+
+ describe('Mobile', () => {
+ beforeAll(() => {
+ Platform.OS = 'android';
+ });
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('toggles title, content and actions when the trigger is pressed', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({
+ title: 'Heading',
+ actions: () => Learn more,
+ });
+
+ expect(queryByText('Body text')).toBeNull();
+
+ await user.press(getTrigger());
+
+ expect(getByText('Heading')).toBeTruthy();
+ expect(getByText('Body text')).toBeTruthy();
+ expect(getByText('Learn more')).toBeTruthy();
+ await user.press(getTrigger());
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('is a dialog named by its title when it has actions', async () => {
+ await setup({
+ title: 'Heading',
+ actions: () => Learn more,
+ });
+
+ await user.press(getTrigger());
+
+ const tooltip = screen.getByTestId('rich-tooltip');
+ expect(tooltip).toHaveProp('role', 'dialog');
+ expect(tooltip).toHaveAccessibleName('Heading');
+ });
+
+ it('is a dialog named by its content when it has actions but no title', async () => {
+ await setup({ actions: () => Learn more });
+
+ await user.press(getTrigger());
+
+ const tooltip = screen.getByTestId('rich-tooltip');
+ expect(tooltip).toHaveProp('role', 'dialog');
+ expect(tooltip).toHaveAccessibleName('Body text');
+ });
+
+ it('renders a custom element as content', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup({ content: Custom node });
+
+ await user.press(getTrigger());
+
+ expect(getByText('Custom node')).toBeTruthy();
+ });
+
+ it('renders the title and content in the onSurfaceVariant color', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup({ title: 'Heading' });
+
+ await user.press(getTrigger());
+
+ expect(getByText('Heading')).toHaveStyle({
+ color: LightTheme.colors.onSurfaceVariant,
+ });
+ expect(getByText('Body text')).toHaveStyle({
+ color: LightTheme.colors.onSurfaceVariant,
+ });
+ });
+
+ it('dismisses when the backdrop is pressed', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup();
+
+ await user.press(getTrigger());
+ expect(getByText('Body text')).toBeTruthy();
+
+ await user.press(getBackdrop());
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('hides the backdrop from screen readers', async () => {
+ await setup();
+
+ await user.press(getTrigger());
+
+ expect(isHiddenFromAccessibility(getBackdrop())).toBe(true);
+ });
+
+ it('describes the trigger with the title and content', async () => {
+ await setup({ title: 'Heading' });
+
+ expect(screen.getByHintText('Heading. Body text')).toBe(getTrigger());
+ });
+
+ it('opens another tooltip when the backdrop is pressed over its trigger', async () => {
+ // Triggers register their page coordinates, which on Android differ from
+ // the window coordinates, so `measureInWindow` reports a rect to ignore
+ const measure = jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 0, 0));
+ jest
+ .spyOn(ViewPrototype, 'measureInWindow')
+ .mockImplementation((cb) => cb(200, 320, 80, 50));
+
+ const { getAllByText, getByText, queryByText } = await render(
+
+
+ {(props) => }
+
+
+ {(props) => }
+
+
+ );
+ const [firstTrigger, secondTrigger] = getAllByText('dummy component');
+
+ await user.press(firstTrigger);
+ expect(getByText('First tooltip')).toBeTruthy();
+
+ measure.mockImplementation((cb) => cb(0, 0, 80, 50, 200, 400));
+ await fireEvent(secondTrigger, 'layout', {
+ nativeEvent: { layout: { x: 0, y: 0, width: 80, height: 50 } },
+ });
+
+ // userEvent can't set where the press lands
+ await fireEvent(
+ screen.getByTestId('first-backdrop', { includeHiddenElements: true }),
+ 'press',
+ { nativeEvent: { pageX: 240, pageY: 425 } }
+ );
+ await runTimers();
+
+ expect(queryByText('First tooltip')).toBeNull();
+ expect(getByText('Second tooltip')).toBeTruthy();
+ });
+
+ it('dismisses the open tooltip when another tooltip trigger is pressed', async () => {
+ jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 220, 200));
+ jest
+ .spyOn(ViewPrototype, 'measureInWindow')
+ .mockImplementation((cb) => cb(0, 0, 0, 0));
+
+ const { getByText, queryByText } = await render(
+
+
+ {(props) => }
+
+
+ {(props) => }
+
+
+ );
+
+ const [triggerA, triggerB] = screen.getAllByTestId('trigger');
+
+ await user.press(triggerA);
+ expect(getByText('First tooltip')).toBeTruthy();
+
+ await user.press(triggerB);
+ await runTimers();
+
+ expect(queryByText('First tooltip')).toBeNull();
+ expect(getByText('Second tooltip')).toBeTruthy();
+ });
+
+ it('leaves the back button to the screen', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup();
+
+ await user.press(getTrigger());
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(() => {
+ BackHandler.mockPressBack();
+ });
+ await runTimers();
+
+ expect(getByText('Body text')).toBeTruthy();
+ expect(BackHandler.exitApp).toHaveBeenCalled();
+ });
+
+ it('closes on the screen reader escape gesture', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup();
+
+ await user.press(getTrigger());
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(async () => {
+ await fireEvent(
+ screen.getByTestId('rich-tooltip'),
+ 'accessibilityEscape'
+ );
+ });
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('dismisses when an action calls dismiss', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({
+ actions: ({ dismiss }) => Learn more,
+ });
+
+ await user.press(getTrigger());
+ expect(getByText('Body text')).toBeTruthy();
+
+ await user.press(getByText('Learn more'));
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ describe('onDismiss', () => {
+ it('does not fire when the tooltip opens', async () => {
+ const onDismiss = jest.fn();
+ const {
+ wrapper: { getByText },
+ } = await setup({ onDismiss });
+
+ await user.press(getTrigger());
+
+ expect(getByText('Body text')).toBeTruthy();
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('fires when an action calls dismiss', async () => {
+ const onDismiss = jest.fn();
+ const {
+ wrapper: { getByText },
+ } = await setup({
+ onDismiss,
+ actions: ({ dismiss }) => Learn more,
+ });
+
+ await user.press(getTrigger());
+ await user.press(getByText('Learn more'));
+ await runTimers();
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('fires when the backdrop is pressed', async () => {
+ const onDismiss = jest.fn();
+ await setup({ onDismiss });
+
+ await user.press(getTrigger());
+ await user.press(getBackdrop());
+ await runTimers();
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('fires once when the trigger is pressed again', async () => {
+ const onDismiss = jest.fn();
+ await setup({ onDismiss });
+
+ await user.press(getTrigger());
+ await user.press(getTrigger());
+ await runTimers();
+
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+ });
+ });
+
+ describe('Web', () => {
+ beforeAll(() => {
+ Platform.OS = 'web';
+ });
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('opens on hover after the enter delay', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ enterTouchDelay: 100 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ });
+ expect(queryByText('Body text')).toBeNull(); // still within the delay
+
+ await runTimers(100);
+
+ expect(getByText('Body text')).toBeTruthy();
+ });
+
+ it('opens on keyboard focus and hides on blur', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ leaveTouchDelay: 500 });
+
+ // Focus shows the tooltip synchronously, so settle it in act() before
+ // asserting (and so its update can't escape act and corrupt the renderer).
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'blur');
+ });
+ await runTimers(500); // leave delay → hide intent
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('keeps the tooltip open while the pointer moves into it', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup({ enterTouchDelay: 0, leaveTouchDelay: 500 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ });
+ await runTimers(0);
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerLeave', mousePointer);
+ await fireEvent(getByText('Body text'), 'pointerEnter', mousePointer);
+ });
+ await runTimers(500);
+
+ expect(getByText('Body text')).toBeTruthy();
+ });
+
+ it('hides the tooltip after the pointer leaves it', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ enterTouchDelay: 0, leaveTouchDelay: 500 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ });
+ await runTimers(0);
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerLeave', mousePointer);
+ await fireEvent(getByText('Body text'), 'pointerEnter', mousePointer);
+ });
+ await runTimers(500);
+
+ await act(async () => {
+ await fireEvent(getByText('Body text'), 'pointerLeave', mousePointer);
+ });
+ await runTimers(500); // leave delay → hide intent
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('keeps the tooltip open when the keyboard-focused trigger is pressed', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ leaveTouchDelay: 500 });
+
+ const trigger = getTrigger();
+ await act(async () => {
+ await fireEvent(trigger, 'focus');
+ });
+ expect(getByText('Body text')).toBeTruthy();
+
+ // Enter on a focused button presses it, which mustn't close the tooltip
+ // the focus opened
+ await user.press(trigger);
+ await runTimers();
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(async () => {
+ await fireEvent(trigger, 'blur');
+ });
+ await runTimers(500);
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('keeps the tooltip open when the hovered trigger is pressed', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup({ enterTouchDelay: 0, leaveTouchDelay: 500 });
+
+ const trigger = getTrigger();
+ await act(async () => {
+ await fireEvent(trigger, 'pointerEnter', mousePointer);
+ });
+ await runTimers(0);
+ expect(getByText('Body text')).toBeTruthy();
+
+ // The pointer never left the trigger, so the click must not close the
+ // tooltip: nothing would bring it back until the pointer leaves first
+ await user.press(trigger);
+ await runTimers(); // exit fade -> would have unmounted a closed tooltip
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(async () => {
+ await fireEvent(trigger, 'pointerLeave', mousePointer);
+ });
+ await runTimers(500); // leave delay -> hide intent
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('describes the trigger with the tooltip so it is announced', async () => {
+ await setup({ enterTouchDelay: 0 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ });
+ await runTimers(0);
+
+ // The trigger points at the text so it is announced on focus. The id
+ // comes from `useId`, so the link is checked by reading it back.
+ // eslint-disable-next-line no-restricted-syntax -- cross-check the link
+ const describedBy = getTrigger().props['aria-describedby'];
+
+ expect(screen.getByTestId('rich-tooltip')).toHaveProp('role', 'tooltip');
+ expect(screen.getByText('Body text')).toHaveProp('nativeID', describedBy);
+ });
+
+ it('marks the trigger as opening a dialog when the tooltip has actions', async () => {
+ await setup({
+ title: 'Heading',
+ actions: () => Learn more,
+ });
+
+ expect(getTrigger()).toHaveProp('aria-haspopup', 'dialog');
+ expect(getTrigger()).toHaveProp('aria-expanded', false);
+
+ await user.press(getTrigger());
+
+ expect(getTrigger()).toHaveProp('aria-expanded', true);
+ // Described by the title and content, without the action labels
+ const trigger = getTrigger();
+ // eslint-disable-next-line no-restricted-syntax -- cross-check the link
+ const describedBy: string = trigger.props['aria-describedby'];
+ const [titleRef, contentRef, ...rest] = describedBy.split(' ');
+
+ expect(rest).toEqual([]);
+ expect(screen.getByText('Heading')).toHaveProp('nativeID', titleRef);
+ expect(screen.getByText('Body text')).toHaveProp('nativeID', contentRef);
+ });
+
+ it('moves focus into the actions on the down arrow without scrolling the page', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup({ actions: () => Learn more });
+ const preventDefault = jest.fn();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'keyDown', {
+ nativeEvent: { key: 'ArrowDown' },
+ preventDefault,
+ });
+ });
+
+ expect(getByText('Learn more')).toBeTruthy();
+ expect(preventDefault).toHaveBeenCalled();
+ });
+
+ it('opens on keyboard focus after a touch that turned into a scroll', async () => {
+ const {
+ wrapper: { getByText },
+ } = await setup();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerDown', {
+ nativeEvent: { pointerType: 'touch' },
+ });
+ await fireEvent(getTrigger(), 'pointerCancel');
+ await fireEvent(getTrigger(), 'focus');
+ });
+
+ expect(getByText('Body text')).toBeTruthy();
+ });
+
+ it('opens on a tap that also focuses the trigger (touch web)', async () => {
+ const {
+ wrapper: { getByText, queryByText },
+ } = await setup();
+ const touchDown = async () => {
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerDown', {
+ nativeEvent: { pointerType: 'touch' },
+ });
+ });
+ };
+
+ // A tap focuses the trigger before the press, and only the press toggles
+ await touchDown();
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ await user.press(getTrigger());
+ await runTimers();
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ await touchDown();
+ await user.press(getTrigger());
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ it('lets the down arrow scroll the page when the tooltip has no actions', async () => {
+ const preventDefault = jest.fn();
+ const {
+ wrapper: { queryByText },
+ } = await setup();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'keyDown', {
+ nativeEvent: { key: 'ArrowDown' },
+ preventDefault,
+ });
+ });
+
+ expect(preventDefault).not.toHaveBeenCalled();
+ expect(queryByText('Body text')).toBeNull();
+ });
+
+ describe('Escape', () => {
+ // The tooltip listens for Escape on the document, which the native test
+ // renderer has none of: stand in just enough of it, and of the DOM
+ // `contains` and `focus` of the tooltip and the trigger
+ const listeners: Array<
+ (event: { key?: string; defaultPrevented?: boolean }) => void
+ > = [];
+ let activeElement: unknown = null;
+ const focus = jest.fn();
+
+ const pressEscape = async () => {
+ await act(() => {
+ listeners.forEach((listener) =>
+ listener({ key: 'Escape', defaultPrevented: false })
+ );
+ });
+ await runTimers(); // hide intent
+ await runTimers();
+ };
+
+ beforeEach(() => {
+ listeners.length = 0;
+ focus.mockClear();
+ Reflect.defineProperty(globalThis, 'document', {
+ value: {
+ get activeElement() {
+ return activeElement;
+ },
+ addEventListener: (
+ type: string,
+ listener: (event: {
+ key?: string;
+ defaultPrevented?: boolean;
+ }) => void
+ ) => {
+ if (type === 'keydown') listeners.push(listener);
+ },
+ removeEventListener: (type: string) => {
+ if (type === 'keydown') listeners.length = 0;
+ },
+ },
+ configurable: true,
+ writable: true,
+ });
+ // Views stand in for DOM elements: the trigger takes the focus it's
+ // given, and nothing inside it is tabbable
+ Reflect.defineProperty(globalThis, 'HTMLElement', {
+ value: View,
+ configurable: true,
+ });
+ Reflect.defineProperty(ViewPrototype, 'contains', {
+ value(this: unknown, node: unknown) {
+ return node === 'inside' || node === this;
+ },
+ configurable: true,
+ });
+ Reflect.defineProperty(ViewPrototype, 'querySelectorAll', {
+ value: () => [],
+ configurable: true,
+ });
+ focus.mockImplementation(function (this: unknown) {
+ activeElement = this;
+ });
+ Reflect.defineProperty(ViewPrototype, 'focus', {
+ value: focus,
+ configurable: true,
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(globalThis, 'document');
+ Reflect.deleteProperty(globalThis, 'HTMLElement');
+ Reflect.deleteProperty(ViewPrototype, 'contains');
+ Reflect.deleteProperty(ViewPrototype, 'querySelectorAll');
+ Reflect.deleteProperty(ViewPrototype, 'focus');
+ });
+
+ it('opens on the next focus when the trigger refuses the focus it returns', async () => {
+ activeElement = 'inside';
+ focus.mockImplementation(() => {});
+ const {
+ wrapper: { getByText, queryByText, unmount },
+ } = await setup();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ await pressEscape();
+
+ expect(queryByText('Body text')).toBeNull();
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ await unmount();
+ });
+
+ it('closes and returns focus to the trigger without reopening from it', async () => {
+ activeElement = 'inside';
+ const {
+ wrapper: { getByText, queryByText, unmount },
+ } = await setup({ leaveTouchDelay: 500 });
+ const trigger = getTrigger();
+
+ await act(async () => {
+ await fireEvent(trigger, 'focus');
+ });
+ expect(getByText('Body text')).toBeTruthy();
+
+ // As in the browser, `focus()` fires the trigger's focus event right
+ // away, which would open the tooltip again unless it's ignored
+ focus.mockImplementation(function (this: unknown) {
+ activeElement = this;
+ // eslint-disable-next-line no-restricted-syntax -- the event a browser fires
+ trigger.props.onFocus?.();
+ });
+
+ await pressEscape();
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ expect(focus).toHaveBeenCalled();
+
+ // A focus after the pointer or focus has moved elsewhere works again.
+ await act(async () => {
+ await fireEvent(trigger, 'blur');
+ await fireEvent(trigger, 'focus');
+ });
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ // Unmount while the stand-in is still in place: the effect cleanup
+ // removes the Escape listener through it.
+ await unmount();
+ });
+
+ it('returns focus to the trigger when an action closes the tooltip', async () => {
+ activeElement = 'inside';
+ const {
+ wrapper: { getByText, queryByText, unmount },
+ } = await setup({
+ actions: ({ dismiss }) => Learn more,
+ });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ await user.press(getByText('Learn more'));
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+ expect(focus).toHaveBeenCalled();
+
+ await unmount();
+ });
+
+ it('stays open when the pointer leaves while focus is inside it', async () => {
+ activeElement = 'inside';
+ const {
+ wrapper: { getByText, unmount },
+ } = await setup({ leaveTouchDelay: 500 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+ await act(async () => {
+ await fireEvent(getByText('Body text'), 'pointerEnter', mousePointer);
+ await fireEvent(getByText('Body text'), 'pointerLeave', mousePointer);
+ });
+ await runTimers(500); // leave delay → hide intent
+ await runTimers();
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ await unmount();
+ });
+
+ it('leaves focus that is outside the tooltip and the trigger alone', async () => {
+ activeElement = 'elsewhere';
+ const {
+ wrapper: { getByText, queryByText, unmount },
+ } = await setup({ enterTouchDelay: 0 });
+
+ await act(async () => {
+ await fireEvent(getTrigger(), 'pointerEnter', mousePointer);
+ });
+ await runTimers(0);
+ expect(getByText('Body text')).toBeTruthy();
+
+ await pressEscape();
+
+ expect(queryByText('Body text')).toBeNull();
+ expect(focus).not.toHaveBeenCalled();
+
+ await unmount();
+ });
+ });
+
+ describe('Tab out of the tooltip', () => {
+ // Views stand in for DOM elements: the tooltip holds two actions, and
+ // the page has the trigger's own element followed by the next one
+ const firstAction = Object.create(ViewPrototype);
+ const lastAction = Object.create(ViewPrototype);
+ const triggerElement = Object.create(ViewPrototype);
+ const nextElement = Object.create(ViewPrototype);
+ let tooltipNode: unknown = null;
+ let activeElement: unknown = null;
+ const focus = jest.fn(function (this: unknown) {
+ activeElement = this;
+ });
+
+ const pressTab = async (shiftKey = false) => {
+ const preventDefault = jest.fn();
+ await act(async () => {
+ await fireEvent(screen.getByText('Body text'), 'keyDown', {
+ nativeEvent: { key: 'Tab', shiftKey },
+ preventDefault,
+ });
+ });
+ return preventDefault;
+ };
+
+ beforeEach(() => {
+ activeElement = null;
+ tooltipNode = null;
+ focus.mockClear();
+ Reflect.defineProperty(globalThis, 'document', {
+ value: {
+ get activeElement() {
+ return activeElement;
+ },
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ },
+ configurable: true,
+ writable: true,
+ });
+ Reflect.defineProperty(globalThis, 'HTMLElement', {
+ value: View,
+ configurable: true,
+ });
+ Reflect.defineProperty(ViewPrototype, 'contains', {
+ value(this: unknown, node: unknown) {
+ if (this === tooltipNode) {
+ return node === firstAction || node === lastAction;
+ }
+ return node === this || node === triggerElement;
+ },
+ configurable: true,
+ });
+ Reflect.defineProperty(ViewPrototype, 'querySelectorAll', {
+ value: () => [],
+ configurable: true,
+ });
+ Reflect.defineProperty(ViewPrototype, 'focus', {
+ value: focus,
+ configurable: true,
+ });
+ jest
+ .spyOn(overlayFocus, 'getTabbables')
+ .mockImplementation((container) => {
+ if (container === document) {
+ return [triggerElement, nextElement];
+ }
+ tooltipNode = container;
+ return [firstAction, lastAction];
+ });
+ });
+
+ afterEach(() => {
+ Reflect.deleteProperty(globalThis, 'document');
+ Reflect.deleteProperty(globalThis, 'HTMLElement');
+ Reflect.deleteProperty(ViewPrototype, 'contains');
+ Reflect.deleteProperty(ViewPrototype, 'querySelectorAll');
+ Reflect.deleteProperty(ViewPrototype, 'focus');
+ });
+
+ it('moves Tab past the last element to the element after the trigger', async () => {
+ const {
+ wrapper: { unmount },
+ } = await setup();
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+
+ activeElement = lastAction;
+ const preventDefault = await pressTab();
+
+ expect(preventDefault).toHaveBeenCalled();
+ expect(activeElement).toBe(nextElement);
+
+ await unmount();
+ });
+
+ it('moves Shift+Tab past the first element back to the trigger', async () => {
+ const {
+ wrapper: { unmount },
+ } = await setup();
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+
+ activeElement = firstAction;
+ const preventDefault = await pressTab(true);
+
+ expect(preventDefault).toHaveBeenCalled();
+ expect(focus).toHaveBeenCalled();
+ expect(activeElement).not.toBe(firstAction);
+
+ await unmount();
+ });
+
+ it('leaves Tab between the elements inside the tooltip to the browser', async () => {
+ const {
+ wrapper: { unmount },
+ } = await setup();
+ await act(async () => {
+ await fireEvent(getTrigger(), 'focus');
+ });
+
+ activeElement = firstAction;
+ const preventDefault = await pressTab();
+
+ expect(preventDefault).not.toHaveBeenCalled();
+ expect(activeElement).toBe(firstAction);
+
+ await unmount();
+ });
+ });
+
+ it('closes on a press outside the tooltip and the trigger', async () => {
+ // A tap doesn't always focus the trigger (buttons in Safari), so blur
+ // can't be relied on: the tooltip listens for presses on the document
+ const listeners: Array<(event: { target: unknown }) => void> = [];
+ Reflect.defineProperty(globalThis, 'document', {
+ value: {
+ addEventListener: (
+ type: string,
+ listener: (event: { target: unknown }) => void
+ ) => {
+ if (type === 'pointerdown') listeners.push(listener);
+ },
+ removeEventListener: (type: string) => {
+ if (type === 'pointerdown') listeners.length = 0;
+ },
+ },
+ configurable: true,
+ writable: true,
+ });
+
+ // Stand-in for the DOM `contains` of the tooltip and the trigger
+ Reflect.defineProperty(ViewPrototype, 'contains', {
+ value: (node: unknown) => node === 'inside',
+ configurable: true,
+ });
+
+ try {
+ const {
+ wrapper: { getByText, queryByText, unmount },
+ } = await setup();
+
+ await user.press(getTrigger());
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(() => {
+ listeners.forEach((listener) => listener({ target: 'inside' }));
+ });
+ await runTimers();
+
+ expect(getByText('Body text')).toBeTruthy();
+
+ await act(() => {
+ listeners.forEach((listener) => listener({ target: null }));
+ });
+ await runTimers();
+
+ expect(queryByText('Body text')).toBeNull();
+
+ await unmount();
+ } finally {
+ Reflect.deleteProperty(globalThis, 'document');
+ Reflect.deleteProperty(ViewPrototype, 'contains');
+ }
+ });
+ });
+});
+
+describe('singleton slot', () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('dismisses the tooltip holding the slot when another takes it', () => {
+ const first = jest.fn();
+ takeSingletonSlot(first);
+ takeSingletonSlot(jest.fn());
+
+ expect(first).toHaveBeenCalledTimes(1);
+ });
+
+ it('forgets a released tooltip', () => {
+ const first = jest.fn();
+ takeSingletonSlot(first);
+ releaseSingletonSlot(first);
+ takeSingletonSlot(jest.fn());
+
+ expect(first).not.toHaveBeenCalled();
+ });
+
+ it("keeps the slot when a tooltip that doesn't hold it releases", () => {
+ const first = jest.fn();
+ const second = jest.fn();
+ takeSingletonSlot(first);
+ releaseSingletonSlot(second);
+ takeSingletonSlot(jest.fn());
+
+ expect(first).toHaveBeenCalledTimes(1);
+ });
+
+ type Trigger = (props: TooltipTriggerProps) => React.ReactElement;
+
+ it.each<[string, (children: Trigger) => React.ReactElement]>([
+ [
+ 'Tooltip',
+ (children) => {children},
+ ],
+ [
+ 'Tooltip.Rich',
+ (children) => (
+
+ {children}
+
+ ),
+ ],
+ ])(
+ '%s releases the slot it took when it unmounts',
+ async (_, renderTooltip) => {
+ jest.replaceProperty(Platform, 'OS', 'web');
+ jest
+ .spyOn(ViewPrototype, 'measure')
+ .mockImplementation((cb) => cb(0, 0, 80, 50, 220, 200));
+ const take = jest.spyOn(registry, 'takeSingletonSlot');
+ const release = jest.spyOn(registry, 'releaseSingletonSlot');
+
+ const { unmount } = await render(
+
+ {renderTooltip((props) => (
+
+ ))}
+
+ );
+
+ await act(async () => {
+ await fireEvent(
+ screen.getByTestId('trigger', { includeHiddenElements: true }),
+ 'focus'
+ );
+ });
+
+ expect(take).toHaveBeenCalledTimes(1);
+ await act(() => unmount());
+
+ expect(release).toHaveBeenCalledWith(take.mock.calls[0][0]);
+ }
+ );
+});
diff --git a/src/index.tsx b/src/index.tsx
index 2b0614c8cc..5f3339f1b8 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -50,7 +50,7 @@ export { default as Appbar } from './components/Appbar';
export { default as TouchableRipple } from './components/TouchableRipple/TouchableRipple';
export { default as TextInput } from './components/TextInput';
export { default as SegmentedButtons } from './components/SegmentedButtons/SegmentedButtons';
-export { default as Tooltip } from './components/Tooltip/Tooltip';
+export { default as Tooltip } from './components/Tooltip';
export { default as Text, customText } from './components/Typography/Text';
@@ -147,7 +147,14 @@ export type { Props as TouchableRippleProps } from './components/TouchableRipple
export type { Props as TextProps } from './components/Typography/Text';
export type { Props as SegmentedButtonsProps } from './components/SegmentedButtons/SegmentedButtons';
export type { Props as ListImageProps } from './components/List/ListImage';
-export type { Props as TooltipProps } from './components/Tooltip/Tooltip';
+export type {
+ Props as TooltipProps,
+ TooltipTriggerProps,
+} from './components/Tooltip/Tooltip';
+export type {
+ Props as TooltipRichProps,
+ TooltipRichTriggerProps,
+} from './components/Tooltip/RichTooltip';
export { type TypescaleKey, type Theme, type Elevation } from './theme/types';
export type { ReduceMotionPreference } from './core/useResolvedReduceMotion';
diff --git a/src/utils/useOverlayFocus.tsx b/src/utils/useOverlayFocus.tsx
index dc6e304a28..a0863a5c3a 100644
--- a/src/utils/useOverlayFocus.tsx
+++ b/src/utils/useOverlayFocus.tsx
@@ -19,10 +19,14 @@ const isVisible = (element: HTMLElement) =>
element.getClientRects().length > 0 &&
getComputedStyle(element).visibility !== 'hidden';
-const findFirstTabbable = (container: HTMLElement) =>
- Array.from(container.querySelectorAll(TABBABLE_SELECTOR)).find(
+// Web only: the visible elements `Tab` reaches inside `container`, in order
+export const getTabbables = (container: ParentNode) =>
+ Array.from(container.querySelectorAll(TABBABLE_SELECTOR)).filter(
isVisible
- ) ?? null;
+ );
+
+const findFirstTabbable = (container: HTMLElement) =>
+ getTabbables(container)[0] ?? null;
/**
* Anything that can take focus: a host element, or the handle of a component
@@ -69,11 +73,24 @@ const moveWebFocusTo = (target: OverlayFocusTarget | null) => {
return false;
};
-// The first element inside, or the container itself when nothing in it can
-// take focus.
+/**
+ * Web only: focuses the first element inside, or the container itself when
+ * nothing in it can take focus. Returns whether focus ended up inside, as the
+ * browser refuses it on a container that can't be focused.
+ */
+export const focusIntoContainer = (container: unknown) => {
+ if (!(container instanceof HTMLElement)) {
+ return false;
+ }
+
+ (findFirstTabbable(container) ?? container).focus();
+
+ return isFocusInside(container);
+};
+
const moveWebFocusIntoContainer = (container: OverlayFocusTarget | null) => {
if (container instanceof HTMLElement) {
- (findFirstTabbable(container) ?? container).focus();
+ focusIntoContainer(container);
return true;
}