Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/custom task states: refactor the editor tooltip

Adorian Dorancf59edac49ea
diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts
index e73bbedd50..b4ef423fc9 100644
--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts
+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts
@@ -1,8 +1,15 @@
import { DEFAULT_TASK_STATES, DONE_STATE_NAME, isAnchorState, NONE_STATE_NAME, type TaskStateDef } from "@triliumnext/commons";
-import { Tooltip } from "bootstrap";
import { Command, getEnvKeystrokeText, ListEditing, Plugin, TodoList, type Editor, type ModelElement, type ViewElement } from "ckeditor5";
import { onTodoRowSplit } from "../todo_list_uncheck_on_enter.js";
+import { EditorTooltipManager, type TooltipHandle } from "../../utils/editor_tooltip_manager.js";
+
+/**
+ * Dwell delay before a hover or a stationary caret pops the checkbox tooltip.
+ * Long enough that brief flyovers don't spawn a tooltip, short enough that
+ * intentional attention consistently produces one.
+ */
+const TOOLTIP_DWELL_MS = 200;
export const TASK_STATE_ATTRIBUTE = "taskState";
const TODO_LIST_CHECKED_ATTRIBUTE = "todoListChecked";
@@ -31,27 +38,60 @@ export default class TodoListMultistateEditing extends Plugin {
}
/**
- * Checkboxes that currently have a tooltip attached, mapped to the task state
- * baked into their tooltip title. Used to dispose stale tooltips on detached
- * checkboxes AND to refresh a tooltip when its checkbox's state changes.
+ * Shared tooltip stack. One hover handle per rendered checkbox plus one
+ * caret handle (moved between checkboxes as the caret does) push/pop
+ * against it — only the top of the stack is on screen at a time. See
+ * {@link EditorTooltipManager} for the rationale.
+ */
+ private _tooltipManager!: EditorTooltipManager;
+
+ /** Hover-driven handle per rendered checkbox. Disposed when the checkbox detaches. */
+ private readonly _hoverHandles = new Map<HTMLInputElement, TooltipHandle>();
+
+ /**
+ * Last known task state per rendered checkbox — used to detect content-changing
+ * events (Ctrl+Shift+Enter, native toggle) so the caret handle can force an
+ * immediate `show()` instead of a delayed one.
*/
- private readonly _checkboxTooltips = new Map<HTMLInputElement, string | null>();
+ private readonly _knownState = new Map<HTMLInputElement, string | null>();
+
+ /** Caret-driven handle, if the caret is currently inside a todo item. */
+ private _caretHandle: TooltipHandle | null = null;
+
+ /** DOM checkbox the caret handle is currently attached to. */
+ private _caretInput: HTMLInputElement | null = null;
/**
- * The checkbox whose tooltip is currently force-shown because the caret is in
- * its todo item. Tracked so a follow-up selection change can `hide()` the
- * previous tooltip before `show()`ing the next, and so a render that recreates
- * the input can re-attach + re-show without a visible gap (same pattern as
- * {@link CollapsibleEditing#registerSummaryTooltips}).
+ * `data-list-item-id` of the todo item the caret is currently inside, or
+ * `null` when the caret isn't inside a todo item. Tracks the *conceptual*
+ * caret target so a mere DOM-node rebuild (Ctrl+Shift+Enter across the
+ * isCompleted boundary recreates the checkbox input) doesn't get treated
+ * as a fresh visit and delayed by the dwell timer.
*/
- private _caretCheckbox: HTMLInputElement | null = null;
+ private _caretItemId: string | null = null;
+
+ /** State-name → definition, keyed for `buildTooltipTitle` calls. */
+ private _stateByName!: Map<string, TaskStateDef>;
+
+ /** Translate function resolved once from editor config; identity fallback. */
+ private _translate!: TranslateFn;
init() {
const editor = this.editor;
const states = getConfiguredTaskStates(editor);
- const stateByName = new Map(states.map((state) => [state.name, state]));
- const translate = (editor.config.get("translate") as ((key: string, params?: Record<string, unknown>) => string) | undefined)
+ this._stateByName = new Map(states.map((state) => [state.name, state]));
+ this._translate = (editor.config.get("translate") as TranslateFn | undefined)
?? ((key: string) => key);
+ const stateByName = this._stateByName;
+ this._tooltipManager = new EditorTooltipManager({
+ tooltipOptions: {
+ // Bootstrap's default sanitizer strips `data-*` attributes, which
+ // the state-icon span in the tooltip relies on to render the
+ // correct colour/glyph.
+ sanitize: false,
+ customClass: "text-editor-content-tooltip"
+ }
+ });
editor.model.schema.extend("$block", {allowAttributes: TASK_STATE_ATTRIBUTE});
@@ -113,87 +153,19 @@ export default class TodoListMultistateEditing extends Plugin {
if (!domRoot) {
return;
}
- // CKEditor recreates the checkbox element when a todo item reconverts
- // (e.g. on click); dispose tooltips left on the detached old checkboxes.
- for (const input of this._checkboxTooltips.keys()) {
- if (!input.isConnected) {
- Tooltip.getInstance(input)?.dispose();
- this._checkboxTooltips.delete(input);
- if (this._caretCheckbox === input) {
- this._caretCheckbox = null;
- }
- }
- }
- // Track inputs whose tooltip was (re)created this render so the caret
- // sync can re-`show()` them even when the caret target didn't change.
- const recreated = new Set<HTMLInputElement>();
- for (const input of domRoot.querySelectorAll<HTMLInputElement>(".todo-list__label input[type=\"checkbox\"]")) {
- const currentState = readTaskState(input);
- // Skip if the tooltip is already up to date for this state.
- if (Tooltip.getInstance(input) && this._checkboxTooltips.get(input) === currentState) {
- continue;
- }
- const wasTracked = this._checkboxTooltips.has(input);
- // Bootstrap stamps `aria-describedby` while a tooltip is shown and
- // clears it on hide, so this tells us whether we're about to tear
- // down a currently-visible popup — regardless of whether it was
- // driven by hover or by the caret. If we don't re-show after the
- // rebuild, a state change on a hovered checkbox blanks the hint
- // until the user moves the mouse out and back in.
- const wasShown = input.hasAttribute("aria-describedby");
- Tooltip.getInstance(input)?.dispose();
- const title = buildTooltipTitle(input.ownerDocument, currentState, stateByName, translate);
- new Tooltip(input, {
- title,
- html: true,
- // Bootstrap's default sanitizer strips `data-*` attributes, which
- // the tooltip's state-icon span relies on to render the correct
- // colour/glyph. The HTML is built from translations we control
- // (with user values interpolated through i18next's default
- // escaping) so disabling the sanitizer is safe here.
- sanitize: false,
- // Manual trigger — Bootstrap's default `hover focus` fires
- // `_leave` on stray focusout events (the checkbox has
- // `tabindex="-1"` and can receive programmatic focus during
- // reconversion), which raced our caret-driven `show()` and
- // dismissed the tooltip. Everything visibility-related is
- // driven from `_syncCaretTooltip` and the hover listeners
- // attached in `_attachHoverListeners`.
- trigger: "manual",
- customClass: "text-editor-content-tooltip"
- });
- this._checkboxTooltips.set(input, currentState);
- recreated.add(input);
- // Preserve visibility across the dispose+recreate. This covers
- // BOTH the hover-shown case (Bootstrap sets `aria-describedby`
- // during `show()`) and the caret-shown case for the same input;
- // for the checkbox-recreated case (fresh input, no aria yet),
- // `_syncCaretTooltip(recreated)` below takes over.
- if (wasShown) {
- Tooltip.getInstance(input)?.show();
- }
- // Attach hover listeners once per input — they use dynamic
- // `Tooltip.getInstance(input)` so they keep working after a
- // state-change refresh replaces the tooltip on the same element.
- if (!wasTracked) {
- this._attachHoverListeners(input);
- }
- }
- // Re-derive the caret target from the model. Covers three cases:
- // a) same input, same tooltip — nothing to do;
- // b) same input, tooltip recreated (state change on the item) —
- // force `show()` so the hint stays up;
- // c) input recreated (Ctrl+Shift+Enter across isCompleted boundary)
- // — old ref was nulled in the reaper above; re-attach to the
- // new input and `show()` its fresh tooltip.
- this._syncCaretTooltip(recreated);
+ // Refresh handles first; the return value tells `_syncCaretTooltip`
+ // whether the caret's item changed state on this render (Ctrl+Shift+Enter,
+ // native toggle, etc.) so it can force an immediate `show()` instead
+ // of waiting out the dwell timer again.
+ const caretItemStateChanged = this._refreshHoverHandles(domRoot);
+ this._syncCaretTooltip({ forceShowIfSameTarget: caretItemStateChanged });
});
// Keyboard-only navigation into an <li> doesn't move DOM focus (the editable
- // root keeps it), so Bootstrap's focus trigger never fires. Drive the tooltip
- // manually from the model selection so keyboard users see the hint too.
+ // root keeps it), so the manager needs to be driven from model-selection
+ // changes to catch the keyboard-into-todo case.
this.listenTo(editor.model.document.selection, "change:range", () => {
- this._syncCaretTooltip();
+ this._syncCaretTooltip({ forceShowIfSameTarget: false });
});
// A new row split off with Enter inherits the previous row's `taskState` (writer.split
@@ -263,79 +235,145 @@ export default class TodoListMultistateEditing extends Plugin {
}
override destroy() {
- for (const input of this._checkboxTooltips.keys()) {
- Tooltip.getInstance(input)?.dispose();
+ this._caretHandle?.dispose();
+ this._caretHandle = null;
+ this._caretInput = null;
+ this._caretItemId = null;
+ for (const handle of this._hoverHandles.values()) {
+ handle.dispose();
}
- this._checkboxTooltips.clear();
- this._caretCheckbox = null;
+ this._hoverHandles.clear();
+ this._knownState.clear();
+ this._tooltipManager?.destroy();
super.destroy();
}
/**
- * Attach hover triggers on a freshly-tracked checkbox. Both handlers no-op
- * when the caret is already inside the same todo item — the caret-driven
- * flow already owns the tooltip's visibility there, and letting `show()` /
- * `hide()` run again produced a rebuild-then-tear-down flicker.
- * `Tooltip.getInstance(input)` is resolved lazily so the same closures keep
- * working after a state-change refresh replaces the tooltip on the same
- * DOM element.
+ * Reconcile hover handles with the current set of rendered checkboxes.
+ * Creates a handle + attaches mouseenter/mouseleave for each new checkbox,
+ * disposes handles whose input was detached, and refreshes content on
+ * inputs whose task state changed since the last render.
+ *
+ * Returns `true` iff the caret's own checkbox saw a state change on this
+ * render — the caller uses that to force `show()` its caret handle instead
+ * of waiting out the dwell timer (state change should reveal the tooltip
+ * immediately, per the "reappear on state change" spec).
*/
- private _attachHoverListeners(input: HTMLInputElement): void {
- const isCaretInThisItem = () => {
- const itemId = input.closest<HTMLElement>("li")?.getAttribute("data-list-item-id");
- return !!itemId && this._isCaretInsideItem(itemId);
- };
- input.addEventListener("mouseenter", () => {
- if (isCaretInThisItem()) {
- return;
+ private _refreshHoverHandles(domRoot: HTMLElement): boolean {
+ // Reap detached checkboxes.
+ for (const input of Array.from(this._hoverHandles.keys())) {
+ if (!input.isConnected) {
+ this._hoverHandles.get(input)?.dispose();
+ this._hoverHandles.delete(input);
+ this._knownState.delete(input);
+ if (input === this._caretInput) {
+ // Caret handle for a detached input; drop it — `_syncCaretTooltip`
+ // will pick up the new one via `_findCaretCheckbox`.
+ this._caretHandle?.dispose();
+ this._caretHandle = null;
+ this._caretInput = null;
+ }
}
- Tooltip.getInstance(input)?.show();
- });
- input.addEventListener("mouseleave", () => {
- if (isCaretInThisItem()) {
- return;
+ }
+
+ let caretItemStateChanged = false;
+
+ for (const input of domRoot.querySelectorAll<HTMLInputElement>(".todo-list__label input[type=\"checkbox\"]")) {
+ const currentState = readTaskState(input);
+ const previousState = this._knownState.get(input);
+ const isNew = !this._hoverHandles.has(input);
+ this._knownState.set(input, currentState);
+
+ if (isNew) {
+ const handle = this._tooltipManager.createHandle(input, this._computeContent(input));
+ this._hoverHandles.set(input, handle);
+ // Cache the enclosing item's id — stable for this input's life, and we
+ // need it on every hover event to decide whether to yield to the caret.
+ const ownItemId = input.closest<HTMLElement>("li")?.getAttribute("data-list-item-id") ?? null;
+ // Hover on the checkbox whose item already has the caret is a no-op:
+ // the caret handle already owns that item's tooltip visibility, and
+ // running the dwell + push cycle on top of it only confuses the stack.
+ const ownedByCaret = () => ownItemId !== null && ownItemId === this._caretItemId;
+ input.addEventListener("mouseenter", () => {
+ if (ownedByCaret()) return;
+ handle.showAfter(TOOLTIP_DWELL_MS);
+ });
+ input.addEventListener("mouseleave", () => {
+ if (ownedByCaret()) return;
+ handle.hide();
+ });
+ } else if (currentState !== previousState) {
+ this._hoverHandles.get(input)?.setContent(this._computeContent(input));
+ if (input === this._caretInput) {
+ caretItemStateChanged = true;
+ }
}
- Tooltip.getInstance(input)?.hide();
- });
+ }
+
+ return caretItemStateChanged;
}
/**
- * Reconcile {@link _caretCheckbox} against the current model caret target and
- * drive the corresponding Bootstrap tooltip's visibility. Called from the
- * selection listener (target may change) AND from the render listener
- * (tooltips may have been (re)created for the current target).
+ * Reconcile the caret handle against the current model caret target. Called
+ * on selection changes AND at the end of every render.
+ *
+ * The item-id vs input-identity distinction matters: a state change across
+ * the isCompleted boundary reconverts the todo item, giving us a new DOM
+ * checkbox even though the caret hasn't moved. We want the tooltip to
+ * reappear immediately in that case (per "reappear on state change"), not
+ * to be delayed as if the user just navigated in.
*
- * `recreated` is the set of inputs whose tooltip was just replaced this render;
- * when the caret target is in that set, `show()` is forced even if the target
- * itself didn't change, so a state-change render keeps the hint visible.
+ * Cases:
+ * - Item unchanged, input unchanged, state unchanged → no-op.
+ * - Item unchanged, input unchanged, state changed (`forceShowIfSameTarget`)
+ * → refresh content, force immediate `show()`.
+ * - Item unchanged, input replaced (isCompleted-boundary reconversion)
+ * → rebuild handle on the new input, immediate `show()`.
+ * - Item changed (user actually moved the caret) → new handle,
+ * `showAfter(TOOLTIP_DWELL_MS)`, so drive-throughs don't spawn a tooltip.
*/
- private _syncCaretTooltip(recreated?: ReadonlySet<HTMLInputElement>): void {
+ private _syncCaretTooltip(options: { forceShowIfSameTarget: boolean }): void {
const target = this._findCaretCheckbox();
- const targetChanged = this._caretCheckbox !== target;
- if (targetChanged && this._caretCheckbox) {
- Tooltip.getInstance(this._caretCheckbox)?.hide();
+ const targetItemId = target?.closest<HTMLElement>("li")?.getAttribute("data-list-item-id") ?? null;
+ const itemChanged = targetItemId !== this._caretItemId;
+ const inputChanged = target !== this._caretInput;
+
+ if (!itemChanged) {
+ if (inputChanged) {
+ // Same conceptual item, but the DOM input was recreated — rebuild
+ // the handle and show immediately (no dwell delay for a rebuild).
+ this._caretHandle?.dispose();
+ this._caretHandle = null;
+ this._caretInput = target;
+ if (target) {
+ this._caretHandle = this._tooltipManager.createHandle(target, this._computeContent(target));
+ this._caretHandle.show();
+ }
+ } else if (target && this._caretHandle && options.forceShowIfSameTarget) {
+ this._caretHandle.setContent(this._computeContent(target));
+ this._caretHandle.show();
+ }
+ return;
}
- this._caretCheckbox = target;
- if (target && (targetChanged || recreated?.has(target))) {
- Tooltip.getInstance(target)?.show();
+
+ this._caretHandle?.dispose();
+ this._caretHandle = null;
+ this._caretInput = target;
+ this._caretItemId = targetItemId;
+ if (target) {
+ this._caretHandle = this._tooltipManager.createHandle(target, this._computeContent(target));
+ this._caretHandle.showAfter(TOOLTIP_DWELL_MS);
}
}
- /**
- * True when the caret's model position sits inside a list item whose
- * `listItemId` matches. Used by the mouseleave guard to keep the tooltip up
- * while the caret is in the hovered item, without depending on DOM identity.
- */
- private _isCaretInsideItem(itemId: string): boolean {
- const position = this.editor.model.document.selection.getFirstPosition();
- let candidate = position?.parent ?? null;
- while (candidate) {
- if (candidate.is("element") && candidate.getAttribute("listItemId") === itemId) {
- return true;
- }
- candidate = candidate.parent;
- }
- return false;
+ /** Assemble the tooltip HTML for the given checkbox's current state. */
+ private _computeContent(input: HTMLInputElement): string {
+ return buildTooltipTitle(
+ input.ownerDocument,
+ readTaskState(input),
+ this._stateByName,
+ this._translate
+ );
}
/**
diff --git a/packages/ckeditor5/src/utils/editor_tooltip_manager.spec.ts b/packages/ckeditor5/src/utils/editor_tooltip_manager.spec.ts
new file mode 100644
index 0000000000..e1d7f90dad
--- /dev/null
+++ b/packages/ckeditor5/src/utils/editor_tooltip_manager.spec.ts
@@ -0,0 +1,265 @@
+import { Tooltip } from "bootstrap";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { EditorTooltipManager, type TooltipHandle } from "./editor_tooltip_manager.js";
+
+/**
+ * The visible `.tooltip` popup that Bootstrap adds to the body when a tooltip
+ * is shown. Returns null when nothing is on screen. Used as the ground-truth
+ * for "is the manager currently rendering something".
+ */
+function livePopup(): HTMLElement | null {
+ return document.body.querySelector<HTMLElement>(".tooltip");
+}
+
+/** Text content of the currently-rendered popup, stripped of surrounding whitespace. */
+function livePopupText(): string | null {
+ return livePopup()?.textContent?.trim() ?? null;
+}
+
+describe("EditorTooltipManager", () => {
+ let host: HTMLDivElement;
+ let a: HTMLButtonElement;
+ let b: HTMLButtonElement;
+ let manager: EditorTooltipManager;
+
+ beforeEach(() => {
+ host = document.createElement("div");
+ a = document.createElement("button");
+ a.textContent = "A";
+ b = document.createElement("button");
+ b.textContent = "B";
+ host.appendChild(a);
+ host.appendChild(b);
+ document.body.appendChild(host);
+ manager = new EditorTooltipManager();
+ });
+
+ afterEach(() => {
+ manager.destroy();
+ host.remove();
+ // Belt-and-braces: strip any orphaned Bootstrap popups left over.
+ document.body.querySelectorAll(".tooltip").forEach(el => el.remove());
+ });
+
+ describe("show / hide", () => {
+ it("renders a Bootstrap tooltip on the element when a handle is shown", () => {
+ const handle = manager.createHandle(a, "hello");
+ expect(livePopup()).toBeNull();
+ handle.show();
+ expect(livePopupText()).toBe("hello");
+ });
+
+ it("removes the popup when the only shown handle is hidden", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.show();
+ handle.hide();
+ expect(livePopup()).toBeNull();
+ });
+
+ it("removing a non-top handle leaves the visible tooltip untouched", () => {
+ const top = manager.createHandle(a, "top");
+ const bottom = manager.createHandle(a, "bottom");
+ bottom.show();
+ top.show();
+ expect(livePopupText()).toBe("top");
+ bottom.hide(); // not on top → no visual change
+ expect(livePopupText()).toBe("top");
+ });
+
+ it("popping the top reveals the handle immediately below it", () => {
+ const bottom = manager.createHandle(a, "bottom");
+ const top = manager.createHandle(a, "top");
+ bottom.show();
+ top.show();
+ expect(livePopupText()).toBe("top");
+ top.hide();
+ expect(livePopupText()).toBe("bottom");
+ });
+
+ it("switches element when the top-of-stack handle is on a different element", () => {
+ const handleA = manager.createHandle(a, "A tip");
+ const handleB = manager.createHandle(b, "B tip");
+ handleA.show();
+ expect(livePopupText()).toBe("A tip");
+ handleB.show();
+ expect(livePopupText()).toBe("B tip");
+ handleB.hide();
+ expect(livePopupText()).toBe("A tip");
+ });
+
+ it("show() on a handle already in the stack moves it to the top", () => {
+ const first = manager.createHandle(a, "A");
+ const second = manager.createHandle(b, "B");
+ first.show();
+ second.show();
+ expect(livePopupText()).toBe("B");
+ first.show(); // re-show → moves to top
+ expect(livePopupText()).toBe("A");
+ });
+
+ it("show() no-ops when the element is detached", () => {
+ const handle = manager.createHandle(a, "hello");
+ host.remove();
+ handle.show();
+ expect(livePopup()).toBeNull();
+ });
+ });
+
+ describe("showAfter (dwell delay)", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("shows the tooltip after the specified delay", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.showAfter(1000);
+ expect(livePopup()).toBeNull();
+ vi.advanceTimersByTime(999);
+ expect(livePopup()).toBeNull();
+ vi.advanceTimersByTime(1);
+ expect(livePopupText()).toBe("hello");
+ });
+
+ it("hide() before the timer fires cancels the pending show", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.showAfter(1000);
+ vi.advanceTimersByTime(500);
+ handle.hide();
+ vi.advanceTimersByTime(600);
+ expect(livePopup()).toBeNull();
+ });
+
+ it("show() before the timer fires cancels the pending and shows immediately", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.showAfter(1000);
+ handle.show();
+ expect(livePopupText()).toBe("hello");
+ });
+
+ it("a second showAfter() resets the timer", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.showAfter(1000);
+ vi.advanceTimersByTime(999);
+ handle.showAfter(1000); // reset
+ vi.advanceTimersByTime(999);
+ expect(livePopup()).toBeNull();
+ vi.advanceTimersByTime(1);
+ expect(livePopupText()).toBe("hello");
+ });
+
+ it("dispose() cancels any pending showAfter", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.showAfter(1000);
+ handle.dispose();
+ vi.advanceTimersByTime(2000);
+ expect(livePopup()).toBeNull();
+ });
+ });
+
+ describe("setContent", () => {
+ it("updates the visible tooltip when the handle is on top", () => {
+ const handle = manager.createHandle(a, "before");
+ handle.show();
+ handle.setContent("after");
+ expect(livePopupText()).toBe("after");
+ });
+
+ it("updates the pending content when the handle is not currently shown", () => {
+ const handle = manager.createHandle(a, "initial");
+ handle.setContent("updated");
+ handle.show();
+ expect(livePopupText()).toBe("updated");
+ });
+ });
+
+ describe("dispose", () => {
+ it("removes the handle from the stack", () => {
+ const bottom = manager.createHandle(a, "bottom");
+ const top = manager.createHandle(a, "top");
+ bottom.show();
+ top.show();
+ expect(livePopupText()).toBe("top");
+ top.dispose();
+ expect(livePopupText()).toBe("bottom");
+ });
+
+ it("is idempotent", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.show();
+ handle.dispose();
+ expect(() => handle.dispose()).not.toThrow();
+ });
+ });
+
+ describe("destroy", () => {
+ it("hides any currently-rendered tooltip", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.show();
+ manager.destroy();
+ expect(livePopup()).toBeNull();
+ });
+
+ it("makes handles inert (subsequent show is a no-op)", () => {
+ const handle = manager.createHandle(a, "hello");
+ manager.destroy();
+ handle.show();
+ expect(livePopup()).toBeNull();
+ });
+ });
+
+ describe("tooltip options", () => {
+ it("applies the base options to every popup", () => {
+ const scoped = new EditorTooltipManager({
+ tooltipOptions: { customClass: "test-scope" }
+ });
+ const handle = scoped.createHandle(a, "hello");
+ handle.show();
+ expect(livePopup()?.classList.contains("test-scope")).toBe(true);
+ scoped.destroy();
+ });
+
+ it("uses `manual` trigger regardless of what the caller passes", () => {
+ const scoped = new EditorTooltipManager({
+ tooltipOptions: { trigger: "hover" as Tooltip.Options["trigger"] }
+ });
+ const handle = scoped.createHandle(a, "hello");
+ handle.show();
+ const instance = Tooltip.getInstance(a);
+ const config = (instance as unknown as { _config: { trigger: string } } | null)?._config;
+ expect(config?.trigger).toBe("manual");
+ scoped.destroy();
+ });
+ });
+
+ describe("detached elements", () => {
+ it("silently drops entries whose element is no longer in the DOM", () => {
+ const handle = manager.createHandle(a, "hello");
+ handle.show();
+ a.remove(); // element detaches while its tooltip is up
+ // A subsequent show anywhere triggers _render, which sweeps dead entries.
+ const other = manager.createHandle(b, "other");
+ other.show();
+ expect(livePopupText()).toBe("other");
+ });
+ });
+
+ describe("handle usage patterns", () => {
+ it("supports independent hover + caret handles on the same element without flicker", () => {
+ // Simulate the multistate plugin's hover + caret pair on one checkbox.
+ const hover: TooltipHandle = manager.createHandle(a, "content");
+ const caret: TooltipHandle = manager.createHandle(a, "content");
+
+ caret.show();
+ expect(livePopupText()).toBe("content");
+
+ // Mouse hovers the checkbox — hover pushes; both are on stack, same element,
+ // so `_render` just refreshes content in place.
+ hover.show();
+ expect(livePopupText()).toBe("content");
+
+ // Mouse leaves — hover pops. Same element still on top; still shown.
+ hover.hide();
+ expect(livePopupText()).toBe("content");
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/utils/editor_tooltip_manager.ts b/packages/ckeditor5/src/utils/editor_tooltip_manager.ts
new file mode 100644
index 0000000000..ac8a95d756
--- /dev/null
+++ b/packages/ckeditor5/src/utils/editor_tooltip_manager.ts
@@ -0,0 +1,217 @@
+import { Tooltip } from "bootstrap";
+
+/**
+ * A tooltip request registered with an {@link EditorTooltipManager}. Any number
+ * of independent handles (hover, caret, keyboard-focus …) can be created and
+ * pushed onto the manager's visibility stack independently; only the top of the
+ * stack is actually rendered, and popping it reveals whatever was pushed
+ * underneath.
+ *
+ * All methods are safe to call after {@link dispose}, in any order.
+ */
+export interface TooltipHandle {
+ /**
+ * Push this handle onto the visibility stack. If it's already on the stack,
+ * move it to the top. Cancels any pending {@link showAfter}. No-op if the
+ * handle's element is detached from the DOM.
+ */
+ show(): void;
+ /**
+ * Schedule a {@link show} `ms` from now. If the user calls {@link hide},
+ * {@link dispose}, or {@link show} before the timer fires, the pending
+ * timer is cancelled. Calling {@link showAfter} again resets the timer.
+ * Used for the hover / caret dwell delay so brief flyovers don't pop the
+ * tooltip.
+ */
+ showAfter(ms: number): void;
+ /**
+ * Remove this handle from the visibility stack (revealing whatever is
+ * below) AND cancel any pending {@link showAfter}.
+ */
+ hide(): void;
+ /**
+ * Replace the HTML this handle will show. Takes effect immediately if this
+ * handle is currently on top of the stack.
+ */
+ setContent(content: string): void;
+ /**
+ * Remove this handle from the manager permanently. Idempotent — safe to call
+ * from cleanup code even when a `hide()` already ran.
+ */
+ dispose(): void;
+}
+
+export interface EditorTooltipManagerOptions {
+ /**
+ * Bootstrap Tooltip config applied to every popup this manager creates.
+ * `trigger` is always forced to `"manual"` because the stack, not Bootstrap's
+ * hover/focus event bindings, decides when a tooltip is visible. `html` is
+ * always forced to `true`.
+ */
+ tooltipOptions?: Partial<Tooltip.Options>;
+}
+
+interface StackEntry {
+ handle: TooltipHandle;
+ element: HTMLElement;
+ content: string;
+}
+
+/**
+ * Stack-based coordinator for tooltips in an editor. Solves two long-standing
+ * problems the per-source event-binding approach has:
+ *
+ * - **Overlap**: hover and caret sources racing to show/hide the same tooltip
+ * end up flickering as each source's Bootstrap listeners fight the other's
+ * manual `show()`/`hide()` calls.
+ * - **Unwanted teardown**: a source hiding "its" tooltip while a different
+ * source still wants it visible (mouse leaves the checkbox while the caret
+ * is still inside its item) blanks the popup unnecessarily.
+ *
+ * The manager rents one Bootstrap Tooltip per visible element and mediates
+ * every push/pop through {@link _render}, so exactly one popup is on screen at
+ * a time and switches are atomic.
+ */
+export class EditorTooltipManager {
+
+ private _stack: StackEntry[] = [];
+ private _currentElement: HTMLElement | null = null;
+ private _currentTooltip: Tooltip | null = null;
+ private readonly _baseOptions: Partial<Tooltip.Options>;
+
+ constructor(options: EditorTooltipManagerOptions = {}) {
+ this._baseOptions = options.tooltipOptions ?? {};
+ }
+
+ /**
+ * Register a tooltip on `element`. The returned handle is persistent — the
+ * caller pushes it on/off the visibility stack at will via `show()`/`hide()`.
+ * Call `dispose()` when the source is done with it (e.g. the element was
+ * removed from the DOM).
+ */
+ createHandle(element: HTMLElement, initialContent: string): TooltipHandle {
+ // Content lives in the closure so `setContent` can update it lazily —
+ // the stack entry (if any) will pick up the new value from the closure
+ // through `_render()`'s next content sync.
+ let currentContent = initialContent;
+ const currentElement = element;
+ let pendingTimer: ReturnType<typeof setTimeout> | null = null;
+ const cancelPending = () => {
+ if (pendingTimer !== null) {
+ clearTimeout(pendingTimer);
+ pendingTimer = null;
+ }
+ };
+ const self = this;
+ const handle: TooltipHandle = {
+ show(): void {
+ cancelPending();
+ if (!currentElement.isConnected) {
+ return;
+ }
+ self._pushOrMoveTop(this, currentElement, currentContent);
+ },
+ showAfter(ms: number): void {
+ cancelPending();
+ pendingTimer = setTimeout(() => {
+ pendingTimer = null;
+ if (!currentElement.isConnected) {
+ return;
+ }
+ self._pushOrMoveTop(handle, currentElement, currentContent);
+ }, ms);
+ },
+ hide(): void {
+ cancelPending();
+ self._removeEntry(this);
+ },
+ setContent(newContent: string): void {
+ currentContent = newContent;
+ const entry = self._stack.find(e => e.handle === handle);
+ if (entry) {
+ entry.content = newContent;
+ self._render();
+ }
+ },
+ dispose(): void {
+ cancelPending();
+ self._removeEntry(this);
+ }
+ };
+ return handle;
+ }
+
+ /**
+ * Dispose the manager. Any outstanding handles become inert (their
+ * `show()`/`setContent()` calls no-op because the stack is empty and won't
+ * be repopulated).
+ */
+ destroy(): void {
+ if (this._currentTooltip) {
+ this._currentTooltip.dispose();
+ }
+ this._currentTooltip = null;
+ this._currentElement = null;
+ this._stack.length = 0;
+ }
+
+ private _pushOrMoveTop(handle: TooltipHandle, element: HTMLElement, content: string): void {
+ const existingIdx = this._stack.findIndex(e => e.handle === handle);
+ if (existingIdx >= 0) {
+ const [entry] = this._stack.splice(existingIdx, 1);
+ entry.element = element;
+ entry.content = content;
+ this._stack.push(entry);
+ } else {
+ this._stack.push({ handle, element, content });
+ }
+ this._render();
+ }
+
+ private _removeEntry(handle: TooltipHandle): void {
+ const idx = this._stack.findIndex(e => e.handle === handle);
+ if (idx < 0) {
+ return;
+ }
+ this._stack.splice(idx, 1);
+ this._render();
+ }
+
+ private _render(): void {
+ // Reap dead entries anywhere in the stack — a source may have gone away
+ // between pushes, and we don't want its stale slot resurfacing on pop.
+ this._stack = this._stack.filter(e => e.element.isConnected);
+
+ const top: StackEntry | undefined = this._stack[this._stack.length - 1];
+ const targetElement = top?.element ?? null;
+
+ // Same element on top → just refresh content on the existing popup.
+ // Bootstrap's `setContent` avoids a dispose+recreate that would fade
+ // the popup out and back in for a mere content change.
+ if (this._currentElement === targetElement) {
+ if (this._currentTooltip && top) {
+ this._currentTooltip.setContent({ ".tooltip-inner": top.content });
+ }
+ return;
+ }
+
+ // Element changed (or nothing on top). Dispose the outgoing popup;
+ // create + show a fresh one for the new element.
+ if (this._currentTooltip) {
+ this._currentTooltip.dispose();
+ this._currentTooltip = null;
+ }
+ this._currentElement = targetElement;
+
+ if (top) {
+ this._currentTooltip = new Tooltip(top.element, {
+ ...this._baseOptions,
+ title: top.content,
+ html: true,
+ trigger: "manual"
+ });
+ this._currentTooltip.show();
+ }
+ }
+
+}