mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 23:56:05 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf95edf296 | ||
|
|
f3e80ba020 | ||
|
|
f767bd2e7c | ||
|
|
51174842cc | ||
|
|
e4ece2bd8d | ||
|
|
a5093c0cd1 | ||
|
|
9a0256c7d4 | ||
|
|
78b478ee38 |
No files matched your search
@@ -241,6 +241,15 @@ impl PathFilter {
|
||||
(!rel.is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
/// Recent Files' stored form: the store key for a project file, the absolute
|
||||
/// path for one outside it (a scratch file). Loading joins it to the root,
|
||||
/// which leaves an absolute path as it is.
|
||||
pub(crate) fn recent_key(&self, path: &Path) -> Option<String> {
|
||||
self.store_key(path).or_else(|| {
|
||||
(path.is_absolute() && !path.starts_with(&self.root)).then(|| path.to_str().map(str::to_owned))?
|
||||
})
|
||||
}
|
||||
|
||||
fn excluded_rel(&self, rel: &str) -> bool {
|
||||
self.excludes.is_match(rel)
|
||||
}
|
||||
|
||||
+18
-15
@@ -400,15 +400,10 @@ impl ProjectIndex {
|
||||
|
||||
/// Boost for "recent files" ranking.
|
||||
/// Records a recently opened file; a virtual document's URI (library
|
||||
/// class) is kept verbatim, like IDEA lists library classes in Recent Files.
|
||||
/// class) is kept verbatim, and a file outside the project (a scratch file)
|
||||
/// by its absolute path.
|
||||
pub fn mark_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
r.retain(|p| p != &path);
|
||||
@@ -420,13 +415,7 @@ impl ProjectIndex {
|
||||
|
||||
/// Drops a file from Recent Files (Delete in the ⌘E popup).
|
||||
pub fn remove_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
let before = r.len();
|
||||
@@ -473,6 +462,20 @@ impl ProjectIndex {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// How Recent Files stores `path`: a virtual URI verbatim, a project file normalized,
|
||||
/// and an existing file outside the root canonicalized. Excluded files under the root
|
||||
/// are left out.
|
||||
fn recent_key(&self, path: &Path) -> Option<PathBuf> {
|
||||
if path.to_str().is_some_and(ide_core::text::is_virtual_uri) {
|
||||
return Some(path.to_owned());
|
||||
}
|
||||
if let Some(p) = self.normalize(path) {
|
||||
return Some(p);
|
||||
}
|
||||
let p = dunce::canonicalize(path).ok().filter(|p| p.is_file())?;
|
||||
(!p.starts_with(&self.root)).then_some(p)
|
||||
}
|
||||
|
||||
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
|
||||
fn normalize(&self, path: &Path) -> Option<PathBuf> {
|
||||
let filter = self.shared.filter();
|
||||
|
||||
@@ -251,6 +251,26 @@ fn recent_files_skip_deleted_files_but_keep_virtual_documents() {
|
||||
assert_eq!(idx.recent_files(), vec![virt]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_files_keep_files_outside_the_project() {
|
||||
let fx = sample();
|
||||
let scratches = tempfile::tempdir().unwrap();
|
||||
let scratch = dunce::canonicalize(scratches.path()).unwrap().join("generated-requests.http");
|
||||
std::fs::write(&scratch, "GET http://localhost\n").unwrap();
|
||||
let app = fx.root.join("web/app.py");
|
||||
{
|
||||
let idx = fx.open();
|
||||
idx.mark_recent(&app);
|
||||
idx.mark_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
}
|
||||
let idx = fx.open();
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()], "persisted by absolute path");
|
||||
idx.remove_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![app]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_skips_unchanged_files_on_reopen() {
|
||||
let fx = sample();
|
||||
|
||||
@@ -591,7 +591,7 @@ impl Shared {
|
||||
let update_elapsed = update_started.elapsed();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Some(store) = &self.store {
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
let d = self.data.read();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
|
||||
@@ -976,7 +976,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
if save_recent && let Some(store) = &self.store {
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
if let Err(e) = store.save_recent(&rels) {
|
||||
tracing::warn!("index cache: saving recent files failed: {e}");
|
||||
}
|
||||
|
||||
@@ -47,13 +47,19 @@ The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen m
|
||||
|
||||
## The window stays blank or stops responding on Linux
|
||||
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal through XWayland first:
|
||||
|
||||
```sh
|
||||
GDK_BACKEND=x11 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is still drawn on the GPU this way; at a fractional display scale the window may look less sharp. If that does not help, turn the DMA-BUF renderer off instead:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep either setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line, for example to `Exec=env GDK_BACKEND=x11 openidea`.
|
||||
|
||||
## OpenIDEA exits at startup with a data directory error
|
||||
|
||||
|
||||
@@ -47,13 +47,19 @@ Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen
|
||||
|
||||
## Linux 上窗口空白或无响应
|
||||
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中通过 XWayland 启动:
|
||||
|
||||
```sh
|
||||
GDK_BACKEND=x11 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面仍由 GPU 绘制;在非整数缩放比例下,窗口可能不够清晰。如果仍有问题,改为关闭 DMA-BUF 渲染器启动:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上其中一个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并修改其中的 `Exec=` 一行,例如改成 `Exec=env GDK_BACKEND=x11 openidea`。
|
||||
|
||||
## 启动时提示数据目录错误并退出
|
||||
|
||||
|
||||
@@ -308,7 +308,7 @@
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.sideTabsResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
|
||||
@@ -62,7 +62,7 @@ export function SideTabsResizer({ side }: { side: "left" | "right" }) {
|
||||
handle.setPointerCapture(e.pointerId);
|
||||
const origin = e.clientX;
|
||||
const previous = pane.style.getPropertyValue(LIMIT_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this pane follows the pointer; every group takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
|
||||
@@ -38,7 +38,7 @@ export function ChangesResizer() {
|
||||
const start = pane.getBoundingClientRect().width;
|
||||
const origin = e.clientX;
|
||||
const previous = session.style.getPropertyValue(WIDTH_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this session follows the pointer; every task takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
|
||||
@@ -1253,7 +1253,7 @@
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.changesResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
right: -3px;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.rowNumber {
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DataSource } from "@/platform/ipc";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
save: vi.fn(),
|
||||
password: vi.fn(),
|
||||
sshSecret: vi.fn(),
|
||||
sources: vi.fn(),
|
||||
connected: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
dbSaveSources: backend.save,
|
||||
dbSetPassword: backend.password,
|
||||
dbSetSshSecret: backend.sshSecret,
|
||||
dbSources: backend.sources,
|
||||
dbConnected: backend.connected,
|
||||
},
|
||||
};
|
||||
});
|
||||
import { DatabaseDialogs } from "./Dialogs";
|
||||
import { useDatabase } from "./store";
|
||||
|
||||
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
|
||||
const mysql: DataSource = { id: "my", name: "MySQL", driver: "mysql", user: "manage" };
|
||||
const tunnelled: DataSource = {
|
||||
...mysql,
|
||||
ssh: { enabled: true, host: "bastion", port: 22, user: "u", auth: "password", saveSecret: false },
|
||||
} as DataSource;
|
||||
|
||||
function ask(kind: "password" | "sshSecret", source: DataSource) {
|
||||
const resolve = vi.fn();
|
||||
useDatabase.setState({
|
||||
sources: [source],
|
||||
dialog: kind === "password" ? { kind, source, resolve } : { kind, source, prompt: "password required", resolve },
|
||||
});
|
||||
render(<DatabaseDialogs />);
|
||||
return resolve;
|
||||
}
|
||||
|
||||
function answer(secret: string) {
|
||||
fireEvent.change(document.querySelector("input[type=password]")!, { target: { value: secret } });
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Save password" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(backend)) m.mockReset();
|
||||
backend.save.mockResolvedValue(ok(null));
|
||||
backend.password.mockResolvedValue(ok(null));
|
||||
backend.sshSecret.mockResolvedValue(ok(null));
|
||||
backend.sources.mockImplementation(async () => ok(backend.save.mock.calls.at(-1)?.[0] ?? [mysql]));
|
||||
backend.connected.mockResolvedValue(ok([]));
|
||||
});
|
||||
|
||||
describe("connect-time secret prompts", () => {
|
||||
it("turns on the data source's Save password when it is ticked in the prompt", async () => {
|
||||
const resolve = ask("password", mysql);
|
||||
answer("secret");
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).toHaveBeenCalledWith([{ ...mysql, savePassword: true }]);
|
||||
expect(backend.password).toHaveBeenCalledWith("my", "secret", true);
|
||||
});
|
||||
|
||||
it("only stores the password when the setting already matches", async () => {
|
||||
const resolve = ask("password", { ...mysql, savePassword: true });
|
||||
fireEvent.change(document.querySelector("input[type=password]")!, { target: { value: "secret" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).not.toHaveBeenCalled();
|
||||
expect(backend.password).toHaveBeenCalledWith("my", "secret", true);
|
||||
});
|
||||
|
||||
it("turns on the SSH tunnel's Save password of the data source's own SSH settings", async () => {
|
||||
const resolve = ask("sshSecret", tunnelled);
|
||||
answer("ssh-secret");
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).toHaveBeenCalledWith([{ ...tunnelled, ssh: { ...tunnelled.ssh, saveSecret: true } }]);
|
||||
expect(backend.sshSecret).toHaveBeenCalledWith("my", "ssh-secret", true);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { call, commands, type DataSource } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Input, lazyComponent, T } from "@/ui";
|
||||
import { sshLabel } from "./model";
|
||||
import { SourceDialog, snowflakeSecretLabel } from "./SourceDialog";
|
||||
import { closeDialog, useDatabase } from "./store";
|
||||
import { closeDialog, saveSource, sourceById, useDatabase } from "./store";
|
||||
import styles from "./Database.module.css";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -27,7 +27,9 @@ function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok:
|
||||
resolve(ok);
|
||||
};
|
||||
const submit = async () => {
|
||||
await call(commands.dbSetPassword(source.id ?? "", password, save));
|
||||
// The checkbox is the data source's Save password setting: saved passwords are read only when it is on.
|
||||
if (save !== !!source.savePassword) await saveSource({ ...source, savePassword: save }, password);
|
||||
else await call(commands.dbSetPassword(source.id ?? "", password, save));
|
||||
done(true);
|
||||
};
|
||||
return (
|
||||
@@ -81,7 +83,12 @@ function SshSecretDialog({
|
||||
resolve(ok);
|
||||
};
|
||||
const submit = async () => {
|
||||
await call(commands.dbSetSshSecret(source.id ?? "", secret, save));
|
||||
// As for the password: the data source's own SSH settings read a saved secret only when Save is on.
|
||||
// An SSH configuration keeps its own setting.
|
||||
const stored = sourceById(source.id);
|
||||
if (stored?.ssh && !stored.ssh.config?.trim() && save !== !!stored.ssh.saveSecret)
|
||||
await saveSource({ ...stored, ssh: { ...stored.ssh, saveSecret: save } }, undefined, secret);
|
||||
else await call(commands.dbSetSshSecret(source.id ?? "", secret, save));
|
||||
done(true);
|
||||
};
|
||||
return (
|
||||
|
||||
@@ -574,7 +574,7 @@ export function Grid(props: GridProps) {
|
||||
const startResize = (e: MouseEvent, col: number) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
const startX = e.clientX;
|
||||
const start = widths[col] ?? 100;
|
||||
const move = (ev: globalThis.MouseEvent) => {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
showServiceView,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerFileNavigation } from "./fileNavigation";
|
||||
import { registerUrlNavigation } from "./urlNavigation";
|
||||
import { registerVariableNavigation } from "./variableNavigation";
|
||||
import { HTTP_LANGUAGE, httpEditorExtension, refreshRequests, requestAtCaret } from "./editor";
|
||||
import { HttpClientHeaderActions, HttpClientView } from "./HttpClientView";
|
||||
@@ -143,6 +144,7 @@ export function activate(): () => void {
|
||||
registerSpringEndpointProvider(),
|
||||
registerFeignNavigation(),
|
||||
registerVariableNavigation(),
|
||||
registerUrlNavigation(),
|
||||
registerFileNavigation(),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) resetHttpClient();
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ConstantPool, type ConstantFiles } from "./constants";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { parseSource } from "./source";
|
||||
|
||||
function project(files: Record<string, string>): ConstantFiles & { reads: string[] } {
|
||||
const reads: string[] = [];
|
||||
return {
|
||||
reads,
|
||||
filesNamed: vi.fn(async (name: string) => Object.keys(files).filter((p) => p.endsWith(`/${name}`))),
|
||||
read: async (path) => {
|
||||
reads.push(path);
|
||||
return files[path] ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function paths(text: string, files: ConstantFiles) {
|
||||
const file = parseSource(text);
|
||||
const pool = new ConstantPool(files);
|
||||
await pool.load([file]);
|
||||
return controllersOf(file, pool.resolverFor(file)).flatMap((c) =>
|
||||
c.endpoints.map((e) => `${e.httpMethod} ${e.paths}`),
|
||||
);
|
||||
}
|
||||
|
||||
const defines = {
|
||||
"/p/common/src/main/java/com/acme/common/AppServiceDefine.java": `package com.acme.common;
|
||||
public interface AppServiceDefine {
|
||||
String API_WEBAPI_PREFIX = "/api";
|
||||
}`,
|
||||
"/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java": `package com.acme.cockpit;
|
||||
public interface CockpitApiDefine {
|
||||
String API_COCKPIT_PREFIX = "/cockpit";
|
||||
String PATH_MAP = "/map";
|
||||
}`,
|
||||
};
|
||||
|
||||
describe("mapping constants of other classes", () => {
|
||||
it("joins constants of interfaces in other files and modules", async () => {
|
||||
const files = project(defines);
|
||||
const text = `package com.acme.cockpit.web;
|
||||
import com.acme.common.AppServiceDefine;
|
||||
import com.acme.cockpit.CockpitApiDefine;
|
||||
@RestController
|
||||
@RequestMapping(AppServiceDefine.API_WEBAPI_PREFIX + CockpitApiDefine.API_COCKPIT_PREFIX)
|
||||
public class CockpitMapController {
|
||||
@GetMapping(CockpitApiDefine.PATH_MAP + "/layers")
|
||||
public MapLayerVO layers(@RequestParam(required = false) String type) { return null; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /api/cockpit/map/layers"]);
|
||||
});
|
||||
|
||||
it("follows static imports, superclasses and constants built from other classes", async () => {
|
||||
const files = project({
|
||||
...defines,
|
||||
"/p/web/src/main/java/com/acme/web/Routes.java": `package com.acme.web;
|
||||
import com.acme.common.AppServiceDefine;
|
||||
public final class Routes {
|
||||
public static final String ORDERS = AppServiceDefine.API_WEBAPI_PREFIX + "/orders";
|
||||
}`,
|
||||
"/p/web/src/main/java/com/acme/web/BaseController.java": `package com.acme.web;
|
||||
public abstract class BaseController {
|
||||
protected static final String ITEMS = "/items";
|
||||
}`,
|
||||
});
|
||||
const text = `package com.acme.web;
|
||||
import static com.acme.web.Routes.ORDERS;
|
||||
@RestController
|
||||
@RequestMapping(ORDERS)
|
||||
public class OrderController extends BaseController {
|
||||
@GetMapping(ITEMS + "/{id}")
|
||||
public Item item(@PathVariable String id) { return null; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /api/orders/items/{id}"]);
|
||||
});
|
||||
|
||||
it("prefers the imported package when several classes share the name", async () => {
|
||||
const files = project({
|
||||
"/p/a/src/main/java/com/a/Paths.java": `package com.a;\npublic interface Paths { String ROOT = "/a"; }`,
|
||||
"/p/b/src/main/java/com/b/Paths.java": `package com.b;\npublic interface Paths { String ROOT = "/b"; }`,
|
||||
});
|
||||
const text = `package com.app;
|
||||
import com.b.Paths;
|
||||
@RestController
|
||||
class C {
|
||||
@GetMapping(Paths.ROOT)
|
||||
String get() { return ""; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /b"]);
|
||||
});
|
||||
|
||||
it("looks each class up once, and leaves out a constant no project file declares", async () => {
|
||||
const files = project(defines);
|
||||
const text = `@RestController
|
||||
class C {
|
||||
@GetMapping(Missing.PATH)
|
||||
String a() { return ""; }
|
||||
@GetMapping(CockpitApiDefine.PATH_MAP)
|
||||
String b() { return ""; }
|
||||
@PostMapping(CockpitApiDefine.PATH_MAP + "/x")
|
||||
String c() { return ""; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /", "GET /map", "POST /map/x"]);
|
||||
expect(files.reads).toEqual(["/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Constants that mapping paths take from other classes: `Paths.API + "/orders"`,
|
||||
* statically imported ones and those of a superclass. Their classes are found by
|
||||
* file name in the index, read and kept until a Java / Kotlin file changes.
|
||||
*/
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Constants, type ExternalConstant } from "./endpoints";
|
||||
import { allClasses, parseSource, type Expr, type SourceFile } from "./source";
|
||||
|
||||
export interface ConstantFiles {
|
||||
/** The project's files called `name`. */
|
||||
filesNamed(name: string): Promise<string[]>;
|
||||
read(path: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
const EXTENSIONS = [".java", ".kt"];
|
||||
/** Classes looked up per pool, and how many hops from a controller to a constant's class. */
|
||||
const MAX_CLASSES = 256;
|
||||
const MAX_DEPTH = 3;
|
||||
/** Qualifiers Spring and the JDK own: never project classes. */
|
||||
const LIBRARY = new Set(["MediaType", "RequestMethod", "HttpMethod", "HttpHeaders", "HttpStatus", "String", "Integer"]);
|
||||
|
||||
const isClassName = (s: string | undefined): s is string => !!s && /^[A-Z]/.test(s);
|
||||
const simpleType = (t: string) => t.replace(/<.*$/, "").replace(/\(.*$/, "").trim().split(".").pop() ?? "";
|
||||
|
||||
/** `C` of `a.b.C.NAME` / `a.b.C.*` (a static import; the parser drops the `static`). */
|
||||
function staticImportClass(imp: string): string | null {
|
||||
const parts = imp.split(".");
|
||||
const owner = parts[parts.length - 2];
|
||||
return parts.length >= 3 && isClassName(owner) ? owner : null;
|
||||
}
|
||||
|
||||
/** Classes whose constants `file` can use without naming the class. */
|
||||
function inheritedClasses(file: SourceFile): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const imp of file.imports) {
|
||||
const c = staticImportClass(imp);
|
||||
if (c) out.add(c);
|
||||
}
|
||||
for (const c of allClasses(file)) if (c.superclass) out.add(simpleType(c.superclass));
|
||||
return [...out].filter(isClassName);
|
||||
}
|
||||
|
||||
function qualifiers(expr: Expr, out: Set<string>) {
|
||||
for (let i = 0; i + 2 < expr.length; i++) {
|
||||
const [a, dot, b] = [expr[i]!, expr[i + 1]!, expr[i + 2]!];
|
||||
if (a.kind === "id" && dot.kind === "p" && dot.text === "." && b.kind === "id" && isClassName(a.text))
|
||||
out.add(a.text);
|
||||
}
|
||||
}
|
||||
|
||||
/** Classes `file` takes constants from: qualifiers in annotations and constant initializers, and the inherited ones. */
|
||||
export function referencedClasses(file: SourceFile): string[] {
|
||||
const out = new Set(inheritedClasses(file));
|
||||
const classes = allClasses(file);
|
||||
for (const c of classes) {
|
||||
for (const a of [...c.annotations, ...c.methods.flatMap((m) => m.annotations)])
|
||||
for (const expr of a.args.values()) qualifiers(expr, out);
|
||||
for (const f of c.fields) if (f.init) qualifiers(f.init, out);
|
||||
}
|
||||
for (const f of file.fields) if (f.init) qualifiers(f.init, out);
|
||||
const own = new Set(classes.map((c) => c.name));
|
||||
return [...out].filter((c) => !own.has(c) && !LIBRARY.has(c));
|
||||
}
|
||||
|
||||
export class ConstantPool {
|
||||
/** Class name → constants of its file; `null` when no project file declares it. */
|
||||
private readonly classes = new Map<string, Constants | null>();
|
||||
private readonly pending = new Map<string, Promise<SourceFile | null>>();
|
||||
private readonly resolving = new Set<string>();
|
||||
|
||||
constructor(private readonly files: ConstantFiles) {}
|
||||
|
||||
/** Resolves the constants `file` takes from classes loaded so far. */
|
||||
resolverFor(file: SourceFile): ExternalConstant {
|
||||
const inherited = inheritedClasses(file);
|
||||
return (qualifier, name) => {
|
||||
for (const owner of qualifier ? [qualifier] : inherited) {
|
||||
const key = `${owner}.${name}`;
|
||||
const constants = this.classes.get(owner);
|
||||
if (!constants || this.resolving.has(key)) continue;
|
||||
this.resolving.add(key);
|
||||
try {
|
||||
const v = constants.named(name);
|
||||
if (v != null) return v;
|
||||
} finally {
|
||||
this.resolving.delete(key);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Loads the classes `files` take constants from, and theirs in turn; true when one of them is now known. */
|
||||
async load(files: readonly SourceFile[]): Promise<boolean> {
|
||||
let added = false;
|
||||
let round = [...files];
|
||||
for (let depth = 0; depth < MAX_DEPTH && round.length; depth++) {
|
||||
const next: SourceFile[] = [];
|
||||
for (const file of round)
|
||||
for (const name of referencedClasses(file)) {
|
||||
if (this.classes.has(name) && !this.pending.has(name)) continue;
|
||||
if (!this.pending.has(name) && this.classes.size >= MAX_CLASSES) continue;
|
||||
const isNew = !this.pending.has(name);
|
||||
const loaded = await this.lookup(name, file);
|
||||
if (!loaded) continue;
|
||||
added = true;
|
||||
if (isNew) next.push(loaded);
|
||||
}
|
||||
round = next;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
private lookup(name: string, from: SourceFile): Promise<SourceFile | null> {
|
||||
const running = this.pending.get(name);
|
||||
if (running) return running;
|
||||
this.classes.set(name, null);
|
||||
const promise = this.find(name, from)
|
||||
.then((file) => {
|
||||
if (file) {
|
||||
const constants = new Constants(file, this.resolverFor(file));
|
||||
// Nested classes too: `Outer.Inner.NAME` names `Inner`.
|
||||
for (const c of allClasses(file))
|
||||
if (c.name === name || !this.classes.get(c.name)) this.classes.set(c.name, constants);
|
||||
}
|
||||
return file;
|
||||
})
|
||||
.catch(() => null)
|
||||
.finally(() => this.pending.delete(name));
|
||||
this.pending.set(name, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** The file declaring class `name`, preferring the package `from` imports it from, then its own package. */
|
||||
private async find(name: string, from: SourceFile): Promise<SourceFile | null> {
|
||||
const imported = from.imports.find((i) => i.endsWith(`.${name}`) || i.includes(`.${name}.`));
|
||||
const pkg = imported ? imported.slice(0, imported.indexOf(`.${name}`)) : from.packageName;
|
||||
for (const ext of EXTENSIONS) {
|
||||
const paths = (await this.files.filesNamed(`${name}${ext}`)).map((p) => p.replace(/\\/g, "/"));
|
||||
if (!paths.length) continue;
|
||||
const suffix = `/${pkg.replace(/\./g, "/")}/${name}${ext}`;
|
||||
const path = paths.find((p) => p.endsWith(suffix)) ?? paths[0]!;
|
||||
const text = await this.files.read(path);
|
||||
if (text != null) return parseSource(text);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const projectFiles: ConstantFiles = {
|
||||
filesNamed: async (name) => (await call(commands.findFilesNamed(name))).map(String),
|
||||
read: async (path) => {
|
||||
try {
|
||||
return await call(commands.fsReadText(path));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let shared: ConstantPool | null = null;
|
||||
|
||||
/** The project's pool, shared by the route index and the editors. */
|
||||
export function constantPool(): ConstantPool {
|
||||
return (shared ??= new ConstantPool(projectFiles));
|
||||
}
|
||||
|
||||
/** Forgets the loaded classes (a Java / Kotlin file changed, or the project closed). */
|
||||
export function resetConstantPool() {
|
||||
shared = null;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { useProject } from "@/platform/project";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { constantPool } from "./constants";
|
||||
import { springAt, springControllers, type Controller, type Endpoint } from "./endpoints";
|
||||
import { bodyLookup, findHost, renderRequest, skeleton, type SourceReader } from "./request";
|
||||
import { parseSource } from "./source";
|
||||
@@ -39,6 +40,11 @@ export const sourceReader: SourceReader = {
|
||||
filesNamed: (name) => call(commands.findFilesNamed(name)),
|
||||
};
|
||||
|
||||
/** Controllers of `text`, with the other classes' constants loaded so far. */
|
||||
function controllersIn(text: string): Controller[] {
|
||||
return springControllers(text, (file) => constantPool().resolverFor(file));
|
||||
}
|
||||
|
||||
/** One request per endpoint (`paths[i]` picks another path of the mapping). */
|
||||
export interface Target {
|
||||
endpoint: Endpoint;
|
||||
@@ -109,7 +115,7 @@ function controllerItems(sourcePath: string, text: string, c: Controller): MenuI
|
||||
|
||||
/** Editor context menu items for the caret at `offset`: the generate actions (a path choice for several paths). */
|
||||
export function springMenuItems(sourcePath: string, text: string, offset: number): MenuItem[] {
|
||||
const { controller, endpoint } = springAt(springControllers(text), offset);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), offset);
|
||||
const items: MenuItem[] = [];
|
||||
if (endpoint)
|
||||
items.push(
|
||||
@@ -136,7 +142,7 @@ export async function generateAtCaret(scope: "endpoint" | "controller"): Promise
|
||||
const e = activeEditor();
|
||||
if (!e || !SPRING_LANGUAGES.has(e.ctx.language)) return;
|
||||
const text = e.view.state.doc.toString();
|
||||
const { controller, endpoint } = springAt(springControllers(text), e.view.state.selection.main.head);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), e.view.state.selection.main.head);
|
||||
const endpoints = scope === "endpoint" ? (endpoint ? [endpoint] : []) : (controller?.endpoints ?? []);
|
||||
if (!endpoints.length) {
|
||||
notifications().notify({
|
||||
@@ -178,7 +184,7 @@ function computeMarks(state: EditorState): Mark[] {
|
||||
const doc = state.doc;
|
||||
const marks: Mark[] = [];
|
||||
const lineStart = (offset: number) => doc.lineAt(Math.min(offset, doc.length)).from;
|
||||
for (const c of springControllers(doc.toString())) {
|
||||
for (const c of controllersIn(doc.toString())) {
|
||||
if (c.endpoints.length)
|
||||
marks.push({
|
||||
pos: lineStart(c.offset),
|
||||
@@ -239,9 +245,18 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
|
||||
const same =
|
||||
cur.length === found.length && cur.every((m, i) => m.pos === found[i]!.pos && m.key === found[i]!.key);
|
||||
if (!same) this.view.dispatch({ effects: setMarks.of(found) });
|
||||
// Paths built from other classes' constants: load those classes, then mark again.
|
||||
if (found.length) {
|
||||
const pool = constantPool();
|
||||
void pool.load([parseSource(this.view.state.doc.toString())]).then((loaded) => {
|
||||
if (loaded && pool === constantPool() && !this.destroyed) this.schedule(0);
|
||||
});
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
destroyed = false;
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
},
|
||||
@@ -250,7 +265,7 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
|
||||
// Only files that have mappings (the gutter found some) are parsed again here.
|
||||
if (!view.state.field(marksField, false)?.length) return [];
|
||||
const text = view.state.doc.toString();
|
||||
const { controller, endpoint } = springAt(springControllers(text), view.state.selection.main.head);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), view.state.selection.main.head);
|
||||
const out: ContributedIntention[] = [];
|
||||
if (endpoint)
|
||||
out.push({
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Spring Web request mappings of a Java / Kotlin source: `@RequestMapping` /
|
||||
* `@GetMapping`… methods of `@RestController` / `@Controller` classes, with
|
||||
* the class-level mapping applied. Constants are resolved within the file.
|
||||
* the class-level mapping applied. Constants are resolved within the file, and
|
||||
* through an {@link ExternalConstant} in other classes (`constants.ts`).
|
||||
*/
|
||||
import {
|
||||
allClasses,
|
||||
@@ -86,12 +87,27 @@ const MEDIA_TYPES: Record<string, string> = {
|
||||
TEXT_XML: "text/xml",
|
||||
};
|
||||
|
||||
/** The value of constant `name` of another class (`qualifier`, or an inherited / statically imported one when absent). */
|
||||
export type ExternalConstant = (qualifier: string | undefined, name: string) => string | null;
|
||||
|
||||
/** Evaluates string-valued annotation arguments within one file. */
|
||||
export class Constants {
|
||||
private readonly fields = new Map<string, Expr>();
|
||||
constructor(file: SourceFile) {
|
||||
for (const f of [...file.fields, ...allClasses(file).flatMap((c) => c.fields)])
|
||||
private readonly classes: Set<string>;
|
||||
constructor(
|
||||
file: SourceFile,
|
||||
private readonly external?: ExternalConstant,
|
||||
) {
|
||||
const classes = allClasses(file);
|
||||
for (const f of [...file.fields, ...classes.flatMap((c) => c.fields)])
|
||||
if (f.init && !this.fields.has(f.name)) this.fields.set(f.name, f.init);
|
||||
this.classes = new Set(classes.map((c) => c.name));
|
||||
}
|
||||
|
||||
/** The value of this file's constant `name`. */
|
||||
named(name: string): string | null {
|
||||
const init = this.fields.get(name);
|
||||
return init ? this.value(init, false, new Set([name])) : null;
|
||||
}
|
||||
|
||||
/** Every element of an array (`{a, b}`, `[a, b]`, `arrayOf(a, b)`) or the single value; unresolvable ones dropped. */
|
||||
@@ -133,7 +149,8 @@ export class Constants {
|
||||
(m, a: string | undefined, b: string | undefined) => {
|
||||
const name = (a ?? b)!;
|
||||
const init = seen.has(name) ? undefined : this.fields.get(name);
|
||||
return init ? (this.value(init, false, new Set([...seen, name])) ?? m) : m;
|
||||
if (init) return this.value(init, false, new Set([...seen, name])) ?? m;
|
||||
return seen.has(name) ? m : (this.external?.(undefined, name) ?? m);
|
||||
},
|
||||
);
|
||||
if (part.length === 1 && part[0]!.kind === "num") return part[0]!.text;
|
||||
@@ -144,11 +161,20 @@ export class Constants {
|
||||
const last = names[names.length - 1]!;
|
||||
const qualifier = names[names.length - 2];
|
||||
if (qualifier === "MediaType") return MEDIA_TYPES[last.replace(/_VALUE$/, "")] ?? null;
|
||||
// `Other.NAME` of a class declared elsewhere.
|
||||
if (qualifier && !this.classes.has(qualifier)) {
|
||||
const v = this.external?.(qualifier, last);
|
||||
if (v != null) return v;
|
||||
}
|
||||
const init = this.fields.get(last);
|
||||
if (init && !seen.has(last)) {
|
||||
seen.add(last);
|
||||
return this.value(init, enums, seen);
|
||||
}
|
||||
if (!qualifier && !enums) {
|
||||
const v = this.external?.(undefined, last);
|
||||
if (v != null) return v;
|
||||
}
|
||||
return enums ? last : null;
|
||||
}
|
||||
}
|
||||
@@ -267,8 +293,8 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
|
||||
};
|
||||
}
|
||||
|
||||
export function controllersOf(file: SourceFile): Controller[] {
|
||||
const constants = new Constants(file);
|
||||
export function controllersOf(file: SourceFile, external?: ExternalConstant): Controller[] {
|
||||
const constants = new Constants(file, external);
|
||||
const out: Controller[] = [];
|
||||
for (const cls of allClasses(file)) {
|
||||
if (!cls.annotations.some((a) => CONTROLLER.has(a.name))) continue;
|
||||
@@ -279,10 +305,11 @@ export function controllersOf(file: SourceFile): Controller[] {
|
||||
}
|
||||
|
||||
/** Controllers of a Java / Kotlin source, with their endpoints. */
|
||||
export function springControllers(text: string): Controller[] {
|
||||
export function springControllers(text: string, external?: (file: SourceFile) => ExternalConstant): Controller[] {
|
||||
// Cheap guard: most files are not controllers.
|
||||
if (!/@(?:[\w.]+\.)?(?:Rest)?Controller\b/.test(text)) return [];
|
||||
return controllersOf(parseSource(text));
|
||||
const file = parseSource(text);
|
||||
return controllersOf(file, external?.(file));
|
||||
}
|
||||
|
||||
/** The controller and endpoint whose declaration holds `offset`. */
|
||||
|
||||
@@ -3,6 +3,7 @@ import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { constantPool, resetConstantPool } from "./constants";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { controllerMethods, type ControllerMethod } from "./feign";
|
||||
import { parseSource } from "./source";
|
||||
@@ -38,6 +39,7 @@ export function isRouteSource(path: string): boolean {
|
||||
/** Forgets the index, so the next search rescans the project. */
|
||||
export function clearRouteIndex() {
|
||||
cached = null;
|
||||
resetConstantPool();
|
||||
}
|
||||
|
||||
/** The project's routes, scanned once per project and kept in memory. */
|
||||
@@ -67,6 +69,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
|
||||
const sources = await call(commands.springRouteSources());
|
||||
const routes: EndpointEntry[] = [];
|
||||
const controllers: ControllerTarget[] = [];
|
||||
const parsed = [];
|
||||
for (const source of sources) {
|
||||
const path = ipcPath(source.path);
|
||||
const folder = project ? projectFolder(project, path)?.root : root;
|
||||
@@ -74,9 +77,14 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
|
||||
const base = ipcPath(folder).replace(/\/$/, "");
|
||||
if (!isSameOrInside(path, base)) continue;
|
||||
if (!source.text.includes("Controller")) continue;
|
||||
const file = parseSource(source.text);
|
||||
parsed.push({ source, path, base, file: parseSource(source.text) });
|
||||
}
|
||||
// Mapping paths built from other classes' constants need those classes first.
|
||||
const pool = constantPool();
|
||||
await pool.load(parsed.map((p) => p.file));
|
||||
for (const { source, path, base, file } of parsed) {
|
||||
controllers.push(...controllerMethods(source.text, file).map((method) => ({ ...method, path })));
|
||||
for (const controller of controllersOf(file)) {
|
||||
for (const controller of controllersOf(file, pool.resolverFor(file))) {
|
||||
for (const endpoint of controller.endpoints) {
|
||||
const at = lineCol(source.text, endpoint.offset);
|
||||
// A mapping without a path answers nothing to look up by URL; the method
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Text } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { EndpointEntry } from "@/workbench/contributions";
|
||||
import { endpointsFor, requestPathAt } from "./urlNavigation";
|
||||
|
||||
const entry = (method: string, url: string, methodName = "handler"): EndpointEntry => ({
|
||||
method,
|
||||
url,
|
||||
controller: "C",
|
||||
methodName,
|
||||
path: "/p/C.java",
|
||||
rel: "C.java",
|
||||
line: 3,
|
||||
col: 4,
|
||||
});
|
||||
|
||||
describe("request URL navigation", () => {
|
||||
const doc = Text.of([
|
||||
"### 读取本区配置",
|
||||
"GET http://localhost:19210/api/cockpit/config?x=1",
|
||||
"Content-Type: application/json",
|
||||
"",
|
||||
"###",
|
||||
"POST {{host}}/api/orders/{{id}}/items",
|
||||
"http://localhost:8080/health",
|
||||
"GET /relative/path",
|
||||
]);
|
||||
const at = (line: number, col: number) => doc.line(line).from + col;
|
||||
|
||||
it("finds the method and the path of the URL under the caret", () => {
|
||||
const get = requestPathAt(doc, at(2, 30));
|
||||
expect(get).toMatchObject({ method: "GET", path: "/api/cockpit/config" });
|
||||
expect(doc.sliceString(get!.from, get!.to)).toBe("/api/cockpit/config");
|
||||
expect(requestPathAt(doc, at(6, 20))).toMatchObject({ method: "POST", path: "/api/orders/{{id}}/items" });
|
||||
expect(requestPathAt(doc, at(7, 5))).toMatchObject({ method: "GET", path: "/health" });
|
||||
expect(requestPathAt(doc, at(8, 8))).toMatchObject({ method: "GET", path: "/relative/path" });
|
||||
expect(requestPathAt(doc, at(1, 5))).toBeNull();
|
||||
expect(requestPathAt(doc, at(3, 5))).toBeNull();
|
||||
expect(requestPathAt(doc, at(2, 1))).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the endpoint by method, path variables and a context path", () => {
|
||||
const endpoints = [
|
||||
entry("GET", "/api/cockpit/config", "getConfig"),
|
||||
entry("POST", "/api/cockpit/config", "saveConfig"),
|
||||
entry("POST", "/api/orders/{id}/items", "addItem"),
|
||||
entry("GET", "/files/**", "file"),
|
||||
entry("*", "/any", "any"),
|
||||
];
|
||||
const names = (method: string, path: string) => endpointsFor(endpoints, method, path).map((e) => e.methodName);
|
||||
expect(names("GET", "/api/cockpit/config")).toEqual(["getConfig"]);
|
||||
expect(names("POST", "/api/orders/{{id}}/items")).toEqual(["addItem"]);
|
||||
expect(names("POST", "/api/orders/42/items")).toEqual(["addItem"]);
|
||||
expect(names("GET", "/files/a/b.txt")).toEqual(["file"]);
|
||||
expect(names("DELETE", "/any")).toEqual(["any"]);
|
||||
expect(names("GET", "/app/api/cockpit/config")).toEqual(["getConfig"]);
|
||||
expect(names("PUT", "/api/cockpit/config")).toEqual([]);
|
||||
expect(names("GET", "/api/cockpit")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Navigate › Declaration (⌘-click, ⌘B) on a request URL in a `.http` file: the
|
||||
* handler of the endpoint the request reaches (a Spring mapping, a plugin's
|
||||
* endpoint), matched by method and path.
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import { docOf } from "@/editor/lsp/lsp";
|
||||
import { registerNavigationProvider, type NavigationMatch } from "@/editor/navigationProviders";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { searchEndpoints, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { HTTP_LANGUAGE } from "./editor";
|
||||
import { METHODS } from "./language";
|
||||
|
||||
/** The request line holding `offset`: its method and the path part of the URL, as document offsets. */
|
||||
export function requestPathAt(
|
||||
doc: Text,
|
||||
offset: number,
|
||||
): { method: string; path: string; from: number; to: number } | null {
|
||||
const line = doc.lineAt(offset);
|
||||
const m = new RegExp(`^(\\s*(?:(${METHODS.join("|")})\\s+)?)(\\S+)`).exec(line.text);
|
||||
if (!m) return null;
|
||||
const url = m[3]!;
|
||||
// The scheme and host, or a `{{host}}` variable standing for them.
|
||||
const origin = /^(?:https?:\/\/[^/\s?#]+|\{\{[^}]+\}\}(?=\/))/.exec(url)?.[0];
|
||||
if (origin === undefined && !(m[2] && url.startsWith("/"))) return null;
|
||||
const start = line.from + m[1]!.length;
|
||||
if (offset < start || offset > start + url.length) return null;
|
||||
const path = url.slice(origin?.length ?? 0).replace(/[?#].*$/, "");
|
||||
// No path (`http://host`): the whole URL is the link.
|
||||
const from = path ? start + (origin?.length ?? 0) : start;
|
||||
return { method: m[2] ?? "GET", path: path || "/", from, to: path ? from + path.length : start + url.length };
|
||||
}
|
||||
|
||||
const segments = (p: string) => p.split("/").filter(Boolean);
|
||||
|
||||
/** How `request` segments match mapping `pattern` segments: `{var}`, `*` and `**` in the mapping, `{{var}}` in the request. */
|
||||
function matches(request: string[], pattern: string[]): boolean {
|
||||
if (!pattern.length) return !request.length;
|
||||
const [p, ...rest] = pattern;
|
||||
if (p === "**") return request.some((_, i) => matches(request.slice(i), rest)) || matches([], rest);
|
||||
if (!request.length) return false;
|
||||
const [r, ...more] = request;
|
||||
const variable = /^\{[^}]*\}$/.test(p!) || p === "*" || /^\{\{[^}]+\}\}$/.test(r!);
|
||||
return (variable || decodeURIComponent(r!) === p) && matches(more, rest);
|
||||
}
|
||||
|
||||
/** Endpoints `method` `path` reaches: the exact path, else after a context path (`/app` + mapping). */
|
||||
export function endpointsFor(endpoints: readonly EndpointEntry[], method: string, path: string): EndpointEntry[] {
|
||||
const request = segments(path);
|
||||
const sameMethod = endpoints.filter((e) => e.method === method || e.method === "*");
|
||||
const exact = sameMethod.filter((e) => matches(request, segments(e.url)));
|
||||
if (exact.length) return exact;
|
||||
for (let skip = 1; skip < request.length; skip++) {
|
||||
const found = sameMethod.filter((e) => matches(request.slice(skip), segments(e.url)));
|
||||
if (found.length) return found;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function urlTargets(doc: Text, offset: number): Promise<NavigationMatch | null> {
|
||||
const at = requestPathAt(doc, offset);
|
||||
if (!at) return null;
|
||||
const endpoints = await searchEndpoints(useProject.getState().project?.root ?? null);
|
||||
const found = endpointsFor(endpoints, at.method, at.path);
|
||||
if (!found.length) return null;
|
||||
return {
|
||||
from: at.from,
|
||||
to: at.to,
|
||||
targets: found.map((e) => ({
|
||||
path: e.path,
|
||||
range: { start: { line: e.line, col: e.col }, end: { line: e.line, col: e.col + e.methodName.length } },
|
||||
name: e.handler ?? `${e.controller}.${e.methodName}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function registerUrlNavigation(): () => void {
|
||||
return registerNavigationProvider(async (view, offset) => {
|
||||
const doc = docOf(view);
|
||||
if (!doc || doc.virtual || doc.language !== HTTP_LANGUAGE) return null;
|
||||
return urlTargets(view.state.doc, offset);
|
||||
});
|
||||
}
|
||||
@@ -132,6 +132,23 @@ describe("recent files switcher", () => {
|
||||
).toEqual(["README.md"]);
|
||||
});
|
||||
|
||||
it("shows a scratch file under its root's label", () => {
|
||||
const labelled = [{ path: "/data/scratches", label: "Scratches" }];
|
||||
const items = filterRecentFiles(
|
||||
["/data/scratches/api/generated-requests.http", "/p/src/Main.kt", "/elsewhere/a.txt"],
|
||||
"",
|
||||
{
|
||||
root: "/p",
|
||||
labelled,
|
||||
},
|
||||
);
|
||||
expect(items.map((f) => [f.rel, f.dir])).toEqual([
|
||||
["Scratches/api/generated-requests.http", "Scratches/api"],
|
||||
["src/Main.kt", "src"],
|
||||
["/elsewhere/a.txt", "/elsewhere"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("preselects the previous file when the current one is first", () => {
|
||||
const items = filterRecentFiles(paths, "", { root: "/p" });
|
||||
expect(initialFileIndex(items, "/p/src/Main.kt", "")).toBe(1);
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
maybeEditorService,
|
||||
toolWindowService,
|
||||
useContributions,
|
||||
useProjectViewRoots,
|
||||
useFileDecoration,
|
||||
type OpenEditorTab,
|
||||
type ToolWindowContribution,
|
||||
@@ -91,6 +92,14 @@ function RecentFilesDialog() {
|
||||
const step = useRecentPopup((s) => s.step);
|
||||
const edited = useTracking((s) => s.edited);
|
||||
const root = useProject((s) => s.project?.root ?? null);
|
||||
const viewRoots = useProjectViewRoots((s) => s.roots);
|
||||
const labelled = useMemo(
|
||||
() =>
|
||||
[...viewRoots.values()].flatMap((r) =>
|
||||
r.scope === "scratches" && r.path ? [{ path: r.path, label: r.label }] : [],
|
||||
),
|
||||
[viewRoots],
|
||||
);
|
||||
const toolWindows = useContributions((s) => s.toolWindows);
|
||||
const [paths, setPaths] = useState<string[] | null>(null);
|
||||
// Switcher: the open editor tabs (files and others), when the editor service lists them.
|
||||
@@ -135,13 +144,13 @@ function RecentFilesDialog() {
|
||||
const files = useMemo(
|
||||
() =>
|
||||
tabs
|
||||
? switcherItems(paths ?? [], tabs, query, root).filter((f) => !removed.has(f.path))
|
||||
? switcherItems(paths ?? [], tabs, query, root, labelled).filter((f) => !removed.has(f.path))
|
||||
: filterRecentFiles(
|
||||
(paths ?? []).filter((p) => !removed.has(p)),
|
||||
query,
|
||||
{ root, edited, editedOnly },
|
||||
{ root, labelled, edited, editedOnly },
|
||||
),
|
||||
[paths, tabs, removed, query, root, edited, editedOnly],
|
||||
[paths, tabs, removed, query, root, labelled, edited, editedOnly],
|
||||
);
|
||||
const fileRows = useMemo(() => files.map((f) => ({ ...f, key: f.path })), [files]);
|
||||
const tools = useMemo(() => switcherToolWindows(toolWindows.values(), !!root, query), [toolWindows, root, query]);
|
||||
|
||||
@@ -18,10 +18,27 @@ export interface RecentFileItem {
|
||||
editor?: { input: EditorInput; icon: string };
|
||||
}
|
||||
|
||||
/** A folder outside the project shown by its label (the Scratches root): `Scratches/requests.http`. */
|
||||
export interface LabelledRoot {
|
||||
path: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function displayPath(path: string, root: string | null, labelled: readonly LabelledRoot[] = []): string {
|
||||
if (root && path.startsWith(root + "/")) return path.slice(root.length + 1);
|
||||
const outside = labelled.find((r) => path.startsWith(r.path + "/"));
|
||||
return outside ? `${outside.label}/${path.slice(outside.path.length + 1)}` : path;
|
||||
}
|
||||
|
||||
export function filterRecentFiles(
|
||||
paths: readonly string[],
|
||||
query: string,
|
||||
opts: { root: string | null; edited?: ReadonlySet<string>; editedOnly?: boolean },
|
||||
opts: {
|
||||
root: string | null;
|
||||
labelled?: readonly LabelledRoot[];
|
||||
edited?: ReadonlySet<string>;
|
||||
editedOnly?: boolean;
|
||||
},
|
||||
): RecentFileItem[] {
|
||||
const out: RecentFileItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
@@ -29,7 +46,7 @@ export function filterRecentFiles(
|
||||
if (seen.has(path)) continue;
|
||||
seen.add(path);
|
||||
if (opts.editedOnly && !opts.edited?.has(path)) continue;
|
||||
const rel = opts.root && path.startsWith(opts.root + "/") ? path.slice(opts.root.length + 1) : path;
|
||||
const rel = displayPath(path, opts.root, opts.labelled);
|
||||
const name = basename(rel);
|
||||
let indices: number[] = [];
|
||||
if (query.trim()) {
|
||||
@@ -70,6 +87,7 @@ export function switcherItems(
|
||||
tabs: readonly OpenEditorTab[],
|
||||
query: string,
|
||||
root: string | null,
|
||||
labelled: readonly LabelledRoot[] = [],
|
||||
): RecentFileItem[] {
|
||||
const fileTabs = new Map(tabs.filter(isFileTab).map((t) => [t.input.path!, t]));
|
||||
const ordered = [
|
||||
@@ -83,7 +101,7 @@ export function switcherItems(
|
||||
const out: RecentFileItem[] = [];
|
||||
for (const t of ordered) {
|
||||
if (isFileTab(t)) {
|
||||
out.push(...filterRecentFiles([t.input.path!], query, { root }));
|
||||
out.push(...filterRecentFiles([t.input.path!], query, { root, labelled }));
|
||||
continue;
|
||||
}
|
||||
let indices: number[] = [];
|
||||
|
||||
@@ -252,7 +252,7 @@
|
||||
background: var(--bg-app);
|
||||
border-left: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border);
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
}
|
||||
.host :global(.cm-diffDivider:hover) {
|
||||
|
||||
@@ -234,7 +234,7 @@
|
||||
overflow:hidden, so any rule drawn into the 8px gap would be clipped away. */
|
||||
inset-inline-start: -4px;
|
||||
width: 8px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
|
||||
@@ -120,7 +120,7 @@ export function useColumnResize(target: ResizeTarget) {
|
||||
x: e.clientX,
|
||||
element: e.currentTarget,
|
||||
pointerId: e.pointerId,
|
||||
releaseCursor: lockDragCursor("ew-resize"),
|
||||
releaseCursor: lockDragCursor("col-resize"),
|
||||
};
|
||||
listeners.current = { blur, escape };
|
||||
e.currentTarget.setPointerCapture?.(e.pointerId);
|
||||
|
||||
@@ -352,7 +352,7 @@ const theme = EditorView.baseTheme({
|
||||
height: "4px",
|
||||
borderRadius: "2px",
|
||||
background: "var(--focus-ring, #3574f0)",
|
||||
cursor: "ns-resize",
|
||||
cursor: "row-resize",
|
||||
},
|
||||
".cm-reviewHandle[data-disabled]": { opacity: "0.4", cursor: "default" },
|
||||
".cm-reviewHandle-start": { top: "-2px" },
|
||||
|
||||
@@ -16,13 +16,14 @@
|
||||
outline: none;
|
||||
transition: background var(--dur) var(--ease);
|
||||
}
|
||||
/* Dividers use col-/row-resize: WebKit on macOS 26.2 shows the arrow for ew-/ns-resize. */
|
||||
.handle[aria-orientation="vertical"] {
|
||||
width: 1px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.handle[aria-orientation="horizontal"] {
|
||||
height: 1px;
|
||||
cursor: ns-resize;
|
||||
cursor: row-resize;
|
||||
}
|
||||
.handle::after {
|
||||
content: "";
|
||||
|
||||
@@ -10,9 +10,9 @@ afterEach(() => {
|
||||
|
||||
describe("lockDragCursor", () => {
|
||||
it("holds the cursor until the drag ends", () => {
|
||||
const release = lockDragCursor("ew-resize");
|
||||
const release = lockDragCursor("col-resize");
|
||||
expect(html.getAttribute("data-drag-cursor")).toBe("");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("ew-resize");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("col-resize");
|
||||
|
||||
release();
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
@@ -20,27 +20,27 @@ describe("lockDragCursor", () => {
|
||||
});
|
||||
|
||||
it("ignores a repeated release", () => {
|
||||
const release = lockDragCursor("ns-resize");
|
||||
const release = lockDragCursor("row-resize");
|
||||
release();
|
||||
release();
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
});
|
||||
|
||||
it("restores an outer drag after a nested one ends", () => {
|
||||
const outer = lockDragCursor("ew-resize");
|
||||
const outer = lockDragCursor("col-resize");
|
||||
const inner = lockDragCursor("nwse-resize");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("nwse-resize");
|
||||
|
||||
inner();
|
||||
expect(html.getAttribute("data-drag-cursor")).toBe("");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("ew-resize");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("col-resize");
|
||||
|
||||
outer();
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
});
|
||||
|
||||
it("releases when the pointer goes up outside the handle", () => {
|
||||
lockDragCursor("ew-resize");
|
||||
lockDragCursor("col-resize");
|
||||
document.dispatchEvent(new Event("pointerup", { bubbles: true }));
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("");
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* default one mid-drag. `global.css` keys off `data-drag-cursor` instead and
|
||||
* wins over those cursors with `!important`.
|
||||
*/
|
||||
export type DragCursor = "ew-resize" | "ns-resize" | "nwse-resize";
|
||||
export type DragCursor = "col-resize" | "row-resize" | "ew-resize" | "ns-resize" | "nwse-resize";
|
||||
|
||||
const active = new Set<() => void>();
|
||||
let listening = false;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
flex: none;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
padding: 0 var(--window-tabs-right, 40px) var(--space-0-5) var(--window-tabs-left, 40px);
|
||||
padding: 0 var(--window-tabs-right, 40px) var(--island-gap) var(--window-tabs-left, 40px);
|
||||
min-width: 0;
|
||||
}
|
||||
.tabs {
|
||||
|
||||
@@ -179,17 +179,17 @@
|
||||
.undocked[data-slot^="left"] > .undockEdge {
|
||||
inset: 0 0 0 auto;
|
||||
width: var(--island-gap);
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.undocked[data-slot^="right"] > .undockEdge {
|
||||
inset: 0 auto 0 0;
|
||||
width: var(--island-gap);
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.undocked[data-slot^="bottom"] > .undockEdge {
|
||||
inset: 0 0 auto;
|
||||
height: var(--island-gap);
|
||||
cursor: ns-resize;
|
||||
cursor: row-resize;
|
||||
}
|
||||
.undockEdge:focus-visible {
|
||||
background: color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
@@ -210,10 +210,10 @@
|
||||
grid-area: gap-bottom;
|
||||
}
|
||||
.gap[aria-orientation="vertical"] {
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.gap[aria-orientation="horizontal"] {
|
||||
cursor: ns-resize;
|
||||
cursor: row-resize;
|
||||
}
|
||||
/* A slightly wider hit area than the gap itself. */
|
||||
.gap::before {
|
||||
@@ -286,7 +286,7 @@
|
||||
flex: none;
|
||||
width: 0;
|
||||
outline: none;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.stripeHandle::before {
|
||||
content: "";
|
||||
|
||||
@@ -269,7 +269,7 @@ function StripeHandle({
|
||||
const origin = e.clientX;
|
||||
const icons = parseFloat(getComputedStyle(stripe).getPropertyValue("--stripe-icon-button")) || 30;
|
||||
const start = names ? width : icons;
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next = { names, width, px: start };
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
@@ -945,7 +945,7 @@ function SplitHandle({ anchor, hidden }: { anchor: ToolWindowAnchor; hidden: boo
|
||||
e.preventDefault();
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const origin = stacked ? e.clientY : e.clientX;
|
||||
const releaseCursor = lockDragCursor(stacked ? "ns-resize" : "ew-resize");
|
||||
const releaseCursor = lockDragCursor(stacked ? "row-resize" : "col-resize");
|
||||
let ratio: number | null = null;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
@@ -1018,7 +1018,7 @@ function UndockEdge({ anchor }: { anchor: ToolWindowAnchor }) {
|
||||
e.preventDefault();
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const origin = vertical ? e.clientX : e.clientY;
|
||||
const releaseCursor = lockDragCursor(vertical ? "ew-resize" : "ns-resize");
|
||||
const releaseCursor = lockDragCursor(vertical ? "col-resize" : "row-resize");
|
||||
let next = m.size;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
@@ -1201,7 +1201,7 @@ function GapHandle({
|
||||
const el = e.currentTarget;
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const origin = vertical ? e.clientX : e.clientY;
|
||||
const releaseCursor = lockDragCursor(vertical ? "ew-resize" : "ns-resize");
|
||||
const releaseCursor = lockDragCursor(vertical ? "col-resize" : "row-resize");
|
||||
let next = m.size;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
|
||||
Reference in new issue
Block a user