Compare commits

...
Author SHA1 Message Date
l0ng-ai 4aef69e73f Merge remote-tracking branch 'origin/main' into fix/quick-documentation-layout 2026-11-20 02:51:55 +08:00
l0ng-ai 121e1fa535 fix(completion): fit the lookup to the editor and its font (#4566)
The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size.
2026-11-20 02:51:47 +08:00
l0ng-ai 4eca76c286 fix(editor): make quick documentation fit narrow windows 2026-11-19 23:56:55 +08:00
6 changed files with 247 additions and 48 deletions

No files matched your search

+82
View File
@@ -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<TransformationResult>",
detail: `${label}(order: Order, options: TransformationOptions): Promise<TransformationResult>`,
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<HTMLElement>(".cm-completionLabel")!;
const type = row.querySelector<HTMLElement>(".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 () => {
+73
View File
@@ -0,0 +1,73 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
async function quickDocumentation(page: Page, markdown: string) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((value) => {
window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null });
}, markdown);
const line = editor.locator(".cm-line", { hasText: "return order.toDto()" });
await line.click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("F1");
const popup = page.getByRole("dialog", { name: "Documentation", exact: true });
await expect(popup.locator(".cm-lsp-markdown")).toBeVisible();
return popup;
}
test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => {
const popup = await quickDocumentation(page, "Returns the total.");
const back = popup.getByRole("button", { name: "Back", exact: true });
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
const bounds = (await popup.boundingBox())!;
expect(bounds.width).toBeGreaterThanOrEqual(298);
expect(bounds.width).toBeLessThan(320);
const backBounds = (await back.boundingBox())!;
const dockBounds = (await dock.boundingBox())!;
expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2);
expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16);
await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => {
const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult";
const markdown = [
`\`\`\`kotlin\n${signature}\n\`\`\``,
...Array.from({ length: 22 }, (_, i) => {
return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`;
}),
"End of pricing documentation.",
].join("\n\n");
const popup = await quickDocumentation(page, markdown);
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(508);
await page.setViewportSize({ width: 430, height: 500 });
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500);
})
.toBeLessThanOrEqual(1);
const body = popup.locator(".cm-lsp-markdown").locator("..");
const last = popup.getByText("End of pricing documentation.");
const dockBefore = (await dock.boundingBox())!;
await expect(body.locator("pre")).toContainText(signature);
const scroll = await body.evaluate((node) => {
node.scrollTop = node.scrollHeight;
return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth };
});
expect(scroll.top).toBeGreaterThan(0);
expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1);
const lastBounds = (await last.boundingBox())!;
expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1);
expect(await dock.boundingBox()).toEqual(dockBefore);
await expect(dock).toBeInViewport();
});
+17 -2
View File
@@ -238,6 +238,10 @@
flex-direction: column;
overflow: hidden;
}
.docPopup:not([data-resized]) {
width: max-content;
min-width: min(300px, 90vw);
}
.docScope {
display: contents;
}
@@ -246,21 +250,32 @@
}
.docPopup .docFrame {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.docPopup:not([data-resized]) .docFrame {
max-width: min(600px, 90vw);
max-height: 420px;
max-width: min(500px, 90vw);
max-height: 500px;
}
.docPopup .docBody {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: var(--space-2) var(--space-4) var(--space-1);
}
.docPopup .docToolbar {
position: static;
flex: none;
align-self: flex-end;
margin: 0 var(--space-2) var(--space-1);
padding: 0;
border: 0;
}
.docPopup .docToolbar .spacer {
display: none;
}
.docWindowFrame {
height: 100%;
+14 -1
View File
@@ -356,6 +356,19 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
const opened = useRef(focusSeq);
// The captured caret can end up outside the viewport while the popup is open.
const anchor = useMemo(
() => ({
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(popup.anchor.x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
}),
[popup.anchor],
);
useEffect(() => {
if (focusSeq !== opened.current)
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
@@ -364,7 +377,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
return (
<Popup
open
anchor={popup.anchor}
anchor={anchor}
onClose={closePopup}
aria-label="Documentation"
className={styles.docPopup}
+32 -21
View File
@@ -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<HTMLElement>(".cm-tooltip-autocomplete"),
...scope.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
];
for (const t of tooltips) {
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
if (footer) {
// CodeMirror rebuilds the option list by appending a fresh <ul>,
// 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<HTMLElement>(":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,
+29 -24
View File
@@ -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",