Skip to content

Commit

Permalink
Center Tooltip to the appropriate placement point
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewserong committed May 25, 2022
1 parent f915032 commit 8001942
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions packages/components/src/tooltip/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,13 @@ const getRegularElement = ( {
};

const addPopoverToGrandchildren = ( {
anchorRef,
grandchildren,
isOver,
offset,
placement,
text,
shortcut,
anchorRef,
text,
} ) =>
concatChildren(
grandchildren,
Expand All @@ -107,6 +108,7 @@ const addPopoverToGrandchildren = ( {
aria-hidden="true"
animate={ false }
anchorRef={ anchorRef }
offset={ offset }
>
{ text }
<Shortcut
Expand Down Expand Up @@ -137,7 +139,7 @@ const emitToChild = ( children, eventName, event ) => {
function Tooltip( props ) {
const {
children,
position = 'bottom middle',
position = 'bottom right',
text,
shortcut,
delay = TOOLTIP_DELAY,
Expand All @@ -151,6 +153,10 @@ function Tooltip( props ) {
const [ isMouseDown, setIsMouseDown ] = useState( false );
const [ isOver, setIsOver ] = useState( false );
const delayedSetIsOver = useDebounce( setIsOver, delay );

// 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 mergedChildRefs = useMergeRefs( [
childRef,
Expand Down Expand Up @@ -259,14 +265,28 @@ function Tooltip( props ) {
? getDisabledElement
: getRegularElement;

// Transform the Tooltip's position property to the relevant
// placement point to be passed to the Popover.
const placement = positionToPlacement( position );

// To adequately support the Tooltip's position property,
// this function centers the Tooltip to the specified placement point.
// For example, setting the "bottom left" position will center the Tooltip
// at the bottom left corner of the Tooltip's first child.
const positionOffset = ( { floating } ) =>
floating?.width
? {
alignmentAxis: -floating.width / 2,
}
: {};

const popoverData = {
anchorRef: childRef,
isOver,
offset: position ? positionOffset : undefined,
placement,
text,
shortcut,
text,
};
const childrenWithPopover = addPopoverToGrandchildren( {
grandchildren,
Expand Down

0 comments on commit 8001942

Please sign in to comment.