From 0eef66d7935d4cbdc3e86343e021ce3fd23a43a6 Mon Sep 17 00:00:00 2001 From: Alexis <44708815+Rhombicdodecahedron@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:08:23 +0100 Subject: [PATCH 001/104] feat(plugins): let web views embed declared and granted origins (#5618) A plugin web view, custom editor or editor panel can list origins in a new frames field (API 1.16). Each origin must be https (or http to a loopback host), name one exact host with no path, and be covered by a net: capability of the manifest, so the install page shows it. Pages under that declaration's directory are served with a frame-src of the declared origins the user granted, and are revalidated instead of cached immutable, so declining or revoking a host takes effect on the next load. Without frames the CSP is unchanged, the plugin page cannot widen it, and the embedded page keeps the frame's sandbox without window.openidea. Closes #5523 Co-authored-by: Rhombicdodecahedron <44708815+Rhombicdodecahedron@users.noreply.github.com> --- Cargo.lock | 1 + crates/ide-host/Cargo.toml | 1 + crates/ide-host/src/plugins/ui_points.rs | 149 ++++++++++++++++++++++- crates/ide-host/src/plugins/web.rs | 39 +++++- crates/ide-host/tests/plugins.rs | 62 ++++++++++ docs/en/plugins/guides/views.mdx | 23 ++++ docs/zh/plugins/guides/views.mdx | 19 +++ plugins/README.md | 38 +++++- src-tauri/src/plugin_web.rs | 29 ++++- 9 files changed, 351 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6efae27195..2950fc8c8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4515,6 +4515,7 @@ dependencies = [ "toml 0.9.12+spec-1.1.0", "tracing", "tracing-subscriber", + "url", "uuid", "windows-sys 0.61.2", "zip", diff --git a/crates/ide-host/Cargo.toml b/crates/ide-host/Cargo.toml index 87fc1b81a4..fb6700729b 100644 --- a/crates/ide-host/Cargo.toml +++ b/crates/ide-host/Cargo.toml @@ -68,6 +68,7 @@ specta.workspace = true specta-typescript.workspace = true tokio = { workspace = true, features = ["io-std"] } tracing.workspace = true +url = "2" tracing-subscriber.workspace = true parking_lot.workspace = true dunce.workspace = true diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index bab56bded6..069b82ca16 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -36,6 +36,7 @@ //! priority = "default" # or "option": only through Open With //! layout = "tab" # or "split" / "preview": beside the text editor //! web = "web/index.html" # a web page from the package instead of rendered content +//! frames = ["https://example.com"] # API 1.16: origins the page may embed; each needs `net:` //! //! [[contributes.editorPanels]] //! id = "minimap" @@ -641,6 +642,65 @@ struct ViewDecl { /// A web page of the package (`web/index.html`) instead of content the code renders. #[serde(default, skip_serializing_if = "Option::is_none")] web: Option, + /// Origins the web page may embed in `").unwrap(); + let header = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.16\"\nwasm = \"p.wasm\"\n\ + [capabilities]\nrequired = [\"editor.read\", \"net:example.com\", \"net:*.games.test\", \"net:localhost\"]\n"; + let check = |point: &str, body: &str, header: &str| { + let manifest = ide_extension::Manifest::parse(&format!("{header}[[contributes.{point}]]\n{body}"))?; + let decl = manifest.declarations(point).into_iter().next().unwrap(); + let pkg = Package::new(manifest, dir.path().to_path_buf()); + match point { + VIEWS => view(&pkg, decl), + CUSTOM_EDITORS => custom_editor(&pkg, decl), + _ => editor_panel(&pkg, decl), + } + }; + let view_with = + |frames: &str| format!("id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\nframes = {frames}\n"); + let ok = check( + VIEWS, + &view_with(r#"["https://EXAMPLE.com/", "https://a.games.test:8443", "http://localhost:5173"]"#), + header, + ) + .unwrap(); + assert_eq!( + ok.json["frames"], + serde_json::json!(["https://example.com", "https://a.games.test:8443", "http://localhost:5173"]) + ); + assert!( + check(VIEWS, "id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\n", header) + .unwrap() + .json + .get("frames") + .is_none() + ); + let editor = "id = \"e\"\ntitle = \"E\"\npatterns = [\"*.x\"]\nweb = \"web/index.html\"\nframes = [\"https://example.com\"]\n"; + assert_eq!( + check(CUSTOM_EDITORS, editor, header).unwrap().json["frames"], + serde_json::json!(["https://example.com"]) + ); + let panel = "id = \"m\"\nweb = \"web/index.html\"\nwidth = 110\nframes = [\"https://example.com\"]\n"; + assert_eq!( + check(EDITOR_PANELS, panel, header).unwrap().json["frames"], + serde_json::json!(["https://example.com"]) + ); + + for (frames, error) in [ + (r#"["https://other.com"]"#, "`net:other.com` capability"), + (r#"["https://games.test"]"#, "`net:games.test` capability"), + (r#"["http://example.com"]"#, "https://, or http:// to localhost"), + (r#"["ftp://example.com"]"#, "https://, or http:// to localhost"), + (r#"["https://example.com/room"]"#, "no path"), + (r#"["https://example.com?x"]"#, "no path"), + (r#"["https://example.com/#x"]"#, "no path"), + (r#"["https://*.games.test"]"#, "one exact host"), + (r#"["https://me@example.com"]"#, "user name"), + (r#"["example.com"]"#, "not a URL"), + (r#"["data:text/html,x"]"#, "https://"), + ] { + let err = check(VIEWS, &view_with(frames), header).unwrap_err(); + assert!(err.contains(error), "{frames} → {err}"); + } + let many = format!("[{}]", vec!["\"https://example.com\""; 17].join(", ")); + assert!(check(VIEWS, &view_with(&many), header).unwrap_err().contains("at most 16")); + let older = header.replace("^1.16", "^1.15"); + assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &older).unwrap_err().contains("1.16")); + let code_view = "id = \"v\"\ntitle = \"V\"\nframes = [\"https://example.com\"]\n"; + assert!(check(VIEWS, code_view, header).unwrap_err().contains("for a web page")); + // `net:ask` is not a listed host: the install page would not show the origin. + let ask = header.replace("\"net:example.com\"", "\"net:ask\""); + assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability")); + } + fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) { let dir = tempfile::tempdir().unwrap(); std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap(); diff --git a/crates/ide-host/src/plugins/web.rs b/crates/ide-host/src/plugins/web.rs index e1192ab5ef..378b610404 100644 --- a/crates/ide-host/src/plugins/web.rs +++ b/crates/ide-host/src/plugins/web.rs @@ -121,6 +121,10 @@ pub(super) struct WebPtySession { pub struct WebFile { pub bytes: Vec, pub mime: &'static str, + /// The origins a page may embed: `None` when no web page whose directory holds + /// the file declares `frames` (API 1.16), else the declared origins the user has + /// granted (`net:` / `net.http:`), possibly none. + pub frames: Option>, } impl PluginHost { @@ -324,6 +328,32 @@ impl PluginHost { }) } + /// `frames` of the web pages whose directory holds `rel`, kept to those `granted`. + fn web_frames(&self, plugin: &str, rel: &str, granted: &[ide_extension::Capability]) -> Option> { + let declared: Vec = super::ui_points::WEB_POINTS + .iter() + .flat_map(|point| self.ui.items(point, Some(plugin))) + .filter(|item| { + let dir = item.decl.get("web").and_then(|w| w.as_str()).and_then(|e| e.rsplit_once('/')); + dir.is_some_and(|(dir, _)| rel.starts_with(&format!("{dir}/"))) + }) + .filter_map(|item| item.decl.get("frames").and_then(|f| f.as_array()).cloned()) + .flatten() + .filter_map(|f| f.as_str().map(str::to_owned)) + .collect(); + if declared.is_empty() { + return None; + } + let mut allowed = Vec::new(); + for origin in declared { + let ok = ide_plugin::net_capability(&origin).is_ok_and(|cap| granted.iter().any(|g| g.covers(&cap))); + if ok && !allowed.contains(&origin) { + allowed.push(origin); + } + } + Some(allowed) + } + /// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated). fn web_dirs(&self, plugin: &str) -> Vec { super::ui_points::WEB_POINTS @@ -376,7 +406,14 @@ impl PluginHost { return Err(IdeError::not_found(format!("{rel}: not part of a web view"))); } let bytes = plugin.pkg.read_bytes(rel_path).map_err(IdeError::not_found)?; - Ok(WebFile { bytes, mime: mime(rel) }) + let mime = mime(rel); + let frames = if mime.starts_with("text/html") { + let granted = plugin.meta.lock().granted.clone(); + self.web_frames(plugin_id, rel, &granted) + } else { + None + }; + Ok(WebFile { bytes, mime, frames }) } } diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 4c289246ea..5692fb4d14 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -3902,6 +3902,68 @@ path = "templates/new.draw" assert!(f.host.web_page("web-demo", "draw").is_err()); } +#[test] +fn web_pages_embed_only_declared_and_granted_frames() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("frame-demo"); + for (path, text) in [ + ("hall/index.html", ""), + ("hall/rules.html", "

rules

"), + ("hall/app.js", "console.log(1)"), + ("panel/index.html", "

panel

"), + ] { + std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap(); + std::fs::write(pkg.join(path), text).unwrap(); + } + std::fs::write( + pkg.join("plugin.toml"), + r#"id = "frame-demo" +name = "Frame Demo" +version = "1.0.0" +engines.openidea = "^1.16" + +[capabilities] +optional = ["net:example.com", "net:*.games.test"] + +[[contributes.views]] +id = "hall" +title = "Hall" +web = "hall/index.html" +frames = ["https://example.com/", "https://play.games.test:8443", "https://example.com"] + +[[contributes.views]] +id = "panel" +title = "Panel" +web = "panel/index.html" +"#, + ) + .unwrap(); + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + assert_eq!( + f.host.ui_items("views").iter().find(|v| v.decl["id"] == "hall").unwrap().decl["frames"], + serde_json::json!(["https://example.com", "https://play.games.test:8443"]) + ); + let page = f.host.web_page("frame-demo", "hall").unwrap(); + let rev = page.path.strip_prefix("frame-demo/").unwrap().split_once('/').unwrap().0.to_owned(); + let frames = |path: &str| f.host.web_file("frame-demo", &format!("{rev}/{path}")).unwrap().frames; + let both = Some(vec!["https://example.com".to_owned(), "https://play.games.test:8443".to_owned()]); + // Every page in the declaring view's directory, not its other files nor another view's pages. + assert_eq!(frames("hall/index.html"), both); + assert_eq!(frames("hall/rules.html"), both); + assert_eq!(frames("hall/app.js"), None); + assert_eq!(frames("panel/index.html"), None); + + // Only what the user granted: declining a host takes it out of the policy. + f.host.set_capability("frame-demo", "net:example.com", false).unwrap(); + assert_eq!(frames("hall/index.html"), Some(vec!["https://play.games.test:8443".to_owned()])); + f.host.set_capability("frame-demo", "net:*.games.test", false).unwrap(); + assert_eq!(frames("hall/index.html"), Some(Vec::new())); + f.host.set_capability("frame-demo", "net:example.com", true).unwrap(); + assert_eq!(frames("hall/index.html"), Some(vec!["https://example.com".to_owned()])); +} + #[test] fn file_icons_without_patterns_require_api_1_8_and_project_assets() { let f = fixture(Limits::default()); diff --git a/docs/en/plugins/guides/views.mdx b/docs/en/plugins/guides/views.mdx index e2f3f24f53..b888192c09 100644 --- a/docs/en/plugins/guides/views.mdx +++ b/docs/en/plugins/guides/views.mdx @@ -270,6 +270,29 @@ corner actions (**Options**, **Hide**) and sets `--openidea-corner-inset-width` } ``` +**Embedded pages** (API 1.16). A web page can embed other sites in `', + '', + '', + '
safe raw text
', + ].join("\n\n"); + const item = (markdownHover: string) => ({ + ...set(), + items: [{ range, style: "highlight", hover: null, after: " + model", markdownHover }], + }); + if (phase === "warm initial hover") await loadMarkdown(); + setPluginDecorations("test", [item(phase === "live refresh" ? "loading conversation" : markdown)]); + vi.useFakeTimers(); + try { + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + } finally { + vi.useRealTimers(); + } + const card = document.querySelector(".cm-tooltip .cm-lsp-hover")!; + expect(card).not.toBeNull(); + // The first hover exercises the lazy parser; subsequent cases use the loaded parser. + await loadMarkdown(); + if (phase === "live refresh") { + expect(card.textContent).toContain("loading conversation"); + setPluginDecorations("test", [item(markdown)]); + expect(document.querySelector(".cm-tooltip .cm-lsp-hover")).toBe(card); + } + await vi.waitFor(() => expect(card.querySelector("strong")?.textContent).toBe("safe text")); + expect([...card.querySelectorAll("a")].map((link) => link.getAttribute("href"))).toEqual([ + "https://docs.example.invalid/guide", + "https://docs.example.invalid/raw", + "file:///p/a.txt#L1", + "jdt://contents/a.class", + ]); + expect(card.querySelector("pre > code")?.textContent).toBe(''); + expect(card.textContent).toContain("![literal](https://code.example.invalid/inline)"); + expect(card.textContent).toContain("safe raw text"); + expect(card.querySelector("td")?.textContent).toBe("safe table"); + expect([ + ...card.querySelectorAll( + "img, picture, source, video, audio, track, iframe, object, embed, link, style, svg, math, [src], [srcset], [poster], [background], [srcdoc], [style], [onerror]", + ), + ]).toEqual([]); + }, +); + +it("reports a failed Markdown load without retrying or inserting plugin resources", async () => { + await loadMarkdown(); + const failure = new Error("Markdown chunk unavailable"); + const loader = vi.spyOn(await import("@/editor/lsp/markdown"), "loadMarkdown").mockRejectedValueOnce(failure); + const logger = vi.spyOn(await import("@/platform/errorLog"), "logError").mockImplementation(() => {}); + try { + setPluginDecorations("test", [ + { + ...set(), + items: [ + { + range, + style: "highlight", + hover: null, + after: " + model", + markdownHover: "**safe text** ![remote](https://assets.example.invalid/image)", + }, + ], + }, + ]); + vi.useFakeTimers(); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + expect(logger).toHaveBeenCalledExactlyOnceWith("cannot render plugin Markdown", failure); + expect(loader).toHaveBeenCalledTimes(1); + const card = document.querySelector(".cm-tooltip .cm-lsp-hover")!; + expect(card.textContent).toContain("safe text"); + expect(card.querySelector("img, [src], [srcset]")).toBeNull(); + } finally { + vi.useRealTimers(); + loader.mockRestore(); + logger.mockRestore(); + } +}); + +it("leaves the shared documentation image policy unchanged", async () => { + await loadMarkdown(); + const dom = renderMarkup({ kind: "markdown", value: "![docs](https://docs.example.invalid/image)" }); + expect(dom.querySelector("img")?.getAttribute("src")).toBe("https://docs.example.invalid/image"); +}); + +it("renders a Markdown hover card instead of the native tooltip", async () => { + setPluginDecorations("test", [ + { + ...set(), + items: [ + { + range, + style: "highlight", + hover: "plain tooltip", + after: " + model", + markdownHover: "**model** card", + }, + ], + }, + ]); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + expect(label.getAttribute("title")).toBeNull(); + expect(editor.view.dom.querySelector('[title="plain tooltip"]')).toBeNull(); + + vi.useFakeTimers(); + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + const card = document.querySelector(".cm-tooltip .cm-lsp-hover"); + expect(card?.textContent).toContain("model"); + expect(card?.querySelector('[role="region"]')?.getAttribute("aria-label")).toBe("Hover card"); + vi.useRealTimers(); +}); + +it("keeps the Markdown hover after the caret moves", async () => { + setPluginDecorations("test", [ + { + ...set(), + items: [{ range, style: "highlight", hover: null, after: " + model", markdownHover: "**model** card" }], + }, + ]); + // A click or arrow key is an ordinary selection transaction. + editor.view.dispatch({ selection: { anchor: 0 } }); + + vi.useFakeTimers(); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + expect(document.querySelector(".cm-tooltip .cm-lsp-hover")?.textContent).toContain("model"); + vi.useRealTimers(); +}); + +it("keeps the Markdown hover after an edit shifts the label", async () => { + setPluginDecorations("test", [ + { + ...set(), + items: [{ range, style: "highlight", hover: null, after: " + model", markdownHover: "**model** card" }], + }, + ]); + editor.view.dispatch({ changes: { from: 0, insert: "xy" } }); + + vi.useFakeTimers(); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + expect(document.querySelector(".cm-tooltip .cm-lsp-hover")?.textContent).toContain("model"); + vi.useRealTimers(); +}); + +it("updates an open hover card when the plugin loads the conversation", async () => { + const item = (markdownHover: string) => ({ + ...set(), + items: [{ range, style: "highlight", hover: null, after: " + model", markdownHover }], + }); + setPluginDecorations("test", [item("**model** is loading…")]); + vi.useFakeTimers(); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + const card = document.querySelector(".cm-tooltip .cm-lsp-hover")!; + expect(card.textContent).toContain("loading"); + + // Hydration finishes while the card is open; the same card shows it. + setPluginDecorations("test", [item("the real conversation")]); + expect(card.textContent).toContain("the real conversation"); + vi.useRealTimers(); +}); + it("filters tree badges by project root but not editor annotations, and drops unknown styles", () => { // Editor annotations follow the file: a set from another root still renders where the file is open. setPluginDecorations("test", [set("/other")]); @@ -124,10 +336,20 @@ it("resolves dynamic file and folder icons declared by the plugin", () => { }); it("selects UTF-16 ranges and reveals without changing text", () => { - handleRuntimeEvent({ type: "editorRanges", path: ctx.path, ranges: [range], reveal: false }); + handleRuntimeEvent({ + type: "editorRanges", + path: ctx.path, + ranges: [range], + reveal: false, + }); expect(editor.view.state.selection.main.from).toBe(2); expect(editor.view.state.selection.main.to).toBe(4); - handleRuntimeEvent({ type: "editorRanges", path: ctx.path, ranges: [range], reveal: true }); + handleRuntimeEvent({ + type: "editorRanges", + path: ctx.path, + ranges: [range], + reveal: true, + }); expect(editor.view.state.doc.toString()).toBe("😀text"); handleRuntimeEvent({ type: "editorRanges", @@ -149,6 +371,337 @@ it("describes ide.commands explicitly in consent", () => { expect(description).toContain("including running programs, committing and pushing"); }); +async function openResizeHover(markdown = "**model** conversation") { + setPluginDecorations("test", [ + { ...set(), items: [{ range, style: "highlight", hover: null, after: " + model", markdownHover: markdown }] }, + ]); + vi.useFakeTimers(); + try { + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + } finally { + vi.useRealTimers(); + } + const card = document.querySelector(".cm-tooltip .cm-lsp-hover")!; + expect(card).not.toBeNull(); + vi.spyOn(card, "getBoundingClientRect").mockReturnValue(new DOMRect(100, 100, 400, 240)); + vi.spyOn(card.closest(".cm-tooltip")!, "getBoundingClientRect").mockReturnValue(new DOMRect(100, 100, 400, 240)); + return card; +} + +function resizePointer(target: EventTarget, type: string, x: number, y: number, buttons = 1) { + const event = new MouseEvent(type, { clientX: x, clientY: y, bubbles: true, cancelable: true, button: 0, buttons }); + Object.defineProperty(event, "pointerId", { value: 1 }); + target.dispatchEvent(event); +} + +it.each([ + ["n", 0, -60, 400, 300, "Resize hover card from the top"], + ["e", 80, 0, 480, 240, "Resize hover card from the right"], + ["s", 0, 60, 400, 300, "Resize hover card from the bottom"], + ["w", -80, 0, 480, 240, "Resize hover card from the left"], + ["se", 80, 60, 480, 300, "Resize hover card from the corner"], +] as const)("resizes the hover card by its %s edge", async (edge, dx, dy, width, height, label) => { + const card = await openResizeHover(); + const handle = card.querySelector(`button[data-edge="${edge}"]`); + expect(handle).not.toBeNull(); + expect(handle!.getAttribute("aria-label")).toBe(label); + resizePointer(handle!, "pointerdown", 300, 220); + resizePointer(window, "pointermove", 300 + dx, 220 + dy); + expect(card.style.width).toBe(`${width}px`); + expect(card.style.height).toBe(`${height}px`); + resizePointer(window, "pointerup", 300 + dx, 220 + dy, 0); + expect(!!document.querySelector("[data-drag-cursor-surface]")).toBe(false); +}); + +it("anchors a long-line conversation to its model label and follows its rendered position", async () => { + const code = "x".repeat(1000); + editor.view.dispatch({ changes: { from: 0, to: editor.view.state.doc.length, insert: code } }); + const longRange = { start: { line: 0, col: 0 }, end: { line: 0, col: code.length } }; + setPluginDecorations("test", [ + { + ...set(), + items: [{ range: longRange, style: "highlight", hover: null, after: " + model", markdownHover: "conversation" }], + }, + ]); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + const labelRect = vi.spyOn(label, "getBoundingClientRect").mockReturnValue(new DOMRect(800, 300, 150, 20)); + vi.spyOn(editor.view, "coordsAtPos").mockReturnValue(new DOMRect(20, 300, 1, 20)); + vi.useFakeTimers(); + try { + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 850, clientY: 310 })); + await vi.advanceTimersByTimeAsync(400); + const tooltip = editor.view.state.facet(showTooltip)[0]!; + const rendered = getTooltip(editor.view, tooltip)!; + expect(rendered.getCoords!(tooltip.pos).left).toBe(800); + expect(rendered.getCoords!(tooltip.pos).top).toBe(300); + labelRect.mockReturnValue(new DOMRect(500, 340, 150, 20)); + expect(rendered.getCoords!(tooltip.pos).left).toBe(500); + expect(rendered.getCoords!(tooltip.pos).top).toBe(340); + } finally { + vi.useRealTimers(); + } +}); + +it("keeps a body-hosted conversation open while crossing from its label, then dismisses outside", async () => { + editor.view.dispatch({ effects: StateEffect.appendConfig.of(tooltips({ parent: document.body })) }); + const card = await openResizeHover("conversation message\n\n".repeat(40)); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + vi.spyOn(label, "getBoundingClientRect").mockReturnValue(new DOMRect(400, 380, 100, 20)); + expect(editor.view.dom.contains(card)).toBe(false); + editor.view.dom.dispatchEvent( + new MouseEvent("mouseleave", { relatedTarget: document.body, clientX: 450, clientY: 370 }), + ); + expect(card.isConnected).toBe(true); + document.body.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 450, clientY: 355 })); + expect(card.isConnected).toBe(true); + card.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 450, clientY: 320 })); + const handle = card.querySelector('button[data-edge="se"]')!; + resizePointer(handle, "pointerdown", 490, 330); + resizePointer(window, "pointermove", 570, 390); + resizePointer(window, "pointerup", 570, 390, 0); + expect(card.isConnected).toBe(true); + expect(card.style.width).toBe("480px"); + expect(card.style.height).toBe("300px"); + expect(card.textContent).toContain("conversation message"); + document.body.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 10, clientY: 10 })); + expect(card.isConnected).toBe(false); +}); + +it("keeps a hydrated conversation anchored to the replacement model label", async () => { + const card = await openResizeHover("loading conversation"); + const handle = card.querySelector('button[data-edge="e"]')!; + resizePointer(handle, "pointerdown", 490, 220); + resizePointer(window, "pointermove", 570, 220); + resizePointer(window, "pointerup", 570, 220, 0); + setPluginDecorations("test", [ + { + ...set(), + items: [ + { range, style: "highlight", hover: null, after: " + model", markdownHover: "the hydrated conversation" }, + ], + }, + ]); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + vi.spyOn(label, "getBoundingClientRect").mockReturnValue(new DOMRect(620, 380, 100, 20)); + const tooltip = editor.view.state.facet(showTooltip)[0]!; + expect(getTooltip(editor.view, tooltip)!.getCoords!(tooltip.pos).left).toBe(620); + expect(document.querySelector(".cm-tooltip .cm-lsp-hover")).toBe(card); + expect(card.textContent).toContain("the hydrated conversation"); + expect(card.style.width).toBe("480px"); +}); + +it.each(["Escape", "outside pointer", "window blur", "window leave", "editor destruction"])( + "cleans up an interactive conversation on %s", + async (action) => { + const card = await openResizeHover(); + const handle = card.querySelector('button[data-edge="e"]')!; + resizePointer(handle, "pointerdown", 490, 220); + resizePointer(window, "pointermove", 570, 220); + expect(!!document.querySelector("[data-drag-cursor-surface]")).toBe(true); + if (action === "Escape") window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + else if (action === "outside pointer") resizePointer(document.body, "pointerdown", 10, 10); + else if (action === "window blur") window.dispatchEvent(new Event("blur")); + else if (action === "window leave") + document.documentElement.dispatchEvent(new MouseEvent("mouseleave", { relatedTarget: null })); + else editor.view.destroy(); + expect(card.isConnected).toBe(false); + expect(!!document.querySelector("[data-drag-cursor-surface]")).toBe(false); + resizePointer(window, "pointermove", 800, 220); + expect(card.style.width).toBe("480px"); + }, +); + +it("dismisses only the plugin conversation, not another provider's hover", async () => { + const other = hoverTooltip(() => ({ + pos: 0, + create: () => { + const dom = document.createElement("div"); + dom.textContent = "other provider"; + return { dom }; + }, + })); + editor.view.dispatch({ effects: StateEffect.appendConfig.of(other) }); + const card = await openResizeHover(); + activateHover(editor.view, 0, 1, { tooltip: other }); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + expect(card.isConnected).toBe(false); + expect(document.body.textContent).toContain("other provider"); + expect(editor.view.state.field(other.active)).toHaveLength(1); +}); + +it("opens the configured commit detail URL when the conversation SHA is clicked", async () => { + const sha = "2b03ef6774cfb016dcf8c48f849c0684d8908c6a"; + const url = `https://tenant.example.invalid/gitai/admin/repos/commit?repo=https%3A%2F%2Fgithub.com%2Fl0ng-ai%2Fopenidea&sha=${sha}`; + await loadMarkdown(); + const card = await openResizeHover(`[${sha.slice(0, 8)}](${url})`); + const link = card.querySelector("a")!; + expect(link.getAttribute("href")).toBe(url); + vi.stubGlobal("__TAURI_INTERNALS__", {}); + try { + link.click(); + await vi.waitFor(() => expect(openUrl).toHaveBeenCalledWith(url)); + } finally { + vi.unstubAllGlobals(); + } +}); + +it("does not run plugin commands for file-fragment links in a hover card", async () => { + // The withdrawn `#openidea-file` contract must stay inert: fragments never dispatch commands. + const info: PluginInfo = { + ...(await createMemoryPluginsBackend().list()).plugins[0]!, + id: "test", + enabled: true, + hasCode: true, + status: "active", + activation: ["on-command:open-decoration-file"], + capabilities: [{ id: "project.read", granted: true, optional: false, risk: "low", description: "Read project" }], + }; + usePlugins.setState({ plugins: [info], ui: [] }); + setPluginsBackend(tauriPluginsBackend); + const run = vi.spyOn(commands, "pluginRunCommand").mockResolvedValue({ status: "ok", data: null }); + openUrl.mockClear(); + const dispose = startPluginDecorations(); + try { + await loadMarkdown(); + const card = await openResizeHover("[entry](#openidea-file/token-0)"); + vi.stubGlobal("__TAURI_INTERNALS__", {}); + card.querySelector("a")!.click(); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(run).not.toHaveBeenCalled(); + expect(openUrl).not.toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + dispose(); + setPluginsBackend(null); + usePlugins.setState({ plugins: [], ui: [] }); + vi.restoreAllMocks(); + } +}); + +it.each([null, " + model"])( + "keeps a text-origin conversation open throughout its annotated range (%s)", + async (after) => { + const code = "x".repeat(1000); + editor.view.dispatch({ changes: { from: 0, to: editor.view.state.doc.length, insert: code } }); + const longRange = { start: { line: 0, col: 0 }, end: { line: 0, col: code.length } }; + setPluginDecorations("test", [ + { + ...set(), + items: [{ range: longRange, style: "highlight", hover: null, after, markdownHover: "text conversation" }], + }, + ]); + vi.spyOn(editor.view, "coordsAtPos").mockImplementation((pos) => new DOMRect(pos, 10, 1, 10)); + vi.spyOn(editor.view, "posAtCoords").mockImplementation(({ x }) => Math.round(x)); + vi.spyOn(editor.view.scrollDOM, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 1200, 600)); + const line = editor.view.contentDOM.querySelector(".cm-line")!; + vi.useFakeTimers(); + try { + line.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 500, clientY: 15 })); + await vi.advanceTimersByTimeAsync(400); + } finally { + vi.useRealTimers(); + } + const card = document.querySelector(".cm-tooltip .cm-lsp-hover")!; + expect(card).not.toBeNull(); + vi.spyOn(card.closest(".cm-tooltip")!, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 30, 400, 100)); + line.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 510, clientY: 15 })); + expect(card.isConnected).toBe(true); + line.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1300, clientY: 15 })); + expect(card.isConnected).toBe(false); + }, +); + +it("does not strand a naturally opened second hover after crossing the popup gap", async () => { + const other = hoverTooltip(() => ({ + pos: 0, + end: 6, + create: () => { + const dom = document.createElement("div"); + dom.textContent = "natural provider"; + return { dom }; + }, + })); + editor.view.dispatch({ effects: StateEffect.appendConfig.of([other, tooltips({ parent: document.body })]) }); + const card = await openResizeHover(); + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + vi.spyOn(label, "getBoundingClientRect").mockReturnValue(new DOMRect(400, 380, 100, 20)); + expect(editor.view.state.field(other.active)).toHaveLength(1); + editor.view.dom.dispatchEvent( + new MouseEvent("mouseleave", { relatedTarget: document.body, clientX: 450, clientY: 370 }), + ); + expect(card.isConnected).toBe(true); + card.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 450, clientY: 320 })); + card + .closest(".cm-tooltip")! + .dispatchEvent(new MouseEvent("mouseleave", { relatedTarget: document.body, clientX: 10, clientY: 10 })); + document.body.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 10, clientY: 10 })); + expect(card.isConnected).toBe(false); + expect(editor.view.state.field(other.active)).toHaveLength(0); +}); + +it("uses the rich model label rather than a plain annotation at the same offset", async () => { + setPluginDecorations("test", [ + { + ...set(), + items: [ + { range, style: "highlight", hover: null, after: "plain note", markdownHover: null }, + { range, style: "highlight", hover: null, after: " + model", markdownHover: "conversation" }, + ], + }, + ]); + const spans = [...editor.view.dom.querySelectorAll("span")]; + const plain = spans.find((span) => span.textContent === "plain note")!; + const label = spans.find((span) => span.textContent === " + model")!; + vi.spyOn(plain, "getBoundingClientRect").mockReturnValue(new DOMRect(200, 300, 100, 20)); + vi.spyOn(label, "getBoundingClientRect").mockReturnValue(new DOMRect(800, 300, 100, 20)); + vi.useFakeTimers(); + try { + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 850, clientY: 310 })); + await vi.advanceTimersByTimeAsync(400); + const tooltip = editor.view.state.facet(showTooltip)[0]!; + expect(getTooltip(editor.view, tooltip)!.getCoords!(tooltip.pos).left).toBe(800); + } finally { + vi.useRealTimers(); + } +}); + +it("does not select a conversation when identical model labels make the anchor ambiguous", async () => { + const item = { range, style: "highlight", hover: null, after: " + model", markdownHover: "first conversation" }; + setPluginDecorations("test", [{ ...set(), items: [item] }]); + setPluginDecorations("second", [{ ...set(), items: [{ ...item, markdownHover: "second conversation" }] }]); + vi.useFakeTimers(); + try { + const label = [...editor.view.dom.querySelectorAll("span")].find((span) => span.textContent === " + model")!; + label.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 1, clientY: 1 })); + await vi.advanceTimersByTimeAsync(400); + expect(document.querySelector(".cm-tooltip .cm-lsp-hover")).toBeNull(); + } finally { + vi.useRealTimers(); + setPluginDecorations("second", []); + } +}); + +it("withdraws a removed conversation without hiding another provider", async () => { + const other = hoverTooltip(() => ({ + pos: 0, + end: 6, + create: () => { + const dom = document.createElement("div"); + dom.textContent = "remaining provider"; + return { dom }; + }, + })); + editor.view.dispatch({ effects: StateEffect.appendConfig.of(other) }); + const card = await openResizeHover(); + expect(editor.view.state.field(other.active)).toHaveLength(1); + setPluginDecorations("test", []); + expect(card.isConnected).toBe(false); + expect(editor.view.state.field(other.active)).toHaveLength(1); + expect(document.body.textContent).toContain("remaining provider"); +}); + it("names the language server of an lsp grant in consent", () => { const description = capabilityDescription({ id: "lsp:phoxite", diff --git a/src/features/plugins/decorationHover.module.css b/src/features/plugins/decorationHover.module.css new file mode 100644 index 0000000000..9970c887be --- /dev/null +++ b/src/features/plugins/decorationHover.module.css @@ -0,0 +1,188 @@ +/* Transfer CodeMirror's available-height cap without changing mixed hover groups. */ +:global(.cm-tooltip):has(> .card:global(.cm-lsp-hover):only-child) { + display: flex; + flex-direction: column; +} + +.card:global(.cm-lsp-hover):global(.cm-tooltip), +:global(.cm-tooltip) .card:global(.cm-lsp-hover) { + box-sizing: border-box; + display: flex; + flex-direction: column; + width: min(580px, calc(100vw - var(--space-3) * 2)); + min-width: 0; + min-height: 0; + max-width: calc(100vw - var(--space-3) * 2); + max-height: min(380px, calc(100vh - var(--space-3) * 2)); + overflow: hidden; + padding: 0; + border-radius: var(--radius-popup); +} + +:global(.cm-tooltip) .card:global(.cm-lsp-hover) { + position: relative; +} + +.card:global(.cm-lsp-hover):global(.cm-tooltip)[data-resized], +:global(.cm-tooltip) .card:global(.cm-lsp-hover)[data-resized] { + max-height: calc(100vh - var(--space-3) * 2); +} + +.card:global(.cm-lsp-hover) .content { + box-sizing: border-box; + flex: 1; + min-width: 0; + min-height: 0; + max-width: 100%; + overflow-x: hidden; + overflow-y: auto; + scrollbar-width: none; + padding: var(--space-3) var(--space-4); + font-family: var(--font-ui); + font-size: var(--fs-ui); + line-height: 1.55; + color: var(--fg-strong); + white-space: normal; + overflow-wrap: anywhere; + word-break: normal; +} + +.card:global(.cm-lsp-hover) .content::-webkit-scrollbar { + display: none; + width: 0; + height: 0; +} + +.card:global(.cm-lsp-hover) .content > :first-child { + margin-top: 0; +} + +.card:global(.cm-lsp-hover) .content > :last-child { + margin-bottom: 0; +} + +.card:global(.cm-lsp-hover) .content :is(pre, code) { + box-sizing: border-box; + min-width: 0; + max-width: 100%; + font-family: var(--openidea-editor-font, var(--font-mono)); + white-space: pre-wrap; + overflow-wrap: anywhere; + word-break: normal; +} + +.card:global(.cm-lsp-hover) .content pre { + margin: var(--space-2) 0; + padding: var(--space-2); + background: var(--bg-popup-inline, var(--bg-elev)); + border-radius: var(--radius-small); +} + +.card:global(.cm-lsp-hover) .content table { + box-sizing: border-box; + width: 100%; + max-width: 100%; + table-layout: fixed; + border-collapse: collapse; +} + +.card:global(.cm-lsp-hover) .content :is(th, td) { + min-width: 0; + padding: var(--space-2); + border: 1px solid var(--border-strong); + white-space: normal; + overflow-wrap: anywhere; +} + +.card:global(.cm-lsp-hover) .content blockquote { + box-sizing: border-box; + min-width: 0; + max-width: 100%; + margin: var(--space-2) 0; + padding-left: var(--space-3); + border-left: 1px solid var(--border-strong); + color: var(--fg-muted); +} + +.card:global(.cm-lsp-hover) .content hr { + margin: var(--space-3) 0; + border: 0; + border-top: 1px solid var(--border-popup); +} + +.card:global(.cm-lsp-hover) .content img { + max-width: 100%; + height: auto; +} + +.card:global(.cm-lsp-hover) .resizeHandle { + position: absolute; + z-index: 1; + box-sizing: border-box; + display: block; + min-width: 0; + min-height: 0; + margin: 0; + padding: 0; + border: 0; + border-radius: var(--radius-small); + background: none; + color: var(--fg-muted); + appearance: none; + touch-action: none; +} + +.card:global(.cm-lsp-hover) .resizeHandle:is([data-edge="n"], [data-edge="s"]) { + right: 0; + left: 0; + height: var(--space-2); + cursor: ns-resize; +} + +.card:global(.cm-lsp-hover) .resizeHandle[data-edge="n"] { + top: 0; +} + +.card:global(.cm-lsp-hover) .resizeHandle[data-edge="s"] { + bottom: 0; +} + +.card:global(.cm-lsp-hover) .resizeHandle:is([data-edge="e"], [data-edge="w"]) { + top: 0; + bottom: 0; + width: var(--space-2); + cursor: ew-resize; +} + +.card:global(.cm-lsp-hover) .resizeHandle[data-edge="e"] { + right: 0; +} + +.card:global(.cm-lsp-hover) .resizeHandle[data-edge="w"] { + left: 0; +} + +.card:global(.cm-lsp-hover) .resizeHandle[data-edge="se"] { + right: 0; + bottom: 0; + z-index: 2; + width: var(--space-4); + height: var(--space-4); + cursor: nwse-resize; +} + +.card:global(.cm-lsp-hover) .resizeHandle[data-edge="se"]::after { + position: absolute; + right: calc(var(--space-2) / 2); + bottom: calc(var(--space-2) / 2); + width: var(--space-2); + height: var(--space-2); + border-right: 1px solid var(--border-strong); + border-bottom: 1px solid var(--border-strong); + content: ""; +} + +.card:global(.cm-lsp-hover) :is(.content, .resizeHandle):focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: -2px; +} diff --git a/src/features/plugins/decorationHover.ts b/src/features/plugins/decorationHover.ts new file mode 100644 index 0000000000..2412e6c815 --- /dev/null +++ b/src/features/plugins/decorationHover.ts @@ -0,0 +1,238 @@ +import { Direction, repositionTooltips, type EditorView, type Rect, type TooltipView } from "@codemirror/view"; +import { hoverCard } from "@/editor/lsp/hover"; +import { tx } from "@/platform/i18n"; +import { lockDragCursor } from "@/ui/dragCursor"; +import styles from "./decorationHover.module.css"; + +type Edge = "n" | "e" | "s" | "w" | "se"; +type Bounds = Pick; + +/** Keep sizing local to plugin cards; CodeMirror still owns placement and dismissal. */ +export function resizableDecorationHover( + view: EditorView, + markdown: HTMLElement, + options: { + anchor?: () => HTMLElement | null; + position: number; + close: () => void; + containsSource: (event: MouseEvent) => boolean; + }, +): TooltipView & { content: HTMLElement } { + const content = document.createElement("div"); + content.className = styles.content!; + content.tabIndex = 0; + content.setAttribute("role", "region"); + content.setAttribute("aria-label", tx("Hover card")); + content.append(markdown); + const dom = hoverCard([content]); + dom.classList.add(styles.card!); + const win = dom.ownerDocument.defaultView!; + const offset = { x: 0, y: 0 }; + let bounds: Bounds | null = null; + let chrome = { width: 0, height: 0 }; + let above = true; + let disposed = false; + let stopDrag: (() => void) | undefined; + + const anchorRect = () => + options.anchor ? options.anchor()?.getBoundingClientRect() : view.coordsAtPos(options.position); + + const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(value, max)); + const limits = () => { + const margin = Number.parseFloat(win.getComputedStyle(dom).getPropertyValue("--space-3")) || 12; + return { + margin, + width: Math.max(1, win.innerWidth - margin * 2), + height: Math.max(1, win.innerHeight - margin * 2), + }; + }; + const apply = (next: Bounds) => { + if (disposed) return; + const { margin, width: maxWidth, height: maxHeight } = limits(); + const width = clamp(next.width, Math.min(240, maxWidth), maxWidth); + const height = clamp(next.height, Math.min(120, maxHeight), maxHeight); + bounds = { + left: clamp(next.left, margin, win.innerWidth - margin - width), + top: clamp(next.top, margin, win.innerHeight - margin - height), + width, + height, + }; + dom.dataset.resized = ""; + dom.style.width = `${Math.max(1, width - chrome.width)}px`; + dom.style.height = `${Math.max(1, height - chrome.height)}px`; + repositionTooltips(view); + }; + const measure = () => { + const surface = dom.closest(".cm-tooltip") ?? dom; + const rect = surface.getBoundingClientRect(); + const card = dom.getBoundingClientRect(); + chrome = { width: Math.max(0, rect.width - card.width), height: Math.max(0, rect.height - card.height) }; + above = surface.classList.contains("cm-tooltip-above"); + return rect; + }; + const resize = (edge: Edge, start: Bounds, dx: number, dy: number) => { + const { margin, width, height } = limits(); + const minWidth = Math.min(240, width), + minHeight = Math.min(120, height); + let left = start.left, + top = start.top; + let right = left + start.width, + bottom = top + start.height; + if (edge === "w") left = clamp(left + dx, margin, right - minWidth); + if (edge === "n") top = clamp(top + dy, margin, bottom - minHeight); + if (edge.includes("e")) right = clamp(right + dx, left + minWidth, win.innerWidth - margin); + if (edge.includes("s")) bottom = clamp(bottom + dy, top + minHeight, win.innerHeight - margin); + apply({ left, top, width: right - left, height: bottom - top }); + }; + const labels = { + n: tx("Resize hover card from the top"), + e: tx("Resize hover card from the right"), + s: tx("Resize hover card from the bottom"), + w: tx("Resize hover card from the left"), + se: tx("Resize hover card from the corner"), + }; + for (const edge of ["n", "e", "s", "w", "se"] as const) { + const handle = document.createElement("button"); + handle.type = "button"; + handle.className = styles.resizeHandle!; + handle.dataset.edge = edge; + handle.setAttribute("aria-label", labels[edge]); + handle.addEventListener("pointerdown", (event) => { + if (disposed || event.button !== 0 || event.isPrimary === false) return; + event.preventDefault(); + event.stopPropagation(); + stopDrag?.(); + const start = measure(); + const releaseCursor = lockDragCursor( + edge === "se" ? "nwse-resize" : edge === "e" || edge === "w" ? "ew-resize" : "ns-resize", + ); + const move = (e: PointerEvent) => { + if (e.pointerId !== event.pointerId) return; + if (!(e.buttons & 1)) return finish(); + resize(edge, start, e.clientX - event.clientX, e.clientY - event.clientY); + }; + const end = (e: PointerEvent) => { + if (e.pointerId === event.pointerId) finish(); + }; + const key = (e: KeyboardEvent) => { + if (e.key !== "Escape") return; + e.preventDefault(); + e.stopPropagation(); + finish(); + }; + const finish = () => { + win.removeEventListener("pointermove", move); + win.removeEventListener("pointerup", end); + win.removeEventListener("pointercancel", end); + win.removeEventListener("blur", finish); + win.removeEventListener("keydown", key, true); + handle.removeEventListener("lostpointercapture", end); + if (handle.hasPointerCapture?.(event.pointerId)) handle.releasePointerCapture(event.pointerId); + releaseCursor(); + stopDrag = undefined; + }; + stopDrag = finish; + win.addEventListener("pointermove", move); + win.addEventListener("pointerup", end); + win.addEventListener("pointercancel", end); + win.addEventListener("blur", finish); + win.addEventListener("keydown", key, true); + handle.addEventListener("lostpointercapture", end); + handle.setPointerCapture?.(event.pointerId); + }); + handle.addEventListener("keydown", (event) => { + if (disposed || stopDrag) return; + const step = event.shiftKey ? 32 : 8; + const dx = event.key === "ArrowLeft" ? -step : event.key === "ArrowRight" ? step : 0; + const dy = event.key === "ArrowUp" ? -step : event.key === "ArrowDown" ? step : 0; + if ( + !( + (dx && (edge === "e" || edge === "w" || edge === "se")) || + (dy && (edge === "n" || edge === "s" || edge === "se")) + ) + ) + return; + event.preventDefault(); + event.stopPropagation(); + resize(edge, measure(), dx, dy); + }); + dom.append(handle); + } + const contains = (rect: Rect, x: number, y: number) => + x >= rect.left - 4 && x <= rect.right + 4 && y >= rect.top - 4 && y <= rect.bottom + 4; + const bridge = (a: Rect, b: Rect, x: number, y: number) => { + if (a.bottom > b.top || y < a.bottom - 4 || y > b.top + 4) return false; + const fraction = a.bottom === b.top ? 0.5 : clamp((y - a.bottom) / (b.top - a.bottom), 0, 1); + return x >= a.left + (b.left - a.left) * fraction - 4 && x <= a.right + (b.right - a.right) * fraction + 4; + }; + const transpose = (rect: Rect): Rect => ({ left: rect.top, right: rect.bottom, top: rect.left, bottom: rect.right }); + const keepOpen = (event: MouseEvent) => { + if (stopDrag || options.containsSource(event)) return true; + const target = event.type === "mouseleave" ? event.relatedTarget : event.target; + if (target instanceof Node && (dom.contains(target) || options.anchor?.()?.contains(target))) return true; + const anchor = anchorRect(); + if (!anchor) return false; + const surface = (dom.closest(".cm-tooltip") ?? dom).getBoundingClientRect(); + const { clientX: x, clientY: y } = event; + return ( + contains(anchor, x, y) || + contains(surface, x, y) || + bridge(anchor, surface, x, y) || + bridge(surface, anchor, x, y) || + bridge(transpose(anchor), transpose(surface), y, x) || + bridge(transpose(surface), transpose(anchor), y, x) + ); + }; + // The provider is explicitly activated; observe its lifetime without intercepting other providers. + const moveOver = (event: MouseEvent) => { + if (!keepOpen(event)) options.close(); + }; + const clickOutside = (event: PointerEvent) => { + if (!(event.target instanceof Node) || (!dom.contains(event.target) && !options.anchor?.()?.contains(event.target))) + options.close(); + }; + const closeOnEscape = (event: KeyboardEvent) => { + if (event.key === "Escape") options.close(); + }; + win.addEventListener("mousemove", moveOver, true); + win.addEventListener("pointerdown", clickOutside, true); + win.addEventListener("keydown", closeOnEscape, true); + win.addEventListener("blur", options.close); + dom.ownerDocument.documentElement.addEventListener("mouseleave", options.close); + + const fitViewport = () => { + stopDrag?.(); + if (bounds) apply(bounds); + }; + win.addEventListener("resize", fitViewport); + return { + dom, + content, + offset, + resize: false, + getCoords: () => { + const anchor = anchorRect(); + if (!anchor) { + // Keep unrendered anchors clipped while satisfying TooltipView's non-null contract. + const top = view.scrollDOM.getBoundingClientRect().top - 1; + return { left: 0, right: 0, top, bottom: top }; + } + if (bounds) { + offset.x = + view.textDirection === Direction.RTL ? anchor.left - bounds.width - bounds.left : bounds.left - anchor.left; + offset.y = above ? anchor.top - bounds.top - bounds.height : bounds.top - anchor.bottom; + } + return anchor; + }, + destroy: () => { + disposed = true; + stopDrag?.(); + win.removeEventListener("resize", fitViewport); + win.removeEventListener("mousemove", moveOver, true); + win.removeEventListener("pointerdown", clickOutside, true); + win.removeEventListener("keydown", closeOnEscape, true); + win.removeEventListener("blur", options.close); + dom.ownerDocument.documentElement.removeEventListener("mouseleave", options.close); + }, + }; +} diff --git a/src/features/plugins/decorations.module.css b/src/features/plugins/decorations.module.css index 2e096092e3..c749553c81 100644 --- a/src/features/plugins/decorations.module.css +++ b/src/features/plugins/decorations.module.css @@ -100,3 +100,10 @@ .after .strikethrough { text-decoration: none; } + +/* A highlighted label carries emphasis; the range background stays on the text. */ +.after .highlight { + background: none; + color: var(--accent); + font-weight: 600; +} diff --git a/src/features/plugins/decorations.ts b/src/features/plugins/decorations.ts index dcf07655d5..7af8333f22 100644 --- a/src/features/plugins/decorations.ts +++ b/src/features/plugins/decorations.ts @@ -1,9 +1,21 @@ import { StateEffect, StateField, type Text } from "@codemirror/state"; -import { Decoration, EditorView, WidgetType, type DecorationSet as CmDecorations } from "@codemirror/view"; +import { + Decoration, + EditorView, + WidgetType, + hoverTooltip, + closeHoverTooltip, + activateHover, + type DecorationSet as CmDecorations, + type Tooltip, +} from "@codemirror/view"; import type { DecorationSet, Range } from "@/bindings"; import { registerEditorContribution, useEditorRegistry, type EditorDocContext } from "@/editor/api"; +import { resizableDecorationHover } from "./decorationHover"; +import { highlightInto, loadMarkdown, markupToHtml, renderMarkup } from "@/editor/lsp/markdown"; import { foldChipWidth } from "@/editor/core/cm/folding"; import { commands, isTauri } from "@/platform/ipc"; +import { logError } from "@/platform/errorLog"; import { useProject } from "@/platform/project"; import { addPathIconProvider, bumpFileIconRevision } from "@/ui"; import { setFileDecorations, type FileDecoration } from "@/workbench/contributions"; @@ -106,6 +118,7 @@ export function setPluginDecorations(plugin: string, sets: DecorationSet[]) { versions.set(plugin, (versions.get(plugin) ?? 0) + 1); snapshots.set(plugin, sets); updateTree(plugin, sets); + refreshOpenHovers(plugin); for (const editor of useEditorRegistry.getState().editors) editor.view.dispatch({ effects: refresh.of(null) }); } @@ -129,11 +142,17 @@ class AfterText extends WidgetType { readonly text: string, readonly style: string, readonly hover: string | null, + readonly markdown: string | null, ) { super(); } override eq(other: AfterText) { - return this.text === other.text && this.style === other.style && this.hover === other.hover; + return ( + this.text === other.text && + this.style === other.style && + this.hover === other.hover && + this.markdown === other.markdown + ); } /** * Line-end annotations stack left to right: the code-vision git hint, every plugin message on @@ -175,7 +194,8 @@ class AfterText extends WidgetType { const text = document.createElement("span"); text.className = `${styles.afterInner ?? ""} ${this.style}`; text.textContent = this.text; - if (this.hover) text.title = this.hover; + // The Markdown hover card replaces the native tooltip; two would stack. + if (this.hover && !this.markdown) text.title = this.hover; span.appendChild(text); // The element is only measurable once CodeMirror has inserted it: defer to the next task, not a // nested frame, so a widget that goes away first simply skips. @@ -195,10 +215,128 @@ class AfterText extends WidgetType { } } +/** A Markdown hover placed on a range (and its `after` label). */ +interface PlacedHover { + plugin: string; + path: string; + range: Range; + from: number; + to: number; + after: string | null; + markdown: string; +} + +/** A hover card that is open now; refreshed when its plugin pushes new data. */ +interface OpenHover { + plugin: string; + path: string; + range: Range; + after: string | null; + close: () => void; + dom: HTMLElement; + uiMode: EditorDocContext["uiMode"]; +} + +const openHovers = new Set(); + +function sameRange(a: Range, b: Range) { + return ( + a.start.line === b.start.line && a.start.col === b.start.col && a.end.line === b.end.line && a.end.col === b.end.col + ); +} + +/** The conversation a plugin now has for an open card, if it is still there. */ +function refreshedMarkdown(card: OpenHover) { + for (const set of currentSets(snapshots.get(card.plugin) ?? [], false)) + if (!set.tree && set.path === card.path) + for (const item of set.items) + if ( + item.markdownHover && + Object.hasOwn(colors, item.style) && + item.after === card.after && + sameRange(item.range, card.range) + ) + return item.markdownHover; + return null; +} + +/** Plugin Markdown has no authority to load resources from the workbench. */ +function withoutPluginResources(html: string): string { + // Template contents are inert: strip resources before they enter the rendered DOM. + const template = document.createElement("template"); + template.innerHTML = html; + for (const element of template.content.querySelectorAll("img, picture, audio, video, source, track")) + element.remove(); + for (const element of template.content.querySelectorAll("[src], [srcset], [poster], [background]")) { + for (const attribute of ["src", "srcset", "poster", "background"]) element.removeAttribute(attribute); + } + return template.innerHTML; +} + +/** Keep the shared renderer's links/styles without its unfiltered async Markdown rewrite. */ +function renderPluginMarkdown(value: string, language: string | null): HTMLElement { + const dom = renderMarkup({ kind: "plaintext", value: "" }, language); + let rendered: string | undefined; + const update = () => { + const html = withoutPluginResources(markupToHtml({ kind: "markdown", value })); + if (html === rendered) return; + rendered = html; + dom.innerHTML = html; + for (const code of dom.querySelectorAll("pre > code")) { + const declared = [...code.classList].find((name) => name.startsWith("language-")); + const text = (code.textContent ?? "").replace(/\n+$/, ""); + code.textContent = text; + void highlightInto(code, text, declared?.slice("language-".length) ?? language); + } + }; + update(); + void loadMarkdown() + .then(update) + .catch((error: unknown) => logError("cannot render plugin Markdown", error)); + return dom; +} + +/** Replace the content of cards whose labels were published again. */ +function refreshOpenHovers(plugin: string) { + for (const card of openHovers) { + if (card.plugin !== plugin) continue; + const markdown = refreshedMarkdown(card); + if (markdown) card.dom.replaceChildren(renderPluginMarkdown(markdown, card.uiMode)); + else card.close(); + } +} + +interface PlacedDecorations { + decorations: CmDecorations; + hovers: PlacedHover[]; +} + export function decorationExtension(ctx: EditorDocContext) { - const build = (doc: Text): CmDecorations => { + const field = StateField.define({ + create: (state) => build(state.doc), + update: (value, tr) => { + if (tr.effects.some((e) => e.is(refresh))) return build(tr.state.doc); + if (tr.docChanged) + return { + decorations: value.decorations.map(tr.changes), + // Follow the same positions as the rendered labels: the mark starts + // after an insertion at its edge, and an after label tracks its text. + hovers: value.hovers.map((h) => ({ + ...h, + from: tr.changes.mapPos(h.from, 1), + to: tr.changes.mapPos(h.to, h.after ? 1 : -1), + })), + }; + // A caret move or a selection change must not drop the hover data. + return value; + }, + provide: (field) => EditorView.decorations.from(field, (value) => value.decorations), + }); + + const build = (doc: Text): PlacedDecorations => { const ranges = []; - for (const sets of snapshots.values()) + const hovers: PlacedHover[] = []; + for (const [plugin, sets] of snapshots) for (const set of currentSets(sets, false)) if (!set.tree && String(set.path) === String(ctx.path)) { for (const item of set.items) { @@ -207,12 +345,23 @@ export function decorationExtension(ctx: EditorDocContext) { const from = offset(doc, item.range.start), to = offset(doc, item.range.end); if (from == null || to == null || from > to) continue; + const markdown = item.markdownHover || null; + if (markdown) + hovers.push({ + plugin, + path: ctx.path, + range: item.range, + from, + to, + after: item.after, + markdown, + }); if (from < to) ranges.push( - Decoration.mark({ class: className, attributes: item.hover ? { title: item.hover } : {} }).range( - from, - to, - ), + Decoration.mark({ + class: className, + attributes: item.hover && !markdown ? { title: item.hover } : {}, + }).range(from, to), ); if (item.after) { // The message belongs at the line end even when the diagnostic's range ends @@ -220,18 +369,126 @@ export function decorationExtension(ctx: EditorDocContext) { // caret there; the inline blame steps past it, so: git hint | lens | blame. const end = doc.lineAt(to); ranges.push( - Decoration.widget({ widget: new AfterText(item.after, className, item.hover), side: 1 }).range(end.to), + Decoration.widget({ + widget: new AfterText(item.after, className, item.hover, markdown), + side: 1, + }).range(end.to), ); } } } - return Decoration.set(ranges, true); + return { decorations: Decoration.set(ranges, true), hovers }; + }; + + const tooltip: ReturnType = hoverTooltip( + markdownHover( + field, + ctx, + (view) => view.dispatch({ effects: closeHoverTooltip(tooltip) }), + (view, pos, side) => activateHover(view, pos, side, { tooltip }), + ), + { hideOnChange: true }, + ); + return [field, tooltip]; +} + +/** + * The decoration under the pointer, preferring an `after` label when the + * pointer is on its widget rather than on the decorated text. + */ +function markdownHover( + field: StateField, + ctx: EditorDocContext, + close: (view: EditorView) => void, + lock: (view: EditorView, pos: number, side: -1 | 1) => void, +) { + const active = new WeakMap(); + return (view: EditorView, pos: number, side: -1 | 1): Tooltip | null => { + const hovers = view.state.field(field).hovers; + // An after label is a widget at the line end, past the range when the + // annotation ends mid-line. + const labelPos = (h: PlacedHover) => (h.after ? view.state.doc.lineAt(h.to).to : null); + const candidates = hovers.filter((h) => (h.from <= pos && pos <= h.to) || pos === labelPos(h)); + const placed = candidates.find((h) => labelPos(h) === pos && side >= 0) ?? candidates[candidates.length - 1]; + if (!placed) return null; + const fromLabel = !!placed.after && labelPos(placed) === pos && side >= 0; + const current = active.get(view); + if ( + current?.placed.plugin === placed.plugin && + current.fromLabel === fromLabel && + sameRange(current.placed.range, placed.range) && + current.placed.after === placed.after + ) + return current.tooltip; + let label: HTMLElement | undefined; + let mounted = false; + const anchor = fromLabel + ? () => { + // The widget sits at the line end (AfterText), which can be past the + // range end when the annotation ends mid-line. + const labelPos = view.state.doc.lineAt(placed.to).to; + if (!label?.isConnected) { + const matches = [...view.dom.querySelectorAll(`.${styles.after}`)].filter( + (node) => node.textContent === placed.after && view.posAtDOM(node) === labelPos, + ); + label = matches.length === 1 ? matches[0] : undefined; + } + if (!label && mounted) + queueMicrotask(() => { + if (active.get(view)?.tooltip === tooltip) close(view); + }); + return label ?? null; + } + : undefined; + if (anchor && !anchor()) return null; + const tooltip: Tooltip = { + pos: fromLabel ? (labelPos(placed) ?? placed.to) : placed.from, + end: placed.to, + above: true, + create: () => { + const hover = resizableDecorationHover(view, renderPluginMarkdown(placed.markdown, ctx.uiMode), { + anchor, + position: fromLabel ? (labelPos(placed) ?? placed.to) : placed.from, + close: () => close(view), + containsSource: (event) => { + if (!(event.target instanceof Node) || !view.contentDOM.contains(event.target)) return false; + const at = view.posAtCoords({ x: event.clientX, y: event.clientY }); + return at != null && ((placed.from <= at && at <= placed.to) || at === labelPos(placed)); + }, + }); + const card: OpenHover = { + plugin: placed.plugin, + path: placed.path, + range: placed.range, + after: placed.after, + close: () => close(view), + dom: hover.content, + uiMode: ctx.uiMode, + }; + openHovers.add(card); + let live = true; + return { + ...hover, + mount: () => { + mounted = true; + // Activate only our provider, after CodeMirror finishes creating its tooltip views. + queueMicrotask(() => { + if (live) lock(view, pos, side); + }); + }, + destroy: () => { + live = false; + mounted = false; + hover.destroy?.(); + openHovers.delete(card); + if (active.get(view)?.tooltip === tooltip) active.delete(view); + }, + }; + }, + }; + active.set(view, { placed, fromLabel, tooltip }); + return tooltip; }; - return StateField.define({ - create: (state) => build(state.doc), - update: (value, tr) => (tr.effects.some((e) => e.is(refresh)) ? build(tr.state.doc) : value.map(tr.changes)), - provide: (field) => EditorView.decorations.from(field), - }); } /** Catch up editors and project trees opened after publication. */ @@ -258,7 +515,10 @@ export function startPluginDecorations(): () => void { for (const editor of useEditorRegistry.getState().editors) editor.view.dispatch({ effects: refresh.of(null) }); load(); }); - const off = registerEditorContribution({ id: "plugins.decorations", extensions: decorationExtension }); + const off = registerEditorContribution({ + id: "plugins.decorations", + extensions: decorationExtension, + }); load(); return () => { disposed = true; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 1d154df68c..17b9afcc88 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3936,5 +3936,11 @@ "Reload classes after compilation": "Reload classes after compilation", "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.": "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.", "Reload '{fileName}' into the running debug session?": "Reload '{fileName}' into the running debug session?", - "Tomcat classes updated": "Tomcat classes updated" + "Tomcat classes updated": "Tomcat classes updated", + "Hover card": "Hover card", + "Resize hover card from the top": "Resize hover card from the top", + "Resize hover card from the right": "Resize hover card from the right", + "Resize hover card from the bottom": "Resize hover card from the bottom", + "Resize hover card from the left": "Resize hover card from the left", + "Resize hover card from the corner": "Resize hover card from the corner" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 847a665c27..15111a94b1 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10169,5 +10169,11 @@ "Reload classes after compilation": "编译后重新加载类", "Reload changed classes into running Java debug sessions after Build Project, Build Module, or Recompile succeeds.": "在 Build Project、Build Module 或 Recompile 编译成功后,将修改的类重新加载到运行中的 Java 调试会话。", "Reload '{fileName}' into the running debug session?": "要将 '{fileName}' 重新加载到正在运行的调试会话中吗?", - "Tomcat classes updated": "Tomcat 类已更新" + "Tomcat classes updated": "Tomcat 类已更新", + "Hover card": "悬浮卡片", + "Resize hover card from the top": "从上边缘调整悬浮卡片大小", + "Resize hover card from the right": "从右边缘调整悬浮卡片大小", + "Resize hover card from the bottom": "从下边缘调整悬浮卡片大小", + "Resize hover card from the left": "从左边缘调整悬浮卡片大小", + "Resize hover card from the corner": "从角部调整悬浮卡片大小" } diff --git a/wit/decorations.wit b/wit/decorations.wit index e3ebf244f4..fbf5755f2e 100644 --- a/wit/decorations.wit +++ b/wit/decorations.wit @@ -9,11 +9,26 @@ interface decorations { use types.{error, range}; /// An editor annotation; after is plain text shown after the range. record decoration { range: range, style: string, hover: option, after: option } + /// An editor annotation whose hover is rendered as Markdown (API 1.16). + /// `hover` stays the plain-text fallback for hosts that do not render it. + record markdown-decoration { + range: range, + style: string, + hover: option, + after: option, + /// Markdown shown in the editor's hover card while the pointer rests on + /// the range or its after label. + markdown-hover: option, + } /// A project-tree annotation; badge is at most two Unicode characters. record file-decoration { badge: option, style: string, tooltip: option } /// Replace this set for a file. At most 10,000 items/file and 50 editor sets/plugin. /// Metadata is bounded to 4 MiB per plugin. Unknown styles are ignored. set: func(path: string, set-id: string, items: list) -> result<_, error>; + /// Like `set`, with each item's Markdown hover rendered as a hover card + /// (API 1.16). Same limits and set-id replacement rules as `set`; `clear` + /// removes a set regardless of which call created it. + set-markdown: func(path: string, set-id: string, items: list) -> result<_, error>; /// Remove this editor set from every file/project. clear: func(set-id: string) -> result<_, error>; /// Replace this set's tree annotation for a file; at most 50 tree sets/plugin. From 675e1ccd612fdb998817b0d90bcb04b304a1cc3f Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 03:59:40 +0800 Subject: [PATCH 037/104] fix(editor): show hovers on the first lines while the caret is further down (#5676) The sticky-scroll top scroll margin reserved the caret's enclosing header rows at all times. CodeMirror also treats that margin as covered when placing tooltips, so with the caret inside a method every hover on the first lines of a file (quick documentation, plugin decoration cards) was parked off screen though no sticky rows were showing. The caret's rows are now reserved only while the caret sits above where they would stick, which is when revealing it scrolls them in; otherwise the margin is the rows showing now. --- src/editor/core/cm/stickyScroll.test.ts | 21 +++++++++++++++---- src/editor/core/cm/stickyScroll.ts | 27 +++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/src/editor/core/cm/stickyScroll.test.ts b/src/editor/core/cm/stickyScroll.test.ts index e29c5df546..1525ef687d 100644 --- a/src/editor/core/cm/stickyScroll.test.ts +++ b/src/editor/core/cm/stickyScroll.test.ts @@ -7,7 +7,7 @@ import { languages } from "@codemirror/language-data"; import { completedSyntaxState } from "@/test/syntax"; import { BracketScanner, DEFAULT_RAINBOW_OPTIONS } from "./rainbowBrackets"; import { renderLineContent } from "./renderLineContent"; -import { selectedSpans, stickyMaxLines, stickyScroll, stickyTopMargin } from "./stickyScroll"; +import { selectedSpans, stickyMaxLines, stickyScroll, stickyScrollMargin, stickyTopMargin } from "./stickyScroll"; describe("selectedSpans", () => { // the sticky line `def run():` at 100..110 @@ -104,9 +104,22 @@ describe("sticky rows and scrolling the caret into view", () => { it("keeps room for the headers that would stick above the caret's line", () => { const v = view(doc.indexOf("target")); expect(stickyTopMargin(v)).toBe(3 * v.defaultLineHeight); - expect(v.state.facet(EditorView.scrollMargins).map((f) => f(v))).toContainEqual({ - top: 3 * v.defaultLineHeight, - }); + v.destroy(); + }); + + it("reserves the caret's rows only while the caret is above where they would stick", () => { + // The caret at 200 with three rows (60) to stick above it, nothing showing yet. + expect(stickyScrollMargin(200, 160, 60, 0)).toBe(60); + expect(stickyScrollMargin(200, 300, 60, 0)).toBe(60); + // Visible below them: only what sticks now covers the top, so hovers there still show. + expect(stickyScrollMargin(200, 0, 60, 0)).toBe(0); + expect(stickyScrollMargin(200, 100, 60, 40)).toBe(40); + expect(stickyScrollMargin(200, 160, 20, 40)).toBe(40); + }); + + it("covers nothing at the top of the file while the caret is further down", () => { + const v = view(doc.indexOf("target")); + expect(v.state.facet(EditorView.scrollMargins).map((f) => f(v))).toContainEqual({ top: 0 }); v.destroy(); }); diff --git a/src/editor/core/cm/stickyScroll.ts b/src/editor/core/cm/stickyScroll.ts index dbda72e8c1..36f29c468b 100644 --- a/src/editor/core/cm/stickyScroll.ts +++ b/src/editor/core/cm/stickyScroll.ts @@ -127,6 +127,10 @@ export function readEditorTopLayout(view: EditorView) { class StickyScroll { dom: HTMLElement; private lines: number[] = []; + /** Header rows showing now. */ + get rows(): number { + return this.lines.length; + } /** * Text and syntax tree the rows were rendered from (re-render when either changes), and * the document while bracket colours are on (an edit above may change their depth). @@ -368,8 +372,27 @@ export function stickyTopMargin(view: EditorView): number { return rows * view.defaultLineHeight; } -export const stickyScroll: Extension = ViewPlugin.fromClass(StickyScroll, { - provide: () => EditorView.scrollMargins.of((view) => ({ top: stickyTopMargin(view) })), +/** + * The editor's top scroll margin. CodeMirror also treats it as covered when placing tooltips, so + * the caret's rows are reserved only while the caret sits above where they would stick (revealing + * it then scrolls up and they appear); otherwise it is what sticks now. A caret deep in a method + * at the top of the file must not hide the hovers of its first lines. + */ +export function stickyScrollMargin(caretTop: number, visibleTop: number, reserve: number, shown: number): number { + return caretTop < visibleTop + reserve ? Math.max(reserve, shown) : shown; +} + +const stickyScrollPlugin: ViewPlugin = ViewPlugin.fromClass(StickyScroll, { + provide: () => + EditorView.scrollMargins.of((view) => { + const caretTop = view.lineBlockAt(view.state.selection.main.head).top; + // In document coordinates, like the caret's block. + const visibleTop = view.scrollDOM.getBoundingClientRect().top - view.documentTop; + const shown = (view.plugin(stickyScrollPlugin)?.rows ?? 0) * view.defaultLineHeight; + return { top: stickyScrollMargin(caretTop, visibleTop, stickyTopMargin(view), shown) }; + }), }); +export const stickyScroll: Extension = stickyScrollPlugin; + export { renderLineContent as renderContextLine }; From 7532ff30fd7f9262c5b20f056b876937a31557e0 Mon Sep 17 00:00:00 2001 From: Mansur Akhmadi Date: Wed, 25 Nov 2026 03:03:10 +0700 Subject: [PATCH 038/104] feat(debugger): Remove All Breakpoints In The Current File action (#5675) Remove All Breakpoints In The Current File (Debugger.RemoveAllBreakpointsInFile) removes the line breakpoints of the file in the active editor, plus the method breakpoints and field watchpoints whose gutter icon is in that file; other files, name-only method breakpoints and exception breakpoints stay. It is in Find Action with no default shortcut. Imported IDEA keymaps and IdeaVim :action now map Debugger.RemoveAllBreakpoints and Debugger.RemoveAllBreakpointsInFile. Closes #5674 Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com> --- docs/en/guide/debugging.mdx | 2 +- docs/zh/guide/debugging.mdx | 2 +- .../debugger/__tests__/actions.test.ts | 33 ++++++++++++++++++- src/features/debugger/actions.ts | 14 +++++++- src/features/debugger/breakpoints/special.ts | 7 ++++ src/features/debugger/breakpoints/store.ts | 4 +++ src/platform/ideaActions.ts | 2 ++ src/platform/ideaKeymap.test.ts | 9 +++++ src/platform/locales/text/zh.json | 1 + 9 files changed, 70 insertions(+), 4 deletions(-) diff --git a/docs/en/guide/debugging.mdx b/docs/en/guide/debugging.mdx index 15fceadc42..252db3969c 100644 --- a/docs/en/guide/debugging.mdx +++ b/docs/en/guide/debugging.mdx @@ -88,7 +88,7 @@ Method breakpoints and field watchpoints need an adapter that supports DAP funct ### The Breakpoints dialog -**View Breakpoints…** (`⌘⇧F8` / `Ctrl+Shift+F8`) lists every breakpoint in the project. From there you can enable, edit, remove and jump to breakpoints, toggle **Mute breakpoints** (skip all of them without removing them), and set exception filters. **Remove All Breakpoints** clears the list. +**View Breakpoints…** (`⌘⇧F8` / `Ctrl+Shift+F8`) lists every breakpoint in the project. From there you can enable, edit, remove and jump to breakpoints, toggle **Mute breakpoints** (skip all of them without removing them), and set exception filters. **Remove All Breakpoints** clears the list. **Remove All Breakpoints In The Current File** (Find Action) removes only the line, method and field breakpoints of the file in the active editor. Breakpoints are saved per project and kept across restarts. A breakpoint the adapter could not place is shown as unverified. diff --git a/docs/zh/guide/debugging.mdx b/docs/zh/guide/debugging.mdx index bd7667afb4..6eb616156c 100644 --- a/docs/zh/guide/debugging.mdx +++ b/docs/zh/guide/debugging.mdx @@ -90,7 +90,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`): ### 断点对话框 -**查看断点…**(`⌘⇧F8` / `Ctrl+Shift+F8`)列出项目中的所有断点。可以在这里启用、编辑、删除断点和跳转到断点位置,打开 **静音断点**(暂时跳过所有断点而不删除),以及设置异常过滤器。**移除所有断点** 会清空列表。 +**查看断点…**(`⌘⇧F8` / `Ctrl+Shift+F8`)列出项目中的所有断点。可以在这里启用、编辑、删除断点和跳转到断点位置,打开 **静音断点**(暂时跳过所有断点而不删除),以及设置异常过滤器。**移除所有断点** 会清空列表。**移除当前文件中的所有断点**(通过查找操作)只移除当前编辑器中文件的行断点、方法断点和字段监视点。 断点按项目保存,重启后仍然保留。适配器无法设置的断点会标为未验证。 diff --git a/src/features/debugger/__tests__/actions.test.ts b/src/features/debugger/__tests__/actions.test.ts index 265a99e258..2a881a09f7 100644 --- a/src/features/debugger/__tests__/actions.test.ts +++ b/src/features/debugger/__tests__/actions.test.ts @@ -85,7 +85,13 @@ import { useProject } from "@/platform/project"; import { provideNotificationService } from "@/workbench/contributions"; import { registerDebugActions } from "../actions"; import { breakpointsOf, loadBreakpoints, toggleBreakpoint } from "../breakpoints/store"; -import { loadSpecialBreakpoints, removeAllSpecial, useSpecialBreakpoints } from "../breakpoints/special"; +import { + addFieldWatchpoint, + addMethodBreakpoint, + loadSpecialBreakpoints, + removeAllSpecial, + useSpecialBreakpoints, +} from "../breakpoints/special"; import { publishContext, updateExecutionPoint, useExecutionPoint, useDebug, type DebugSession } from "../state"; import { useJsProfile, watchProfiledSessions } from "../js/profile"; import { focusDebugView, blurDebugView } from "../ui/focusedView"; @@ -488,6 +494,31 @@ describe("debugger actions (IDEA parity)", () => { expect(useSpecialBreakpoints.getState().fields).toEqual([]); }); + it("Remove All Breakpoints In The Current File removes only the active file's breakpoints", async () => { + toggleBreakpoint("/p/a.py", 0); + toggleBreakpoint("/p/a.py", 2); + toggleBreakpoint("/p/b.py", 0); + addMethodBreakpoint("run", { path: "/p/a.py", line: 1 }); + addMethodBreakpoint("main"); + addFieldWatchpoint({ dataId: "a.A#count", label: "count" }, { path: "/p/A.java", line: 2 }); + caret("/p/a.py", "python", "x = 1\ndef run():\n pass", 2); + + await executeAction("debug.removeAllBreakpointsInFile"); + expect(breakpointsOf("/p/a.py")).toEqual([]); + expect(breakpointsOf("/p/b.py")).toHaveLength(1); + expect(useSpecialBreakpoints.getState().methods.map((m) => m.name)).toEqual(["main"]); + expect(useSpecialBreakpoints.getState().fields).toHaveLength(1); + + // A watchpoint is removed with its file too; without an editor there is no file, so nothing goes. + caret("/p/A.java", "java", "package a;\nclass A {\n private int count;\n}", 0); + await executeAction("debug.removeAllBreakpointsInFile"); + expect(useSpecialBreakpoints.getState().fields).toEqual([]); + editor.current = null; + await executeAction("debug.removeAllBreakpointsInFile"); + expect(breakpointsOf("/p/b.py")).toHaveLength(1); + expect(useSpecialBreakpoints.getState().methods).toHaveLength(1); + }); + it("Attach to Process opens the popup and loads the process list", async () => { await executeAction("debug.attachToProcess"); await settle(); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index ad147600cd..15c0f35484 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -24,12 +24,13 @@ import { lineHasCode } from "./breakpoints/codeLines"; import { canPlaceBreakpoint } from "./breakpoints/languages"; import { removeAllBreakpoints, + removeFileBreakpoints, setMuted, toggleBreakpoint, toggleTemporaryBreakpoint, useBreakpoints, } from "./breakpoints/store"; -import { removeAllSpecial, specialAt, toggleFieldAt, toggleMethodAt } from "./breakpoints/special"; +import { removeAllSpecial, removeSpecialIn, specialAt, toggleFieldAt, toggleMethodAt } from "./breakpoints/special"; import { removeAllExceptionClasses } from "./breakpoints/exceptionClasses"; import { fieldAt, methodAt } from "./breakpoints/symbols"; import { toggleBreakpointSmart } from "./breakpoints/toggle"; @@ -1141,6 +1142,17 @@ export function registerDebugActions(): () => void { removeAllExceptionClasses(); }, }, + { + id: "debug.removeAllBreakpointsInFile", + title: "Remove All Breakpoints In The Current File", + category: "Debug", + run: () => { + const path = activeEditor()?.ctx.path; + if (!path) return; + removeFileBreakpoints(path); + removeSpecialIn(path); + }, + }, { id: "debug.evaluate", title: "Evaluate Expression…", diff --git a/src/features/debugger/breakpoints/special.ts b/src/features/debugger/breakpoints/special.ts index 873d057872..81aa819bae 100644 --- a/src/features/debugger/breakpoints/special.ts +++ b/src/features/debugger/breakpoints/special.ts @@ -221,6 +221,13 @@ export function removeAllSpecial() { setLists({ methods: [], fields: [] }); } +/** Removes the method breakpoints / watchpoints located in `path`. */ +export function removeSpecialIn(path: string) { + const { methods, fields } = useSpecialBreakpoints.getState(); + if (![...methods, ...fields].some((b) => b.path === path)) return; + setLists({ methods: methods.filter((m) => m.path !== path), fields: fields.filter((f) => f.path !== path) }); +} + /** Method breakpoints / watchpoints whose gutter icon is in `path`. */ export function specialAt(path: string): SpecialBreakpoint[] { const { methods, fields } = useSpecialBreakpoints.getState(); diff --git a/src/features/debugger/breakpoints/store.ts b/src/features/debugger/breakpoints/store.ts index d31b4634ea..a36b997d75 100644 --- a/src/features/debugger/breakpoints/store.ts +++ b/src/features/debugger/breakpoints/store.ts @@ -226,6 +226,10 @@ export function removeAllBreakpoints() { for (const path of Object.keys(useBreakpoints.getState().byFile)) setFile(path, []); } +export function removeFileBreakpoints(path: string) { + setFile(path, []); +} + /** Replaces a file's list after its lines moved with an edit (from the editor gutter). */ export function setFileBreakpoints(path: string, list: BreakpointEntry[]) { setFile(path, list); diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index 1531e3052c..55d5ae65ad 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -78,6 +78,8 @@ export const IDEA_ACTIONS: Readonly> = { Rerun: "run.rerun", ChooseRunConfiguration: "run.chooseConfig", ToggleLineBreakpoint: "debug.toggleBreakpoint", + "Debugger.RemoveAllBreakpoints": "debug.removeAllBreakpoints", + "Debugger.RemoveAllBreakpointsInFile": "debug.removeAllBreakpointsInFile", SaveAll: "file.save", ShowSettings: "file.settings", NewScratchFile: "file.newScratchFile", diff --git a/src/platform/ideaKeymap.test.ts b/src/platform/ideaKeymap.test.ts index f575475d3b..aefb69ec12 100644 --- a/src/platform/ideaKeymap.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -57,6 +57,15 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.unknownActions).toEqual([]); }); + it("maps Remove All Breakpoints and Remove All Breakpoints In The Current File", () => { + const k = parseIdeaKeymap( + ``, + ); + expect(k.overrides["debug.removeAllBreakpoints"]).toEqual([normalizeBinding("Shift+Meta+F9")]); + expect(k.overrides["debug.removeAllBreakpointsInFile"]).toEqual([normalizeBinding("Alt+Meta+F9")]); + expect(k.unknownActions).toEqual([]); + }); + it("rejects other XML", () => { expect(() => parseIdeaKeymap("")).toThrow(/keymap/); }); diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 15111a94b1..fd23d6e61a 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2965,6 +2965,7 @@ "Remove": "移除", "Remove All Bookmarks": "移除所有书签", "Remove All Breakpoints": "移除所有断点", + "Remove All Breakpoints In The Current File": "移除当前文件中的所有断点", "Remove Configuration": "移除配置", "Remove Data Source": "移除数据源", "Remove Data Source…": "移除数据源…", From af3e174702f48e2759f505d2b267fb5d8014de04 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 04:37:46 +0800 Subject: [PATCH 039/104] fix(java): apply the Eclipse plugin to the project in the Gradle classpath init script (#5677) Inside the Gradle classpath init script's closures a bare `apply plugin: 'eclipse'` resolves to the init script's own apply. On Gradle 7 the Eclipse plugin then can't get its project services (no IdeArtifactRegistry), applying java fails, and jdtls's Gradle import fails for every Gradle 7 project, leaving all Java files red. The script now calls project.apply; a test keeps bare apply calls out of it. Fixes #5669 --- crates/ide-sdk/src/apply.rs | 10 ++++++++++ crates/ide-sdk/src/gradle-classpath.init.gradle | 4 +++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index 791c8b4470..30b357aec9 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -2796,6 +2796,16 @@ mod maven_linkage_tests { assert!(nowhere.settings.is_none(), "no usable directory: the import runs without it"); } + #[test] + fn gradle_classpath_script_applies_plugins_to_the_project() { + // Inside the script's closures a bare `apply` is the init script's own: on Gradle 7 the + // Eclipse plugin then fails to start and the whole import fails. + let script = include_str!("gradle-classpath.init.gradle"); + let bare: Vec<&str> = script.lines().filter(|line| line.trim_start().starts_with("apply ")).collect(); + assert!(bare.is_empty(), "{bare:?}"); + assert!(script.contains("project.apply plugin: 'eclipse'")); + } + #[test] fn gradle_import_of_a_gradle_build_runs_on_the_project_jdk_like_the_ides_builds() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-sdk/src/gradle-classpath.init.gradle b/crates/ide-sdk/src/gradle-classpath.init.gradle index 68c89d4a37..60fc1e5cd7 100644 --- a/crates/ide-sdk/src/gradle-classpath.init.gradle +++ b/crates/ide-sdk/src/gradle-classpath.init.gradle @@ -3,7 +3,9 @@ // compile classpath names, so Java code sees the classes it compiles against. allprojects { plugins.withId('java') { - apply plugin: 'eclipse' + // `project.`: a bare `apply` in this closure is the init script's own (Gradle 7 fails to create the + // plugin then: no IdeArtifactRegistry service). + project.apply plugin: 'eclipse' eclipse.classpath.file.whenMerged { classpath -> def projectOf = { dep -> def path From 3927e70476f343a27fba4b69950e8a3049b9bbcd Mon Sep 17 00:00:00 2001 From: Vladislav Kuzmin <67874880+principalwater@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:43:07 +0300 Subject: [PATCH 040/104] fix(run): scope JVM thread-dump test helpers to Unix (#5672) The thread-dump tests' helpers in ide-jvm-attach and ide-host use Unix-only APIs, so the Windows test build failed to compile on main. Gate the helpers and the tests that use them to Unix. Closes #5671 Co-authored-by: principalwater <67874880+principalwater@users.noreply.github.com> --- crates/ide-host/src/ops/thread_dump.rs | 1 + crates/ide-jvm-attach/src/listener.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ide-host/src/ops/thread_dump.rs b/crates/ide-host/src/ops/thread_dump.rs index 82cbbc9fd7..eec90236aa 100644 --- a/crates/ide-host/src/ops/thread_dump.rs +++ b/crates/ide-host/src/ops/thread_dump.rs @@ -68,6 +68,7 @@ mod tests { panic!("not reached") } + #[cfg(unix)] fn proc(pid: u32, ppid: u32, command: &str) -> ProcEntry { ProcEntry { pid, ppid, command: command.into() } } diff --git a/crates/ide-jvm-attach/src/listener.rs b/crates/ide-jvm-attach/src/listener.rs index e4acbe8718..9e6ba26022 100644 --- a/crates/ide-jvm-attach/src/listener.rs +++ b/crates/ide-jvm-attach/src/listener.rs @@ -3,7 +3,7 @@ use std::time::Duration; use crate::socket::AttachError; #[cfg(unix)] use crate::socket::{check_socket, has_listener, has_listener_at, socket_path, temp_dir}; -#[cfg(any(target_os = "linux", target_os = "macos", test))] +#[cfg(any(target_os = "linux", target_os = "macos", all(unix, test)))] use std::time::UNIX_EPOCH; #[cfg(unix)] use std::{ @@ -204,7 +204,7 @@ fn process_start(_pid: u32) -> Option { /// `/proc//stat` field 22 is the start in clock ticks since boot; `btime` in `/proc/stat` /// is the boot time in seconds since the epoch. -#[cfg(any(target_os = "linux", test))] +#[cfg(any(target_os = "linux", all(unix, test)))] fn start_from_proc(stat: &str, system: &str, ticks_per_sec: u64) -> Option { // The command name (field 2) may contain spaces and parentheses; the fields after it start at 3. let ticks: u64 = stat.rsplit_once(')')?.1.split_whitespace().nth(22 - 3)?.parse().ok()?; From d269570f72c69a493fbe5070b732571e03dad336 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 04:51:37 +0800 Subject: [PATCH 041/104] =?UTF-8?q?feat(database):=20freeze=20the=20result?= =?UTF-8?q?=20grid's=20row=20numbers=20and=20add=20rows=20with=20=E2=8C=98?= =?UTF-8?q?/Ctrl-click=20(#5678)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The row-number column scrolled away with the data when a wide result was scrolled sideways. It is now sticky at the left edge (header included) and drawn above the cells passing under it. Row numbers also select like a row header: ⌘/Ctrl-click adds or removes a row, Shift-click extends the lead range, dragging down the numbers selects whole rows. Copy, Copy Rows, the row context menu and the Aggregates panel use every selected row. Fixes #5527 --- e2e/databaseFrozenRowNumbers.spec.ts | 70 +++++++++++++++++++++ src/features/database/DataView.tsx | 5 +- src/features/database/Database.module.css | 7 +++ src/features/database/Grid.test.tsx | 42 +++++++++++++ src/features/database/Grid.tsx | 77 +++++++++++++++++++---- 5 files changed, 186 insertions(+), 15 deletions(-) create mode 100644 e2e/databaseFrozenRowNumbers.spec.ts diff --git a/e2e/databaseFrozenRowNumbers.spec.ts b/e2e/databaseFrozenRowNumbers.spec.ts new file mode 100644 index 0000000000..dc1874dc47 --- /dev/null +++ b/e2e/databaseFrozenRowNumbers.spec.ts @@ -0,0 +1,70 @@ +import { expect, test } from "./fixtures"; + +test("result grid keeps row numbers at the left edge while scrolling sideways", async ({ workbench: page }) => { + await page.evaluate(async () => { + const storePath = "/src/features/database/store.ts"; + const contributionsPath = "/src/workbench/contributions.ts"; + const { useDatabase, RESULTS_VIEW } = await import(storePath); + const { showServiceView } = await import(contributionsPath); + const text = "SELECT * FROM wide"; + const columns = Array.from({ length: 30 }, (_, i) => ({ name: `column_${i}`, typeName: "TEXT" })); + useDatabase.setState({ + loaded: true, + sources: [{ id: "wide", name: "Wide", driver: "postgres", readOnly: true }], + consoles: { "wide-console.sql": "wide" }, + results: [ + { + id: 1, + title: "Result 1", + path: "wide-console.sql", + sourceId: "wide", + outcome: { + statement: { text, from: 0, to: text.length }, + error: null, + result: { + statement: text, + columns, + rows: Array.from({ length: 3 }, (_, r) => columns.map((_, c) => `value ${r}:${c} padded out`)), + affected: null, + hasMore: false, + elapsedMs: 1, + executionMs: 1, + }, + }, + page: 0, + pageSize: 500, + }, + ], + activeResult: 1, + }); + showServiceView(RESULTS_VIEW); + }); + const grid = page.getByRole("grid", { name: "Result 1", exact: true }); + await expect(grid.getByRole("gridcell").first()).toBeVisible(); + const offsets = () => + grid.evaluate((el) => { + const left = el.getBoundingClientRect().left; + const rows = [...el.querySelectorAll('[role="row"]')]; + return rows.map((row) => Math.round(row.firstElementChild!.getBoundingClientRect().left - left)); + }); + expect(await offsets()).toEqual([0, 0, 0, 0]); + await grid.evaluate((el) => { + el.scrollLeft = 1500; + }); + expect(await grid.evaluate((el) => el.scrollLeft)).toBeGreaterThan(1000); + // Header and body row numbers stay put; the first data column has scrolled away under them. + expect(await offsets()).toEqual([0, 0, 0, 0]); + const firstCell = await grid + .getByRole("gridcell") + .first() + .evaluate((el) => el.getBoundingClientRect().right); + const gridLeft = await grid.evaluate((el) => el.getBoundingClientRect().left); + expect(firstCell).toBeLessThan(gridLeft); + // The number is drawn on top, not under the cells scrolled beneath it. + const hit = await grid.evaluate((el) => { + const number = el.querySelectorAll('[role="row"]')[1]!.firstElementChild!; + const box = number.getBoundingClientRect(); + return document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2) === number; + }); + expect(hit).toBe(true); +}); diff --git a/src/features/database/DataView.tsx b/src/features/database/DataView.tsx index f52cadf36c..571d387c6c 100644 --- a/src/features/database/DataView.tsx +++ b/src/features/database/DataView.tsx @@ -741,8 +741,9 @@ function ValueView(props: { function AggregatesView({ range, value }: { range: GridRange; value: (row: number, col: number) => Cell }) { const cells: Cell[] = []; - for (let r = range.top; r <= range.bottom; r++) - for (let c = range.left; c <= range.right; c++) cells.push(value(r, c)); + const rows = new Set(range.rows); + for (let r = range.top; r <= range.bottom; r++) rows.add(r); + for (const r of rows) for (let c = range.left; c <= range.right; c++) cells.push(value(r, c)); const a = aggregates(cells); const show = (v: number | string | null) => (v === null ? "—" : typeof v === "number" ? formatNumber(v) : v); return ( diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index d93528b0da..3b85528a23 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -70,6 +70,10 @@ cursor: col-resize; } .rowNumber { + /* Frozen at the left edge: only vertical scrolling moves the numbers. */ + position: sticky; + left: 0; + z-index: 1; display: flex; align-items: center; justify-content: flex-end; @@ -80,6 +84,9 @@ border-bottom: 1px solid var(--border); user-select: none; } +.rowNumberSelected { + color: var(--fg-line-number-current); +} .cell { display: flex; align-items: center; diff --git a/src/features/database/Grid.test.tsx b/src/features/database/Grid.test.tsx index 2d661b2f82..93231b4a6d 100644 --- a/src/features/database/Grid.test.tsx +++ b/src/features/database/Grid.test.tsx @@ -92,6 +92,48 @@ describe("database grid", () => { expect(writeText).toHaveBeenCalledWith("one\ttwo\nthree\tfour"); expect(globalCopy).not.toHaveBeenCalled(); }); + it("adds and removes separate rows with ⌘-click on their numbers, and drags across numbers for a range", () => { + const writeText = vi.fn(); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); + const data = [ + ["1", "a"], + ["2", "b"], + ["3", "c"], + ["4", "d"], + ]; + render( + data[r]![c]!} + />, + ); + const number = (r: number) => screen.getAllByRole("row")[r + 1]!.firstElementChild!; + const copied = () => { + writeText.mockClear(); + fireEvent.keyDown(screen.getByRole("grid"), { key: "c", metaKey: true }); + return writeText.mock.calls[0]?.[0]; + }; + fireEvent.mouseDown(number(0), { button: 0 }); + fireEvent.mouseUp(window); + fireEvent.mouseDown(number(2), { button: 0, metaKey: true }); + fireEvent.mouseUp(window); + fireEvent.mouseDown(number(3), { button: 0, metaKey: true }); + fireEvent.mouseUp(window); + expect(copied()).toBe("1\ta\n3\tc\n4\td"); + // ⌘-click on a selected row takes it out again. + fireEvent.mouseDown(number(2), { button: 0, metaKey: true }); + fireEvent.mouseUp(window); + expect(copied()).toBe("1\ta\n4\td"); + // A plain click starts over; dragging down the numbers selects whole rows. + fireEvent.mouseDown(number(1), { button: 0 }); + fireEvent.mouseEnter(number(2)); + fireEvent.mouseUp(window); + expect(copied()).toBe("2\tb\n3\tc"); + }); it("copies the selection in the extractor's format for plain ⌘C", () => { const writeText = vi.fn(); Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); diff --git a/src/features/database/Grid.tsx b/src/features/database/Grid.tsx index 935e17628b..3d1a825f76 100644 --- a/src/features/database/Grid.tsx +++ b/src/features/database/Grid.tsx @@ -24,6 +24,7 @@ import { initialJsonText, isJsonColumn, isJsonValue } from "./jsonValue"; import { JsonValueWindow } from "./JsonValueEditor"; import styles from "./Database.module.css"; import { tx } from "@/platform/i18n"; +import { hasPrimaryModifier } from "@/platform/keymap"; import { CELL_PREVIEW_LIMIT, cellPreview, hasLineBreak } from "./cellPreview"; import { booleanLiterals, @@ -116,6 +117,8 @@ export interface GridRange { left: number; right: number; lead: { row: number; col: number }; + /** Further whole rows selected with ⌘/Ctrl-click, besides `top`..`bottom`. */ + rows?: number[]; } interface Sel { @@ -123,6 +126,8 @@ interface Sel { c0: number; r1: number; c1: number; + /** Whole rows added with ⌘/Ctrl-click on their numbers, besides the block above. */ + rows?: number[]; } const ROW_H = 24; @@ -154,6 +159,29 @@ function cellText(value: string) { ); } +/** + * The selection after a click on row `r`'s number: the whole row, a range of whole rows with + * Shift, or (⌘/Ctrl) that row added to or removed from the selected rows. + */ +export function rowNumberClick( + sel: Sel | null, + r: number, + last: number, + mods: { shift: boolean; add: boolean }, +): Sel | null { + if (mods.shift && sel) return { ...sel, r1: r, c1: last }; + if (!mods.add || !sel) return { r0: r, c0: 0, r1: r, c1: last }; + const n = norm(sel); + const block = Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i); + const rows = [...new Set([...(sel.rows ?? []), ...block])]; + if (!rows.includes(r)) return { r0: r, c0: 0, r1: r, c1: last, rows }; + // ⌘-click on a selected row deselects it; the last remaining row leads. + const rest = rows.filter((x) => x !== r); + const lead = rest.at(-1); + if (lead === undefined) return null; + return { r0: lead, c0: 0, r1: lead, c1: last, rows: rest.slice(0, -1) }; +} + function norm(s: Sel) { return { top: Math.min(s.r0, s.r1), @@ -179,7 +207,8 @@ export function Grid(props: GridProps) { const scrollRef = useRef(null); const numberWidth = Math.max(40, String(firstRowNumber + rowCount - 1).length * 8 + 8); const [sel, setSel] = useState(null); - const dragging = useRef(false); + /** A drag that started on a cell extends the block; one on a row number extends whole rows. */ + const dragging = useRef<"cells" | "rows" | false>(false); useEffect(() => { const stop = () => { dragging.current = false; @@ -220,7 +249,9 @@ export function Grid(props: GridProps) { const { onSelectionChange } = props; useEffect(() => { onSelectionChange?.( - sel && rowCount ? { ...norm(sel), lead: { row: Math.min(sel.r1, rowCount - 1), col: sel.c1 } } : null, + sel && rowCount + ? { ...norm(sel), lead: { row: Math.min(sel.r1, rowCount - 1), col: sel.c1 }, rows: sel.rows } + : null, ); }, [sel, rowCount, onSelectionChange]); @@ -276,21 +307,28 @@ export function Grid(props: GridProps) { const selected = (r: number, c: number) => { if (!sel) return false; const n = norm(sel); - return r >= n.top && r <= n.bottom && c >= n.left && c <= n.right; + return (r >= n.top && r <= n.bottom && c >= n.left && c <= n.right) || !!sel.rows?.includes(r); }; const selectedRows = (): number[] => { if (!sel) return []; const n = norm(sel); - return Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i); + const block = Array.from({ length: n.bottom - n.top + 1 }, (_, i) => n.top + i); + if (!sel.rows?.length) return block; + return [...new Set([...sel.rows, ...block])].sort((a, b) => a - b); }; + const rowSelected = (() => { + const rows = new Set(selectedRows()); + return (r: number) => rows.has(r); + })(); const copy = async (format: CopyFormat, header: boolean, wholeRows = false) => { if (!sel) return; const n = norm(sel); - const cols = wholeRows - ? columns.map((_, i) => i) - : Array.from({ length: n.right - n.left + 1 }, (_, i) => n.left + i); + const cols = + wholeRows || sel.rows?.length + ? columns.map((_, i) => i) + : Array.from({ length: n.right - n.left + 1 }, (_, i) => n.left + i); const picked = selectedRows(); const rows = picked.map((r) => cols.map((c) => value(r, c))); // A cut cell copies as its whole value. @@ -542,7 +580,7 @@ export function Grid(props: GridProps) { if (editing) commit(); e.preventDefault(); scrollRef.current?.focus(); - dragging.current = true; + dragging.current = "cells"; setSel(e.shiftKey && sel ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c }); }; @@ -569,9 +607,15 @@ export function Grid(props: GridProps) { }; const onRowNumberMouseDown = (e: MouseEvent, r: number) => { - if (e.button !== 0 && sel && selected(r, 0)) return; - const last = columns.length - 1; - setSel(e.shiftKey && sel ? { ...sel, r1: r, c1: last } : { r0: r, c0: 0, r1: r, c1: last }); + if (e.button !== 0) { + if (!sel || !selected(r, 0)) setSel({ r0: r, c0: 0, r1: r, c1: columns.length - 1 }); + return; + } + if (editing) commit(); + e.preventDefault(); + scrollRef.current?.focus(); + dragging.current = "rows"; + setSel(rowNumberClick(sel, r, columns.length - 1, { shift: e.shiftKey, add: hasPrimaryModifier(e) })); }; const onContextMenu = (e: MouseEvent) => { @@ -756,7 +800,13 @@ export function Grid(props: GridProps) { )} style={{ gridTemplateColumns: template, transform: `translateY(${v.start + ROW_H}px)` }} > -
onRowNumberMouseDown(e, r)}> +
onRowNumberMouseDown(e, r)} + onMouseEnter={() => { + if (dragging.current === "rows") setSel((s) => (s ? { ...s, r1: r } : s)); + }} + > {state === "inserted" ? "+" : (props.rowNumber?.(r) ?? firstRowNumber + r)}
{columns.map((col, c) => { @@ -849,7 +899,8 @@ export function Grid(props: GridProps) { )} onMouseDown={(e) => onCellMouseDown(e, r, c)} onMouseEnter={() => { - if (dragging.current) setSel((s) => (s ? { ...s, r1: r, c1: c } : s)); + if (dragging.current === "cells") setSel((s) => (s ? { ...s, r1: r, c1: c } : s)); + else if (dragging.current === "rows") setSel((s) => (s ? { ...s, r1: r } : s)); }} onDoubleClick={() => startEdit(r, c)} title={ From 4fa84461ef0c9d73696d5670c8f902d8e0c67a14 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 04:57:31 +0800 Subject: [PATCH 042/104] feat(vcs): add a Git Branch status bar widget (#5679) A Git Branch widget can now be switched on from the status bar's context menu (off by default). It shows the same branch label and incoming/outgoing markers as the toolbar widget, and a click opens Git Branches anchored above it. The popup state records which widget opened it, so each widget shows its own expanded state. Fixes #5610 --- e2e/statusBarGitBranch.spec.ts | 82 +++++++++++++++++++ src/features/vcs/BranchWidget.module.css | 7 ++ src/features/vcs/BranchWidget.tsx | 36 ++++---- src/features/vcs/SyncCommitsPopup.tsx | 3 +- .../vcs/__tests__/branchesPopupHost.test.tsx | 31 +++++++ src/features/vcs/branchesPopupState.ts | 20 +++++ src/features/vcs/index.ts | 27 ++++-- src/platform/locales/text/zh-TW.json | 1 + src/platform/locales/text/zh.json | 1 + 9 files changed, 184 insertions(+), 24 deletions(-) create mode 100644 e2e/statusBarGitBranch.spec.ts create mode 100644 src/features/vcs/branchesPopupState.ts diff --git a/e2e/statusBarGitBranch.spec.ts b/e2e/statusBarGitBranch.spec.ts new file mode 100644 index 0000000000..16b12a98c5 --- /dev/null +++ b/e2e/statusBarGitBranch.spec.ts @@ -0,0 +1,82 @@ +/** + * The status bar's Git Branch widget (off by default, as in IDEA's New UI): switched on from the + * status bar's context menu, it shows the branch and opens Git Branches above itself. + */ +import { expect, stubDesktop, test } from "./fixtures"; + +const ROOT = "/dev/acme-api"; + +test.beforeEach(async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async (root) => { + const h = window.__ipc.handlers; + const branch = (name: string, current = false) => ({ + name, + current, + remote: false, + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: null, + commit: "1111111", + }); + h.vcs_roots = () => [{ root, operation: null, head: "feature/login", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ + head: "feature/login", + headCommit: "1111111", + upstream: "origin/feature/login", + ahead: 1, + behind: 2, + operation: null, + }); + h.vcs_status = () => []; + h.vcs_tags = () => []; + h.vcs_branches = () => [branch("main"), branch("feature/login", true)]; + const storeModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ storeModule); + h.settings_set = (args) => { + const { key, value } = args as { key: string; value: string }; + const next = structuredClone(useProject.getState().settings ?? {}) as Record; + const path = key.split("."); + let node = next; + for (const seg of path.slice(0, -1)) { + node[seg] ??= {}; + node = node[seg] as Record; + } + node[path[path.length - 1]!] = JSON.parse(value); + useProject.setState({ settings: next as never }); + return next; + }; + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, ROOT); +}); + +test("Git Branch status bar widget is off by default and opens Git Branches above itself", async ({ + workbench: page, +}) => { + const widget = page.locator('[data-status-item="vcs.statusBranch"]').getByRole("button"); + await expect(page.locator('[data-branches-widget="toolbar"]')).toContainText("feature/login"); + await expect(widget).toHaveCount(0); + + const bar = page.getByRole("contentinfo", { name: "Status bar" }); + const barBox = (await bar.boundingBox())!; + await page.mouse.click(barBox.x + barBox.width / 2, barBox.y + barBox.height / 2, { button: "right" }); + const menu = page.getByRole("menu"); + await menu.getByRole("menuitemcheckbox", { name: "Git Branch", checked: false }).click(); + await expect(widget).toContainText("feature/login"); + await expect(widget.locator("svg")).not.toHaveCount(0); + + await widget.click(); + const popup = page.getByRole("dialog", { name: "Git Branches" }); + await expect(popup.getByRole("listbox", { name: "Branches" })).toBeVisible(); + await popup.evaluate((el) => Promise.all(el.getAnimations().map((a) => a.finished))); + const popupBox = (await popup.boundingBox())!; + const widgetBox = (await widget.boundingBox())!; + expect(popupBox.y + popupBox.height).toBeLessThanOrEqual(widgetBox.y + 1); + await expect(widget).toHaveAttribute("aria-expanded", "true"); + await expect(page.locator('[data-branches-widget="toolbar"]')).toHaveAttribute("aria-expanded", "false"); + await page.screenshot({ path: "test-results/status-bar-git-branch.png", animations: "disabled" }); +}); diff --git a/src/features/vcs/BranchWidget.module.css b/src/features/vcs/BranchWidget.module.css index 04b5b8971a..4f960c634b 100644 --- a/src/features/vcs/BranchWidget.module.css +++ b/src/features/vcs/BranchWidget.module.css @@ -6,6 +6,13 @@ height: var(--h-toolbar-widget); border-radius: var(--radius-toolbar-dropdown); } +/* The status bar's Git Branch widget: the bar's own button, sized like its other widgets. */ +.statusWidget { + display: inline-flex; + align-items: center; + gap: var(--space-1); + max-width: 240px; +} .icon { flex: none; color: var(--fg-muted); diff --git a/src/features/vcs/BranchWidget.tsx b/src/features/vcs/BranchWidget.tsx index a0cb6ca73d..a1034dee33 100644 --- a/src/features/vcs/BranchWidget.tsx +++ b/src/features/vcs/BranchWidget.tsx @@ -63,6 +63,9 @@ import { outgoingCount, outgoingDestination, type SyncDirection } from "./syncCo import styles from "./BranchWidget.module.css"; import { tx } from "@/platform/i18n"; import { useWorkflowSettings } from "@/platform/workflowSettings"; +import { branchWidgetAnchor, useBranchesPopup, type BranchWidgetPlace } from "./branchesPopupState"; + +export { showBranchesPopup, STATUS_BRANCH_WIDGET, useBranchesPopup } from "./branchesPopupState"; /** `active` until the user moves: a new filter selects the row IDEA prefers for it. */ const PREFERRED = -1; @@ -80,9 +83,6 @@ function pickActive( return firstSelectable(rows, isSection); } -export const useBranchesPopup = create<{ open: boolean }>(() => ({ open: false })); -export const showBranchesPopup = () => useBranchesPopup.setState({ open: true }); - export function headLabel(branch: { head: string | null; headCommit: string | null } | null): string { if (!branch) return ""; if (branch.head) return branch.head; @@ -95,7 +95,11 @@ function useBranchRepositories(current: string | null) { return useMemo(() => branchRepositoryRoots(roots, branchRoots, current), [roots, branchRoots, current]); } -export function BranchWidget() { +export function StatusBranchWidget() { + return ; +} + +export function BranchWidget({ place = "toolbar" }: { place?: BranchWidgetPlace }) { const available = useVcs((s) => s.available); const current = useActiveRepository(); const roots = useBranchRepositories(current); @@ -107,9 +111,10 @@ export function BranchWidget() { // Several repositories on different branches: the widget names the current one. const diverged = widgetShowsRepo(roots.map((r) => ({ head: heads[r]?.head ?? null }))); const pending = useVcs((s) => unfetchedBranch(s.unfetched, current, branch?.head, branch?.trackedTip)); - const open = useBranchesPopup((s) => s.open); + const open = useBranchesPopup((s) => s.open && (s.from ?? "toolbar") === place); const extensions = useBranchWidgetExtensions((s) => s.extensions); if (!available || !branch) return null; + const toolbar = place === "toolbar"; // Another feature presents the current branch (the GitHub pull request on it). const presented = current === selected ? branchPresentation(extensions) : null; const repo = diverged && branchRoot ? repoName(branchRoot) : null; @@ -138,28 +143,28 @@ export function BranchWidget() { .join("\n"); // A marker lists its commits; the rest of the widget keeps opening the branches popup. const openSync = (direction: SyncDirection) => { - useBranchesPopup.setState({ open: false }); + useBranchesPopup.setState({ open: false, from: place }); showBranchSync(current, branch, direction); }; return ( <> useBranchesPopup.setState({ open: !open })} + onClick={() => useBranchesPopup.setState({ open: !open, from: place })} > {diverged && repo && ( - + {repo} )} - + {inProgress(branch.operation) ? operationTitle(inProgress(branch.operation)!, branch.head) : (presented?.text ?? headLabel(branch))} @@ -169,7 +174,7 @@ export function BranchWidget() { )} {/* Like IDEA's widget: icons only; counts are in the tooltip. */} - + {toolbar && } ); @@ -177,8 +182,9 @@ export function BranchWidget() { export function BranchesPopupHost() { const open = useBranchesPopup((s) => s.open); + const from = useBranchesPopup((s) => s.from); if (!open) return null; - const anchor = document.querySelector("[data-branches-widget]") ?? { x: window.innerWidth / 2 - 160, y: 60 }; + const anchor = branchWidgetAnchor(from) ?? { x: window.innerWidth / 2 - 160, y: 60 }; return useBranchesPopup.setState({ open: false })} />; } diff --git a/src/features/vcs/SyncCommitsPopup.tsx b/src/features/vcs/SyncCommitsPopup.tsx index e911841099..458c8df853 100644 --- a/src/features/vcs/SyncCommitsPopup.tsx +++ b/src/features/vcs/SyncCommitsPopup.tsx @@ -14,6 +14,7 @@ import { notifications } from "@/workbench/contributions"; import { Button, Icon, List, Popup, Spinner, T, firstSelectable } from "@/ui"; import type { PopupAnchor } from "@/ui/Popup"; import { activeRepository } from "./activeRepository"; +import { branchWidgetAnchor, useBranchesPopup } from "./branchesPopupState"; import { showChangesDiff, toLogChanges } from "./logChanges"; import { formatTime } from "./model"; import { currentRepoRoot, unfetchedBranch, useVcs } from "./store"; @@ -87,7 +88,7 @@ function syncSource(repo: string | null, info: BranchInfo, direction?: SyncDirec export function SyncCommitsPopupHost() { const source = useSyncCommits((s) => s.source); if (!source) return null; - const anchor: PopupAnchor = document.querySelector("[data-branches-widget]") ?? { + const anchor: PopupAnchor = branchWidgetAnchor(useBranchesPopup.getState().from) ?? { x: window.innerWidth / 2 - 280, y: 60, }; diff --git a/src/features/vcs/__tests__/branchesPopupHost.test.tsx b/src/features/vcs/__tests__/branchesPopupHost.test.tsx index 4818bfe38d..44771b505c 100644 --- a/src/features/vcs/__tests__/branchesPopupHost.test.tsx +++ b/src/features/vcs/__tests__/branchesPopupHost.test.tsx @@ -126,3 +126,34 @@ it("shows common branch totals and pending remote changes from another repositor expect(await within(list).findByLabelText("6 outgoing commits in 2 repositories")).toHaveTextContent("6"); expect(within(list).getByTitle(/3 incoming commits\s+Remote changes available to fetch/)).toHaveTextContent("3"); }); + +it("opens Git Branches from the status bar's Git Branch widget, anchored to it", async () => { + const { BranchWidget, StatusBranchWidget } = await import("../BranchWidget"); + useVcs.setState({ + available: true, + root: "/work/app", + repo: "/work/app", + roots: ["/work/app"], + heads: { "/work/app": { head: "feature/login", headCommit: "abc" } }, + branch: { head: "feature/login", headCommit: "abc", upstream: null, ahead: 0, behind: 0 } as never, + }); + render( + <> + + + + , + ); + const [toolbar, status] = screen.getAllByRole("button", { name: /feature\/login/ }); + expect(toolbar).toHaveAttribute("data-branches-widget", "toolbar"); + expect(status).toHaveAttribute("data-branches-widget", "status"); + fireEvent.click(status!); + expect(screen.getByRole("dialog", { name: "Git Branches" })).toBeInTheDocument(); + expect(status).toHaveAttribute("aria-expanded", "true"); + expect(toolbar).toHaveAttribute("aria-expanded", "false"); + // VCS › Branches… opens it from the toolbar widget again. + act(() => useBranchesPopup.setState({ open: false })); + act(showBranchesPopup); + expect(toolbar).toHaveAttribute("aria-expanded", "true"); + expect(status).toHaveAttribute("aria-expanded", "false"); +}); diff --git a/src/features/vcs/branchesPopupState.ts b/src/features/vcs/branchesPopupState.ts new file mode 100644 index 0000000000..b8dcdae9cf --- /dev/null +++ b/src/features/vcs/branchesPopupState.ts @@ -0,0 +1,20 @@ +/** Where the Git Branches popup is open from, shared by the branch widgets and the popups they anchor. */ +import { create } from "zustand"; + +/** `from`: the widget the popup opened from (the status bar's or, by default, the toolbar's). */ +export const useBranchesPopup = create<{ open: boolean; from?: BranchWidgetPlace }>(() => ({ open: false })); +/** Opens it from the toolbar widget (or whichever widget is shown): VCS › Branches… and its shortcut. */ +export const showBranchesPopup = () => useBranchesPopup.setState({ open: true, from: undefined }); + +export type BranchWidgetPlace = "toolbar" | "status"; + +/** The status bar's Git Branch widget (IDEA's status bar widget of the same name), off by default. */ +export const STATUS_BRANCH_WIDGET = { id: "vcs.statusBranch", title: "Git Branch", defaultVisible: false } as const; + +/** The branch widget a popup anchors to: the one it opened from, else whichever is shown. */ +export function branchWidgetAnchor(from: BranchWidgetPlace | undefined): Element | null { + return ( + document.querySelector(`[data-branches-widget="${from ?? "toolbar"}"]`) ?? + document.querySelector("[data-branches-widget]") + ); +} diff --git a/src/features/vcs/index.ts b/src/features/vcs/index.ts index 8d1d89bd0c..c54751a749 100644 --- a/src/features/vcs/index.ts +++ b/src/features/vcs/index.ts @@ -12,6 +12,7 @@ import { registerEditorKind, registerMenuGroup, registerOverlay, + registerStatusItem, registerTitleItem, registerToolWindow, } from "@/workbench/contributions"; @@ -32,7 +33,13 @@ import { controlLabel, controlOperation, inProgress, installOperationNoticeExpir import { annotationsShown, blameSlot } from "./blame"; import { activateRevisionAnnotations } from "./annotateRevisionProvider"; import { inlineBlame } from "./inlineBlame"; -import { BranchWidget, BranchesPopupHost, useBranchesPopup } from "./BranchWidget"; +import { + BranchWidget, + BranchesPopupHost, + STATUS_BRANCH_WIDGET, + StatusBranchWidget, + useBranchesPopup, +} from "./BranchWidget"; import { SyncCommitsPopupHost } from "./SyncCommitsPopup"; import { clearUnstashConflictNotices, showConflictsDialog } from "./conflictsUi"; import { registerCompareActions } from "./compare"; @@ -109,13 +116,17 @@ function trackTitleItem(): () => void { let dispose: (() => void) | null = null; const sync = (available: boolean) => { if (available && !dispose) { - dispose = registerTitleItem({ - id: "vcs.branch", - title: "VCS Widget", - align: "left", - priority: 10, - component: BranchWidget, - }); + const disposers = [ + registerTitleItem({ + id: "vcs.branch", + title: "VCS Widget", + align: "left", + priority: 10, + component: BranchWidget, + }), + registerStatusItem({ ...STATUS_BRANCH_WIDGET, align: "right", priority: 60, component: StatusBranchWidget }), + ]; + dispose = () => disposers.forEach((d) => d()); } else if (!available && dispose) { dispose(); dispose = null; diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index bc60891cce..5189ccfcff 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -1594,6 +1594,7 @@ "Get from Version Control…": "從版本控制取得…", "Project from Version Control…": "來自版本控制的專案…", "Gevent compatible": "相容 Gevent", + "Git Branch": "Git 分支", "Git Branches": "Git 分支", "Git Log": "Git 記錄", "Git Reset": "Git 重設", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index fd23d6e61a..30a3dae1dd 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1981,6 +1981,7 @@ "Get from Version Control…": "从版本控制获取…", "Project from Version Control…": "来自版本控制的项目…", "Gevent compatible": "兼容 Gevent", + "Git Branch": "Git 分支", "Git Branches": "Git 分支", "Git Log": "Git 日志", "Git Reset": "Git 重置", From 966e4cd03c99ab996122aa88db57ae4e9e476785 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 25 Nov 2026 05:06:00 +0800 Subject: [PATCH 043/104] feat(toolbar): add a Center group to Customize Main Toolbar (#5682) Customize Main Toolbar now has Left, Center and Right groups (appearance.mainToolbar.center, empty by default). The Center group is centred on the whole title bar when the other groups leave room, otherwise pushed against the group it would overlap, as IDEA's main toolbar lays it out. Fixes #5612 --- crates/ide-core/src/settings.rs | 2 + e2e/toolbarCustomization.spec.ts | 50 +++++++++++++++++-- src/bindings.ts | 2 + src/platform/locales/text/zh-TW.json | 4 +- src/platform/locales/text/zh.json | 4 +- src/workbench/MainToolbarDialog.tsx | 65 +++++++++++++++--------- src/workbench/TitleBar.module.css | 7 +++ src/workbench/TitleBar.tsx | 27 ++++++++-- src/workbench/mainToolbar.test.ts | 16 ++++++ src/workbench/mainToolbar.ts | 31 +++++++----- src/workbench/toolbarCenter.test.ts | 17 +++++++ src/workbench/toolbarCenter.ts | 75 ++++++++++++++++++++++++++++ 12 files changed, 254 insertions(+), 46 deletions(-) create mode 100644 src/workbench/toolbarCenter.test.ts create mode 100644 src/workbench/toolbarCenter.ts diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 78b61da575..8b0b579ba0 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -941,6 +941,8 @@ pub struct FileIconThemeOptions { #[serde(default, rename_all = "camelCase")] pub struct MainToolbarSettings { pub left: Vec, + /// Centred in the toolbar (between the other two groups when they leave too little room). + pub center: Vec, pub right: Vec, /// Widgets the user removed. pub hidden: Vec, diff --git a/e2e/toolbarCustomization.spec.ts b/e2e/toolbarCustomization.spec.ts index a93ff0ebc9..84bb614608 100644 --- a/e2e/toolbarCustomization.spec.ts +++ b/e2e/toolbarCustomization.spec.ts @@ -11,6 +11,7 @@ test("Customize Main Toolbar keeps layout actions above the groups and stacks th await open(); const dialog = page.getByRole("dialog", { name: "Customize Main Toolbar", exact: true }); const left = dialog.getByRole("listbox", { name: "Left group" }); + const center = dialog.getByRole("listbox", { name: "Center group" }); const right = dialog.getByRole("listbox", { name: "Right group" }); const add = dialog.getByRole("button", { name: "Add…", exact: true }); const restore = dialog.getByRole("button", { name: "Restore Defaults", exact: true }); @@ -19,16 +20,19 @@ test("Customize Main Toolbar keeps layout actions above the groups and stacks th for (const width of [1120, 460]) { await page.setViewportSize({ width, height: 620 }); await expect(async () => { - const [addBox, restoreBox, leftBox, rightBox] = await Promise.all( - [add, restore, left, right].map((el) => el.boundingBox()), + const [addBox, restoreBox, leftBox, centerBox, rightBox] = await Promise.all( + [add, restore, left, center, right].map((el) => el.boundingBox()), ); expect(addBox!.y + addBox!.height).toBeLessThan(leftBox!.y); expect(restoreBox!.y).toBe(addBox!.y); if (width === 1120) { + expect(centerBox!.y).toBe(leftBox!.y); expect(rightBox!.y).toBe(leftBox!.y); - expect(rightBox!.x).toBeGreaterThan(leftBox!.x + leftBox!.width); + expect(centerBox!.x).toBeGreaterThan(leftBox!.x + leftBox!.width); + expect(rightBox!.x).toBeGreaterThan(centerBox!.x + centerBox!.width); } else { - expect(rightBox!.y).toBeGreaterThan(leftBox!.y + leftBox!.height); + expect(centerBox!.y).toBeGreaterThan(leftBox!.y + leftBox!.height); + expect(rightBox!.y).toBeGreaterThan(centerBox!.y + centerBox!.height); expect(rightBox!.width).toBe(leftBox!.width); } }).toPass({ timeout: 3000 }); @@ -39,8 +43,13 @@ test("Customize Main Toolbar keeps layout actions above the groups and stacks th await expect(project(left)).toHaveAttribute("aria-selected", "true"); await actions.getByRole("button", { name: "Move Down" }).click(); await expect(left.getByRole("option").nth(1)).toHaveText("Project Widget"); + // Left has nothing further left; the arrows step through Center to Right and back. + await expect(actions.getByRole("button", { name: "Move to Left" })).toBeDisabled(); + await actions.getByRole("button", { name: "Move to Center" }).click(); + await expect(project(center)).toBeVisible(); await actions.getByRole("button", { name: "Move to Right" }).click(); await expect(project(right)).toBeVisible(); + await expect(actions.getByRole("button", { name: "Move to Right" })).toBeDisabled(); await actions.getByRole("button", { name: "Remove", exact: true }).click(); await expect(project(right)).toHaveCount(0); @@ -59,3 +68,36 @@ test("Customize Main Toolbar keeps layout actions above the groups and stacks th await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); await expect(dialog).toBeHidden(); }); + +test("the Center group is centred in the main toolbar", async ({ workbench: page }) => { + const bar = page + .locator("header") + .filter({ has: page.locator("[data-toolbar-spacer]") }) + .first(); + await expect(bar.locator("[data-toolbar-center]")).toHaveCount(0); + await page.evaluate(async () => { + const path = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ path); + const settings = useProject.getState().settings; + useProject.setState({ + settings: { + ...settings, + appearance: { + ...settings?.appearance, + mainToolbar: { left: [], center: ["project"], right: ["action:navigate.searchEverywhere"], hidden: [] }, + }, + }, + }); + }); + const group = bar.locator("[data-toolbar-center]"); + await expect(group).toContainText("acme-api"); + for (const width of [1400, 900]) { + await page.setViewportSize({ width, height: 700 }); + await expect(async () => { + const [barBox, groupBox] = await Promise.all([bar.boundingBox(), group.boundingBox()]); + const middle = groupBox!.x + groupBox!.width / 2; + expect(Math.abs(middle - (barBox!.x + barBox!.width / 2))).toBeLessThanOrEqual(1); + }).toPass({ timeout: 3000 }); + } + await page.screenshot({ path: "test-results/toolbar-center.png", animations: "disabled" }); +}); diff --git a/src/bindings.ts b/src/bindings.ts index d01c21ad5e..8b6dcbbce0 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -9390,6 +9390,8 @@ export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" | export type MainToolbarSettings = { left?: string[], + /** Centred in the toolbar (between the other two groups when they leave too little room). */ + center?: string[], right?: string[], /** Widgets the user removed. */ hidden?: string[], diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 5189ccfcff..3c90529314 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9228,5 +9228,7 @@ "Configure skills for this session": "為此工作階段設定技能", "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "未在 .agents/skills、.openidea/skills、~/.agents/skills 或 Claude Code、GitHub Copilot、Codex 與 Cursor 的 CLI 資料夾中找到技能。", "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "該 CLI 會自己發現這個資料夾:關閉只會讓 OpenIDEA 的 / 選單不再提供該技能,並且只在 CLI 支援停用時生效。", - "Cannot find the source of {0}": "找不到 {0} 的原始碼" + "Cannot find the source of {0}": "找不到 {0} 的原始碼", + "Center group": "置中群組", + "Move to Center": "移到置中" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 30a3dae1dd..2d3634a88b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10177,5 +10177,7 @@ "Resize hover card from the right": "从右边缘调整悬浮卡片大小", "Resize hover card from the bottom": "从下边缘调整悬浮卡片大小", "Resize hover card from the left": "从左边缘调整悬浮卡片大小", - "Resize hover card from the corner": "从角部调整悬浮卡片大小" + "Resize hover card from the corner": "从角部调整悬浮卡片大小", + "Center group": "居中组", + "Move to Center": "移到居中" } diff --git a/src/workbench/MainToolbarDialog.tsx b/src/workbench/MainToolbarDialog.tsx index df5ca83f61..d64ba92d0c 100644 --- a/src/workbench/MainToolbarDialog.tsx +++ b/src/workbench/MainToolbarDialog.tsx @@ -15,7 +15,9 @@ import { entryAction, useMainToolbarSettings, widgetTitle, + TOOLBAR_SIDES, type ToolbarLayout, + type ToolbarSide, } from "./mainToolbar"; import styles from "./MainToolbarDialog.module.css"; @@ -27,8 +29,18 @@ export function MainToolbarDialogHost() { return open ? useCustomize.setState({ open: false })} /> : null; } -type Side = "left" | "right"; -const SIDES: Side[] = ["left", "right"]; +type Side = ToolbarSide; + +const SIDE_TITLES: Record = { left: "Left", center: "Center", right: "Right" }; +const GROUP_LABELS: Record = { left: "Left group", center: "Center group", right: "Right group" }; +const MOVE_TITLES: Record = { left: "Move to Left", center: "Move to Center", right: "Move to Right" }; + +/** Moves entry `index` of `side` to the end of the group `to`. */ +export function moveToGroup(layout: ToolbarLayout, side: Side, index: number, to: Side): ToolbarLayout { + const id = layout[side][index]; + if (id === undefined || to === side) return layout; + return { ...layout, [side]: layout[side].filter((_, i) => i !== index), [to]: [...layout[to], id] }; +} function move(layout: ToolbarLayout, side: Side, index: number, delta: -1 | 1): ToolbarLayout { const list = [...layout[side]]; @@ -75,7 +87,7 @@ function CustomizeDialog({ onClose }: { onClose: () => void }) { open title="Customize Main Toolbar" onClose={onClose} - width={620} + width={760} buttons={[ { label: "OK", role: "default", onClick: () => void apply() }, { label: t("common.cancel"), role: "cancel" }, @@ -120,22 +132,23 @@ function CustomizeDialog({ onClose }: { onClose: () => void }) { setSel({ ...sel, index: sel.index + 1 }); }} /> - { - if (selected === undefined) return; - const other: Side = sel.side === "left" ? "right" : "left"; - setLayout({ - ...layout, - [sel.side]: layout[sel.side].filter((_, i) => i !== sel.index), - [other]: [...layout[other], selected], - }); - setSel({ side: other, index: layout[other].length }); - }} - /> + {([-1, 1] as const).map((step) => { + const to = TOOLBAR_SIDES[TOOLBAR_SIDES.indexOf(sel.side) + step]; + return ( + { + if (!to) return; + setLayout(moveToGroup(layout, sel.side, sel.index, to)); + setSel({ side: to, index: layout[to].length }); + }} + /> + ); + })} void }) { }} />
- {adding &&