Skip to content

Commit a9eb655

Browse files
committed
fix(tooltip-web): render one tooltip element and preserve descriptions
Keep one content element in the DOM, hidden and inert while closed, so custom content is not duplicated. Merge the tooltip id into existing aria-describedby values and watch the trigger for late-mounted elements and attribute resets.
1 parent 14f6b5a commit a9eb655

4 files changed

Lines changed: 218 additions & 50 deletions

File tree

‎packages/pluggableWidgets/tooltip-web/src/components/Tooltip.tsx‎

Lines changed: 81 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import { Placement } from "@floating-ui/react";
22
import classNames from "classnames";
3-
import { CSSProperties, ReactElement, ReactNode, useCallback, useEffect, useId, useRef, useState } from "react";
3+
import {
4+
CSSProperties,
5+
ReactElement,
6+
ReactNode,
7+
useCallback,
8+
useEffect,
9+
useLayoutEffect,
10+
useRef,
11+
useState
12+
} from "react";
413
import { OpenOnEnum, RenderMethodEnum } from "../../typings/TooltipProps";
514
import { useFloatingUI } from "../utils/useFloatingUI";
615

@@ -18,13 +27,19 @@ export interface TooltipProps {
1827
preview?: boolean;
1928
}
2029

30+
const FOCUSABLE_SELECTOR = 'button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
31+
32+
const getDescribedByIds = (element: HTMLElement): string[] =>
33+
element.getAttribute("aria-describedby")?.split(/\s+/).filter(Boolean) ?? [];
34+
2135
export const Tooltip = (props: TooltipProps): ReactElement => {
2236
const { trigger, htmlMessage, textMessage, openOn, position, preview, renderMethod } = props;
2337
const [showTooltip, setShowTooltip] = useState(preview ?? false);
2438
const [arrowElement, setArrowElement] = useState<HTMLDivElement | null>(null);
25-
const contentId = useId();
26-
const hasTooltipContent = !!(textMessage || htmlMessage);
39+
const content = renderMethod === "text" ? textMessage : htmlMessage;
40+
const hasTooltipContent = !!content;
2741
const triggerWrapperRef = useRef<HTMLDivElement>(null);
42+
const contentRef = useRef<HTMLDivElement | null>(null);
2843

2944
const { arrowStyles, blurFocusEvents, floatingStyles, getFloatingProps, getReferenceProps, refs, staticSide } =
3045
useFloatingUI({
@@ -34,30 +49,47 @@ export const Tooltip = (props: TooltipProps): ReactElement => {
3449
arrowElement,
3550
openOn
3651
});
52+
const floatingProps = getFloatingProps?.();
53+
const contentId = floatingProps?.id as string | undefined;
3754

38-
// Apply aria-describedby to all focusable elements inside the trigger wrapper
55+
// Add the tooltip to the aria-describedby of all focusable elements inside the trigger wrapper.
56+
// Trigger widgets can render late or reset the attribute, so keep watching the wrapper.
3957
useEffect(() => {
40-
if (!hasTooltipContent || !triggerWrapperRef.current) {
58+
const wrapper = triggerWrapperRef.current;
59+
if (preview || !hasTooltipContent || !contentId || !wrapper) {
4160
return;
4261
}
4362

44-
// Find all focusable elements (button, a, input, select, textarea, etc.)
45-
const focusableElements = triggerWrapperRef.current.querySelectorAll<HTMLElement>(
46-
'button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
47-
);
48-
49-
if (focusableElements.length > 0) {
50-
focusableElements.forEach(element => {
51-
element.setAttribute("aria-describedby", contentId);
63+
const applyDescription = (): void => {
64+
wrapper.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR).forEach(element => {
65+
const ids = getDescribedByIds(element);
66+
if (!ids.includes(contentId)) {
67+
element.setAttribute("aria-describedby", [...ids, contentId].join(" "));
68+
}
5269
});
70+
};
5371

54-
return () => {
55-
focusableElements.forEach(element => {
72+
applyDescription();
73+
const observer = new MutationObserver(applyDescription);
74+
observer.observe(wrapper, {
75+
attributes: true,
76+
attributeFilter: ["aria-describedby", "href", "tabindex"],
77+
childList: true,
78+
subtree: true
79+
});
80+
81+
return () => {
82+
observer.disconnect();
83+
wrapper.querySelectorAll<HTMLElement>("[aria-describedby]").forEach(element => {
84+
const ids = getDescribedByIds(element).filter(id => id !== contentId);
85+
if (ids.length > 0) {
86+
element.setAttribute("aria-describedby", ids.join(" "));
87+
} else {
5688
element.removeAttribute("aria-describedby");
57-
});
58-
};
59-
}
60-
}, [hasTooltipContent, contentId]);
89+
}
90+
});
91+
};
92+
}, [hasTooltipContent, contentId, preview]);
6193

6294
// Merge our ref with floating-ui's ref
6395
const setTriggerRef = useCallback(
@@ -70,6 +102,20 @@ export const Tooltip = (props: TooltipProps): ReactElement => {
70102
[refs]
71103
);
72104

105+
// Floating UI only tracks the content while the tooltip is open
106+
const setContentRef = useCallback(
107+
(node: HTMLDivElement | null) => {
108+
contentRef.current = node;
109+
refs?.setFloating?.(showTooltip ? node : null);
110+
},
111+
[refs, showTooltip]
112+
);
113+
114+
// Set through the DOM because React versions handle the inert prop differently
115+
useLayoutEffect(() => {
116+
contentRef.current?.toggleAttribute("inert", !showTooltip);
117+
}, [hasTooltipContent, showTooltip]);
118+
73119
return (
74120
<div className={classNames(props.class, "widget-tooltip", `widget-tooltip-${position}`)}>
75121
<div
@@ -81,23 +127,24 @@ export const Tooltip = (props: TooltipProps): ReactElement => {
81127
>
82128
{trigger}
83129
</div>
84-
{/* Hidden content for screen readers - always in DOM, only accessible via aria-describedby */}
85-
{hasTooltipContent && (
86-
<div id={contentId} className="sr-only" aria-hidden="true">
87-
{renderMethod === "text" ? textMessage : htmlMessage}
88-
</div>
89-
)}
90-
{/* Visible content for sighted users */}
91-
{showTooltip && hasTooltipContent ? (
130+
{/* Always in the DOM so aria-describedby can reference it, visible only while open */}
131+
{hasTooltipContent ? (
92132
<div
93-
className="widget-tooltip-content"
94-
ref={refs?.setFloating}
95-
style={floatingStyles}
96-
{...getFloatingProps?.()}
97-
data-overlay-content
133+
className={showTooltip ? "widget-tooltip-content" : "widget-tooltip-sr-only"}
134+
ref={setContentRef}
135+
style={showTooltip ? floatingStyles : undefined}
136+
{...floatingProps}
137+
aria-hidden={showTooltip ? undefined : true}
138+
data-overlay-content={showTooltip ? true : undefined}
98139
>
99-
{renderMethod === "text" ? textMessage : htmlMessage}
100-
<div className={`widget-tooltip-arrow-${staticSide}`} ref={setArrowElement} style={arrowStyles} />
140+
{content}
141+
{showTooltip && (
142+
<div
143+
className={`widget-tooltip-arrow-${staticSide}`}
144+
ref={setArrowElement}
145+
style={arrowStyles}
146+
/>
147+
)}
101148
</div>
102149
) : null}
103150
</div>

‎packages/pluggableWidgets/tooltip-web/src/components/__tests__/Tooltip.spec.tsx‎

Lines changed: 134 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { act, render, screen } from "@testing-library/react";
22
import "@testing-library/jest-dom";
33

44
import userEvent from "@testing-library/user-event";
5+
import { ReactElement, useEffect } from "react";
56
import { Tooltip, TooltipProps } from "../Tooltip";
67

78
jest.useFakeTimers();
@@ -165,15 +166,15 @@ describe("Tooltip", () => {
165166

166167
it("renders sr-only content for screen readers before tooltip is shown", () => {
167168
render(<Tooltip {...defaultTooltipProps} />);
168-
const srOnlyContent = document.querySelector(".sr-only");
169+
const srOnlyContent = document.querySelector(".widget-tooltip-sr-only");
169170

170171
expect(srOnlyContent).toBeInTheDocument();
171172
expect(srOnlyContent).toHaveTextContent(defaultTooltipProps.textMessage as string);
172173
});
173174

174175
it("sr-only content is always in DOM even when tooltip is not visible", () => {
175176
render(<Tooltip {...defaultTooltipProps} openOn="click" />);
176-
const srOnlyContent = document.querySelector(".sr-only");
177+
const srOnlyContent = document.querySelector(".widget-tooltip-sr-only");
177178

178179
// Content should exist before tooltip is shown
179180
expect(srOnlyContent).toBeInTheDocument();
@@ -183,7 +184,7 @@ describe("Tooltip", () => {
183184
it("sr-only content matches the text message", () => {
184185
const customMessage = "Custom accessibility message";
185186
render(<Tooltip {...defaultTooltipProps} textMessage={customMessage} />);
186-
const srOnlyContent = document.querySelector(".sr-only");
187+
const srOnlyContent = document.querySelector(".widget-tooltip-sr-only");
187188

188189
expect(srOnlyContent).toHaveTextContent(customMessage);
189190
});
@@ -198,17 +199,99 @@ describe("Tooltip", () => {
198199
textMessage={undefined}
199200
/>
200201
);
201-
const srOnlyContent = document.querySelector(".sr-only");
202+
const srOnlyContent = document.querySelector(".widget-tooltip-sr-only");
202203

203204
expect(srOnlyContent).toHaveTextContent("Custom HTML Content");
204205
});
205206

206207
it("does not add aria-describedby when no tooltip content is provided", () => {
207208
render(<Tooltip {...defaultTooltipProps} textMessage={undefined} htmlMessage={undefined} />);
208209
const triggerElement = screen.getByTestId("tooltip-trigger");
209-
const parentElement = triggerElement.parentElement;
210210

211-
expect(parentElement).not.toHaveAttribute("aria-describedby");
211+
expect(triggerElement).not.toHaveAttribute("aria-describedby");
212+
});
213+
214+
it("renders open custom content once and keeps widgets mounted across open and close", async () => {
215+
const onMount = jest.fn();
216+
const CustomWidget = (): ReactElement => {
217+
useEffect(onMount, []);
218+
return <div>Custom widget</div>;
219+
};
220+
render(
221+
<Tooltip
222+
{...defaultTooltipProps}
223+
renderMethod="custom"
224+
htmlMessage={<CustomWidget />}
225+
textMessage={undefined}
226+
/>
227+
);
228+
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
229+
const triggerElement = screen.getByTestId("tooltip-trigger");
230+
231+
await user.click(triggerElement);
232+
expect(screen.getAllByText("Custom widget")).toHaveLength(1);
233+
234+
await user.click(triggerElement);
235+
expect(screen.getAllByText("Custom widget")).toHaveLength(1);
236+
expect(onMount).toHaveBeenCalledTimes(1);
237+
});
238+
239+
it("makes content inert and aria-hidden only while closed", async () => {
240+
render(<Tooltip {...defaultTooltipProps} />);
241+
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
242+
const closedContent = document.querySelector(".widget-tooltip-sr-only");
243+
244+
expect(closedContent).toHaveAttribute("inert");
245+
expect(closedContent).toHaveAttribute("aria-hidden", "true");
246+
247+
await user.click(screen.getByTestId("tooltip-trigger"));
248+
const openContent = screen.getByRole("tooltip");
249+
250+
expect(openContent).toBe(closedContent);
251+
expect(openContent).not.toHaveAttribute("inert");
252+
expect(openContent).not.toHaveAttribute("aria-hidden");
253+
});
254+
255+
it("places focusable elements in closed custom content inside the inert element", () => {
256+
render(
257+
<Tooltip
258+
{...defaultTooltipProps}
259+
renderMethod="custom"
260+
htmlMessage={<button>Inside tooltip</button>}
261+
textMessage={undefined}
262+
/>
263+
);
264+
265+
expect(screen.getByText("Inside tooltip").closest("[inert]")).toBeInTheDocument();
266+
});
267+
268+
it("ignores custom content in text mode when the text is empty", async () => {
269+
render(
270+
<Tooltip {...defaultTooltipProps} htmlMessage={<div>Custom content</div>} textMessage={undefined} />
271+
);
272+
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
273+
const triggerElement = screen.getByTestId("tooltip-trigger");
274+
275+
expect(triggerElement).not.toHaveAttribute("aria-describedby");
276+
277+
await user.click(triggerElement);
278+
expect(screen.queryByText("Custom content")).toBeNull();
279+
expect(screen.queryByRole("tooltip")).toBeNull();
280+
});
281+
282+
it("renders preview content once without adding a description", () => {
283+
render(
284+
<Tooltip
285+
{...defaultTooltipProps}
286+
preview
287+
renderMethod="custom"
288+
htmlMessage={<div>Drop zone</div>}
289+
textMessage={undefined}
290+
/>
291+
);
292+
293+
expect(screen.getAllByText("Drop zone")).toHaveLength(1);
294+
expect(screen.getByTestId("tooltip-trigger")).not.toHaveAttribute("aria-describedby");
212295
});
213296

214297
it("adds aria-describedby to all focusable elements in trigger", () => {
@@ -244,5 +327,50 @@ describe("Tooltip", () => {
244327
expect(ariaDescribedBy1).toBe(ariaDescribedBy2);
245328
expect(ariaDescribedBy2).toBe(ariaDescribedBy3);
246329
});
330+
331+
it("keeps an existing aria-describedby and restores it when the content is removed", () => {
332+
const trigger = <input aria-describedby="help-text" data-testid="input" />;
333+
const { rerender } = render(<Tooltip {...defaultTooltipProps} trigger={trigger} />);
334+
const input = screen.getByTestId("input");
335+
const contentId = document.querySelector(".widget-tooltip-sr-only")?.id;
336+
337+
expect(input).toHaveAttribute("aria-describedby", `help-text ${contentId}`);
338+
339+
rerender(<Tooltip {...defaultTooltipProps} trigger={trigger} textMessage={undefined} />);
340+
341+
expect(input).toHaveAttribute("aria-describedby", "help-text");
342+
});
343+
344+
it("removes aria-describedby when it only contained the tooltip", () => {
345+
const trigger = <button data-testid="button">Button</button>;
346+
const { rerender } = render(<Tooltip {...defaultTooltipProps} trigger={trigger} />);
347+
348+
rerender(<Tooltip {...defaultTooltipProps} trigger={trigger} textMessage={undefined} />);
349+
350+
expect(screen.getByTestId("button")).not.toHaveAttribute("aria-describedby");
351+
});
352+
353+
it("adds aria-describedby to focusable elements that mount later", async () => {
354+
const { rerender } = render(<Tooltip {...defaultTooltipProps} trigger={<span>Loading</span>} />);
355+
const contentId = document.querySelector(".widget-tooltip-sr-only")?.id;
356+
357+
await act(async () => {
358+
rerender(<Tooltip {...defaultTooltipProps} trigger={<button data-testid="button">Button</button>} />);
359+
});
360+
361+
expect(screen.getByTestId("button")).toHaveAttribute("aria-describedby", contentId);
362+
});
363+
364+
it("adds the tooltip back when the trigger resets aria-describedby", async () => {
365+
render(<Tooltip {...defaultTooltipProps} trigger={<button data-testid="button">Button</button>} />);
366+
const button = screen.getByTestId("button");
367+
const contentId = document.querySelector(".widget-tooltip-sr-only")?.id;
368+
369+
await act(async () => {
370+
button.setAttribute("aria-describedby", "validation-message");
371+
});
372+
373+
expect(button).toHaveAttribute("aria-describedby", `validation-message ${contentId}`);
374+
});
247375
});
248376
});

‎packages/pluggableWidgets/tooltip-web/src/components/__tests__/__snapshots__/Tooltip.spec.tsx.snap‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ exports[`Tooltip render DOM structure 1`] = `
66
class="widget-tooltip widget-tooltip-right"
77
>
88
<div
9-
aria-describedby=":r1:"
9+
aria-describedby=":r0:"
1010
class="widget-tooltip-trigger"
1111
>
1212
<div
@@ -17,18 +17,11 @@ exports[`Tooltip render DOM structure 1`] = `
1717
Trigger
1818
</div>
1919
</div>
20-
<div
21-
aria-hidden="true"
22-
class="sr-only"
23-
id=":r0:"
24-
>
25-
Tooltip text
26-
</div>
2720
<div
2821
class="widget-tooltip-content"
2922
data-floating-ui-focusable=""
3023
data-overlay-content="true"
31-
id=":r1:"
24+
id=":r0:"
3225
role="tooltip"
3326
style="position: fixed; left: 0px; top: 0px; transform: translate(0px, 0px);"
3427
tabindex="-1"

‎packages/pluggableWidgets/tooltip-web/src/ui/Tooltip.scss‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
}
66

77
// Screen reader only - visually hidden but accessible to assistive technology
8-
.sr-only {
8+
.widget-tooltip-sr-only {
99
position: absolute;
1010
width: 1px;
1111
height: 1px;

0 commit comments

Comments
 (0)