Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

perf(Tooltip): keep trigger refs stable across rerenders (#5951)

freddymeta4ec74d9ddc52
diff --git a/.changeset/keep-tooltip-refs-stable-across-rerenders-ce7j.md b/.changeset/keep-tooltip-refs-stable-across-rerenders-ce7j.md
new file mode 100644
index 0000000000..6e9314488f
--- /dev/null
+++ b/.changeset/keep-tooltip-refs-stable-across-rerenders-ce7j.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[perf] Keep Tooltip refs stable across rerenders
+@freddymeta
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index add1bd5e06..afcb97cd29 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -158,6 +158,17 @@
"overlayRoot": ".astryx-tokenizer"
}
},
+ {
+ "component": "Tooltip",
+ "storyId": "core-tooltip--rtl-logical-placement",
+ "dims": [
+ "D4"
+ ],
+ "selectors": {
+ "overlay": ".astryx-tooltip",
+ "overlayRoot": "button:has-text(\"RTL placement target\")"
+ }
+ },
{
"component": "Toast",
"storyId": "core-toast--logical-placement",
diff --git a/apps/storybook/stories/Tooltip.stories.tsx b/apps/storybook/stories/Tooltip.stories.tsx
index 71892f9fca..2edaf747c0 100644
--- a/apps/storybook/stories/Tooltip.stories.tsx
+++ b/apps/storybook/stories/Tooltip.stories.tsx
@@ -68,6 +68,17 @@ export const Start: Story = {
},
};
+export const RTLLogicalPlacement: Story = {
+ args: {
+ placement: 'start',
+ content: 'Tooltip on logical start',
+ children: (
+ <Button label="RTL placement target">RTL placement target</Button>
+ ),
+ isDefaultOpen: true,
+ },
+};
+
export const End: Story = {
args: {
placement: 'end',
diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsx
index e380d926da..c98b5f4375 100644
--- a/packages/core/src/Tooltip/Tooltip.test.tsx
+++ b/packages/core/src/Tooltip/Tooltip.test.tsx
@@ -18,8 +18,15 @@ import {
beforeEach,
afterAll,
} from 'vitest';
-import {render, screen, fireEvent, waitFor} from '@testing-library/react';
+import {
+ render,
+ renderHook,
+ screen,
+ fireEvent,
+ waitFor,
+} from '@testing-library/react';
import {Tooltip} from './Tooltip';
+import {useTooltip} from './useTooltip';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
// Store original matches to restore later
@@ -54,6 +61,19 @@ afterAll(() => {
(HTMLElement.prototype as any).matches = originalMatches;
});
+describe('useTooltip identity', () => {
+ it('keeps callback refs stable across unchanged rerenders', () => {
+ const {result, rerender} = renderHook(() => useTooltip());
+ const firstRef = result.current.ref;
+ const firstInteractionRef = result.current.interactionRef;
+
+ rerender();
+
+ expect(result.current.ref).toBe(firstRef);
+ expect(result.current.interactionRef).toBe(firstInteractionRef);
+ });
+});
+
describe('Tooltip', () => {
it('renders trigger element', () => {
render(
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index 72ef454d13..b904ce2073 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -5,7 +5,7 @@
/**
* @file useTooltip.tsx
* @input Uses useLayer, useTouchTrigger, React hooks
- * @output Exports useTooltip hook for hover/focus/tap triggered tooltips
+ * @output Exports useTooltip hook with stable trigger refs for hover/focus/tap tooltips
* @position Layer hook; builds on useLayer for tooltip behavior
*
* SYNC: When modified, update:
@@ -284,6 +284,15 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
onShow,
onHide,
});
+ const {
+ ref: layerRef,
+ anchorId: layerAnchorId,
+ show: showLayer,
+ hide: hideLayer,
+ isOpen: isLayerOpen,
+ id: layerId,
+ render: renderLayer,
+ } = layer;
const popoverXstyle = styles.container;
@@ -307,20 +316,26 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// passing across the trigger, and a tap is never that.
const showNow = useCallback(() => {
clearTimeouts();
- layer.show();
- }, [clearTimeouts, layer]);
+ showLayer();
+ }, [clearTimeouts, showLayer]);
const hideNow = useCallback(() => {
clearTimeouts();
- layer.hide();
- }, [clearTimeouts, layer]);
+ hideLayer();
+ }, [clearTimeouts, hideLayer]);
- const touch = useTouchTrigger({
+ const {
+ isTouchPointerRef,
+ isTouchInteraction,
+ handlePointerEnter,
+ handlePointerDown: handleTouchPointerDown,
+ clearTapOpen,
+ } = useTouchTrigger({
touchTrigger,
isEnabled,
isControlled: isOpen !== undefined,
- isOpen: layer.isOpen,
- layerId: layer.id,
+ isOpen: isLayerOpen,
+ layerId: layerId,
triggerRef,
show: showNow,
hide: hideNow,
@@ -333,9 +348,9 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
}
clearTimeouts();
showTimeoutRef.current = setTimeout(() => {
- layer.show();
+ showLayer();
}, delay);
- }, [isEnabled, isOpen, clearTimeouts, layer, delay]);
+ }, [isEnabled, isOpen, clearTimeouts, showLayer, delay]);
// Schedule hide with delay (suppressed when isOpen is true).
// A small hover bridge (when hideDelay is 0) lets the pointer travel from the
@@ -348,9 +363,9 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
clearTimeouts();
const effectiveHideDelay = hideDelay > 0 ? hideDelay : HOVER_BRIDGE_DELAY;
hideTimeoutRef.current = setTimeout(() => {
- layer.hide();
+ hideLayer();
}, effectiveHideDelay);
- }, [isOpen, clearTimeouts, layer, hideDelay]);
+ }, [isOpen, clearTimeouts, hideLayer, hideDelay]);
// Cancel a pending hide (e.g. the pointer entered the tooltip surface).
const cancelHide = useCallback(() => {
@@ -365,21 +380,21 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// A tap synthesizes mouseenter. On touch the tap path owns the decision,
// so hover must not also fire — including the tap that just opened the
// tooltip, which would otherwise be double-handled.
- if (touch.isTouchPointerRef.current) {
+ if (isTouchPointerRef.current) {
return;
}
scheduleShow();
- }, [touch, scheduleShow]);
+ }, [isTouchPointerRef, scheduleShow]);
const handleMouseLeave = useCallback(() => {
// On touch the synthesized mouseleave arrives with the next tap elsewhere,
// which the outside-tap dismissal already handles — and handling it here
// too would close the tooltip behind the tap-open bookkeeping's back.
- if (touch.isTouchPointerRef.current) {
+ if (isTouchPointerRef.current) {
return;
}
scheduleHide();
- }, [touch, scheduleHide]);
+ }, [isTouchPointerRef, scheduleHide]);
const handleFocusIn = useCallback(
(e: Event) => {
@@ -391,7 +406,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// matches it. Those are exactly the action triggers `auto` just decided
// to keep shut, so without this the focus reopens what the tap
// suppressed, over the field the user is trying to type into.
- if (touch.isTouchInteraction()) {
+ if (isTouchInteraction()) {
return;
}
// Only show tooltip for keyboard focus (:focus-visible),
@@ -401,9 +416,9 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
return;
}
clearTimeouts();
- layer.show();
+ showLayer();
},
- [isEnabled, touch, clearTimeouts, layer],
+ [isEnabled, isTouchInteraction, clearTimeouts, showLayer],
);
const handleFocusOut = useCallback(() => {
@@ -414,25 +429,24 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// the hint has served its purpose, and a tooltip lingering over a
// just-pressed control reads as stale. Fires on pointerdown so it feels
// immediate. Uncontrolled tooltips only — a controlled tooltip's visibility
- // is owned by the consumer. `layer.hide()` self-guards when already closed.
+ // is owned by the consumer. `hideLayer()` self-guards when already closed.
// A touch press is a different gesture (it may be the only way to open the
// tooltip at all), so the touch path answers it first.
const handlePointerDown = useCallback(
(event: PointerEvent) => {
- if (touch.handlePointerDown(event)) {
+ if (handleTouchPointerDown(event)) {
return;
}
if (isOpen !== undefined) {
return;
}
clearTimeouts();
- layer.hide();
+ hideLayer();
},
- [touch, isOpen, clearTimeouts, layer],
+ [handleTouchPointerDown, isOpen, clearTimeouts, hideLayer],
);
// Interaction ref that handles event listeners only
- const {handlePointerEnter, clearTapOpen} = touch;
const interactionRef: RefCallback<HTMLElement> = useCallback(
(el: HTMLElement | null) => {
// Cleanup previous element
@@ -488,10 +502,10 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// Combined ref - shorthand for calling both positionRef and interactionRef
const ref: RefCallback<HTMLElement> = useCallback(
(el: HTMLElement | null) => {
- layer.ref(el);
+ layerRef(el);
interactionRef(el);
},
- [layer, interactionRef],
+ [layerRef, interactionRef],
);
// Cleanup on unmount
@@ -504,7 +518,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// Show on mount when isDefaultOpen is true
useEffect(() => {
if (isDefaultOpen) {
- layer.show();
+ showLayer();
}
// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive
}, []);
@@ -516,12 +530,12 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
}
if (isOpen) {
clearTimeouts();
- layer.show();
+ showLayer();
} else {
clearTimeouts();
- layer.hide();
+ hideLayer();
}
- }, [isOpen, clearTimeouts, layer]);
+ }, [isOpen, clearTimeouts, showLayer, hideLayer]);
// Dismiss on Escape (WCAG 1.4.13 — dismissible) through the shared layer
// stack. A visible tip is the top-most layer, so it takes the press and
@@ -536,7 +550,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
// consumer's value, so only their update may change it. Same contract as a
// controlled Dialog.
useLayerDismissal({
- // Registered for the hook's lifetime rather than gated on `layer.isOpen`:
+ // Registered for the hook's lifetime rather than gated on `isLayerOpen`:
// that state can lag a frame behind the DOM, so a press arriving right after
// the layer appears would find nothing registered. Because this layer
// CONSUMES the press, a stale registration would be worse than a missed one
@@ -547,7 +561,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
const el =
typeof document === 'undefined'
? null
- : document.getElementById(layer.id);
+ : document.getElementById(layerId);
if (el == null) {
return false;
}
@@ -556,7 +570,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
} catch {
// Browsers without the Popover API (and some test environments) cannot
// answer the selector; fall back to the hook's own state.
- return layer.isOpen;
+ return isLayerOpen;
}
},
onDismiss: () => {
@@ -566,7 +580,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
onHide?.();
return;
}
- layer.hide();
+ hideLayer();
},
});
@@ -592,20 +606,27 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
onMouseLeave: scheduleHide,
};
- return layer.render(
+ return renderLayer(
<div {...stylex.props(styles.content)}>{children}</div>,
renderProps,
);
},
- [layer, placement, alignment, popoverXstyle, cancelHide, scheduleHide],
+ [
+ renderLayer,
+ placement,
+ alignment,
+ popoverXstyle,
+ cancelHide,
+ scheduleHide,
+ ],
);
return {
ref,
- positionRef: layer.ref,
+ positionRef: layerRef,
interactionRef,
- anchorId: layer.anchorId,
- describedBy: layer.id,
+ anchorId: layerAnchorId,
+ describedBy: layerId,
renderTooltip,
};
}