Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 28 additions & 13 deletions packages/core/src/editor/BlockNoteEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,10 @@ export class BlockNoteEditor<
// Portal elements registered by the view layer, with reference counts so
// several UI elements can share one (e.g. multiple popovers portalling into
// the same custom element).
private _portalElements = new Map<HTMLElement, number>();
private _portalElements = new Map<
HTMLElement,
{ count: number; untrackFocus: () => void }
>();

/**
* Registers an element as a portal element for this editor's floating UI, so
Expand All @@ -838,10 +841,15 @@ export class BlockNoteEditor<
* {@link unregisterPortalElement}.
*/
public registerPortalElement = (element: HTMLElement) => {
this._portalElements.set(
element,
(this._portalElements.get(element) ?? 0) + 1,
);
const registration = this._portalElements.get(element);
if (registration) {
registration.count++;
} else {
this._portalElements.set(element, {
count: 1,
untrackFocus: this._eventManager.trackUIFocus(element),
});
}
};

/**
Expand All @@ -850,15 +858,14 @@ export class BlockNoteEditor<
* been released.
*/
public unregisterPortalElement = (element: HTMLElement) => {
const count = this._portalElements.get(element);
if (count === undefined) {
const registration = this._portalElements.get(element);
if (!registration) {
return;
}

if (count <= 1) {
if (--registration.count === 0) {
registration.untrackFocus();
this._portalElements.delete(element);
} else {
this._portalElements.set(element, count - 1);
}
};

Expand Down Expand Up @@ -898,9 +905,17 @@ export class BlockNoteEditor<
if (!options?.includeEditorUI) {
return contentFocused;
}
const active =
typeof document !== "undefined" ? document.activeElement : null;
return contentFocused || (!!active && this.isWithinEditor(active));
// UI rendered beside the content (e.g. a static toolbar) belongs to the
// editor too, just as in isWithinEditor. Check its parent, not only content.
// :focus-within also sees focused inputs inside shadow roots, where
// document.activeElement would only expose the shadow host.
return (
contentFocused ||
!!this.domElement?.parentElement?.matches(":focus-within") ||
Array.from(this._portalElements.keys()).some((element) =>
element.matches(":focus-within"),
)
);
}

public headless = true;
Expand Down
41 changes: 28 additions & 13 deletions packages/core/src/editor/managers/EventManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,31 @@ export class EventManager<
});
}

private uiFocusHandler?: (event: FocusEvent) => void;

/** Observe the boundary itself, even if it later moves into a shadow root. */
public trackUIFocus(element: HTMLElement): Unsubscribe {
// Portal registration can precede editor mount; use the current tracker.
const onFocus = (event: FocusEvent) => this.uiFocusHandler?.(event);
element.addEventListener("focusin", onFocus, true);
element.addEventListener("focusout", onFocus, true);
return () => {
element.removeEventListener("focusin", onFocus, true);
element.removeEventListener("focusout", onFocus, true);
};
}

