From c01444b6dbf9cf4938474be57b9c65b146e82c8c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 21:16:34 +0000 Subject: [PATCH 1/2] fix(react): close popovers without re-parsing innerHTML The close transition replayed a stored HTML string, so inline style attributes were applied again and a strict style-src CSP rejected them. Clone the open DOM and reattach those nodes for the fade instead. Co-authored-by: Rahul Kashyap --- .../Popovers/GenericPopover.test.tsx | 215 ++++++++++++++++++ .../components/Popovers/GenericPopover.tsx | 85 ++++--- 2 files changed, 271 insertions(+), 29 deletions(-) create mode 100644 packages/react/src/components/Popovers/GenericPopover.test.tsx diff --git a/packages/react/src/components/Popovers/GenericPopover.test.tsx b/packages/react/src/components/Popovers/GenericPopover.test.tsx new file mode 100644 index 0000000000..e44e09148e --- /dev/null +++ b/packages/react/src/components/Popovers/GenericPopover.test.tsx @@ -0,0 +1,215 @@ +// Closing a popover used to re-parse a stored HTML string +// (`dangerouslySetInnerHTML`). That re-applies inline style attributes, which +// a CSP `style-src` without 'unsafe-inline' blocks. jsdom does not enforce +// CSP, but it does perform the assignment, so this test fails on that write +// and on a close transition that drops or replaces the open content. +import { + act, + type CSSProperties, + type ReactElement, + type ReactNode, +} from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; + +import { + BlockNoteContext, + type BlockNoteContextValue, +} from "../../editor/BlockNoteContext.js"; +import { GenericPopover } from "./GenericPopover.js"; + +declare global { + // eslint-disable-next-line no-var + var IS_REACT_ACT_ENVIRONMENT: boolean; +} +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +const POPOVER_CLASS = "bn-test-popover"; +const LABEL_ATTR = "data-testid"; +const LABEL_ID = "popover-label"; + +let reactHost: HTMLDivElement; +let editorDom: HTMLDivElement; +let root: Root; +let editor: NonNullable; + +function createEditor(domElement: HTMLElement) { + return { + domElement, + isWithinEditor: () => false, + _tiptapEditor: { + on() { + return; + }, + off() { + return; + }, + }, + } as unknown as NonNullable; +} + +function popover() { + return document.querySelector(`.${POPOVER_CLASS}`); +} + +function labels() { + return document.querySelectorAll( + `[${LABEL_ATTR}="${LABEL_ID}"]`, + ); +} + +function Harness(props: { + open: boolean; + marker: string; + zIndex?: number; + childrenWhileClosed?: boolean; + focusManagerDisabled?: boolean; +}) { + const labelStyle: CSSProperties & { "--bn-test": string } = { + color: "rgb(255, 0, 0)", + "--bn-test": "1", + }; + const content: ReactNode = ( + + {props.marker} + + ); + + return ( + + + {props.open || props.childrenWhileClosed ? content : null} + + + ); +} + +async function render(element: ReactElement) { + await act(async () => { + root.render(element); + }); +} + +beforeEach(() => { + reactHost = document.createElement("div"); + const portalParent = document.createElement("div"); + editorDom = document.createElement("div"); + portalParent.append(editorDom); + document.body.append(reactHost, portalParent); + root = createRoot(reactHost); + editor = createEditor(editorDom); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + reactHost.remove(); + editorDom.parentElement?.remove(); +}); + +describe("GenericPopover close transition", () => { + it("keeps the open content visible while closing without assigning innerHTML", async () => { + await render(); + + expect(popover()?.textContent).toContain("Slash menu"); + + const writes: Array<{ element: Element; value: string }> = []; + const descriptor = Object.getOwnPropertyDescriptor( + Element.prototype, + "innerHTML", + ); + if (!descriptor?.set || !descriptor.get) { + throw new Error("Expected Element.innerHTML to be configurable"); + } + Object.defineProperty(Element.prototype, "innerHTML", { + configurable: true, + enumerable: descriptor.enumerable, + get() { + return descriptor.get!.call(this); + }, + set(this: Element, value: string) { + writes.push({ element: this, value: String(value) }); + descriptor.set!.call(this, value); + }, + }); + + try { + await render(); + } finally { + Object.defineProperty(Element.prototype, "innerHTML", descriptor); + } + + const floating = popover(); + expect(floating?.textContent).toContain("Slash menu"); + expect(floating?.textContent).not.toContain("replaced while closing"); + expect(labels()).toHaveLength(1); + const label = labels()[0]; + expect(label?.style.color).toBe("rgb(255, 0, 0)"); + expect(label?.style.getPropertyValue("--bn-test")).toBe("1"); + expect(floating?.style.opacity).toBe("0"); + // Re-parsing HTML that contains `style="..."` is what CSP rejects. + expect( + writes.filter( + (write) => + (write.element === floating || floating?.contains(write.element)) && + (write.value.includes("style") || write.value.includes("Slash menu")), + ), + ).toEqual([]); + + await render( + , + ); + expect(popover()?.textContent).toContain("Slash menu"); + expect(labels()).toHaveLength(1); + }); + + it("ignores child updates during the close transition", async () => { + await render(); + await render(); + await render( + , + ); + + expect(popover()?.textContent).toContain("Slash menu"); + expect(popover()?.textContent).not.toContain("replaced while closing"); + expect(labels()).toHaveLength(1); + }); + + it("drops the frozen content when the popover opens again", async () => { + await render(); + await render(); + await render(); + + expect(popover()?.textContent).toContain("Open again"); + expect(popover()?.textContent).not.toContain("Slash menu"); + expect(labels()).toHaveLength(1); + }); + + it("keeps the close snapshot when the focus manager is enabled", async () => { + await render( + , + ); + await render( + , + ); + + expect(popover()?.textContent).toContain("Slash menu"); + expect(labels()).toHaveLength(1); + }); +}); diff --git a/packages/react/src/components/Popovers/GenericPopover.tsx b/packages/react/src/components/Popovers/GenericPopover.tsx index 8f715b4e14..518c7875e5 100644 --- a/packages/react/src/components/Popovers/GenericPopover.tsx +++ b/packages/react/src/components/Popovers/GenericPopover.tsx @@ -1,4 +1,3 @@ -/* eslint-disable react/refs -- Closing transitions render the previously captured HTML snapshot from this ref. */ import { autoUpdate, FloatingFocusManager, @@ -21,6 +20,7 @@ import { usePortalElement, } from "../../editor/PortalElementOverride.js"; import { useBlockNoteEditor } from "../../hooks/useBlockNoteEditor.js"; +import { useIsomorphicLayoutEffect } from "../../util/useIsomorphicLayoutEffect.js"; import { FloatingUIOptions } from "./FloatingUIOptions.js"; export type GenericPopoverReference = @@ -164,7 +164,15 @@ export const GenericPopover = ( // possible both are needed. const { getFloatingProps } = useInteractions([dismiss, hover]); - const innerHTML = useRef(""); + // Cloned DOM nodes from the last render while the popover was open, shown + // again for the close transition. The React children may rerender during + // that time (often to nothing), which would cancel the exit animation. + // + // Nodes, not an HTML string: re-parsing `innerHTML` reapplies the inline + // `style` attributes those children carry, and a CSP `style-src` without + // 'unsafe-inline' blocks every one of them. `cloneNode` keeps the styles + // without a parse. + const snapshot = useRef([]); const ref = useRef(null); const mergedRefs = useMergeRefs([ref, refs.setFloating]); @@ -207,27 +215,50 @@ export const GenericPopover = ( } }, [props.reference, refs, props.focusManagerProps?.disabled, editor]); - // Stores the last rendered `innerHTML` of the popover while it was open. The - // `innerHTML` is used while the popover is closing, as the React children - // may rerender during this time, causing unwanted behaviour. - useEffect( - () => { - if (status === "initial" || status === "open") { - // Only store while the children have rendered something. In the - // render where a controller flips `open` to `false`, its children are - // typically already gone while `status` is still "open", and that - // empty state must not replace the snapshot the closing popover is - // about to show. The wrapper is never truly empty though: it always - // contains the `PortalElementAnchor` holder. - if (ref.current && hasChildrenBesidesPortalElementAnchor(ref.current)) { - innerHTML.current = ref.current.innerHTML; + // Stores clones of the popover's DOM while it is open. `props.children` is + // a dependency because that DOM is the rendered children. + useEffect(() => { + if (status === "initial" || status === "open") { + // Only store while the children have rendered something. In the + // render where a controller flips `open` to `false`, its children are + // typically already gone while `status` is still "open", and that + // empty state must not replace the snapshot the closing popover is + // about to show. The wrapper is never truly empty though: it always + // contains the `PortalElementAnchor` holder. + if (ref.current && hasChildrenBesidesPortalElementAnchor(ref.current)) { + snapshot.current = Array.from(ref.current.childNodes, (node) => + node.cloneNode(true), + ); + } + } + }, [status, props.reference, props.children]); + + // While closing, the wrapper renders no React children (see below) and + // these clones are attached before paint. Cleanup runs before the next + // commit, and again when `status` leaves "close", so a popover that opens + // again during the fade doesn't keep the snapshot next to its real + // children. Re-attaching on every commit covers transition and position + // updates: those render the wrapper with no React children, and a host + // update can drop nodes React does not own. + useIsomorphicLayoutEffect(() => { + if (status !== "close" || !ref.current) { + return; + } + + const parent = ref.current; + const nodes = snapshot.current; + for (const node of nodes) { + parent.appendChild(node); + } + + return () => { + for (const node of nodes) { + if (node.parentNode === parent) { + parent.removeChild(node); } } - }, - // `props.children` is added to the deps, since it's ultimately the HTML of - // the children that we're storing. - [status, props.reference, props.children], - ); + }; + }); if (!isMounted || !portalElement) { return false; @@ -249,9 +280,9 @@ export const GenericPopover = ( }; if (status === "close") { - // While the popover is closing, shows its last rendered `innerHTML` while - // it was open, instead of the React children. This is because they may - // rerender during this time, causing unwanted behaviour. + // While the popover is closing, shows the cloned DOM from when it was + // open, instead of the React children. They may rerender during this + // time, causing unwanted behaviour. // // When we use the `GenericPopover` for BlockNote's internal UI elements // this isn't a huge deal, as we only pass child components if the popover @@ -259,11 +290,7 @@ export const GenericPopover = ( // out and will instead appear to hide instantly. return ( -
+
); } From 94001e4ca53e9a07030af99b43b4c82979e9a0f3 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Tue, 10 Nov 2026 15:47:02 +0100 Subject: [PATCH 2/2] refactor(react): simplify popover close snapshots --- .../Popovers/GenericPopover.test.tsx | 24 ++---- .../components/Popovers/GenericPopover.tsx | 75 ++++++++----------- 2 files changed, 37 insertions(+), 62 deletions(-) diff --git a/packages/react/src/components/Popovers/GenericPopover.test.tsx b/packages/react/src/components/Popovers/GenericPopover.test.tsx index e44e09148e..abb45e57bf 100644 --- a/packages/react/src/components/Popovers/GenericPopover.test.tsx +++ b/packages/react/src/components/Popovers/GenericPopover.test.tsx @@ -3,12 +3,7 @@ // a CSP `style-src` without 'unsafe-inline' blocks. jsdom does not enforce // CSP, but it does perform the assignment, so this test fails on that write // and on a close transition that drops or replaces the open content. -import { - act, - type CSSProperties, - type ReactElement, - type ReactNode, -} from "react"; +import { act, type CSSProperties, type ReactElement } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test"; @@ -25,7 +20,6 @@ declare global { globalThis.IS_REACT_ACT_ENVIRONMENT = true; const POPOVER_CLASS = "bn-test-popover"; -const LABEL_ATTR = "data-testid"; const LABEL_ID = "popover-label"; let reactHost: HTMLDivElement; @@ -53,9 +47,7 @@ function popover() { } function labels() { - return document.querySelectorAll( - `[${LABEL_ATTR}="${LABEL_ID}"]`, - ); + return document.querySelectorAll(`[data-testid="${LABEL_ID}"]`); } function Harness(props: { @@ -69,7 +61,7 @@ function Harness(props: { color: "rgb(255, 0, 0)", "--bn-test": "1", }; - const content: ReactNode = ( + const content = ( {props.marker} @@ -129,15 +121,13 @@ describe("GenericPopover close transition", () => { if (!descriptor?.set || !descriptor.get) { throw new Error("Expected Element.innerHTML to be configurable"); } + // oxlint-disable-next-line typescript/unbound-method -- Called with the target element as `this` below. + const setInnerHTML = descriptor.set; Object.defineProperty(Element.prototype, "innerHTML", { - configurable: true, - enumerable: descriptor.enumerable, - get() { - return descriptor.get!.call(this); - }, + ...descriptor, set(this: Element, value: string) { writes.push({ element: this, value: String(value) }); - descriptor.set!.call(this, value); + setInnerHTML.call(this, value); }, }); diff --git a/packages/react/src/components/Popovers/GenericPopover.tsx b/packages/react/src/components/Popovers/GenericPopover.tsx index 518c7875e5..2eb58081ca 100644 --- a/packages/react/src/components/Popovers/GenericPopover.tsx +++ b/packages/react/src/components/Popovers/GenericPopover.tsx @@ -164,15 +164,7 @@ export const GenericPopover = ( // possible both are needed. const { getFloatingProps } = useInteractions([dismiss, hover]); - // Cloned DOM nodes from the last render while the popover was open, shown - // again for the close transition. The React children may rerender during - // that time (often to nothing), which would cancel the exit animation. - // - // Nodes, not an HTML string: re-parsing `innerHTML` reapplies the inline - // `style` attributes those children carry, and a CSP `style-src` without - // 'unsafe-inline' blocks every one of them. `cloneNode` keeps the styles - // without a parse. - const snapshot = useRef([]); + const snapshot = useRef | undefined>(undefined); const ref = useRef(null); const mergedRefs = useMergeRefs([ref, refs.setFloating]); @@ -215,50 +207,43 @@ export const GenericPopover = ( } }, [props.reference, refs, props.focusManagerProps?.disabled, editor]); - // Stores clones of the popover's DOM while it is open. `props.children` is - // a dependency because that DOM is the rendered children. - useEffect(() => { - if (status === "initial" || status === "open") { - // Only store while the children have rendered something. In the - // render where a controller flips `open` to `false`, its children are - // typically already gone while `status` is still "open", and that - // empty state must not replace the snapshot the closing popover is - // about to show. The wrapper is never truly empty though: it always - // contains the `PortalElementAnchor` holder. - if (ref.current && hasChildrenBesidesPortalElementAnchor(ref.current)) { - snapshot.current = Array.from(ref.current.childNodes, (node) => - node.cloneNode(true), - ); + // Stores the last rendered DOM of the popover while it was open. The + // snapshot is used while the popover is closing, as the React children + // may rerender during this time, causing unwanted behaviour. + useEffect( + () => { + if (status === "initial" || status === "open") { + // Only store while the children have rendered something. In the + // render where a controller flips `open` to `false`, its children are + // typically already gone while `status` is still "open", and that + // empty state must not replace the snapshot the closing popover is + // about to show. The wrapper is never truly empty though: it always + // contains the `PortalElementAnchor` holder. + if (ref.current && hasChildrenBesidesPortalElementAnchor(ref.current)) { + snapshot.current = ref.current.cloneNode(true).childNodes; + } } - } - }, [status, props.reference, props.children]); + }, + // `props.children` is added to the deps, since it's ultimately the DOM of + // the children that we're storing. + [status, props.reference, props.children], + ); - // While closing, the wrapper renders no React children (see below) and - // these clones are attached before paint. Cleanup runs before the next - // commit, and again when `status` leaves "close", so a popover that opens - // again during the fade doesn't keep the snapshot next to its real - // children. Re-attaching on every commit covers transition and position - // updates: those render the wrapper with no React children, and a host - // update can drop nodes React does not own. + // Attach clones before paint, avoiding HTML parsing and its inline-style CSP checks. useIsomorphicLayoutEffect(() => { - if (status !== "close" || !ref.current) { + if (status !== "close" || !ref.current || !snapshot.current) { return; } - const parent = ref.current; - const nodes = snapshot.current; - for (const node of nodes) { - parent.appendChild(node); - } + const nodes = [...snapshot.current]; + ref.current.append(...nodes); return () => { for (const node of nodes) { - if (node.parentNode === parent) { - parent.removeChild(node); - } + node.parentNode?.removeChild(node); } }; - }); + }, [status]); if (!isMounted || !portalElement) { return false; @@ -280,9 +265,9 @@ export const GenericPopover = ( }; if (status === "close") { - // While the popover is closing, shows the cloned DOM from when it was - // open, instead of the React children. They may rerender during this - // time, causing unwanted behaviour. + // While the popover is closing, shows its last rendered DOM snapshot while + // it was open, instead of the React children. This is because they may + // rerender during this time, causing unwanted behaviour. // // When we use the `GenericPopover` for BlockNote's internal UI elements // this isn't a huge deal, as we only pass child components if the popover