Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): keep the suggestion picker inside the editor pane (PRD-7166) (#3863)
Andrew Mikofalvy8cb0b4a48643
diff --git a/.changeset/olive-donkeys-shake.md b/.changeset/olive-donkeys-shake.mdnew file mode 100644index 000000000..51b9b56d4--- /dev/null+++ b/.changeset/olive-donkeys-shake.md@@ -0,0 +1,7 @@+---+'@inkeep/open-knowledge': patch+---++Keep the slash and wiki-link suggestion picker inside the editor pane++The picker is two fixed columns — a list beside a preview — about 490px wide, so a pane narrowed by a docked terminal or agents rail could not hold it and it painted over the dock, the same escape the formatting bar and comment composer were just fixed for. The picker now caps its width to the pane, and drops the preview column when the pane cannot hold both rather than squeezing each into something unreadable.diff --git a/packages/app/src/editor/extensions/suggestion-floating-ui.ts b/packages/app/src/editor/extensions/suggestion-floating-ui.tsindex 4a31ae9e2..8d61465db 100644--- a/packages/app/src/editor/extensions/suggestion-floating-ui.ts+++ b/packages/app/src/editor/extensions/suggestion-floating-ui.ts@@ -1,9 +1,12 @@+import type { MiddlewareState } from '@floating-ui/dom';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,+ deriveEditorSizeOptions,+ editorRegionWidthPx,} from '@/editor/utils/editor-visible-region';export interface SuggestionPositionState {@@ -64,6 +67,17 @@ export function suggestionHasSelectableItem(view: object): boolean {* ideal placement, caps the list at the room actually available beside the* anchor, and leaves the clamp with nothing to do.*/+/**+ * Width below which the picker drops to one column.+ *+ * The slash menu is a `w-56` list beside a `w-64` preview with a `gap-2`+ * between them — 488px of fixed columns. A pane that cannot hold both squeezes+ * BOTH, and a half-width list beside a sliver of preview reads worse than the+ * list alone. The preview is `aria-hidden` decoration, so dropping it costs+ * nothing a screen reader was getting.+ */+const SUGGESTION_TWO_COLUMN_MIN_PX = 488;+function buildMiddleware(popup: HTMLDivElement, editor: Editor | undefined) {const applySize = {apply({ availableHeight }: { availableHeight: number }) {@@ -88,14 +102,47 @@ function buildMiddleware(popup: HTMLDivElement, editor: Editor | undefined) {];}const clipOptions = deriveEditorClipOptions(editor);+ const capWidth = deriveEditorSizeOptions(editor);return [offset(SUGGESTION_ANCHOR_GAP_PX),flip(clipOptions),- size(() => ({ ...clipOptions(), ...applySize })),+ // The width cap rides the EXISTING `size` rather than a second one, and+ // this call keeps its place BEFORE the clamp. That position is load-bearing+ // for the height half above (see this function's docstring) and the cap is+ // indifferent to it: `deriveEditorSizeOptions` measures the region instead+ // of reading floating-ui's position-dependent `availableWidth`, so it is+ // correct wherever in the chain it runs.+ size(() => {+ const { apply: applyWidthCap } = capWidth();+ return {+ ...clipOptions(),+ apply(state: MiddlewareState & { availableHeight: number }) {+ applyWidthCap(state);+ applySize.apply(state);+ applyColumnCount(popup, editor);+ },+ };+ }),shift(deriveEditorShiftOptions(editor)),];}+/**+ * Mark the popup one-column when the region cannot hold both of its columns.+ *+ * A `data-` attribute plus a CSS rule rather than React state: the menus are+ * rendered into this popup by three different components, the decision is a+ * pure function of a width this positioning pass already measured, and routing+ * it back through React would re-render the list on every scroll tick. No+ * resolvable region leaves the attribute alone — same fallback as the cap.+ */+function applyColumnCount(popup: HTMLDivElement, editor: Editor): void {+ if (!popup.isConnected) return;+ const regionWidth = editorRegionWidthPx(editor);+ if (regionWidth === null) return;+ popup.toggleAttribute('data-suggestion-narrow', regionWidth < SUGGESTION_TWO_COLUMN_MIN_PX);+}+/*** Create a positioned suggestion popup element and its positioning helpers.* Shared by slash-command and wiki-link suggestion menus.diff --git a/packages/app/src/editor/slash-command/SlashCommandMenu.tsx b/packages/app/src/editor/slash-command/SlashCommandMenu.tsxindex f82cfa3f2..82cc79874 100644--- a/packages/app/src/editor/slash-command/SlashCommandMenu.tsx+++ b/packages/app/src/editor/slash-command/SlashCommandMenu.tsx@@ -150,7 +150,12 @@ export function SlashCommandMenu({<asidearia-hidden="true"onMouseDown={preventFocusSteal}- className={`w-64 rounded-lg border bg-popover p-2 shadow-md ${+ // `ok-suggestion-preview` is the hook the positioning pass hides this+ // column by when the editor pane cannot hold both columns — see+ // `suggestion-floating-ui.ts`. Hidden in CSS rather than unrendered+ // here because the width that decides it is measured per+ // `computePosition` pass, outside React.+ className={`ok-suggestion-preview w-64 rounded-lg border bg-popover p-2 shadow-md ${selectedItem?.preview ? '' : 'invisible'}`}>diff --git a/packages/app/src/editor/tag-suggestion/TagSuggestionMenu.tsx b/packages/app/src/editor/tag-suggestion/TagSuggestionMenu.tsxindex febb28533..d1b80e72c 100644--- a/packages/app/src/editor/tag-suggestion/TagSuggestionMenu.tsx+++ b/packages/app/src/editor/tag-suggestion/TagSuggestionMenu.tsx@@ -91,7 +91,7 @@ export function TagSuggestionMenu({ref={containerRef}role="status"aria-live="polite"- className="w-64 rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"+ className="w-64 max-w-full rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"style={{ maxHeight: 'var(--suggestion-menu-max-height, 40vh)' }}onMouseDown={preventFocusSteal}>@@ -113,7 +113,7 @@ export function TagSuggestionMenu({ref={containerRef}role="status"aria-live="polite"- className="w-64 rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"+ className="w-64 max-w-full rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"style={{ maxHeight: 'var(--suggestion-menu-max-height, 40vh)' }}onMouseDown={preventFocusSteal}>@@ -133,7 +133,7 @@ export function TagSuggestionMenu({aria-activedescendant={activeDescendant}tabIndex={-1}onMouseDown={preventFocusSteal}- className="w-64 overflow-y-auto subtle-scrollbar rounded-lg border bg-popover p-1 shadow-md"+ className="w-64 max-w-full overflow-y-auto subtle-scrollbar rounded-lg border bg-popover p-1 shadow-md"style={{ maxHeight: 'var(--suggestion-menu-max-height, 40vh)' }}>{/* Live region announces the selected item on arrow navigation —diff --git a/packages/app/src/editor/utils/editor-visible-region.ts b/packages/app/src/editor/utils/editor-visible-region.tsindex 885badd68..cab06b037 100644--- a/packages/app/src/editor/utils/editor-visible-region.ts+++ b/packages/app/src/editor/utils/editor-visible-region.ts@@ -236,12 +236,11 @@ export function deriveEditorSizeOptions(): () => EditorSizeOptions {return () => ({apply({ elements }) {- const boundary = resolveRegionBoundary(editor);- if (!boundary) {+ const regionWidth = editorRegionWidthPx(editor);+ if (regionWidth === null) {elements.floating.style.maxWidth = '';return;}- const regionWidth = Math.max(0, boundary.getBoundingClientRect().width - PANE_GUTTER_PX * 2);elements.floating.style.maxWidth = authorMaxWidth? `min(${authorMaxWidth}, ${regionWidth}px)`: `${regionWidth}px`;@@ -249,6 +248,26 @@ export function deriveEditorSizeOptions(});}+/**+ * The width a surface may occupy inside the region — the number+ * `deriveEditorSizeOptions` caps to, exposed for the one caller that has to+ * decide something other than a `max-width` from it.+ *+ * The suggestion picker is that caller: it is two columns, and squeezing both+ * into a pane that fits neither reads worse than dropping the decorative one.+ * Deciding that needs the measurement itself, not the style the producer+ * writes — and re-measuring at the call site would be a second definition of+ * the region free to drift from this one.+ *+ * `null` when no region resolves, matching the producer's own fallback: the+ * caller has no basis for a width-conditional decision either.+ */+export function editorRegionWidthPx(editor: Editor): number | null {+ const boundary = resolveRegionBoundary(editor);+ if (!boundary) return null;+ return Math.max(0, boundary.getBoundingClientRect().width - PANE_GUTTER_PX * 2);+}+/*** Both overlay heights are published as inline styles on the document root* (BottomComposer and use-conflict-footer-height.ts), so read the inlinediff --git a/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx b/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsxindex 80087034b..1107dc624 100644--- a/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx+++ b/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.tsx@@ -97,7 +97,7 @@ export function WikiLinkSuggestionMenu({ref={containerRef}role="status"aria-live="polite"- className="w-80 max-w-[min(28rem,90vw)] rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"+ className="w-80 max-w-[min(28rem,90vw,100%)] rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"style={{ maxHeight: 'var(--suggestion-menu-max-height, 40vh)' }}onMouseDown={preventFocusSteal}>@@ -124,7 +124,7 @@ export function WikiLinkSuggestionMenu({ref={containerRef}role="status"aria-live="polite"- className="w-80 max-w-[min(28rem,90vw)] rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"+ className="w-80 max-w-[min(28rem,90vw,100%)] rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground"style={{ maxHeight: 'var(--suggestion-menu-max-height, 40vh)' }}onMouseDown={preventFocusSteal}>@@ -144,7 +144,7 @@ export function WikiLinkSuggestionMenu({aria-activedescendant={activeDescendant}tabIndex={-1}onMouseDown={preventFocusSteal}- className="w-80 max-w-[min(28rem,90vw)] overflow-y-auto subtle-scrollbar rounded-lg border bg-popover p-1 shadow-md"+ className="w-80 max-w-[min(28rem,90vw,100%)] overflow-y-auto subtle-scrollbar rounded-lg border bg-popover p-1 shadow-md"style={{ maxHeight: 'var(--suggestion-menu-max-height, 40vh)' }}>{/*diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 6408fcd3f..2b4887305 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -5719,6 +5719,17 @@ html.electron-mode [data-slot="sidebar-inner"] {be clickable and the enter/leave handlers keep the box alive while thepointer travels to it, so it also swallows clicks on the region it covers(the line above the hovered one). Any keypress retires it. */+/* One-column suggestion picker.++ `suggestion-floating-ui.ts` sets `data-suggestion-narrow` on the popup when+ the editor's visible region cannot hold the list AND the preview beside it.+ Squeezing both columns into a pane that fits neither reads worse than the+ list alone, and the preview is `aria-hidden` decoration, so it is the column+ that gives way. */+[data-suggestion-popup][data-suggestion-narrow] .ok-suggestion-preview {+ display: none;+}+.ok-lint-tooltip {position: absolute;z-index: 50;diff --git a/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts b/packages/app/tests/stress/selection-surface-pane-clip.e2e.tsindex 2250a72c9..9f4a0a3c4 100644--- a/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts+++ b/packages/app/tests/stress/selection-surface-pane-clip.e2e.ts@@ -1302,7 +1302,8 @@ test('comment composer stays inside a pane narrower than the card', async ({ pag* the rail beside it.*/-const SUGGESTION_POPUP = '[data-suggestion-popup="slash-command"]';+const SLASH_PICKER = '[data-suggestion-popup="slash-command"]';+const SUGGESTION_POPUP = SLASH_PICKER;const LINT_CALLOUT = '.ok-lint-tooltip';/**@@ -1401,9 +1402,65 @@ async function placeCaretNearPaneRight(page: Page, marker: string, insetPx: numb* 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);+ await openPicker(page, SLASH_PICKER);+}++/**+ * Every picker that rides the shared middleware, with the characters that+ * summon it. Parameterised rather than one arm for the slash menu, because the+ * three do NOT degrade alike: the slash menu's columns are flex items that+ * shrink under the cap on their own, while the other two render a block root+ * carrying a fixed `width`, which a `max-width` on the portaled wrapper cannot+ * shrink. A group that only exercised the flex shape would go green while the+ * other two kept overhanging.+ */+const PICKERS = [+ { label: 'slash', trigger: ' /', selector: '[data-suggestion-popup="slash-command"]' },+ {+ label: 'wiki-link',+ trigger: ' [[',+ selector: '[data-suggestion-popup="wiki-link-suggestion"]',+ },+ { label: 'tag', trigger: ' #', selector: '[data-suggestion-popup="tag-suggestion"]' },+] as const;++async function openPicker(page: Page, selector: string, trigger = ' /'): Promise<void> {+ await page.keyboard.type(trigger);+ await page.locator(selector).waitFor({ state: 'visible', timeout: 10_000 });+ await waitForFloatingSurfaceSettled(page, selector);+}++/**+ * The widest box the picker actually PAINTS — the wrapper unioned with every+ * descendant.+ *+ * `readFloatingSurfaceGeometry` reads the wrapper's own border box, and a+ * child is free to overflow it: a block menu root with `width: 20rem` inside a+ * wrapper capped at 287px leaves the wrapper at 287 and paints 320. Measuring+ * the wrapper alone therefore reports containment for a picker the user can+ * plainly see lying across the dock, which is the exact hole that let a cap+ * inert on two of the three pickers look pinned.+ */+async function readPaintedPickerBox(+ page: Page,+ selector: string,+): Promise<{ left: number; right: number }> {+ return page.evaluate((sel) => {+ const root = Array.from(document.querySelectorAll(sel)).find(+ (element): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0,+ );+ if (!root) throw new Error(`readPaintedPickerBox: no painted ${sel}`);+ const boxes = [root, ...root.querySelectorAll('*')]+ .filter(+ (el): el is HTMLElement => el instanceof HTMLElement && el.getClientRects().length > 0,+ )+ .map((el) => el.getBoundingClientRect());+ return {+ left: Math.min(...boxes.map((b) => b.left)),+ right: Math.max(...boxes.map((b) => b.right)),+ };+ }, selector);}/** The caret's rect, read the way the picker's virtual element reads it. */@@ -1458,6 +1515,85 @@ test('suggestion picker stays inside the pane when opened past the middle of a lexpectInsideVisibleRegionHorizontally(geometry, 'suggestion picker');});+for (const picker of PICKERS) {+ test(`${picker.label} picker stays inside a pane narrower than the picker`, async ({+ page,+ api,+ }) => {+ await openTallDoc(page, api, `clip-suggest-narrow-${picker.label}`);+ await selectSingleMarker(page, blockMarker(40));+ const before = await readFloatingSurfaceGeometry(page, picker.selector);+ await parkCaretAtViewportY(page, before.regionTop + 40);+ await openPicker(page, picker.selector, picker.trigger);+ const natural = await readPaintedPickerBox(page, picker.selector);+ const naturalWidth = natural.right - natural.left;+ if (picker.label === 'slash') {+ // Both columns up in a roomy pane. Asserted so the narrow-pane check+ // below pins a TOGGLE rather than an absence that a never-rendered+ // preview would satisfy just as well. Only the slash menu has one.+ expect(await previewColumnCount(page), 'preview column up in a roomy pane').toBe(1);+ }++ await narrowPaneAsFarAsPossible(page);+ // The trigger characters and the caret do not survive the reflow the+ // resize causes, so the picker is re-opened against the narrowed pane+ // rather than measured where it was.+ const region = await readFloatingSurfaceGeometry(page, picker.selector);+ await parkCaretAtViewportY(page, region.regionTop + 40);+ await openPicker(page, picker.selector, picker.trigger);++ const geometry = await readFloatingSurfaceGeometry(page, picker.selector);+ expect(geometry.present, `${picker.label} picker still mounted`).toBe(true);+ expect(geometry.visible, `${picker.label} picker must be on screen to bite`).toBe(true);+ // Reachability from the two MEASURED numbers rather than a table of+ // expected widths: `narrowPaneTo` bottoms out at whatever chrome the host+ // keeps beside the pane, and a picker narrower than that floor has no+ // overhang for this arm to contain however narrow the window goes — the+ // same limit that keeps the lint callout out of the group above. Skipping+ // says so with both numbers instead of passing on nothing, and a picker+ // that grows past the floor starts being covered with no edit here.+ const paneWidth = geometry.regionRight - geometry.regionLeft;+ test.skip(+ naturalWidth <= paneWidth,+ `${picker.label} picker is ${naturalWidth}px, which already fits the narrowest pane ` ++ `this host lays out (${paneWidth}px) — no overhang to contain`,+ );+ expectPaneNarrowerThan(geometry, naturalWidth, `${picker.label} picker`);++ // The PAINTED box, not the wrapper's: a menu root carrying a fixed `width`+ // leaves the wrapper at the cap and paints past it, which the wrapper's+ // own rect reports as contained.+ const painted = await readPaintedPickerBox(page, picker.selector);+ expect(+ painted.right,+ `${picker.label} picker painted past the pane's right edge (${geometry.regionRight}): ` ++ `rendered ${painted.left}-${painted.right}`,+ ).toBeLessThanOrEqual(geometry.regionRight + REGION_TOLERANCE_PX);+ expect(+ painted.left,+ `${picker.label} picker painted past the pane's left edge (${geometry.regionLeft}): ` ++ `rendered ${painted.left}-${painted.right}`,+ ).toBeGreaterThanOrEqual(geometry.regionLeft - REGION_TOLERANCE_PX);++ if (picker.label === 'slash') {+ // Containment alone would also be satisfied by squeezing both columns+ // into the pane, which is what the one-column rule exists to avoid.+ expect(await previewColumnCount(page), 'preview column dropped in a narrow pane').toBe(0);+ }+ });+}++/** Painted preview columns inside the suggestion picker — 0 once it goes one-column. */+async function previewColumnCount(page: Page): Promise<number> {+ return page.evaluate(+ (selector) =>+ Array.from(document.querySelectorAll(`${selector} .ok-suggestion-preview`)).filter(+ (el) => el.getClientRects().length > 0,+ ).length,+ SUGGESTION_POPUP,+ );+}+test('suggestion picker stays inside the pane when the caret sits mid-pane', async ({page,api,