/**
* Settled focus-within-UI tracking. Document-level listeners (attached on
* editor mount, detached on unmount — a no-op per focus event is too
* cheap to be worth gating on subscribers) cover the case tiptap events
* can't: focus moving from the editor's own UI outside the content area
* (including registered portal elements) to somewhere else entirely.
* Settled focus-within-UI tracking. Tiptap only tracks the content area, so
* boundary listeners also observe focus leaving its surrounding UI and
* registered portals, including transitions hidden inside closed shadow roots.
* Blur-side changes are re-checked after the current task because
* `document.activeElement` transiently becomes `<body>` during focus
* handoffs (and `relatedTarget` is unreliable on mobile).
*/
private attachUIFocusTracker(): Unsubscribe {
if (typeof document === "undefined") {
const element = this.editor.domElement?.parentElement;
if (!element) {
return () => {};
}
let wasLastFocused = this.editor.isFocused({ includeEditorUI: true });
Expand All @@ -139,25 +152,27 @@ export class EventManager<
};
// On focusin the new element already holds focus, so the state can be
// read immediately.
const onFocusIn = (event: FocusEvent) => settleUIFocus(event);

// On focusout it can't: `document.activeElement` is still the outgoing
// element (and passes through `<body>` mid-handoff), and some UI
// libraries restore focus asynchronously — the ariakit and shadcn link
// popovers both do. The check therefore has to wait for the current task
// to finish. A microtask is too early (verified: those popover tests go
// red), and a frame would work but doesn't run in a background tab.
const onFocusOut = (event: FocusEvent) => {
const handleUIFocus = (event: FocusEvent) => {
if (event.type === "focusin") {
settleUIFocus(event);
return;
}
clearTimeout(settleUiFocusedTimeout);
settleUiFocusedTimeout = setTimeout(() => settleUIFocus(event));
};

document.addEventListener("focusin", onFocusIn, true);
document.addEventListener("focusout", onFocusOut, true);
this.uiFocusHandler = handleUIFocus;
const untrackElement = this.trackUIFocus(element);
return () => {
clearTimeout(settleUiFocusedTimeout);
document.removeEventListener("focusin", onFocusIn, true);
document.removeEventListener("focusout", onFocusOut, true);
this.uiFocusHandler = undefined;
untrackElement();
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export const FormattingToolbarController = (props: {
/**
* Override the DOM node this floating element portals into. Falls back to
* the ambient portal element (the element wrapping the editor by default)
* when omitted.
* when omitted. On mobile, the default escapes to the editor's shadow root
* or document body instead.
*/
portalElement?: HTMLElement;
}) => {
Expand All @@ -25,6 +26,7 @@ export const FormattingToolbarController = (props: {
return (
<MobileFormattingToolbarController
formattingToolbar={props.formattingToolbar}
portalElement={props.portalElement}
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/* eslint-disable react/globals -- Test components expose the mounted editor to assertions. */
import type { BlockNoteEditor } from "@blocknote/core";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, expect, test, vi } from "vite-plus/test";

import { BlockNoteViewRaw } from "../../editor/BlockNoteView.js";
import { PortalElementAnchor } from "../../editor/PortalElementOverride.js";
import type { PortalElementsMap } from "../../editor/portalElements.js";
import { useCreateBlockNote } from "../../hooks/useCreateBlockNote.js";
import { FormattingToolbarController } from "./FormattingToolbarController.js";

// Only the device/keyboard signals are faked. Portal placement and focus use
// real DOM, including closed shadow roots; no skin or mobile harness is needed.
vi.mock("./useVirtualKeyboard.js", () => ({ useVirtualKeyboard: () => true }));
vi.mock("@blocknote/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@blocknote/core")>()),
isTouchDevice: () => true,
}));

let editor: BlockNoteEditor;
let reactRoot: Root | undefined;
const elements: HTMLElement[] = [];

function appendElement(parent: HTMLElement | ShadowRoot = document.body) {
const element = document.createElement("div");
parent.append(element);
elements.push(element);
return element;
}

function Toolbar() {
return <input data-test="toolbar-input" />;
}

function Probe(props: {
portalElements?: PortalElementsMap;
portalElement?: HTMLElement;
theme?: "light" | "dark";
}) {
editor = useCreateBlockNote();
return (
<BlockNoteViewRaw
editor={editor}
portalElements={props.portalElements}
formattingToolbar={false}
theme={props.theme ?? "dark"}
>
<PortalElementAnchor>
<FormattingToolbarController
formattingToolbar={Toolbar}
portalElement={props.portalElement}
/>
</PortalElementAnchor>
</BlockNoteViewRaw>
);
}

async function mount(
parent: HTMLElement | ShadowRoot,
props: Parameters<typeof Probe>[0] = {},
) {
reactRoot = createRoot(appendElement(parent));
reactRoot.render(<Probe {...props} />);
await vi.waitFor(() => expect(editor?.domElement).toBeDefined());
editor.focus();
}

async function toolbar(parent: HTMLElement | ShadowRoot) {
return vi.waitFor(() => {
const input = parent.querySelector<HTMLInputElement>(
'[data-test="toolbar-input"]',
);
expect(input).not.toBeNull();
return input!;
});
}

afterEach(() => {
reactRoot?.unmount();
reactRoot = undefined;
elements.splice(0).forEach((element) => element.remove());
});

test("escapes the editor container to body in light DOM", async () => {
await mount(document.body);
const input = await toolbar(document.body);
const portalRoot = input.closest(".bn-root");
expect(portalRoot?.parentNode).toBe(document.body);
expect(editor.domElement?.parentElement?.contains(input)).toBe(false);
expect(editor.isWithinEditor(input)).toBe(true);
expect(portalRoot?.classList.contains("dark")).toBe(true);

reactRoot!.unmount();
reactRoot = undefined;
expect(portalRoot?.isConnected).toBe(false);
expect(editor.isWithinEditor(input)).toBe(false);
});

test.each(["open", "closed"] as const)(
"uses the nearest %s shadow root and keeps toolbar input focus",
async (mode) => {
const outer = appendElement().attachShadow({ mode: "open" });
const shadow = appendElement(outer).attachShadow({ mode });
const outside = document.createElement("input");
const style = document.createElement("style");
style.textContent =
'[data-test="toolbar-input"] { color: rgb(12, 34, 56); }';
shadow.append(style, outside);

await mount(shadow);
const input = await toolbar(shadow);
expect(input.closest(".bn-root")?.parentNode).toBe(shadow);
expect(document.querySelector('[data-test="toolbar-input"]')).toBeNull();
expect(getComputedStyle(input).color).toBe("rgb(12, 34, 56)");

input.focus();
await vi.waitFor(() =>
expect(editor.isFocused({ includeEditorUI: true })).toBe(true),
);
expect(editor.isFocused()).toBe(false);
// A fresh turn lets deferred blur settling run. The input must survive it.
await new Promise((resolve) => setTimeout(resolve, 60));
expect(input.isConnected).toBe(true);

// Both elements share a shadow host: document receives neither event.
outside.focus();
await vi.waitFor(() => expect(input.isConnected).toBe(false));
expect(editor.isFocused({ includeEditorUI: true })).toBe(false);
},
);

test("inherits a view default through a local anchor", async () => {
const target = appendElement();
await mount(document.body, { portalElements: { default: target } });
const input = await toolbar(target);
expect(target.contains(input)).toBe(true);
expect(
input.closest(".bn-root")?.parentElement?.closest(".bn-root"),
).not.toBeNull();
});

test("a controller target beats the view default, including in shadow DOM", async () => {
const shadow = appendElement().attachShadow({ mode: "open" });
const defaultTarget = appendElement();
const target = appendElement();
await mount(shadow, {
portalElements: { default: defaultTarget },
portalElement: target,
});
const input = await toolbar(target);
expect(input.closest(".bn-root")?.parentNode).toBe(target);
expect(defaultTarget.contains(input)).toBe(false);
});

test("a nested editor resets the outer view's escape target", async () => {
const target = appendElement();
const shadow = appendElement().attachShadow({ mode: "open" });
function NestedProbe() {
const outerEditor = useCreateBlockNote();
return (
<BlockNoteViewRaw
editor={outerEditor}
portalElements={{ default: target }}
formattingToolbar={false}
>
<Probe />
</BlockNoteViewRaw>
);
}
reactRoot = createRoot(appendElement(shadow));
reactRoot.render(<NestedProbe />);
await vi.waitFor(() => expect(editor.domElement?.isConnected).toBe(true));
editor.focus();
const input = await toolbar(shadow);
expect(input.closest(".bn-root")?.parentNode).toBe(shadow);
expect(target.contains(input)).toBe(false);
});

test("replacing the target moves and cleans up the registered root", async () => {
const first = appendElement();
const second = appendElement();
await mount(document.body, { portalElement: first });
const input = await toolbar(first);
input.focus();

reactRoot!.render(<Probe portalElement={second} />);
await vi.waitFor(() => expect(first.childElementCount).toBe(0));
// Moving a DOM subtree may blur it; restore editor focus to show the toolbar.
editor.focus();
const movedInput = await toolbar(second);
expect(editor.isWithinEditor(movedInput)).toBe(true);
movedInput.focus();
expect(editor.isFocused({ includeEditorUI: true })).toBe(true);
});

test("changing theme preserves the portal and its focused input", async () => {
await mount(document.body);
const input = await toolbar(document.body);
const portalRoot = input.closest(".bn-root")!;
input.focus();
const changes: MutationRecord[] = [];
const observer = new MutationObserver((records) => changes.push(...records));
observer.observe(portalRoot.parentNode!, { childList: true });
try {
reactRoot!.render(<Probe theme="light" />);
await vi.waitFor(() =>
expect(portalRoot.classList.contains("light")).toBe(true),
);
expect(await toolbar(document.body)).toBe(input);
expect(document.activeElement).toBe(input);
expect(editor.isWithinEditor(input)).toBe(true);
expect(
changes.flatMap((change) => Array.from(change.removedNodes)),
).not.toContain(portalRoot);
} finally {
observer.disconnect();
}
});
Loading
Loading