Skip to content

Exports Tooltip event handler utils #2910

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 28 commits into from
Jun 30, 2025
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
530b369
feat(tooltip): implement event handler utils for hover and click inte…
TheSonOfThomp Jun 23, 2025
c1ef609
changesets
TheSonOfThomp Jun 23, 2025
5420b98
LG-5139: optional icon in chart titles (#2899)
charcoalyy Jun 18, 2025
3be1113
Adds missing `./static` directory to SB addon (#2905)
TheSonOfThomp Jun 23, 2025
c24fe7d
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 23, 2025
e14515f
clean up handlers. mv types
TheSonOfThomp Jun 26, 2025
7397bb0
simplifies hook
TheSonOfThomp Jun 26, 2025
debb0e3
adds tests
TheSonOfThomp Jun 26, 2025
beb7cbe
adds DEFAULT_HOVER_DELAY
TheSonOfThomp Jun 26, 2025
ffefe0f
update triggerEventHandlers
TheSonOfThomp Jun 26, 2025
040fc71
tsdoc
TheSonOfThomp Jun 26, 2025
b712f35
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 26, 2025
227531d
only hook
TheSonOfThomp Jun 27, 2025
422b5ab
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 27, 2025
bbab87b
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 27, 2025
de62b44
Update useTooltipTriggerEventHandlers.spec.tsx
TheSonOfThomp Jun 27, 2025
6a3e3be
Merge branch 'a/tooltip-utils' of https://github.com/mongodb/leafygre…
TheSonOfThomp Jun 27, 2025
6243c75
memoize
TheSonOfThomp Jun 27, 2025
b1ef563
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 27, 2025
9e5c696
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 30, 2025
c946b3e
Update packages/tooltip/src/Tooltip/utils/useTooltipTriggerEventHandl…
TheSonOfThomp Jun 30, 2025
712760e
SA feedback 👍
TheSonOfThomp Jun 30, 2025
abbefea
Merge branch 'a/tooltip-utils' of https://github.com/mongodb/leafygre…
TheSonOfThomp Jun 30, 2025
d697951
Merge branch 'main' into a/tooltip-utils
TheSonOfThomp Jun 30, 2025
94b1976
Update useTooltipTriggerEventHandlers.spec.tsx
TheSonOfThomp Jun 30, 2025
f9e12d3
Merge branch 'a/tooltip-utils' of https://github.com/mongodb/leafygre…
TheSonOfThomp Jun 30, 2025
9ce40cf
type names
TheSonOfThomp Jun 30, 2025
faafb16
rm delay escape hatch
TheSonOfThomp Jun 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tooltip-named-export.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@leafygreen-ui/tooltip': minor
---

Exports `Tooltip` as a named export (as well as default)
27 changes: 27 additions & 0 deletions .changeset/tooltip-trigger-handlers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
'@leafygreen-ui/tooltip': minor
---

Exports utilities (`createTooltipTriggerEventHandlers` & `useTooltipTriggerEventHandlers`) to enable handling external tooltip triggers.

```tsx
const [open, setOpen] = useState(false);
const tooltipEventHandlers = useTooltipTriggerEventHandlers({
triggerEvent: TriggerEvent.Hover,
setState: setOpen,
onFocus: (e) => { console.log(e) } // side effects called on focus of the trigger
});

return (
<>
<Button ref={triggerRef} {...tooltipEventHandlers}>
Button
</Button>
<Tooltip
refEl={triggerRef}
open={open}
setOpen={setOpen}
>Content</Tooltip>
</>
)
```
93 changes: 16 additions & 77 deletions packages/tooltip/src/Tooltip/Tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import React, {
useRef,
useState,
} from 'react';
import { flushSync } from 'react-dom';
import debounce from 'lodash/debounce';

import { css, cx } from '@leafygreen-ui/emotion';
import {
Expand All @@ -26,6 +24,7 @@ import {

import SvgNotch from '../Notch';

import { useTooltipTriggerEventHandlers } from './utils/useTooltipTriggerEventHandlers';
import {
baseStyles,
baseTypeStyle,
Expand All @@ -40,7 +39,6 @@ import {
TooltipProps,
TriggerEvent,
} from './Tooltip.types';
import { hoverDelay } from './tooltipConstants';
import { notchPositionStyles } from './tooltipUtils';

const stopClickPropagation = (evt: React.MouseEvent) => {
Expand Down Expand Up @@ -111,7 +109,6 @@ function Tooltip({
const setOpen =
isControlled && controlledSetOpen ? controlledSetOpen : uncontrolledSetOpen;

const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const tooltipRef = useRef<HTMLDivElement>(null);

const existingId = id ?? tooltipRef.current?.id;
Expand All @@ -127,13 +124,8 @@ function Tooltip({
}
}, [trigger]);

useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [timeoutRef]);
const triggerComponent =
typeof trigger === 'function' ? trigger({}) : trigger;

const handleClose = useCallback(() => {
if (typeof shouldClose !== 'function' || shouldClose()) {
Expand All @@ -142,70 +134,20 @@ function Tooltip({
}
}, [setOpen, shouldClose, onClose]);

const createTriggerProps = useCallback(
(triggerEvent: TriggerEvent, triggerProps?: any) => {
switch (triggerEvent) {
case TriggerEvent.Hover:
return {
onMouseEnter: debounce((e: MouseEvent) => {
userTriggerHandler('onMouseEnter', e);
// Without this the tooltip sometimes opens without a transition. flushSync prevents this state update from automatically batching. Instead updates are made synchronously.
// https://react.dev/reference/react-dom/flushSync#flushing-updates-for-third-party-integrations
flushSync(() => {
timeoutRef.current = setTimeout(() => {
setOpen(true);
}, hoverDelay);
});
}, 35),
onMouseLeave: debounce((e: MouseEvent) => {
userTriggerHandler('onMouseLeave', e);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
handleClose();
}, 35),
onFocus: (e: MouseEvent) => {
userTriggerHandler('onFocus', e);
setOpen(true);
},
onBlur: (e: MouseEvent) => {
userTriggerHandler('onBlur', e);
handleClose();
},
};
case TriggerEvent.Click:
default:
return {
onClick: (e: MouseEvent) => {
// ensure that we don't close the tooltip when content inside tooltip is clicked
if (e.target !== tooltipRef.current) {
userTriggerHandler('onClick', e);
setOpen((curr: boolean) => !curr);
}
},
};
}

function userTriggerHandler(handler: string, e: MouseEvent): void {
// call any click handlers already on the trigger
if (
triggerProps &&
triggerProps[handler] &&
typeof triggerProps[handler] == 'function'
)
triggerProps[handler](e);
}
},
[handleClose, setOpen, tooltipRef],
);

useEscapeKey(handleClose, { enabled: open });

useBackdropClick(handleClose, [tooltipRef], {
enabled: open && triggerEvent === 'click',
});

const triggerEventHandlers = useTooltipTriggerEventHandlers({
setState: setOpen,
triggerEvent,
tooltipRef,
isEnabled: enabled,
...triggerComponent?.props,
});

const popoverProps = {
popoverZIndex,
refEl,
Expand Down Expand Up @@ -291,20 +233,17 @@ function Tooltip({
</Popover>
);

if (trigger) {
const originalTrigger =
typeof trigger === 'function' ? trigger({}) : trigger;

return React.cloneElement(originalTrigger, {
...createTriggerProps(triggerEvent, originalTrigger.props),
if (triggerComponent) {
return React.cloneElement(triggerComponent, {
...triggerEventHandlers,
'aria-describedby': active ? tooltipId : undefined,
children: (
<>
{originalTrigger.props.children}
{triggerComponent.props.children}
{tooltip}
</>
),
className: cx(positionRelative, originalTrigger.props.className),
className: cx(positionRelative, triggerComponent.props.className),
});
}

Expand Down
4 changes: 2 additions & 2 deletions packages/tooltip/src/Tooltip/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import {
type TooltipProps,
TriggerEvent,
} from './Tooltip.types';
import { hoverDelay } from './tooltipConstants';
import { DEFAULT_HOVER_DELAY } from './tooltipConstants';

export {
Align,
DismissMode,
hoverDelay,
DEFAULT_HOVER_DELAY as hoverDelay,
Justify,
RenderMode,
type TooltipProps,
Expand Down
4 changes: 3 additions & 1 deletion packages/tooltip/src/Tooltip/tooltipConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ import { transitionDuration } from '@leafygreen-ui/tokens';
export const notchHeight = 8;
export const notchWidth = 26;
export const borderRadius = 16;
export const hoverDelay = transitionDuration.slowest;

export const DEFAULT_HOVER_DELAY = transitionDuration.slowest;
export const CALLBACK_DEBOUNCE = 35; // ms
95 changes: 95 additions & 0 deletions packages/tooltip/src/Tooltip/utils/tooltipHandlers.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { FocusEventHandler, MouseEventHandler, RefObject } from 'react';

import type { TriggerEvent } from '../Tooltip.types';

export interface CreateTooltipEventsBaseArgs {
/**
* The `useState` dispatch method to toggle the tooltip state
*/
setState: React.Dispatch<React.SetStateAction<boolean>>;

/**
* Whether the tooltip event handlers should be enabled
*/
isEnabled?: boolean;

/**
* The delay in milliseconds before the tooltip opens on hover.
*/
delay?: number;
}

export interface CreateTooltipEventsArgsHover {
/**
* Whether the tooltip will open/close on `hover` or `click` events.
* Note: must match the value passed onto `tooltip`
*/
triggerEvent: typeof TriggerEvent.Hover;

/**
* A ref to the Tooltip element.
* Optional when the trigger event is `hover`
*/
tooltipRef?: RefObject<HTMLElement>;

/** Additional side effects to run on this event */
onMouseEnter?: MouseEventHandler<HTMLElement>;

/** Additional side effects to run on this event */
onMouseLeave?: MouseEventHandler<HTMLElement>;

/** Additional side effects to run on this event */
onFocus?: FocusEventHandler<HTMLElement>;

/** Additional side effects to run on this event */
onBlur?: FocusEventHandler<HTMLElement>;
}

export interface CreateTooltipEventsArgsClick {
/**
* Whether the tooltip will open/close on `hover` or `click` events.
* Note: must match the value passed onto `tooltip`
*/
triggerEvent: typeof TriggerEvent.Click;

/**
* A ref to the Tooltip element.
* Optional when the trigger event is `hover`
*/
tooltipRef: RefObject<HTMLElement>;

/**
* Additional side effects to run on this event
*/
onClick?: MouseEventHandler<HTMLElement>;
}

export type CreateTooltipEventsArgs<Trigger extends TriggerEvent> =
CreateTooltipEventsBaseArgs &
(Trigger extends 'hover'
? CreateTooltipEventsArgsHover
: Trigger extends 'click'
? CreateTooltipEventsArgsClick
: never);

export interface TooltipHoverEvents {
onMouseEnter: MouseEventHandler<HTMLElement>;
onMouseLeave: MouseEventHandler<HTMLElement>;
onFocus: FocusEventHandler<HTMLElement>;
onBlur: FocusEventHandler<HTMLElement>;
onClick: undefined;
}
export interface TooltipClickEvents {
onClick: MouseEventHandler<HTMLElement>;
onMouseEnter: undefined;
onMouseLeave: undefined;
onFocus: undefined;
onBlur: undefined;
}

export type TooltipEventHandlers<Trigger extends TriggerEvent> =
Trigger extends 'hover'
? TooltipHoverEvents
: Trigger extends 'click'
? TooltipClickEvents
: never;
Loading