feat(endpoints): add an Endpoints tool window (#7997)

* feat(endpoints): add endpoints tool window

Supersedes #883.

Co-authored-by: Roberto Scinocca <[email protected]>

* fix(endpoints): translate the plural and use spacing tokens

---------

Co-authored-by: arookieofc <[email protected]>
Co-authored-by: Roberto Scinocca <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
Цей коміт міститься в:
authored and GitHub committed 2026-12-05 10:36:02 +08:00
1 джерело 6d576e8ff5
коміт 630e56a263
13 files changed
+1265 -7

No files matched your search

+10 -5
Переглянути файл
@@ -32,13 +32,18 @@ const DEFAULT_HOSTS: Record<string, string> = {
Symfony: "http://127.0.0.1:8000",
};
/** The endpoint as an HTTP Client request block, with the development server's address resolved. */
export async function endpointRequest(endpoint: EndpointEntry): Promise<string> {
// The server address of the endpoint's module (`server.port`, context path), as for Spring mappings.
const host =
(!endpoint.pluginId && DEFAULT_HOSTS[endpoint.framework ?? ""]) ||
(await findHost(endpoint.path, useProject.getState().project?.root ?? null, sourceReader));
return renderEndpoint(endpoint, host);
}
export async function openEndpoint(endpoint: EndpointEntry): Promise<void> {
try {
// The server address of the endpoint's module (`server.port`, context path), as for Spring mappings.
const host =
(!endpoint.pluginId && DEFAULT_HOSTS[endpoint.framework ?? ""]) ||
(await findHost(endpoint.path, useProject.getState().project?.root ?? null, sourceReader));
await appendGeneratedRequests([renderEndpoint(endpoint, host)]);
await appendGeneratedRequests([await endpointRequest(endpoint)]);
} catch (e) {
notifications().notify({ level: "error", title: tx("Cannot generate the HTTP request"), body: String(e) });
}
+272
Переглянути файл
@@ -0,0 +1,272 @@
.view {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.body {
flex: 1;
min-height: 0;
}
.body > * {
height: 100%;
}
.panel {
min-height: 0;
display: flex;
flex-direction: column;
}
.panel > * {
flex: 1;
min-height: 0;
}
.spacer {
flex: 1;
}
/* Module / Type / Framework filters and details toggle. */
.filterBar {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
min-height: 32px;
padding: 4px 6px 4px 8px;
border-bottom: 1px solid var(--border);
}
.filterButton {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
height: 24px;
padding: 0 4px 0 6px;
border: none;
border-radius: var(--radius-small);
background: transparent;
color: var(--fg-secondary);
font: inherit;
white-space: nowrap;
cursor: pointer;
}
.filterButton:hover:not(:disabled) {
background: var(--bg-hover);
}
.filterButton:disabled {
opacity: 0.5;
cursor: default;
}
.filterActive {
color: var(--accent, var(--info));
}
.filterChevron {
color: var(--fg-muted);
}
/* Search field. */
.searchBar {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
height: 30px;
padding: 0 8px;
border-bottom: 1px solid var(--border);
}
.searchIcon {
flex: none;
color: var(--fg-muted);
}
.search {
flex: 1;
min-width: 0;
}
/* Module / file rows. */
.groupRow {
display: flex;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
white-space: nowrap;
}
.groupIcon {
flex: none;
color: var(--fg-muted);
}
.groupName {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-emphasis);
}
.count {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
margin-left: 4px;
}
/* `/photos/:id [GET]` … PhotosController */
.endpoint {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex: 1;
min-width: 0;
white-space: nowrap;
}
.endpointIcon {
flex: none;
color: var(--fg-muted);
}
.path {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.verb {
flex: none;
font-family: var(--font-mono);
font-size: var(--fs-small);
font-weight: 600;
}
.get {
color: var(--info);
}
.post {
color: var(--success, var(--info));
}
.put {
color: var(--warning);
}
.delete {
color: var(--danger);
}
.controller {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-muted);
}
/* Details pane. */
.details {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
border-top: 1px solid var(--border);
}
.detailTabs {
flex: none;
border: 0;
background: none;
border-bottom: 1px solid var(--border);
}
.detailEmpty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
color: var(--fg-muted);
}
.httpTab {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.request {
flex: 1;
min-height: 0;
overflow: auto;
padding: 6px 0;
font-family: var(--font-mono);
font-size: var(--fs-code, var(--fs-ui));
background: var(--bg-editor);
}
.requestLine {
display: flex;
align-items: center;
min-height: 22px;
white-space: pre;
}
.requestMain {
background: var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent));
}
.requestGutter {
flex: none;
width: 34px;
display: flex;
justify-content: center;
}
.requestText {
flex: 1;
min-width: 0;
padding-right: 8px;
color: var(--fg-muted);
}
.requestMain .requestText {
color: var(--fg);
}
.detailButtons {
flex: none;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
padding: 8px;
border-top: 1px solid var(--border);
}
/* Documentation tab. */
.docs {
flex: 1;
min-height: 0;
overflow: auto;
padding: 8px 12px;
}
.docList {
margin: 0;
display: grid;
grid-template-columns: max-content 1fr;
gap: var(--space-1) var(--space-4);
}
.docRow {
display: contents;
}
.docRow dt {
color: var(--fg-muted);
}
.docRow dd {
margin: 0;
font-family: var(--font-mono);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.link {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: bottom;
padding: 0;
border: none;
background: none;
color: var(--link, var(--info));
font: inherit;
cursor: pointer;
text-decoration: underline;
}
.loading {
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 12px;
color: var(--fg-muted);
}
+572
Переглянути файл
@@ -0,0 +1,572 @@
/**
* Endpoints tool window: Module / Type / Framework filters, search, endpoints
* grouped by module, and details with the generated HTTP Client request.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { create } from "zustand";
import clsx from "clsx";
import { tx } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import { editorService, notifications, useOccurrenceNavigator } from "@/workbench/contributions";
import {
Button,
EmptyState,
Icon,
IconButton,
Input,
Menu,
Spinner,
SplitGroup,
SplitHandle,
SplitPanel,
Tabs,
Tree,
T,
type MenuItem,
type TreeHandle,
type TreeRowState,
} from "@/ui";
import { endpointRequest, renderEndpoint } from "../endpoints";
import { appendGeneratedRequests } from "../generatedRequests";
import { runRequest } from "../store";
import {
distinct,
filterEndpoints,
groupBy,
navigationTarget,
relativeTo,
type EndpointGroup,
type EndpointRow,
} from "./model";
import { refreshEndpoints, useEndpoints } from "./store";
import styles from "./EndpointsView.module.css";
export const ENDPOINTS_WINDOW = "endpoints";
const OPTIONS_KEY = "openidea.endpoints.view.v1";
interface ViewOptions {
groupByFile: boolean;
autoscroll: boolean;
details: boolean;
}
function loadOptions(): Partial<ViewOptions> {
try {
return JSON.parse(globalThis.localStorage?.getItem(OPTIONS_KEY) ?? "{}") as Partial<ViewOptions>;
} catch {
return {};
}
}
export const useEndpointsViewOptions = create<ViewOptions>(() => ({
groupByFile: false,
autoscroll: false,
details: true,
...loadOptions(),
}));
useEndpointsViewOptions.subscribe((s) => {
try {
globalThis.localStorage?.setItem(OPTIONS_KEY, JSON.stringify(s));
} catch {
/* storage unavailable */
}
});
type DetailsTab = "http" | "docs";
interface ViewState {
query: string;
hiddenModules: Set<string>;
hiddenTypes: Set<string>;
hiddenFrameworks: Set<string>;
collapsed: Set<string>;
tab: DetailsTab;
currentId: string | null;
}
export const useEndpointsView = create<ViewState>(() => ({
query: "",
hiddenModules: new Set(),
hiddenTypes: new Set(),
hiddenFrameworks: new Set(),
collapsed: new Set(),
tab: "http",
currentId: null,
}));
export function resetEndpointsView(): void {
useEndpointsView.setState({
query: "",
hiddenModules: new Set(),
hiddenTypes: new Set(),
hiddenFrameworks: new Set(),
collapsed: new Set(),
currentId: null,
});
}
export function useEndpointsHeaderMenu(): MenuItem[] {
const o = useEndpointsViewOptions();
const toggle = (key: keyof ViewOptions) => () => useEndpointsViewOptions.setState({ [key]: !o[key] });
return [
{ id: "group", label: "Group by File", checked: o.groupByFile, run: toggle("groupByFile") },
{ id: "details", label: "Show Details", checked: o.details, run: toggle("details") },
{ id: "autoscroll", label: "Autoscroll to Source", checked: o.autoscroll, run: toggle("autoscroll") },
];
}
type Node =
| { kind: "module"; key: string; name: string; endpoints: EndpointRow[] }
| { kind: "file"; key: string; group: EndpointGroup }
| { kind: "endpoint"; key: string; endpoint: EndpointRow };
export function openEndpointSource(e: EndpointRow, focus: boolean) {
const { path, line, col } = navigationTarget(e);
void editorService().openFile(path, { selection: { line, col }, focus, preview: !focus });
}
export function useVisibleEndpoints(): EndpointRow[] {
const endpoints = useEndpoints((s) => s.endpoints);
const query = useEndpointsView((s) => s.query);
const hiddenModules = useEndpointsView((s) => s.hiddenModules);
const hiddenTypes = useEndpointsView((s) => s.hiddenTypes);
const hiddenFrameworks = useEndpointsView((s) => s.hiddenFrameworks);
return useMemo(
() =>
filterEndpoints(
endpoints.filter(
(e) => !hiddenModules.has(e.module) && !hiddenTypes.has(e.type) && !hiddenFrameworks.has(e.framework),
),
query,
),
[endpoints, query, hiddenModules, hiddenTypes, hiddenFrameworks],
);
}
export function EndpointsHeaderActions() {
const loading = useEndpoints((s) => s.loading);
return (
<IconButton
icon="refresh"
size="small"
title="Refresh"
disabled={loading}
onClick={() => void refreshEndpoints()}
/>
);
}
function FilterMenu({
label,
entries,
hidden,
onToggle,
}: {
label: string;
entries: string[];
hidden: ReadonlySet<string>;
onToggle: (entry: string) => void;
}) {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const active = entries.some((e) => hidden.has(e));
const items: MenuItem[] = entries.map((e) => ({
id: e,
label: e,
verbatim: true,
checked: !hidden.has(e),
run: () => onToggle(e),
}));
return (
<>
<button
type="button"
className={clsx(styles.filterButton, active && styles.filterActive)}
disabled={entries.length === 0}
aria-haspopup="menu"
aria-expanded={!!anchor}
onClick={(e) => setAnchor(anchor ? null : e.currentTarget)}
>
<T>{label}</T>
<Icon name="chevron-down" size={16} className={styles.filterChevron} />
</button>
<Menu open={!!anchor} anchor={anchor} items={items} onClose={() => setAnchor(null)} aria-label={label} />
</>
);
}
const toggleIn = (set: Set<string>, entry: string): Set<string> => {
const next = new Set(set);
if (!next.delete(entry)) next.add(entry);
return next;
};
function FilterBar() {
const endpoints = useEndpoints((s) => s.endpoints);
const project = useProject((s) => s.project?.name ?? "");
const { hiddenModules, hiddenTypes, hiddenFrameworks } = useEndpointsView();
const details = useEndpointsViewOptions((o) => o.details);
const modules = distinct([project, ...endpoints.map((e) => e.module)].filter(Boolean));
const types = distinct(endpoints.map((e) => e.type));
const frameworks = distinct(endpoints.map((e) => e.framework));
const filter = (
label: string,
entries: string[],
hidden: ReadonlySet<string>,
key: "hiddenModules" | "hiddenTypes" | "hiddenFrameworks",
) => (
<FilterMenu
label={label}
entries={entries}
hidden={hidden}
onToggle={(entry) => useEndpointsView.setState((s) => ({ [key]: toggleIn(s[key], entry) }))}
/>
);
return (
<div className={styles.filterBar}>
{filter("Module", modules, hiddenModules, "hiddenModules")}
{filter("Type", types, hiddenTypes, "hiddenTypes")}
{filter("Framework", frameworks, hiddenFrameworks, "hiddenFrameworks")}
<span className={styles.spacer} />
<IconButton
icon="eye"
size="small"
title="Show Details"
pressed={details}
onClick={() => useEndpointsViewOptions.setState({ details: !details })}
/>
</div>
);
}
function SearchBar() {
const query = useEndpointsView((s) => s.query);
return (
<div className={styles.searchBar}>
<Icon name="search" size={16} className={styles.searchIcon} />
<Input
variant="bare"
className={styles.search}
placeholder="Search endpoints"
aria-label="Search endpoints"
value={query}
onChange={(e) => useEndpointsView.setState({ query: e.target.value })}
/>
</div>
);
}
function methodClass(method: string): string | undefined {
switch (method) {
case "GET":
return styles.get;
case "POST":
return styles.post;
case "PUT":
case "PATCH":
return styles.put;
case "DELETE":
return styles.delete;
default:
return undefined;
}
}
function EndpointRowView({ endpoint: e }: { endpoint: EndpointRow }) {
return (
<span className={styles.endpoint} title={`${e.method} ${e.path} → ${e.target}`}>
<Icon name="file-http" size={16} className={styles.endpointIcon} />
<span className={styles.path}>{e.path}</span>
<span className={clsx(styles.verb, methodClass(e.method))}>[{e.method}]</span>
<span className={styles.spacer} />
<span className={styles.controller}>{e.targetClass}</span>
</span>
);
}
function HttpClientTab({ endpoint: e }: { endpoint: EndpointRow }) {
const [block, setBlock] = useState<string | null>(null);
useEffect(() => {
let live = true;
endpointRequest(e.entry)
.catch(() => renderEndpoint(e.entry))
.then((text) => {
if (live) setBlock(text);
});
return () => {
live = false;
};
}, [e]);
const lines = useMemo(() => {
const seen = new Map<string, number>();
return (block ?? "")
.trimEnd()
.split("\n")
.map((line, i) => {
const occurrence = seen.get(line) ?? 0;
seen.set(line, occurrence + 1);
return { key: `${line}:${occurrence}`, line, number: i };
});
}, [block]);
const submit = () => {
if (block) void runRequest(null, block, 0);
};
const openInEditor = () => {
if (!block) return;
void appendGeneratedRequests([block]).catch((err) => {
notifications().notify({ level: "error", title: tx("Cannot generate the HTTP request"), body: String(err) });
});
};
const displayMethod = e.method === "*" ? "GET" : e.method;
return (
<div className={styles.httpTab}>
<div className={styles.request} role="region" aria-label={tx("HTTP request")}>
{!block ? (
<div className={styles.loading}>
<Spinner size={14} /> <T>Reading endpoints…</T>
</div>
) : (
lines.map(({ key, line, number }) => (
<div key={key} className={clsx(styles.requestLine, number === 1 && styles.requestMain)}>
<span className={styles.requestGutter}>
{number === 0 && <IconButton icon="run" size="small" title="Submit Request" onClick={submit} />}
</span>
<span className={styles.requestText}>
{number === 1 ? (
<>
<span className={clsx(styles.verb, methodClass(displayMethod))}>{displayMethod}</span>{" "}
{line.replace(/^\S+\s+/, "")}
</>
) : (
line
)}
</span>
</div>
))
)}
</div>
<div className={styles.detailButtons}>
<Button disabled={!block} onClick={submit}>
Submit Request
</Button>
<Button disabled={!block} onClick={openInEditor}>
Open in Editor
</Button>
</div>
</div>
);
}
function DocumentationTab({ endpoint: e }: { endpoint: EndpointRow }) {
const root = useProject((s) => s.project?.root ?? "");
const rows: [string, string][] = [
["Path", e.path],
["Method", e.method],
["Handler", e.target],
["Framework", e.framework],
];
return (
<div className={styles.docs}>
<dl className={styles.docList}>
{rows.map(([k, v]) => (
<div key={k} className={styles.docRow}>
<dt>
<T>{k}</T>
</dt>
<dd>{v}</dd>
</div>
))}
<div className={styles.docRow}>
<dt>
<T>Defined in</T>
</dt>
<dd>
<button type="button" className={styles.link} onClick={() => openEndpointSource(e, true)}>
{relativeTo(root, e.file)}:{e.line + 1}
</button>
</dd>
</div>
</dl>
</div>
);
}
function DetailsPane({ endpoint }: { endpoint: EndpointRow | null }) {
const tab = useEndpointsView((s) => s.tab);
return (
<div className={styles.details}>
<Tabs
variant="compact"
aria-label="Endpoint details"
className={styles.detailTabs}
activeId={tab}
onSelect={(id) => useEndpointsView.setState({ tab: id as DetailsTab })}
items={[
{ id: "http", label: "HTTP Client" },
{ id: "docs", label: "Documentation" },
]}
/>
{!endpoint ? (
<div className={styles.detailEmpty}>
<T>Select an endpoint</T>
</div>
) : tab === "http" ? (
<HttpClientTab key={endpoint.id} endpoint={endpoint} />
) : (
<DocumentationTab endpoint={endpoint} />
)}
</div>
);
}
const count = (n: number) => (n === 1 ? tx`${n} endpoint` : tx`${n} endpoints`);
export function EndpointsView() {
const { endpoints: all, loading, loaded, error } = useEndpoints();
const root = useProject((s) => s.project?.root ?? null);
const endpoints = useVisibleEndpoints();
const { groupByFile: grouped, details } = useEndpointsViewOptions();
const collapsed = useEndpointsView((s) => s.collapsed);
const currentId = useEndpointsView((s) => s.currentId);
const current = useMemo(() => endpoints.find((e) => e.id === currentId) ?? null, [endpoints, currentId]);
const tree = useRef<TreeHandle>(null);
useEffect(() => {
void refreshEndpoints();
}, [root]);
useOccurrenceNavigator(ENDPOINTS_WINDOW, (dir, focus) => {
const step = tree.current?.selectOccurrence(dir);
const n = step?.node as Node | undefined;
if (!step || n?.kind !== "endpoint") return null;
openEndpointSource(n.endpoint, focus);
return step;
});
const roots = useMemo<Node[]>(
() =>
groupBy(endpoints, (e) => e.module).map((g) => ({
kind: "module",
key: `module:${g.key}`,
name: g.key,
endpoints: g.endpoints,
})),
[endpoints],
);
const getChildren = useCallback(
(n: Node): Node[] | undefined => {
const leaf = (e: EndpointRow): Node => ({ kind: "endpoint", key: e.id, endpoint: e });
if (n.kind === "module")
return grouped
? groupBy(n.endpoints, (e) => e.file).map((g) => ({ kind: "file", key: `file:${n.name}:${g.key}`, group: g }))
: n.endpoints.map(leaf);
if (n.kind === "file") return n.group.endpoints.map(leaf);
return undefined;
},
[grouped],
);
const expanded = useMemo(() => {
const keys = new Set<string>();
for (const m of roots) {
if (m.kind !== "module" || collapsed.has(m.key)) continue;
keys.add(m.key);
if (grouped)
for (const g of groupBy(m.endpoints, (e) => e.file)) {
const key = `file:${m.name}:${g.key}`;
if (!collapsed.has(key)) keys.add(key);
}
}
return keys;
}, [roots, collapsed, grouped]);
const renderNode = (n: Node, _state: TreeRowState) => {
if (n.kind === "module")
return (
<span className={styles.groupRow}>
<Icon name="module" size={16} className={styles.groupIcon} />
<span className={styles.groupName}>{n.name}</span>
<span className={styles.count}>{count(n.endpoints.length)}</span>
</span>
);
if (n.kind === "file")
return (
<span className={styles.groupRow}>
<Icon name="file" size={16} className={styles.groupIcon} />
<span className={styles.groupName}>{basename(n.group.key)}</span>
<span className={styles.count}>{count(n.group.endpoints.length)}</span>
</span>
);
return <EndpointRowView endpoint={n.endpoint} />;
};
const empty = error ? (
<EmptyState icon="toolwindow-endpoints" title="Endpoints unavailable">
{error}
</EmptyState>
) : loading || !loaded ? (
<div className={styles.loading}>
<Spinner size={14} /> <T>Reading endpoints…</T>
</div>
) : all.length ? (
<EmptyState icon="toolwindow-endpoints" title="No endpoints match the filters" />
) : (
<EmptyState icon="toolwindow-endpoints" title="No endpoints found" />
);
return (
<div className={styles.view}>
<FilterBar />
<SearchBar />
<div className={styles.body}>
<SplitGroup orientation="vertical" storageKey="openidea.endpoints.split">
<SplitPanel id="endpoints" minSize={120} className={styles.panel}>
<Tree<Node>
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) =>
n.kind === "module"
? n.name
: n.kind === "file"
? basename(n.group.key)
: `${n.endpoint.path} ${n.endpoint.method}`
}
getChildren={getChildren}
isExpandable={(n) => n.kind !== "endpoint"}
expanded={expanded}
onExpandedChange={(_next, node, isExpanded) =>
useEndpointsView.setState((s) => {
const c = new Set(s.collapsed);
if (isExpanded) c.delete(node.key);
else c.add(node.key);
return { collapsed: c };
})
}
renderNode={renderNode}
onActivate={(n) => {
if (n.kind === "endpoint") openEndpointSource(n.endpoint, true);
}}
onSelectionChange={(_sel, node) => {
if (node?.kind !== "endpoint") return;
useEndpointsView.setState({ currentId: node.endpoint.id });
if (useEndpointsViewOptions.getState().autoscroll) openEndpointSource(node.endpoint, false);
}}
activateExpandable={false}
multiSelect={false}
aria-label="Endpoints"
empty={empty}
/>
</SplitPanel>
{details && (
<>
<SplitHandle />
<SplitPanel id="details" minSize={120} defaultSize="40%" className={styles.panel}>
<DetailsPane endpoint={current} />
</SplitPanel>
</>
)}
</SplitGroup>
</div>
</div>
);
}
+66
Переглянути файл
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import type { EndpointEntry } from "@/workbench/contributions";
import { endpointRow, filterEndpoints, groupBy, navigationTarget, relativeTo } from "./model";
function entry(overrides: Partial<EndpointEntry> = {}): EndpointEntry {
return {
method: "GET",
url: "/photos/{id}",
controller: "PhotosController",
methodName: "show",
path: "/project/src/photos.rs",
rel: "src/photos.rs",
line: 0,
col: 4,
...overrides,
};
}
describe("Endpoints tool window model", () => {
it("maps the shared endpoint entry into display data", () => {
const row = endpointRow(entry({ framework: "FastAPI" }), 0, null);
expect(row).toMatchObject({
method: "GET",
path: "/photos/{id}",
target: "PhotosController.show",
targetClass: "PhotosController",
framework: "FastAPI",
type: "HTTP",
file: "/project/src/photos.rs",
line: 0,
col: 4,
});
});
it("uses the shared 0-based declaration coordinates unchanged", () => {
expect(navigationTarget(endpointRow(entry({ line: 0, col: 0 }), 0, null))).toEqual({
path: "/project/src/photos.rs",
line: 0,
col: 0,
});
});
it("defaults built-in endpoints to Spring and plugin endpoints to Plugin", () => {
expect(endpointRow(entry(), 0, null).framework).toBe("Spring");
expect(endpointRow(entry({ pluginId: "demo" }), 0, null).framework).toBe("Plugin");
});
it("matches every whitespace-separated search word", () => {
const rows = [
endpointRow(entry(), 0, null),
endpointRow(entry({ method: "POST", url: "/users", controller: "UsersController" }), 1, null),
];
expect(filterEndpoints(rows, "photos get")).toEqual([rows[0]]);
expect(filterEndpoints(rows, "photos show")).toEqual([rows[0]]);
expect(filterEndpoints(rows, "")).toEqual(rows);
});
it("groups in first-use order and makes project-relative paths", () => {
const rows = [endpointRow(entry(), 0, null), endpointRow(entry({ path: "/project/other.rs" }), 1, null)];
expect(groupBy(rows, (e) => e.type).map((g) => [g.key, g.endpoints.length])).toEqual([["HTTP", 2]]);
expect(relativeTo("/project", "/project/src/photos.rs")).toBe("src/photos.rs");
expect(relativeTo("/project/", "/project/src/photos.rs")).toBe("src/photos.rs");
expect(relativeTo("C:\\project", "C:\\project\\src\\photos.rs")).toBe("src\\photos.rs");
expect(relativeTo("/project", "/elsewhere/photos.rs")).toBe("/elsewhere/photos.rs");
});
});
+96
Переглянути файл
@@ -0,0 +1,96 @@
/** Framework-neutral rows of the Endpoints tool window over the shared endpoint model. */
import type { ProjectInfo } from "@/platform/ipc";
import { projectFolder } from "@/platform/project";
import type { EndpointEntry } from "@/workbench/contributions";
export interface EndpointRow {
/** Stable within one refresh. */
id: string;
entry: EndpointEntry;
/** `GET`, `POST`, …; `*` means any method. */
method: string;
/** `/photos/{id}` as the framework writes it. */
path: string;
/** What handles it, short (`PhotosController.show`, `photos#show`). */
target: string;
/** The handler's class/framework as the row's right column. */
targetClass: string;
/** The file and 0-based line/column of the declaration. */
file: string;
line: number;
col: number;
/** Module (workspace member) the endpoint belongs to. */
module: string;
/** Provider's framework name, shown in the Framework filter. */
framework: string;
/** Endpoint type (`HTTP` for the current model), shown in the Type filter. */
type: string;
}
export function endpointRow(e: EndpointEntry, index: number, project: ProjectInfo | null): EndpointRow {
const target = e.handler ?? [e.controller, e.methodName].filter(Boolean).join(".");
const module = projectFolder(project, e.path)?.name ?? project?.name ?? "";
return {
id: `${e.path}:${e.line}:${e.col}:${e.method}:${e.url}:${index}`,
entry: e,
method: e.method,
path: e.url,
target,
targetClass: e.controller || e.framework || e.pluginId || "",
file: e.path,
line: e.line,
col: e.col,
module,
// The built-in provider is Spring's; plugin and dynamic providers name their framework.
framework: e.framework ?? (e.pluginId ? "Plugin" : "Spring"),
type: "HTTP",
};
}
/** Case-insensitive match of every whitespace-separated word of `query` against method, path, target and handler. */
export function filterEndpoints(endpoints: readonly EndpointRow[], query: string): EndpointRow[] {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
if (!words.length) return [...endpoints];
return endpoints.filter((e) => {
const text = `${e.method} ${e.path} ${e.target} ${e.targetClass}`.toLowerCase();
return words.every((w) => text.includes(w));
});
}
export interface EndpointGroup<K extends string = string> {
key: K;
endpoints: EndpointRow[];
}
/** Endpoints per `key`, in the order the keys are first used. */
export function groupBy<K extends string>(
endpoints: readonly EndpointRow[],
key: (e: EndpointRow) => K,
): EndpointGroup<K>[] {
const groups = new Map<K, EndpointRow[]>();
for (const e of endpoints) {
const k = key(e);
const list = groups.get(k);
if (list) list.push(e);
else groups.set(k, [e]);
}
return [...groups].map(([k, list]) => ({ key: k, endpoints: list }));
}
/** Where "jump to source" goes: the declaration (already 0-based in the shared model). */
export function navigationTarget(e: EndpointRow): { path: string; line: number; col: number } {
return { path: e.file, line: Math.max(0, e.line), col: Math.max(0, e.col) };
}
export function relativeTo(root: string, path: string): string {
const trimmed = root.replace(/[/\\]+$/, "");
if (!trimmed) return path;
const normRoot = trimmed.replaceAll("\\", "/");
const normPath = path.replaceAll("\\", "/");
return normPath.startsWith(`${normRoot}/`) ? path.slice(trimmed.length + 1) : path;
}
/** Distinct values in first-use order. */
export function distinct(values: readonly string[]): string[] {
return [...new Set(values)];
}
+90
Переглянути файл
@@ -0,0 +1,90 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import type { EndpointEntry } from "@/workbench/contributions";
const mocks = vi.hoisted(() => ({
searchEndpoints: vi.fn<(root: string | null) => Promise<EndpointEntry[]>>(),
listeners: new Set<() => void>(),
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
searchEndpoints: (root: string | null) => mocks.searchEndpoints(root),
onEndpointsChanged: (fn: () => void) => {
mocks.listeners.add(fn);
return () => mocks.listeners.delete(fn);
},
}));
const { installEndpointsStore, refreshEndpoints, useEndpoints } = await import("./store");
const project = (root: string, name: string) =>
({ root, name, folders: [{ root, name }] }) as unknown as ReturnType<typeof useProject.getState>["project"];
const sample = (url: string, path: string): EndpointEntry => ({
method: "GET",
url,
controller: "ApiController",
methodName: "list",
path,
rel: "src/Api.java",
line: 10,
col: 2,
});
describe("Endpoints tool window store", () => {
let dispose: (() => void) | null = null;
afterEach(() => {
dispose?.();
dispose = null;
useProject.setState({ project: null });
useEndpoints.setState({ endpoints: [], loading: false, loaded: false, error: null });
mocks.searchEndpoints.mockReset();
mocks.listeners.clear();
});
it("ignores stale rejections and stale resolutions across project switches", async () => {
const onProjectChange = vi.fn();
useProject.setState({ project: project("/a", "a") });
dispose = installEndpointsStore(onProjectChange);
let rejectA!: (err: Error) => void;
mocks.searchEndpoints.mockReturnValueOnce(
new Promise((_, reject) => {
rejectA = reject;
}),
);
const pending = refreshEndpoints();
expect(useEndpoints.getState().loading).toBe(true);
// Switching projects invalidates the in-flight request and resets state.
useProject.setState({ project: project("/b", "b") });
expect(onProjectChange).toHaveBeenCalledTimes(1);
expect(useEndpoints.getState()).toMatchObject({ endpoints: [], loading: false, loaded: false, error: null });
// Even if we switch back to /a before the first request settles, its rejection must be ignored.
useProject.setState({ project: project("/a", "a") });
rejectA(new Error("boom"));
await pending;
expect(useEndpoints.getState()).toMatchObject({ endpoints: [], loading: false, loaded: false, error: null });
});
it("refreshes on onEndpointsChanged only after the window has loaded", async () => {
useProject.setState({ project: project("/a", "a") });
dispose = installEndpointsStore();
mocks.searchEndpoints.mockResolvedValue([sample("/items", "/a/src/Api.java")]);
// Never loaded yet -> provider change should not trigger a search.
mocks.listeners.forEach((fn) => fn());
expect(mocks.searchEndpoints).not.toHaveBeenCalled();
await refreshEndpoints();
expect(useEndpoints.getState().endpoints).toHaveLength(1);
expect(mocks.searchEndpoints).toHaveBeenCalledTimes(1);
// Once loaded -> provider change triggers a refresh.
mocks.listeners.forEach((fn) => fn());
await vi.waitFor(() => expect(mocks.searchEndpoints).toHaveBeenCalledTimes(2));
});
});
+71
Переглянути файл
@@ -0,0 +1,71 @@
/** The shared endpoint model as the Endpoints tool window reads it. */
import { create } from "zustand";
import { useProject } from "@/platform/project";
import { onEndpointsChanged, searchEndpoints } from "@/workbench/contributions";
import { endpointRow, type EndpointRow } from "./model";
interface EndpointsState {
endpoints: EndpointRow[];
loading: boolean;
/** Answered at least once for this project. */
loaded: boolean;
error: string | null;
}
export const useEndpoints = create<EndpointsState>(() => ({
endpoints: [],
loading: false,
loaded: false,
error: null,
}));
let refreshSeq = 0;
/** Reads every registered endpoint provider again. */
export async function refreshEndpoints(): Promise<void> {
const seq = ++refreshSeq;
const project = useProject.getState().project;
const root = project?.root ?? null;
if (!root) {
useEndpoints.setState({ endpoints: [], loading: false, loaded: true, error: null });
return;
}
useEndpoints.setState({ loading: true, error: null });
try {
const found = await searchEndpoints(root);
if (seq !== refreshSeq || root !== (useProject.getState().project?.root ?? null)) return;
useEndpoints.setState({
endpoints: found.map((e, index) => endpointRow(e, index, useProject.getState().project)),
loading: false,
loaded: true,
error: null,
});
} catch (error) {
if (seq !== refreshSeq || root !== (useProject.getState().project?.root ?? null)) return;
useEndpoints.setState({
loading: false,
loaded: true,
error: error instanceof Error ? error.message : String(error),
});
}
}
/** Keeps an opened window in step with endpoint providers and the open project. */
export function installEndpointsStore(onProjectChange?: () => void): () => void {
const unsubscribe = onEndpointsChanged(() => {
const s = useEndpoints.getState();
if (s.loaded || s.loading) void refreshEndpoints();
});
const projectUnsubscribe = useProject.subscribe((state, previous) => {
if (state.project?.root !== previous.project?.root) {
refreshSeq++;
useEndpoints.setState({ endpoints: [], loading: false, loaded: false, error: null });
onProjectChange?.();
}
});
return () => {
refreshSeq++;
unsubscribe();
projectUnsubscribe();
};
}
+39
Переглянути файл
@@ -15,7 +15,9 @@ import {
notifications,
registerMenuGroup,
registerServiceView,
registerToolWindow,
showServiceView,
toolWindowService,
} from "@/workbench/contributions";
import { registerFileNavigation } from "./fileNavigation";
import { registerUrlNavigation } from "./urlNavigation";
@@ -32,6 +34,14 @@ import {
springEditorExtension,
} from "./spring/editor";
import { endpointEditorExtension, OPEN_ENDPOINT, openEndpoint } from "./endpoints";
import {
ENDPOINTS_WINDOW,
EndpointsHeaderActions,
EndpointsView,
resetEndpointsView,
useEndpointsHeaderMenu,
} from "./endpointsWindow/EndpointsView";
import { installEndpointsStore, refreshEndpoints } from "./endpointsWindow/store";
import type { EndpointEntry } from "@/workbench/contributions";
import { registerPhpEndpointProvider } from "./php/routeIndex";
import { registerPythonEndpointProvider } from "./python/routeIndex";
@@ -146,6 +156,18 @@ async function newRequest(directory?: string) {
export function activate(): () => void {
const disposers = [
installEndpointsStore(resetEndpointsView),
registerToolWindow({
id: ENDPOINTS_WINDOW,
title: "Endpoints",
icon: "toolwindow-endpoints",
anchor: "right",
order: 45,
stripe: "shown",
component: EndpointsView,
headerActions: EndpointsHeaderActions,
headerMenu: useEndpointsHeaderMenu,
}),
registerSpringEndpointProvider(),
registerPythonEndpointProvider(),
registerPhpEndpointProvider(),
@@ -257,6 +279,23 @@ export function activate(): () => void {
if (e) await runAll(filePath(e.ctx.path, e.ctx.virtual), e.view.state.doc.toString());
},
},
{
id: "endpoints.show",
title: "Endpoints",
category: "Tools",
icon: "toolwindow-endpoints",
keywords: ["routes", "rest", "url", "api"],
when: "projectOpen",
run: () => toolWindowService().show(ENDPOINTS_WINDOW, true),
},
{
id: "endpoints.refresh",
title: "Refresh Endpoints",
category: "Tools",
icon: "refresh",
when: "projectOpen",
run: () => refreshEndpoints(),
},
{
id: "http.newRequest",
title: "New HTTP Request",
+24 -1
Переглянути файл
@@ -5762,5 +5762,28 @@
"Run Device": "Run Device",
"Select Device": "Select Device",
"Cannot prepare the device for '{name}'": "Cannot prepare the device for '{name}'",
"Preparing {name}…\n": "Preparing {name}…\n"
"Preparing {name}…\n": "Preparing {name}…\n",
"Autoscroll to Source": "Autoscroll to Source",
"Defined in": "Defined in",
"Documentation": "Documentation",
"Endpoint details": "Endpoint details",
"Endpoints": "Endpoints",
"Endpoints unavailable": "Endpoints unavailable",
"Group by File": "Group by File",
"Handler": "Handler",
"HTTP Client": "HTTP Client",
"HTTP request": "HTTP request",
"Method": "Method",
"Module": "Module",
"No endpoints found": "No endpoints found",
"No endpoints match the filters": "No endpoints match the filters",
"Reading endpoints…": "Reading endpoints…",
"Refresh": "Refresh",
"Refresh Endpoints": "Refresh Endpoints",
"Search endpoints": "Search endpoints",
"Select an endpoint": "Select an endpoint",
"Show Details": "Show Details",
"Submit Request": "Submit Request",
"{n} endpoint": "{n} endpoint",
"{n} endpoints": "{n} endpoints"
}
+16 -1
Переглянути файл
@@ -12661,5 +12661,20 @@
"Installation": "安装位置",
"Host architecture": "主机架构",
"Detect toolchains": "检测工具链",
"For MinGW, empty fields are detected from the toolset, otherwise from PATH. Visual Studio uses vcvarsall for its compiler, headers and libraries. Explicit compilers and build tools are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "对于 MinGW,留空的字段会从工具集检测,否则从 PATH 检测。Visual Studio 通过 vcvarsall 提供编译器、头文件和库。显式设置的编译器和构建工具会作为 CMAKE_C_COMPILER、CMAKE_CXX_COMPILER 和 CMAKE_MAKE_PROGRAM 传给 CMake。"
"For MinGW, empty fields are detected from the toolset, otherwise from PATH. Visual Studio uses vcvarsall for its compiler, headers and libraries. Explicit compilers and build tools are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "对于 MinGW,留空的字段会从工具集检测,否则从 PATH 检测。Visual Studio 通过 vcvarsall 提供编译器、头文件和库。显式设置的编译器和构建工具会作为 CMAKE_C_COMPILER、CMAKE_CXX_COMPILER 和 CMAKE_MAKE_PROGRAM 传给 CMake。",
"Defined in": "定义于",
"Endpoint details": "端点详情",
"Endpoints unavailable": "端点不可用",
"Group by File": "按文件分组",
"HTTP request": "HTTP 请求",
"No endpoints found": "未找到端点",
"No endpoints match the filters": "没有符合过滤条件的端点",
"Reading endpoints…": "正在读取端点…",
"Refresh Endpoints": "刷新端点",
"Search endpoints": "搜索端点",
"Select an endpoint": "选择一个端点",
"Show Details": "显示详情",
"Submit Request": "提交请求",
"{n} endpoint": "{n} 个端点",
"{n} endpoints": "{n} 个端点"
}
+1
Переглянути файл
@@ -274,6 +274,7 @@ const ICONS = {
"toolwindow-jupyter-variables": "openidea/toolwindows/jupyterVariables",
"toolwindow-nuget": "openidea/toolwindows/nuget",
"toolwindow-ports": "openidea/toolwindows/ports",
"toolwindow-endpoints": "openidea/toolwindows/endpoints",
// Coding agents (logos via Paseo)
"agent-claude": "openidea/agents/claude",
"agent-codex": "openidea/agents/codex",
+4
Переглянути файл
@@ -0,0 +1,4 @@
<!-- OpenIDEA: Endpoints tool window (open ring with a connection point) -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.4 4.9A5.5 5.5 0 1 0 13.5 8" stroke="#6C707E" stroke-linecap="round"/><circle cx="12.75" cy="3.25" r="1.75" stroke="#6C707E"/><circle cx="8" cy="8" r="1.5" fill="#6C707E"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 365 B

+4
Переглянути файл
@@ -0,0 +1,4 @@
<!-- OpenIDEA: Endpoints tool window (open ring with a connection point), stripe size -->
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.3 6.3A7 7 0 1 0 17 10" stroke="#6C707E" stroke-width="1.2" stroke-linecap="round"/><circle cx="15.75" cy="4.25" r="2" stroke="#6C707E" stroke-width="1.2"/><circle cx="10" cy="10" r="1.8" fill="#6C707E"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 410 B