Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(dropdown): keep the toggle's tooltip reachable, so it can be taken down
Elian Doran1fc61e3209b7
diff --git a/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx b/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsxindex 9799601c83..dcc3de163b 100644--- a/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";import Dropdown from "./Dropdown";// Bootstrap is left real here — unlike Dropdown.spec.tsx, which mocks it away to assert the component's-// wiring — because what is under test is which element Bootstrap ends up attached to.+// wiring — because what is under test is what Bootstrap does with the elements it is handed.class ResizeObserverStub {observe() {}@@ -17,6 +17,21 @@ globalThis.ResizeObserver = globalThis.ResizeObserver ?? (ResizeObserverStub asdescribe("Dropdown tooltip", () => {let container: HTMLElement;+ /** Bootstrap defers both the show and its completion, so the tooltip settles a tick after the event. */+ const settle = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 40)); });+ const shownTooltips = () => document.querySelectorAll(".tooltip").length;++ function mount() {+ act(() => render(<Dropdown title="Show help" iconAction hideToggleArrow>item</Dropdown>, container));+ const toggle = container.querySelector("button");+ expect(toggle).not.toBeNull();+ return toggle as HTMLButtonElement;+ }++ /** Bootstrap listens for `mouseover` and tells a hover from a move within by the related target. */+ const hover = (element: Element) =>+ act(() => { element.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, relatedTarget: null })); });+beforeEach(() => {container = document.createElement("div");document.body.appendChild(container);@@ -30,27 +45,31 @@ describe("Dropdown tooltip", () => {}});- it("hangs the tooltip off the toggle rather than off the wrapper the open menu sits in", () => {- act(() => render(<Dropdown title="Show help" iconAction hideToggleArrow>item</Dropdown>, container));-+ it("hangs the tooltip off the wrapper, which Bootstrap will register it against", () => {+ const toggle = mount();const wrapper = container.querySelector(".dropdown");- const toggle = container.querySelector("button");- const menu = container.querySelector(".dropdown-menu");- expect(toggle).not.toBeNull();- expect(menu).not.toBeNull();- // Bootstrap takes the `title` of whatever it is initialised on over to `data-bs-original-title`- // — so this says which element it is driving the hover of, without reaching into its internals.- expect(toggle?.getAttribute("data-bs-original-title"), "driven by the toggle").toBe("Show help");- expect(wrapper?.getAttribute("data-bs-original-title"), "not by the wrapper").toBeNull();+ // Bootstrap moves the `title` of whatever it is initialised on into `data-bs-original-title`, so+ // this says which element it is driving — without reaching into its internals.+ expect(wrapper?.getAttribute("data-bs-original-title"), "driven by the wrapper").toBe("Show help");+ expect(wrapper?.getAttribute("title"), "handed over to Bootstrap").toBeNull();++ // Not the toggle: Bootstrap keeps one component instance per element and the toggle is already+ // the dropdown's, so a tooltip put there is refused registration and can never be disposed.+ expect(toggle.getAttribute("data-bs-original-title"), "not by the toggle").toBeNull();+ });++ it("takes its tooltip down with it, rather than leaving the popup on screen", async () => {+ const toggle = mount();- // Which is the point of it: the wrapper holds the menu as well, so a tooltip driven by the- // wrapper stayed up over the menu the pointer had moved into. The toggle never holds the menu.- expect(wrapper?.contains(menu ?? null), "the wrapper holds the menu").toBe(true);- expect(toggle?.contains(menu ?? null), "the toggle does not").toBe(false);+ await hover(toggle);+ await settle();+ expect(shownTooltips(), "shown on hover").toBe(1);- // And with nothing left on the wrapper, the browser's own tooltip can't double up with ours.- expect(wrapper?.getAttribute("title")).toBeNull();- expect(toggle?.getAttribute("title"), "handed over to Bootstrap").toBeNull();+ // Unmounted with the tooltip still up — a sidebar card rebuilt under the pointer, say. Nothing+ // else would ever take the popup down, so they piled up on screen one hover at a time.+ await act(async () => render(null, container));+ await settle();+ expect(shownTooltips(), "gone with the dropdown").toBe(0);});});diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex ac10e9153d..4da61423b9 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -64,15 +64,18 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chiplacement: titlePosition ?? "bottom",fallbackPlacements: [ titlePosition ?? "bottom" ]}), [title, titleOptions, titlePosition]);- // On the toggle button rather than on the wrapper, and left to Bootstrap's own hover/focus triggering.- // The wrapper holds the open menu as well (for a non-portaled dropdown), so a tooltip bound to it stayed- // up over the menu the pointer had moved into — which is what manual triggering off the button's own- // mouseenter/mouseleave used to work around. Bound to the button, that can't arise: the button never- // contains the menu. And Bootstrap's own triggering is worth having back — it keeps the hover state- // that decides whether a tooltip stays up, which no amount of driving it from outside can stand in for.- const { hideTooltip } = useTooltip(triggerRef, tooltipConfig);-const [ shown, setShown ] = useState(false);+ // On the wrapper, not on the toggle: Bootstrap keeps one component instance per element and the toggle+ // is already the dropdown's own, so a tooltip put there is refused registration and can never be+ // disposed — it goes on showing its title with nothing left to take it down.+ //+ // Triggering is Bootstrap's, though, rather than driven from the toggle's mouseenter/mouseleave as it+ // once was: only Bootstrap's own listeners keep the hover state it decides by, and a tooltip shown+ // around it is liable to be taken away again under the pointer. What that arrangement was for — the+ // wrapper holding the open menu too, so the title hung over the menu the pointer had moved into — is+ // answered by silencing the tooltip for as long as the menu is up.+ const { hideTooltip } = useTooltip(containerRef, tooltipConfig, !shown);+// A portaled menu lives in `document.body`, detached from the toggle's subtree. Mounting it eagerly// for every instance leaves an empty menu wrapper in the body for every note context/tab, so only// mount it while it's actually needed: open (`shown`), about to open (`armed` — set on interaction@@ -194,7 +197,9 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi);return (- <div ref={containerRef} class={`dropdown ${className ?? ""}`} style={{ display: "flex" }}>+ // `title` stands in only for the moment before the tooltip is wired: Bootstrap moves the+ // attribute into the tooltip and drops it, so the browser's own doesn't double up with ours.+ <div ref={containerRef} class={`dropdown ${className ?? ""}`} style={{ display: "flex" }} title={title}><buttonclassName={`${iconAction ? "icon-action" : "btn"} ${!noSelectButtonStyle ? "select-button" : ""} ${buttonClassName ?? ""} ${!hideToggleArrow ? "dropdown-toggle" : ""}`}ref={triggerRef}@@ -205,10 +210,6 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chiaria-expanded="false"id={id ?? ariaId}disabled={disabled}- // Sits beside the tooltip rather than being what drives it: Bootstrap takes the attribute- // over on init (it moves it into the tooltip and drops it), so it only stands in for the- // moment before, and stops the browser's own tooltip doubling up with ours afterwards.- title={title}// Mount the portaled menu just before it can open: any interaction that leads to a// Bootstrap open (pointer press, or focusing the toggle ahead of a keyboard open) is// preceded by one of these, so `_menu` is wired by the time the click/keydown fires.diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex a434e510ee..09ee14f210 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -990,46 +990,64 @@ TooltipProto.dispose = function () {this._element = disposedTooltipPlaceholder.element;};-export function useTooltip(elRef: RefObject<HTMLElement>, config: Partial<Tooltip.Options>) {+/**+ * A Bootstrap tooltip whose lifetime follows the element it hangs off.+ *+ * @param enabled while false the tooltip is put away and kept away, for a host with something of its own+ * to put in front of the user — see {@link Dropdown}, which silences its toggle's title+ * for as long as the menu that title opened is on screen.+ */+export function useTooltip(elRef: RefObject<HTMLElement>, config: Partial<Tooltip.Options>, enabled = true) {+ const tooltipRef = useRef<Tooltip | null>(null);+useEffect(() => {if (!elRef?.current) return;const element = elRef.current;- const $el = $(element);- // Dispose any existing tooltip before creating a new one+ // Held on to rather than looked up again through `Tooltip.getInstance`: Bootstrap keeps one+ // component instance per element and refuses to register a second (it logs and returns), so on+ // an element another Bootstrap component has already claimed — a dropdown's toggle, say — the+ // lookup comes back empty. The tooltip works all the same, being a live object with its own+ // listeners, but nothing can reach it to dispose it, and whatever it has shown is left on+ // screen for good.Tooltip.getInstance(element)?.dispose();- $el.tooltip(config);-- // Capture the tooltip instance now, since elRef.current may be null during cleanup.- const tooltip = Tooltip.getInstance(element);+ const tooltip = new Tooltip(element, config);+ tooltipRef.current = tooltip;return () => {+ tooltipRef.current = null;// Dispose even when the trigger element is already detached (e.g. a keyed remount// replaced it before this cleanup ran) — dispose() also removes a currently-shown// popup from the DOM, and with the trigger gone nothing else ever would (#10567).// The pending-callback crash of bootstrap#37474 is handled by the dispose() patch above.- tooltip?.dispose();+ tooltip.dispose();};}, [ elRef, config ]);- const showTooltip = useCallback(() => {- if (!elRef?.current) return;+ // Runs after the effect above, so a tooltip just recreated for a new config is caught by it too —+ // hence the same dependencies alongside `enabled`.+ useEffect(() => {+ const tooltip = tooltipRef.current;+ if (!tooltip) return;- const element = elRef.current;- const tooltip = Tooltip.getInstance(element);- if (tooltip) {- clearStaleHoverState(tooltip);+ if (enabled) {+ tooltip.enable();+ } else {+ tooltip.hide();+ tooltip.disable();}- $(element).tooltip("show");- }, [ elRef, config ]);+ }, [ enabled, elRef, config ]);- const hideTooltip = useCallback(() => {- if (!elRef?.current) return;+ const showTooltip = useCallback(() => {+ const tooltip = tooltipRef.current;+ if (!tooltip) return;++ clearStaleHoverState(tooltip);+ tooltip.show();+ }, []);- const $el = $(elRef.current);- $el.tooltip("hide");- }, [ elRef ]);+ const hideTooltip = useCallback(() => tooltipRef.current?.hide(), []);useDebugValue(config.title);