diff --git a/packages/pluggableWidgets/tooltip-web/CHANGELOG.md b/packages/pluggableWidgets/tooltip-web/CHANGELOG.md index af5fada629..07f5584992 100644 --- a/packages/pluggableWidgets/tooltip-web/CHANGELOG.md +++ b/packages/pluggableWidgets/tooltip-web/CHANGELOG.md @@ -6,6 +6,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] +### Changed + +- New Tooltip widgets now default to Open on Hover,focus, so keyboard users can see the tooltip. Existing widgets keep their setting. + +### Fixed + +- We fixed an issue where the tooltip in Click mode didn't open when the trigger was an action button: with an action set, it didn't open on click, Enter or Space; without one, it didn't open on Enter or Space. + +- We fixed an issue where holding Enter on a trigger in Click mode made the tooltip flicker. + +- We fixed an issue where a click in a text box or on a check box in Click mode closed the tooltip. A click there now opens the tooltip but doesn't close it. + +- We fixed an issue where Enter or Space on a tooltip nested inside another Click tooltip also opened the outer tooltip. + +- We fixed an issue where pressing Escape while focus was inside custom tooltip content moved focus to the top of the page. Focus now returns to the trigger. + +- We fixed an issue where pressing Tab from a Hover,focus trigger into custom tooltip content closed the tooltip and moved focus to the top of the page. The tooltip now stays open while focus is inside its content. + ## [1.5.1] - 2026-02-10 ### Added diff --git a/packages/pluggableWidgets/tooltip-web/openspec/changes/archive/2026-11-11-open-tooltip-on-keyboard-focus/.openspec.yaml b/packages/pluggableWidgets/tooltip-web/openspec/changes/archive/2026-11-11-open-tooltip-on-keyboard-focus/.openspec.yaml new file mode 100644 index 0000000000..2a7773d65e --- /dev/null +++ b/packages/pluggableWidgets/tooltip-web/openspec/changes/archive/2026-11-11-open-tooltip-on-keyboard-focus/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-11 diff --git a/packages/pluggableWidgets/tooltip-web/openspec/changes/archive/2026-11-11-open-tooltip-on-keyboard-focus/design.md b/packages/pluggableWidgets/tooltip-web/openspec/changes/archive/2026-11-11-open-tooltip-on-keyboard-focus/design.md new file mode 100644 index 0000000000..49c7677e72 --- /dev/null +++ b/packages/pluggableWidgets/tooltip-web/openspec/changes/archive/2026-11-11-open-tooltip-on-keyboard-focus/design.md @@ -0,0 +1,84 @@ +## Context + +The Tooltip widget uses Floating UI (`@floating-ui/react` 0.26.28) for its interactions. `useFloatingUI.ts` sets up the hooks per **Open on** mode: + +- `useHover` is enabled for `hover` and `hoverFocus`. +- `useFocus` is enabled only for `hoverFocus`. `Tooltip.tsx` also passes `blurFocusEvents` (`onFocus` opens, `onBlur` closes) for `hoverFocus`. +- `useClick` is enabled only for `click`. +- `useDismiss` (Escape and outside press) and `useRole("tooltip")` are always on. + +The reference props sit on the `widget-tooltip-trigger` wrapper `div`, not on the focusable element inside it. + +`Tooltip.xml` sets `openOn` to `hover` by default, so a new Tooltip doesn't open on keyboard focus. + +We reproduced both problems in a running app (SampleWidgetProject, page `TooltipTest.Tooltip_Focus_WC3663`, Tooltip 1.4.2 and 1.5.1, Chrome): + +- **Hover**: tabbing to a trigger opens nothing, and mouse hover works. This is the intended Hover behavior. +- **Hover,focus**: Tab opens the tooltip. Escape closes it, and focus stays on the button. +- **Click, action button with no action**: a mouse click opens the tooltip. Enter and Space don't. The button dispatches `keydown` and `keyup` but no `click` for Enter, while a plain `; + + it("opens on focus and closes on blur", async () => { + render(); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const button = screen.getByRole("button", { name: "Trigger button" }); + + await user.keyboard("{Tab}"); + expect(button).toHaveFocus(); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard("{Tab}"); + expect(button).not.toHaveFocus(); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("stays open while the user types in a text box", async () => { + render(} />); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const input = screen.getByRole("textbox", { name: "Name" }); + + await user.keyboard("{Tab}"); + expect(input).toHaveFocus(); + await user.keyboard("Some text and spaces"); + expect(input).toHaveValue("Some text and spaces"); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + }); + + it("shows custom content on focus without moving focus into the tooltip", async () => { + render( + Custom content} + textMessage={undefined} + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const button = screen.getByRole("button", { name: "Trigger button" }); + + await user.keyboard("{Tab}"); + expect(screen.queryByRole("tooltip")).toHaveTextContent("Custom content"); + expect(button).toHaveFocus(); + }); + + it("Escape closes the tooltip, keeps focus and doesn't reopen", async () => { + render(); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const button = screen.getByRole("button", { name: "Trigger button" }); + + await user.keyboard("{Tab}"); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard("{Escape}"); + expect(screen.queryByRole("tooltip")).toBeNull(); + expect(button).toHaveFocus(); + + act(() => { + jest.advanceTimersByTime(500); + }); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("stays open while focus moves into custom content, and closes when focus leaves it", async () => { + render( + Inside tooltip} + textMessage={undefined} + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}"); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard("{Tab}"); + act(() => { + jest.advanceTimersByTime(100); + }); + expect(screen.getByRole("button", { name: "Inside tooltip" })).toHaveFocus(); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard("{Tab}"); + act(() => { + jest.advanceTimersByTime(100); + }); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("Escape inside custom content closes the tooltip and moves focus back to the trigger", async () => { + render( + Inside tooltip} + textMessage={undefined} + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}{Tab}"); + expect(screen.getByRole("button", { name: "Inside tooltip" })).toHaveFocus(); + + await user.keyboard("{Escape}"); + expect(screen.queryByRole("tooltip")).toBeNull(); + expect(screen.getByRole("button", { name: "Trigger button" })).toHaveFocus(); + }); + }); + + describe("keyboard in click mode", () => { + // Like the Mendix action button: handles Enter and Space itself, so the browser dispatches no click + const NoNativeClickButton = (): ReactElement => ( + + ); + + it.each(["{Enter}", " "])("toggles with %s on a button that dispatches no click", async key => { + const clickSpy = jest.fn(); + render( + + + + } + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}"); + expect(screen.getByRole("button", { name: "Action button" })).toHaveFocus(); + expect(screen.queryByRole("tooltip")).toBeNull(); + + await user.keyboard(key); + expect(clickSpy).not.toHaveBeenCalled(); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard(key); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it.each(["{Enter}", " "])("toggles once with %s on a native button", async key => { + const clickSpy = jest.fn(); + render( + + Native button + + } + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}"); + await user.keyboard(key); + expect(clickSpy).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard(key); + expect(clickSpy).toHaveBeenCalledTimes(2); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + // Like a Mendix action button with an action: runs it and stops propagation of click and keydown + const ActionButton = ({ onAction }: { onAction: () => void }): ReactElement => ( + + ); + + it("opens on mouse click on a button that stops propagation, and the button action still runs", async () => { + const action = jest.fn(); + render(} />); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const button = screen.getByRole("button", { name: "Button with action" }); + + await user.click(button); + expect(action).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.click(button); + expect(action).toHaveBeenCalledTimes(2); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it.each(["{Enter}", " "])( + "toggles with %s on a button that stops propagation, and the button action still runs", + async key => { + const action = jest.fn(); + render( + } /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}"); + await user.keyboard(key); + expect(action).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard(key); + expect(action).toHaveBeenCalledTimes(2); + expect(screen.queryByRole("tooltip")).toBeNull(); + } + ); + + it("opens on a synthetic click without key events, as screen readers send", () => { + render( + Native button} + /> + ); + + act(() => { + screen.getByRole("button", { name: "Native button" }).click(); + }); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + }); + + it("doesn't swallow a mouse click after a key toggle on a button that dispatches no click", async () => { + render(} />); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const button = screen.getByRole("button", { name: "Action button" }); + + await user.keyboard("{Tab}"); + await user.keyboard("{Enter}"); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.click(button); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("doesn't toggle on Enter or Space in a text input, or on focus", async () => { + render(} />); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const input = screen.getByRole("textbox", { name: "Name" }); + + await user.keyboard("{Tab}"); + expect(input).toHaveFocus(); + expect(screen.queryByRole("tooltip")).toBeNull(); + + await user.keyboard("a b{Enter}"); + expect(input).toHaveValue("a b"); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("Escape closes the tooltip and keeps focus on the button", async () => { + render( + Native button} + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const button = screen.getByRole("button", { name: "Native button" }); + + await user.keyboard("{Tab}"); + await user.keyboard("{Enter}"); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard("{Escape}"); + expect(screen.queryByRole("tooltip")).toBeNull(); + expect(button).toHaveFocus(); + }); + + it("toggles once when Enter is held down", async () => { + render( + Native button} + /> + ); + const button = screen.getByRole("button", { name: "Native button" }); + + // Holding a key sends one keydown, then repeated keydowns with repeat set + fireEvent.keyDown(button, { key: "Enter" }); + fireEvent.keyDown(button, { key: "Enter", repeat: true }); + fireEvent.keyDown(button, { key: "Enter", repeat: true }); + fireEvent.keyDown(button, { key: "Enter", repeat: true }); + fireEvent.keyUp(button, { key: "Enter" }); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + }); + + it("a click in a text box opens the tooltip and a second click doesn't close it", async () => { + render(} />); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const input = screen.getByRole("textbox", { name: "Name" }); + + await user.click(input); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + await user.click(input); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + }); + + it("Space on a check box opens the tooltip and doesn't close it on the next Space", async () => { + render( + } + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const checkbox = screen.getByRole("checkbox", { name: "Agree" }); + + await user.keyboard("{Tab}"); + await user.keyboard(" "); + expect(checkbox).toBeChecked(); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + + await user.keyboard(" "); + expect(checkbox).not.toBeChecked(); + expect(screen.queryByRole("tooltip")).toBeInTheDocument(); + }); + + it("Enter on a nested tooltip's trigger opens only the nested tooltip", async () => { + render( + + Inner button} + /> + + } + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}"); + expect(screen.getByRole("button", { name: "Inner button" })).toHaveFocus(); + await user.keyboard("{Enter}"); + expect(screen.getAllByRole("tooltip").map(tooltip => tooltip.textContent)).toEqual(["Inner text"]); + + await user.keyboard("{Enter}"); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("Escape inside custom content closes the tooltip and moves focus back to the trigger", async () => { + render( + Native button} + renderMethod="custom" + htmlMessage={} + textMessage={undefined} + /> + ); + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + + await user.keyboard("{Tab}{Enter}{Tab}"); + expect(screen.getByRole("button", { name: "Inside tooltip" })).toHaveFocus(); + + await user.keyboard("{Escape}"); + expect(screen.queryByRole("tooltip")).toBeNull(); + expect(screen.getByRole("button", { name: "Native button" })).toHaveFocus(); + }); + }); + it("open tooltip onClick", async () => { render(); const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); diff --git a/packages/pluggableWidgets/tooltip-web/src/utils/useFloatingUI.ts b/packages/pluggableWidgets/tooltip-web/src/utils/useFloatingUI.ts index 2b01bdb341..a6d4124a60 100644 --- a/packages/pluggableWidgets/tooltip-web/src/utils/useFloatingUI.ts +++ b/packages/pluggableWidgets/tooltip-web/src/utils/useFloatingUI.ts @@ -7,7 +7,6 @@ import { ReferenceElement, safePolygon, shift, - useClick, useDismiss, useFloating, UseFloatingReturn, @@ -16,7 +15,8 @@ import { useInteractions, useRole } from "@floating-ui/react"; -import { Dispatch, SetStateAction, useCallback } from "react"; +import { Dispatch, FocusEvent, SetStateAction, useCallback, useEffect, useRef } from "react"; +import { useKeyboardClick } from "./useKeyboardClick"; import { OpenOnEnum } from "../../typings/TooltipProps"; interface FloatingProps { position: Placement; @@ -36,8 +36,24 @@ interface InternalFloatingProps { }; blurFocusEvents: { onFocus: () => void; - onBlur: () => void; + onBlur: (event: FocusEvent) => void; }; + floatingFocusEvents: { + onBlur: (event: FocusEvent) => void; + }; +} + +const FOCUSABLE_SELECTOR = [ + "button:not([disabled])", + "a[href]", + "input:not([disabled]):not([type='hidden'])", + "select:not([disabled])", + "textarea:not([disabled])", + "[tabindex]:not([tabindex='-1'])" +].join(","); + +function contains(parent: Element | null | undefined, child: EventTarget | null): boolean { + return !!parent && child instanceof Node && parent.contains(child); } type FloatingPropsReturn = Partial> & @@ -46,11 +62,29 @@ type FloatingPropsReturn = Partial> & export function useFloatingUI(props: FloatingProps): FloatingPropsReturn { const { position, showTooltip, setShowTooltip, arrowElement, openOn } = props; + const elementsRef = useRef<{ reference: Element | null; floating: HTMLElement | null }>({ + reference: null, + floating: null + }); + + const onOpenChange = useCallback( + (open: boolean, _event?: Event, reason?: string): void => { + const { reference, floating } = elementsRef.current; + // Escape removes the tooltip content. If focus was inside it, the browser drops focus to the + // top of the page, so move it back to the trigger first. + if (!open && reason === "escape-key" && contains(floating, document.activeElement)) { + reference?.querySelector(FOCUSABLE_SELECTOR)?.focus(); + } + setShowTooltip(open); + }, + [setShowTooltip] + ); + const { refs, floatingStyles, context, middlewareData, placement } = useFloating({ strategy: "fixed", placement: position, open: showTooltip, - onOpenChange: setShowTooltip, + onOpenChange, middleware: [ offset(8), flip({ @@ -73,13 +107,29 @@ export function useFloatingUI(props: FloatingProps): FloatingPropsReturn { handleClose: safePolygon() }); const focus = useFocus(context, { enabled: openOn === "hoverFocus" }); - const click = useClick(context, { toggle: showTooltip, enabled: openOn === "click" }); + const click = useKeyboardClick(context, { enabled: openOn === "click" }); const dismiss = useDismiss(context, { outsidePress: true }); const role = useRole(context, { role: "tooltip" }); + useEffect(() => { + elementsRef.current = { reference: refs.domReference.current, floating: refs.floating.current }; + }); + const onShow = useCallback(() => setShowTooltip(true), [setShowTooltip]); - const onHide = useCallback(() => setShowTooltip(false), [setShowTooltip]); - const blurFocusEvents = { onFocus: onShow, onBlur: onHide }; + // Keep the tooltip open while focus moves between the trigger and its content, so a keyboard user can + // reach a button inside custom content. Close it when focus leaves both. + const onFocusOut = useCallback( + (event: FocusEvent) => { + const next = event.relatedTarget; + if (contains(refs.domReference.current, next) || contains(refs.floating.current, next)) { + return; + } + setShowTooltip(false); + }, + [refs, setShowTooltip] + ); + const blurFocusEvents = { onFocus: onShow, onBlur: onFocusOut }; + const floatingFocusEvents = { onBlur: onFocusOut }; const side = placement.split("-")[0]; const alignment = placement.split("-")[1]; @@ -104,6 +154,7 @@ export function useFloatingUI(props: FloatingProps): FloatingPropsReturn { return { arrowStyles, blurFocusEvents, + floatingFocusEvents, floatingStyles, getFloatingProps, getReferenceProps, diff --git a/packages/pluggableWidgets/tooltip-web/src/utils/useKeyboardClick.ts b/packages/pluggableWidgets/tooltip-web/src/utils/useKeyboardClick.ts new file mode 100644 index 0000000000..ba3030252f --- /dev/null +++ b/packages/pluggableWidgets/tooltip-web/src/utils/useKeyboardClick.ts @@ -0,0 +1,133 @@ +import { ElementProps, FloatingRootContext } from "@floating-ui/react"; +import { KeyboardEvent, MouseEvent, useMemo, useRef } from "react"; + +// Elements that a user activates with Enter or Space. Text inputs and other typeable elements are left out on purpose. +const ACTIVATABLE_SELECTOR = [ + "button", + "a[href]", + 'input[type="button"]', + 'input[type="submit"]', + 'input[type="reset"]', + '[role="button"]', + '[role="link"]' +].join(","); + +// Form controls that a user types in or changes. A click on them opens the tooltip but never closes it, +// so moving the cursor in a text box or ticking a check box doesn't hide it. +const FORM_CONTROL_SELECTOR = "input, textarea, select, label"; + +function isActivatable(target: EventTarget | null): boolean { + return target instanceof HTMLElement && !target.isContentEditable && target.matches(ACTIVATABLE_SELECTOR); +} + +function isFormControl(target: EventTarget | null): boolean { + return ( + target instanceof HTMLElement && + !isActivatable(target) && + (target.isContentEditable || target.closest(FORM_CONTROL_SELECTOR) !== null) + ); +} + +/** + * True when the event comes from this tooltip's own trigger, not from a tooltip nested inside it. + * Without this check, Enter on a nested trigger toggles the outer tooltip too. + */ +function isOwnEvent(event: KeyboardEvent | MouseEvent): boolean { + const target = event.target; + if (!(target instanceof Element)) { + return false; + } + return target.closest(".widget-tooltip") === event.currentTarget.closest(".widget-tooltip"); +} + +interface UseKeyboardClickProps { + enabled: boolean; +} + +/** + * Toggles the tooltip on click, Enter and Space. + * + * Floating UI's `useClick` relies on the browser dispatching a native `click` when Enter or Space is + * pressed on a button. Some trigger widgets, like the Mendix action button, handle those keys + * themselves and dispatch no `click`, so the tooltip never opened from the keyboard. + * This hook toggles on the key itself and skips the native `click` that may follow it. + * + * The handlers run in the capture phase: a Mendix action button with an action stops propagation + * of `click` and `keydown`, so bubble-phase handlers on the wrapper never see them. The handlers + * never stop propagation or prevent default, so the trigger's own action still runs. + */ +export function useKeyboardClick( + context: Pick, + { enabled }: UseKeyboardClickProps +): ElementProps { + const { open, onOpenChange } = context; + // Set when a key press toggled the tooltip, so the native click of the same activation is skipped + const keyToggledRef = useRef(false); + const spaceDownRef = useRef(false); + + const reference = useMemo(() => { + const toggle = (event: KeyboardEvent | MouseEvent): void => { + onOpenChange(!open, event.nativeEvent, "click"); + }; + const openOnly = (event: MouseEvent): void => { + if (!open) { + onOpenChange(true, event.nativeEvent, "click"); + } + }; + + return { + onKeyDownCapture(event: KeyboardEvent) { + keyToggledRef.current = false; + if (!isOwnEvent(event) || !isActivatable(event.target)) { + return; + } + if (event.repeat) { + // Holding a key sends repeated keydowns. Toggle once per press and skip the native + // click a repeated Enter dispatches on a button. + keyToggledRef.current = event.key === "Enter"; + return; + } + if (event.key === "Enter") { + keyToggledRef.current = true; + toggle(event); + } else if (event.key === " ") { + spaceDownRef.current = true; + } + }, + onKeyUpCapture(event: KeyboardEvent) { + if (event.key !== " " || !spaceDownRef.current || !isOwnEvent(event)) { + return; + } + spaceDownRef.current = false; + if (isActivatable(event.target)) { + keyToggledRef.current = true; + toggle(event); + } + }, + onPointerDownCapture() { + keyToggledRef.current = false; + spaceDownRef.current = false; + }, + onBlur() { + keyToggledRef.current = false; + spaceDownRef.current = false; + }, + onClickCapture(event: MouseEvent) { + if (keyToggledRef.current) { + keyToggledRef.current = false; + return; + } + if (!isOwnEvent(event)) { + return; + } + if (isFormControl(event.target)) { + openOnly(event); + return; + } + toggle(event); + } + }; + }, [open, onOpenChange]); + + return useMemo(() => (enabled ? { reference } : {}), [enabled, reference]); +}