diff --git a/CHANGELOG.md b/CHANGELOG.md index d357f514..e70b525f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,35 @@ since the previous tag. ## [Unreleased] +### Selection bubble P0: a plugin-free controller and a first-line anchor + +The selection bubble no longer registers a ProseMirror plugin from its lazy +chunk, and it anchors to the line it belongs to (spec +`2026-11-17-bubble-and-quick-insert-design.md` §12.1, v1 contract A18). The +editor chunk group is unchanged (393,171 B gz, −1 B against `main`), and the +bubble chunk shrinks from 12,238 B to 9,798 B gz (−2,440 B). + +#### Changed + +- **Bubble:** a `BubbleController` per editor shows, hides and positions the + bubble instead of Tiptap's `BubbleMenu`, so the bubble chunk landing no + longer rebuilds all 29 plugin views. The DOM contract is unchanged: one + `[data-smart-bubble]` root, appended to the scroll container on show and + removed on hide. +- **Bubble:** it anchors to the first selected line that shows, not to the + box between the selection's two ends: a selection that wraps onto the + next line is centred on its selected part of the first line, not the + middle of the column, and one that starts at the end of a paragraph + anchors to the next line's text, never to a whole block. Below the text, + it stays in view when the selection runs past the bottom of the window. +- **Bubble:** Esc on a bubble item plays the 90 ms exit fade before the + bubble goes; a re-shown bubble never flashes at its old position. + +#### Fixed + +- **Bubble:** select all (⌘A / Ctrl+A) shows the bubble, under the first + visible line; a whitespace-only selection shows none. + ### Desktop P2.1b: `local-session`, the batcher and `MemoryDocStore` The second half of desktop plan P2.1: the platform-neutral storage path that diff --git a/components/smart-toolbar/bubble/bubble-anchor.ts b/components/smart-toolbar/bubble/bubble-anchor.ts new file mode 100644 index 00000000..6b545418 --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-anchor.ts @@ -0,0 +1,213 @@ +import { posToDOMRect } from "@tiptap/core"; +import type { Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { TextSelection } from "@tiptap/pm/state"; +import type { EditorView } from "@tiptap/pm/view"; + +import { + type BubblePlacement, + type BubbleRect, + firstLineRect, + lastLineRect, +} from "./bubble-rules"; + +/** + * The bubble's anchor (spec §12.1, BQ3): one selected line inside the + * visible band, never the union rectangle, measured from a DOM range of at + * most `MAX_RANGE` positions. `getClientRects` over a ⌘A range would lay + * out every `content-visibility`-skipped block. + */ + +/** Most positions one anchor range spans. */ +const MAX_RANGE = 300; +const STICKY_TOOLBAR = ':scope > [data-slot="toolbar"]'; + +interface Band { + top: number; + bottom: number; +} + +/** Under the sticky row (else the scroll target's top), above its bottom. */ +function visibleBand(scrollTarget: HTMLElement): Band { + const box = scrollTarget.getBoundingClientRect(); + const toolbar = scrollTarget.querySelector(STICKY_TOOLBAR); + return { + top: toolbar ? toolbar.getBoundingClientRect().bottom : box.top, + bottom: box.bottom, + }; +} + +const clamp = (value: number, min: number, max: number) => + Math.min(max, Math.max(min, value)); + +/** + * The document position where the line `top` px down starts. Both inline + * edges are probed and the smaller position wins: in a right-to-left line + * the left edge is the line's logical end. + */ +function posAtBandEdge(view: EditorView, top: number): number | undefined { + const { left, right } = view.dom.getBoundingClientRect(); + let found: number | undefined; + for (const x of [left + 1, right - 1]) { + const pos = view.posAtCoords({ left: x, top })?.pos; + if (pos !== undefined && (found === undefined || pos < found)) found = pos; + } + return found; +} + +/** Client rects of the DOM range between two document positions. */ +function rangeRects(view: EditorView, from: number, to: number): DOMRect[] { + const start = view.domAtPos(from); + const end = view.domAtPos(to); + const range = view.dom.ownerDocument.createRange(); + range.setStart(start.node, start.offset); + range.setEnd(end.node, end.offset); + return Array.from(range.getClientRects()); +} + +/** + * `pos`, or the nearest position inside a textblock in direction `dir`, + * never past `limit`. A range that starts (or ends) on a block boundary + * holds that whole block, and `getClientRects` returns its border box: the + * "first line" of select all would be the title's whole box. + */ +export function intoTextblock( + doc: ProseMirrorNode, + pos: number, + dir: 1 | -1, + limit: number, +): number { + const $pos = doc.resolve(pos); + if ($pos.parent.inlineContent) return pos; + const found = TextSelection.findFrom($pos, dir, true)?.head; + if (found === undefined) return pos; + return dir > 0 ? Math.min(found, limit) : Math.max(found, limit); +} + +/** + * The first line that shows in the band, read forward from `start` one + * textblock at a time: each range stays inside one textblock, so it never + * holds a whole block (whose border box `getClientRects` would return). + * A position at a textblock's end, or an empty textblock, has no line: + * the scan goes on to the next. At most `MAX_RANGE` positions in all. + */ +function firstLineFrom( + view: EditorView, + band: Band, + start: number, + to: number, +) { + const { doc } = view.state; + let pos = start; + let budget = MAX_RANGE; + while (budget > 0 && pos < to) { + pos = intoTextblock(doc, pos, 1, to); + const $pos = doc.resolve(pos); + if (!$pos.parent.inlineContent) return null; + const end = Math.min($pos.end(), to, pos + budget); + if (end > pos) { + const line = firstLineRect(rangeRects(view, pos, end), band); + if (line) return line; + } + budget -= Math.max(1, end - pos); + pos = $pos.after(); + } + return null; +} + +/** Like `firstLineFrom`, backward from `end` for the last line. */ +function lastLineFrom(view: EditorView, band: Band, from: number, end: number) { + const { doc } = view.state; + let pos = end; + let budget = MAX_RANGE; + while (budget > 0 && pos > from) { + pos = intoTextblock(doc, pos, -1, from); + const $pos = doc.resolve(pos); + if (!$pos.parent.inlineContent) return null; + const start = Math.max($pos.start(), from, pos - budget); + if (pos > start) { + const line = lastLineRect(rangeRects(view, start, pos), band); + if (line) return line; + } + budget -= Math.max(1, pos - start); + pos = $pos.before(); + } + return null; +} + +/** + * First selected line in the band, from where the band starts. Positions + * are moved into a textblock before `coordsAtPos` reads them: at the + * document's edges it measures whatever the view's first or last child is. + */ +function topAnchor(view: EditorView, band: Band, from: number, to: number) { + let start = intoTextblock(view.state.doc, from, 1, to); + if (view.coordsAtPos(start).bottom < band.top) { + const hit = posAtBandEdge(view, band.top + 1); + if (hit !== undefined) start = clamp(hit, from, to); + } + return firstLineFrom(view, band, start, to); +} + +/** + * Last selected line, with `room` px free under it inside the band. When + * the selection runs past the band's bottom (select all), or its last line + * sits too close to that edge, the bubble under it would leave the view: + * it goes under the first line that shows instead. + */ +function bottomAnchor( + view: EditorView, + band: Band, + from: number, + to: number, + room: number, +) { + const end = intoTextblock(view.state.doc, to, -1, from); + if (view.coordsAtPos(end).top > band.bottom) { + return topAnchor(view, band, from, to); + } + const line = lastLineFrom(view, band, from, end); + if (line && line.bottom + room > band.bottom) { + return topAnchor(view, band, from, to); + } + return line; +} + +const toDOMRect = ({ left, top, right, bottom }: BubbleRect) => + new DOMRect(left, top, right - left, bottom - top); + +/** The selection's union rect (the plugin's anchor), or an empty rect. */ +function selectionRect(view: EditorView, from: number, to: number): DOMRect { + try { + return toDOMRect(posToDOMRect(view, from, to)); + } catch { + return new DOMRect(); + } +} + +/** + * The rect the bubble anchors to: the first selected line that shows in + * the scroll target's band for `"top"`, the last selected line for + * `"bottom"` (the first that shows when the selection runs past the band, + * or when `room`, the bubble's height plus its offset, does not fit under + * the last). Falls back to the selection's union rect when no line shows + * or measuring throws. + */ +export function bubbleReferenceRect( + view: EditorView, + scrollTarget: HTMLElement, + placement: BubblePlacement, + room = 0, +): DOMRect { + const { from, to } = view.state.selection; + try { + const band = visibleBand(scrollTarget); + const line = + placement === "top" + ? topAnchor(view, band, from, to) + : bottomAnchor(view, band, from, to, room); + if (line) return toDOMRect(line); + } catch { + // Positions the DOM no longer has (a remote step replaced the block). + } + return selectionRect(view, from, to); +} diff --git a/components/smart-toolbar/bubble/bubble-controller.ts b/components/smart-toolbar/bubble/bubble-controller.ts new file mode 100644 index 00000000..47cfd174 --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-controller.ts @@ -0,0 +1,340 @@ +import { + autoUpdate, + computePosition, + hide as hideMiddleware, + offset, + shift, + type VirtualElement, +} from "@floating-ui/dom"; +import type { Editor, EditorEvents } from "@tiptap/core"; +import type { Transaction } from "@tiptap/pm/state"; + +import { BUBBLE_OFFSET, type BubblePlacement } from "./bubble-rules"; + +/** + * Selection bubble controller (spec §12.1): shows, hides and positions one + * root element for an editor without a ProseMirror plugin, so the lazy + * bubble chunk never calls `registerPlugin` (which re-creates every plugin + * view). The behaviours copy Tiptap's `bubble-menu-plugin.ts` + * (`@tiptap/extension-bubble-menu` 3.33); line numbers below cite it. + */ + +/** Delay before a non-empty selection shows the bubble (`updateDelay`, :378). */ +export const BUBBLE_SHOW_DELAY_MS = 250; +/** Debounce for repositioning on resize and scroll (`resizeDelay`, :379). */ +export const BUBBLE_RESIZE_DELAY_MS = 60; + +/** What the controller drives: the view's root, rules and callbacks. */ +export interface BubbleHost { + /** Reused; appended to the scroll target on show, removed on hide. */ + readonly root: HTMLElement; + /** The view's `shouldShowBubble` plus its suppression. */ + shouldShow(): boolean; + /** The anchor for `placement`, in client coordinates. */ + getReferenceRect(placement: BubblePlacement): DOMRect; + onShow(): void; + onHide(): void; + /** After each applied position (or reference-hidden) result. */ + onPosition(): void; +} + +/** One editor's bubble: its visibility, position and teardown. */ +export interface BubbleController { + readonly visible: boolean; + /** Re-evaluates now, without the show delay. */ + update(): void; + updatePosition(): void; + hide(): void; + /** Stores the side; the next `updatePosition` uses it. */ + setPlacement(placement: BubblePlacement): void; + /** Removes every listener and timer and hides. Idempotent. */ + destroy(): void; +} + +type Timer = ReturnType | undefined; + +/** One controller per editor (StrictMode effects run twice). */ +const controllers = new WeakMap(); + +/** + * Whether a dispatch set the selection or changed the doc. The + * `transaction` event carries no previous state, and these flags are O(1) + * where `doc.eq` (the plugin's check, :534-535) is O(top-level blocks). + * A selection set to an equal one counts: it only restarts the delay. + */ +function changesSelectionOrDoc( + transaction: Transaction, + appended: readonly Transaction[], +): boolean { + const changes = (tr: Transaction) => tr.docChanged || tr.selectionSet; + return changes(transaction) || appended.some(changes); +} + +/** + * Creates the bubble controller for `editor`, replacing any earlier one. + * The root is appended to `scrollTarget` (`.document-editor-wrapper`) on + * show and removed synchronously on hide (v1 contract §5.2). + */ +export function createBubbleController( + editor: Editor, + scrollTarget: HTMLElement, + host: BubbleHost, +): BubbleController { + controllers.get(editor)?.destroy(); + + // Captured once: after `editor.destroy()`, `editor.view` is a proxy. + const view = editor.view; + const dom = view.dom; + const { root } = host; + + let visible = false; + let destroyed = false; + let placement: BubblePlacement = "top"; + let dragging = false; + let preventHide = false; + let showTimer: Timer; + let deferTimer: Timer; + let resizeTimer: Timer; + let stopAutoUpdate: (() => void) | undefined; + /** Bumped per position request and on hide: stale results are dropped. */ + let positionRun = 0; + + const reference: VirtualElement = { + getBoundingClientRect: () => host.getReferenceRect(placement), + contextElement: dom, + }; + + function updatePosition() { + if (!visible || destroyed) return; + const run = ++positionRun; + computePosition(reference, root, { + strategy: "absolute", + placement, + middleware: [ + offset(BUBBLE_OFFSET), + shift({ padding: 8 }), + hideMiddleware(), + ], + }).then( + ({ x, y, strategy, middlewareData }) => { + if (run !== positionRun) return; + // Scrolled out or clipped: hidden in place, not removed (:508-511). + const clipped = middlewareData.hide; + if (clipped?.referenceHidden || clipped?.escaped) { + root.style.visibility = "hidden"; + } else { + root.style.visibility = "visible"; + root.style.width = "max-content"; + root.style.position = strategy; + root.style.left = `${x}px`; + root.style.top = `${y}px`; + } + host.onPosition(); + }, + () => { + // No layout (happy-dom) or a reference that threw: keep the last + // position. + }, + ); + } + + /** + * :605-622, plus `autoUpdate` while shown. `ancestorScroll: false`: the + * root scrolls with the text; the debounced scroll listener re-runs the + * `hide` middleware. + */ + function show() { + if (visible) return; + visible = true; + scrollTarget.appendChild(root); + host.onShow(); + if (!visible) return; + try { + stopAutoUpdate = autoUpdate(reference, root, updatePosition, { + ancestorScroll: false, + elementResize: true, + }); + } catch { + updatePosition(); + } + } + + /** :624-639. Cancels a pending show; the root leaves before `onHide`. */ + function hide() { + clearTimeout(showTimer); + showTimer = undefined; + if (!visible) return; + visible = false; + positionRun += 1; + stopAutoUpdate?.(); + stopAutoUpdate = undefined; + root.remove(); + // A later show stays hidden until its first position lands. + root.style.visibility = "hidden"; + host.onHide(); + } + + /** Re-evaluates now (`updateHandler`, :579-603). Never shows mid-drag. */ + function update() { + clearTimeout(showTimer); + showTimer = undefined; + if (destroyed || editor.isDestroyed || view.composing) return; + if (editor.state.selection.empty || !host.shouldShow()) { + hide(); + return; + } + if (visible) updatePosition(); + else if (!dragging) show(); + } + + /** + * Hides at once, or (re)starts the show delay (:529-555). A drag waits + * for `pointerup`, which evaluates again. + */ + function evaluate() { + if (destroyed || editor.isDestroyed || view.composing) return; + if (editor.state.selection.empty || !host.shouldShow()) { + hide(); + return; + } + if (dragging) return; + clearTimeout(showTimer); + showTimer = setTimeout(() => { + showTimer = undefined; + update(); + }, BUBBLE_SHOW_DELAY_MS); + } + + /** Evaluates once the selection has settled (focus :459-462, IME :431-442). */ + function evaluateLater() { + clearTimeout(deferTimer); + deferTimer = setTimeout(() => { + deferTimer = undefined; + evaluate(); + }); + } + + // Every keystroke runs this: typing with no bubble exits on the first line. + const onTransaction = ({ + transaction, + appendedTransactions, + }: EditorEvents["transaction"]) => { + if (!visible && editor.state.selection.empty) return; + if (view.composing) return; + if (!changesSelectionOrDoc(transaction, appendedTransactions)) return; + evaluate(); + }; + + /** + * Focus (:459-462) re-evaluates only while hidden. While shown, focus + * coming back from an item (Esc) must not hide at once: the view's + * suppression would cut its exit fade, which the plugin's debounced + * focus handler let play. + */ + const onFocus = () => { + if (!visible) evaluateLater(); + }; + + /** :464-484, but only focus moving into the root itself keeps it. */ + const onBlur = ({ event }: EditorEvents["blur"]) => { + if (preventHide) { + preventHide = false; + return; + } + const related = event?.relatedTarget as Node | null | undefined; + if (related && (related === dom || root.contains(related))) return; + hide(); + }; + + // `setEditable` emits `update` and no transaction. + const onUpdate = () => { + if (editor.isEditable) return; + hide(); + }; + + const onRootMouseDown = () => { + preventHide = true; + }; + + // A context menu or a drag may swallow the `pointerup`: never stay stuck. + const onHideEvent = () => { + dragging = false; + hide(); + }; + + const onPointerDown = () => { + dragging = true; + }; + + // On the window: a drag-select often ends outside the editor. + const onPointerUp = () => { + if (!dragging) return; + dragging = false; + evaluate(); + }; + + /** Resize and scroll (:411-412, :449-457): reposition, debounced. */ + const onReposition = () => { + if (!visible) return; + clearTimeout(resizeTimer); + resizeTimer = setTimeout(() => { + resizeTimer = undefined; + updatePosition(); + }, BUBBLE_RESIZE_DELAY_MS); + }; + + function destroy() { + if (destroyed) return; + destroyed = true; + editor.off("transaction", onTransaction); + editor.off("focus", onFocus); + editor.off("blur", onBlur); + editor.off("update", onUpdate); + editor.off("destroy", destroy); + root.removeEventListener("mousedown", onRootMouseDown, { capture: true }); + dom.removeEventListener("dragstart", onHideEvent); + dom.removeEventListener("contextmenu", onHideEvent); + dom.removeEventListener("compositionend", evaluateLater); + dom.removeEventListener("pointerdown", onPointerDown); + window.removeEventListener("pointerup", onPointerUp); + window.removeEventListener("pointercancel", onPointerUp); + window.removeEventListener("resize", onReposition); + scrollTarget.removeEventListener("scroll", onReposition); + clearTimeout(deferTimer); + clearTimeout(resizeTimer); + deferTimer = undefined; + resizeTimer = undefined; + hide(); + if (controllers.get(editor) === controller) controllers.delete(editor); + } + + editor.on("transaction", onTransaction); + editor.on("focus", onFocus); + editor.on("blur", onBlur); + editor.on("update", onUpdate); + editor.on("destroy", destroy); + root.addEventListener("mousedown", onRootMouseDown, { capture: true }); + dom.addEventListener("dragstart", onHideEvent); + dom.addEventListener("contextmenu", onHideEvent); + dom.addEventListener("compositionend", evaluateLater); + dom.addEventListener("pointerdown", onPointerDown); + window.addEventListener("pointerup", onPointerUp); + window.addEventListener("pointercancel", onPointerUp); + window.addEventListener("resize", onReposition); + scrollTarget.addEventListener("scroll", onReposition, { passive: true }); + + const controller: BubbleController = { + get visible() { + return visible; + }, + update, + updatePosition, + hide, + setPlacement(next) { + placement = next; + }, + destroy, + }; + controllers.set(editor, controller); + return controller; +} diff --git a/components/smart-toolbar/bubble/bubble-rules.ts b/components/smart-toolbar/bubble/bubble-rules.ts index a8d6333b..13d6156c 100644 --- a/components/smart-toolbar/bubble/bubble-rules.ts +++ b/components/smart-toolbar/bubble/bubble-rules.ts @@ -1,5 +1,6 @@ import { getMarkRange } from "@tiptap/core"; import { + AllSelection, type EditorState, NodeSelection, TextSelection, @@ -61,8 +62,9 @@ function insideOneLink(state: EditorState, from: number, to: number) { * * Hidden when read-only, suppressed (a keystroke or Esc dismissed it), * unfocused (neither the editor nor the bubble), on a node selection, on a - * range with no text, with either end in a code block (code and Mermaid), - * or with both ends inside one hyperlink (its own preview takes over). + * range with no text or only whitespace, with either end in a code block + * (code and Mermaid), or with both ends inside one hyperlink (its own + * preview takes over). Shows for a text range and for select all. */ export function shouldShowBubble( view: BubbleView, @@ -74,10 +76,16 @@ export function shouldShowBubble( if (!view.editable || suppressed) return false; if (!isFocusWithBubble(view, root)) return false; if (selection instanceof NodeSelection) return false; - if (!(selection instanceof TextSelection)) return false; + // Select all (⌘A) is an `AllSelection` (spec §7.2: it shows). + if ( + !(selection instanceof TextSelection) && + !(selection instanceof AllSelection) + ) { + return false; + } const { from, to, $from, $to } = selection; const { doc } = view.state; - if (doc.textBetween(from, to).length === 0) return false; + if (doc.textBetween(from, to).trim().length === 0) return false; if ( $from.parent.type.name === CODE_BLOCK || $to.parent.type.name === CODE_BLOCK @@ -189,3 +197,55 @@ export function chooseBubblePlacement({ rect.right > band.left; return obstacles.some(overlaps) ? "bottom" : "top"; } + +/** Two rects are on one line when their tops differ by at most this (px). */ +export const BUBBLE_LINE_SLACK = 2; + +/** The visible, non-empty rects of `rects`, as the band sees them. */ +function visibleRects( + rects: readonly BubbleRect[], + band: { top: number; bottom: number }, +): BubbleRect[] { + return rects.filter( + (rect) => + rect.right - rect.left >= 1 && + rect.bottom > band.top && + rect.top < band.bottom, + ); +} + +/** Bounding box of the rects on the line whose top is `lineTop`. */ +function unionLine(rects: readonly BubbleRect[], lineTop: number): BubbleRect { + const line = rects.filter( + (rect) => Math.abs(rect.top - lineTop) <= BUBBLE_LINE_SLACK, + ); + return { + top: Math.min(...line.map((rect) => rect.top)), + bottom: Math.max(...line.map((rect) => rect.bottom)), + left: Math.min(...line.map((rect) => rect.left)), + right: Math.max(...line.map((rect) => rect.right)), + }; +} + +/** + * The first line of a selection that shows inside `band` (the scroll + * viewport): its client rects on that line, unioned. Null when none show. + */ +export function firstLineRect( + rects: readonly BubbleRect[], + band: { top: number; bottom: number }, +): BubbleRect | null { + const visible = visibleRects(rects, band); + if (visible.length === 0) return null; + return unionLine(visible, Math.min(...visible.map((rect) => rect.top))); +} + +/** Like `firstLineRect`, for the last line that shows inside `band`. */ +export function lastLineRect( + rects: readonly BubbleRect[], + band: { top: number; bottom: number }, +): BubbleRect | null { + const visible = visibleRects(rects, band); + if (visible.length === 0) return null; + return unionLine(visible, Math.max(...visible.map((rect) => rect.top))); +} diff --git a/components/smart-toolbar/bubble/selection-bubble-view.tsx b/components/smart-toolbar/bubble/selection-bubble-view.tsx index 05d8a4f2..fa946c3a 100644 --- a/components/smart-toolbar/bubble/selection-bubble-view.tsx +++ b/components/smart-toolbar/bubble/selection-bubble-view.tsx @@ -1,18 +1,15 @@ "use client"; -import { PluginKey } from "@tiptap/pm/state"; -import type { EditorView } from "@tiptap/pm/view"; -import { type Editor, posToDOMRect } from "@tiptap/react"; -import { BubbleMenu } from "@tiptap/react/menus"; +import type { Editor } from "@tiptap/react"; import { useCallback, useEffect, useLayoutEffect, - useMemo, useRef, useState, useSyncExternalStore, } from "react"; +import { createPortal } from "react-dom"; import { Toolbar, ToolbarSeparator } from "@/components/ui/toolbar"; import { emitUiIntent } from "@/lib/editor-actions/ui-intents"; @@ -21,6 +18,11 @@ import { ActionButton } from "../action-button"; import { ColorSplit } from "../color-controls"; import { PaintFormatButton } from "../formats/paint-format-button"; import { StatusPill } from "../status-pill"; +import { bubbleReferenceRect } from "./bubble-anchor"; +import { + type BubbleController, + createBubbleController, +} from "./bubble-controller"; import { BUBBLE_OFFSET, type BubblePlacement, @@ -33,14 +35,28 @@ import { } from "./bubble-rules"; import "./selection-bubble.scss"; -/** One key for every editor: plugin state is per editor state. */ -const BUBBLE_KEY = new PluginKey("selectionBubble"); /** Exit fade (spec §4.3: 140 ms in / 90 ms out). */ const EXIT_MS = 90; const CARET_LABEL = ".collaboration-carets__label"; const STICKY_TOOLBAR = ':scope > [data-slot="toolbar"]'; const FOCUS_GUARD = "[data-base-ui-focus-guard]"; +/** + * The bubble's one root (v1 contract §5.2). The controller appends it to + * the scroll container on show and removes it on hide; it is absolute, and + * hidden until each show's first position lands (the controller hides it + * again on hide). + */ +function createBubbleRoot(): HTMLDivElement { + const root = document.createElement("div"); + root.className = "st-bubble"; + root.dataset.smartBubble = ""; + root.dataset.state = "closed"; + root.style.position = "absolute"; + root.style.visibility = "hidden"; + return root; +} + /** Keeps the editor's focus and selection on a click between the items. */ function keepEditorFocus(event: React.MouseEvent) { // React events bubble through portals: act only on the panel's own DOM. @@ -87,18 +103,22 @@ export function SelectionBubbleView(props: SelectionBubbleViewProps) { /** * The desktop selection bubble (spec §4.3, design pass §1): B · I · U │ - * text colour split │ link │ Paint format. A `BubbleMenu` registered once - * per editor with stable - * props; its items mount only while it shows, so typing with no bubble - * runs no bubble code past `shouldShowBubble`'s empty-selection exit. + * text colour split │ link │ Paint format. A `BubbleController` (spec + * §12.1) shows, hides and positions it without a ProseMirror plugin, so + * this lazy chunk never calls `registerPlugin`. Its items mount only while + * it shows, so typing with no bubble runs no bubble code past the + * controller's empty-selection exit. * * DOM contract (v1 contract §5.2, read by D1's Alt+F10): the root carries * `data-smart-bubble` and `data-state="open" | "closed"`, with one - * `role="toolbar"` inside. + * `role="toolbar"` inside; it is a child of the scroll container only while + * shown. */ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { const [shown, setShown] = useState(false); - const rootRef = useRef(null); + // This chunk is client-only: creating the root at first render is safe. + const [root] = useState(createBubbleRoot); + const controllerRef = useRef(null); const suppressedRef = useRef(false); const placementRef = useRef("top"); // Mirrors `placementRef` so the colour popover opens away from the text. @@ -107,54 +127,52 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { const focusInsideRef = useRef(false); const restoreFocusRef = useRef(false); - const dispatchMeta = useCallback( - (meta: unknown) => { - if (editor.isDestroyed) return; - editor.view.dispatch(editor.state.tr.setMeta(BUBBLE_KEY, meta)); - }, - [editor], - ); - /** Esc: fade out for 90 ms, then hide; stays hidden until a new selection. */ const startClose = useCallback(() => { - const root = rootRef.current; - if (!root?.isConnected) return; + if (!root.isConnected) return; suppressedRef.current = true; root.dataset.state = "closed"; root.dataset.closing = ""; window.clearTimeout(closeTimerRef.current); closeTimerRef.current = window.setTimeout( - () => dispatchMeta("hide"), + () => controllerRef.current?.hide(), EXIT_MS, ); - }, [dispatchMeta]); + }, [root]); - const shouldShow = useCallback( - ({ view, element }: { view: EditorView; element: HTMLElement }) => - shouldShowBubble(view, element, suppressedRef.current), - [], - ); + /** + * Scrolled out (the controller hid the root in place) or wholly under the + * sticky row (covered, WCAG 2.4.11; it scrolls with the text, so only a + * scroll tells): not open for Alt+F10, and focus moves to the editor + * before the browser drops it on `body`. + */ + const syncVisibility = useCallback(() => { + if (!root.isConnected || root.dataset.closing !== undefined) return; + const toolbar = scrollTarget.querySelector(STICKY_TOOLBAR); + const covered = + root.style.visibility === "hidden" || + (toolbar !== null && + root.getBoundingClientRect().bottom <= + toolbar.getBoundingClientRect().bottom); + root.dataset.state = covered ? "closed" : "open"; + if (covered && focusInsideRef.current) { + focusInsideRef.current = false; + editor.view.focus(); + } + }, [editor, root, scrollTarget]); - const options = useMemo(() => { - const base = { - scrollTarget, - strategy: "absolute" as const, - placement: "top" as const, - offset: BUBBLE_OFFSET, - // The side is decided here (toolbar, remote caret labels), not by flip. - flip: false, - shift: { padding: 8 }, - hide: true, - }; + // One controller per editor for this view's lifetime (StrictMode's second + // effect replaces the first). + useEffect(() => { + if (editor.isDestroyed) return; + const view = editor.view; - /** Flips the bubble below when the band above is taken. */ + /** Flips the bubble below when the band above its first line is taken. */ const place = () => { - const root = rootRef.current; - if (!root?.isConnected || editor.isDestroyed) return; - const { from, to } = editor.state.selection; + if (!root.isConnected || editor.isDestroyed) return; const toolbar = scrollTarget.querySelector(STICKY_TOOLBAR); const next = chooseBubblePlacement({ - selection: posToDOMRect(editor.view, from, to), + selection: bubbleReferenceRect(view, scrollTarget, "top"), bubble: { width: root.offsetWidth, height: root.offsetHeight }, obstacles: Array.from(scrollTarget.querySelectorAll(CARET_LABEL), (n) => n.getBoundingClientRect(), @@ -163,26 +181,28 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { toolbar ? "bottom" : "top" ], }); + // Only on a change: an unconditional reposition would run `place` + // again from its own result. if (next === placementRef.current) return; placementRef.current = next; root.dataset.placement = next; setPlacement(next); - dispatchMeta({ - type: "updateOptions", - options: { options: { ...base, placement: next } }, - }); - dispatchMeta("updatePosition"); + controller.setPlacement(next); + controller.updatePosition(); }; - return { - ...base, + const controller = createBubbleController(editor, scrollTarget, { + root, + shouldShow: () => shouldShowBubble(view, root, suppressedRef.current), + getReferenceRect: (side) => + bubbleReferenceRect( + view, + scrollTarget, + side, + BUBBLE_OFFSET + root.offsetHeight, + ), onShow: () => { - const root = rootRef.current; - if (!root) return; window.clearTimeout(closeTimerRef.current); - // The plugin makes its root a Tab stop; the toolbar inside has one. - // Not `-1` either: a click on the panel would focus a nameless div. - root.removeAttribute("tabindex"); root.dataset.state = "open"; root.dataset.placement = placementRef.current; setPlacement(placementRef.current); @@ -190,54 +210,46 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { setShown(true); }, onHide: () => { - const root = rootRef.current; window.clearTimeout(closeTimerRef.current); - if (root) { - root.dataset.state = "closed"; - delete root.dataset.closing; - } + root.dataset.state = "closed"; + delete root.dataset.closing; restoreFocusRef.current = focusInsideRef.current; focusInsideRef.current = false; setShown(false); }, - onUpdate: place, - }; - }, [editor, scrollTarget, dispatchMeta]); - - // `BubbleMenu` keeps one root for its lifetime. When it registers again - // (dev StrictMode's double effect, or a new editor), the previous - // cleanup removes that root one frame later if it has a parent. With a - // selection already there (this chunk landed after it) the new plugin - // shows the root at once, so the removal detaches a shown bubble without - // `onHide`, and the plugin never shows it again. This frame runs after - // that one: put the root back where the plugin shows it. - useEffect(() => { - const frame = requestAnimationFrame(() => { - const root = rootRef.current; - if (!root || root.isConnected || root.dataset.state !== "open") return; - scrollTarget.appendChild(root); - dispatchMeta("updatePosition"); + onPosition: () => { + syncVisibility(); + place(); + }, }); - return () => cancelAnimationFrame(frame); - }, [scrollTarget, dispatchMeta]); + controller.setPlacement(placementRef.current); + controllerRef.current = controller; + // A selection made before this chunk landed shows now. + controller.update(); + return () => { + controller.destroy(); + if (controllerRef.current === controller) controllerRef.current = null; + }; + }, [editor, scrollTarget, root, syncVisibility]); // One keydown and one mousedown listener on the editor, for the editor's // lifetime. They do nothing unless the bubble is in the DOM, so typing - // with no bubble dispatches nothing extra. + // with no bubble does nothing extra. useEffect(() => { + if (editor.isDestroyed) return; const dom = editor.view.dom; const onKeyDown = (event: KeyboardEvent) => { if (clearsBubbleSuppression(event)) { suppressedRef.current = false; return; } - if (!rootRef.current?.isConnected || !isBubbleDismissKey(event)) return; + if (!root.isConnected || !isBubbleDismissKey(event)) return; if (event.key === "Escape") { startClose(); return; } suppressedRef.current = true; - dispatchMeta("hide"); + controllerRef.current?.hide(); }; const onMouseDown = () => { suppressedRef.current = false; @@ -249,28 +261,24 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { dom.removeEventListener("mousedown", onMouseDown); window.clearTimeout(closeTimerRef.current); }; - }, [editor, dispatchMeta, startClose]); + }, [editor, root, startClose]); - // While shown: hide on read-only (`setEditable` changes neither the - // selection nor the document, so the plugin never re-checks) and when - // focus moves anywhere but the editor, the bubble or its popups (colour - // dialog), from the editor or from the bubble (the stock - // blur check keeps it for anything inside its parent, the whole editor - // shell, and never sees a blur from the bubble itself). Track whether - // focus is in the bubble or a popup. + // While shown: hide when focus moves anywhere but the editor, the bubble + // or its popups (colour dialog), from the editor or from the bubble (the + // controller's blur check never sees a blur from the bubble itself). + // Track whether focus is in the bubble or a popup. Read-only hides in the + // controller (`update` event). useEffect(() => { if (!shown) return; - const root = rootRef.current; - const onEditorUpdate = () => { - if (!editor.isEditable) queueMicrotask(() => dispatchMeta("hide")); - }; - // Focus to the window or `body` fires no `focusin`. + const hide = () => controllerRef.current?.hide(); + // Focus to the window or `body` fires no `focusin`. This also covers a + // `preventHide` left set by a click in the bubble. const onEditorBlur = ({ event }: { event: FocusEvent }) => { - if (event.relatedTarget === null) dispatchMeta("hide"); + if (event.relatedTarget === null) hide(); }; const onFocusIn = (event: FocusEvent) => { const target = event.target; - if (!root || !(target instanceof Element)) return; + if (!(target instanceof Element)) return; const inPopover = target.closest(POPOVER_CONTENT) !== null || // Base UI's guards next to the portal hand focus straight on. @@ -284,7 +292,7 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { !inPopover && !editor.view.dom.contains(target) ) { - dispatchMeta("hide"); + hide(); } }; // Tab past the last stop (or a click on nothing) drops focus on `body`, @@ -294,34 +302,13 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { // (as after Esc) instead of reopening on that focus. const onFocusOut = (event: FocusEvent) => { if (event.relatedTarget !== null || !document.hasFocus()) return; - // The plugin's own `hide()` (it sets opacity 0, then removes the - // root) blurs a focused item mid-dispatch: a nested hide here would - // make its `remove()` throw. `onHide` restores focus as above. - if (root?.style.opacity === "0") return; + // The controller's own hide removes a focused item: not a Tab out. + if (!controllerRef.current?.visible) return; suppressedRef.current = true; - dispatchMeta("hide"); - }; - // `hide: true` hides the root (inline `visibility`) when the selection - // scrolls out, without `onHide`; wholly under the sticky row it is - // covered (WCAG 2.4.11; it scrolls with the text, so only a scroll - // tells). Either way it is not open for Alt+F10, and focus moves to the - // editor before the browser drops it on `body`. - const toolbar = scrollTarget.querySelector(STICKY_TOOLBAR); - const syncVisibility = () => { - if (!root?.isConnected || root.dataset.closing !== undefined) return; - const covered = - root.style.visibility === "hidden" || - (toolbar !== null && - root.getBoundingClientRect().bottom <= - toolbar.getBoundingClientRect().bottom); - root.dataset.state = covered ? "closed" : "open"; - if (covered && focusInsideRef.current) { - focusInsideRef.current = false; - editor.view.focus(); - } + hide(); }; - const observer = new MutationObserver(syncVisibility); - if (root) observer.observe(root, { attributeFilter: ["style"] }); + // The controller repositions on scroll after a debounce; the sticky + // row covers the bubble frame by frame. let frame = 0; const onScroll = () => { if (frame) return; @@ -331,25 +318,22 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { }); }; scrollTarget.addEventListener("scroll", onScroll, { passive: true }); - editor.on("update", onEditorUpdate); editor.on("blur", onEditorBlur); document.addEventListener("focusin", onFocusIn, true); - root?.addEventListener("focusout", onFocusOut); + root.addEventListener("focusout", onFocusOut); return () => { - root?.removeEventListener("focusout", onFocusOut); - observer.disconnect(); + root.removeEventListener("focusout", onFocusOut); scrollTarget.removeEventListener("scroll", onScroll); cancelAnimationFrame(frame); - editor.off("update", onEditorUpdate); editor.off("blur", onEditorBlur); document.removeEventListener("focusin", onFocusIn, true); }; - }, [shown, editor, scrollTarget, dispatchMeta]); + }, [shown, editor, root, scrollTarget, syncVisibility]); useLayoutEffect(() => { if (shown) { // Items just mounted: position (and place) with the real size. - dispatchMeta("updatePosition"); + controllerRef.current?.updatePosition(); return; } if (!restoreFocusRef.current) return; @@ -359,11 +343,12 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { const frame = requestAnimationFrame(() => { const active = document.activeElement; if (active && active !== document.body && active.isConnected) return; + if (editor.isDestroyed) return; if (editor.isEditable) editor.view.focus(); else emitUiIntent(editor, { type: "toolbar.focus" }); }); return () => cancelAnimationFrame(frame); - }, [shown, editor, dispatchMeta]); + }, [shown, editor]); /** Esc on an item: back to the document with its selection, then fade. */ const onEscape = useCallback(() => { @@ -371,36 +356,26 @@ function BubbleView({ editor, scrollTarget }: SelectionBubbleViewProps) { startClose(); }, [editor, startClose]); - return ( - - {shown ? ( - - - - - - - - - - - - ) : null} - + return createPortal( + shown ? ( + + + + + + + + + + + + ) : null, + root, ); } diff --git a/components/smart-toolbar/bubble/selection-bubble.scss b/components/smart-toolbar/bubble/selection-bubble.scss index 99f05048..39e66b0d 100644 --- a/components/smart-toolbar/bubble/selection-bubble.scss +++ b/components/smart-toolbar/bubble/selection-bubble.scss @@ -1,5 +1,5 @@ -// Selection bubble (spec §4.3). The plugin owns the root's inline -// position, visibility and opacity, so the motion runs on the inner panel. +// Selection bubble (spec §4.3). The controller owns the root's inline +// position and visibility, so the motion runs on the inner panel. // Below the sticky toolbar (`z-10`): the bubble slides under it on scroll. .st-bubble { diff --git a/components/smart-toolbar/selection-bubble.tsx b/components/smart-toolbar/selection-bubble.tsx index cfd49a2d..2a17ac59 100644 --- a/components/smart-toolbar/selection-bubble.tsx +++ b/components/smart-toolbar/selection-bubble.tsx @@ -11,7 +11,7 @@ import { import type { SurfaceProps } from "./types"; /** - * The bubble and its plugin are their own chunk; phones never fetch it. + * The bubble and its controller are their own chunk; phones never fetch it. * If it fails to load there is no bubble (every action is in the row) * until the next editor mounts this again. */ @@ -51,7 +51,7 @@ function mountedViewDom(editor: Editor): HTMLElement | null { /** * The scroll container the bubble is appended to and scrolls with. The - * plugin reads it once, so the bubble waits until the view is mounted. + * controller reads it once, so the bubble waits until the view is mounted. */ function useScrollTarget(editor: Editor | null): HTMLElement | null { const [target, setTarget] = useState(null); diff --git a/components/smart-toolbar/status-pill.tsx b/components/smart-toolbar/status-pill.tsx index 3b317239..f1f60dbd 100644 --- a/components/smart-toolbar/status-pill.tsx +++ b/components/smart-toolbar/status-pill.tsx @@ -24,7 +24,7 @@ const PILL_MS = 2500; const ACTION_PILL_MS = 5000; const STICKY_ROW = '.document-editor-wrapper > [data-slot="toolbar"]'; const PAGE_COLUMN = ".document-editor-content"; -/** The bubble's scroll container: the plugin appends its root here. */ +/** The bubble's scroll container: the controller appends its root here. */ const SCROLL_CONTAINER = ".document-editor-wrapper"; const BUBBLE_ROOT = ":scope > [data-smart-bubble]"; @@ -100,7 +100,7 @@ function desktopPosition(pill: HTMLElement): CSSProperties { /** * Calls `measure` (at most once a frame) whenever the bubble appears, - * moves or closes while the pill shows: the plugin appends and removes + * moves or closes while the pill shows: the controller appends and removes * its root and moves it by its inline style, the view flips `data-state`, * and it scrolls with the text under the fixed pill. Returns the cleanup. */ diff --git a/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-dark.jpg b/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-dark.jpg new file mode 100644 index 00000000..e2659c92 Binary files /dev/null and b/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-dark.jpg differ diff --git a/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-light.jpg b/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-light.jpg new file mode 100644 index 00000000..767dcff7 Binary files /dev/null and b/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-light.jpg differ diff --git a/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-rtl.jpg b/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-rtl.jpg new file mode 100644 index 00000000..541023de Binary files /dev/null and b/docs/design/2026-11-17-bubble-quick-insert/p0/branch-two-line-rtl.jpg differ diff --git a/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-dark.jpg b/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-dark.jpg new file mode 100644 index 00000000..7b7d599c Binary files /dev/null and b/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-dark.jpg differ diff --git a/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-light.jpg b/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-light.jpg new file mode 100644 index 00000000..04fdb674 Binary files /dev/null and b/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-light.jpg differ diff --git a/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-rtl.jpg b/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-rtl.jpg new file mode 100644 index 00000000..356be930 Binary files /dev/null and b/docs/design/2026-11-17-bubble-quick-insert/p0/main-two-line-rtl.jpg differ diff --git a/docs/superpowers/specs/2026-11-13-smart-toolbar-v1-contract.md b/docs/superpowers/specs/2026-11-13-smart-toolbar-v1-contract.md index 39290967..46b8133d 100644 --- a/docs/superpowers/specs/2026-11-13-smart-toolbar-v1-contract.md +++ b/docs/superpowers/specs/2026-11-13-smart-toolbar-v1-contract.md @@ -747,6 +747,13 @@ Recorded by the owner of the files they touch. Each one names what changed and w - **§3.2:** the "/" menu (`lib/slash-menu/slash-items.ts`) is a third view that lists from the registry, next to the palette and Insert. It lists the `style` and `list` groups and the `insert.*` actions that can run at the caret (the others only say why when a query matches nothing else), and, as Insert's Diagram ▸ (design pass §9), shows Diagram as one row or as the `template.mermaid` options, never both. Picks run through `runAction` (`lib/slash-menu/run-slash-pick.ts`, one Yjs undo step). - **Eager:** `SlashTrigger` (`extensions/slash-trigger/slash-trigger.ts`, one plugin with state only) and `SlashMenuHost`. Keys (a window capture listener), the combobox attributes (set on `view.dom`), items, matching and the pick runner are the lazy menu chunk, fetched on idle and on the first "/". - **Measured** (same method as A9 and A13; both builds with the same `NEXT_PUBLIC_*` values) on `main` at `b7eddfb` (396,248 B gz, +18,360 B) plus this change: **397,136 B gz, +19,248 B (+888 B eager), 4,816 B under the 23.5 KB budget**, 10 files. On `4b55ec6` it was +923 B; a first build with keys and attributes in the trigger measured +1,398 B there. The menu chunk: **5,291 B gz** (`SLASH_BUDGET=1`, budget 6 KB). The palette's first Alt+/ (`PALETTE_BUDGET=1`, `next start`): 403 B + 20,072 B = **20,475 B, the same files at the same sizes as `main`.** +- **A18 (bubble controller, 2026-11-17): the selection bubble attaches without a plugin.** Spec: `docs/superpowers/specs/2026-11-17-bubble-and-quick-insert-design.md` §4.1, §10.1, §12.1 (BQ2, BQ3). No budget change, no schema or protocol change, no action id, `UiIntent` or memory slot. + - **Gone:** Tiptap's React `` (`@tiptap/react/menus`), the `BUBBLE_KEY` plugin key and its `hide`, `updatePosition` and `updateOptions` metas, and the `requestAnimationFrame` re-append workaround. The lazy bubble chunk no longer calls `registerPlugin`, which rebuilt every plugin view (29) when the chunk landed and again at unmount. `@tiptap/extension-bubble-menu` stays installed and is imported by nothing. + - **Now:** `components/smart-toolbar/bubble/bubble-controller.ts`, one controller per editor (a module `WeakMap`; `destroy()` is idempotent and runs on the editor's `destroy` too), with the plugin's behaviours: the 250 ms show delay, immediate hide, the IME skip, the blur rules, a focus re-check only while hidden (so Esc on an item keeps its 90 ms exit fade; the plugin debounced it), hide on `dragstart`, `contextmenu` and read-only, never showing mid-drag, `computePosition` with `offset(8)`, `shift({ padding: 8 })` and `hide()`, and `autoUpdate` only while shown (`ancestorScroll: false`). Its one `transaction` listener returns at once while hidden with an empty selection. `selection-bubble-view.tsx` renders the items into the root through a React portal. + - **Anchor (`bubble-anchor.ts`):** the first selected line that shows under the sticky row, never the union box (the box between the selection's two ends): a selection that wraps onto the next line is centred on its selected part of the first line, and one that starts at a paragraph's end anchors to the next line's text, never to a whole block. The band-edge probe reads both inline edges and keeps the smaller position (right-to-left lines); the bottom side takes the last selected line, or the first that shows when the selection runs past the view (select all) or the bubble has no room under the last. Each measured range stays inside one textblock (a textblock's end or an empty one moves the scan on to the next), so `getClientRects` never returns a whole block's border box, and a scan reads at most 300 positions. + - **Rules:** select all (an `AllSelection`) shows the bubble; a whitespace-only selection does not. + - **DOM contract (§5.2) unchanged:** the root is `.st-bubble` with `data-smart-bubble`, `data-state` and `data-placement` and one `role="toolbar"` inside; it is appended to `.document-editor-wrapper` on show and removed synchronously on hide, before `onHide` runs, so a focused item leaving with it hides nothing twice. + - **Measured** (same method as A9 and A13, both builds in one clean checkout with the same env): `origin/main` at `08b7663` **393,172 B gz**, this branch merged with it (re-measured at `fad9d16`, after the review fixes) **393,171 B gz (−1 B)**, 10 files, +15,283 B against the baseline, 8,781 B under the 23.5 KB budget. The bubble chunk: **12,238 → 9,798 B gz (−2,440 B)**; `@floating-ui/dom` stays in its shared chunk. ### Open owner decisions (v1 → `main` blockers) Not decided by any track. Each needs the owner's call recorded here before v1 opens against `main`. O1, O2, O3, O4, O6, O8, O9 and O10 are decided; O7 is closed by measurement. O5 is the owner's palette budget, which E records as A7 on `feat/smart-toolbar-e-v11`; it is not a v1 item. diff --git a/tests/e2e/editor-leak.spec.ts b/tests/e2e/editor-leak.spec.ts index b3ab9b29..f791a8ec 100644 --- a/tests/e2e/editor-leak.spec.ts +++ b/tests/e2e/editor-leak.spec.ts @@ -1,6 +1,7 @@ import { type CDPSession, expect, type Page, test } from "@playwright/test"; import { EditorPage } from "./helpers/editor-page"; +import { listenerCounts } from "./helpers/listener-counts"; /** Longer than collab-session's deferred release (1 s). */ const SETTLE_MS = 1_100; @@ -48,36 +49,6 @@ async function liveEditors(cdp: CDPSession): Promise { } } -/** - * Event listeners on `document` and `window`, counted per target and type - * (`"document:keydown"`), so a failure names the listener that leaked. - */ -async function listenerCounts( - cdp: CDPSession, -): Promise> { - const objectGroup = "listener-count"; - const counts: Record = {}; - try { - for (const target of ["document", "window"]) { - const { result } = await cdp.send("Runtime.evaluate", { - expression: target, - objectGroup, - }); - if (!result.objectId) throw new Error(`no ${target}`); - const { listeners } = await cdp.send("DOMDebugger.getEventListeners", { - objectId: result.objectId, - }); - for (const { type } of listeners) { - const key = `${target}:${type}`; - counts[key] = (counts[key] ?? 0) + 1; - } - } - return counts; - } finally { - await cdp.send("Runtime.releaseObjectGroup", { objectGroup }); - } -} - async function reading(page: Page, cdp: CDPSession) { await page.waitForTimeout(SETTLE_MS); await collectGarbage(cdp); diff --git a/tests/e2e/helpers/listener-counts.ts b/tests/e2e/helpers/listener-counts.ts new file mode 100644 index 00000000..c9b958ee --- /dev/null +++ b/tests/e2e/helpers/listener-counts.ts @@ -0,0 +1,32 @@ +import type { CDPSession } from "@playwright/test"; + +/** + * Event listeners on `document` and `window`, counted per target and type + * (`"document:keydown"`), so a failure names the listener that leaked. + * Chromium only (DevTools protocol). + */ +export async function listenerCounts( + cdp: CDPSession, +): Promise> { + const objectGroup = "listener-count"; + const counts: Record = {}; + try { + for (const target of ["document", "window"]) { + const { result } = await cdp.send("Runtime.evaluate", { + expression: target, + objectGroup, + }); + if (!result.objectId) throw new Error(`no ${target}`); + const { listeners } = await cdp.send("DOMDebugger.getEventListeners", { + objectId: result.objectId, + }); + for (const { type } of listeners) { + const key = `${target}:${type}`; + counts[key] = (counts[key] ?? 0) + 1; + } + } + return counts; + } finally { + await cdp.send("Runtime.releaseObjectGroup", { objectGroup }); + } +} diff --git a/tests/e2e/selection-bubble.spec.ts b/tests/e2e/selection-bubble.spec.ts index 3312d634..f87cefb8 100644 --- a/tests/e2e/selection-bubble.spec.ts +++ b/tests/e2e/selection-bubble.spec.ts @@ -16,6 +16,7 @@ import { } from "./helpers/a11y"; import { EditorPage } from "./helpers/editor-page"; import { CHUNK_MARKERS, holdChunk, interceptChunk } from "./helpers/lazy-chunk"; +import { listenerCounts } from "./helpers/listener-counts"; const SCREENS = ".superpowers/screens-r2-bubble"; @@ -924,3 +925,479 @@ test("no bubble on a coarse pointer", async ({ browser }) => { await context.close(); } }); + +/** The non-Playground tab `openDoc` opened. */ +const docTabId = async (page: Page) => { + const id = await page + .locator('[data-tab-id]:not([data-tab-id="playground"])') + .first() + .getAttribute("data-tab-id"); + if (!id) throw new Error("no document tab"); + return id; +}; + +/** Switches to tab `id` and waits for its new editor's server sync. */ +async function openTab(page: Page, id: string) { + await page.evaluate(() => { + const el = document.querySelector(".ProseMirror"); + if (el) Object.assign(el, { tabProbeOld: true }); + }); + await page.locator(`[data-tab-id="${id}"] [aria-selected]`).click(); + await page.waitForFunction(() => { + const region = document.querySelector(".document-editor-content"); + const view = region?.querySelector(".ProseMirror"); + return ( + region?.getAttribute("data-server-synced") === "true" && + view != null && + !("tabProbeOld" in view) + ); + }); +} + +test.describe("selection bubble controller (spec §12.1)", () => { + test("mounting the bubble chunk registers no plugin", async ({ page }) => { + const chunk = await holdChunk(page, CHUNK_MARKERS.bubble); + await openDoc(page); + await page.evaluate(() => { + const editor = window.__tiptap_editor; + if (!editor) throw new Error("editor missing"); + const views = (editor.view as unknown as { pluginViews: object[] }) + .pluginViews; + Object.assign(window, { + __bubbleProbe: { + plugins: editor.state.plugins.length, + views: new WeakSet(views), + }, + }); + }); + chunk.release(); + await dragSelect(page, "some words"); + await expectBubbleOpen(page); + const after = await page.evaluate(() => { + const editor = window.__tiptap_editor; + if (!editor) throw new Error("editor missing"); + const probe = ( + window as unknown as { + __bubbleProbe: { plugins: number; views: WeakSet }; + } + ).__bubbleProbe; + const views = (editor.view as unknown as { pluginViews: object[] }) + .pluginViews; + return { + plugins: editor.state.plugins.length, + before: probe.plugins, + rebuilt: views.filter((view) => !probe.views.has(view)).length, + }; + }); + expect(after.plugins).toBe(after.before); + expect(after.rebuilt).toBe(0); + await chunk.restore(); + }); + + test("Esc on a bubble item plays the exit fade before the root leaves", async ({ + page, + }) => { + await openDoc(page); + await selectText(page, "some words"); + await expectBubbleOpen(page); + await page.keyboard.press("Alt+F10"); + await expect( + bubbleToolbar(page).getByRole("button", { name: "Bold", exact: true }), + ).toBeFocused(); + // Times, in the page, of `data-closing` appearing and the root leaving. + await page.evaluate(() => { + const root = document.querySelector("[data-smart-bubble]"); + const wrapper = root?.parentElement; + if (!root || !wrapper) throw new Error("no bubble"); + const times: { closing?: number; removed?: number } = {}; + Object.assign(window, { __fadeTimes: times }); + new MutationObserver(() => { + if (times.closing === undefined && root.hasAttribute("data-closing")) { + times.closing = performance.now(); + } + }).observe(root, { attributeFilter: ["data-closing"] }); + new MutationObserver(() => { + if (times.removed === undefined && !root.isConnected) { + times.removed = performance.now(); + } + }).observe(wrapper, { childList: true }); + }); + await page.keyboard.press("Escape"); + await expect(page.locator(".tiptap")).toBeFocused(); + await expect(bubble(page)).toHaveCount(0); + const times = await page.evaluate( + () => + (window as unknown as { __fadeTimes: Record }) + .__fadeTimes, + ); + expect(times.closing).toBeDefined(); + // The 90 ms exit fade, not a hide on the returning focus. + expect(times.removed - times.closing).toBeGreaterThanOrEqual(60); + }); + + test("a selection that wraps from the second line anchors to that line", async ({ + page, + }) => { + const long = Array.from( + { length: 6 }, + (_, i) => + `Sentence ${i + 1} of a long paragraph that wraps across several visual lines.`, + ).join(" "); + await openDoc(page, { + type: "doc", + content: [ + { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, + paragraph(text(long)), + ], + }); + // 12 characters from 6 before the end of the paragraph's second visual + // line, so the selection wraps onto the third. The anchor is the part + // on the second line: the rects on the top-most line only (the box + // between the two carets, the old anchor, centres mid-column). + const target = await page.evaluate(() => { + const editor = window.__tiptap_editor; + if (!editor) throw new Error("editor missing"); + const view = editor.view; + const lineStart = (after: number) => { + const top = view.coordsAtPos(after, 1).top; + let pos = after; + while (view.coordsAtPos(pos, 1).top === top) pos += 1; + return pos; + }; + const start = (editor.state.doc.firstChild?.nodeSize ?? 0) + 1; + const second = lineStart(start); + const third = lineStart(second); + const from = third - 6; + const to = from + 12; + editor.chain().focus().setTextSelection({ from, to }).run(); + const a = view.domAtPos(from); + const b = view.domAtPos(to); + const range = document.createRange(); + range.setStart(a.node, a.offset); + range.setEnd(b.node, b.offset); + const rects = [...range.getClientRects()].filter((r) => r.width > 0); + const lineTop = Math.min(...rects.map((r) => r.top)); + const line = rects.filter((r) => Math.abs(r.top - lineTop) <= 2); + const left = Math.min(...line.map((r) => r.left)); + const right = Math.max(...line.map((r) => r.right)); + return { + secondTop: view.coordsAtPos(second, 1).top, + lineTop, + lines: new Set(rects.map((r) => Math.round(r.top))).size, + centre: (left + right) / 2, + }; + }); + expect(target.lines).toBe(2); + expect(Math.abs(target.lineTop - target.secondTop)).toBeLessThanOrEqual(2); + await expectBubbleOpen(page); + await expect(bubble(page)).toHaveAttribute("data-placement", "top"); + await expect + .poll(async () => { + const box = await bubble(page).boundingBox(); + if (!box) return "no box"; + const centred = Math.abs(box.x + box.width / 2 - target.centre) <= 2; + const bottom = box.y + box.height; + const above = + bottom <= target.lineTop && + bottom >= target.lineTop - 8 - box.height - 1; + return centred && above ? "anchored" : JSON.stringify({ box, target }); + }) + .toBe("anchored"); + }); + + test("a selection that starts at a paragraph's end anchors to the next line's text", async ({ + page, + }) => { + await openDoc(page, { + type: "doc", + content: [ + { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, + paragraph(text("A paragraph the selection starts after")), + paragraph(text("Short")), + paragraph(text("The paragraph where the selection ends")), + ], + }); + // From the end of the first paragraph (nothing of it is selected on + // screen) into the third: the second is wholly inside the range, and + // a range over it returns its full-width border box too. + const target = await page.evaluate(() => { + const editor = window.__tiptap_editor; + if (!editor) throw new Error("editor missing"); + const { doc } = editor.state; + const starts: number[] = []; + doc.forEach((_node, offset) => { + starts.push(offset); + }); + const from = starts[2] - 1; + const to = starts[3] + 5; + editor.chain().focus().setTextSelection({ from, to }).run(); + const a = editor.view.domAtPos(starts[2] + 1); + const range = document.createRange(); + range.selectNodeContents(a.node); + const box = range.getBoundingClientRect(); + return { top: box.top, centre: (box.left + box.right) / 2 }; + }); + await expectBubbleOpen(page); + await expect(bubble(page)).toHaveAttribute("data-placement", "top"); + await expect + .poll(async () => { + const box = await bubble(page).boundingBox(); + if (!box) return "no box"; + const centred = Math.abs(box.x + box.width / 2 - target.centre) <= 2; + const above = box.y + box.height <= target.top; + return centred && above ? "anchored" : JSON.stringify({ box, target }); + }) + .toBe("anchored"); + }); + + /** + * A long document scrolled to its middle, then ⌘A: the bubble is in the + * view, just under the sticky row (under the first line that shows). + * `edge` puts the band's top edge in the gap between two paragraphs or + * inside one. Without `warm`, off-screen blocks keep their estimated + * heights (`content-visibility`), and ⌘A, which renders every selected + * block, shifts the page under the view. + */ + async function expectSelectAllUnderRow( + page: Page, + blocks: unknown[], + { edge, warm = true }: { edge?: "gap" | "inside"; warm?: boolean } = {}, + ) { + await openDoc(page, { + type: "doc", + content: [ + { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, + ...blocks, + ], + }); + const ends = await page.evaluate( + async ([edgeAt, warmUp]) => { + const editor = window.__tiptap_editor; + const wrapper = document.querySelector(".document-editor-wrapper"); + const toolbar = wrapper?.querySelector('[data-slot="toolbar"]'); + const children = editor?.view.dom.children; + const count = children?.length ?? 0; + const middle = children?.[Math.floor(count / 2)]; + if (!editor || !wrapper || !toolbar || !children || !middle) { + throw new Error("missing"); + } + const frames = () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + if (warmUp) { + editor.commands.selectAll(); + await frames(); + editor.commands.setTextSelection(1); + await frames(); + } + for (let i = 0; i < 5; i += 1) { + middle.scrollIntoView({ block: "center" }); + await frames(); + } + if (edgeAt) { + const bandTop = toolbar.getBoundingClientRect().bottom + 1; + const blocks = [...children].map((el) => el.getBoundingClientRect()); + const k = blocks.findIndex((box) => box.bottom > bandTop); + const y = + edgeAt === "gap" + ? (blocks[k].bottom + blocks[k + 1].top) / 2 + : (blocks[k].top + blocks[k].bottom) / 2; + wrapper.scrollTop += y - bandTop; + await frames(); + } + editor.view.dom.focus({ preventScroll: true }); + const size = editor.state.doc.content.size; + return { + first: editor.view.coordsAtPos(1).top, + last: editor.view.coordsAtPos(size - 1).top, + }; + }, + [edge, warm] as const, + ); + const viewport = page.viewportSize(); + // The selection runs past both edges of the view. + expect(ends.first).toBeLessThan(0); + expect(ends.last).toBeGreaterThan(viewport?.height ?? 0); + await page.keyboard.press("ControlOrMeta+a"); + await expectBubbleOpen(page); + await expect + .poll(async () => { + const box = await bubble(page).boundingBox(); + const toolbarBottom = await page.evaluate( + () => + document + .querySelector('.document-editor-wrapper > [data-slot="toolbar"]') + ?.getBoundingClientRect().bottom ?? 0, + ); + if (!box || !viewport) return "no box"; + const inside = box.y >= 0 && box.y + box.height <= viewport.height; + const under = box.y >= toolbarBottom && box.y <= toolbarBottom + 60; + return inside && under + ? "under the row" + : JSON.stringify({ box, toolbarBottom }); + }) + .toBe("under the row"); + } + + const wrappingParagraph = (i: number) => + paragraph( + text( + `Paragraph ${i + 1} is long enough to wrap onto three visual lines in the page column, so the top edge of the view can fall inside it or in the gap after it, and the anchor must still pick the first line that shows.`, + ), + ); + + test("select all anchors to the first visible line", async ({ page }) => { + await expectSelectAllUnderRow( + page, + Array.from({ length: 300 }, (_, i) => + paragraph(text(`Paragraph ${i + 1} of a long document`)), + ), + ); + }); + + for (const edge of ["gap", "inside"] as const) { + test(`select all with multi-line paragraphs, the band edge ${edge === "gap" ? "between two" : "inside one"}`, async ({ + page, + }) => { + await expectSelectAllUnderRow( + page, + Array.from({ length: 120 }, (_, i) => wrappingParagraph(i)), + { edge }, + ); + }); + } + + test("a whitespace-only selection shows no bubble", async ({ page }) => { + await openDoc(page, { + type: "doc", + content: [ + { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, + paragraph(text("Gap between words")), + ], + }); + await selectText(page, " "); + expect(await selectionRange(page)).not.toEqual({ from: 0, to: 0 }); + await page.waitForTimeout(400); + await expect(bubble(page)).toHaveCount(0); + }); + + test("dragstart hides it", async ({ page }) => { + await openDoc(page); + await selectText(page, "some words"); + await expectBubbleOpen(page); + await page.locator(".tiptap").dispatchEvent("dragstart"); + await expect(bubble(page)).toHaveCount(0); + }); + + test("tab switch with the bubble open leaves no root and no listeners", async ({ + page, + browserName, + }) => { + test.skip(browserName !== "chromium", "CDP only"); + test.setTimeout(120_000); + await openDoc(page); + const id = await docTabId(page); + // Warm up: both editors, their chunks and the bubble chunk exist. + await openTab(page, "playground"); + await openTab(page, id); + await selectText(page, "some words"); + await expectBubbleOpen(page); + await page.evaluate(() => { + const editor = window.__tiptap_editor; + editor?.commands.setTextSelection(editor.state.selection.from); + }); + await expect(bubble(page)).toHaveCount(0); + const cdp = await page.context().newCDPSession(page); + // Past collab-session's deferred release (1 s). + await page.waitForTimeout(1_100); + const before = await listenerCounts(cdp); + + for (let i = 0; i < 5; i += 1) { + await selectText(page, "some words"); + await expectBubbleOpen(page); + await openTab(page, "playground"); + await expect(bubble(page)).toHaveCount(0); + await openTab(page, id); + } + await expect( + page.locator(".document-editor-wrapper > [data-smart-bubble]"), + ).toHaveCount(0); + expect( + await page.evaluate(() => window.__tiptap_editor?.state.selection.empty), + ).toBe(true); + await page.waitForTimeout(1_100); + const after = await listenerCounts(cdp); + test.info().annotations.push({ + type: "document + window listeners", + description: `${JSON.stringify(before)} → ${JSON.stringify(after)}`, + }); + expect(after).toEqual(before); + }); + + test("a collaborator deleting the selection hides the bubble", async ({ + browser, + }) => { + test.setTimeout(60_000); + const docId = `bubble-collab-${Date.now()}-${Math.random().toString(36).slice(2)}`; + const contextA = await browser.newContext(); + const contextB = await browser.newContext(); + try { + const pageA = await contextA.newPage(); + const pageB = await contextB.newPage(); + await pageA.addInitScript( + `window.__HOCUS_TOKEN = ${JSON.stringify(`user-a-${docId}`)}`, + ); + await pageB.addInitScript( + `window.__HOCUS_TOKEN = ${JSON.stringify(`user-b-${docId}`)}`, + ); + const editorA = new EditorPage(pageA); + await editorA.goto(docId); + await editorA.waitForSync(); + await pageA.evaluate((content) => { + window.__tiptap_editor + ?.chain() + .setMeta("addToHistory", false) + .setContent(content) + .run(); + }, DOC as object); + const editorB = new EditorPage(pageB); + await editorB.goto(docId); + await editorB.waitForSync(); + await expect(pageB.locator(".tiptap")).toContainText("some words", { + timeout: 15_000, + }); + + await selectText(pageA, "some words"); + await expectBubbleOpen(pageA); + // Focus inside the bubble: its removal must hand focus back. + await pageA.keyboard.press("Alt+F10"); + await expect( + bubbleToolbar(pageA).getByRole("button", { name: "Bold", exact: true }), + ).toBeFocused(); + await pageB.evaluate(() => { + const editor = window.__tiptap_editor; + if (!editor) throw new Error("editor missing"); + let range: { from: number; to: number } | null = null; + editor.state.doc.forEach((node, offset) => { + if (!range && node.textContent.includes("some words")) { + range = { from: offset, to: offset + node.nodeSize }; + } + }); + if (!range) throw new Error("paragraph missing"); + editor.chain().deleteRange(range).run(); + }); + await expect(pageA.locator(".tiptap")).not.toContainText("some words", { + timeout: 15_000, + }); + await expect(bubble(pageA)).toHaveCount(0); + await expect(pageA.locator(".tiptap")).toBeFocused(); + // Not suppressed: a new selection (one that clears nothing) shows it. + await selectText(pageA, "First line"); + await expectBubbleOpen(pageA); + } finally { + await contextA.close(); + await contextB.close(); + } + }); +}); diff --git a/tests/unit/components/bubble-controller.test.ts b/tests/unit/components/bubble-controller.test.ts new file mode 100644 index 00000000..9bbb9a3d --- /dev/null +++ b/tests/unit/components/bubble-controller.test.ts @@ -0,0 +1,767 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; + +import type { Editor, JSONContent } from "@tiptap/core"; +import type { Node as ProseMirrorNode } from "@tiptap/pm/model"; +import type { EditorView } from "@tiptap/pm/view"; + +import { + bubbleReferenceRect, + intoTextblock, +} from "@/components/smart-toolbar/bubble/bubble-anchor"; +import { + BUBBLE_SHOW_DELAY_MS, + type BubbleController, + type BubbleHost, + createBubbleController, +} from "@/components/smart-toolbar/bubble/bubble-controller"; +import type { BubblePlacement } from "@/components/smart-toolbar/bubble/bubble-rules"; + +import { createTestEditor } from "../../helpers/create-test-editor"; + +/** Long enough for the show delay and the deferred re-checks to run. */ +const SETTLE_MS = BUBBLE_SHOW_DELAY_MS + 50; +/** Ceiling for `until`: a loaded shared test process can run timers late. */ +const UNTIL_MS = 1_000; + +/** + * Polls `check` until it holds, failing after `UNTIL_MS`. "Now shown" + * assertions use it instead of a fixed slack after the delay. + */ +async function until(check: () => boolean): Promise { + const deadline = performance.now() + UNTIL_MS; + while (!check()) { + if (performance.now() > deadline) { + throw new Error(`not true within ${UNTIL_MS} ms: ${check}`); + } + await Bun.sleep(5); + } +} + +const connected = () => host.root.isConnected; + +const DOC: JSONContent = { + type: "doc", + content: [ + { + type: "heading", + attrs: { level: 1 }, + content: [{ type: "text", text: "Title" }], + }, + { type: "paragraph", content: [{ type: "text", text: "Hello world" }] }, + ], +}; + +let editor: Editor; +let scrollTarget: HTMLElement; +let controller: BubbleController; +let allow: boolean; +let shouldShow: ReturnType boolean>>; +let getReferenceRect: ReturnType< + typeof mock<(placement: BubblePlacement) => DOMRect> +>; +let onShow: ReturnType void>>; +let onHide: ReturnType void>>; +let onPosition: ReturnType void>>; +let host: BubbleHost; + +beforeEach(async () => { + editor = createTestEditor({ content: DOC }); + // `create` runs a tick later; UniqueID then fixes the doc (a doc change). + await new Promise((resolve) => editor.on("create", resolve)); + scrollTarget = document.createElement("div"); + document.body.appendChild(scrollTarget); + allow = true; + shouldShow = mock(() => allow); + getReferenceRect = mock(() => new DOMRect(10, 10, 50, 20)); + onShow = mock(() => {}); + onHide = mock(() => {}); + onPosition = mock(() => {}); + host = { + root: document.createElement("div"), + shouldShow, + getReferenceRect, + onShow, + onHide, + onPosition, + }; + controller = createBubbleController(editor, scrollTarget, host); +}); + +afterEach(() => { + controller.destroy(); + if (!editor.isDestroyed) editor.destroy(); + scrollTarget.remove(); +}); + +const select = (from = 1, to = 4) => + editor.commands.setTextSelection({ from, to }); + +async function showBubble() { + select(); + await until(() => controller.visible); +} + +function setComposing(value: boolean) { + Object.defineProperty(editor.view, "composing", { + configurable: true, + get: () => value, + }); +} + +function blurEditor(relatedTarget: EventTarget | null) { + editor.view.dom.dispatchEvent(new FocusEvent("blur", { relatedTarget })); +} + +describe("createBubbleController", () => { + test("shows after the delay for a non-empty selection and appends the root", async () => { + select(); + expect(host.root.isConnected).toBe(false); + expect(controller.visible).toBe(false); + await until(connected); + expect(host.root.parentElement).toBe(scrollTarget); + expect(controller.visible).toBe(true); + expect(onShow).toHaveBeenCalledTimes(1); + }); + + test("each selection change restarts the delay", async () => { + select(1, 3); + await Bun.sleep(BUBBLE_SHOW_DELAY_MS - 100); + select(1, 4); + await Bun.sleep(BUBBLE_SHOW_DELAY_MS - 100); + expect(host.root.isConnected).toBe(false); + await until(connected); + expect(onShow).toHaveBeenCalledTimes(1); + }); + + test("a transaction that changes neither selection nor doc keeps the timer", async () => { + select(); + await Bun.sleep(BUBBLE_SHOW_DELAY_MS - 100); + const at = performance.now(); + editor.view.dispatch(editor.state.tr.setMeta("noop", true)); + await until(connected); + // The kept timer fires about 100 ms later; a restarted one takes the + // whole delay again. + expect(performance.now() - at).toBeLessThan(BUBBLE_SHOW_DELAY_MS); + }); + + test("hides synchronously on an empty selection and removes the root", async () => { + await showBubble(); + editor.commands.setTextSelection(2); + expect(host.root.isConnected).toBe(false); + expect(controller.visible).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("hides at once when shouldShow turns false on a new selection", async () => { + await showBubble(); + allow = false; + select(1, 3); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("typing with an empty selection never asks shouldShow", async () => { + editor.commands.setTextSelection(2); + shouldShow.mockClear(); + editor.commands.insertContent("abc"); + expect(shouldShow).not.toHaveBeenCalled(); + await Bun.sleep(SETTLE_MS); + expect(shouldShow).not.toHaveBeenCalled(); + expect(host.root.isConnected).toBe(false); + }); + + test("no show while composing; shows after compositionend", async () => { + setComposing(true); + select(); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(false); + setComposing(false); + editor.view.dom.dispatchEvent(new Event("compositionend")); + await until(connected); + }); + + test("dragstart and contextmenu on the editor hide it", async () => { + await showBubble(); + editor.view.dom.dispatchEvent(new Event("dragstart")); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + + select(1, 3); + await until(connected); + editor.view.dom.dispatchEvent(new Event("contextmenu")); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(2); + }); + + test("a hide during the delay cancels the pending show", async () => { + select(); + editor.view.dom.dispatchEvent(new Event("contextmenu")); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(false); + expect(onShow).not.toHaveBeenCalled(); + }); + + test("a pointer drag shows only after pointerup", async () => { + editor.view.dom.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true }), + ); + select(); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(false); + // The drag may end outside the editor. + document.body.dispatchEvent( + new PointerEvent("pointerup", { bubbles: true }), + ); + expect(host.root.isConnected).toBe(false); + await until(connected); + }); + + test("a context menu ends a drag whose pointerup never comes", async () => { + editor.view.dom.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true }), + ); + editor.view.dom.dispatchEvent(new Event("contextmenu")); + select(); + await until(connected); + }); + + test("a pointer drag that empties the selection hides at once", async () => { + await showBubble(); + editor.view.dom.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true }), + ); + editor.commands.setTextSelection(2); + expect(host.root.isConnected).toBe(false); + }); + + test("blur to outside hides; a mousedown inside the root keeps it", async () => { + await showBubble(); + host.root.dispatchEvent(new MouseEvent("mousedown", { bubbles: true })); + blurEditor(null); + expect(host.root.isConnected).toBe(true); + + const inside = document.createElement("button"); + host.root.appendChild(inside); + blurEditor(inside); + expect(host.root.isConnected).toBe(true); + + blurEditor(editor.view.dom); + expect(host.root.isConnected).toBe(true); + + const outside = document.createElement("button"); + document.body.appendChild(outside); + blurEditor(outside); + outside.remove(); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("focus re-evaluates after the selection settles", async () => { + allow = false; + select(); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(false); + allow = true; + editor.view.dom.dispatchEvent(new FocusEvent("focus")); + await until(connected); + }); + + test("focus while shown leaves it to the view (Esc's exit fade)", async () => { + await showBubble(); + // Esc on an item: the view suppresses and fades, focus returns. + allow = false; + editor.view.dom.dispatchEvent(new FocusEvent("focus")); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(true); + }); + + test("hide resets visibility, so a re-shown root waits for its position", async () => { + await showBubble(); + host.root.style.visibility = "visible"; + controller.hide(); + expect(host.root.style.visibility).toBe("hidden"); + }); + + test("setEditable(false) hides it (update event)", async () => { + await showBubble(); + editor.setEditable(false); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("update() re-evaluates at once, without the delay", () => { + select(); + controller.update(); + expect(host.root.isConnected).toBe(true); + expect(onShow).toHaveBeenCalledTimes(1); + allow = false; + controller.update(); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("hide() removes the root synchronously before onHide", async () => { + await showBubble(); + let connectedInOnHide = true; + onHide.mockImplementation(() => { + connectedInOnHide = host.root.isConnected; + }); + controller.hide(); + expect(connectedInOnHide).toBe(false); + controller.hide(); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("positions the root while shown and reads the current placement", async () => { + await showBubble(); + await Bun.sleep(0); + expect(onPosition).toHaveBeenCalled(); + // happy-dom has no layout: the hide middleware reports it hidden. + expect(host.root.style.visibility).not.toBe(""); + expect(getReferenceRect).toHaveBeenLastCalledWith("top"); + + controller.setPlacement("bottom"); + controller.updatePosition(); + await Bun.sleep(0); + expect(getReferenceRect).toHaveBeenLastCalledWith("bottom"); + }); + + test("window resize and scroll reposition after the resize delay", async () => { + await showBubble(); + await Bun.sleep(0); + onPosition.mockClear(); + scrollTarget.dispatchEvent(new Event("scroll")); + window.dispatchEvent(new Event("resize")); + await until(() => onPosition.mock.calls.length > 0); + }); + + test("a position result after hide() is ignored", async () => { + await showBubble(); + await Bun.sleep(0); + onPosition.mockClear(); + controller.updatePosition(); + controller.hide(); + await Bun.sleep(0); + expect(onPosition).not.toHaveBeenCalled(); + }); + + test("destroy is idempotent and detaches every listener", async () => { + controller.destroy(); + controller.destroy(); + select(); + await Bun.sleep(SETTLE_MS); + editor.view.dom.dispatchEvent(new Event("compositionend")); + editor.view.dom.dispatchEvent(new FocusEvent("focus")); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(false); + expect(onShow).not.toHaveBeenCalled(); + expect(onHide).not.toHaveBeenCalled(); + }); + + test("destroy while shown removes the root and clears timers", async () => { + await showBubble(); + select(1, 3); + controller.destroy(); + expect(host.root.isConnected).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + await Bun.sleep(SETTLE_MS); + expect(host.root.isConnected).toBe(false); + expect(onShow).toHaveBeenCalledTimes(1); + }); + + test("editor destroy tears the controller down", async () => { + await showBubble(); + editor.destroy(); + expect(host.root.isConnected).toBe(false); + expect(controller.visible).toBe(false); + expect(onHide).toHaveBeenCalledTimes(1); + controller.destroy(); + expect(onHide).toHaveBeenCalledTimes(1); + }); + + test("one controller per editor: a new one replaces the old", async () => { + const second: BubbleHost = { ...host, root: document.createElement("div") }; + const next = createBubbleController(editor, scrollTarget, second); + select(); + await until(() => second.root.isConnected); + expect(host.root.isConnected).toBe(false); + // The replaced controller's late destroy leaves the new one alone. + controller.destroy(); + expect(second.root.isConnected).toBe(true); + next.destroy(); + expect(second.root.isConnected).toBe(false); + }); +}); + +describe("bubbleReferenceRect", () => { + test("returns a DOMRect in happy-dom (no layout) for both sides", () => { + select(); + for (const placement of ["top", "bottom"] as const) { + const rect = bubbleReferenceRect(editor.view, scrollTarget, placement); + expect(rect).toBeInstanceOf(DOMRect); + } + }); + + interface Line { + top: number; + left: number; + right: number; + } + + const rect = ({ top, left, right }: Line) => + new DOMRect(left, top, right - left, 20); + + /** + * A view with stubbed geometry: the band is 150..700 (sticky row bottom + * to scroll target bottom), lines are 20 px tall. + */ + function stubView({ + from, + to, + lines, + coords, + hit, + domAtPos, + doc, + rectsFor, + }: { + from: number; + to: number; + lines: Line[]; + coords: (pos: number) => { top: number; bottom: number }; + /** The position each band probe hits (a function: per probe). */ + hit?: number | ((probe: { left: number; top: number }) => number); + domAtPos?: (pos: number) => { node: Node; offset: number }; + /** A real document; by default one big textblock. */ + doc?: ProseMirrorNode; + /** The rects of one measured range; by default `lines`. */ + rectsFor?: (from: number, to: number) => Line[]; + }) { + const ranges: Array<[number, number]> = []; + const probes: Array<{ left: number; top: number }> = []; + const text = document.createTextNode("x"); + let start = -1; + const view = { + state: { + selection: { from, to }, + // By default every position is inside one big textblock, so + // ranges are only capped by the selection and the 300 positions. + doc: doc ?? { + content: { size: 5000 }, + resolve: () => ({ + parent: { inlineContent: true }, + start: () => 0, + end: () => 1e6, + before: () => -1, + after: () => 1e6 + 1, + }), + }, + }, + dom: { + getBoundingClientRect: () => new DOMRect(40, 0, 600, 5000), + ownerDocument: { + createRange: () => ({ + setStart: () => {}, + setEnd: () => {}, + getClientRects: () => { + const last = ranges.at(-1); + const own = rectsFor && last ? rectsFor(...last) : lines; + return own.map(rect); + }, + }), + }, + }, + coordsAtPos: (pos: number) => ({ left: 50, right: 60, ...coords(pos) }), + posAtCoords: (probe: { left: number; top: number }) => { + probes.push(probe); + if (hit === undefined) return null; + return { pos: typeof hit === "number" ? hit : hit(probe), inside: -1 }; + }, + domAtPos: (pos: number) => { + if (start < 0) start = pos; + else { + ranges.push([start, pos]); + start = -1; + } + return domAtPos ? domAtPos(pos) : { node: text, offset: 0 }; + }, + }; + return { view: view as unknown as EditorView, ranges, probes }; + } + + function stubScrollTarget(): HTMLElement { + const target = document.createElement("div"); + target.getBoundingClientRect = () => new DOMRect(0, 100, 800, 600); + const toolbar = document.createElement("div"); + toolbar.dataset.slot = "toolbar"; + toolbar.getBoundingClientRect = () => new DOMRect(0, 100, 800, 50); + target.appendChild(toolbar); + return target; + } + + const inBand = () => ({ top: 300, bottom: 320 }); + + test("top: the first line of the selection inside the band", () => { + const { view, ranges } = stubView({ + from: 10, + to: 50, + coords: inBand, + lines: [ + { top: 120, left: 60, right: 700 }, // under the sticky row + { top: 300, left: 100, right: 300 }, + { top: 301, left: 300, right: 500 }, + { top: 320, left: 40, right: 640 }, + ], + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "top"); + expect(ranges).toEqual([[10, 50]]); + expect([result.left, result.right, result.top, result.bottom]).toEqual([ + 100, 500, 300, 321, + ]); + }); + + test("top: a start above the band reads at most 300 positions from the band's first line", () => { + const { view, ranges, probes } = stubView({ + from: 10, + to: 4000, + coords: (pos) => (pos === 10 ? { top: 20, bottom: 40 } : inBand()), + hit: 900, + lines: [{ top: 160, left: 40, right: 640 }], + }); + bubbleReferenceRect(view, stubScrollTarget(), "top"); + expect(probes).toEqual([ + { left: 41, top: 151 }, + { left: 639, top: 151 }, + ]); + expect(ranges).toEqual([[900, 1200]]); + }); + + test("top: a right-to-left line starts at its right edge (the smaller position)", () => { + const { view, ranges } = stubView({ + from: 10, + to: 4000, + coords: (pos) => (pos === 10 ? { top: 20, bottom: 40 } : inBand()), + // The left edge of an RTL line is its logical end. + hit: ({ left }) => (left < 100 ? 950 : 900), + lines: [{ top: 160, left: 40, right: 640 }], + }); + bubbleReferenceRect(view, stubScrollTarget(), "top"); + expect(ranges).toEqual([[900, 1200]]); + }); + + test("top: the band hit is clamped into the selection", () => { + const { view, ranges } = stubView({ + from: 10, + to: 40, + coords: (pos) => (pos === 10 ? { top: 20, bottom: 40 } : inBand()), + hit: 3, + lines: [{ top: 160, left: 40, right: 640 }], + }); + bubbleReferenceRect(view, stubScrollTarget(), "top"); + expect(ranges).toEqual([[10, 40]]); + }); + + test("bottom: the last selected line, when the selection ends in the band", () => { + const { view, ranges, probes } = stubView({ + from: 10, + to: 2000, + coords: (pos) => (pos === 10 ? { top: 20, bottom: 40 } : inBand()), + lines: [ + { top: 600, left: 40, right: 640 }, + { top: 680, left: 40, right: 200 }, + ], + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "bottom"); + expect(probes).toEqual([]); + expect(ranges).toEqual([[1700, 2000]]); + expect([result.left, result.right, result.top]).toEqual([40, 200, 680]); + }); + + test("bottom: no room under the last line takes the first visible line", () => { + const { view, ranges } = stubView({ + from: 10, + to: 2000, + coords: inBand, + lines: [ + { top: 300, left: 40, right: 640 }, + { top: 680, left: 40, right: 200 }, + ], + }); + const target = stubScrollTarget(); + const roomy = bubbleReferenceRect(view, target, "bottom", 0); + expect(roomy.top).toBe(680); + // 680 + 20 + 46 is past the band's bottom (700). + const tight = bubbleReferenceRect(view, target, "bottom", 46); + expect(tight.top).toBe(300); + expect(ranges.at(-1)).toEqual([10, 310]); + }); + + test("bottom: a selection past the band's bottom (select all) takes its first visible line", () => { + const { view, ranges, probes } = stubView({ + from: 0, + to: 4000, + coords: (pos) => + pos === 0 + ? { top: 20, bottom: 40 } + : pos === 4000 + ? { top: 900, bottom: 920 } + : inBand(), + hit: 900, + lines: [ + { top: 160, left: 40, right: 300 }, + { top: 680, left: 40, right: 640 }, + ], + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "bottom"); + expect(probes).toEqual([ + { left: 41, top: 151 }, + { left: 639, top: 151 }, + ]); + expect(ranges).toEqual([[900, 1200]]); + expect([result.left, result.right, result.top]).toEqual([40, 300, 160]); + }); + + describe("each range stays inside one textblock", () => { + // Title 0..7 (text 1..6), "One" 7..12 (text 8..11), empty paragraph + // 12..14, "Two" 14..19 (text 15..18). + const realDoc = () => { + const ed = createTestEditor({ + content: { + type: "doc", + content: [ + { + type: "heading", + attrs: { level: 1 }, + content: [{ type: "text", text: "Title" }], + }, + { type: "paragraph", content: [{ type: "text", text: "One" }] }, + { type: "paragraph" }, + { type: "paragraph", content: [{ type: "text", text: "Two" }] }, + ], + }, + }); + const doc = ed.state.doc; + ed.destroy(); + return doc; + }; + + test("top: a start at a textblock's end reads the next one, skipping an empty one", () => { + const doc = realDoc(); + expect(doc.content.size).toBe(19); + const { view, ranges } = stubView({ + doc, + from: 11, + to: 18, + coords: inBand, + lines: [], + // Only "Two" has a line; a whole-block box would be in every other. + rectsFor: (a) => (a === 15 ? [{ top: 300, left: 40, right: 80 }] : []), + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "top"); + // "One" from its end is empty; the empty paragraph is skipped. + expect(ranges).toEqual([[15, 18]]); + expect([result.top, result.left, result.right]).toEqual([300, 40, 80]); + }); + + test("top: a select-all start reads the title only, never past it", () => { + const doc = realDoc(); + const { view, ranges } = stubView({ + doc, + from: 0, + to: 19, + coords: inBand, + lines: [{ top: 300, left: 40, right: 640 }], + }); + bubbleReferenceRect(view, stubScrollTarget(), "top"); + expect(ranges).toEqual([[1, 6]]); + }); + + test("bottom: an end at a textblock's start reads the previous one", () => { + const doc = realDoc(); + const { view, ranges } = stubView({ + doc, + from: 1, + to: 15, + coords: inBand, + lines: [], + rectsFor: (a) => (a === 8 ? [{ top: 300, left: 40, right: 80 }] : []), + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "bottom"); + expect(ranges).toEqual([[8, 11]]); + expect(result.top).toBe(300); + }); + }); + + test("falls back to the selection's rect when no line shows", () => { + const { view } = stubView({ + from: 10, + to: 50, + coords: (pos) => ({ top: pos, bottom: pos + 20 }), + lines: [], + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "top"); + expect([result.top, result.bottom]).toEqual([10, 70]); + }); + + test("falls back when measuring throws", () => { + const { view } = stubView({ + from: 10, + to: 50, + coords: (pos) => ({ top: pos, bottom: pos + 20 }), + lines: [{ top: 300, left: 40, right: 640 }], + domAtPos: () => { + throw new RangeError("no DOM"); + }, + }); + const result = bubbleReferenceRect(view, stubScrollTarget(), "bottom"); + expect([result.top, result.bottom]).toEqual([10, 70]); + }); +}); + +describe("intoTextblock", () => { + const doc = () => + createTestEditor({ + content: { + type: "doc", + content: [ + { + type: "heading", + attrs: { level: 1 }, + content: [{ type: "text", text: "Title" }], + }, + { type: "horizontalRule" }, + { type: "paragraph", content: [{ type: "text", text: "Body" }] }, + ], + }, + }); + + test("keeps a position that is already in a textblock", () => { + const ed = doc(); + expect(intoTextblock(ed.state.doc, 3, 1, 20)).toBe(3); + expect(intoTextblock(ed.state.doc, 3, -1, 0)).toBe(3); + ed.destroy(); + }); + + test("moves a block boundary forward into the next textblock, past a rule", () => { + const ed = doc(); + // 0: before the title; 7: after it, before the rule; 8: after the rule. + expect(intoTextblock(ed.state.doc, 0, 1, 100)).toBe(1); + expect(intoTextblock(ed.state.doc, 7, 1, 100)).toBe(9); + ed.destroy(); + }); + + test("moves the end backward into the previous textblock", () => { + const ed = doc(); + const size = ed.state.doc.content.size; + expect(intoTextblock(ed.state.doc, size, -1, 0)).toBe(size - 1); + expect(intoTextblock(ed.state.doc, 8, -1, 0)).toBe(6); + ed.destroy(); + }); + + test("never passes the limit", () => { + const ed = doc(); + expect(intoTextblock(ed.state.doc, 7, 1, 8)).toBe(8); + expect(intoTextblock(ed.state.doc, 8, -1, 7)).toBe(7); + ed.destroy(); + }); +}); diff --git a/tests/unit/components/selection-bubble-rules.test.ts b/tests/unit/components/selection-bubble-rules.test.ts index 4dfe10b1..879f9bef 100644 --- a/tests/unit/components/selection-bubble-rules.test.ts +++ b/tests/unit/components/selection-bubble-rules.test.ts @@ -1,14 +1,16 @@ import { afterEach, describe, expect, it } from "bun:test"; import type { Editor, JSONContent } from "@tiptap/core"; -import { NodeSelection, TextSelection } from "@tiptap/pm/state"; +import { AllSelection, NodeSelection, TextSelection } from "@tiptap/pm/state"; import { BUBBLE_ACTION_IDS, type BubbleView, chooseBubblePlacement, clearsBubbleSuppression, + firstLineRect, isBubbleDismissKey, + lastLineRect, POPOVER_CONTENT, shouldShowBubble, } from "@/components/smart-toolbar/bubble/bubble-rules"; @@ -223,6 +225,14 @@ describe("shouldShowBubble", () => { expect(shouldShowBubble(viewFor(editor), root(), false)).toBe(false); }); + it("shows for select all (an AllSelection)", () => { + editor = createTestEditor({ content: DOC }); + editor.view.dispatch( + editor.state.tr.setSelection(new AllSelection(editor.state.doc)), + ); + expect(shouldShowBubble(viewFor(editor), root(), false)).toBe(true); + }); + it("hides inside a code block", () => { editor = createTestEditor({ content: DOC }); const from = posOf(editor, "const"); @@ -263,6 +273,23 @@ describe("shouldShowBubble", () => { expect(shouldShowBubble(viewFor(editor), root(), false)).toBe(true); }); + it("hides for a whitespace-only selection", () => { + editor = createTestEditor({ + content: { + type: "doc", + content: [ + { type: "heading", attrs: { level: 1 }, content: [text("Title")] }, + { type: "paragraph", content: [text("a b")] }, + ], + }, + }); + const from = posOf(editor, "a b") + 1; + select(editor, from, from + 3); + const { from: f, to: t } = editor.state.selection; + expect(editor.state.doc.textBetween(f, t)).toBe(" "); + expect(shouldShowBubble(viewFor(editor), root(), false)).toBe(false); + }); + it("hides for a range with no text (across block boundaries only)", () => { editor = createTestEditor({ content: DOC }); const hrEnd = posOf(editor, "after"); @@ -373,6 +400,55 @@ describe("chooseBubblePlacement", () => { }); }); +const rect = (top: number, left: number, right: number, h = 20) => ({ + top, + bottom: top + h, + left, + right, +}); + +describe("firstLineRect / lastLineRect", () => { + it("firstLineRect unions the rects on the first visible line", () => { + const band = { top: 0, bottom: 1000 }; + expect( + firstLineRect( + [rect(100, 300, 500), rect(101, 500, 520), rect(130, 50, 400)], + band, + ), + ).toEqual({ top: 100, bottom: 121, left: 300, right: 520 }); + }); + + it("firstLineRect skips lines above the band and zero-width rects", () => { + expect( + firstLineRect([rect(-40, 0, 300), rect(10, 40, 40), rect(30, 60, 90)], { + top: 0, + bottom: 800, + }), + ).toEqual({ top: 30, bottom: 50, left: 60, right: 90 }); + }); + + it("firstLineRect is null when no line is in the band", () => { + expect( + firstLineRect([rect(900, 0, 10)], { top: 0, bottom: 800 }), + ).toBeNull(); + }); + + it("lastLineRect unions the rects on the last visible line", () => { + expect( + lastLineRect( + [rect(100, 300, 500), rect(130, 50, 400), rect(131, 400, 420)], + { top: 0, bottom: 1000 }, + ), + ).toEqual({ top: 130, bottom: 151, left: 50, right: 420 }); + }); + + it("lastLineRect is null when no line is in the band", () => { + expect( + lastLineRect([rect(-90, 0, 10)], { top: 0, bottom: 800 }), + ).toBeNull(); + }); +}); + describe("BUBBLE_ACTION_IDS", () => { it("names registry actions that exist, so every bubble action is also in the row", () => { for (const id of BUBBLE_ACTION_IDS) {