diff --git a/docs/app/layout.tsx b/docs/app/layout.tsx
index 0309bc3fbd..13c1d10790 100644
--- a/docs/app/layout.tsx
+++ b/docs/app/layout.tsx
@@ -2,7 +2,7 @@ import { Footer } from "@/components/Footer";
import { Provider } from "@/components/provider";
import { getFullMetadata } from "@/lib/getFullMetadata";
import { Analytics } from "@vercel/analytics/next";
-import { Metadata } from "next";
+import { Metadata, Viewport } from "next";
import "./global.css";
import "./gradients.css";
import "./styles.css";
@@ -13,14 +13,27 @@ export const metadata: Metadata = getFullMetadata({
"A beautiful text editor that just works. Easily add an editor to your app that users will love. Customize it with your own functionality like custom blocks or AI tooling.",
});
+// Resizes the layout viewport (not just the visual viewport) when a virtual
+// keyboard opens, so `position: fixed` elements can be pinned to the top of the
+// keyboard. Must be set in the initial HTML, so it lives here rather than in an
+// example's App. Mirrors the examples' generated `index.html` viewport meta.
+export const viewport: Viewport = {
+ width: "device-width",
+ initialScale: 1,
+ interactiveWidget: "resizes-content",
+};
+
export default function Layout({ children }: LayoutProps<"/">) {
return (
diff --git a/docs/content/docs/getting-started/index.mdx b/docs/content/docs/getting-started/index.mdx
index 0ee82296f4..8030c5f89a 100644
--- a/docs/content/docs/getting-started/index.mdx
+++ b/docs/content/docs/getting-started/index.mdx
@@ -67,6 +67,19 @@ For more information about the `useCreateBlockNote` hook and the `BlockNoteView`
guide on setting up Next.js + BlockNote](/docs/getting-started/nextjs)
+## Mobile compatibility
+
+If your app is used on touch devices, it's good practice to add `interactive-widget=resizes-content` to your page's viewport meta tag:
+
+```html
+
+```
+
+This isn't specific to BlockNote - it mitigates undesired behaviour that some browsers have when the virtual keyboard is open. For more on BlockNote's mobile UX, see the [mobile Formatting Toolbar](/docs/react/components/formatting-toolbar#mobile-formatting-toolbar).
+
## Next steps
You now know how to integrate BlockNote into your React app! However, this is just scratching the surface of what you can do with BlockNote.
diff --git a/docs/content/docs/react/components/formatting-toolbar.mdx b/docs/content/docs/react/components/formatting-toolbar.mdx
index 962035ba57..569e298d6a 100644
--- a/docs/content/docs/react/components/formatting-toolbar.mdx
+++ b/docs/content/docs/react/components/formatting-toolbar.mdx
@@ -38,3 +38,25 @@ The first element in the default Formatting Toolbar is the Block Type Select, an
Here, we use the `FormattingToolbar` component but keep the default buttons (we don't pass any children). Instead, we pass our customized Block Type Select items using the `blockTypeSelectItems` prop.
+
+## Mobile Formatting Toolbar
+
+On touch devices, BlockNote's default UI replaces the floating Formatting Toolbar with a mobile Formatting Toolbar that sits just above the on-screen keyboard. It shows the same items as the regular Formatting Toolbar and is enabled by default - there's nothing to set up. Open any of the examples above on a phone to see it.
+
+### Browser limitations
+
+Mobile browsers vary in how they handle the on-screen keyboard, which can affect the toolbar. Before anything else, make sure your page has the viewport meta tag from the [mobile compatibility guide](/docs/getting-started#mobile-compatibility).
+
+Most notably, iOS doesn't support the aforementioned viewport meta tag, which can result in jitter/lag when scrolling. There is however a workaround for this, which is why you won't see any choppiness in any of the examples here.
+
+The workaround is to wrap all of your app's content in a single element with the `bn-scroll-container` class:
+
+```tsx
+
{/* nav, editor, page content... */}
+```
+
+This element must be a direct child of `` and cover its full area. BlockNote will keep its size in sync with the [visual viewport](https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport) and render the Formatting Toolbar outside of it, eliminating any jitter/lag.
+
+
+ Your app should only ever have a single `bn-scroll-container` element. It's pinned to the visual viewport with `position: fixed`, so multiple containers would overlap each other. Wrap all your scrollable page content in one.
+
diff --git a/docs/next.config.ts b/docs/next.config.ts
index fafa53592a..149bb5a0dd 100644
--- a/docs/next.config.ts
+++ b/docs/next.config.ts
@@ -8,6 +8,13 @@ const withMDX = createMDX();
const config = {
// output: "export",
reactStrictMode: true,
+ // Next.js 16 blocks cross-origin requests to dev resources (`/_next/*`, HMR)
+ // by default. When testing on a device on the local network - e.g. a phone
+ // checking the mobile toolbar - the browser's origin is the machine's LAN IP,
+ // not `localhost`, so those requests get a 403 and the page breaks. Allow the
+ // common private LAN ranges so network devices can load the dev server. This
+ // only affects `next dev`.
+ allowedDevOrigins: ["192.168.*.*", "10.*.*.*", "172.*.*.*"],
serverExternalPackages: ["typescript", "twoslash"],
reactCompiler: true,
// TypeScript 7 ships only the native `tsc` binary; it no longer exposes the
diff --git a/examples/01-basic/01-minimal/index.html b/examples/01-basic/01-minimal/index.html
index 7f8240617e..dfd0b3fd65 100644
--- a/examples/01-basic/01-minimal/index.html
+++ b/examples/01-basic/01-minimal/index.html
@@ -1,7 +1,10 @@
-
+
Basic Setup
diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/main.tsx b/examples/03-ui-components/14-mobile-formatting-toolbar/main.tsx
similarity index 100%
rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/main.tsx
rename to examples/03-ui-components/14-mobile-formatting-toolbar/main.tsx
diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/package.json b/examples/03-ui-components/14-mobile-formatting-toolbar/package.json
similarity index 89%
rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/package.json
rename to examples/03-ui-components/14-mobile-formatting-toolbar/package.json
index c0843c027a..79453826e2 100644
--- a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/package.json
+++ b/examples/03-ui-components/14-mobile-formatting-toolbar/package.json
@@ -1,5 +1,5 @@
{
- "name": "@blocknote/example-ui-components-experimental-mobile-formatting-toolbar",
+ "name": "@blocknote/example-ui-components-mobile-formatting-toolbar",
"description": "AUTO-GENERATED FILE, DO NOT EDIT DIRECTLY",
"type": "module",
"private": true,
diff --git a/examples/03-ui-components/14-mobile-formatting-toolbar/src/App.tsx b/examples/03-ui-components/14-mobile-formatting-toolbar/src/App.tsx
new file mode 100644
index 0000000000..daf3e432c7
--- /dev/null
+++ b/examples/03-ui-components/14-mobile-formatting-toolbar/src/App.tsx
@@ -0,0 +1,63 @@
+import "@blocknote/core/fonts/inter.css";
+import { useCreateBlockNote } from "@blocknote/react";
+import { BlockNoteView } from "@blocknote/mantine";
+import "@blocknote/mantine/style.css";
+import { useState } from "react";
+
+import "./style.css";
+import { StaticText, NavBar } from "./DummyUI";
+
+// Enough content that the editor actually overflows, so scrolling is testable.
+const initialContent = [
+ { type: "paragraph" as const, content: "Welcome to this demo!" },
+ {
+ type: "paragraph" as const,
+ content:
+ "Select some text to bring up the toolbar, then scroll. With the pinned " +
+ "scroll container layout on, it stays put because the document itself " +
+ "doesn't scroll. Toggle it off in the nav bar to compare.",
+ },
+ ...Array.from({ length: 20 }, (_, i) => ({
+ type: "paragraph" as const,
+ content:
+ `Filler paragraph ${i + 1}. Select some text here and bring up the ` +
+ "keyboard to see the toolbar sit above it.",
+ })),
+];
+
+export default function App() {
+ const editor = useCreateBlockNote({ initialContent });
+ // A second editor, to check the mobile toolbar still works with multiple
+ // editors on a page: the scroll container styles come from BlockNote's stylesheet
+ // and each editor tracks the shared visual viewport independently.
+ const secondEditor = useCreateBlockNote({ initialContent });
+
+ // Which element scrolls the page. The pinned scroll container is opt-in via a
+ // single class: adding `bn-scroll-container` to the element wrapping the page
+ // content makes BlockNote's stylesheet pin it to the visual viewport, so the
+ // page content scrolls inside it. Switching is therefore just adding/removing
+ // the class - a real app would apply it unconditionally, the switch is only
+ // here so you can compare both.
+ const [scrollMode, setScrollMode] = useState<
+ "scrolling-document" | "scroll-container"
+ >("scroll-container");
+
+ return (
+
+
+
+
+ {/* On mobile, the default UI automatically shows the mobile formatting
+ toolbar above the keyboard - no extra setup needed. */}
+
+
+
+
+
+
+ );
+}
+
+export function NavBar(props: {
+ scrollMode: "scrolling-document" | "scroll-container";
+ onScrollModeChange: (
+ scrollMode: "scrolling-document" | "scroll-container",
+ ) => void;
+}) {
+ return (
+
+
+ Lorem Ipsum
+ {/* Switches between the default "scrolling document" layout and the
+ "pinned scroll container" layout, to compare the toolbar in both. */}
+
+
+ );
+}
+
+/** A block of static page text, to sit around the editor. */
+export function StaticText() {
+ return (
+
+
Lorem Ipsum
+
+ Elit ipsum qui deserunt deserunt. Qui labore eu esse veniam excepteur.
+ Aute ipsum qui dolore in ipsum commodo adipisicing velit. Qui
+ consectetur et cupidatat consectetur sunt anim excepteur reprehenderit
+ sunt quis magna aliqua laborum. Lorem irure est ipsum ea nisi incididunt
+ culpa qui consequat eiusmod deserunt ipsum nostrud velit laboris.
+
+
+ Culpa quis id ipsum enim proident dolore non. Ad occaecat nostrud
+ eiusmod pariatur occaecat nisi voluptate nulla. Nisi quis ut esse ex
+ reprehenderit Lorem tempor ex tempor id sit officia. Commodo sunt sint
+ aliqua quis reprehenderit. Occaecat id ad dolor officia qui sunt dolor.
+ Consectetur magna excepteur in minim pariatur qui elit in sit consequat
+ aliquip voluptate laboris. Reprehenderit et eu dolor ex cupidatat aliqua
+ in elit anim eiusmod et adipisicing. Cupidatat fugiat fugiat amet duis.
+
+
+ Voluptate quis dolor ipsum commodo fugiat sit tempor tempor non aliqua
+ qui. Veniam consectetur mollit consequat exercitation sit ad. Lorem amet
+ deserunt qui sint et. Sint aute cillum aliqua pariatur cillum id.
+ Consectetur proident Lorem qui laborum id in sit. Aute aute irure nisi
+ est veniam Lorem. Anim labore irure ut sit mollit velit et duis veniam
+ ipsum aliquip.
+
+
+ Occaecat dolore excepteur qui proident laborum. Dolor deserunt cillum
+ veniam nulla minim eu in est aute nulla anim incididunt ea. Anim aliquip
+ aute duis aliqua eu pariatur est dolor magna Lorem dolore do sunt
+ aliquip est. Laborum pariatur fugiat do reprehenderit tempor cupidatat
+ proident ipsum ad dolor laboris.
+
+
+ );
+}
diff --git a/examples/03-ui-components/14-mobile-formatting-toolbar/src/style.css b/examples/03-ui-components/14-mobile-formatting-toolbar/src/style.css
new file mode 100644
index 0000000000..d30b1b26bc
--- /dev/null
+++ b/examples/03-ui-components/14-mobile-formatting-toolbar/src/style.css
@@ -0,0 +1,155 @@
+html,
+body {
+ margin: 0;
+}
+
+/* Fixed-height, internally scrollable editor — a nested scroll container inside
+ the page's `.bn-scroll-container`, to check nested scrolling works. */
+.bn-container {
+ height: 300px;
+ border: 1px solid #e0e0e0;
+ border-radius: 8px;
+}
+
+.bn-editor {
+ height: 100%;
+ overflow: auto;
+}
+
+/* --- Dummy app UI (see DummyUI.tsx) --- */
+
+.dummy-top-nav {
+ position: sticky;
+ top: 0;
+ z-index: 20;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ height: 48px;
+ padding: 0 12px;
+ background: #1a1a1a;
+ color: #fff;
+}
+
+.dummy-top-nav-title {
+ font: 600 15px/1 sans-serif;
+}
+
+/* Switch for the pinned scroll container layout, pushed to the right edge. */
+.dummy-layout-toggle {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ height: 44px;
+ margin-left: auto;
+ padding: 0 4px 0 10px;
+ background: none;
+ border: none;
+ color: inherit;
+ font: 13px/1 sans-serif;
+ cursor: pointer;
+}
+
+.dummy-layout-toggle-track {
+ position: relative;
+ width: 36px;
+ height: 20px;
+ border-radius: 10px;
+ background: #555;
+ transition: background 0.15s;
+}
+
+.dummy-layout-toggle[aria-pressed="true"] .dummy-layout-toggle-track {
+ background: #4caf50;
+}
+
+.dummy-layout-toggle-track::after {
+ content: "";
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #fff;
+ transition: transform 0.15s;
+}
+
+.dummy-layout-toggle[aria-pressed="true"] .dummy-layout-toggle-track::after {
+ transform: translateX(16px);
+}
+
+.dummy-hamburger {
+ position: relative;
+}
+
+.dummy-hamburger-button {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ gap: 5px;
+ width: 44px;
+ height: 44px;
+ margin: -10px;
+ padding: 0;
+ background: none;
+ border: none;
+ cursor: pointer;
+}
+
+.dummy-hamburger-button span {
+ display: block;
+ width: 22px;
+ height: 2px;
+ border-radius: 1px;
+ background: #fff;
+}
+
+.dummy-hamburger-menu {
+ position: absolute;
+ top: calc(100% + 8px);
+ left: 0;
+ display: flex;
+ flex-direction: column;
+ min-width: 180px;
+ padding: 8px;
+ background: #fff;
+ color: #111;
+ border-radius: 8px;
+ box-shadow: 0 6px 20px rgb(0 0 0 / 0.15);
+}
+
+.dummy-hamburger-menu a {
+ display: flex;
+ align-items: center;
+ min-height: 44px;
+ padding: 8px 10px;
+ color: inherit;
+ text-decoration: none;
+ border-radius: 6px;
+}
+
+.dummy-hamburger-menu a:hover {
+ background: #f0f0f0;
+}
+
+.app-main {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ max-width: 720px;
+ margin: 0 auto;
+ padding: 16px;
+}
+
+.dummy-prose h2 {
+ margin: 0 0 8px;
+ font: 600 18px/1.2 sans-serif;
+}
+
+.dummy-prose p {
+ margin: 0 0 8px;
+ font: 14px/1.6 sans-serif;
+ color: #333;
+}
diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/vite-env.d.ts b/examples/03-ui-components/14-mobile-formatting-toolbar/src/vite-env.d.ts
similarity index 100%
rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/vite-env.d.ts
rename to examples/03-ui-components/14-mobile-formatting-toolbar/src/vite-env.d.ts
diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/tsconfig.json b/examples/03-ui-components/14-mobile-formatting-toolbar/tsconfig.json
similarity index 100%
rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/tsconfig.json
rename to examples/03-ui-components/14-mobile-formatting-toolbar/tsconfig.json
diff --git a/examples/03-ui-components/14-mobile-formatting-toolbar/vite-env.d.ts b/examples/03-ui-components/14-mobile-formatting-toolbar/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/examples/03-ui-components/14-mobile-formatting-toolbar/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/vite.config.ts b/examples/03-ui-components/14-mobile-formatting-toolbar/vite.config.ts
similarity index 100%
rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/vite.config.ts
rename to examples/03-ui-components/14-mobile-formatting-toolbar/vite.config.ts
diff --git a/examples/03-ui-components/15-advanced-tables/index.html b/examples/03-ui-components/15-advanced-tables/index.html
index ac1e67a652..8dcaf9b4c6 100644
--- a/examples/03-ui-components/15-advanced-tables/index.html
+++ b/examples/03-ui-components/15-advanced-tables/index.html
@@ -1,7 +1,10 @@
-
+
Advanced Tables
-
+
{project.title}
diff --git a/packages/mantine/src/blocknoteStyles.css b/packages/mantine/src/blocknoteStyles.css
index accb33f62a..beb3c8182f 100644
--- a/packages/mantine/src/blocknoteStyles.css
+++ b/packages/mantine/src/blocknoteStyles.css
@@ -155,10 +155,6 @@
overflow: auto;
}
-.bn-mantine .mantine-Button-root[aria-controls*="dropdown"] {
- min-width: fit-content;
-}
-
/* Toolbar styling */
.bn-mantine .bn-toolbar {
background-color: var(--bn-colors-menu-background);
@@ -170,7 +166,6 @@
padding: 2px;
width: fit-content;
overflow-x: auto;
- max-width: 100vw;
}
.bn-mantine .bn-toolbar:empty {
@@ -183,13 +178,18 @@
border: none;
border-radius: var(--bn-border-radius-small);
color: var(--bn-colors-menu-text);
+ flex-shrink: 0;
}
-.bn-toolbar .mantine-Button-root:hover,
-.bn-toolbar .mantine-ActionIcon-root:hover {
- background-color: var(--bn-colors-hovered-background);
- border: none;
- color: var(--bn-colors-hovered-text);
+/* Hover styles are gated behind `hover: hover` so they don't stick after a tap
+on touch devices (e.g. the mobile formatting toolbar). */
+@media (hover: hover) {
+ .bn-toolbar .mantine-Button-root:hover,
+ .bn-toolbar .mantine-ActionIcon-root:hover {
+ background-color: var(--bn-colors-hovered-background);
+ border: none;
+ color: var(--bn-colors-hovered-text);
+ }
}
.bn-toolbar .mantine-Button-root[data-selected],
@@ -206,6 +206,16 @@
color: var(--bn-colors-disabled-text);
}
+.bn-mobile-formatting-toolbar .bn-toolbar .mantine-Button-root {
+ height: 40px;
+ padding-inline: 12px;
+}
+
+.bn-mobile-formatting-toolbar .bn-toolbar .mantine-ActionIcon-root {
+ width: 40px;
+ height: 40px;
+}
+
.bn-toolbar .mantine-Menu-item {
font-size: 12px;
height: 30px;
diff --git a/packages/mantine/src/menu/Menu.tsx b/packages/mantine/src/menu/Menu.tsx
index c81ed870d7..4a04322152 100644
--- a/packages/mantine/src/menu/Menu.tsx
+++ b/packages/mantine/src/menu/Menu.tsx
@@ -16,7 +16,7 @@ const SubMenuContext = createContext<
>(undefined);
export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => {
- const { children, onOpenChange, position, sub, ...rest } = props;
+ const { children, onOpenChange, position, portalRoot, sub, ...rest } = props;
assertEmpty(rest);
@@ -36,7 +36,11 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => {
return (
(
{
+ onMouseDown={(event) => {
+ // On touch, keep focus on the editor (so the on-screen keyboard stays
+ // open) without canceling the tap's click. `mousedown` is the compat
+ // event that moves focus, so preventing it keeps focus here while the
+ // click still fires. Preventing `pointerdown` instead suppresses the
+ // synthesized click on iOS WebKit, so a button that opens a popover
+ // would never toggle it.
+ if (isTouchDevice()) {
+ event.preventDefault();
+ return;
+ }
+
+ // Needed as Safari doesn't focus button elements on mouse down
+ // unlike other browsers.
if (isSafari()) {
- (e.currentTarget as HTMLButtonElement).focus();
+ (event.currentTarget as HTMLButtonElement).focus();
}
}}
onClick={(event) => {
@@ -90,11 +101,22 @@ export const ToolbarButton = forwardRef(
{
+ onMouseDown={(event) => {
+ // On touch, keep focus on the editor (so the on-screen keyboard stays
+ // open) without canceling the tap's click. `mousedown` is the compat
+ // event that moves focus, so preventing it keeps focus here while the
+ // click still fires. Preventing `pointerdown` instead suppresses the
+ // synthesized click on iOS WebKit, so a button that opens a popover
+ // would never toggle it.
+ if (isTouchDevice()) {
+ event.preventDefault();
+ return;
+ }
+
+ // Needed as Safari doesn't focus button elements on mouse down
+ // unlike other browsers.
if (isSafari()) {
- (e.currentTarget as HTMLButtonElement).focus();
+ (event.currentTarget as HTMLButtonElement).focus();
}
}}
onClick={(event) => {
diff --git a/packages/mantine/src/toolbar/ToolbarSelect.tsx b/packages/mantine/src/toolbar/ToolbarSelect.tsx
index 21cee2a1fd..16f7023c16 100644
--- a/packages/mantine/src/toolbar/ToolbarSelect.tsx
+++ b/packages/mantine/src/toolbar/ToolbarSelect.tsx
@@ -4,7 +4,7 @@ import {
Menu as MantineMenu,
} from "@mantine/core";
-import { assertEmpty, isSafari } from "@blocknote/core";
+import { assertEmpty, isSafari, isTouchDevice } from "@blocknote/core";
import { ComponentProps } from "@blocknote/react";
import { forwardRef } from "react";
import { HiChevronDown } from "react-icons/hi";
@@ -14,7 +14,7 @@ export const ToolbarSelect = forwardRef<
HTMLDivElement,
ComponentProps["FormattingToolbar"]["Select"]
>((props, ref) => {
- const { className, items, isDisabled, ...rest } = props;
+ const { className, items, isDisabled, portalRoot, ...rest } = props;
assertEmpty(rest);
@@ -26,18 +26,37 @@ export const ToolbarSelect = forwardRef<
return (
{
+ // On touch, keep focus on the editor (so the on-screen keyboard
+ // stays open) without canceling the tap's click. `mousedown` is the
+ // compat event that moves focus, so preventing it keeps focus here
+ // while the click still fires. Preventing `pointerdown` instead
+ // suppresses the synthesized click on iOS WebKit.
+ if (isTouchDevice()) {
+ e.preventDefault();
+ return;
+ }
+
+ // Needed as Safari doesn't focus button elements on mouse down
+ // unlike other browsers.
if (isSafari()) {
(e.currentTarget as HTMLButtonElement).focus();
}
diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/AddCommentButton.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/AddCommentButton.tsx
index 470a50dcba..4d6e6e16d2 100644
--- a/packages/react/src/components/FormattingToolbar/DefaultButtons/AddCommentButton.tsx
+++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/AddCommentButton.tsx
@@ -6,6 +6,7 @@ import { RiChat3Line } from "react-icons/ri";
import { useComponentsContext } from "../../../editor/ComponentsContext.js";
import { useBlockNoteEditor } from "../../../hooks/useBlockNoteEditor.js";
+import { useEditorState } from "../../../hooks/useEditorState.js";
import { useExtension } from "../../../hooks/useExtension.js";
import { useDictionary } from "../../../i18n/dictionary.js";
@@ -13,16 +14,29 @@ export const AddCommentButtonInner = () => {
const dict = useDictionary();
const Components = useComponentsContext()!;
+ const editor = useBlockNoteEditor();
+
const comments = useExtension("comments") as unknown as ReturnType<
ReturnType
>;
const { store } = useExtension(FormattingToolbarExtension);
+ // Only shown while content is selected, as comments can't be added to an
+ // empty selection.
+ const selectionEmpty = useEditorState({
+ editor,
+ selector: ({ editor }) => editor.prosemirrorState.selection.empty,
+ });
+
const onClick = useCallback(() => {
comments.startPendingComment();
store.setState(false);
}, [comments, store]);
+ if (selectionEmpty) {
+ return null;
+ }
+
return (
{
StyleSchema
>();
+ // Only shown while content is selected, as comments can't be added to an
+ // empty selection.
+ const selectionEmpty = useEditorState({
+ editor,
+ selector: ({ editor }) => editor.prosemirrorState.selection.empty,
+ });
+
const onClick = useCallback(() => {
(editor._tiptapEditor as any).chain().focus().addPendingComment().run();
}, [editor]);
@@ -27,7 +35,9 @@ export const AddTiptapCommentButton = () => {
// We manually check if a comment extension (like liveblocks) is installed
// By adding default support for this, the user doesn't need to customize the formatting toolbar
!(editor._tiptapEditor.commands as any)["addPendingComment"] ||
- !editor.isEditable
+ !editor.isEditable ||
+ // No content is selected.
+ selectionEmpty
) {
return null;
}
diff --git a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.tsx b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.tsx
index d0e98c5c8f..25e0e429e7 100644
--- a/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.tsx
+++ b/packages/react/src/components/FormattingToolbar/DefaultButtons/ColorStyleButton.tsx
@@ -7,6 +7,7 @@ import {
import { useCallback } from "react";
import { useComponentsContext } from "../../../editor/ComponentsContext.js";
+import { useMobileToolbarPortal } from "../../../editor/MobileToolbarPortalContext.js";
import { useBlockNoteEditor } from "../../../hooks/useBlockNoteEditor.js";
import { useEditorState } from "../../../hooks/useEditorState.js";
import { useDictionary } from "../../../i18n/dictionary.js";
@@ -43,6 +44,7 @@ function checkColorInSchema(
export const ColorStyleButton = () => {
const Components = useComponentsContext()!;
const dict = useDictionary();
+ const mobileToolbarPortal = useMobileToolbarPortal();
const editor = useBlockNoteEditor<
BlockSchema,
InlineContentSchema,
@@ -136,7 +138,16 @@ export const ColorStyleButton = () => {
}
return (
-
+ {
const editorDOMElement = useEditorDOMElement();
const Components = useComponentsContext()!;
const dict = useDictionary();
+ const mobileToolbarPortal = useMobileToolbarPortal();
const formattingToolbar = useExtension(FormattingToolbarExtension);
// eslint-disable-next-line @typescript-eslint/unbound-method -- showSelection is a plain object method, not a class method
@@ -56,6 +58,17 @@ export const CreateLinkButton = () => {
return () => showSelection(false, "createLinkButton");
}, [showPopover, showSelection]);
+ // Return focus to editor on close.
+ const setPopoverOpen = useCallback(
+ (open: boolean) => {
+ if (!open) {
+ editor.focus();
+ }
+ setShowPopover(open);
+ },
+ [editor],
+ );
+
const state = useEditorState({
editor,
selector: ({ editor }) => {
@@ -63,6 +76,8 @@ export const CreateLinkButton = () => {
if (
// The editor is read-only.
!editor.isEditable ||
+ // The selection is empty, i.e. no content is selected.
+ editor.prosemirrorState.selection.empty ||
// Links are not in the schema.
!checkLinkInSchema(editor) ||
// Table cells are selected.
@@ -114,7 +129,14 @@ export const CreateLinkButton = () => {
return (
{/* TODO: hide tooltip on click */}
@@ -128,7 +150,7 @@ export const CreateLinkButton = () => {
dict.generic.ctrl_shortcut,
)}
icon={}
- onClick={() => setShowPopover((open) => !open)}
+ onClick={() => setPopoverOpen(!showPopover)}
/>
{
const dict = useDictionary();
const Components = useComponentsContext()!;
+ const mobileToolbarPortal = useMobileToolbarPortal();
const editor = useBlockNoteEditor<
BlockSchema,
@@ -53,7 +55,20 @@ export const FileCaptionButton = () => {
},
});
- const [popoverOpen, setPopoverOpen] = useState(false);
+ const [popoverOpen, setPopoverOpenState] = useState(false);
+
+ // Return focus to the editor when closing, so on mobile the on-screen
+ // keyboard and formatting toolbar stay up instead of being dismissed as
+ // focus falls back to ``.
+ const setPopoverOpen = useCallback(
+ (open: boolean) => {
+ if (!open) {
+ editor.focus();
+ }
+ setPopoverOpenState(open);
+ },
+ [editor],
+ );
const handleChange = useCallback(
(event: ChangeEvent) => {
@@ -73,12 +88,15 @@ export const FileCaptionButton = () => {
[block, editor],
);
- const handleKeyDown = useCallback((event: KeyboardEvent) => {
- if (event.key === "Enter" && !event.nativeEvent.isComposing) {
- event.preventDefault();
- setPopoverOpen(false);
- }
- }, []);
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ setPopoverOpen(false);
+ }
+ },
+ [setPopoverOpen],
+ );
if (block === undefined) {
return null;
@@ -88,6 +106,13 @@ export const FileCaptionButton = () => {
{
label={dict.formatting_toolbar.file_caption.tooltip}
mainTooltip={dict.formatting_toolbar.file_caption.tooltip}
icon={}
- onClick={() => setPopoverOpen((open) => !open)}
+ onClick={() => setPopoverOpen(!popoverOpen)}
/>
{
const dict = useDictionary();
const Components = useComponentsContext()!;
+ const mobileToolbarPortal = useMobileToolbarPortal();
const editor = useBlockNoteEditor<
BlockSchema,
@@ -53,7 +55,20 @@ export const FileRenameButton = () => {
},
});
- const [popoverOpen, setPopoverOpen] = useState(false);
+ const [popoverOpen, setPopoverOpenState] = useState(false);
+
+ // Return focus to the editor when closing, so on mobile the on-screen
+ // keyboard and formatting toolbar stay up instead of being dismissed as
+ // focus falls back to ``.
+ const setPopoverOpen = useCallback(
+ (open: boolean) => {
+ if (!open) {
+ editor.focus();
+ }
+ setPopoverOpenState(open);
+ },
+ [editor],
+ );
const handleChange = useCallback(
(event: ChangeEvent) => {
@@ -73,12 +88,15 @@ export const FileRenameButton = () => {
[block, editor],
);
- const handleKeyDown = useCallback((event: KeyboardEvent) => {
- if (event.key === "Enter" && !event.nativeEvent.isComposing) {
- event.preventDefault();
- setPopoverOpen(false);
- }
- }, []);
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ setPopoverOpen(false);
+ }
+ },
+ [setPopoverOpen],
+ );
if (block === undefined) {
return null;
@@ -88,6 +106,13 @@ export const FileRenameButton = () => {
{
dict.formatting_toolbar.file_rename.tooltip["file"]
}
icon={}
- onClick={() => setPopoverOpen((open) => !open)}
+ onClick={() => setPopoverOpen(!popoverOpen)}
/>
{
const dict = useDictionary();
const Components = useComponentsContext()!;
+ const mobileToolbarPortal = useMobileToolbarPortal();
const editor = useBlockNoteEditor<
BlockSchema,
@@ -56,7 +58,17 @@ export const FileReplaceButton = () => {
}
return (
-
+ {
+ // Return focus to the editor when closing, so on mobile the on-screen
+ // keyboard and formatting toolbar stay up instead of being dismissed as
+ // focus falls back to ``.
+ if (!open) {
+ editor.focus();
+ }
+ }}
+ portalRoot={mobileToolbarPortal ?? undefined}
+ >
{
const Components = useComponentsContext()!;
+ const mobileToolbarPortal = useMobileToolbarPortal();
const editor = useBlockNoteEditor<
BlockSchema,
@@ -212,6 +214,7 @@ export const BlockTypeSelect = (props: { items?: BlockTypeSelectItem[] }) => {
);
};
diff --git a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.tsx b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.tsx
new file mode 100644
index 0000000000..5ba258dfca
--- /dev/null
+++ b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.tsx
@@ -0,0 +1,129 @@
+import {
+ blockHasType,
+ BlockSchema,
+ defaultProps,
+ DefaultProps,
+ InlineContentSchema,
+ StyleSchema,
+} from "@blocknote/core";
+import { FormattingToolbarExtension } from "@blocknote/core/extensions";
+import { flip, offset, shift } from "@floating-ui/react";
+import { FC, useMemo } from "react";
+
+import { useBlockNoteEditor } from "../../hooks/useBlockNoteEditor.js";
+import { useEditorState } from "../../hooks/useEditorState.js";
+import { useExtension, useExtensionState } from "../../hooks/useExtension.js";
+import { FloatingUIOptions } from "../Popovers/FloatingUIOptions.js";
+import { PositionPopover } from "../Popovers/PositionPopover.js";
+import { FormattingToolbar } from "./FormattingToolbar.js";
+import { FormattingToolbarProps } from "./FormattingToolbarProps.js";
+
+const textAlignmentToPlacement = (
+ textAlignment: DefaultProps["textAlignment"],
+) => {
+ switch (textAlignment) {
+ case "left":
+ return "top-start";
+ case "center":
+ return "top";
+ case "right":
+ return "top-end";
+ default:
+ return "top-start";
+ }
+};
+
+export const DesktopFormattingToolbarController = (props: {
+ formattingToolbar?: FC;
+ floatingUIOptions?: FloatingUIOptions;
+ /**
+ * Override the DOM node this floating element portals into. Falls back to
+ * `editor.portalElement` (which by default is mounted inside `bn-container`)
+ * when omitted.
+ */
+ portalElement?: HTMLElement | null;
+}) => {
+ const editor = useBlockNoteEditor<
+ BlockSchema,
+ InlineContentSchema,
+ StyleSchema
+ >();
+ const formattingToolbar = useExtension(FormattingToolbarExtension, {
+ editor,
+ });
+ const show = useExtensionState(FormattingToolbarExtension, {
+ editor,
+ });
+
+ const position = useEditorState({
+ editor,
+ selector: ({ editor }) =>
+ formattingToolbar.store.state
+ ? {
+ from: editor.prosemirrorState.selection.from,
+ to: editor.prosemirrorState.selection.to,
+ }
+ : undefined,
+ });
+
+ const placement = useEditorState({
+ editor,
+ selector: ({ editor }) => {
+ const block = editor.getTextCursorPosition().block;
+
+ if (
+ !blockHasType(block, editor, block.type, {
+ textAlignment: defaultProps.textAlignment,
+ })
+ ) {
+ return "top-start";
+ } else {
+ return textAlignmentToPlacement(block.props.textAlignment);
+ }
+ },
+ });
+
+ const floatingUIOptions = useMemo(
+ () => ({
+ ...props.floatingUIOptions,
+ useFloatingOptions: {
+ open: show,
+ // Needed as hooks like `useDismiss` call `onOpenChange` to change the
+ // open state.
+ onOpenChange: (open, _event, reason) => {
+ formattingToolbar.store.setState(open);
+
+ if (reason === "escape-key") {
+ editor.focus();
+ }
+ },
+ placement,
+ middleware: [offset(10), shift(), flip()],
+ ...props.floatingUIOptions?.useFloatingOptions,
+ },
+ focusManagerProps: {
+ disabled: true,
+ ...props.floatingUIOptions?.focusManagerProps,
+ },
+ elementProps: {
+ style: {
+ zIndex: 40,
+ },
+ ...props.floatingUIOptions?.elementProps,
+ },
+ }),
+ [show, placement, props.floatingUIOptions, formattingToolbar.store, editor],
+ );
+
+ const Component = props.formattingToolbar || FormattingToolbar;
+
+ return (
+
+ {show && }
+
+ );
+};
diff --git a/packages/react/src/components/FormattingToolbar/ExperimentalMobileFormattingToolbarController.tsx b/packages/react/src/components/FormattingToolbar/ExperimentalMobileFormattingToolbarController.tsx
deleted file mode 100644
index a729bb4433..0000000000
--- a/packages/react/src/components/FormattingToolbar/ExperimentalMobileFormattingToolbarController.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-import { BlockSchema, InlineContentSchema, StyleSchema } from "@blocknote/core";
-import { FormattingToolbarExtension } from "@blocknote/core/extensions";
-import { FC, useRef, useEffect } from "react";
-
-import { useBlockNoteEditor } from "../../hooks/useBlockNoteEditor.js";
-import { useExtensionState } from "../../hooks/useExtension.js";
-import { FormattingToolbar } from "./FormattingToolbar.js";
-import { FormattingToolbarProps } from "./FormattingToolbarProps.js";
-
-/**
- * Flicker-free mobile formatting toolbar controller.
- *
- * Uses a CSS custom property (`--bn-mobile-keyboard-offset`) instead of React
- * state to position the toolbar above the virtual keyboard. This avoids the
- * re-render storm that caused visible flickering in the previous implementation.
- *
- * Two-tier keyboard detection:
- * 1. **VirtualKeyboard API** (Chrome / Edge 94+, Samsung Internet) — provides
- * exact keyboard geometry before the animation starts.
- * 2. **Visual Viewport API fallback** (Safari iOS 13+, Firefox Android 68+) —
- * computes keyboard height from the difference between layout and visual
- * viewport, with focus-based prediction for instant initial positioning.
- */
-export const ExperimentalMobileFormattingToolbarController = (props: {
- formattingToolbar?: FC;
-}) => {
- const divRef = useRef(null);
- const editor = useBlockNoteEditor<
- BlockSchema,
- InlineContentSchema,
- StyleSchema
- >();
-
- const show = useExtensionState(FormattingToolbarExtension, {
- editor,
- });
-
- useEffect(() => {
- const el = divRef.current;
- if (!el) {
- return;
- }
-
- const setOffset = (px: number) => {
- el.style.setProperty(
- "--bn-mobile-keyboard-offset",
- px > 0 ? `${px}px` : "0px",
- );
- };
-
- let scrollTimer: ReturnType;
-
- const scrollSelectionIntoView = () => {
- const sel = window.getSelection();
- if (!sel || sel.rangeCount === 0) {
- return;
- }
- const rect = sel.getRangeAt(0).getBoundingClientRect();
- const vp = window.visualViewport;
- if (!vp) {
- return;
- }
- const toolbarHeight = el.getBoundingClientRect().height || 44;
- const visibleBottom = vp.offsetTop + vp.height - toolbarHeight;
- if (rect.bottom > visibleBottom) {
- window.scrollBy({
- top: rect.bottom - visibleBottom + 16,
- behavior: "smooth",
- });
- } else if (rect.top < vp.offsetTop) {
- window.scrollBy({
- top: rect.top - vp.offsetTop - 16,
- behavior: "smooth",
- });
- }
- };
-
- // Tier 1: VirtualKeyboard API (Chrome/Edge 94+) — exact geometry, no delay
- const vk = (navigator as any).virtualKeyboard;
- if (vk) {
- vk.overlaysContent = true;
- const onGeometryChange = () => {
- setOffset(vk.boundingRect.height);
- clearTimeout(scrollTimer);
- scrollTimer = setTimeout(scrollSelectionIntoView, 100);
- };
- vk.addEventListener("geometrychange", onGeometryChange);
- const onSelectionChange = () => scrollSelectionIntoView();
- document.addEventListener("selectionchange", onSelectionChange);
- return () => {
- vk.removeEventListener("geometrychange", onGeometryChange);
- document.removeEventListener("selectionchange", onSelectionChange);
- clearTimeout(scrollTimer);
- };
- }
-
- // Tier 2: Visual Viewport API fallback (Safari iOS, Firefox Android)
- const vp = window.visualViewport;
- if (!vp) {
- return;
- }
-
- let lastKnownKeyboardHeight = 0;
-
- const update = () => {
- const layoutHeight = document.documentElement.clientHeight;
- const keyboardHeight = layoutHeight - vp.height - vp.offsetTop;
- if (keyboardHeight > 50) {
- lastKnownKeyboardHeight = keyboardHeight;
- }
- setOffset(keyboardHeight);
- clearTimeout(scrollTimer);
- scrollTimer = setTimeout(scrollSelectionIntoView, 100);
- };
-
- const onFocusIn = (e: FocusEvent) => {
- const target = e.target as HTMLElement;
- if (
- target.isContentEditable ||
- target.tagName === "INPUT" ||
- target.tagName === "TEXTAREA"
- ) {
- if (lastKnownKeyboardHeight > 0) {
- setOffset(lastKnownKeyboardHeight);
- }
- }
- };
-
- const onFocusOut = () => {
- setOffset(0);
- };
-
- const onSelectionChange = () => scrollSelectionIntoView();
-
- vp.addEventListener("resize", update);
- vp.addEventListener("scroll", update);
- document.addEventListener("focusin", onFocusIn);
- document.addEventListener("focusout", onFocusOut);
- document.addEventListener("selectionchange", onSelectionChange);
- return () => {
- vp.removeEventListener("resize", update);
- vp.removeEventListener("scroll", update);
- document.removeEventListener("focusin", onFocusIn);
- document.removeEventListener("focusout", onFocusOut);
- document.removeEventListener("selectionchange", onSelectionChange);
- clearTimeout(scrollTimer);
- };
- }, []);
-
- if (!show && divRef.current) {
- return (
-
- );
- }
-
- const Component = props.formattingToolbar || FormattingToolbar;
-
- return (
-
-
-
- );
-};
diff --git a/packages/react/src/components/FormattingToolbar/FormattingToolbarController.tsx b/packages/react/src/components/FormattingToolbar/FormattingToolbarController.tsx
index a10469eab1..1045043e14 100644
--- a/packages/react/src/components/FormattingToolbar/FormattingToolbarController.tsx
+++ b/packages/react/src/components/FormattingToolbar/FormattingToolbarController.tsx
@@ -1,37 +1,11 @@
-import {
- blockHasType,
- BlockSchema,
- defaultProps,
- DefaultProps,
- InlineContentSchema,
- StyleSchema,
-} from "@blocknote/core";
-import { FormattingToolbarExtension } from "@blocknote/core/extensions";
-import { flip, offset, shift } from "@floating-ui/react";
-import { FC, useMemo } from "react";
+import { isTouchDevice } from "@blocknote/core";
+import { FC } from "react";
-import { useBlockNoteEditor } from "../../hooks/useBlockNoteEditor.js";
-import { useEditorState } from "../../hooks/useEditorState.js";
-import { useExtension, useExtensionState } from "../../hooks/useExtension.js";
import { FloatingUIOptions } from "../Popovers/FloatingUIOptions.js";
-import { PositionPopover } from "../Popovers/PositionPopover.js";
-import { FormattingToolbar } from "./FormattingToolbar.js";
+import { DesktopFormattingToolbarController } from "./DesktopFormattingToolbarController.js";
import { FormattingToolbarProps } from "./FormattingToolbarProps.js";
-
-const textAlignmentToPlacement = (
- textAlignment: DefaultProps["textAlignment"],
-) => {
- switch (textAlignment) {
- case "left":
- return "top-start";
- case "center":
- return "top";
- case "right":
- return "top-end";
- default:
- return "top-start";
- }
-};
+import { MobileFormattingToolbarController } from "./MobileFormattingToolbarController.js";
+import { useVirtualKeyboard } from "./useVirtualKeyboard.js";
export const FormattingToolbarController = (props: {
formattingToolbar?: FC;
@@ -43,87 +17,17 @@ export const FormattingToolbarController = (props: {
*/
portalElement?: HTMLElement | null;
}) => {
- const editor = useBlockNoteEditor<
- BlockSchema,
- InlineContentSchema,
- StyleSchema
- >();
- const formattingToolbar = useExtension(FormattingToolbarExtension, {
- editor,
- });
- const show = useExtensionState(FormattingToolbarExtension, {
- editor,
- });
-
- const position = useEditorState({
- editor,
- selector: ({ editor }) =>
- formattingToolbar.store.state
- ? {
- from: editor.prosemirrorState.selection.from,
- to: editor.prosemirrorState.selection.to,
- }
- : undefined,
- });
-
- const placement = useEditorState({
- editor,
- selector: ({ editor }) => {
- const block = editor.getTextCursorPosition().block;
-
- if (
- !blockHasType(block, editor, block.type, {
- textAlignment: defaultProps.textAlignment,
- })
- ) {
- return "top-start";
- } else {
- return textAlignmentToPlacement(block.props.textAlignment);
- }
- },
- });
-
- const floatingUIOptions = useMemo(
- () => ({
- ...props.floatingUIOptions,
- useFloatingOptions: {
- open: show,
- // Needed as hooks like `useDismiss` call `onOpenChange` to change the
- // open state.
- onOpenChange: (open, _event, reason) => {
- formattingToolbar.store.setState(open);
-
- if (reason === "escape-key") {
- editor.focus();
- }
- },
- placement,
- middleware: [offset(10), shift(), flip()],
- ...props.floatingUIOptions?.useFloatingOptions,
- },
- focusManagerProps: {
- disabled: true,
- ...props.floatingUIOptions?.focusManagerProps,
- },
- elementProps: {
- style: {
- zIndex: 40,
- },
- ...props.floatingUIOptions?.elementProps,
- },
- }),
- [show, placement, props.floatingUIOptions, formattingToolbar.store, editor],
- );
-
- const Component = props.formattingToolbar || FormattingToolbar;
+ const keyboardOpen = useVirtualKeyboard();
+
+ // Checks both if the device is touch-capable and the virtual keyboard is open, as phones,
+ // tablets, etc. can still use external keyboards and mice.
+ if (isTouchDevice() && keyboardOpen) {
+ return (
+
+ );
+ }
- return (
-
- {show && }
-
- );
+ return ;
};
diff --git a/packages/react/src/components/FormattingToolbar/MobileFormattingToolbarController.tsx b/packages/react/src/components/FormattingToolbar/MobileFormattingToolbarController.tsx
new file mode 100644
index 0000000000..dd33ce607e
--- /dev/null
+++ b/packages/react/src/components/FormattingToolbar/MobileFormattingToolbarController.tsx
@@ -0,0 +1,150 @@
+import { FC, useCallback, useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+
+import { MobileToolbarPortalContext } from "../../editor/MobileToolbarPortalContext.js";
+import { useBlockNoteEditor } from "../../hooks/useBlockNoteEditor.js";
+import { FormattingToolbarProps } from "./FormattingToolbarProps.js";
+import { FormattingToolbar } from "./FormattingToolbar.js";
+import { useVirtualKeyboard } from "./useVirtualKeyboard.js";
+
+// Theme-carrying attributes copied from `editor.portalElement` onto the mobile
+// toolbar's body-level container: the classes (`bn-root`, the UI-library class
+// like `bn-mantine`, the color-scheme class) that existing CSS keys off, the
+// color-scheme data attributes, and any inline theme CSS variables (set for
+// custom object themes).
+const THEME_ATTRIBUTES = [
+ "class",
+ "style",
+ "data-color-scheme",
+ "data-mantine-color-scheme",
+];
+
+/**
+ * Mobile formatting toolbar controller.
+ *
+ * Pins the formatting toolbar to the bottom of the visual viewport — just above
+ * the on-screen keyboard — positioning itself purely from the `--bn-vv-*` CSS
+ * variables published by {@link useVirtualKeyboard} (see
+ * `.bn-mobile-formatting-toolbar` in the styles), so it needs no re-render to
+ * follow the viewport.
+ *
+ * The toolbar is portaled into a container mounted on `document.body` rather
+ * than rendered inline in the editor container. The editor commonly lives inside
+ * a scrolling/pinned container (e.g. the `bn-scroll-container` layout), and on
+ * iOS that container's `-webkit-overflow-scrolling` stacking context paints the
+ * `position: fixed` toolbar behind page content like footers; rendering at the
+ * body level avoids that. Its dropdown buttons portal their menus into the same
+ * container (via {@link MobileToolbarPortalContext}) so they escape the editor
+ * container's overflow instead of being clipped. A set `portalRoot` also tells
+ * the UI adapters not to move focus into the dropdown, which would blur the
+ * editor and dismiss the keyboard.
+ *
+ * Because the container lives outside the editor's themed subtree, it mirrors
+ * the theme attributes from `editor.portalElement` ({@link THEME_ATTRIBUTES}) so
+ * the toolbar and dropdowns stay styled. React context (editor, components,
+ * theme provider) still flows through the portal, so only the DOM-inherited
+ * styling needs recreating.
+ *
+ * Shown while the virtual keyboard is open and this editor holds focus. The
+ * focus check is essential when multiple editors share a page: the virtual
+ * keyboard is a single, page-wide signal, so without it every editor's
+ * controller would show its toolbar whenever any editor (or any other input)
+ * opened the keyboard. Touch toolbar buttons `preventDefault` on pointer down
+ * to keep the editor focused, so tapping them doesn't dismiss the toolbar.
+ */
+export const MobileFormattingToolbarController = (props: {
+ formattingToolbar?: FC;
+}) => {
+ const editor = useBlockNoteEditor();
+ const keyboardOpen = useVirtualKeyboard();
+
+ // Whether focus is within this editor's UI, kept in sync via its
+ // `focus`/`blur` events so the toolbar shows/hides as focus enters or leaves
+ // the editor.
+ const [focused, setFocused] = useState(() => editor.isFocused());
+ useEffect(() => {
+ // Re-sync on mount in case focus changed before the listeners attached.
+ setFocused(editor.isFocused());
+
+ const onFocus = () => setFocused(true);
+ // When the editor's content blurs, focus may still be within the editor's
+ // own floating UI — e.g. a toolbar popover's input autofocusing, which
+ // portals into `document.body`. Treating that as "focus left the editor"
+ // would unmount this toolbar (and the popover with it), so it would appear
+ // to never open. `relatedTarget` is unreliable on mobile, so we re-check
+ // `document.activeElement` on the next frame and only hide once focus has
+ // truly left the editor and its portal.
+ const onBlur = () => {
+ requestAnimationFrame(() => {
+ const active = document.activeElement;
+ setFocused(
+ editor.isFocused() || (!!active && editor.isWithinEditor(active)),
+ );
+ });
+ };
+
+ editor._tiptapEditor.on("focus", onFocus);
+ editor._tiptapEditor.on("blur", onBlur);
+
+ return () => {
+ editor._tiptapEditor.off("focus", onFocus);
+ editor._tiptapEditor.off("blur", onBlur);
+ };
+ }, [editor]);
+
+ if (!keyboardOpen || !focused) {
+ return null;
+ }
+
+ return (
+
+ );
+};
+
+/**
+ * The visible part of the mobile toolbar, split out so it can own the state for
+ * its themed body-level container. See the controller docstring.
+ */
+function MobileFormattingToolbar(props: {
+ formattingToolbar: FC;
+}) {
+ const editor = useBlockNoteEditor();
+
+ // The themed container the toolbar and its dropdowns render into. Tracked in
+ // state so it can be provided to the dropdown buttons once mounted.
+ const [container, setContainer] = useState(null);
+ const containerRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (node) {
+ // Mirror the editor portal's theme attributes so the container matches
+ // the editor's `.bn-root`/UI-library theming despite living outside its
+ // subtree. Recreating the styling in the DOM, not React context (which
+ // the portal preserves).
+ const portal = editor.portalElement;
+ for (const name of THEME_ATTRIBUTES) {
+ const value = portal.getAttribute(name);
+ if (value !== null) {
+ node.setAttribute(name, value);
+ }
+ }
+ }
+ setContainer(node);
+ },
+ [editor],
+ );
+
+ const Component = props.formattingToolbar;
+
+ return createPortal(
+
+
+
+
+
+
+ ,
+ document.body,
+ );
+}
diff --git a/packages/react/src/components/FormattingToolbar/useVirtualKeyboard.ts b/packages/react/src/components/FormattingToolbar/useVirtualKeyboard.ts
new file mode 100644
index 0000000000..b58fd323fe
--- /dev/null
+++ b/packages/react/src/components/FormattingToolbar/useVirtualKeyboard.ts
@@ -0,0 +1,102 @@
+import { useLayoutEffect, useState } from "react";
+
+// The tallest layout-equivalent viewport height seen so far — our stand-in for
+// "keyboard closed" — and the layout width it was measured at. Module scope so
+// they survive re-renders; the height only ever grows within a given width, so
+// refreshing it from a render pass is safe.
+let maxLayoutViewportHeight = 0;
+let baselineLayoutWidth = 0;
+
+/**
+ * Whether the on-screen keyboard is open, from the current visual viewport. We
+ * compare `height * scale` — the zoom-invariant layout-equivalent height, so
+ * pinch-zoom (which also shrinks `height`) doesn't count — against the tallest
+ * value seen, treating a drop of more than 150px as open: comfortably above
+ * URL-bar show/hide (~60-100px) and below any real keyboard (~250px+).
+ *
+ * The keyboard never changes the viewport width, but an orientation change
+ * does — so when the width changes we reset the baseline, otherwise a shorter
+ * landscape viewport would be mistaken for an open keyboard.
+ *
+ * We read the width from `document.documentElement.clientWidth` — the layout
+ * viewport, which pinch-zoom and the keyboard both leave untouched on iOS and
+ * Android alike. (`window.innerWidth` and `visualViewport.width * scale` both
+ * track the *visual* viewport on Android/Chrome, so they wobble by a few
+ * percent as you pinch.) And we only reset on a *large* change: an orientation
+ * flip moves the width by tens of percent, so a 20% threshold clears it while
+ * ignoring any residual sub-pixel jitter — without it, a stray wobble resets
+ * the baseline to the keyboard-open height and the toolbar vanishes until the
+ * keyboard is reopened.
+ */
+function isVirtualKeyboardOpen(): boolean {
+ if (typeof window === "undefined") {
+ return false;
+ }
+
+ const vp = window.visualViewport;
+ const scale = vp?.scale ?? 1;
+ const layoutHeight = (vp?.height ?? window.innerHeight) * scale;
+ const layoutWidth = document.documentElement.clientWidth;
+
+ if (Math.abs(layoutWidth - baselineLayoutWidth) > baselineLayoutWidth * 0.2) {
+ baselineLayoutWidth = layoutWidth;
+ maxLayoutViewportHeight = 0;
+ }
+
+ maxLayoutViewportHeight = Math.max(maxLayoutViewportHeight, layoutHeight);
+ return maxLayoutViewportHeight - layoutHeight > 150;
+}
+
+/**
+ * Tracks the visual viewport, publishing the rectangle + pinch-zoom scale as CSS
+ * custom properties on the root (`--bn-vv-top/left/width/height/scale`) so the
+ * mobile toolbar (and the app's scroll container) can position themselves off
+ * the viewport without a React re-render, and returning whether the on-screen
+ * keyboard is open.
+ *
+ * Since it only returns a boolean, the consumer re-renders when the keyboard
+ * opens/closes, not on every viewport change (zoom/pan/scroll) — those keep the
+ * CSS properties up to date without a re-render.
+ *
+ * For the smoother "pinned scroll container" layout, the host app opts in by
+ * adding the `bn-scroll-container` class to the element wrapping its page
+ * content — the matching styles live in `editor/styles.css`, keyed off that
+ * class and the `--bn-vv-*` variables this hook publishes.
+ */
+export function useVirtualKeyboard(): boolean {
+ const [open, setOpen] = useState(isVirtualKeyboardOpen);
+
+ useLayoutEffect(() => {
+ const html = document.documentElement;
+
+ const vp = window.visualViewport;
+ const update = () => {
+ setOpen(isVirtualKeyboardOpen());
+ html.style.setProperty("--bn-vv-top", `${vp?.offsetTop ?? 0}px`);
+ html.style.setProperty("--bn-vv-left", `${vp?.offsetLeft ?? 0}px`);
+ html.style.setProperty(
+ "--bn-vv-width",
+ `${vp?.width ?? window.innerWidth}px`,
+ );
+ html.style.setProperty(
+ "--bn-vv-height",
+ `${vp?.height ?? window.innerHeight}px`,
+ );
+ html.style.setProperty("--bn-vv-scale", `${vp?.scale ?? 1}`);
+ };
+ update();
+
+ // Fire on keyboard open/close, zoom/pan, and content scroll.
+ vp?.addEventListener("resize", update);
+ vp?.addEventListener("scroll", update);
+ window.addEventListener("resize", update);
+
+ return () => {
+ vp?.removeEventListener("resize", update);
+ vp?.removeEventListener("scroll", update);
+ window.removeEventListener("resize", update);
+ };
+ }, []);
+
+ return open;
+}
diff --git a/packages/react/src/components/Popovers/GenericPopover.tsx b/packages/react/src/components/Popovers/GenericPopover.tsx
index 0056085297..e185e36618 100644
--- a/packages/react/src/components/Popovers/GenericPopover.tsx
+++ b/packages/react/src/components/Popovers/GenericPopover.tsx
@@ -2,6 +2,7 @@ import {
autoUpdate,
FloatingFocusManager,
FloatingPortal,
+ hide,
useDismiss,
useFloating,
UseFloatingOptions,
@@ -134,16 +135,19 @@ export const GenericPopover = (
}
const {
whileElementsMounted: _whileElementsMounted,
+ middleware,
...restFloatingOptions
} = props.useFloatingOptions ?? {};
- const { refs, floatingStyles, context } = useFloating({
- whileElementsMounted: mergeWhileElementsMounted(
- autoUpdate,
- props.useFloatingOptions?.whileElementsMounted,
- ),
- ...restFloatingOptions,
- });
+ const { refs, floatingStyles, context, middlewareData } =
+ useFloating({
+ whileElementsMounted: mergeWhileElementsMounted(
+ autoUpdate,
+ props.useFloatingOptions?.whileElementsMounted,
+ ),
+ middleware: [...(middleware ?? []), hide()],
+ ...restFloatingOptions,
+ });
const { isMounted, styles } = useTransitionStyles(
context,
@@ -231,6 +235,9 @@ export const GenericPopover = (
zIndex: `calc(var(--bn-ui-base-z-index, 0) + ${props.elementProps?.style?.zIndex || 0})`,
...floatingStyles,
...styles,
+ ...(middlewareData.hide?.referenceHidden
+ ? { visibility: "hidden" as const }
+ : {}),
},
...getFloatingProps(),
};
diff --git a/packages/react/src/editor/ComponentsContext.tsx b/packages/react/src/editor/ComponentsContext.tsx
index 35d8a1ee3c..5d71bc58dc 100644
--- a/packages/react/src/editor/ComponentsContext.tsx
+++ b/packages/react/src/editor/ComponentsContext.tsx
@@ -47,6 +47,7 @@ type ToolbarSelectType = {
isDisabled?: boolean;
}[];
isDisabled?: boolean;
+ portalRoot?: HTMLElement | null;
};
type MenuButtonType = {
@@ -333,6 +334,7 @@ export type ComponentProps = {
| "bottom"
| "left"
| `${"top" | "right" | "bottom" | "left"}-${"start" | "end"}`;
+ portalRoot?: HTMLElement | null;
children?: ReactNode;
};
Divider: {
diff --git a/packages/react/src/editor/MobileToolbarPortalContext.ts b/packages/react/src/editor/MobileToolbarPortalContext.ts
new file mode 100644
index 0000000000..5630409344
--- /dev/null
+++ b/packages/react/src/editor/MobileToolbarPortalContext.ts
@@ -0,0 +1,26 @@
+import { createContext, useContext } from "react";
+
+/**
+ * The DOM node the mobile formatting toolbar's dropdowns should portal into, or
+ * `null` when not in the mobile toolbar (e.g. on desktop). This doubles as the
+ * "is this the mobile toolbar?" signal for toolbar buttons: it's non-null only
+ * while they're rendered inside the mobile toolbar.
+ *
+ * `MobileFormattingToolbarController` renders the toolbar into a themed
+ * container mounted on `document.body` (so it escapes the editor's scroll
+ * container, whose overflow would otherwise clip the dropdowns and whose iOS
+ * stacking context would trap the toolbar), and provides that container here.
+ * The dropdowns portal into it rather than bare `document.body` so they land
+ * inside its theme classes/variables and stay styled — Mantine and the other
+ * adapters append popovers as direct children of the portal target, so
+ * targeting `document.body` would drop them outside the theme scope. A set
+ * `portalRoot` also tells the UI adapters not to move focus into the dropdown,
+ * which would blur the editor and dismiss the on-screen keyboard.
+ */
+export const MobileToolbarPortalContext = createContext(
+ null,
+);
+
+export function useMobileToolbarPortal(): HTMLElement | null {
+ return useContext(MobileToolbarPortalContext);
+}
diff --git a/packages/react/src/editor/styles.css b/packages/react/src/editor/styles.css
index 507f2cd46f..a385ca1649 100644
--- a/packages/react/src/editor/styles.css
+++ b/packages/react/src/editor/styles.css
@@ -509,21 +509,53 @@ SideMenuController offsets its position to keep it centered on the line. */
gap: 4px;
}
-/* Mobile formatting toolbar positioning */
.bn-mobile-formatting-toolbar {
display: flex;
+ justify-content: center;
position: fixed;
- bottom: var(--bn-mobile-keyboard-offset, 0px);
+ top: 0;
left: 0;
- right: 0;
+ width: 100vw;
z-index: calc(var(--bn-ui-base-z-index) + 40);
- transition: bottom 0.15s ease-out;
- touch-action: pan-x;
- -webkit-overflow-scrolling: touch;
- overflow-x: auto;
+ /* `translate`: Move just below bottom of visual viewport. */
+ /* `translateY`: Move from below under bottom edge of visual viewport to just above it. */
+ /* `scale`: Preserve size on zoom. */
+ transform: translate(
+ var(--bn-vv-left, 0px),
+ calc(var(--bn-vv-top, 0px) + var(--bn-vv-height, 0px))
+ )
+ translateY(-100%) scale(calc(1 / var(--bn-vv-scale, 1)));
+ transform-origin: left bottom;
+ will-change: transform;
+ /* Slightly mitigates jitter. */
+ transition: transform 0.2s cubic-bezier(0.5, 1, 0.89, 1);
padding-bottom: env(safe-area-inset-bottom, 0);
}
+@media (prefers-reduced-motion: reduce) {
+ .bn-mobile-formatting-toolbar {
+ transition: none;
+ }
+}
+
+/* CSS styles for scroll container pinned to virtual viewport. Used to make the mobile formatting
+ toolbar scroll smoother. `bn-vv-*` variables track virtual viewport and are set in
+ `useVirtualKeyboard`. */
+.bn-scroll-container {
+ position: fixed;
+ top: var(--bn-vv-top, 0px);
+ left: var(--bn-vv-left, 0px);
+ width: var(--bn-vv-width, 100vw);
+ height: var(--bn-vv-height, 100dvh);
+ overflow-y: auto;
+ -webkit-overflow-scrolling: touch;
+ /* Stop overscroll at the boundary from chaining to the document. Without
+ this, dragging past the bottom on iOS rubber-bands the whole page, which
+ shifts the visual viewport (repinning the container mid-bounce → jitter)
+ and surfaces a second, document-level scrollbar. */
+ overscroll-behavior: contain;
+}
+
/* Emoji Picker styling */
.bn-root em-emoji-picker {
max-height: 100%;
diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts
index 0553f8a30d..bb1811a729 100644
--- a/packages/react/src/index.ts
+++ b/packages/react/src/index.ts
@@ -42,8 +42,11 @@ export * from "./components/FormattingToolbar/DefaultButtons/TableCellMergeButto
export * from "./components/FormattingToolbar/DefaultButtons/TextAlignButton.js";
export * from "./components/FormattingToolbar/DefaultSelects/BlockTypeSelect.js";
export * from "./components/FormattingToolbar/FormattingToolbar.js";
+export * from "./components/FormattingToolbar/DesktopFormattingToolbarController.js";
export * from "./components/FormattingToolbar/FormattingToolbarController.js";
-export * from "./components/FormattingToolbar/ExperimentalMobileFormattingToolbarController.js";
+export * from "./components/FormattingToolbar/MobileFormattingToolbarController.js";
+export * from "./editor/MobileToolbarPortalContext.js";
+export * from "./components/FormattingToolbar/useVirtualKeyboard.js";
export * from "./components/FormattingToolbar/FormattingToolbarProps.js";
export * from "./components/LinkToolbar/DefaultButtons/DeleteLinkButton.js";
diff --git a/packages/shadcn/src/menu/Menu.tsx b/packages/shadcn/src/menu/Menu.tsx
index 1e5eb6ea54..47114a79c5 100644
--- a/packages/shadcn/src/menu/Menu.tsx
+++ b/packages/shadcn/src/menu/Menu.tsx
@@ -1,16 +1,20 @@
import { assertEmpty } from "@blocknote/core";
import { ComponentProps, useBlockNoteEditor } from "@blocknote/react";
import { ChevronRight } from "lucide-react";
-import { forwardRef, ReactElement } from "react";
-
+import { createContext, forwardRef, ReactElement, useContext } from "react";
import { cn } from "../lib/utils.js";
import { useShadCNComponentsContext } from "../ShadCNComponentsContext.js";
+const PortalRootContext = createContext(
+ undefined,
+);
+
export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => {
const {
children,
onOpenChange,
position: _position, // Unused
+ portalRoot,
sub,
...rest
} = props;
@@ -24,7 +28,9 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => {
- {children}
+
+ {children}
+
);
} else {
@@ -33,7 +39,9 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => {
modal={false}
onOpenChange={onOpenChange}
>
- {children}
+
+ {children}
+
);
}
@@ -73,10 +81,11 @@ export const MenuDropdown = forwardRef<
const ShadCNComponents = useShadCNComponentsContext()!;
- // Portal into the editor's portal element (which carries the color-scheme
+ const portalRoot = useContext(PortalRootContext);
+ // Default to the editor's portal element (which carries the color-scheme
// class) so the menu inherits light/dark mode instead of the document body's.
const editor = useBlockNoteEditor();
- const container = editor.portalElement;
+ const container = portalRoot ?? editor.portalElement;
if (sub) {
return (
diff --git a/packages/shadcn/src/popover/popover.tsx b/packages/shadcn/src/popover/popover.tsx
index 76c822dba2..1ccb01243f 100644
--- a/packages/shadcn/src/popover/popover.tsx
+++ b/packages/shadcn/src/popover/popover.tsx
@@ -60,11 +60,11 @@ export const PopoverContent = forwardRef<
assertEmpty(rest);
const ShadCNComponents = useShadCNComponentsContext()!;
- const portalRoot = useContext(PortalRootContext);
+ const portalRoot = useContext(PortalRootContext);
// Default to the editor's portal element (which carries the color-scheme
// class) so popovers inherit light/dark mode instead of the document body's,
- // even when the caller doesn't pass an explicit portalRoot.
+ // and escape the mobile formatting toolbar's horizontal scroll clip.
const editor = useBlockNoteEditor();
return (
diff --git a/packages/shadcn/src/toolbar/Toolbar.tsx b/packages/shadcn/src/toolbar/Toolbar.tsx
index 6ac937ee7c..6f1f990b4e 100644
--- a/packages/shadcn/src/toolbar/Toolbar.tsx
+++ b/packages/shadcn/src/toolbar/Toolbar.tsx
@@ -126,13 +126,13 @@ export const ToolbarSelect = forwardRef<
HTMLDivElement,
ComponentProps["FormattingToolbar"]["Select"]
>((props, ref) => {
- const { className, items, isDisabled, ...rest } = props;
+ const { className, items, isDisabled, portalRoot, ...rest } = props;
assertEmpty(rest);
const ShadCNComponents = useShadCNComponentsContext()!;
- // Portal into the editor's portal element (which carries the color-scheme
+ // Default to the editor's portal element (which carries the color-scheme
// class) so the dropdown inherits light/dark mode instead of the body's.
const editor = useBlockNoteEditor();
@@ -163,7 +163,7 @@ export const ToolbarSelect = forwardRef<
-
+
BlockNote Playground
-
+
+
diff --git a/playground/src/examples.gen.tsx b/playground/src/examples.gen.tsx
index fc95039f22..4c9be7af2e 100644
--- a/playground/src/examples.gen.tsx
+++ b/playground/src/examples.gen.tsx
@@ -733,30 +733,6 @@ export const examples = {
readme:
"In this example, we implement a basic editor interface using components from Material UI. We replace the Formatting Toolbar, Slash Menu, and Block Side Menu while disabling the other default elements. Additionally, the Formatting Toolbar is made static and always visible above the editor.\n\n**Relevant Docs:**\n\n- [Formatting Toolbar](/docs/react/components/formatting-toolbar)\n- [Manipulating Inline Content](/docs/reference/editor/manipulating-content)\n- [Slash Menu](/docs/react/components/suggestion-menus)\n- [Side Menu](/docs/react/components/side-menu)\n- [Editor Setup](/docs/getting-started/editor-setup)",
},
- {
- projectSlug: "experimental-mobile-formatting-toolbar",
- fullSlug: "ui-components/experimental-mobile-formatting-toolbar",
- pathFromRoot:
- "examples/03-ui-components/14-experimental-mobile-formatting-toolbar",
- config: {
- playground: true,
- docs: true,
- author: "areknawo",
- tags: [
- "Intermediate",
- "UI Components",
- "Formatting Toolbar",
- "Appearance & Styling",
- ],
- },
- title: "Experimental Mobile Formatting Toolbar",
- group: {
- pathFromRoot: "examples/03-ui-components",
- slug: "ui-components",
- },
- readme:
- "This example shows how to use the experimental mobile formatting toolbar, which uses [Visual Viewport API](https://developer.mozilla.org/en-US/docs/Web/API/Visual_Viewport_API) to position the toolbar right above the virtual keyboard on mobile devices.\n\nController is currently marked **experimental** due to the flickering issue with positioning (caused by delays of the Visual Viewport API)\n\n**Relevant Docs:**\n\n- [Changing the Formatting Toolbar](/docs/react/components/formatting-toolbar)\n- [Editor Setup](/docs/getting-started/editor-setup)",
- },
{
projectSlug: "advanced-tables",
fullSlug: "ui-components/advanced-tables",
diff --git a/playground/src/style.css b/playground/src/style.css
index 7ce5324f7c..b81ce2738c 100644
--- a/playground/src/style.css
+++ b/playground/src/style.css
@@ -49,7 +49,7 @@ body {
.mantine-AppShell-root {
height: 100vh;
- width: 100vw;
+ width: 100%;
}
.mantine-AppShell-navbar {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6decb347ed..a4417cee1d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1987,7 +1987,7 @@ importers:
specifier: ^8.0.0
version: 8.0.8(@types/node@25.6.0)(esbuild@0.27.5)(jiti@2.6.1)(terser@5.46.2)(tsx@4.21.0)(yaml@2.9.0)
- examples/03-ui-components/14-experimental-mobile-formatting-toolbar:
+ examples/03-ui-components/14-mobile-formatting-toolbar:
dependencies:
'@blocknote/ariakit':
specifier: latest