Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): keep selection-anchored floating surfaces inside the editor pane (PRD-8075, PRD-8216) (#3734)
serafin-garciab76de9a8e1ee
diff --git a/.changeset/selection-surfaces-stay-in-editor-pane.md b/.changeset/selection-surfaces-stay-in-editor-pane.mdnew file mode 100644index 000000000..ed28d0372--- /dev/null+++ b/.changeset/selection-surfaces-stay-in-editor-pane.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++Floating surfaces anchored inside the editor now stay inside the editor pane.++The formatting toolbar and the comment composer used to escape it. Selecting a passage taller than the visible area and then scrolling left them floating above the pane over the document tab strip, or below it over the Ask AI composer and the status footer. Both now clamp to the same visible region: below the toolbar, above the Ask AI composer and any conflict-resolution footer, and inside the pane's side edges. The toolbar still disappears once the selected passage is completely out of sight, and the comment composer stays put while it holds a draft so an in-progress comment is never lost to a scroll.++The same fix reaches two more surfaces that had the same defect. The slash, wiki-link, and tag pickers used to overhang the pane's right edge whenever the cursor sat past the middle of a line, and could extend below the pane over the Ask AI composer. They now stay inside the pane, and their list shortens to fit the room actually available beside the cursor instead of covering the line being typed on. The markdown-lint hover callout used to paint over the editor toolbar when its line sat near the top of the pane, and to overhang the right edge near the end of a line. It now stays inside the pane on both axes.diff --git a/knip.config.ts b/knip.config.tsindex 8ad68f996..b61debe5e 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -124,9 +124,7 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/package.json b/packages/app/package.jsonindex 7120eb5da..d9e6cd413 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -28,7 +28,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/selection-surface-pane-clip.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts tests/stress/tab-close-scroll-restore.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsxindex 0b92a5df1..c4344540a 100644--- a/packages/app/src/comments/CommentSelectionAffordance.tsx+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx@@ -13,9 +13,12 @@* selection, so without that mark a multi-line pick lost its end; with it, a* quote preview would be saying twice what the page already shows.*- * Positioning clones the BubbleMenuBar recipe (posToDOMRect virtual element ++ * Positioning follows the BubbleMenuBar recipe (posToDOMRect virtual element +* floating-ui autoUpdate/computePosition) anchored to the captured range so the- * card stays put while you type. Rendered above the native bar (z-60).+ * card stays put while you type. The middleware chain is this card's own, but+ * the region it clips and clamps against comes from the same producers the+ * formatting bar uses (editor/utils/editor-visible-region.ts) rather than a+ * second description of the pane. Rendered above the native bar (z-60).*/// biome-ignore-all lint/plugin/no-physical-direction-utility: pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-physical-direction-utilitygrit@@ -32,6 +35,11 @@ import {ComposerMentionInput,type ComposerMentionInputHandle,} from '@/editor/ComposerMentionInput';+import {+ deriveEditorClipOptions,+ deriveEditorShiftOptions,+ SELECTION_SURFACE_GAP_PX,+} from '@/editor/utils/editor-visible-region';import { getEditorView } from '@/editor/utils/get-editor-view';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';import { cn } from '@/lib/utils';@@ -143,12 +151,36 @@ export function CommentSelectionAffordance({computePosition(virtualEl, floating, {placement: 'bottom-start',strategy: 'fixed',- middleware: [offset(8), flip(), shift({ padding: 8 })],- }).then(({ x, y }) => {- floating.style.position = 'fixed';- floating.style.left = `${x}px`;- floating.style.top = `${y}px`;- });+ middleware: [+ offset(SELECTION_SURFACE_GAP_PX),+ // A bare flip() clips against the viewport, which includes the+ // tab strip above the pane — so the card needs the region+ // boundary as well as the clamp that keeps it inside it.+ flip(deriveEditorClipOptions(editor)),+ shift(deriveEditorShiftOptions(editor)),+ // No hide(): unlike the formatting bar, this card holds a draft and+ // owns focus, so stamping `visibility: hidden` on it would drop the+ // caret to <body> mid-sentence. Scrolling the captured passage out+ // of the region parks the card at the region's edge instead, where+ // the draft stays reachable.+ ],+ })+ .then(({ x, y }) => {+ if (!floating.isConnected) return;+ floating.style.position = 'fixed';+ floating.style.left = `${x}px`;+ floating.style.top = `${y}px`;+ })+ .catch((error: unknown) => {+ // The region producers are evaluated inside this call, so a rejection+ // can originate here or in floating-ui. Keep the last good+ // coordinates rather than moving the card somewhere wrong, and say+ // why — a silent card that has stopped tracking its passage reads as+ // a positioning bug with no trail.+ if (floating.isConnected) {+ console.warn('[comments] composer computePosition failed', error);+ }+ });});}, [captured, editor]);diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsxindex 14913c51c..dc84f3276 100644--- a/packages/app/src/components/EditorActivityPool.tsx+++ b/packages/app/src/components/EditorActivityPool.tsx@@ -1071,7 +1071,7 @@ export function ScrollPreservingContainer({<divref={ref}data-testid="editor-scroll-container"- // Toolbar exclusion zone = 3.5rem (EditorToolbar's rendered height). Five+ // Toolbar exclusion zone = 3.5rem (EditorToolbar's rendered height). Six// load-bearing constants must move together if the toolbar height changes:// - `pt-14` (here): initial-paint content reserve so doc content doesn't// start behind the absolute-positioned EditorToolbar overlay.@@ -1092,6 +1092,9 @@ export function ScrollPreservingContainer({// - editorToolbarOverlapPx in editor/mode-switch-landing.ts: the mode-switch// capture probes step in from this inset, and the landing hands it to// the controller as the target's resting offset below the toolbar.+ // - editorToolbarOverlapPx in editor/utils/editor-visible-region.ts: the+ // top inset of the region selection-anchored floating surfaces clip+ // and clamp against, so the toolbar band counts as occluded.// The toolbar itself: components/EditorToolbar.tsx.className={cn('editor-doc-scroll subtle-scrollbar h-full overflow-y-auto',diff --git a/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx b/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsxindex 328a82f5f..97df8be30 100644--- a/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx+++ b/packages/app/src/editor/bubble-menu/BubbleMenuBar.tsx@@ -6,8 +6,12 @@ import { BubbleMenu } from '@tiptap/react/menus';import { useRef, useState } from 'react';import { CommentBubbleButton } from '@/comments/CommentBubbleButton';import { Separator } from '@/components/ui/separator';+import {+ deriveEditorClipOptions,+ deriveEditorShiftOptions,+ SELECTION_SURFACE_GAP_PX,+} from '../utils/editor-visible-region';import { BlockTypeSelector } from './BlockTypeSelector';-import { deriveEditorClipOptions } from './bubble-menu-clip';import { shouldShowBubbleMenu } from './bubble-menu-state';import { FileBubbleButtons, isFileNodeSelected } from './FileBubbleButtons';import { FootnoteBubbleButton } from './FootnoteBubbleButton';@@ -60,8 +64,11 @@ export function BubbleMenuBar({// Clips placement to the editor's visible content region and hides the bar// when the selection scrolls behind the toolbar / bottom composer / footer —- // see bubble-menu-clip.ts for why the viewport alone is the wrong boundary.+ // see editor-visible-region.ts for why the viewport alone is the wrong boundary.const clipOptions = deriveEditorClipOptions(editor);+ // The clamp that keeps the bar inside that region. The boundary alone only+ // detects the overflow.+ const shiftOptions = deriveEditorShiftOptions(editor);const onShow = () => {const popup = menuRef.current;@@ -71,7 +78,12 @@ export function BubbleMenuBar({computePosition(virtualEl, popup, {placement: 'top',strategy: 'fixed',- middleware: [offset(8), flip(clipOptions), shift({ padding: 8 }), hide(clipOptions)],+ middleware: [+ offset(SELECTION_SURFACE_GAP_PX),+ flip(clipOptions),+ shift(shiftOptions),+ hide(clipOptions),+ ],}).then(({ x, y, middlewareData }) => {if (popup.isConnected) {@@ -84,8 +96,12 @@ export function BubbleMenuBar({popup.style.visibility = middlewareData.hide?.referenceHidden ? 'hidden' : 'visible';}})- .catch(() => {- // Position calculation failed (e.g., detached element) — autoUpdate will retry+ .catch((error: unknown) => {+ // computePosition is deferred third-party work, so teardown can win+ // the race. Live popups need a diagnostic; autoUpdate will retry.+ if (popup.isConnected) {+ console.warn('[bubble-menu] computePosition failed', error);+ }});});};@@ -108,15 +124,24 @@ export function BubbleMenuBar({updateDelay={250}// flip/shift/hide mirror the autoUpdate loop above: the plugin runs its// own computePosition on editor transactions (remote CRDT edits- // included), so both paths must agree on clipping and on when the- // selection counts as occluded — the plugin applies `referenceHidden`- // itself.+ // included), so both paths must agree on clipping, on the clamp that+ // keeps the bar inside the clip region, and on when the selection counts+ // as occluded — the plugin applies `referenceHidden` itself.+ //+ // `placement` and `offset` are stated rather than inherited from the+ // plugin's defaults because `pendingOffsetPx` below compensates for this+ // chain applying its gap AFTER the clamp — that compensation is only+ // correct while the gap matches the loop's, so both paths name it.options={{onShow,onHide,strategy: 'fixed',+ placement: 'top',+ offset: SELECTION_SURFACE_GAP_PX,flip: clipOptions,- shift: { padding: 8 },+ shift: deriveEditorShiftOptions(editor, {+ pendingOffsetPx: SELECTION_SURFACE_GAP_PX,+ }),hide: clipOptions,}}className="z-50 flex items-center gap-0.5 rounded-lg border bg-background p-1 shadow-md"diff --git a/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsx b/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsxdeleted file mode 100644index 49f376c97..000000000--- a/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsx+++ /dev/null@@ -1,106 +0,0 @@-/**- * DOM-tier tests for `deriveEditorClipOptions` — the floating-ui clipping- * config that keeps the selection bubble menu inside the editor's visible- * content region (scroll container minus the toolbar band and the live- * bottom-composer / conflict-footer overlays).- *- * DOM tier because the derivable resolves the `.editor-doc-scroll` ancestor- * via `closest()` on a rendered tree and reads the overlay-height CSS vars- * off the document root's inline style — both real-DOM behaviors.- *- * The load-bearing property is liveness: the options function is re-invoked- * per `computePosition` pass and must reflect the overlay vars *at that- * moment* (the composer card grows with its draft and collapses to nothing),- * not a snapshot from when the menu mounted.- *- * Invocation: `bun run test:dom` from `packages/app/`.- */--import { cleanup, render } from '@testing-library/react';-import type { Editor } from '@tiptap/react';-import { afterEach, describe, expect, test } from 'vitest';-import { TOOLBAR_HEIGHT } from '../extensions/frozen-table-headers';-import { deriveEditorClipOptions } from './bubble-menu-clip';--/** Renders the editor-DOM shape the derivable walks: a `.editor-doc-scroll`- * scroll container wrapping the ProseMirror mount the editor points at. */-function renderEditorInScroller(): { editor: Editor; scroller: HTMLElement } {- const { container } = render(- <div className="editor-doc-scroll">- <div data-testid="pm-mount" />- </div>,- );- const scroller = container.querySelector('.editor-doc-scroll') as HTMLElement;- const dom = container.querySelector('[data-testid="pm-mount"]') as HTMLElement;- return { editor: { view: { dom } } as unknown as Editor, scroller };-}--afterEach(() => {- cleanup();- document.documentElement.style.removeProperty('--ask-composer-height');- document.documentElement.style.removeProperty('--conflict-footer-height');-});--describe('deriveEditorClipOptions', () => {- test('bounds to the editor scroll container with the toolbar band as top inset', () => {- const { editor, scroller } = renderEditorInScroller();- const options = deriveEditorClipOptions(editor)();- expect(options.boundary).toBe(scroller);- expect(options.padding).toEqual({ top: TOOLBAR_HEIGHT, bottom: 0 });- });-- test('bottom inset tracks the published composer height', () => {- const { editor } = renderEditorInScroller();- document.documentElement.style.setProperty('--ask-composer-height', '236px');- expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(236);- });-- test('conflict-footer overlay alone sets the bottom inset', () => {- const { editor } = renderEditorInScroller();- document.documentElement.style.setProperty('--conflict-footer-height', '48px');- expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(48);- });-- test('composer and conflict-footer overlays stack into one bottom inset', () => {- const { editor } = renderEditorInScroller();- document.documentElement.style.setProperty('--ask-composer-height', '236px');- document.documentElement.style.setProperty('--conflict-footer-height', '48px');- expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(284);- });-- test('re-reads overlay heights on every invocation', () => {- const { editor } = renderEditorInScroller();- const derive = deriveEditorClipOptions(editor);- expect(derive().padding.bottom).toBe(0);- document.documentElement.style.setProperty('--ask-composer-height', '180px');- expect(derive().padding.bottom).toBe(180);- document.documentElement.style.removeProperty('--ask-composer-height');- expect(derive().padding.bottom).toBe(0);- });-- test('malformed overlay value reads as no inset', () => {- const { editor } = renderEditorInScroller();- document.documentElement.style.setProperty('--ask-composer-height', 'auto');- expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(0);- });-- test('omits the boundary when no scroll container is resolvable', () => {- const { container } = render(<div data-testid="pm-mount" />);- const dom = container.querySelector('[data-testid="pm-mount"]') as HTMLElement;- const editor = { view: { dom } } as unknown as Editor;- const options = deriveEditorClipOptions(editor)();- expect('boundary' in options).toBe(false);- expect(options.padding.top).toBe(TOOLBAR_HEIGHT);- });-- test('pre-mount editor (throwing view proxy) falls back to the default boundary', () => {- const editor = {- get view(): never {- throw new Error('view not mounted');- },- } as unknown as Editor;- const options = deriveEditorClipOptions(editor)();- expect('boundary' in options).toBe(false);- expect(options.padding.top).toBe(TOOLBAR_HEIGHT);- });-});diff --git a/packages/app/src/editor/bubble-menu/bubble-menu-clip.ts b/packages/app/src/editor/bubble-menu/bubble-menu-clip.tsdeleted file mode 100644index b65fbad4d..000000000--- a/packages/app/src/editor/bubble-menu/bubble-menu-clip.ts+++ /dev/null@@ -1,57 +0,0 @@-import type { Editor } from '@tiptap/react';-import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';--/**- * Floating-UI clipping options that keep selection-anchored menus inside the- * editor's *visible* content region, not just inside the viewport.- *- * `.editor-doc-scroll` clips the document, but the region where a selection- * actually reads as visible is smaller than the container's box: the- * EditorToolbar overlays the container's top exclusion zone, and the Ask AI- * bottom composer (stacked above the conflict-resolution footer when one is- * up) floats over the container's bottom edge. None of these are clipping- * ancestors, so a body-appended `position: fixed` bubble menu keeps tracking- * a selection that has scrolled behind them — sliding over the composer card- * and the status footer below the container.- *- * Pass the result to `flip()` so placement decisions stay inside the visible- * region, and to `hide()` (default strategy `referenceHidden`) so the menu- * disappears once the selection itself is fully occluded — matching what the- * user can see rather than what the DOM clips.- *- * Shaped as a floating-ui derivable (re-evaluated on every `computePosition`- * pass) because the composer publishes a live height — its card grows with- * the draft and collapses to nothing — and the scroll container can be- * remounted across document switches.- */-export function deriveEditorClipOptions(editor: Editor) {- return () => {- let boundary: Element | null = null;- try {- boundary = editor.view.dom.closest('.editor-doc-scroll');- } catch {- // `editor.view` is a throwing proxy until the ProseMirror view mounts- // (recycle/remount race) — fall back to the default boundary this pass.- }- const padding = {- top: editorToolbarOverlapPx(),- bottom:- readRootInlinePxVar('--ask-composer-height') +- readRootInlinePxVar('--conflict-footer-height'),- };- // No resolvable scroll container (detached view, non-doc host): fall back- // to floating-ui's default boundary rather than pinning a stale element.- return boundary ? { boundary, padding } : { padding };- };-}--/**- * Both overlay heights are published as inline styles on the document root- * (BottomComposer and use-conflict-footer-height.ts), so read the inline- * declaration directly instead of paying a `getComputedStyle` resolution on- * every scroll tick. Absent (overlay closed) or malformed values read as 0.- */-function readRootInlinePxVar(name: string): number {- const value = Number.parseFloat(document.documentElement.style.getPropertyValue(name));- return Number.isFinite(value) ? value : 0;-}diff --git a/packages/app/src/editor/extensions/frozen-table-headers.ts b/packages/app/src/editor/extensions/frozen-table-headers.tsindex 39e43862b..b04679a04 100644--- a/packages/app/src/editor/extensions/frozen-table-headers.ts+++ b/packages/app/src/editor/extensions/frozen-table-headers.ts@@ -56,11 +56,13 @@ import { Plugin, PluginKey } from '@tiptap/pm/state';import { EDITOR_TOOLBAR_HEIGHT, editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';// EditorToolbar is absolutely positioned at the top of the scroll container,-// 3.5rem tall. Frozen headers must clear it. One of the four load-bearing+// 3.5rem tall. Frozen headers must clear it. One of the six load-bearing// toolbar-height constants listed in components/EditorActivityPool.tsx —-// move them together. Exported so selection-anchored floating menus can treat-// the toolbar band as occluded (editor/bubble-menu/bubble-menu-clip.ts)-// instead of keeping a fifth drifting copy of the value.+// move them together. A re-export of the canonical value in+// lib/editor-toolbar-overlap.ts rather than a second copy: the+// selection-anchored floating surfaces read that module directly (through+// editorToolbarOverlapPx), and this name is what their region tests and the+// globals.css occluder note cite for the band.export const TOOLBAR_HEIGHT = EDITOR_TOOLBAR_HEIGHT;// Subtle shadow to indicate the frozen row overlaps the table body.diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.tsindex 49cb3b805..54aa6e75d 100644--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts@@ -41,7 +41,7 @@ import {MarkdownManager,} from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';-import { Extension } from '@tiptap/core';+import { type Editor, Extension } from '@tiptap/core';import type { Node as PmNode } from '@tiptap/pm/model';import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state';import { Decoration, DecorationSet, type EditorView } from '@tiptap/pm/view';@@ -52,11 +52,22 @@ import {clearPendingSourceNavigation,peekPendingSourceNavigation,} from '@/editor/source-editor-navigation';+import {+ deriveEditorClipOptions,+ deriveEditorShiftOptions,+} from '@/editor/utils/editor-visible-region';import { cn } from '@/lib/utils';import { blockIndexForLine, comparableChildCount, computeSourceBlockSpans } from '../block-spans';import { fetchEffectiveLintConfig, subscribeToLintConfigChanged } from '../lint-config-client';import { runScrollNavigation } from '../scroll-restore-coordination';+/**+ * Gap the hover callout keeps from the block it describes. Independent of the+ * visible-region contract: the clamp works at any gap, so this stays at the+ * value the callout has always used.+ */+const LINT_CALLOUT_GAP_PX = 6;+const markdownLintDecorationKey = new PluginKey<DecorationSet>('markdownLintDecorations');/** CSS classes consumed by `.ProseMirror .ok-lint-block*` in globals.css. */@@ -176,6 +187,8 @@ function createLintTooltip(opts: {getFixes: (block: HTMLElement) => LintTextEdit[];applyFix?: (fixes: LintTextEdit[]) => void;+ /** The host editor, for the visible-region clip/clamp the callout takes. */+ editor: Editor;},): { destroy: () => void } {const tooltip = document.createElement('div');@@ -257,10 +270,19 @@ function createLintTooltip(hideTimer = setTimeout(reallyHide, 140);}+ // The callout is anchored to a line inside the document's scroll container,+ // so the editor's visible content region — not the window — is the box it has+ // to stay in. The boundary alone only detects the overflow; the clamp is what+ // keeps a callout hovered near the column's right edge from sliding over the+ // rail beside the pane, and one hovered near the top of the pane from+ // painting across the toolbar.+ const clipOptions = deriveEditorClipOptions(opts.editor);+ const shiftOptions = deriveEditorShiftOptions(opts.editor);+function position() {computePosition(virtualEl, tooltip, {placement: 'top-start',- middleware: [offset(6), flip(), shift({ padding: 8 })],+ middleware: [offset(LINT_CALLOUT_GAP_PX), flip(clipOptions), shift(shiftOptions)],}).then(({ x, y }) => {if (tooltip.isConnected) {@@ -426,6 +448,7 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsOaddProseMirrorPlugins() {const { docName, getSource, applyFix } = this.options;+ const { editor } = this;// One serializer/parser for this editor's lifetime — same extension set the// bridge uses, so serialize→lint→parseToMdast matches the rendered content.const md = new MarkdownManager({ extensions: coreExtensions });@@ -662,7 +685,7 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsOconst offset = resolved.depth >= 1 ? resolved.before(1) : 0;return currentFixes.get(offset) ?? [];};- const tooltip = createLintTooltip(view, { getFixes, applyFix });+ const tooltip = createLintTooltip(view, { getFixes, applyFix, editor });window.addEventListener(LINT_NAV_EVENT, onLintNav);// Re-lint after a source-only auto-fix (which leaves the PM doc — and// thus the update() hook below — untouched) so the stale squiggle clears.diff --git a/packages/app/src/editor/extensions/slash-command.ts b/packages/app/src/editor/extensions/slash-command.tsindex 201dfa1e8..208a17ccc 100644--- a/packages/app/src/editor/extensions/slash-command.ts+++ b/packages/app/src/editor/extensions/slash-command.ts@@ -202,7 +202,9 @@ export const SlashCommand = Extension.create<SlashCommandOptions>({currentProps = props;selectedIndex = 0;- const result = createSuggestionPopup(() => currentProps, 'slash-command');+ const result = createSuggestionPopup(() => currentProps, 'slash-command', {+ clipToEditorPane: true,+ });posState.popup = result.popup;doPosition = result.doPosition;diff --git a/packages/app/src/editor/extensions/suggestion-floating-ui.ts b/packages/app/src/editor/extensions/suggestion-floating-ui.tsindex ce1c7f41f..4a31ae9e2 100644--- a/packages/app/src/editor/extensions/suggestion-floating-ui.ts+++ b/packages/app/src/editor/extensions/suggestion-floating-ui.ts@@ -1,11 +1,24 @@import { autoUpdate, computePosition, flip, offset, shift, size } from '@floating-ui/dom';+import type { Editor } from '@tiptap/core';import type { SuggestionProps } from '@tiptap/suggestion';+import {+ deriveEditorClipOptions,+ deriveEditorShiftOptions,+} from '@/editor/utils/editor-visible-region';export interface SuggestionPositionState {popup: HTMLDivElement | null;stopAutoUpdate: (() => void) | null;}+/**+ * Gap a suggestion picker keeps from its caret, in both the document editor and+ * the composers. Independent of the visible-region contract: the clamp works at+ * any gap, so this stays at the value the pickers have always used rather than+ * harmonising with the bubble bar's.+ */+const SUGGESTION_ANCHOR_GAP_PX = 4;+/*** How many selectable items the currently-open suggestion picker holds, keyed* by the ProseMirror view it is attached to. The COMPOSER pickers (`@` and@@ -33,6 +46,56 @@ export function suggestionHasSelectableItem(view: object): boolean {return (suggestionSelectableCounts.get(view) ?? 0) > 0;}+/**+ * The picker's middleware chain.+ *+ * Without an `editor` this is the window-relative chain: `flip`/`shift` fall+ * back to floating-ui's clipping ancestors, and `size` caps the list at 40vh.+ * With one, all three take the editor's visible content region instead, so a+ * ~490px picker opened past the middle of the prose column stops sliding over+ * whatever sits in the rail beside the pane.+ *+ * `size` sits BEFORE `shift`, which is the reverse of floating-ui's usual+ * advice and is load-bearing here. `size` measures the floating rect where it+ * currently is; run after the clamp it sees a box the clamp has already pushed+ * inside the region, reports no overflow, and never shrinks anything — leaving+ * a full-height picker parked over the caret line whenever the caret sits too+ * far from both region edges to host one. Run before the clamp it measures the+ * ideal placement, caps the list at the room actually available beside the+ * anchor, and leaves the clamp with nothing to do.+ */+function buildMiddleware(popup: HTMLDivElement, editor: Editor | undefined) {+ const applySize = {+ apply({ availableHeight }: { availableHeight: number }) {+ if (popup.isConnected) {+ popup.style.setProperty(+ '--suggestion-menu-max-height',+ `${Math.min(availableHeight, window.innerHeight * 0.4)}px`,+ );+ }+ },+ };+ if (!editor) {+ return [+ offset(SUGGESTION_ANCHOR_GAP_PX),+ flip(),+ // Keep the popup inside the viewport when its width pushes past the+ // right edge — required since the slash-menu preview panel widened the+ // popup to ~490px, where right-half cursor positions or narrow viewports+ // would otherwise clip the preview.+ shift({ padding: 8 }),+ size(applySize),+ ];+ }+ const clipOptions = deriveEditorClipOptions(editor);+ return [+ offset(SUGGESTION_ANCHOR_GAP_PX),+ flip(clipOptions),+ size(() => ({ ...clipOptions(), ...applySize })),+ shift(deriveEditorShiftOptions(editor)),+ ];+}+/*** Create a positioned suggestion popup element and its positioning helpers.* Shared by slash-command and wiki-link suggestion menus.@@ -58,10 +121,19 @@ export function suggestionHasSelectableItem(view: object): boolean {* is async (returns Promise). The `.then()` can resolve after cleanup has* called `popup.remove()` — at that point the reference is non-null but* disconnected. A null-check alone would miss this race.+ *+ * `clipToEditorPane` opts a picker into the editor's visible-region contract:+ * the caret it tracks lives in the document's scroll container, so the picker+ * belongs inside that container's visible box rather than merely inside the+ * window. It is opt-in rather than derived because this factory also serves the+ * COMPOSER pickers, whose caret sits in the Ask AI / comment composer — a+ * surface that legitimately floats outside the document pane, and would be+ * clamped into it by a blanket application.*/export function createSuggestionPopup(getCurrentProps: () => SuggestionProps<unknown> | null,label: string,+ { clipToEditorPane = false }: { clipToEditorPane?: boolean } = {},): {popup: HTMLDivElement;doPosition: () => void;@@ -107,27 +179,10 @@ export function createSuggestionPopup(// available space → items load but flip() still sees the constrained height// → never flips above. The fallback 40vh matches the component's CSS default.popup.style.removeProperty('--suggestion-menu-max-height');+ const editor = clipToEditorPane ? getCurrentProps()?.editor : undefined;computePosition(virtualEl, popup, {placement: 'bottom-start',- middleware: [- offset(4),- flip(),- // Keep the popup inside the viewport when its width pushes past the- // right edge — required since the slash-menu preview panel widened the- // popup to ~490px, where right-half cursor positions or narrow viewports- // would otherwise clip the preview.- shift({ padding: 8 }),- size({- apply({ availableHeight }) {- if (popup.isConnected) {- popup.style.setProperty(- '--suggestion-menu-max-height',- `${Math.min(availableHeight, window.innerHeight * 0.4)}px`,- );- }- },- }),- ],+ middleware: buildMiddleware(popup, editor),}).then(({ x, y }) => {if (popup.isConnected) {diff --git a/packages/app/src/editor/extensions/tag-suggestion.ts b/packages/app/src/editor/extensions/tag-suggestion.tsindex 270ba0604..ddcf7f7cc 100644--- a/packages/app/src/editor/extensions/tag-suggestion.ts+++ b/packages/app/src/editor/extensions/tag-suggestion.ts@@ -306,7 +306,9 @@ export function configureTagSuggestion(editor: Editor) {currentProps = props;selectedIndex = 0;- const result = createSuggestionPopup(() => currentProps, 'tag-suggestion');+ const result = createSuggestionPopup(() => currentProps, 'tag-suggestion', {+ clipToEditorPane: true,+ });posState.popup = result.popup;doPosition = result.doPosition;reveal = result.reveal;diff --git a/packages/app/src/editor/extensions/wiki-link-suggestion.ts b/packages/app/src/editor/extensions/wiki-link-suggestion.tsindex 33feb8085..d20693ed4 100644--- a/packages/app/src/editor/extensions/wiki-link-suggestion.ts+++ b/packages/app/src/editor/extensions/wiki-link-suggestion.ts@@ -761,7 +761,9 @@ export function configureWikiLinkSuggestion(editor: Editor) {currentProps = props;selectedIndex = 0;- const result = createSuggestionPopup(() => currentProps, 'wiki-link-suggestion');+ const result = createSuggestionPopup(() => currentProps, 'wiki-link-suggestion', {+ clipToEditorPane: true,+ });posState.popup = result.popup;doPosition = result.doPosition;reveal = result.reveal;diff --git a/packages/app/src/editor/utils/editor-visible-region.dom.test.tsx b/packages/app/src/editor/utils/editor-visible-region.dom.test.tsxnew file mode 100644index 000000000..122b81d29--- /dev/null+++ b/packages/app/src/editor/utils/editor-visible-region.dom.test.tsx@@ -0,0 +1,253 @@+/**+ * DOM-tier tests for both halves of the editor's visible-region contract:+ * `deriveEditorClipOptions`, which describes the region (scroll container+ * minus the toolbar band and the live bottom-composer / conflict-footer+ * overlays), and `deriveEditorShiftOptions`, which clamps a surface into it.+ * The consumers are the formatting bubble bar and the comment composer, so+ * neither the module nor these tests belong to either one.+ *+ * DOM tier because the derivable resolves the `.editor-doc-scroll` ancestor+ * via `closest()` on a rendered tree and reads the overlay-height CSS vars+ * off the document root's inline style — both real-DOM behaviors.+ *+ * The load-bearing property is liveness: the options function is re-invoked+ * per `computePosition` pass and must reflect the overlay vars *at that+ * moment* (the composer card grows with its draft and collapses to nothing),+ * not a snapshot from when the menu mounted.+ *+ * Invocation: `pnpm run test:dom` from `packages/app/`.+ */++import { cleanup, render } from '@testing-library/react';+import type { Editor } from '@tiptap/react';+import { afterEach, describe, expect, test } from 'vitest';+import { TOOLBAR_HEIGHT } from '../extensions/frozen-table-headers';+import { deriveEditorClipOptions, deriveEditorShiftOptions } from './editor-visible-region';++/** Renders the editor-DOM shape the derivable walks: a `.editor-doc-scroll`+ * scroll container wrapping the ProseMirror mount the editor points at. */+function renderEditorInScroller(): { editor: Editor; scroller: HTMLElement } {+ const { container } = render(+ <div className="editor-doc-scroll">+ <div data-testid="pm-mount" />+ </div>,+ );+ const scroller = container.querySelector('.editor-doc-scroll') as HTMLElement;+ const dom = container.querySelector('[data-testid="pm-mount"]') as HTMLElement;+ return { editor: { editorView: { dom } } as unknown as Editor, scroller };+}++/** An editor whose ProseMirror view has not mounted yet (recycle/remount+ * race): `getEditorView` reads the real `editorView` field, which is+ * `undefined` until the view exists. */+function preMountEditor(): Editor {+ return {} as unknown as Editor;+}++afterEach(() => {+ cleanup();+ document.documentElement.style.removeProperty('--ask-composer-height');+ document.documentElement.style.removeProperty('--conflict-footer-height');+});++describe('deriveEditorClipOptions', () => {+ test('bounds to the editor scroll container with the toolbar band as top inset', () => {+ const { editor, scroller } = renderEditorInScroller();+ const options = deriveEditorClipOptions(editor)();+ expect(options.boundary).toBe(scroller);+ expect(options.padding).toEqual({ top: TOOLBAR_HEIGHT, bottom: 0 });+ });++ test('bottom inset tracks the published composer height', () => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', '236px');+ expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(236);+ });++ test('conflict-footer overlay alone sets the bottom inset', () => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--conflict-footer-height', '48px');+ expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(48);+ });++ test('composer and conflict-footer overlays stack into one bottom inset', () => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', '236px');+ document.documentElement.style.setProperty('--conflict-footer-height', '48px');+ expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(284);+ });++ test('re-reads overlay heights on every invocation', () => {+ const { editor } = renderEditorInScroller();+ const derive = deriveEditorClipOptions(editor);+ expect(derive().padding.bottom).toBe(0);+ document.documentElement.style.setProperty('--ask-composer-height', '180px');+ expect(derive().padding.bottom).toBe(180);+ document.documentElement.style.removeProperty('--ask-composer-height');+ expect(derive().padding.bottom).toBe(0);+ });++ test('malformed overlay value reads as no inset', () => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', 'auto');+ expect(deriveEditorClipOptions(editor)().padding.bottom).toBe(0);+ });++ test('omits the boundary when no scroll container is resolvable', () => {+ const { container } = render(<div data-testid="pm-mount" />);+ const dom = container.querySelector('[data-testid="pm-mount"]') as HTMLElement;+ const editor = { editorView: { dom } } as unknown as Editor;+ const options = deriveEditorClipOptions(editor)();+ expect('boundary' in options).toBe(false);+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT);+ });++ test('pre-mount editor (no ProseMirror view yet) falls back to the default boundary', () => {+ const options = deriveEditorClipOptions(preMountEditor())();+ expect('boundary' in options).toBe(false);+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT);+ });+});++/**+ * The producer's counterpart: `deriveEditorClipOptions` describes the visible+ * region, and `deriveEditorShiftOptions` keeps a surface inside it. Its+ * options are pure arithmetic over the same inputs, so they are pinnable at+ * this tier — unlike the rendered coordinate, which needs a real layout engine+ * (`tests/stress/selection-surface-pane-clip.e2e.ts`).+ */++/**+ * A chain that applies its anchor gap AFTER the clamp (tiptap's BubbleMenu+ * plugin builds `flip -> shift -> offset`) leaves that many pixels still to be+ * added when the clamp is computed, so the clamp region has to absorb them.+ *+ * Deliberately NOT the production gap (`SELECTION_SURFACE_GAP_PX`, 8): a+ * distinct probe value is what distinguishes a producer that compensates by+ * the argument it was handed from one that reaches for the module constant.+ */+const PENDING_OFFSET_PX = 12;++/** Restates `PANE_GUTTER_PX`, which the module keeps private. */+const EXPECTED_PANE_GUTTER_PX = 8;++/** Overlay heights chosen to make the bottom inset a non-zero, non-round sum. */+const COMPOSER_HEIGHT_PX = 236;+const CONFLICT_FOOTER_HEIGHT_PX = 48;++describe('deriveEditorShiftOptions', () => {+ test('clamps both axes against the region deriveEditorClipOptions describes', () => {+ const { editor, scroller } = renderEditorInScroller();+ const options = deriveEditorShiftOptions(editor)({ placement: 'top' });+ // Cross-axis is the load-bearing half: for a top/bottom placement the Y+ // axis is shift's cross axis, which is the axis a selection scrolled+ // behind the toolbar escapes along.+ expect(options.mainAxis).toBe(true);+ expect(options.crossAxis).toBe(true);+ expect(options.boundary).toBe(scroller);+ });++ test('uncompensated insets match the clip region exactly', () => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ document.documentElement.style.setProperty(+ '--conflict-footer-height',+ `${CONFLICT_FOOTER_HEIGHT_PX}px`,+ );+ const clip = deriveEditorClipOptions(editor)();+ const options = deriveEditorShiftOptions(editor)({ placement: 'top' });+ expect(options.padding.top).toBe(clip.padding.top);+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT);+ expect(options.padding.bottom).toBe(clip.padding.bottom);+ expect(options.padding.bottom).toBe(COMPOSER_HEIGHT_PX + CONFLICT_FOOTER_HEIGHT_PX);+ });++ test.each([+ 'top',+ 'top-start',+ ] as const)('a %s placement absorbs a pending anchor gap by tightening the top inset', (placement) => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ const options = deriveEditorShiftOptions(editor, {+ pendingOffsetPx: PENDING_OFFSET_PX,+ })({ placement });+ // A top-side surface is pushed further UP by the pending gap, so the+ // region it may be clamped into starts that much lower.+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT + PENDING_OFFSET_PX);+ expect(options.padding.bottom).toBe(COMPOSER_HEIGHT_PX - PENDING_OFFSET_PX);+ });++ test.each([+ 'bottom',+ 'bottom-start',+ ] as const)('a %s placement mirrors the compensation', (placement) => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ const options = deriveEditorShiftOptions(editor, {+ pendingOffsetPx: PENDING_OFFSET_PX,+ })({ placement });+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT - PENDING_OFFSET_PX);+ expect(options.padding.bottom).toBe(COMPOSER_HEIGHT_PX + PENDING_OFFSET_PX);+ });++ test.each([+ 'left',+ 'right',+ ] as const)('a %s placement needs no compensation — the pending gap is horizontal there', (placement) => {+ const { editor } = renderEditorInScroller();+ document.documentElement.style.setProperty('--ask-composer-height', `${COMPOSER_HEIGHT_PX}px`);+ const options = deriveEditorShiftOptions(editor, {+ pendingOffsetPx: PENDING_OFFSET_PX,+ })({ placement });+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT);+ expect(options.padding.bottom).toBe(COMPOSER_HEIGHT_PX);+ });++ test('a top placement with no composer up drives the bottom inset negative', () => {+ const { editor } = renderEditorInScroller();+ // Negative is correct, and it is the one arithmetic a reader is most+ // likely to "fix". The plugin's trailing `offset()` re-adds exactly this+ // much: its clamp ceiling is `B - h - padding.bottom`, so a bottom inset+ // of `-p` puts it at `B - h + p` and the offset lands it on `B - h`, the+ // loop's value. Clamp the inset at 0 and the ceiling is `B - h`, the+ // offset takes it to `B - h - p`, and the plugin settles a gap ABOVE the+ // loop. Pinned here because the browser tier never runs with the Ask AI+ // composer collapsed, which is the only state that reaches it.+ const options = deriveEditorShiftOptions(editor, {+ pendingOffsetPx: PENDING_OFFSET_PX,+ })({ placement: 'top' });+ expect(options.padding.bottom).toBe(-PENDING_OFFSET_PX);+ });++ test('keeps a symmetric horizontal gutter that no placement moves', () => {+ const { editor } = renderEditorInScroller();+ const derive = deriveEditorShiftOptions(editor, { pendingOffsetPx: PENDING_OFFSET_PX });+ const top = derive({ placement: 'top' }).padding;+ const bottom = derive({ placement: 'bottom' }).padding;+ expect(top.left).toBe(top.right);+ // The value, not just the symmetry: the e2e's containment tolerance is+ // itself 8 px, so a change to the gutter is invisible at that tier.+ expect(top.left).toBe(EXPECTED_PANE_GUTTER_PX);+ expect(bottom.left).toBe(top.left);+ expect(bottom.right).toBe(top.right);+ });++ test('falls back to insets alone when no scroll container is resolvable', () => {+ const { container } = render(<div data-testid="pm-mount" />);+ const dom = container.querySelector('[data-testid="pm-mount"]') as HTMLElement;+ const editor = { editorView: { dom } } as unknown as Editor;+ const options = deriveEditorShiftOptions(editor)({ placement: 'top' });+ expect('boundary' in options).toBe(false);+ expect(options.mainAxis).toBe(true);+ expect(options.crossAxis).toBe(true);+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT);+ });++ test('pre-mount editor still clamps, against the default boundary', () => {+ const options = deriveEditorShiftOptions(preMountEditor())({ placement: 'top' });+ expect('boundary' in options).toBe(false);+ expect(options.mainAxis).toBe(true);+ expect(options.crossAxis).toBe(true);+ expect(options.padding.top).toBe(TOOLBAR_HEIGHT);+ });+});diff --git a/packages/app/src/editor/utils/editor-visible-region.ts b/packages/app/src/editor/utils/editor-visible-region.tsnew file mode 100644index 000000000..f63a81a8c--- /dev/null+++ b/packages/app/src/editor/utils/editor-visible-region.ts@@ -0,0 +1,172 @@+import type { DetectOverflowOptions, MiddlewareState, ShiftOptions } from '@floating-ui/dom';+import type { Editor } from '@tiptap/react';+import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';+import { getEditorView } from './get-editor-view';++/** Insets that shrink the editor's scroll box down to its visible region. */+interface RegionInsets {+ top: number;+ bottom: number;+}++/** The region insets plus the side gutters a clamped surface also keeps. */+interface SurfaceInsets extends RegionInsets {+ left: number;+ right: number;+}++/**+ * What `deriveEditorClipOptions` emits. `boundary` is narrowed from+ * floating-ui's `Boundary` union to the one element kind this module resolves,+ * and `padding` from `number | Partial<SideObject>` to the two insets it+ * always states — so `deriveEditorShiftOptions` can read `padding.top`+ * directly and a renamed field fails to compile instead of silently+ * forwarding nothing.+ */+type EditorClipOptions = Omit<DetectOverflowOptions, 'boundary' | 'padding'> & {+ boundary?: Element;+ padding: RegionInsets;+};++/**+ * What `deriveEditorShiftOptions` emits. `crossAxis` is stated as the literal+ * `true` rather than left as `boolean`, because dropping it is the one edit+ * that reverts this module's whole purpose: `shift()` defaults it to `false`,+ * and Y is the axis a selection scrolled behind the toolbar escapes along. As+ * a required literal, an omission is a compile error at the producer.+ */+type EditorShiftOptions = Omit<ShiftOptions, 'boundary' | 'padding' | 'mainAxis' | 'crossAxis'> & {+ boundary?: Element;+ mainAxis: true;+ crossAxis: true;+ padding: SurfaceInsets;+};++/**+ * Floating-UI clipping options that keep selection-anchored menus inside the+ * editor's *visible* content region, not just inside the viewport.+ *+ * `.editor-doc-scroll` clips the document, but the region where a selection+ * actually reads as visible is smaller than the container's box: the+ * EditorToolbar overlays the container's top exclusion zone, and the Ask AI+ * bottom composer (stacked above the conflict-resolution footer when one is+ * up) floats over the container's bottom edge. None of these are clipping+ * ancestors, so a body-appended `position: fixed` bubble menu keeps tracking+ * a selection that has scrolled behind them — sliding over the composer card+ * and the status footer below the container.+ *+ * Pass the result to `flip()` so placement decisions stay inside the visible+ * region, to `hide()` (default strategy `referenceHidden`) so the menu+ * disappears once the selection itself is fully occluded — matching what the+ * user can see rather than what the DOM clips — and to+ * `deriveEditorShiftOptions` below, which converts this description of the+ * region into the clamp that keeps a surface inside it. A boundary handed to+ * `flip()`/`hide()` alone detects the overflow and then declines to correct+ * it, so the two producers are consumed together.+ *+ * Floating UI is the canonical positioning primitive for selection-anchored+ * overlays (precedent #35), and this module owns the visible-region half of+ * that contract for any surface anchored inside the editor's scrollable+ * content. It lives under `editor/utils/` rather than beside any one consumer+ * because comments, menus, suggestions, and lint surfaces all read it.+ *+ * Shaped as a floating-ui derivable (re-evaluated on every `computePosition`+ * pass) because the composer publishes a live height — its card grows with+ * the draft and collapses to nothing — and the scroll container can be+ * remounted across document switches.+ */+export function deriveEditorClipOptions(editor: Editor): () => EditorClipOptions {+ return () => {+ // `getEditorView` rather than `editor.view`, which is a proxy that throws+ // until the ProseMirror view mounts (recycle/remount race). A try/catch+ // around that throw swallows every other one too, and a missing boundary+ // is invisible: the clamp quietly falls back to the viewport.+ const boundary = getEditorView(editor)?.dom.closest('.editor-doc-scroll') ?? null;+ const padding = {+ top: editorToolbarOverlapPx(),+ bottom:+ readRootInlinePxVar('--ask-composer-height') ++ readRootInlinePxVar('--conflict-footer-height'),+ };+ // No resolvable scroll container (detached view, non-doc host): fall back+ // to floating-ui's default boundary rather than pinning a stale element.+ return boundary ? { boundary, padding } : { padding };+ };+}++/** Gap a selection-anchored surface keeps between itself and its anchor. */+export const SELECTION_SURFACE_GAP_PX = 8;++/** Gutter a selection-anchored surface keeps from the pane's left/right edges. */+const PANE_GUTTER_PX = 8;++/**+ * The enforcement half of the contract `deriveEditorClipOptions` describes:+ * `shift()` options that clamp a surface into the editor's visible content+ * region on BOTH axes.+ *+ * The load-bearing option is `crossAxis`. For a `top`/`bottom` placement+ * shift's main axis is X and its cross axis is Y, and `crossAxis` defaults to+ * `false` — which is why supplying the boundary alone never kept a surface+ * inside the region it describes. Y is the axis a selection scrolled behind+ * the toolbar escapes along.+ *+ * `pendingOffsetPx` is the anchor gap that `offset()` will still apply AFTER+ * this clamp. It is zero when `offset()` runs first (floating-ui's documented+ * ordering, which the middleware arrays we assemble ourselves follow) and the+ * gap size only for tiptap's BubbleMenu plugin, which builds its own array as+ * `flip -> shift -> offset` and gives us no way to reorder it. Shifting the+ * clamp region by that pending delta makes both writers settle on the same+ * coordinate FOR THE SAME PLACEMENT; that equality is what+ * `selection-surface-pane-clip.e2e.ts` asserts directly, so a tiptap release+ * that adopted floating-ui's documented order would fail there by name rather+ * than drift in the product.+ *+ * The compensation does not extend to `flip`, which is not passed one:+ * `detectOverflow` measures the floating rect at its CURRENT coordinates, so+ * the loop's `flip` (after `offset`) sees a rect one gap further from the+ * anchor than the plugin's (before `offset`). Inside that one-gap band of+ * anchor positions the two writers can still choose different placements, and+ * the bar reads as jumping from above the selection to below it. Both results+ * stay inside the region, so containment is unaffected.+ *+ * Chain order has to be known statically here: `computePosition` never clears+ * `middlewareData` across a `flip()` reset, so sniffing for+ * `middlewareData.offset` reads pass-1 data on pass 2.+ */+export function deriveEditorShiftOptions(+ editor: Editor,+ { pendingOffsetPx = 0 }: { pendingOffsetPx?: number } = {},+): (state: Pick<MiddlewareState, 'placement'>) => EditorShiftOptions {+ const clip = deriveEditorClipOptions(editor);+ return (state) => {+ const { padding, ...boundaryOptions } = clip();+ const side = state.placement.split('-')[0];+ // A top-side surface is pushed further up by the pending gap and a+ // bottom-side one further down; for left/right placements the gap is+ // horizontal and there is no pending Y delta to absorb.+ const pendingY = side === 'top' ? -pendingOffsetPx : side === 'bottom' ? pendingOffsetPx : 0;+ return {+ ...boundaryOptions,+ mainAxis: true,+ crossAxis: true,+ padding: {+ top: padding.top - pendingY,+ bottom: padding.bottom + pendingY,+ left: PANE_GUTTER_PX,+ right: PANE_GUTTER_PX,+ },+ };+ };+}++/**+ * Both overlay heights are published as inline styles on the document root+ * (BottomComposer and use-conflict-footer-height.ts), so read the inline+ * declaration directly instead of paying a `getComputedStyle` resolution on+ * every scroll tick. Absent (overlay closed) or malformed values read as 0.+ */+function readRootInlinePxVar(name: string): number {+ const value = Number.parseFloat(document.documentElement.style.getPropertyValue(name));+ return Number.isFinite(value) ? value : 0;+}diff --git a/packages/app/tests/stress/markdown-lint.e2e.ts b/packages/app/tests/stress/markdown-lint.e2e.tsindex 3c4406a47..4b8b7196c 100644--- a/packages/app/tests/stress/markdown-lint.e2e.ts+++ b/packages/app/tests/stress/markdown-lint.e2e.ts@@ -949,7 +949,7 @@ test.describe('markdown lint — WYSIWYG hover callout vs the editing region', (/*** Max distance from the callout's bottom edge to the top of the block it- * describes. `offset(6)` sets the intended gap; the allowance absorbs+ * describes. `LINT_CALLOUT_GAP_PX` sets the intended gap; the allowance absorbs* `shift()` nudges and sub-pixel jitter while staying far below a callout* that has lost its anchor altogether — an anchor rect of all zeros parks it* at the viewport origin, measured 170.4 px from its block on this fixturediff --git a/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts b/packages/app/tests/stress/selection-surface-pane-clip.e2e.tsnew file mode 100644index 000000000..a61f4ccce--- /dev/null+++ b/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts@@ -0,0 +1,1445 @@+/**+ * Selection-anchored floating surfaces stay inside the editor's visible+ * content region — or don't render.+ *+ * Both surfaces (the formatting bubble bar and the comment composer card) are+ * `position: fixed`, body-appended, and anchored to a virtual element whose+ * rect is the SELECTION's rect, not a laid-out node. Nothing in the DOM clips+ * them: the editor's scroll container is not an ancestor. Their final `top` is+ * whatever floating-ui's middleware chain emits, so the chain is the only thing+ * standing between a selection scrolled behind the toolbar band and a toolbar+ * painted over the document tab strip.+ *+ * `flip()` selects a placement but never moves a coordinate, `shift()` clamps+ * the cross axis only when asked (it isn't, by default) and defaults its+ * boundary to the clipping ancestors rather than the pane, and `hide()`'s+ * `referenceHidden` reports only a FULLY occluded anchor. A selection taller+ * than the pane therefore overflows both candidate placements, keeps the+ * top-side one, and lands at `selectionTop - offset - surfaceHeight` — a+ * coordinate that can be arbitrarily far above the pane, or above the window.+ *+ * What this file pins is the observable contract, not a middleware+ * arrangement: the surface's rendered rect sits inside the visible content+ * region, or the surface is not visible. The region's top edge is read from+ * the opaque `EditorToolbar` overlay's own rect (the same anchor+ * `outline-toolbar-occlusion.e2e.ts` measures against) and its bottom edge+ * from the scroll container MINUS the overlay band the Ask AI composer and+ * the conflict footer publish, which is the same floor production clamps+ * into. Taking the raw container edge instead would leave a composer-sized+ * strip in which a surface could sit over the composer's input and still+ * satisfy every assertion here.+ *+ * Three positioning call sites share the contract and are covered separately:+ *+ * 1. `BubbleMenuBar`'s `autoUpdate` loop — driven by scroll and resize.+ * 2. The `<BubbleMenu>` plugin's OWN `computePosition`, which tiptap runs on+ * editor transactions (remote CRDT edits included) with a second copy of+ * the options. Fixing only the loop leaves this path escaping, so it is+ * exercised through a transaction that cannot wake the loop — see+ * `repositionViaPluginPath`.+ * 3. `CommentSelectionAffordance`'s `autoUpdate` loop.+ *+ * The short-selection cases are guards rather than regressions, and the two+ * surfaces diverge there on purpose. The bar takes `hide()`: it already fires+ * for a fully occluded anchor today and the fix must keep it firing, since+ * clamping the ANCHOR rect instead of the surface's own coordinate would+ * silently break it (`referenceHidden` is computed from that very rect) and+ * leave a bar floating over the composer with no visible selection under it.+ * The comment composer declines that arm: it holds a live draft and owns the+ * caret, so it parks at the region's edge instead of vanishing.+ */++import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { Page } from '@playwright/test';+import {+ type ApiHelpers,+ blockMarker,+ expect,+ generateTallDoc,+ test,+ waitForActiveProviderSynced,+} from './_helpers';++const WYSIWYG = '.ProseMirror:not(.composer-prosemirror)';+const SCROLLER = '[data-testid="editor-scroll-container"]';+const TOOLBAR = '[data-testid="editor-toolbar"]';+const BUBBLE_BAR = 'bubble-menu-bar';+const COMMENT_COMPOSER = 'comment-composer';++/**+ * Absorbs sub-pixel rounding and the few pixels by which the toolbar's+ * rendered box can differ from the constant the clamp reserves for it (the+ * toolbar is content-sized, not a fixed `h-14`). Every escape under test+ * clears the region by at least one surface height — roughly 40 px for the+ * bar, more for the composer card — and by the anchor's whole distance above+ * the pane in the upward cases, so no real escape hides inside it.+ */+const REGION_TOLERANCE_PX = 8;++/**+ * How far below the scroll container's top edge the selection's top is parked.+ * Any value inside the toolbar band works; 20 px puts it unambiguously behind+ * the opaque overlay without touching the band's edges.+ */+const SELECTION_TOP_INSET_PX = 20;++/**+ * Where the selection's top is parked for the composer's occluded-anchor case:+ * ABOVE the scroll container, not merely behind the toolbar band.+ *+ * At `SELECTION_TOP_INSET_PX` the card's unclamped `bottom-start` coordinate+ * already sits within a few px of the region's top, so a containment assertion+ * there passes whether or not the clamp ran. Scrolling the anchor off the top+ * puts the unclamped coordinate ~130 px above the region and gives that half of+ * the test the same margin the other arms have. Kept small enough that the+ * anchor's block stays in a materialized chunk, so `coordsAtPos` is meaningful.+ */+const SELECTION_ABOVE_PANE_INSET_PX = -120;++/**+ * How far above the visible region's FLOOR the selection's END is parked for+ * the downward cases (the floor, not the scroll container's own edge — the Ask+ * AI composer floats over the band between them). Small enough that a surface+ * placed below the anchor clears the region by far more than+ * `REGION_TOLERANCE_PX`, large enough that the anchor stays visible.+ */+const SELECTION_BOTTOM_INSET_PX = 8;++interface SurfaceGeometry {+ present: boolean;+ visible: boolean;+ top: number;+ bottom: number;+ /** Bottom edge of the opaque toolbar overlay — the visible region's top. */+ regionTop: number;+ /** Scroll container's bottom edge less the overlay band — the region's bottom. */+ regionBottom: number;+ /** The raw scroll-container bottom, i.e. `regionBottom` plus the band. */+ scrollerBottom: number;+ /** Height the Ask AI composer + conflict footer reserve at the container's foot. */+ overlayBandPx: number;+ left: number;+ right: number;+ /** The scroll container's left/right edges — the visible region is a box,+ * not a horizontal band, so the pane's side edges bound it too. */+ regionLeft: number;+ regionRight: number;+}++async function readSurfaceGeometry(page: Page, testId: string): Promise<SurfaceGeometry> {+ return readFloatingSurfaceGeometry(page, `[data-testid="${testId}"]`);+}++/**+ * Same read against an arbitrary selector, for the surfaces that carry no+ * `data-testid`: the suggestion picker (a body-appended `div` tagged only by+ * `data-suggestion-popup`) and the markdown-lint hover callout (`.ok-lint-tooltip`).+ *+ * Resolves the same way the scroller and toolbar do — first element that has a+ * layout box — because a pool-hidden editor keeps its own callout in the DOM+ * (`display: none`, so no client rects) alongside the painted one's.+ */+async function readFloatingSurfaceGeometry(page: Page, selector: string): Promise<SurfaceGeometry> {+ return page.evaluate(+ ({ surfaceSel, scrollerSel, toolbarSel }) => {+ // First-match `querySelector` is unsafe here: a hidden `<Activity>`+ // entry keeps its scroll container in the DOM, so more than one can+ // exist and only the painted one is the active scrollport (the idiom+ // `_helpers/scrollport.ts` was factored out to carry).+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ // Same reason as the scroller above: a toolbar renders per visible doc,+ // so a retained hidden entry can hand back a zero rect.+ const toolbar = Array.from(document.querySelectorAll(toolbarSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!scroller || !toolbar) {+ throw new Error(`missing chrome: scroller=${!!scroller} toolbar=${!!toolbar}`);+ }+ const scrollerBox = scroller.getBoundingClientRect();+ // The same two vars `deriveEditorClipOptions` reads. Reading them here+ // rather than restating the container's raw edge is what makes this+ // assertion the region production clamps into: a clamp that dropped the+ // overlay inset would land a surface over the Ask AI composer's input+ // and still sit inside the container.+ const readRootPx = (name: string): number => {+ const value = Number.parseFloat(document.documentElement.style.getPropertyValue(name));+ return Number.isFinite(value) ? value : 0;+ };+ const overlayBandPx =+ readRootPx('--ask-composer-height') + readRootPx('--conflict-footer-height');+ const regionTop = toolbar.getBoundingClientRect().bottom;+ const regionBottom = scrollerBox.bottom - overlayBandPx;+ const region = {+ regionTop,+ regionBottom,+ scrollerBottom: scrollerBox.bottom,+ overlayBandPx,+ regionLeft: scrollerBox.left,+ regionRight: scrollerBox.right,+ };+ const candidates = Array.from(document.querySelectorAll(surfaceSel)).filter(+ (element): element is HTMLElement => element instanceof HTMLElement,+ );+ const el = candidates.find((element) => element.getClientRects().length > 0) ?? candidates[0];+ if (!el) {+ return { present: false, visible: false, top: 0, bottom: 0, left: 0, right: 0, ...region };+ }+ const box = el.getBoundingClientRect();+ return {+ present: true,+ visible: getComputedStyle(el).visibility !== 'hidden' && el.getClientRects().length > 0,+ top: box.top,+ bottom: box.bottom,+ left: box.left,+ right: box.right,+ ...region,+ };+ },+ { surfaceSel: selector, scrollerSel: SCROLLER, toolbarSel: TOOLBAR },+ );+}++function expectInsideVisibleRegionHorizontally(geometry: SurfaceGeometry, label: string): void {+ const inside =+ geometry.left >= geometry.regionLeft - REGION_TOLERANCE_PX &&+ geometry.right <= geometry.regionRight + REGION_TOLERANCE_PX;+ expect(+ !geometry.visible || inside,+ `${label} escaped the editor's visible content region horizontally: rendered ` ++ `${geometry.left}–${geometry.right}, region ${geometry.regionLeft}–${geometry.regionRight}`,+ ).toBe(true);+}++function expectInsideVisibleRegion(geometry: SurfaceGeometry, label: string): void {+ const inside =+ geometry.top >= geometry.regionTop - REGION_TOLERANCE_PX &&+ geometry.bottom <= geometry.regionBottom + REGION_TOLERANCE_PX;+ expect(+ !geometry.visible || inside,+ `${label} escaped the editor's visible content region: rendered ` ++ `${geometry.top}–${geometry.bottom}, region ${geometry.regionTop}–${geometry.regionBottom}`,+ ).toBe(true);+}++async function openTallDoc(page: Page, api: ApiHelpers, prefix: string): Promise<string> {+ const docName = `${prefix}-${randomUUID().slice(0, 8)}`;+ const { markdown } = generateTallDoc({ blockCount: 300 });+ await api.seedDocs([{ name: docName, markdown }]);+ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();+ return docName;+}++/**+ * Select from the block carrying `fromMarker` through the one carrying+ * `toMarker`. The resulting selection is taller than the pane, which is the+ * amplifier the escape needs: both candidate placements overflow, so `flip`'s+ * `bestFit` keeps the top-side one instead of moving the surface anywhere.+ */+async function selectBlockSpan(page: Page, fromMarker: string, toMarker: string): Promise<void> {+ await page.evaluate(+ ({ a, b }) => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('selectBlockSpan: window.__activeEditor not set');+ let from = -1;+ let to = -1;+ editor.state.doc.descendants((node, pos) => {+ const text = node.isText ? node.text : undefined;+ if (!text) return true;+ const startIndex = text.indexOf(a);+ if (startIndex !== -1 && from === -1) from = pos + startIndex;+ const endIndex = text.indexOf(b);+ if (endIndex !== -1) to = pos + endIndex + b.length;+ return true;+ });+ if (from === -1 || to === -1) throw new Error(`selectBlockSpan: markers not found ${a} ${b}`);+ editor.chain().focus().setTextSelection({ from, to }).run();+ },+ { a: fromMarker, b: toMarker },+ );+ await page.waitForFunction(+ ({ a, b }) => {+ const editor = window.__activeEditor;+ if (!editor) return false;+ const { from, to } = editor.state.selection;+ const text = editor.state.doc.textBetween(from, to);+ return text.startsWith(a) && text.endsWith(b);+ },+ { a: fromMarker, b: toMarker },+ { timeout: 5_000 },+ );+}++/** Select just the marker word of one block — a selection shorter than the pane. */+async function selectSingleMarker(page: Page, marker: string): Promise<void> {+ await page.evaluate((target) => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('selectSingleMarker: window.__activeEditor not set');+ let from = -1;+ editor.state.doc.descendants((node, pos) => {+ if (from !== -1) return false;+ const text = node.isText ? node.text : undefined;+ if (text) {+ const index = text.indexOf(target);+ if (index !== -1) from = pos + index;+ }+ return true;+ });+ if (from === -1) throw new Error(`selectSingleMarker: ${target} not found`);+ editor+ .chain()+ .focus()+ .setTextSelection({ from, to: from + target.length })+ .run();+ }, marker);+ await page.waitForFunction(+ (target) => {+ const editor = window.__activeEditor;+ if (!editor) return false;+ const { from, to } = editor.state.selection;+ return editor.state.doc.textBetween(from, to) === target;+ },+ marker,+ { timeout: 5_000 },+ );+}++/** Yield until layout has settled for the scroll just applied. */+async function nextLayoutFrame(page: Page): Promise<void> {+ await page.evaluate(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ }),+ );+}++/**+ * Scroll the pane until the selection's top edge sits `inset` px below the+ * scroll container's top.+ *+ * A POSITIVE inset parks the selection's start inside the toolbar band, where+ * the user can no longer see where it begins but the container still holds it.+ * A NEGATIVE one parks it above the container entirely — a strictly stronger+ * occlusion, and the state the composer's occluded-anchor case needs.+ *+ * Iterative because moving the scrollport re-lays-out lazily-rendered blocks,+ * which moves the target again; it converges in a handful of passes and stops+ * once the residual is sub-pixel.+ */+async function parkSelectionTopAtPaneInset(page: Page, inset: number): Promise<void> {+ let residual = Number.NaN;+ for (let attempt = 0; attempt < 12; attempt++) {+ residual = await page.evaluate(+ ({ target, scrollerSel }) => {+ const editor = window.__activeEditor;+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ // Throw rather than report a zero residual: 0 is this loop's+ // "converged" value, so a missing editor or scrollport would read as+ // a successful park and surface downstream as a confusing assertion+ // about the selection instead.+ if (!editor) throw new Error('parkSelectionTopAtPaneInset: no active editor');+ if (!scroller) throw new Error('parkSelectionTopAtPaneInset: no painted scrollport');+ const { from } = editor.state.selection;+ const selectionTop = editor.view.coordsAtPos(from).top;+ const delta = selectionTop - (scroller.getBoundingClientRect().top + target);+ scroller.scrollTop += delta;+ return delta;+ },+ { target: inset, scrollerSel: SCROLLER },+ );+ if (Math.abs(residual) < 2) return;+ await nextLayoutFrame(page);+ }+ throw new Error(+ `parkSelectionTopAtPaneInset: selection top still ${residual.toFixed(1)}px from its ` ++ `${inset}px target after 12 passes`,+ );+}++interface SelectionRect {+ top: number;+ height: number;+}++/**+ * The selection's rendered rect, read the same way the surfaces' virtual+ * elements read it. Used to prove the trigger state was actually reached+ * rather than asserted against a selection that never left the visible region.+ */+async function readSelectionRect(page: Page): Promise<SelectionRect> {+ return page.evaluate(() => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('readSelectionRect: window.__activeEditor not set');+ const { from, to } = editor.state.selection;+ const start = editor.view.coordsAtPos(from);+ const end = editor.view.coordsAtPos(to, -1);+ const top = Math.min(start.top, end.top);+ const bottom = Math.max(start.bottom, end.bottom);+ return { top, height: bottom - top };+ });+}++/**+ * Assert the escape's preconditions actually hold: the selection is taller+ * than the visible region (so both candidate placements overflow and `flip` has+ * nowhere good to go), its top edge has scrolled behind the toolbar band (so+ * the top-side placement resolves above the pane), and the surface is on+ * screen — without that last one the contract's "or does not render" arm+ * would satisfy the containment assertion vacuously, and anything that made+ * occlusion detection over-eager would turn these tests from "the bar is+ * contained" into "the bar is absent" while staying green.+ *+ * Asserting visibility is safe precisely because the selection is taller than+ * the region: it is always partially on screen, so `referenceHidden` is false.+ */+async function expectEscapeTriggerReached(+ page: Page,+ geometry: SurfaceGeometry,+ label: string,+): Promise<void> {+ const selection = await readSelectionRect(page);+ const regionHeight = geometry.regionBottom - geometry.regionTop;+ expect(+ selection.height,+ `selection must be taller than the ${regionHeight}px visible region`,+ ).toBeGreaterThan(regionHeight);+ expect(+ selection.top,+ `selection top must sit above the visible region's top (${geometry.regionTop})`,+ ).toBeLessThan(geometry.regionTop);+ expect(+ geometry.visible,+ `${label} must be on screen for the containment arm of the contract to be the one under test`,+ ).toBe(true);+}++/**+ * Wait until the surface's rendered position stops moving across two samples,+ * on both axes — the X-axis tests read `left`/`right` with this as their only+ * gate.+ *+ * Polling the ASSERTION directly would terminate on the first satisfying+ * sample, which can be an intermediate position from part-way through the+ * scroll, and never observe the terminal one. Settling first makes the read+ * deterministic in both the escaping and the corrected case.+ *+ * The poll's own interval is the gap between the two samples — the shape+ * `primeFullLayout` uses — rather than a fixed sleep inside the callback,+ * which would be the busy-wait the E2E stop rules ban.+ */+async function waitForSurfaceSettled(page: Page, testId: string): Promise<void> {+ await waitForFloatingSurfaceSettled(page, `[data-testid="${testId}"]`);+}++/** `waitForSurfaceSettled` against an arbitrary selector. */+async function waitForFloatingSurfaceSettled(page: Page, selector: string): Promise<void> {+ let previous: string | null = null;+ await expect+ .poll(+ async () => {+ const geometry = await readFloatingSurfaceGeometry(page, selector);+ // Both axes: this helper is the only gate before the X-axis tests read+ // `left`/`right`, and Y-stability implies X-stability only while both+ // land in the same assignment block.+ const current =+ `${geometry.present}:${geometry.visible}:` ++ `${Math.round(geometry.top)}:${Math.round(geometry.left)}`;+ const settled = current === previous;+ previous = current;+ return settled;+ },+ { timeout: 10_000, intervals: [200, 200, 400] },+ )+ .toBe(true);+}++/**+ * Make the `<BubbleMenu>` plugin's own positioning pass the last writer, with+ * the component's `autoUpdate` loop provably asleep.+ *+ * tiptap's bubble-menu view re-runs `computePosition` whenever a transaction+ * carries its `updatePosition` meta. A meta-only transaction changes neither+ * the document nor the selection nor any layout, so none of `autoUpdate`'s+ * triggers (ancestor scroll/resize, element resize, layout shift) can fire —+ * leaving the plugin as the only code that can write to the bar.+ *+ * Attribution is what makes that useful, and `top`/`visibility` cannot supply+ * it — both writers set exactly those. `width` can: tiptap stamps+ * `max-content` alongside its coordinates, and the loop never touches width.+ * So the clear pins `width` to the bar's own measured box (identical under+ * `box-sizing: border-box`, so the ResizeObserver stays quiet) and the wait+ * keys on `max-content` coming back, which only the plugin writes.+ *+ * The `visibility: hidden` disjunct is the plugin's early-return branch, but+ * the loop reaches that state too (`BubbleMenuBar` stamps it on+ * `referenceHidden`), so it is a terminal condition rather than an attribution+ * signal — the callers close it by asserting the surface is on screen. The+ * `top === ''` control across the clear window is what catches a loop tick+ * before the dispatch.+ *+ * Returns the coordinate the plugin actually wrote, because attribution ends+ * when the wait resolves and every caller reads its geometry a round trip+ * later. `autoUpdate` can tick in that gap with no scroll or resize: its+ * ResizeObserver unobserves and re-observes the floating element on a frame,+ * and `observe()` delivers an initial entry, so a lazily-materialized chunk+ * resizing `editor.view.dom` produces one. The loop never touches width, so+ * nothing else downstream would notice it had overwritten the plugin.+ */+async function repositionViaPluginPath(page: Page): Promise<PluginWrite> {+ await page.evaluate((barId) => {+ const bar = document.querySelector(`[data-testid="${barId}"]`);+ if (!(bar instanceof HTMLElement)) throw new Error('repositionViaPluginPath: no bubble bar');+ bar.style.top = '';+ bar.style.visibility = '';+ bar.style.width = `${bar.getBoundingClientRect().width}px`;+ }, BUBBLE_BAR);++ await nextLayoutFrame(page);+ expect(+ await page.evaluate((barId) => {+ const bar = document.querySelector(`[data-testid="${barId}"]`);+ return bar instanceof HTMLElement ? bar.style.top : null;+ }, BUBBLE_BAR),+ 'the autoUpdate loop must stay asleep across the clear, or the plugin is not the writer ' ++ 'under test',+ ).toBe('');++ await page.evaluate(() => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('repositionViaPluginPath: window.__activeEditor not set');+ const pluginKey = editor.state.plugins+ .map((plugin) => plugin.key)+ .find((key) => key.startsWith('bubbleMenu'));+ if (!pluginKey) throw new Error('repositionViaPluginPath: bubble-menu plugin not registered');+ editor.view.dispatch(editor.state.tr.setMeta(pluginKey, 'updatePosition'));+ });++ // `expect.poll` rather than `page.waitForFunction`, which carries no message:+ // three paths through tiptap's `updatePosition` write nothing at all (not+ // visible, no virtual element, destroyed/disconnected inside the `.then()`),+ // and any upstream change to the width stamp lands the same way, so the bare+ // form would report every one of them as an unexplained 5 s timeout.+ let written: PluginWrite = { top: null };+ await expect+ .poll(+ async () => {+ written = await page.evaluate((barId) => {+ const bar = document.querySelector(`[data-testid="${barId}"]`);+ if (!(bar instanceof HTMLElement)) return { top: null };+ if (bar.style.visibility === 'hidden') return { top: null, settled: true };+ if (bar.style.width !== 'max-content') return { top: null };+ return { top: bar.getBoundingClientRect().top, settled: true };+ }, BUBBLE_BAR);+ return written.settled === true;+ },+ {+ message:+ "the bubble-menu plugin never wrote: `width: max-content` is tiptap's stamp on its " ++ 'success branch and `visibility: hidden` its occluded one, so neither appearing means ' ++ 'the plugin declined to position (not visible, no virtual element, destroyed) or ' ++ 'stopped stamping width',+ timeout: 5_000,+ },+ )+ .toBe(true);+ return written;+}++/** What the plugin's own positioning pass wrote, or `null` on its hidden branch. */+interface PluginWrite {+ top: number | null;+ settled?: boolean;+}++/**+ * Assert the geometry the caller went on to read is still the plugin's write.+ *+ * Cheap insurance on the round trip between the wait resolving and the read:+ * a loop tick landing there would overwrite the coordinate with nothing else+ * noticing, since the loop never touches width.+ */+function expectGeometryIsThePluginsWrite(+ written: PluginWrite,+ geometry: SurfaceGeometry,+ label: string,+): void {+ if (written.top === null) return;+ expect(+ Math.abs(geometry.top - written.top),+ `${label}: the surface moved from the plugin's ${written.top} to ${geometry.top} between ` ++ `the wait resolving and the geometry read, so the assertions below describe a later writer`,+ ).toBeLessThanOrEqual(1);+}++/**+ * The plugin's pass and the loop's pass must land on the same pixel.+ *+ * The two chains apply the same anchor gap in opposite orders — the loop as+ * `offset -> flip -> shift`, tiptap's plugin as `flip -> shift -> offset` —+ * and `deriveEditorShiftOptions`' `pendingOffsetPx` exists solely to cancel+ * that difference. The order is tiptap's private `middlewares` getter, with no+ * options passthrough and no test of its own upstream, and floating-ui's own+ * guidance is the opposite arrangement. So a tiptap release that "fixed" the+ * order would turn the compensation from a correction into a gap-sized+ * injection: correct in the loop, off by the gap in the plugin, with the bar+ * jittering by that much on every transaction. Containment alone cannot see+ * it — both coordinates stay inside the region — so the agreement is asserted+ * directly.+ */+function expectPluginAgreesWithLoop(+ loop: SurfaceGeometry,+ plugin: SurfaceGeometry,+ label: string,+): void {+ expect(+ Math.abs(plugin.top - loop.top),+ `${label}: tiptap's own positioning pass settled at ${plugin.top} where the autoUpdate ` ++ `loop settled at ${loop.top}. A disagreement of about one anchor gap means the plugin ` ++ `no longer builds its middleware as flip -> shift -> offset, so pendingOffsetPx now ` ++ `injects the delta it was written to absorb.`,+ ).toBeLessThanOrEqual(1);+}++test('bubble bar stays in the pane when a tall selection scrolls behind the toolbar', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar');+ await selectBlockSpan(page, blockMarker(5), blockMarker(80));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await parkSelectionTopAtPaneInset(page, SELECTION_TOP_INSET_PX);+ await waitForSurfaceSettled(page, BUBBLE_BAR);++ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ expect(geometry.present, 'bubble bar still mounted').toBe(true);+ await expectEscapeTriggerReached(page, geometry, 'bubble bar');+ expectInsideVisibleRegion(geometry, 'bubble bar');+});++test('bubble bar stays in the pane when the plugin repositions it on a transaction', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar-plugin');+ await selectBlockSpan(page, blockMarker(5), blockMarker(80));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await parkSelectionTopAtPaneInset(page, SELECTION_TOP_INSET_PX);+ await waitForSurfaceSettled(page, BUBBLE_BAR);+ const fromLoop = await readSurfaceGeometry(page, BUBBLE_BAR);++ const written = await repositionViaPluginPath(page);++ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ expect(geometry.present, 'bubble bar still mounted').toBe(true);+ expectGeometryIsThePluginsWrite(written, geometry, 'bubble bar above a tall selection');+ await expectEscapeTriggerReached(page, geometry, 'bubble bar (plugin pass)');+ expectInsideVisibleRegion(geometry, 'bubble bar (plugin pass)');+ expectPluginAgreesWithLoop(fromLoop, geometry, 'bubble bar above a tall selection');+});++test('comment composer stays in the pane when a tall selection scrolls behind the toolbar', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-composer');+ await selectBlockSpan(page, blockMarker(5), blockMarker(80));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await page.getByTestId('comment-bubble-button').click();+ await expect(page.getByTestId(COMMENT_COMPOSER)).toBeVisible();++ await parkSelectionTopAtPaneInset(page, SELECTION_TOP_INSET_PX);+ await waitForSurfaceSettled(page, COMMENT_COMPOSER);++ const geometry = await readSurfaceGeometry(page, COMMENT_COMPOSER);+ expect(geometry.present, 'comment composer still mounted').toBe(true);+ await expectEscapeTriggerReached(page, geometry, 'comment composer');+ expectInsideVisibleRegion(geometry, 'comment composer');+});++test('bubble bar hides when a short selection scrolls fully behind the toolbar', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar-short');+ await selectSingleMarker(page, blockMarker(40));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await parkSelectionTopAtPaneInset(page, SELECTION_TOP_INSET_PX);+ await waitForSurfaceSettled(page, BUBBLE_BAR);++ // The anchor is fully occluded here, so the contract's "or does not render"+ // arm is the one that must hold. Asserting the surface is hidden — not+ // merely inside the region — is what stops a fix from satisfying the tall+ // cases by clamping the anchor rect, which would keep this bar visible over+ // the pane's chrome with nothing under it.+ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ // Prove the trigger state first. Without it this passes whenever the bar is+ // absent for any reason at all, including a park that overshot and left the+ // anchor somewhere else entirely.+ const selection = await readSelectionRect(page);+ expect(+ selection.top + selection.height,+ `the whole selection must sit above the visible region's top ` ++ `(${geometry.regionTop}) for the "or does not render" arm to be the one under test`,+ ).toBeLessThanOrEqual(geometry.regionTop);+ expect(+ geometry.visible,+ `bubble bar should be hidden for a fully occluded selection; rendered ` ++ `${geometry.top}–${geometry.bottom} in region ${geometry.regionTop}–${geometry.regionBottom}`,+ ).toBe(false);+});++test('comment composer stays put when its captured passage scrolls behind the toolbar', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-composer-occluded');+ await selectSingleMarker(page, blockMarker(40));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await page.getByTestId('comment-bubble-button').click();+ await expect(page.getByTestId(COMMENT_COMPOSER)).toBeVisible();++ await parkSelectionTopAtPaneInset(page, SELECTION_ABOVE_PANE_INSET_PX);+ await waitForSurfaceSettled(page, COMMENT_COMPOSER);++ // The mirror image of the bar's guard above, and a deliberate divergence:+ // the two surfaces share the region producers but not the middleware chain.+ // The bar takes hide() and vanishes with its anchor; this card holds a live+ // draft and owns the caret, so stamping `visibility: hidden` on it would+ // drop focus to <body> mid-sentence. It stays put at the region's edge, and+ // the passage it annotates stays marked in the document. Pinning the choice+ // here keeps it a decision rather than an accident of omission.+ const geometry = await readSurfaceGeometry(page, COMMENT_COMPOSER);+ const selection = await readSelectionRect(page);+ expect(+ selection.top + selection.height,+ `the captured passage must have scrolled clear above the visible region's top ` ++ `(${geometry.regionTop}) for this case to be about an occluded anchor`,+ ).toBeLessThanOrEqual(geometry.regionTop);+ expect(+ geometry.visible,+ 'comment composer must stay on screen while it holds a draft, even with its anchor occluded',+ ).toBe(true);+ expectInsideVisibleRegion(geometry, 'comment composer (occluded anchor)');+});++/**+ * Scroll the pane until the selection's END sits `inset` px above the visible+ * region's floor.+ *+ * This is the mirror of `parkSelectionTopAtPaneInset`, and it reaches the+ * contract's other arm: with the selection's start far above the pane and its+ * end at the region's floor, the bottom-side placement is the one `flip`+ * keeps, and the surface lands below the anchor — over the bottom composer and+ * the status footer rather than inside the region.+ *+ * Constructed rather than inherited. Selecting a range taller than the pane+ * already leaves the head near the pane's bottom, because ProseMirror scrolls+ * it into view; but that resting coordinate comes out of a race between the+ * scroll and the lazily-resolving chunk heights of a virtualized 300-block+ * document, and it settles in one of two places from run to run. Converging on+ * it explicitly makes the trigger identical every time.+ *+ * Iterative for the same reason the top-side helper is: moving the scrollport+ * re-lays-out lazily-rendered blocks, which moves the target again.+ */+async function parkSelectionBottomAtRegionFloor(page: Page, inset: number): Promise<void> {+ let residual = Number.NaN;+ for (let attempt = 0; attempt < 12; attempt++) {+ residual = await page.evaluate(+ ({ target, scrollerSel }) => {+ const editor = window.__activeEditor;+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!editor) throw new Error('parkSelectionBottomAtRegionFloor: no active editor');+ if (!scroller) throw new Error('parkSelectionBottomAtRegionFloor: no painted scrollport');+ // Against the region's floor, not the container's: the Ask AI+ // composer floats over the band between them, so parking the anchor+ // there would put it behind the composer card and make the "the+ // anchor is still visible" precondition false.+ const readRootPx = (name: string): number => {+ const value = Number.parseFloat(document.documentElement.style.getPropertyValue(name));+ return Number.isFinite(value) ? value : 0;+ };+ const overlayBandPx =+ readRootPx('--ask-composer-height') + readRootPx('--conflict-footer-height');+ const regionBottom = scroller.getBoundingClientRect().bottom - overlayBandPx;+ const { to } = editor.state.selection;+ const selectionBottom = editor.view.coordsAtPos(to, -1).bottom;+ const delta = selectionBottom - (regionBottom - target);+ scroller.scrollTop += delta;+ return delta;+ },+ { target: inset, scrollerSel: SCROLLER },+ );+ if (Math.abs(residual) < 2) return;+ await nextLayoutFrame(page);+ }+ throw new Error(+ `parkSelectionBottomAtRegionFloor: selection end still ${residual.toFixed(1)}px from its ` ++ `${inset}px target after 12 passes`,+ );+}++/**+ * Assert the downward escape's preconditions: the region's floor really is+ * inset by a published overlay band, the selection is taller than the visible+ * region (so both candidate placements overflow), its end rests in the+ * region's lower half but still inside it (so the anchor is genuinely on+ * screen rather than behind the composer card, and the bottom-side placement+ * is the one that overflows least), and the surface is on screen — without that last one+ * the contract's "or does not render" arm would satisfy the assertion+ * vacuously.+ */+async function expectBottomEscapeTriggerReached(+ page: Page,+ geometry: SurfaceGeometry,+ label: string,+): Promise<void> {+ const selection = await readSelectionRect(page);+ const regionHeight = geometry.regionBottom - geometry.regionTop;+ const selectionBottom = selection.top + selection.height;+ // Without a published overlay band the region's floor collapses onto the+ // scroll container's own edge, and the downward arm silently degrades into+ // the weaker claim a pre-fix surface already satisfies.+ expect(+ geometry.overlayBandPx,+ `the Ask AI composer must be up for this arm to bite: the region's floor ` ++ `(${geometry.regionBottom}) has to sit above the container's ` ++ `(${geometry.scrollerBottom})`,+ ).toBeGreaterThan(0);+ expect(+ selection.height,+ `selection must be taller than the ${regionHeight}px visible region`,+ ).toBeGreaterThan(regionHeight);+ expect(+ selectionBottom,+ `selection's end must rest in the lower half of the visible region ` ++ `(${geometry.regionTop}–${geometry.regionBottom})`,+ ).toBeGreaterThan(geometry.regionTop + regionHeight / 2);+ expect(+ selectionBottom,+ `selection's end must still be inside the visible region ` ++ `(${geometry.regionTop}–${geometry.regionBottom}), so the anchor is visible`,+ ).toBeLessThanOrEqual(geometry.regionBottom + REGION_TOLERANCE_PX);+ expect(+ geometry.visible,+ `${label} must be on screen for the containment arm of the contract to be the one under test`,+ ).toBe(true);+}++test("bubble bar stays in the pane when a tall selection's end sits at the pane floor", async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar-floor');+ await selectBlockSpan(page, blockMarker(5), blockMarker(80));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await parkSelectionBottomAtRegionFloor(page, SELECTION_BOTTOM_INSET_PX);+ await waitForSurfaceSettled(page, BUBBLE_BAR);++ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ expect(geometry.present, 'bubble bar still mounted').toBe(true);+ await expectBottomEscapeTriggerReached(page, geometry, 'bubble bar (below anchor)');+ expectInsideVisibleRegion(geometry, 'bubble bar (below anchor)');+});++test('bubble bar stays in the pane when the plugin repositions it below the anchor', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar-floor-plugin');+ await selectBlockSpan(page, blockMarker(5), blockMarker(80));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await parkSelectionBottomAtRegionFloor(page, SELECTION_BOTTOM_INSET_PX);+ await waitForSurfaceSettled(page, BUBBLE_BAR);+ const fromLoop = await readSurfaceGeometry(page, BUBBLE_BAR);++ const written = await repositionViaPluginPath(page);++ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ expect(geometry.present, 'bubble bar still mounted').toBe(true);+ expectGeometryIsThePluginsWrite(written, geometry, 'bubble bar below a tall selection');+ await expectBottomEscapeTriggerReached(page, geometry, 'bubble bar (below anchor, plugin pass)');+ expectInsideVisibleRegion(geometry, 'bubble bar (below anchor, plugin pass)');+ expectPluginAgreesWithLoop(fromLoop, geometry, 'bubble bar below a tall selection');+});++test("comment composer stays in the pane when a tall selection's end sits at the pane floor", async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-composer-floor');+ await selectBlockSpan(page, blockMarker(5), blockMarker(80));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await page.getByTestId('comment-bubble-button').click();+ await expect(page.getByTestId(COMMENT_COMPOSER)).toBeVisible();++ await parkSelectionBottomAtRegionFloor(page, SELECTION_BOTTOM_INSET_PX);+ await waitForSurfaceSettled(page, COMMENT_COMPOSER);++ const geometry = await readSurfaceGeometry(page, COMMENT_COMPOSER);+ expect(geometry.present, 'comment composer still mounted').toBe(true);+ await expectBottomEscapeTriggerReached(page, geometry, 'comment composer (below anchor)');+ expectInsideVisibleRegion(geometry, 'comment composer (below anchor)');+});++/**+ * The selection's horizontal extent, read the way the surfaces' virtual+ * elements read it.+ */+async function readSelectionHorizontalRect(page: Page): Promise<{ left: number; right: number }> {+ return page.evaluate(() => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('readSelectionHorizontalRect: window.__activeEditor not set');+ const { from, to } = editor.state.selection;+ const start = editor.view.coordsAtPos(from);+ const end = editor.view.coordsAtPos(to, -1);+ return { left: Math.min(start.left, end.left), right: Math.max(start.right, end.right) };+ });+}++/**+ * The precondition every horizontal case shares: the surface is on screen, and+ * its anchor is itself well inside the pane's side edges — so anything that+ * spills past them does so on the surface's own account, not because the user+ * selected text that was already out of bounds.+ *+ * Says nothing about whether the clamp had anything to do; that is+ * `expectCentredSurfaceWouldOverhang`, which only the centred surfaces can+ * answer.+ */+async function expectAnchorInsideRegionHorizontally(+ page: Page,+ geometry: SurfaceGeometry,+): Promise<void> {+ expect(geometry.visible, 'surface must be on screen for the horizontal arm to bite').toBe(true);+ const anchor = await readSelectionHorizontalRect(page);+ expect(+ anchor.left,+ `anchor's left edge must sit inside the pane (${geometry.regionLeft}–${geometry.regionRight})`,+ ).toBeGreaterThanOrEqual(geometry.regionLeft);+ expect(+ anchor.right,+ `anchor's right edge must sit inside the pane (${geometry.regionLeft}–${geometry.regionRight})`,+ ).toBeLessThanOrEqual(geometry.regionRight);+}++/**+ * Assert the horizontal clamp is actually under test: for a placement centred+ * on its anchor the unclamped left edge is derivable, and it has to overhang+ * the pane for the clamp to have anything to do. Without this the whole arm+ * turns into a no-op the day `--content-max-width` or the pane's side margin+ * moves the prose column far enough inboard, and nothing goes red.+ *+ * Its own assertion rather than a flag on the one above, so a surface that+ * cannot reach the escape — the comment composer, whose `bottom-start` is+ * anchor-aligned rather than centred and which is narrow enough to clear the+ * gutter today — omits a visible call instead of an invisible argument.+ */+async function expectCentredSurfaceWouldOverhang(+ page: Page,+ geometry: SurfaceGeometry,+): Promise<void> {+ const anchor = await readSelectionHorizontalRect(page);+ const unclampedLeft = (anchor.left + anchor.right) / 2 - (geometry.right - geometry.left) / 2;+ expect(+ unclampedLeft,+ `an anchor-centred surface must overhang the pane's left edge (${geometry.regionLeft}) ` ++ `for the clamp to be under test; unclamped left would be ${unclampedLeft}`,+ ).toBeLessThan(geometry.regionLeft);+}++test('bubble bar stays inside the pane when anchored at the text column left margin', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar-x');+ await selectSingleMarker(page, blockMarker(40));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();+ await waitForSurfaceSettled(page, BUBBLE_BAR);++ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ expect(geometry.present, 'bubble bar still mounted').toBe(true);+ await expectAnchorInsideRegionHorizontally(page, geometry);+ await expectCentredSurfaceWouldOverhang(page, geometry);+ expectInsideVisibleRegionHorizontally(geometry, 'bubble bar');+});++test('bubble bar stays inside the pane horizontally when the plugin repositions it', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-bar-x-plugin');+ await selectSingleMarker(page, blockMarker(40));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();+ await waitForSurfaceSettled(page, BUBBLE_BAR);++ const written = await repositionViaPluginPath(page);++ const geometry = await readSurfaceGeometry(page, BUBBLE_BAR);+ expect(geometry.present, 'bubble bar still mounted').toBe(true);+ expectGeometryIsThePluginsWrite(written, geometry, 'bubble bar at the column left margin');+ await expectAnchorInsideRegionHorizontally(page, geometry);+ await expectCentredSurfaceWouldOverhang(page, geometry);+ expectInsideVisibleRegionHorizontally(geometry, 'bubble bar (plugin pass)');+});++test('comment composer stays inside the pane when anchored at the text column left margin', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-composer-x');+ await selectSingleMarker(page, blockMarker(40));+ await expect(page.getByTestId(BUBBLE_BAR)).toBeVisible();++ await page.getByTestId('comment-bubble-button').click();+ await expect(page.getByTestId(COMMENT_COMPOSER)).toBeVisible();+ await waitForSurfaceSettled(page, COMMENT_COMPOSER);++ // The composer is narrow enough to clear the pane's left edge today, so this+ // is a guard rather than a regression: moving the horizontal clamp from the+ // window to the pane must not start pushing it out of the pane instead.+ const geometry = await readSurfaceGeometry(page, COMMENT_COMPOSER);+ expect(geometry.present, 'comment composer still mounted').toBe(true);+ await expectAnchorInsideRegionHorizontally(page, geometry);+ expectInsideVisibleRegionHorizontally(geometry, 'comment composer');+});++/**+ * The same contract at the two remaining editor-anchored floating surfaces:+ * the suggestion picker (slash / wiki-link / tag) and the markdown-lint hover+ * callout. Both are body-appended, `position: fixed`, and anchored to a+ * virtual element built from a position inside the scrolled content, so+ * nothing in the DOM clips them either.+ *+ * They are anchored to a CARET or a text LINE rather than to a whole+ * selection, so they cannot reach the tall-reference amplifier the cases above+ * turn on: `hide()` is never the arm under test and the vertical escape has to+ * be constructed differently. What they share with the bar and the card is the+ * absent boundary — `shift()` clamps against the clipping ancestors, which is+ * the window, not the pane — and that is axis-independent. A ~490 px picker+ * opened past the middle of the prose column, or a callout hovered near the+ * column's right edge, leaves the pane sideways and lands on whatever occupies+ * the rail beside it.+ */++const SUGGESTION_POPUP = '[data-suggestion-popup="slash-command"]';+const LINT_CALLOUT = '.ok-lint-tooltip';++/**+ * The picker's own ceiling on its height (`size()`'s `40vh` cap). Used as the+ * precondition's yardstick rather than the picker's measured height, which the+ * fix is free to shrink: a caret with less than this much room on either side+ * of it cannot host a full-size picker whatever the chain does, so the surface+ * must be clamped, shrunk, or escaping.+ */+const SUGGESTION_MAX_HEIGHT_FRACTION = 0.4;++/** Scroll the pane until the caret's top edge rests at viewport `y`. */+async function parkCaretAtViewportY(page: Page, y: number): Promise<void> {+ let residual = Number.NaN;+ for (let attempt = 0; attempt < 12; attempt++) {+ residual = await page.evaluate(+ ({ target, scrollerSel }) => {+ const editor = window.__activeEditor;+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!editor) throw new Error('parkCaretAtViewportY: no active editor');+ if (!scroller) throw new Error('parkCaretAtViewportY: no painted scrollport');+ const delta = editor.view.coordsAtPos(editor.state.selection.from).top - target;+ scroller.scrollTop += delta;+ return delta;+ },+ { target: y, scrollerSel: SCROLLER },+ );+ if (Math.abs(residual) < 2) return;+ await nextLayoutFrame(page);+ }+ throw new Error(+ `parkCaretAtViewportY: caret still ${residual.toFixed(1)}px from its ${y}px target ` ++ 'after 12 passes',+ );+}++/**+ * Put the caret inside the block carrying `marker`, as far right as it can go+ * while still resting at least `insetPx` inside the pane's right edge.+ *+ * The picker is `*-start`-placed, so its unclamped left edge IS the caret's x:+ * a caret in the right half of the prose column is the whole trigger, and the+ * inset keeps the ANCHOR unambiguously inside the pane so anything that spills+ * past the edge does so on the picker's own account.+ */+async function placeCaretNearPaneRight(page: Page, marker: string, insetPx: number): Promise<void> {+ const placed = await page.evaluate(+ ({ target, inset, scrollerSel }) => {+ const editor = window.__activeEditor;+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!editor) throw new Error('placeCaretNearPaneRight: no active editor');+ if (!scroller) throw new Error('placeCaretNearPaneRight: no painted scrollport');+ const limit = scroller.getBoundingClientRect().right - inset;+ let found = -1;+ editor.state.doc.descendants((node, pos) => {+ if (found !== -1) return false;+ const text = node.isText ? node.text : undefined;+ if (text?.includes(target)) found = pos;+ return true;+ });+ if (found === -1) throw new Error(`placeCaretNearPaneRight: ${target} not found`);+ // The marker is its own short text node at the block's head, so scanning+ // it alone would never reach the right half of the column. Widen to the+ // whole top-level block the marker sits in.+ const resolved = editor.state.doc.resolve(found);+ const start = resolved.before(1) + 1;+ const end = resolved.after(1) - 1;+ let best = start;+ let bestLeft = Number.NEGATIVE_INFINITY;+ for (let pos = start; pos <= end; pos++) {+ const { left } = editor.view.coordsAtPos(pos);+ if (left <= limit && left > bestLeft) {+ bestLeft = left;+ best = pos;+ }+ }+ editor.chain().focus().setTextSelection(best).run();+ return bestLeft;+ },+ { target: marker, inset: insetPx, scrollerSel: SCROLLER },+ );+ expect(placed, `no caret position in ${marker} sits inside the pane`).toBeGreaterThan(0);+}++/**+ * Type the suggestion trigger and wait for the picker to settle.+ *+ * The leading space is load-bearing: the plugin's `allowedPrefixes` accepts the+ * trigger only after whitespace or at a block start, so a bare `/` typed+ * mid-word never opens anything and the test would fail on setup.+ */+async function openSuggestionPicker(page: Page): Promise<void> {+ await page.keyboard.type(' /');+ await page.locator(SUGGESTION_POPUP).waitFor({ state: 'visible', timeout: 10_000 });+ await waitForFloatingSurfaceSettled(page, SUGGESTION_POPUP);+}++/** The caret's rect, read the way the picker's virtual element reads it. */+async function readCaretRect(page: Page): Promise<{ top: number; bottom: number; left: number }> {+ return page.evaluate(() => {+ const editor = window.__activeEditor;+ if (!editor) throw new Error('readCaretRect: window.__activeEditor not set');+ const coords = editor.view.coordsAtPos(editor.state.selection.from);+ return { top: coords.top, bottom: coords.bottom, left: coords.left };+ });+}++test('suggestion picker stays inside the pane when opened past the middle of a line', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-suggest-x');+ // Bring the block on screen before measuring anything in it: a chunk the+ // scrollport has never reached is content-visibility-skipped, and+ // `coordsAtPos` inside one reports the placeholder's geometry.+ await selectSingleMarker(page, blockMarker(40));+ const region = await readFloatingSurfaceGeometry(page, SUGGESTION_POPUP);+ // High in the pane, so there is ample room below the caret and the vertical+ // arm cannot confound this one.+ await parkCaretAtViewportY(page, region.regionTop + 40);+ // Short of the line's end: the trigger characters reflow the text, and a+ // caret parked at the wrap point would ride the pushed word onto the next+ // line and lose the right-hand anchor this case is about.+ await placeCaretNearPaneRight(page, blockMarker(40), 200);+ await openSuggestionPicker(page);++ const geometry = await readFloatingSurfaceGeometry(page, SUGGESTION_POPUP);+ expect(geometry.present, 'suggestion picker still mounted').toBe(true);+ expect(geometry.visible, 'suggestion picker must be on screen for containment to be tested').toBe(+ true,+ );++ // The clamp is under test only if the unclamped placement would overhang.+ // A `*-start` picker's unclamped left edge is the caret's own x, so its+ // right edge is that plus the picker's width.+ const caret = await readCaretRect(page);+ expect(+ caret.left,+ `caret must sit inside the pane (${geometry.regionLeft}–${geometry.regionRight})`,+ ).toBeLessThan(geometry.regionRight);+ expect(+ caret.left + (geometry.right - geometry.left),+ `an anchor-aligned picker must overhang the pane's right edge (${geometry.regionRight}) ` ++ 'for the clamp to be under test',+ ).toBeGreaterThan(geometry.regionRight);++ expectInsideVisibleRegionHorizontally(geometry, 'suggestion picker');+});++test('suggestion picker stays inside the pane when the caret sits mid-pane', async ({+ page,+ api,+}) => {+ await openTallDoc(page, api, 'clip-suggest-y');+ await selectSingleMarker(page, blockMarker(40));+ await placeCaretNearPaneRight(page, blockMarker(40), 400);++ const region = await readFloatingSurfaceGeometry(page, SUGGESTION_POPUP);+ await parkCaretAtViewportY(page, (region.regionTop + region.regionBottom) / 2);+ await openSuggestionPicker(page);++ const geometry = await readFloatingSurfaceGeometry(page, SUGGESTION_POPUP);+ expect(geometry.present, 'suggestion picker still mounted').toBe(true);+ expect(geometry.visible, 'suggestion picker must be on screen for containment to be tested').toBe(+ true,+ );+ // A picker shrunk to nothing would satisfy containment for the wrong reason.+ expect(+ geometry.bottom - geometry.top,+ 'suggestion picker must keep a usable height',+ ).toBeGreaterThan(60);++ // Neither side of the caret has room for a full-height picker, so whatever+ // the chain does it cannot simply place one and walk away. Stated against+ // `size()`'s own ceiling rather than the picker's measured height, which a+ // fix is free to shrink.+ const caret = await readCaretRect(page);+ const ceiling = (await page.evaluate(() => window.innerHeight)) * SUGGESTION_MAX_HEIGHT_FRACTION;+ expect(+ geometry.regionBottom - caret.bottom,+ `room below the caret must be under the picker's ${ceiling}px ceiling for the clamp ` ++ 'to be under test',+ ).toBeLessThan(ceiling);+ expect(+ caret.top - geometry.regionTop,+ `room above the caret must be under the picker's ${ceiling}px ceiling for the clamp ` ++ 'to be under test',+ ).toBeLessThan(ceiling);++ expectInsideVisibleRegion(geometry, 'suggestion picker');+});++/**+ * The markdown-lint hover callout. Opt-in per project, so these enable the+ * plugin for the worker's content dir and hand it back afterwards — the same+ * arrangement `markdown-lint.e2e.ts` uses, and the reason they sit in their own+ * describe at the end of the file rather than beside the cases above.+ */+test.describe('markdown-lint hover callout', () => {+ // A hard tab mid-sentence trips MD010 without turning the line into an+ // indented code block, and the paragraph is long enough to wrap so a pointer+ // can rest near either the left or the right edge of the prose column.+ const LINT_PARAGRAPH =+ 'A wrapping paragraph with\ta hard tab in the middle of it, long enough that it spans ' ++ 'more than one visual line in the editor so a pointer can rest anywhere along its width.';++ test.beforeEach(({ workerServer }) => {+ mkdirSync(join(workerServer.contentDir, '.ok'), { recursive: true });+ writeFileSync(+ join(workerServer.contentDir, '.ok', 'config.yml'),+ 'contentRules:\n markdownlint:\n enabled: true\n',+ 'utf-8',+ );+ });++ test.afterAll(({ workerServer }) => {+ writeFileSync(join(workerServer.contentDir, '.ok', 'config.yml'), '', 'utf-8');+ });++ async function openLintDoc(page: Page, api: ApiHelpers, prefix: string): Promise<void> {+ const docName = `${prefix}-${randomUUID().slice(0, 8)}`;+ // Plain paragraphs, deliberately not `1.`-prefixed: an ordered list is ONE+ // top-level block, so every violation in the document would collapse into a+ // single decoration whose callout lists all sixty.+ const body = Array.from(+ { length: 60 },+ (_, index) => `Block ${index} — ${LINT_PARAGRAPH}`,+ ).join('\n\n');+ await api.seedDocs([{ name: docName, markdown: body }]);+ await page.goto(`/#/${docName}`);+ await waitForActiveProviderSynced(page);+ await expect(page.locator(WYSIWYG).first()).toBeVisible();+ await expect(page.locator(`${WYSIWYG} .ok-lint-block`).first()).toBeVisible({+ timeout: 20_000,+ });+ }++ /**+ * The painted lint block nearest `targetTop`, after scrolling one into place.+ * Returns its box so the caller can aim the pointer at a known line.+ */+ async function scrollLintBlockTo(+ page: Page,+ targetTop: number,+ ): Promise<{ top: number; bottom: number; left: number; right: number }> {+ let residual = Number.NaN;+ for (let attempt = 0; attempt < 12; attempt++) {+ residual = await page.evaluate(+ ({ target, scrollerSel, wysiwygSel }) => {+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!scroller) throw new Error('scrollLintBlockTo: no painted scrollport');+ const blocks = Array.from(+ document.querySelectorAll<HTMLElement>(`${wysiwygSel} .ok-lint-block`),+ );+ if (blocks.length === 0) throw new Error('scrollLintBlockTo: no lint blocks painted');+ const nearest = blocks.reduce((best, block) =>+ Math.abs(block.getBoundingClientRect().top - target) <+ Math.abs(best.getBoundingClientRect().top - target)+ ? block+ : best,+ );+ const delta = nearest.getBoundingClientRect().top - target;+ scroller.scrollTop += delta;+ return delta;+ },+ { target: targetTop, scrollerSel: SCROLLER, wysiwygSel: WYSIWYG },+ );+ if (Math.abs(residual) < 2) break;+ await nextLayoutFrame(page);+ }+ await waitForScrollSettled(page);+ return page.evaluate(+ ({ target, wysiwygSel }) => {+ const blocks = Array.from(+ document.querySelectorAll<HTMLElement>(`${wysiwygSel} .ok-lint-block`),+ );+ const nearest = blocks.reduce((best, block) =>+ Math.abs(block.getBoundingClientRect().top - target) <+ Math.abs(best.getBoundingClientRect().top - target)+ ? block+ : best,+ );+ const box = nearest.getBoundingClientRect();+ return { top: box.top, bottom: box.bottom, left: box.left, right: box.right };+ },+ { target: targetTop, wysiwygSel: WYSIWYG },+ );+ }++ /**+ * Hold until the scrollport stops moving on its own.+ *+ * Chromium answers a programmatic `scrollTop` write with a scroll correction+ * of its own a frame or two later. Hovering before that lands moves the text+ * out from under a stationary pointer, which reads as a pointer-leave and+ * retires the callout ~140 ms into the measurement — the callout is raised,+ * then silently gone by the time its geometry is read.+ */+ async function waitForScrollSettled(page: Page): Promise<void> {+ let previous: number | null = null;+ await expect+ .poll(+ async () => {+ const current = await page.evaluate((scrollerSel) => {+ const scroller = Array.from(document.querySelectorAll(scrollerSel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ return scroller ? scroller.scrollTop : Number.NaN;+ }, SCROLLER);+ const settled = previous !== null && Math.abs(current - previous) < 0.5;+ previous = current;+ return settled;+ },+ { timeout: 10_000, intervals: [200, 200, 400] },+ )+ .toBe(true);+ }++ /** Rest the pointer on a lint block and wait for its callout to settle. */+ async function hoverLintBlock(page: Page, x: number, y: number): Promise<void> {+ await page.mouse.move(x, y);+ await expect(page.locator(`${LINT_CALLOUT}:visible`)).not.toHaveCount(0);+ // The callout is appended at 0,0 and moved by an async `computePosition`,+ // so a settle poll alone could sample that initial coordinate twice.+ await expect+ .poll(async () => {+ const geometry = await readFloatingSurfaceGeometry(page, LINT_CALLOUT);+ return geometry.top !== 0 || geometry.left !== 0;+ })+ .toBe(true);+ await waitForFloatingSurfaceSettled(page, LINT_CALLOUT);+ }++ test('hover callout stays inside the pane when its line rests below the toolbar band', async ({+ page,+ api,+ }) => {+ await openLintDoc(page, api, 'clip-lint-y');+ const region = await readFloatingSurfaceGeometry(page, LINT_CALLOUT);+ const block = await scrollLintBlockTo(page, region.regionTop + 4);+ await hoverLintBlock(page, block.left + 40, block.top + 8);++ const geometry = await readFloatingSurfaceGeometry(page, LINT_CALLOUT);+ expect(geometry.present, 'hover callout still mounted').toBe(true);+ expect(geometry.visible, 'hover callout must be on screen for containment to be tested').toBe(+ true,+ );+ // The callout is `top-start`-placed, so it escapes only if the hovered line+ // has less clearance above it than the callout is tall.+ expect(+ block.top - geometry.regionTop,+ `the hovered line must sit within one callout height (${geometry.bottom - geometry.top}px) ` ++ `of the visible region's top (${geometry.regionTop}) for the clamp to be under test`,+ ).toBeLessThan(geometry.bottom - geometry.top);++ expectInsideVisibleRegion(geometry, 'hover callout');+ });++ test('hover callout stays inside the pane when hovered near the column right edge', async ({+ page,+ api,+ }) => {+ await openLintDoc(page, api, 'clip-lint-x');+ const region = await readFloatingSurfaceGeometry(page, LINT_CALLOUT);+ const block = await scrollLintBlockTo(page, (region.regionTop + region.regionBottom) / 2);+ const pointerX = block.right - 8;+ await hoverLintBlock(page, pointerX, block.top + 8);++ const geometry = await readFloatingSurfaceGeometry(page, LINT_CALLOUT);+ expect(geometry.present, 'hover callout still mounted').toBe(true);+ expect(geometry.visible, 'hover callout must be on screen for containment to be tested').toBe(+ true,+ );+ // The callout anchors to the pointer's x and is `*-start`-placed, so its+ // unclamped left edge is that x.+ expect(+ pointerX,+ `the pointer must rest inside the pane (${geometry.regionLeft}–${geometry.regionRight})`,+ ).toBeLessThan(geometry.regionRight);+ expect(+ pointerX + (geometry.right - geometry.left),+ `the callout must overhang the pane's right edge (${geometry.regionRight}) for the clamp ` ++ 'to be under test',+ ).toBeGreaterThan(geometry.regionRight);++ expectInsideVisibleRegionHorizontally(geometry, 'hover callout');+ });+});diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex dfd95ef49..d7a845280 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,4 +1,3 @@-import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 8bfdb40cd..005627195 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,4 +1,3 @@-import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.tsindex d979f4b39..6b505314d 100644--- a/packages/core/src/bridge/divergence-locate.ts+++ b/packages/core/src/bridge/divergence-locate.ts@@ -1,4 +1,3 @@-import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';export const BRIDGE_LINE_KINDS = [diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 01ef76a9f..8fb428b90 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 463e89595..9d9c244b0 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,4 +1,3 @@-const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex 0939885bb..c43fdd7e7 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,4 +1,3 @@-export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex c0dc65705..251560a35 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,7 +65,6 @@ export function tryLineLevelCombine(return { clean: true, merged };}-export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex dcc5b0690..01ac80099 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,4 +1,3 @@-import { stripFrontmatter } from '../extensions/frontmatter.ts';import { bodyEdgeEmpties } from './doc-boundary-space.ts';diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 0be5203e4..754dc5cc2 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;-interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}-/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}-export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex dca644141..af20de1e2 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,4 +1,3 @@-/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex a363dfd54..83d47404a 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,4 +1,3 @@-import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 4499dbc92..9807a7e82 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,4 +1,3 @@-export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 34704165b..7415c474a 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex b6299a948..ece5c02a1 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,4 +1,3 @@-import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex acd398aa6..54774764a 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex ba9b56384..43ecdc709 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 4513da9bb..6d3f3643e 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,4 +1,3 @@-const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 6931623c7..00f5771ee 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}-interface GfmExample {section: string;markdown: string;@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}-interface MdxCrashEntry {id: string;input: string;@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}-export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}-export interface NgPinnedCase {id: string;name: string;@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}-export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex daa3ef82b..8b1eb8519 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;-function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}-const WORDS = ['lorem','ipsum',@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}-type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}-function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 32c055c5b..420dc0fe5 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,7 +7,6 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';-export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 283913255..2653473da 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,4 +1,3 @@-export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex 5d1000cc4..da0a81d23 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 9681c0056..787315157 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,4 +1,3 @@-import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -129,8 +128,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified()- .use(rehypeParse, { fragment: true });+ const processor = unified().use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 994eb6917..706fa9afb 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,4 +1,3 @@-import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex ec1ac1b7e..779e27500 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromPmMark,@@ -207,7 +206,6 @@ export class MarkdownManager {}}-const registry = createRegistry();function destructureAttrs(@@ -256,7 +254,6 @@ function destructureAttrs(return result;}-function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -279,7 +276,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}-function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}-import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(}));}-if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(}));}-if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(};}-const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}-function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex b79e9aef7..fa0be9e86 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,4 +1,3 @@-import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 94b34dee1..312c9c74b 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,4 +1,3 @@-const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex fbbd309df..1a81aa524 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -52,7 +52,6 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;-export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex a51f2ffb0..d48eea5e4 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};-export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex 9c9542661..ef478e268 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,4 +1,3 @@-import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex b0e7833fd..5f953d667 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,4 +1,3 @@-import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex ffd277a90..11b5abdfd 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,4 +1,3 @@-import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.tsindex f438f1b16..7a5af097e 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts@@ -1,4 +1,3 @@-import type { OkfRuleId } from '../okf-rule-meta.ts';import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.tsindex c290b6878..1ee913527 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts@@ -1,4 +1,3 @@-import type { OkfRuleId } from '../okf-rule-meta.ts';export const OKF_SCHEMA_DIR = '.ok/okf';diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.tsindex 53ecb619d..f325fbbb4 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts@@ -1,4 +1,3 @@-import { compileAppliesTo } from '../applies-to.ts';import { validateFrontmatterSource } from '../frontmatter-validate.ts';import {diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.tsindex 89845d3d5..f1c37671b 100644--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts@@ -1,4 +1,3 @@-// file-level form is deliberate: the sibling `biome-ignore` must sit on the line// oxlint-disable unicorn/no-thenablediff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.tsindex 8b476332e..6d691ae2b 100644--- a/packages/core/src/markdown/lint/okf-project/rules.ts+++ b/packages/core/src/markdown/lint/okf-project/rules.ts@@ -1,4 +1,3 @@-import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.tsindex 44913a9dc..4de50d79f 100644--- a/packages/core/src/markdown/lint/okf-rule-meta.ts+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts@@ -1,4 +1,3 @@-export const OKF_RULE_IDS = ['no-wiki-links','log-shape',diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.tsindex d0999b62e..1d5538421 100644--- a/packages/core/src/markdown/lint/okf-rules.ts+++ b/packages/core/src/markdown/lint/okf-rules.ts@@ -1,4 +1,3 @@-import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';import type { OkfRule } from './okf-runner.ts';import { indexShape } from './rules/index-shape.ts';diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.tsindex fabb08d6e..de130e3f4 100644--- a/packages/core/src/markdown/lint/okf-runner.ts+++ b/packages/core/src/markdown/lint/okf-runner.ts@@ -1,4 +1,3 @@-import type { Root } from 'mdast';import remarkFrontmatter from 'remark-frontmatter';import remarkGfm from 'remark-gfm';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 0a089990e..09c8450ee 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,4 +1,3 @@-import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -24,7 +23,6 @@ import {type OkfSlice,} from './types.ts';-const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.tsindex fcbb1b56c..59fe9b87d 100644--- a/packages/core/src/markdown/lint/rules/index-shape.ts+++ b/packages/core/src/markdown/lint/rules/index-shape.ts@@ -1,4 +1,3 @@-import type { List, ListItem } from 'mdast';import { EXIT, visit } from 'unist-util-visit';import { defineScopedOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.tsindex 431e4e9c8..e0159519f 100644--- a/packages/core/src/markdown/lint/rules/log-shape.ts+++ b/packages/core/src/markdown/lint/rules/log-shape.ts@@ -1,4 +1,3 @@-import type { Heading } from 'mdast';import { toString as headingText } from 'mdast-util-to-string';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.tsindex f75a04d15..2123e977f 100644--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts@@ -1,4 +1,3 @@-import type { Point } from 'unist';import { visit } from 'unist-util-visit';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.tsindex c8b4d8f28..89ef3e4a9 100644--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts@@ -1,4 +1,3 @@-import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';import { defineOkfRule } from '../okf-runner.ts';diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex c04fa4de0..6836b962d 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,4 +1,3 @@-import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';import type { OkfRuleId } from './okf-rule-meta.ts';@@ -113,7 +112,6 @@ export interface OkfSlice {generate?: { index?: boolean };}-interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 437cc539a..98238656e 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,4 +1,3 @@-export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex bd79424c7..a5b511f25 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 00fbc0035..ed89371d0 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex df788a80d..8ce2b2492 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,4 +1,3 @@-import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 17ed2b829..1a897fca8 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,4 +1,3 @@-import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 4aa0490c4..d988f4b8b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,7 +168,6 @@ export function parseRecursive(}}-interface VFilePlace {offset?: number;start?: { offset?: number };@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}-interface Region {start: number;end: number;@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}-export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}-interface SourceBlock {src: string;start: number;@@ -456,7 +452,6 @@ function tryPerBlockFallback(};}-function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex 43d420187..e6ab4fd57 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,4 +1,3 @@-export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 55736041c..0e3224206 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,4 +1,3 @@-import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex ccf06e94d..91cdf658f 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,4 +1,3 @@-import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex e5b4c9eba..0f399d34c 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,4 +1,3 @@-import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- }- else if (first === '[') {+ } else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex ca225ce9b..db10fa54b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,4 +1,3 @@-import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 3a2524a9a..34068d103 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 2279a0189..93151d43b 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex a0f467c42..188f02d83 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4e8542a21..4ba2c3418 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex a3c96b24a..1a74b1272 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex e95cf43d6..de35e7b79 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,4 +1,3 @@-import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex ffdb4d5b5..b4be1b2ea 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,4 +1,3 @@-import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex e2a96d1a7..3c8d88b7c 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,4 +1,3 @@-import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex 0389575ac..cf2c9da8e 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,4 +1,3 @@-import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 96304e7a5..0dd54070e 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,4 +1,3 @@-import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 93798cf83..7cac5b042 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,4 +1,3 @@-import type { Node as PmNode } from '@tiptap/pm/model';import type {MdxJsxAttribute,diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex 8c08b7a04..b012a5aff 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,4 +1,3 @@-import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 959cc0bd2..3e79f8cb6 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,4 +1,3 @@-import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 6e6d73400..0f1b0f27d 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 932d7d2a8..1a082bda7 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,4 +1,3 @@-import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex ac9f5239b..d578476a7 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,4 +1,3 @@-const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex afd9936fe..6dad26200 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {}}-const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {};}-function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};-const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {