From ced43e6fa74f60d619919c7a7f8d82f494979686 Mon Sep 17 00:00:00 2001 From: Goga Koreli <12997449+gogakoreli@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:07 +0000 Subject: [PATCH 1/2] fix: remove a tooltip that closes before it shows A tooltip is rendered first and shown 10ms later. The fallback that removes a closed tooltip was armed when `show` changed, so a tooltip that closed before that timer ran, or that a controlled `isOpen` never let show, stayed in the DOM with the closing class. Removal now has its own hook with one rule: a tooltip that is neither showing nor asked to show leaves the DOM. The timer and the transition end only mark the removal as due, and it is carried out where `show` is current. A tooltip that is hovered again while it closes is no longer removed just before it shows. Refs #1292 --- src/components/Tooltip/Tooltip.tsx | 62 ++-- .../Tooltip/use-tooltip-removal.tsx | 97 +++++++ src/test/tooltip-removal.spec.js | 268 ++++++++++++++++++ 3 files changed, 383 insertions(+), 44 deletions(-) create mode 100644 src/components/Tooltip/use-tooltip-removal.tsx create mode 100644 src/test/tooltip-removal.spec.js diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx index 149bd30e..98568d89 100644 --- a/src/components/Tooltip/Tooltip.tsx +++ b/src/components/Tooltip/Tooltip.tsx @@ -9,22 +9,15 @@ import React, { } from 'react' import { createPortal } from 'react-dom' import clsx from 'clsx' -import { - useIsomorphicLayoutEffect, - computeTooltipPosition, - cssTimeToMs, - clearTimeoutRef, -} from '../../utils' +import { useIsomorphicLayoutEffect, computeTooltipPosition, clearTimeoutRef } from '../../utils' import type { IComputedPosition } from '../../utils' import coreStyles from './core-styles.module.css' import styles from './styles.module.css' import useTooltipAnchors from './use-tooltip-anchors' import useTooltipEvents from './use-tooltip-events' +import useTooltipRemoval from './use-tooltip-removal' import type { IPosition, ITooltip, TooltipImperativeOpenOptions } from './TooltipTypes' -// Shared across all tooltip instances — the CSS variable is on :root and never changes per-instance -let globalTransitionShowDelay: number | null = null - const Tooltip = ({ // props forwardRef, @@ -76,13 +69,13 @@ const Tooltip = ({ const tooltipShowDelayTimerRef = useRef(null) const tooltipHideDelayTimerRef = useRef(null) const tooltipAutoCloseTimerRef = useRef(null) - const missedTransitionTimerRef = useRef(null) const [computedPosition, setComputedPosition] = useState({ tooltipStyles: {}, tooltipArrowStyles: {}, place, }) const [show, setShow] = useState(false) + const [showRequested, setShowRequested] = useState(false) const [rendered, setRendered] = useState(false) const [imperativeOptions, setImperativeOptions] = useState( null, @@ -121,6 +114,7 @@ const Tooltip = ({ if (!mounted.current) { return } + setShowRequested(value) if (value) { setRendered(true) } @@ -199,33 +193,23 @@ const Tooltip = ({ if (show === wasShowing.current) { return } - clearTimeoutRef(missedTransitionTimerRef) wasShowing.current = show if (show) { afterShow?.() - } else { - /** - * see `onTransitionEnd` on tooltip wrapper - */ - if (globalTransitionShowDelay === null) { - const style = getComputedStyle(document.body) - globalTransitionShowDelay = cssTimeToMs( - style.getPropertyValue('--rt-transition-show-delay'), - ) - } - const transitionShowDelay = globalTransitionShowDelay - missedTransitionTimerRef.current = setTimeout(() => { - /** - * if the tooltip switches from `show === true` to `show === false` too fast - * the transition never runs, so `onTransitionEnd` callback never gets fired - */ - setRendered(false) - setImperativeOptions(null) - afterHide?.() - // +25ms just to make sure `onTransitionEnd` (if it gets fired) has time to run - }, transitionShowDelay + 25) } - }, [afterHide, afterShow, show]) + }, [afterShow, show]) + + const handleTransitionEnd = useTooltipRemoval({ + rendered, + show, + // a controlled tooltip shows when `isOpen` says so, whatever was requested + showRequested: isOpen === undefined ? showRequested : isOpen, + afterHide, + onRemove: () => { + setRendered(false) + setImperativeOptions(null) + }, + }) useEffect(() => { clearTimeoutRef(tooltipAutoCloseTimerRef) @@ -550,7 +534,6 @@ const Tooltip = ({ clearTimeoutRef(tooltipShowDelayTimerRef) clearTimeoutRef(tooltipHideDelayTimerRef) clearTimeoutRef(tooltipAutoCloseTimerRef) - clearTimeoutRef(missedTransitionTimerRef) } }, [defaultIsOpen, handleShow]) @@ -639,7 +622,6 @@ const Tooltip = ({ clearTimeoutRef(tooltipShowDelayTimerRef) clearTimeoutRef(tooltipHideDelayTimerRef) clearTimeoutRef(tooltipAutoCloseTimerRef) - clearTimeoutRef(missedTransitionTimerRef) } }, []) @@ -660,15 +642,7 @@ const Tooltip = ({ positionStrategy === 'fixed' && coreStyles['fixed'], clickable && coreStyles['clickable'], )} - onTransitionEnd={(event: TransitionEvent) => { - clearTimeoutRef(missedTransitionTimerRef) - if (show || event.propertyName !== 'opacity') { - return - } - setRendered(false) - setImperativeOptions(null) - afterHide?.() - }} + onTransitionEnd={handleTransitionEnd} style={tooltipStyle} ref={tooltipRef} > diff --git a/src/components/Tooltip/use-tooltip-removal.tsx b/src/components/Tooltip/use-tooltip-removal.tsx new file mode 100644 index 00000000..aa07a55c --- /dev/null +++ b/src/components/Tooltip/use-tooltip-removal.tsx @@ -0,0 +1,97 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { cssTimeToMs, useIsomorphicLayoutEffect } from '../../utils' + +// Shared across all tooltip instances — the CSS variable is on :root and never changes per-instance +let globalTransitionShowDelay: number | null = null + +const getMissedTransitionDelay = () => { + if (globalTransitionShowDelay === null) { + const style = getComputedStyle(document.body) + globalTransitionShowDelay = cssTimeToMs(style.getPropertyValue('--rt-transition-show-delay')) + } + // +25ms just to make sure `onTransitionEnd` (if it gets fired) has time to run + return globalTransitionShowDelay + 25 +} + +/** + * Takes a tooltip out of the DOM once it is neither showing nor asked to show, + * and calls `afterHide` if it had shown. + * + * The tooltip is rendered a moment before it shows, and stays rendered while it fades out. + * The closing transition ends that (see the returned `onTransitionEnd` handler). + * A timer ends it when no transition runs: + * - the tooltip showed and closed too fast for the transition to start + * - the tooltip closed before it showed, so `show` never changed + * - a controlled `isOpen` never let the tooltip show + */ +const useTooltipRemoval = ({ + rendered, + show, + showRequested, + afterHide, + onRemove, +}: { + rendered: boolean + show: boolean + /** the tooltip was asked to show, and `show` follows a moment later */ + showRequested: boolean + afterHide?: () => void + onRemove: () => void +}) => { + /** + * the timer and the transition end only mark the removal as due. + * either can run in the same turn as a request to show that has not rendered yet, + * and removing the tooltip right there would take it out just as it shows again + */ + const [removalDue, setRemovalDue] = useState(false) + // the tooltip showed, and `afterHide` has not been called for it yet + const afterHidePending = useRef(false) + + useEffect(() => { + if (show) { + afterHidePending.current = true + } + }, [show]) + + useEffect(() => { + if (show || showRequested || (!rendered && !afterHidePending.current)) { + return undefined + } + const timer = setTimeout(() => { + setRemovalDue(true) + }, getMissedTransitionDelay()) + return () => { + clearTimeout(timer) + } + }, [rendered, show, showRequested]) + + /** + * `show` and `showRequested` are current here, so this is where a due removal + * is carried out or dropped. a layout effect, so the tooltip is gone before the next paint + */ + useIsomorphicLayoutEffect(() => { + if (!removalDue) { + return + } + setRemovalDue(false) + if (show || showRequested) { + return + } + onRemove() + if (afterHidePending.current) { + afterHidePending.current = false + afterHide?.() + } + }, [removalDue, show, showRequested, onRemove, afterHide]) + + return useCallback( + (event: TransitionEvent) => { + if (!show && event.propertyName === 'opacity') { + setRemovalDue(true) + } + }, + [show], + ) +} + +export default useTooltipRemoval diff --git a/src/test/tooltip-removal.spec.js b/src/test/tooltip-removal.spec.js new file mode 100644 index 00000000..166280be --- /dev/null +++ b/src/test/tooltip-removal.spec.js @@ -0,0 +1,268 @@ +import React, { createRef, useState } from 'react' +import { act, render, screen, fireEvent, waitFor } from '@testing-library/react' +import '@testing-library/jest-dom' +import { TooltipController } from '../components/TooltipController' +import { + advanceTimers, + flushPendingTimers, + hoverAnchor, + unhoverAnchor, + waitForTooltip, +} from './test-utils' +import { installMockMutationObserver } from './mutation-observer-test-utils' + +jest.mock('@floating-ui/dom', () => { + const originalModule = jest.requireActual('@floating-ui/dom') + return { + ...originalModule, + autoUpdate: jest.fn(() => jest.fn()), + } +}) + +const TOOLTIP_ID = 'removal-test' +// the tooltip is rendered at once and shows 10ms later +const SHOW_TIMER_MS = 10 +// long enough for a tooltip that is not showing to leave the DOM +const REMOVAL_MS = 500 + +const getTooltip = () => document.getElementById(TOOLTIP_ID) + +const fireOpacityTransitionEnd = (tooltip) => { + const transitionEndEvent = new Event('transitionend', { bubbles: true }) + Object.defineProperty(transitionEndEvent, 'propertyName', { value: 'opacity' }) + fireEvent(tooltip, transitionEndEvent) +} + +const expectTooltipToShow = async (tooltip) => { + await waitFor(() => { + expect(getTooltip()).toHaveClass('react-tooltip__show') + }) + // the same element all along, not one that was removed and rendered again + expect(getTooltip()).toBe(tooltip) +} + +const TestTooltip = ({ tooltipRef, ...tooltipProps }) => ( + <> + Hover Me + + +) + +describe('tooltip removal', () => { + let mutationObserverController + + beforeEach(() => { + jest.useFakeTimers() + jest.clearAllMocks() + mutationObserverController = installMockMutationObserver() + }) + + afterEach(() => { + flushPendingTimers() + mutationObserverController.restore() + jest.useRealTimers() + }) + + test('removes a tooltip that is opened and closed in the same turn', () => { + const afterShow = jest.fn() + const afterHide = jest.fn() + const tooltipRef = createRef() + + render() + + act(() => { + tooltipRef.current.open() + tooltipRef.current.close() + }) + expect(getTooltip()).toBeInTheDocument() + + advanceTimers(SHOW_TIMER_MS) + expect(getTooltip()).not.toHaveClass('react-tooltip__show') + + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + // it never showed, so there is no show to report, and no hide after it + expect(afterShow).not.toHaveBeenCalled() + expect(afterHide).not.toHaveBeenCalled() + }) + + test('removes a tooltip that is closed while its show timer is pending, when both timers run in the same turn', () => { + const tooltipRef = createRef() + + render() + + act(() => { + tooltipRef.current.open() + }) + advanceTimers(SHOW_TIMER_MS - 5) + act(() => { + tooltipRef.current.close() + }) + expect(getTooltip()).toBeInTheDocument() + + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + }) + + test('removes a controlled tooltip that is closed before it shows', () => { + const { rerender } = render() + + rerender() + advanceTimers(SHOW_TIMER_MS - 5) + rerender() + expect(getTooltip()).toBeInTheDocument() + + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + }) + + test('removes a tooltip that a controlled `isOpen={false}` keeps from showing', () => { + render() + + hoverAnchor(screen.getByText('Hover Me'), SHOW_TIMER_MS) + expect(getTooltip()).toBeInTheDocument() + expect(getTooltip()).not.toHaveClass('react-tooltip__show') + + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + }) + + test('removes a closing tooltip after a transition ends for another CSS property', async () => { + const afterHide = jest.fn() + + render() + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + const tooltip = await waitForTooltip(TOOLTIP_ID) + + unhoverAnchor(anchor, 20) + const transitionEndEvent = new Event('transitionend', { bubbles: true }) + Object.defineProperty(transitionEndEvent, 'propertyName', { value: 'transform' }) + fireEvent(tooltip, transitionEndEvent) + expect(getTooltip()).toBeInTheDocument() + + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + expect(afterHide).toHaveBeenCalledTimes(1) + }) + + test('calls afterHide once when the anchor of a showing tooltip is removed', async () => { + const afterHide = jest.fn() + const AnchorRemovalTest = () => { + const [hasAnchor, setHasAnchor] = useState(true) + + return ( + <> + {hasAnchor && Hover Me} + + + + ) + } + + render() + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + await waitForTooltip(TOOLTIP_ID) + + fireEvent.click(screen.getByText('Remove Anchor')) + mutationObserverController.triggerAll([ + { type: 'childList', removedNodes: [anchor], addedNodes: [] }, + ]) + // the tooltip leaves the DOM with its anchor, and stops showing a moment later + advanceTimers(50) + advanceTimers(50) + expect(getTooltip()).not.toBeInTheDocument() + + advanceTimers(REMOVAL_MS) + expect(afterHide).toHaveBeenCalledTimes(1) + }) + + test('does not call afterHide when unmounted while the removal is pending', async () => { + const afterHide = jest.fn() + const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}) + + const { unmount } = render() + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + await waitForTooltip(TOOLTIP_ID) + unhoverAnchor(anchor, SHOW_TIMER_MS + 5) + + unmount() + advanceTimers(REMOVAL_MS) + + expect(afterHide).not.toHaveBeenCalled() + expect(consoleError).not.toHaveBeenCalled() + consoleError.mockRestore() + }) + + /** + * In the tests below the tooltip is hovered again while it closes, + * and what removes it runs before the tooltip shows again. + */ + test('keeps a tooltip that is hovered again just before its closing transition ends', async () => { + const afterHide = jest.fn() + + render() + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + const tooltip = await waitForTooltip(TOOLTIP_ID) + + unhoverAnchor(anchor, SHOW_TIMER_MS + 5) + expect(tooltip).toHaveClass('react-tooltip__closing') + + // the show timer is still pending when the transition ends + hoverAnchor(anchor) + fireOpacityTransitionEnd(tooltip) + advanceTimers(REMOVAL_MS) + + await expectTooltipToShow(tooltip) + expect(afterHide).not.toHaveBeenCalled() + }) + + test('keeps a tooltip that is hovered again while closing, when its show timer and its removal timer run in the same turn', async () => { + const afterHide = jest.fn() + + render() + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + const tooltip = await waitForTooltip(TOOLTIP_ID) + + // long enough to stop showing, too short for the removal to come due + unhoverAnchor(anchor, SHOW_TIMER_MS + 5) + expect(tooltip).toHaveClass('react-tooltip__closing') + + hoverAnchor(anchor, REMOVAL_MS) + + await expectTooltipToShow(tooltip) + expect(afterHide).not.toHaveBeenCalled() + }) + + test('keeps a tooltip that is hovered again while closing, when its show timer and its transition end run in the same turn', async () => { + const afterHide = jest.fn() + + render() + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + const tooltip = await waitForTooltip(TOOLTIP_ID) + + unhoverAnchor(anchor, SHOW_TIMER_MS + 5) + expect(tooltip).toHaveClass('react-tooltip__closing') + + act(() => { + fireEvent.mouseEnter(anchor) + jest.advanceTimersByTime(SHOW_TIMER_MS) + fireOpacityTransitionEnd(tooltip) + }) + advanceTimers(REMOVAL_MS) + + await expectTooltipToShow(tooltip) + expect(afterHide).not.toHaveBeenCalled() + }) +}) From bd8525c86c2893efafa53a7e74f68d66963ce389 Mon Sep 17 00:00:00 2001 From: Goga Koreli <12997449+gogakoreli@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:00:11 +0000 Subject: [PATCH 2/2] fix: ignore the pointer on a clickable tooltip that is not showing A clickable tooltip took pointer events from the moment it was rendered: before it was positioned, before it was visible, and while it faded out. An invisible tooltip in the top-left corner could be hovered and clicked. Refs #1292 --- src/components/Tooltip/core-styles.module.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/components/Tooltip/core-styles.module.css b/src/components/Tooltip/core-styles.module.css index df740e63..2451c9f7 100644 --- a/src/components/Tooltip/core-styles.module.css +++ b/src/components/Tooltip/core-styles.module.css @@ -27,7 +27,8 @@ display: none; } -.clickable { +/* only while it shows: a tooltip that is not showing is invisible and must not take the pointer */ +.clickable.show { pointer-events: auto; }