Skip to content

Commit

Permalink
Tooltip: refactor using Popover's new anchor prop (#43799)
Browse files Browse the repository at this point in the history
* Tooltip: use Popover s new anchor prop

* Use internal state to force re-renders when the anchor ref changes

* Simplify code
  • Loading branch information
ciampo committed Sep 9, 2022
1 parent c3ae984 commit 77a5036
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions packages/components/src/tooltip/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
concatChildren,
useEffect,
useState,
useRef,
} from '@wordpress/element';
import { useDebounce, useMergeRefs } from '@wordpress/compose';

Expand Down Expand Up @@ -60,7 +59,7 @@ const getRegularElement = ( {
};

const addPopoverToGrandchildren = ( {
anchorRef,
anchor,
grandchildren,
isOver,
offset,
Expand All @@ -78,7 +77,7 @@ const addPopoverToGrandchildren = ( {
aria-hidden="true"
animate={ false }
offset={ offset }
anchorRef={ anchorRef }
anchor={ anchor }
shift
>
{ text }
Expand Down Expand Up @@ -124,13 +123,18 @@ function Tooltip( props ) {
const [ isMouseDown, setIsMouseDown ] = useState( false );
const [ isOver, setIsOver ] = useState( false );
const delayedSetIsOver = useDebounce( setIsOver, delay );
// Using internal state (instead of a ref) for the popover anchor to make sure
// that the component re-renders when the anchor updates.
const [ popoverAnchor, setPopoverAnchor ] = useState();

// Create a reference to the Tooltip's child, to be passed to the Popover
// so that the Tooltip can be correctly positioned. Also, merge with the
// existing ref for the first child, so that its ref is preserved.
const childRef = useRef( null );
const existingChildRef = Children.toArray( children )[ 0 ]?.ref;
const mergedChildRefs = useMergeRefs( [ childRef, existingChildRef ] );
const mergedChildRefs = useMergeRefs( [
setPopoverAnchor,
existingChildRef,
] );

const createMouseDown = ( event ) => {
// In firefox, the mouse down event is also fired when the select
Expand Down Expand Up @@ -253,7 +257,8 @@ function Tooltip( props ) {
: getRegularElement;

const popoverData = {
anchorRef: childRef,
// `anchor` should never be `null`
anchor: popoverAnchor ?? undefined,
isOver,
offset: 4,
position,
Expand Down

0 comments on commit 77a5036

Please sign in to comment.