diff --git a/docs/content/docs/react/components/formatting-toolbar.mdx b/docs/content/docs/react/components/formatting-toolbar.mdx index 962035ba57..1ef97afac1 100644 --- a/docs/content/docs/react/components/formatting-toolbar.mdx +++ b/docs/content/docs/react/components/formatting-toolbar.mdx @@ -38,3 +38,60 @@ 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. + +The mobile Formatting Toolbar works with two page layouts. Which one you get is decided purely by your app's CSS: + +- **Scrolling document** (the default): the page scrolls as usual and BlockNote repositions the toolbar as you scroll. +- **Scroll container**: the document itself doesn't scroll; a container pinned to the visual viewport scrolls instead, and the toolbar never has to move. + +### Scrolling document + +This is what you get without any changes to your app. The toolbar follows the visible area above the keyboard as the page scrolls. Mobile browsers only report visual viewport changes after the fact, so the toolbar can lag or jitter slightly while the page is scrolling. If that matters for your app, switch to a scroll container. + +### Scroll container + +In this layout, `` and `` are locked and all page content lives inside a single scroll container that BlockNote keeps aligned with the visual viewport. Since the document never scrolls, the toolbar can stay at a truly fixed position and the lag/jitter disappears. Since the document no longer scrolls, this comes with some potential trade-offs. Browser gestures that rely on document scrolling, like pull-to-refresh, may stop working and browser UI elements like the address bar, which normally hides and reappears as you scroll, may stay fixed. Note that these trade-offs are browser-dependent - some will have neither, while others will have both. + +To set this up, add the `bn-scroll-host` class to your scroll container: + +```tsx +
{/* nav, editor, page content... */}
+``` + + + Your app should only ever have a single `bn-scroll-host` element. It's pinned + to the visual viewport with `position: fixed`, so multiple hosts would overlap + each other. Wrap all your scrollable page content in one host. + + +That's all the setup needed. BlockNote injects the following styles for you: + +```css +html:has(.bn-scroll-host), +body:has(.bn-scroll-host) { + overflow: hidden; +} +``` + +This locks scrolling on `` and `` whenever a `bn-scroll-host` element is present. It's then pinned to the visual viewport using the `--bn-vv-*` CSS variables that BlockNote publishes on ``: + +```css +.bn-scroll-host { + 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; + overscroll-behavior: contain; +} +``` + +These variables track the [visual viewport](https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport) - the part of the page actually visible above the keyboard. BlockNote keeps `--bn-vv-top`, `--bn-vv-left`, `--bn-vv-width`, and `--bn-vv-height` (plus `--bn-vv-scale`, the pinch-zoom factor) up to date as the keyboard opens and closes and as the user pans or zooms, so the scroll container always lines up with the visible area above the keyboard without any JavaScript on your end. + +Because this layout changes how the whole page scrolls, the example can't be embedded here - open the [standalone example](https://playground.blocknotejs.org/ui-components/mobile-formatting-toolbar?hideMenu=true) on a phone instead. It puts a navigation bar, some static text, and the editor inside a container with the `bn-scroll-host` class, and the switch in the navigation bar toggles the pinned scroll container layout on and off so you can compare it with the default scrolling document. Select some text and scroll in each layout to see the difference. diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/README.md b/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/README.md deleted file mode 100644 index 02eaf7673f..0000000000 --- a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Experimental Mobile Formatting Toolbar - -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. - -Controller is currently marked **experimental** due to the flickering issue with positioning (caused by delays of the Visual Viewport API) - -**Relevant Docs:** - -- [Changing the Formatting Toolbar](/docs/react/components/formatting-toolbar) -- [Editor Setup](/docs/getting-started/editor-setup) diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/App.tsx b/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/App.tsx deleted file mode 100644 index 47d59e453c..0000000000 --- a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/App.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import "@blocknote/core/fonts/inter.css"; -import { - ExperimentalMobileFormattingToolbarController, - useCreateBlockNote, -} from "@blocknote/react"; -import { BlockNoteView } from "@blocknote/mantine"; -import "@blocknote/mantine/style.css"; - -import "./style.css"; - -export default function App() { - // Creates a new editor instance. - const editor = useCreateBlockNote({ - initialContent: [ - { - type: "paragraph", - content: "Welcome to this demo!", - }, - { - type: "paragraph", - content: - "Check out the experimental mobile formatting toolbar by selecting some text (best experienced on a mobile device).", - }, - ], - }); - - // Renders the editor instance using a React component. - return ( - // Disables the default formatting toolbar and re-adds it without the - // `FormattingToolbarController` component. You may have seen - // `FormattingToolbarController` used in other examples, but we omit it here - // as we want to control the position and visibility ourselves. BlockNote - // also uses the `FormattingToolbarController` when displaying the - // Formatting Toolbar by default. - - - - ); -} diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/style.css b/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/style.css deleted file mode 100644 index 98e93611cd..0000000000 --- a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/style.css +++ /dev/null @@ -1,9 +0,0 @@ -.bn-container { - display: flex; - flex-direction: column-reverse; - gap: 8px; -} - -.bn-formatting-toolbar { - margin-inline: auto; -} diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/.bnexample.json b/examples/03-ui-components/14-mobile-formatting-toolbar/.bnexample.json similarity index 90% rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/.bnexample.json rename to examples/03-ui-components/14-mobile-formatting-toolbar/.bnexample.json index 16f9aea065..2d14483537 100644 --- a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/.bnexample.json +++ b/examples/03-ui-components/14-mobile-formatting-toolbar/.bnexample.json @@ -1,6 +1,6 @@ { "playground": true, - "docs": true, + "docs": false, "author": "areknawo", "tags": [ "Intermediate", diff --git a/examples/03-ui-components/14-mobile-formatting-toolbar/README.md b/examples/03-ui-components/14-mobile-formatting-toolbar/README.md new file mode 100644 index 0000000000..5b5ef133d7 --- /dev/null +++ b/examples/03-ui-components/14-mobile-formatting-toolbar/README.md @@ -0,0 +1,8 @@ +# Mobile Formatting Toolbar + +This example demos the opt-in **scroll container** layout: adding the `bn-scroll-host` class to your scroll container locks `html`/`body` scrolling and pins the container to the visual viewport (BlockNote injects the styles), so the toolbar stays perfectly in place while scrolling and zooming. Use the switch in the nav bar to toggle it off and compare it with the default scrolling document layout. + +**Relevant Docs:** + +- [Mobile Formatting Toolbar](/docs/react/components/formatting-toolbar#mobile-formatting-toolbar) +- [Editor Setup](/docs/getting-started/editor-setup) diff --git a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/index.html b/examples/03-ui-components/14-mobile-formatting-toolbar/index.html similarity index 85% rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/index.html rename to examples/03-ui-components/14-mobile-formatting-toolbar/index.html index 69b3583594..edd82eaea0 100644 --- a/examples/03-ui-components/14-experimental-mobile-formatting-toolbar/index.html +++ b/examples/03-ui-components/14-mobile-formatting-toolbar/index.html @@ -2,7 +2,7 @@ - Experimental Mobile Formatting Toolbar + Mobile Formatting Toolbar 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..88afbfdb7d --- /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-host styles are injected only once and each + // editor tracks the shared visual viewport independently. + const secondEditor = useCreateBlockNote({ initialContent }); + + // Which element scrolls the page. The "pinned scroll container" layout is + // opt-in via a single class: adding `bn-scroll-host` to the scroll container + // makes BlockNote's injected styles lock document scroll and pin the container + // to the visual viewport. Switching layouts 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. */} + + + + +
+
+ ); +} diff --git a/examples/03-ui-components/14-mobile-formatting-toolbar/src/DummyUI.tsx b/examples/03-ui-components/14-mobile-formatting-toolbar/src/DummyUI.tsx new file mode 100644 index 0000000000..b553b7f1bb --- /dev/null +++ b/examples/03-ui-components/14-mobile-formatting-toolbar/src/DummyUI.tsx @@ -0,0 +1,100 @@ +import { useState } from "react"; + +function HamburgerMenu() { + const [open, setOpen] = useState(false); + + return ( +
+ + {open && ( + + )} +
+ ); +} + +export function NavBar(props: { + scrollMode: "scrolling-document" | "scroll-container"; + onScrollModeChange: ( + scrollContainer: "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..5d8a2e4110 --- /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-host`, 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-experimental-mobile-formatting-toolbar/src/vite-env.d.ts b/examples/03-ui-components/14-mobile-formatting-toolbar/vite-env.d.ts similarity index 100% rename from examples/03-ui-components/14-experimental-mobile-formatting-toolbar/src/vite-env.d.ts rename to examples/03-ui-components/14-mobile-formatting-toolbar/vite-env.d.ts 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/packages/ariakit/src/menu/Menu.tsx b/packages/ariakit/src/menu/Menu.tsx index c2a401204a..177dc37f73 100644 --- a/packages/ariakit/src/menu/Menu.tsx +++ b/packages/ariakit/src/menu/Menu.tsx @@ -11,13 +11,20 @@ import { import { assertEmpty, mergeCSSClasses } from "@blocknote/core"; import { ComponentProps } from "@blocknote/react"; -import { forwardRef } from "react"; +import { createContext, forwardRef, useContext } from "react"; + +// Threads the `portalRoot` override from `Menu` (the provider) down to +// `MenuDropdown`, where ariakit's `portalElement` prop actually lives. +const PortalRootContext = createContext( + undefined, +); export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => { const { children, onOpenChange, position, + portalRoot, sub: _sub, // unused ...rest } = props; @@ -30,7 +37,9 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => { setOpen={onOpenChange} virtualFocus={true} > - {children} + + {children} + ); }; @@ -48,10 +57,13 @@ export const MenuDropdown = forwardRef< assertEmpty(rest); + const portalRoot = useContext(PortalRootContext); + return ( {children} diff --git a/packages/ariakit/src/popover/Popover.tsx b/packages/ariakit/src/popover/Popover.tsx index df8e01128b..29e662e5a6 100644 --- a/packages/ariakit/src/popover/Popover.tsx +++ b/packages/ariakit/src/popover/Popover.tsx @@ -8,6 +8,8 @@ import { assertEmpty, mergeCSSClasses } from "@blocknote/core"; import { ComponentProps } from "@blocknote/react"; import { createContext, forwardRef, useContext } from "react"; +// Threads the `portalRoot` override from `Popover` (the provider) down to +// `PopoverContent`, where ariakit's `portalElement` prop actually lives. const PortalRootContext = createContext( undefined, ); diff --git a/packages/ariakit/src/toolbar/ToolbarSelect.tsx b/packages/ariakit/src/toolbar/ToolbarSelect.tsx index f596cbbae6..26d817976e 100644 --- a/packages/ariakit/src/toolbar/ToolbarSelect.tsx +++ b/packages/ariakit/src/toolbar/ToolbarSelect.tsx @@ -16,7 +16,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); @@ -40,6 +40,7 @@ export const ToolbarSelect = forwardRef< className={mergeCSSClasses("bn-ak-popover", className || "")} ref={ref} gutter={4} + portalElement={portalRoot ?? undefined} > {items.map((option) => ( { const styles: Styles = {}; - const marks = tr.selection.$to.marks(); + const marks = + (tr.selection.empty && tr.storedMarks) || tr.selection.$to.marks(); for (const mark of marks) { const config = this.editor.schema.styleSchema[mark.type.name]; diff --git a/packages/core/src/util/browser.ts b/packages/core/src/util/browser.ts index 118c138a48..d070115c2a 100644 --- a/packages/core/src/util/browser.ts +++ b/packages/core/src/util/browser.ts @@ -28,3 +28,24 @@ export function mergeCSSClasses(...classes: (string | false | undefined)[]) { export const isSafari = () => /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + +// Cached lazily on first call in a browser environment. Touch capability +// doesn't change during a session, so there's no need to re-run `matchMedia` on +// every call. We only cache once `navigator`/`window` are available, so a +// `false` computed during SSR isn't frozen and carried onto the client. +let isTouchDeviceCache: boolean | undefined; + +export const isTouchDevice = () => { + if (typeof navigator === "undefined" || typeof window === "undefined") { + return false; + } + + if (isTouchDeviceCache === undefined) { + isTouchDeviceCache = + navigator.maxTouchPoints > 0 && + typeof window.matchMedia === "function" && + window.matchMedia("(pointer: coarse)").matches; + } + + return isTouchDeviceCache; +}; diff --git a/packages/mantine/src/blocknoteStyles.css b/packages/mantine/src/blocknoteStyles.css index accb33f62a..70c179e26a 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,7 @@ padding: 2px; width: fit-content; overflow-x: auto; - max-width: 100vw; + max-width: var(--bn-vv-width, 100vw); } .bn-mantine .bn-toolbar:empty { @@ -183,13 +179,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 +207,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..14e08bbdd1 100644 --- a/packages/mantine/src/menu/Menu.tsx +++ b/packages/mantine/src/menu/Menu.tsx @@ -16,16 +16,20 @@ 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); + // When explicitly positioned to a `top` placement (e.g. the mobile toolbar's + // color menu, opening above the keyboard) don't let `flip` send it back down. + const flip = !position?.startsWith("top"); + if (sub) { return ( @@ -36,11 +40,14 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => { return ( {children} diff --git a/packages/mantine/src/popover/Popover.tsx b/packages/mantine/src/popover/Popover.tsx index a96c1f284f..e965800251 100644 --- a/packages/mantine/src/popover/Popover.tsx +++ b/packages/mantine/src/popover/Popover.tsx @@ -20,6 +20,9 @@ export const Popover = ( middlewares={{ size: { padding: 20 } }} withinPortal={!!portalRoot} portalProps={portalRoot ? { target: portalRoot } : undefined} + // Do not move focus to dropdown when portaled (mobile), as it blurs the + // editor's contentEditable and dismisses the on-screen keyboard. + trapFocus={portalRoot ? false : undefined} opened={open} onChange={onOpenChange} position={position} diff --git a/packages/mantine/src/toolbar/ToolbarButton.tsx b/packages/mantine/src/toolbar/ToolbarButton.tsx index 179b08b03c..678d025c96 100644 --- a/packages/mantine/src/toolbar/ToolbarButton.tsx +++ b/packages/mantine/src/toolbar/ToolbarButton.tsx @@ -6,7 +6,7 @@ import { Tooltip as MantineTooltip, } from "@mantine/core"; -import { assertEmpty, isSafari } from "@blocknote/core"; +import { assertEmpty, isSafari, isTouchDevice } from "@blocknote/core"; import { ComponentProps } from "@blocknote/react"; import { forwardRef, useState } from "react"; @@ -57,11 +57,17 @@ export const ToolbarButton = forwardRef( { + onPointerDown={(event) => { + // Prevents focus shift on mobile. + 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 +96,17 @@ export const ToolbarButton = forwardRef( { + onPointerDown={(event) => { + // Prevents focus shift on mobile. + 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..5c627ef928 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,33 @@ export const ToolbarSelect = forwardRef< return ( { + onPointerDown={(e) => { + // Prevents focus shift on mo + 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/Comments/EmojiPicker.tsx b/packages/react/src/components/Comments/EmojiPicker.tsx index db078703f2..f029146942 100644 --- a/packages/react/src/components/Comments/EmojiPicker.tsx +++ b/packages/react/src/components/Comments/EmojiPicker.tsx @@ -20,6 +20,8 @@ export const EmojiPicker = (props: { } return ( + // Portal into the editor's portal element (which carries the color-scheme + // class) so the picker inherits light/dark mode instead of the body's.
{ 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..a7d292df48 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 { useUIMode } from "../../../editor/UIModeContext.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 uiMode = useUIMode(); const editor = useBlockNoteEditor< BlockSchema, InlineContentSchema, @@ -136,7 +138,9 @@ export const ColorStyleButton = () => { } return ( - + { const editorDOMElement = useEditorDOMElement(); const Components = useComponentsContext()!; const dict = useDictionary(); + const uiMode = useUIMode(); 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,8 @@ export const CreateLinkButton = () => { return ( {/* TODO: hide tooltip on click */} @@ -128,7 +144,7 @@ export const CreateLinkButton = () => { dict.generic.ctrl_shortcut, )} icon={} - onClick={() => setShowPopover((open) => !open)} + onClick={() => setPopoverOpen(!showPopover)} /> { const dict = useDictionary(); const Components = useComponentsContext()!; + const uiMode = useUIMode(); const editor = useBlockNoteEditor< BlockSchema, @@ -88,6 +90,7 @@ export const FileCaptionButton = () => { { const dict = useDictionary(); const Components = useComponentsContext()!; + const uiMode = useUIMode(); const editor = useBlockNoteEditor< BlockSchema, @@ -88,6 +90,7 @@ export const FileRenameButton = () => { { const dict = useDictionary(); const Components = useComponentsContext()!; + const uiMode = useUIMode(); const editor = useBlockNoteEditor< BlockSchema, @@ -56,7 +58,9 @@ export const FileReplaceButton = () => { } return ( - + { const Components = useComponentsContext()!; + const uiMode = useUIMode(); 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..154ff8910f --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/MobileFormattingToolbarController.tsx @@ -0,0 +1,79 @@ +import { FC, useEffect, useState } from "react"; + +import { UIModeContext } from "../../editor/UIModeContext.js"; +import { useBlockNoteEditor } from "../../hooks/useBlockNoteEditor.js"; +import { FormattingToolbarProps } from "./FormattingToolbarProps.js"; +import { FormattingToolbar } from "./FormattingToolbar.js"; +import { useVirtualKeyboard } from "./useVirtualKeyboard.js"; + +/** + * 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. + * + * Works with both page layouts described in the docs. In the default + * "scrolling document" layout the toolbar follows the visual viewport as the + * page scrolls. For the smoother "scroll container" layout (the toolbar + * staying pinned during scroll with no per-frame work), the host app opts in + * via CSS: locking document scroll (`overflow: hidden` on `html`/`body`) and + * pinning its scroll container to the visual viewport via the same `--bn-vv-*` + * variables. + * + * The toolbar itself scrolls horizontally (`overflow-x: auto`), which clips any + * inline dropdown on mobile. So this publishes {@link UIModeContext} as + * `"mobile"`, which the toolbar's dropdown buttons read (via `useUIMode`) to + * pass `editor.portalElement` as the `portalRoot` of their + * menus/popovers/selects — rendering them outside the scroll container. A set + * `portalRoot` also tells the UI adapters not to move focus into the dropdown, + * which would blur the editor and dismiss the keyboard. + * + * 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 this editor holds focus, 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); + const onBlur = () => setFocused(false); + + 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; + } + + const Component = props.formattingToolbar || FormattingToolbar; + + return ( + +
+ +
+
+ ); +}; diff --git a/packages/react/src/components/FormattingToolbar/useVirtualKeyboard.ts b/packages/react/src/components/FormattingToolbar/useVirtualKeyboard.ts new file mode 100644 index 0000000000..e17dc88e0b --- /dev/null +++ b/packages/react/src/components/FormattingToolbar/useVirtualKeyboard.ts @@ -0,0 +1,103 @@ +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-host` class to its scroll container — the matching + * styles (and the document scroll lock) 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 (unless the document is locked + // via CSS) 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/UIModeContext.ts b/packages/react/src/editor/UIModeContext.ts new file mode 100644 index 0000000000..4a1a8cbbdd --- /dev/null +++ b/packages/react/src/editor/UIModeContext.ts @@ -0,0 +1,19 @@ +import { createContext, useContext } from "react"; + +/** + * Describes the kind of UI surface the editor's floating elements + * (menus, popovers, dropdowns in `ComponentsContext`) are rendered into. + * + * `"desktop"` is the default. `"mobile"` is provided by + * `MobileFormattingToolbarController` and signals that the surrounding surface + * is pinned above the on-screen keyboard, so consumers portal their dropdowns + * into `editor.portalElement` (escaping the toolbar's horizontal scroll clip) + * by passing it as the `portalRoot` prop of `ComponentsContext` dropdowns. + */ +export type UIMode = "desktop" | "mobile"; + +export const UIModeContext = createContext("desktop"); + +export function useUIMode(): UIMode { + return useContext(UIModeContext); +} diff --git a/packages/react/src/editor/styles.css b/packages/react/src/editor/styles.css index 507f2cd46f..2c4e509fb3 100644 --- a/packages/react/src/editor/styles.css +++ b/packages/react/src/editor/styles.css @@ -509,21 +509,54 @@ 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: var(--bn-vv-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; + 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; + 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`. */ +html:has(.bn-scroll-host), +body:has(.bn-scroll-host) { + overflow: hidden; +} + +.bn-scroll-host { + 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 host 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..c8689667b2 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/UIModeContext.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..2cd7bc44f0 100644 --- a/packages/shadcn/src/menu/Menu.tsx +++ b/packages/shadcn/src/menu/Menu.tsx @@ -1,16 +1,22 @@ 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"; +// Threads the `portalRoot` override from `Menu` down to `MenuDropdown`, where +// shadcn's `container` prop actually lives. +const PortalRootContext = createContext( + undefined, +); + export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => { const { children, onOpenChange, position: _position, // Unused + portalRoot, sub, ...rest } = props; @@ -24,7 +30,9 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => { - {children} + + {children} + ); } else { @@ -33,7 +41,9 @@ export const Menu = (props: ComponentProps["Generic"]["Menu"]["Root"]) => { modal={false} onOpenChange={onOpenChange} > - {children} + + {children} + ); } @@ -73,10 +83,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..65a11d6df7 100644 --- a/packages/shadcn/src/popover/popover.tsx +++ b/packages/shadcn/src/popover/popover.tsx @@ -5,6 +5,8 @@ import { createContext, forwardRef, ReactElement, useContext } from "react"; import { cn } from "../lib/utils.js"; import { useShadCNComponentsContext } from "../ShadCNComponentsContext.js"; +// Threads the `portalRoot` override from `Popover` down to `PopoverContent`, +// where shadcn's `container` prop actually lives. const PortalRootContext = createContext( undefined, ); @@ -60,11 +62,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<