diff --git a/src/components/Tooltip/Tooltip.tsx b/src/components/Tooltip/Tooltip.tsx index 98568d89..c339a50e 100644 --- a/src/components/Tooltip/Tooltip.tsx +++ b/src/components/Tooltip/Tooltip.tsx @@ -208,7 +208,13 @@ const Tooltip = ({ onRemove: () => { setRendered(false) setImperativeOptions(null) + // a tooltip that is not in the DOM is not under the pointer, + // even when it left the DOM without a `mouseout` + hoveringTooltip.current = false + // and a hide that was waiting for the pointer has nothing left to close + clearTimeoutRef(tooltipHideDelayTimerRef) }, + tooltipRef, }) useEffect(() => { @@ -394,6 +400,8 @@ const Tooltip = ({ ]) const handleActiveAnchorRemoved = useCallback(() => { + // the tooltip leaves the DOM here too, so it is no longer under the pointer + hoveringTooltip.current = false setRendered(false) handleShow(false) setActiveAnchor(null) diff --git a/src/components/Tooltip/use-tooltip-events.tsx b/src/components/Tooltip/use-tooltip-events.tsx index 4f030043..74e1d15e 100644 --- a/src/components/Tooltip/use-tooltip-events.tsx +++ b/src/components/Tooltip/use-tooltip-events.tsx @@ -534,6 +534,7 @@ const useTooltipEvents = ({ return } handleShowRef.current(false) + clearTimeoutRef(tooltipShowDelayTimerRef) } if (actualGlobalCloseEvents.escape) { window.addEventListener('keydown', handleEsc) diff --git a/src/components/Tooltip/use-tooltip-removal.tsx b/src/components/Tooltip/use-tooltip-removal.tsx index aa07a55c..5ec3ffd5 100644 --- a/src/components/Tooltip/use-tooltip-removal.tsx +++ b/src/components/Tooltip/use-tooltip-removal.tsx @@ -1,16 +1,21 @@ import { useCallback, useEffect, useRef, useState } from 'react' +import type { RefObject } 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')) - } +/** + * the removal waits as long as the closing transition takes. + * read on the tooltip, where the transition runs, + * so the variable can be set on the tooltip or on any of its ancestors + */ +const getMissedTransitionDelay = (tooltip: HTMLElement | null) => { + const style = getComputedStyle(tooltip ?? document.body) + // a custom property keeps an expression such as `calc()` as written, which reads as 0 here. + // the closing transition that uses it has it resolved + const delay = + cssTimeToMs(style.getPropertyValue('--rt-transition-closing-delay').trim()) || + cssTimeToMs(style.transitionDuration.split(',')[0].trim()) // +25ms just to make sure `onTransitionEnd` (if it gets fired) has time to run - return globalTransitionShowDelay + 25 + return delay + 25 } /** @@ -30,6 +35,7 @@ const useTooltipRemoval = ({ showRequested, afterHide, onRemove, + tooltipRef, }: { rendered: boolean show: boolean @@ -37,6 +43,7 @@ const useTooltipRemoval = ({ showRequested: boolean afterHide?: () => void onRemove: () => void + tooltipRef: RefObject }) => { /** * the timer and the transition end only mark the removal as due. @@ -59,11 +66,11 @@ const useTooltipRemoval = ({ } const timer = setTimeout(() => { setRemovalDue(true) - }, getMissedTransitionDelay()) + }, getMissedTransitionDelay(tooltipRef.current)) return () => { clearTimeout(timer) } - }, [rendered, show, showRequested]) + }, [rendered, show, showRequested, tooltipRef]) /** * `show` and `showRequested` are current here, so this is where a due removal @@ -86,7 +93,8 @@ const useTooltipRemoval = ({ return useCallback( (event: TransitionEvent) => { - if (!show && event.propertyName === 'opacity') { + // the tooltip's own fade, not a transition inside its content that bubbled up + if (!show && event.target === event.currentTarget && event.propertyName === 'opacity') { setRemovalDue(true) } }, diff --git a/src/test/tooltip-close-and-delay-behavior.spec.js b/src/test/tooltip-close-and-delay-behavior.spec.js index 37cd5a31..85337de1 100644 --- a/src/test/tooltip-close-and-delay-behavior.spec.js +++ b/src/test/tooltip-close-and-delay-behavior.spec.js @@ -1,5 +1,5 @@ import React, { useState } from 'react' -import { render, screen, fireEvent } from '@testing-library/react' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' import '@testing-library/jest-dom' import { TooltipController } from '../components/TooltipController' import { @@ -335,6 +335,66 @@ describe('tooltip close and delay behavior', () => { expect(document.getElementById('cancel-show-timer-test')).not.toBeInTheDocument() }) + test('cancels a pending show timer on Escape when configured globally', () => { + render( + <> + Hover Me + + , + ) + + hoverAnchor(screen.getByText('Hover Me')) + advanceTimers(40) + fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' }) + advanceTimers(200) + + expect(document.getElementById('escape-cancels-show-timer-test')).not.toBeInTheDocument() + }) + + test('closes a clickable tooltip on leaving its anchor after Escape closed one under the pointer', async () => { + render( + <> + Hover Me + + , + ) + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + const tooltip = await waitForTooltip('escape-on-tooltip-test') + await waitFor(() => { + expect(tooltip).toHaveClass('react-tooltip__show') + }) + // the pointer moves onto the tooltip, and Escape removes the tooltip from under it + unhoverAnchor(anchor) + fireEvent.mouseOver(tooltip) + fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' }) + advanceTimers(500) + advanceTimers(500) + expect(document.getElementById('escape-on-tooltip-test')).not.toBeInTheDocument() + + hoverAnchor(anchor, 100) + await waitFor(() => { + expect(document.getElementById('escape-on-tooltip-test')).toHaveClass('react-tooltip__show') + }) + unhoverAnchor(anchor) + advanceTimers(500) + // Second advancement needed: the first fires handleShow(false) timeout, + // which creates the missedTransitionTimer during the effect flush + advanceTimers(500) + expect(document.getElementById('escape-on-tooltip-test')).not.toBeInTheDocument() + }) + test('does not close on non-Escape keys', async () => { render( <> diff --git a/src/test/tooltip-closing-transition.spec.js b/src/test/tooltip-closing-transition.spec.js new file mode 100644 index 00000000..085c9193 --- /dev/null +++ b/src/test/tooltip-closing-transition.spec.js @@ -0,0 +1,91 @@ +import React from 'react' +import { render, screen, waitFor } from '@testing-library/react' +import '@testing-library/jest-dom' +import { TooltipController } from '../components/TooltipController' +import { + advanceTimers, + flushPendingTimers, + hoverAnchor, + unhoverAnchor, + waitForTooltip, +} from './test-utils' + +jest.mock('@floating-ui/dom', () => { + const originalModule = jest.requireActual('@floating-ui/dom') + return { + ...originalModule, + autoUpdate: jest.fn(() => jest.fn()), + } +}) + +const TOOLTIP_ID = 'closing-transition-test' +const getTooltip = () => document.getElementById(TOOLTIP_ID) + +const showThenClose = async (tooltipProps) => { + render( + <> + Hover Me + + , + ) + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + await waitForTooltip(TOOLTIP_ID) + await waitFor(() => { + expect(getTooltip()).toHaveClass('react-tooltip__show') + }) + + unhoverAnchor(anchor, 20) + expect(getTooltip()).toHaveClass('react-tooltip__closing') +} + +describe('tooltip closing transition', () => { + beforeEach(() => { + jest.useFakeTimers() + }) + + afterEach(() => { + flushPendingTimers() + jest.useRealTimers() + }) + + test('keeps a closing tooltip for its closing transition when it is longer than the show transition', async () => { + await showThenClose({ + style: { '--rt-transition-show-delay': '0.15s', '--rt-transition-closing-delay': '0.6s' }, + }) + + // half way through the 0.6s closing transition + advanceTimers(300) + expect(getTooltip()).toBeInTheDocument() + + // removed after it, even if no `transitionend` fires + advanceTimers(400) + expect(getTooltip()).not.toBeInTheDocument() + }) + + test('keeps a closing tooltip for its closing transition when the length is set on the tooltip', async () => { + // nothing on body: the length is read where the transition runs + await showThenClose({ style: { '--rt-transition-closing-delay': '0.6s' } }) + + advanceTimers(300) + expect(getTooltip()).toBeInTheDocument() + + advanceTimers(400) + expect(getTooltip()).not.toBeInTheDocument() + }) + + test('keeps a closing tooltip for its closing transition when the length is a calc() expression', async () => { + // a custom property keeps `calc()` as written. jsdom does not apply the closing class's + // stylesheet, so the resolved length of the closing transition is set directly + await showThenClose({ + style: { '--rt-transition-closing-delay': 'calc(0.3s + 0.3s)', transitionDuration: '0.6s' }, + }) + + advanceTimers(300) + expect(getTooltip()).toBeInTheDocument() + + advanceTimers(400) + expect(getTooltip()).not.toBeInTheDocument() + }) +}) diff --git a/src/test/tooltip-removal.spec.js b/src/test/tooltip-removal.spec.js index 166280be..cdbf6f23 100644 --- a/src/test/tooltip-removal.spec.js +++ b/src/test/tooltip-removal.spec.js @@ -147,6 +147,113 @@ describe('tooltip removal', () => { expect(afterHide).toHaveBeenCalledTimes(1) }) + test('keeps a closing tooltip when an opacity transition inside its content ends', async () => { + render( + <> + Hover Me + + Content + + , + ) + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + const tooltip = await waitForTooltip(TOOLTIP_ID) + await expectTooltipToShow(tooltip) + + unhoverAnchor(anchor, 20) + expect(getTooltip()).toHaveClass('react-tooltip__closing') + fireOpacityTransitionEnd(screen.getByText('Content')) + expect(getTooltip()).toBeInTheDocument() + + fireOpacityTransitionEnd(getTooltip()) + expect(getTooltip()).not.toBeInTheDocument() + }) + + test.each([ + ['away from the tooltip', false], + ['on the tooltip', true], + ])( + 'drops a hide that was pending when Escape removed a clickable tooltip, pointer %s', + async (_, pointerOnTooltip) => { + const tooltipRef = createRef() + render( + , + ) + + const anchor = screen.getByText('Hover Me') + hoverAnchor(anchor, 100) + await expectTooltipToShow(await waitForTooltip(TOOLTIP_ID)) + // leaving the anchor starts the 1000ms hide + unhoverAnchor(anchor) + if (pointerOnTooltip) { + fireEvent.mouseOver(getTooltip()) + } + fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' }) + advanceTimers(50) + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + + act(() => { + tooltipRef.current.open() + }) + advanceTimers(SHOW_TIMER_MS) + await waitFor(() => { + expect(getTooltip()).toHaveClass('react-tooltip__show') + }) + // the old hide's 1000ms run out + advanceTimers(1000) + advanceTimers(REMOVAL_MS) + expect(getTooltip()).toHaveClass('react-tooltip__show') + }, + ) + + test('closes the next tooltip on leaving its anchor after the anchor of a hovered clickable tooltip is removed', async () => { + const TwoAnchors = () => { + const [hasFirst, setHasFirst] = useState(true) + + return ( + <> + {hasFirst && First} + Second + + + + ) + } + + render() + + const first = screen.getByText('First') + hoverAnchor(first, 100) + await expectTooltipToShow(await waitForTooltip(TOOLTIP_ID)) + // the pointer is on the tooltip when its anchor goes away + unhoverAnchor(first) + fireEvent.mouseOver(getTooltip()) + fireEvent.click(screen.getByText('Remove First')) + mutationObserverController.triggerAll([ + { type: 'childList', removedNodes: [first], addedNodes: [] }, + ]) + advanceTimers(50) + expect(getTooltip()).not.toBeInTheDocument() + + const second = screen.getByText('Second') + hoverAnchor(second, 100) + await waitFor(() => { + expect(getTooltip()).toHaveClass('react-tooltip__show') + }) + unhoverAnchor(second) + advanceTimers(REMOVAL_MS) + advanceTimers(REMOVAL_MS) + expect(getTooltip()).not.toBeInTheDocument() + }) + test('calls afterHide once when the anchor of a showing tooltip is removed', async () => { const afterHide = jest.fn() const AnchorRemovalTest = () => { diff --git a/src/tokens.css b/src/tokens.css index 6220a6e5..f5356baf 100644 --- a/src/tokens.css +++ b/src/tokens.css @@ -1,4 +1,8 @@ -:root { +/** + * The defaults have no specificity, so an app's own :root rule (outside a cascade layer) + * overrides them wherever it comes in the page. The injected styles can come after the app's. + */ +:where(:root) { --rt-color-white: #fff; --rt-color-dark: #222; --rt-color-success: #8dc572;