diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index b222fd919..cf711098c 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -65,6 +65,7 @@ test("completion lists the server's items and inserts the chosen one", async ({ const popup = page.locator(".cm-tooltip-autocomplete"); await expect(popup.getByText("total", { exact: true })).toBeVisible(); await expect(popup.getByText("toDto", { exact: true })).toBeVisible(); + expect((await popup.boundingBox())!.width).toBeLessThan(360); const field = popup.locator("li").filter({ has: page.locator(".cm-completionLabel", { hasText: /^total$/ }) }); await expect(field.locator(".cm-completionDetail")).toHaveCount(0); await expect(field.locator(".cm-lsp-type")).toHaveText("BigDecimal"); @@ -83,6 +84,17 @@ test("completion lists the server's items and inserts the chosen one", async ({ const label = await method.locator(".cm-completionLabel").boundingBox(); // Subpixel rounding differs per platform/font; a mis-set inset is a whole icon column off. expect(Math.abs(label!.x - wordStart)).toBeLessThanOrEqual(2); + const zoomedSize = await editor.locator(".cm-content").evaluate(async (content) => { + const viewModule = "/node_modules/.vite/deps/@codemirror_view.js"; + const prefsModule = "/src/editor/core/cm/prefs.ts"; + const { EditorView } = await import(/* @vite-ignore */ viewModule); + const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule); + const fontSize = Number.parseFloat(getComputedStyle(content).fontSize); + stepFontZoom(EditorView.findFromDOM(content as HTMLElement)!, 6); + return `${fontSize + 6}px`; + }); + await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize); + await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize); await page.keyboard.type("toD"); await expect(popup.getByText("total", { exact: true })).toBeHidden(); // Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top. @@ -98,6 +110,76 @@ test("completion lists the server's items and inserts the chosen one", async ({ expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0); }); +test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => { + const editor = await openSample(page); + const label = "transformOrder" + "AcrossParticipatingRegions".repeat(5); + await page.evaluate((label) => { + const item: CompletionItem = { + label, + labelDetail: "(order: Order, options: TransformationOptions)", + labelDescription: "Promise", + detail: `${label}(order: Order, options: TransformationOptions): Promise`, + kind: "method", + documentation: { kind: "markdown", value: "Transforms the order." }, + sortText: null, + filterText: null, + preselect: true, + deprecated: false, + insertText: `${label}()`, + isSnippet: false, + replaceRange: null, + replaceRangeTab: null, + additionalEdits: [], + commitCharacters: [], + command: null, + data: null, + server: 1, + }; + window.__ipc.handlers.lsp_completion = () => ({ isIncomplete: false, items: [item] }); + }, label); + await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click(); + await page.keyboard.press("End"); + await page.keyboard.press("Enter"); + await page.keyboard.type("order."); + await page.keyboard.press("Control+Space"); + + const popup = page.locator(".cm-tooltip-autocomplete"); + const option = popup.getByRole("option").filter({ + has: page.locator(".cm-completionLabel", { hasText: label }), + }); + await expect(option.locator(".cm-completionLabel")).toHaveText(label); + await page.setViewportSize({ width: 580, height: 900 }); + const bounds = (await editor.boundingBox())!; + await expect + .poll(async () => { + const box = (await popup.boundingBox())!; + return Math.max(bounds.x - box.x, box.x + box.width - (bounds.x + bounds.width)); + }) + .toBeLessThanOrEqual(2); + const geometry = await option.evaluate((row) => { + const label = row.querySelector(".cm-completionLabel")!; + const type = row.querySelector(".cm-lsp-type")!; + return { + nameTruncated: label.scrollWidth > label.clientWidth, + nameWidth: label.clientWidth, + typeWidth: type.clientWidth, + typeOverflow: type.getBoundingClientRect().right - row.getBoundingClientRect().right, + }; + }); + expect(geometry.nameTruncated).toBe(true); + expect(geometry.nameWidth).toBeGreaterThan(40); + expect(geometry.typeWidth).toBeGreaterThan(16); + expect(geometry.typeOverflow).toBeLessThanOrEqual(1); + + await page.keyboard.press("F1"); + await expect(popup.locator(".cm-completionInfo")).toContainText( + `${label}(order: Order, options: TransformationOptions)`, + ); + await page.keyboard.press("Enter"); + await expect(popup).toBeHidden(); + await expect(editor.locator(".cm-activeLine")).toContainText(`order.${label}()`); +}); + test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => { const editor = await openSample(page); await page.evaluate(async () => { diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index 4d0bc6ae4..6e8e9570b 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -25,7 +25,7 @@ import { type CompletionSource, } from "@codemirror/autocomplete"; import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state"; -import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view"; +import { EditorView, ViewPlugin, getTooltip, keymap, showTooltip, type Rect, type ViewUpdate } from "@codemirror/view"; import { call, commands, @@ -59,6 +59,8 @@ import { showHint } from "./hint"; import { inplaceRenameActive } from "./inplaceRename"; import { languageSemantics } from "./semantic"; import { remoteChange } from "@/editor/api"; +import { tooltipBounds } from "@/editor/core/cm/setup"; +import { completionLabelOffset } from "./theme"; interface RequestContext { doc: number; @@ -983,36 +985,45 @@ function sortToggle(view: EditorView): HTMLElement { return button; } -/** IDEA's advertiser bar under the list (one tip: "Press ↵ to insert, ⇥ to replace") and its Sort by Name toggle. */ -const completionFooter = ViewPlugin.fromClass( +const completionPopup = ViewPlugin.fromClass( class { constructor(private view: EditorView) {} update(u: ViewUpdate) { if (completionStatus(u.state) !== "active") return; this.view.requestMeasure({ - read: () => null, - write: () => { - const scope = this.view.dom.ownerDocument; - const tooltips = [ - ...this.view.dom.querySelectorAll(".cm-tooltip-autocomplete"), - ...scope.querySelectorAll(".cm-tooltip-autocomplete"), - ]; - for (const t of tooltips) { - let footer = t.querySelector(":scope > .cm-lsp-completion-footer"); - if (footer) { - // CodeMirror rebuilds the option list by appending a fresh
    , - // which would leave an existing footer above the list. - const list = t.querySelector(":scope > ul"); - if (list && list.nextElementSibling !== footer) list.after(footer); - continue; - } + key: this, + read: () => { + const { left, right } = tooltipBounds(this.view); + return { + width: `${Math.max(0, Math.floor(right - left))}px`, + fontSize: getComputedStyle(this.view.contentDOM).fontSize, + }; + }, + write: ({ width, fontSize }) => { + const popup = this.view.state + .facet(showTooltip) + .map((tooltip) => tooltip && getTooltip(this.view, tooltip)) + .find((tooltip) => tooltip?.dom.classList.contains("cm-lsp-completion")); + if (!popup) return; + // Apply the label alignment inside CodeMirror's viewport clamp. + popup.offset = { x: -completionLabelOffset, y: 0 }; + const t = popup.dom; + if (t.style.getPropertyValue("--cm-completion-max-width") !== width) + t.style.setProperty("--cm-completion-max-width", width); + // The body-level tooltip does not inherit the editor's temporary font zoom. + if (t.style.getPropertyValue("--openidea-editor-font-size") !== fontSize) + t.style.setProperty("--openidea-editor-font-size", fontSize); + let footer = t.querySelector(":scope > .cm-lsp-completion-footer"); + if (!footer) { footer = document.createElement("div"); footer.className = "cm-lsp-completion-footer"; const tip = document.createElement("span"); tip.textContent = tx("Press ↵ to insert, ⇥ to replace"); footer.append(tip, sortToggle(this.view)); - t.appendChild(footer); } + // CodeMirror appends a fresh list when the candidates change. + const list = t.querySelector(":scope > ul"); + if (list && list.nextElementSibling !== footer) list.after(footer); }, }); } @@ -1067,7 +1078,7 @@ export function completionExtension() { tooltipClass: () => "cm-lsp-completion", positionInfo: positionCompletionInfo, }), - completionFooter, + completionPopup, lookupTracker, serverInsertAt, caretAfterServerInsert, diff --git a/src/editor/lsp/theme.ts b/src/editor/lsp/theme.ts index 5cd4270d0..846df3f7a 100644 --- a/src/editor/lsp/theme.ts +++ b/src/editor/lsp/theme.ts @@ -10,19 +10,17 @@ const tooltipSurface = { color: "var(--fg)", }; -/** - * Row metrics that put a label one icon column right of the popup's left edge. They live on the - * popup as custom properties so every rule consuming them — including the popup's negative - * offset below — changes together. The remaining 1px is tooltipSurface's border, shared with - * the hover and signature tooltips. - */ +const completionInsets = { edge: 4, padding: 6, icon: 16, gap: 6 }; +export const completionLabelOffset = + 1 + completionInsets.edge + completionInsets.padding + completionInsets.icon + completionInsets.gap; + const completionRowMetrics = { // Rows grow with the editor font size (lookup text uses the editor font, as typed text does). "--cm-completion-row": "max(var(--h-list-row), calc(var(--openidea-editor-font-size, var(--fs-code)) * 1.7))", - "--cm-completion-edge": "4px", - "--cm-completion-inset": "6px", - "--cm-completion-icon": "16px", - "--cm-completion-gap": "6px", + "--cm-completion-edge": `${completionInsets.edge}px`, + "--cm-completion-inset": `${completionInsets.padding}px`, + "--cm-completion-icon": `${completionInsets.icon}px`, + "--cm-completion-gap": `${completionInsets.gap}px`, }; const markdown = { @@ -103,22 +101,19 @@ export const lspTheme = EditorView.theme({ fontFamily: "var(--openidea-editor-font, var(--font-mono))", fontWeight: "var(--fw-code, 400)", fontSize: "var(--openidea-editor-font-size, var(--fs-code))", - // CodeMirror anchors the popup at the completed word's start. Pull it left by one row's - // leading inset so the labels, not the icon column, sit on the text. CodeMirror's horizontal - // clamp measures the border box (margins excluded), so this offset sits outside its math: - // near the right edge it leaves that much extra space, and a word starting within one inset - // of the viewport's left edge would let the popup clip there. The normal editor layout - // (gutter + project sidebar) keeps the word well clear of that edge. - marginLeft: - "calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))", + display: "flex", + flexDirection: "column", + width: "max-content", + maxWidth: "min(720px, var(--cm-completion-max-width, 100vw))", // No overflow clipping: CodeMirror nests the documentation pane in this box and // positions it outside it (see `positionCompletionInfo`). The footer rounds itself. }, ".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": { fontFamily: "var(--openidea-editor-font, var(--font-mono))", fontWeight: "var(--fw-code, 400)", - minWidth: "420px", - maxWidth: "min(720px, 80vw)", + minWidth: "0", + maxWidth: "100%", + height: "auto", maxHeight: "calc(var(--cm-completion-row) * 11 + 8px)", padding: "4px 0", }, @@ -153,9 +148,15 @@ export const lspTheme = EditorView.theme({ alignItems: "center", justifyContent: "center", }, - ".cm-lsp-completion .cm-completionLabel": { flex: "none", overflow: "hidden", textOverflow: "ellipsis" }, + ".cm-lsp-completion .cm-completionLabel": { + flex: "0 1 auto", + minWidth: "0", + overflow: "hidden", + textOverflow: "ellipsis", + }, ".cm-lsp-completion .cm-completionDetail": { flex: "0 1 auto", + minWidth: "0", marginLeft: "0", fontStyle: "normal", color: "var(--fg-subtle)", @@ -172,7 +173,8 @@ export const lspTheme = EditorView.theme({ marginLeft: "calc(-1 * var(--cm-completion-gap))", }, ".cm-lsp-completion .cm-lsp-type": { - flex: "1 0 auto", + flex: "0 1 auto", + minWidth: "0", maxWidth: "60%", marginLeft: "auto", paddingLeft: "16px", @@ -188,18 +190,21 @@ export const lspTheme = EditorView.theme({ }, ".cm-lsp-completion-footer": { display: "flex", + flex: "none", + flexWrap: "wrap", alignItems: "center", padding: "5px 12px", backgroundColor: "var(--bg-popup-inline, var(--bg-elev))", color: "var(--fg-subtle)", fontFamily: "var(--font-ui)", fontSize: "var(--fs-small)", - whiteSpace: "nowrap", - gap: "12px", + gap: "var(--space-1) var(--space-3)", justifyContent: "space-between", borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)", }, ".cm-lsp-completion-sort": { + flex: "none", + maxWidth: "100%", padding: "0", border: "none", background: "none",