Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 94966475dc feat(navigation): Navigate › Related Symbol for header/source and Rails files
Related Symbol… (⌃⌘↑ / Ctrl+Alt+Home, in the Navigate menu and the editor's
Go To submenu) goes to the files tied to the current one by convention: one
target opens directly, several open a Choose Target list, none shows
"No related symbols". Providers register through editor/relatedProviders.

- C, C++, Objective-C and CUDA: a header and its source files of the same
  name, the ones in the same folder first.
- Rails: a controller action and its views, a controller and all its views,
  helper and model, a view and its controller action, a helper and its
  controller and views, a model and its controller and migrations.

Refs #900
2026-11-16 14:57:40 +08:00
19 змінених файлів з 512 додано та 6 видалено

No files matched your search

+2
Переглянути файл
@@ -52,6 +52,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
| **Go to Type Declaration** | `⇧⌘B` | `Ctrl+Shift+B` |
| **Super Method** | `⌘U` | `Ctrl+U` |
| **Navigate › Test** | `⇧⌘T` | `Ctrl+Shift+T` |
| **Navigate › Related Symbol…** | `⌃⌘↑` | `Ctrl+Alt+Home` |
| **Back** / **Forward** | `⌘[` / `⌘]` | `Ctrl+Alt+Left` / `Ctrl+Alt+Right` |
| **Next Method** / **Previous Method** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
@@ -59,6 +60,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations. With several targets it shows a chooser.
Going to files, classes and symbols by name is covered in [Search and navigation](/en/guide/search).
+1
Переглянути файл
@@ -38,6 +38,7 @@ Some shortcuts depend on where the focus is. For example `⌘N` / `Alt+Insert` i
| Go to Type Declaration | `⇧⌘B` / `⌃⇧B` | `Ctrl+Shift+B` |
| Navigate › Super Method | `⌘U` | `Ctrl+U` |
| Navigate › Test | `⇧⌘T` | `Ctrl+Shift+T` |
| Navigate › Related Symbol… | `⌃⌘↑` | `Ctrl+Alt+Home` |
| Find Usages | `⌥F7` | `Alt+F7` |
| Show Usages | `⌥⌘F7` | `Ctrl+Alt+F7` |
| Highlight Usages in File | `⇧⌘F7` | `Ctrl+Shift+F7` |
+2
Переглянути файл
@@ -52,6 +52,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
| **转到类型声明** | `⇧⌘B` | `Ctrl+Shift+B` |
| **超方法** | `⌘U` | `Ctrl+U` |
| **导航 › 测试** | `⇧⌘T` | `Ctrl+Shift+T` |
| **导航 › 相关符号…** | `⌃⌘↑` | `Ctrl+Alt+Home` |
| **后退** / **前进** | `⌘[` / `⌘]` | `Ctrl+Alt+Left` / `Ctrl+Alt+Right` |
| **下一个方法** / **上一个方法** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
@@ -59,6 +60,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
- 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移。有多个目标时显示选择列表。
按名称跳转到文件、类和符号,见 [搜索与导航](/zh/guide/search)。
+1
Переглянути файл
@@ -38,6 +38,7 @@ macOS 符号:`⌘` Command、`⌥` Option、`⌃` Control、`⇧` Shift、`↵
| 转到类型声明 | `⇧⌘B` / `⌃⇧B` | `Ctrl+Shift+B` |
| 导航 › super 方法 | `⌘U` | `Ctrl+U` |
| 导航 › 测试 | `⇧⌘T` | `Ctrl+Shift+T` |
| 导航 › 相关符号… | `⌃⌘↑` | `Ctrl+Alt+Home` |
| 查找用法 | `⌥F7` | `Alt+F7` |
| 显示用法 | `⌥⌘F7` | `Ctrl+Alt+F7` |
| 高亮文件中的用法 | `⇧⌘F7` | `Ctrl+Shift+F7` |
+1
Переглянути файл
@@ -466,6 +466,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("navigate.typeDeclaration", "Type Declaration"),
act("navigate.superMethod", "Super Method"),
act("navigate.gotoTest", "Test"),
act("navigate.relatedSymbol", "Related Symbol…"),
SEP,
act("navigate.fileStructure", "File Structure"),
act("navigate.showFilePath", "File Path"),
+1
Переглянути файл
@@ -917,6 +917,7 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "navigate.implementation", label: "Implementation(s)" },
{ kind: "action", action: "navigate.typeDeclaration", label: "Type Declaration" },
{ kind: "action", action: "navigate.superMethod", label: "Super Method" },
{ kind: "action", action: "navigate.relatedSymbol", label: "Related Symbol…" },
{ kind: "action", action: "navigate.gotoTest", label: "Test" },
{ kind: "separator" },
{ kind: "action", action: "find.usages", label: "Find Usages" },
+31
Переглянути файл
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { counterpartNames, headerSourceItems, rankCounterparts } from "./headerSource";
describe("header / source counterparts", () => {
it("names the other side by stem", () => {
expect(counterpartNames("/p/src/foo.cpp")?.names).toContain("foo.h");
expect(counterpartNames("/p/src/foo.cpp")?.group).toBe("Header");
expect(counterpartNames("/p/include/foo.hpp")?.names).toEqual(expect.arrayContaining(["foo.cc", "foo.mm"]));
expect(counterpartNames("/p/include/foo.HPP")?.group).toBe("Source");
expect(counterpartNames("/p/main.rs")).toBeNull();
expect(counterpartNames("/p/Makefile")).toBeNull();
});
it("prefers the same folder, else the nearest", () => {
expect(rankCounterparts("/p/src/a/foo.cpp", ["/p/include/foo.h", "/p/src/a/foo.h", "/p/src/a/foo.hpp"])).toEqual([
"/p/src/a/foo.h",
"/p/src/a/foo.hpp",
]);
expect(rankCounterparts("/p/src/a/foo.cpp", ["/x/foo.h", "/p/include/foo.h", "/p/src/b/foo.h"])).toEqual([
"/p/src/b/foo.h",
"/p/include/foo.h",
"/x/foo.h",
]);
});
it("collects the matches of every counterpart name", async () => {
const files: Record<string, string[]> = { "foo.h": ["/p/foo.h"], "foo.hpp": ["/q/foo.hpp"] };
const items = await headerSourceItems("/p/foo.c", async (n) => files[n] ?? []);
expect(items).toEqual([{ path: "/p/foo.h", group: "Header" }]);
});
});
+53
Переглянути файл
@@ -0,0 +1,53 @@
/** Related Symbol for C, C++, Objective-C and CUDA: a header and its source files, by name. */
import type { RelatedItem } from "@/editor/relatedProviders";
import { tx } from "@/platform/i18n";
const HEADERS = ["h", "hh", "hpp", "hxx", "h++", "cuh"];
const SOURCES = ["c", "cc", "cpp", "cxx", "c++", "m", "mm", "cu"];
function split(path: string): { dir: string; stem: string; ext: string } | null {
const slash = path.lastIndexOf("/");
const name = path.slice(slash + 1);
const dot = name.lastIndexOf(".");
if (dot <= 0) return null;
return { dir: path.slice(0, slash), stem: name.slice(0, dot), ext: name.slice(dot + 1).toLowerCase() };
}
/** The file names whose stem matches `path`'s on the other side (header ↔ source), or none. */
export function counterpartNames(path: string): { names: string[]; group: string } | null {
const parts = split(path);
if (!parts) return null;
if (HEADERS.includes(parts.ext)) return { names: SOURCES.map((e) => `${parts.stem}.${e}`), group: tx("Source") };
if (SOURCES.includes(parts.ext)) return { names: HEADERS.map((e) => `${parts.stem}.${e}`), group: tx("Header") };
return null;
}
function sharedPrefix(a: string, b: string): number {
const x = a.split("/");
const y = b.split("/");
let n = 0;
while (n < x.length && n < y.length && x[n] === y[n]) n++;
return n;
}
/**
* The counterparts of `path` among `candidates`: those in its own folder when there are any
* (the pair to switch to), else all of them, nearest folders first.
*/
export function rankCounterparts(path: string, candidates: readonly string[]): string[] {
const dir = split(path)?.dir ?? "";
const unique = [...new Set(candidates)].filter((c) => c !== path);
const local = unique.filter((c) => split(c)?.dir === dir);
if (local.length) return local;
return unique.sort((a, b) => sharedPrefix(path, b) - sharedPrefix(path, a) || a.localeCompare(b));
}
export async function headerSourceItems(
path: string,
findNamed: (name: string) => Promise<string[]>,
): Promise<RelatedItem[]> {
const counterpart = counterpartNames(path);
if (!counterpart) return [];
const found = await Promise.all(counterpart.names.map((n) => findNamed(n).catch(() => [] as string[])));
return rankCounterparts(path, found.flat()).map((p) => ({ path: p, group: counterpart.group }));
}
+59 -4
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Navigate › Test / Test Subject (⇧⌘T), Super Method (⌘U), Next / Previous
* Method (⌃⇧↓ / ⌃⇧↑). Editor-side like editor/lsp (whose popups it uses);
* Navigate › Test / Test Subject (⇧⌘T), Super Method (⌘U), Related Symbol (⌃⌘↑), Next /
* Previous Method (⌃⇧↓ / ⌃⇧↑). Editor-side like editor/lsp (whose popups it uses);
* the file templates are reached through the `templates.newFromTemplate` action.
*/
import { EditorSelection } from "@codemirror/state";
@@ -13,12 +13,14 @@ import { dedupeLocations, locationItems, navigateTo } from "@/editor/lsp/navigat
import { showHint } from "@/editor/lsp/hint";
import { registerActions, executeAction, type Action } from "@/platform/actions";
import { call, commands, isCancelled, type Location, type OutlineItem, type Pos } from "@/platform/ipc";
import { basename, useProject } from "@/platform/project";
import { basename, relativePath, useProject } from "@/platform/project";
import { currentRoots } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { editorService } from "@/workbench/contributions";
import { fileIconName } from "@/ui";
import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders";
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { headerSourceItems } from "./headerSource";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
import { tx } from "@/platform/i18n";
@@ -195,15 +197,68 @@ function editorAction(
};
}
/** Navigate › Related Symbol: one target opens, several open a chooser. */
async function gotoRelated(view: EditorView) {
const ctx = docOf(view);
if (!ctx || isVirtualUri(ctx.path)) return;
const head = view.state.selection.main.head;
const items = await relatedItems({
path: ctx.path,
language: ctx.language,
text: view.state.doc.toString(),
offset: head,
});
if (!items.length) {
showHint(view, tx("No related symbols"), { tone: "error" });
return;
}
const open = (item: (typeof items)[number]) =>
editorService().openFile(item.path, {
selection: item.line === undefined ? undefined : { line: item.line, col: item.col ?? 0 },
focus: true,
});
if (items.length === 1) {
await open(items[0]!);
return;
}
const root = useProject.getState().project?.root ?? "";
openPopup({
kind: "list",
anchor: caretAnchor(view, head),
title: tx("Choose Target"),
items: items.map((item, i) => {
const where = relativePath(root, item.path) + (item.line === undefined ? "" : `:${item.line + 1}`);
return {
id: `${i}`,
label: item.label ?? basename(item.path),
detail: `${item.group} · ${where}`,
icon: fileIconName(basename(item.path), item.path),
location: { path: item.path, line: item.line ?? 0 },
run: () => open(item),
};
}),
});
}
const findFilesNamed = async (name: string) => call(commands.findFilesNamed(name));
export function registerNavigationActions(): () => void {
return registerActions([
const unregisterHeaders = registerRelatedProvider((ctx) => headerSourceItems(ctx.path, findFilesNamed));
const unregister = registerActions([
editorAction("navigate.gotoTest", "Test", gotoTest, { keywords: ["go to test", "test subject", "create test"] }),
editorAction("navigate.superMethod", "Super Method", superMethod, {
keywords: ["go to super", "overridden", "parent"],
}),
editorAction("navigate.nextMethod", "Next Method", (v) => gotoMethod(v, 1)),
editorAction("navigate.previousMethod", "Previous Method", (v) => gotoMethod(v, -1)),
editorAction("navigate.relatedSymbol", "Related Symbol…", gotoRelated, {
keywords: ["go to related", "header", "source", "switch header source", "view", "controller"],
}),
]);
return () => {
unregister();
unregisterHeaders();
};
}
export { implementationGutter } from "./implementationGutter";
+47
Переглянути файл
@@ -0,0 +1,47 @@
/**
* Navigate › Related Symbol (⌃⌘↑): files and places tied to the current one by a language's or
* framework's conventions (a C header and its source, a Rails action and its views). Features
* register providers; the action merges what they find.
*/
export interface RelatedContext {
path: string;
language: string;
text: string;
/** The caret offset in `text`. */
offset: number;
}
export interface RelatedItem {
path: string;
/** 0-based; the file's start when absent. */
line?: number;
col?: number;
/** What the chooser shows (else the file name). */
label?: string;
/** The kind of relation shown after the label, e.g. "Header" or "View". */
group: string;
}
type Provider = (ctx: RelatedContext) => Promise<RelatedItem[]>;
const providers = new Set<Provider>();
export function registerRelatedProvider(provider: Provider): () => void {
providers.add(provider);
return () => {
providers.delete(provider);
};
}
/** Every provider's items, the first of each place kept; a failing provider adds nothing. */
export async function relatedItems(ctx: RelatedContext): Promise<RelatedItem[]> {
const found = await Promise.all([...providers].map((p) => p(ctx).catch(() => [] as RelatedItem[])));
const seen = new Set<string>();
return found.flat().filter((item) => {
const key = `${item.path}:${item.line ?? 0}`;
if (item.path === ctx.path && item.line === undefined) return false;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
+2
Переглянути файл
@@ -49,6 +49,7 @@ import { activate as services } from "./services";
import { activate as github, activateSettingsPages as githubPages } from "./github";
import { activate as httpClient } from "./http-client";
import { activate as cucumber } from "./cucumber";
import { activate as rails } from "./rails";
import { activate as thymeleaf } from "./thymeleaf";
import { activate as database, activateSettingsPages as databasePages } from "./database";
import { activate as graphql } from "./graphql";
@@ -102,6 +103,7 @@ const features: Array<[string, Activate]> = [
["github", github],
["http-client", httpClient],
["cucumber", cucumber],
["rails", rails],
["thymeleaf", thymeleaf],
["database", database],
["graphql", graphql],
+101
Переглянути файл
@@ -0,0 +1,101 @@
import { describe, expect, it } from "vitest";
import { actionAt, controllerName, pluralize, railsFile, railsTargets, singularize, type RailsFs } from "./conventions";
const CONTROLLER = `class Admin::UsersController < ApplicationController
before_action :load_user
def index
@users = User.all
end
def show
end
end
`;
const files: Record<string, string[]> = {
"/app/app/views/admin/users": ["index.html.erb", "show.html.erb", "_form.html.erb"],
"/app/app/helpers/admin": ["users_helper.rb"],
"/app/app/models": ["user.rb"],
"/app/app/controllers/admin": ["users_controller.rb"],
"/app/app/controllers": ["people_controller.rb", "users_controller.rb"],
"/app/db/migrate": [
"20240101000000_create_users.rb",
"20240102000000_add_email_to_users.rb",
"20240103_create_posts.rb",
],
};
const texts: Record<string, string> = {
"/app/app/controllers/admin/users_controller.rb": CONTROLLER,
"/app/app/controllers/users_controller.rb": "class UsersController\nend\n",
};
const fs: RailsFs = { list: async (d) => files[d] ?? null, read: async (p) => texts[p] ?? null };
describe("rails conventions", () => {
it("inflects and names", () => {
expect(pluralize("user")).toBe("users");
expect(pluralize("category")).toBe("categories");
expect(pluralize("box")).toBe("boxes");
expect(pluralize("person")).toBe("people");
expect(singularize("users")).toBe("user");
expect(singularize("categories")).toBe("category");
expect(singularize("addresses")).toBe("address");
expect(singularize("people")).toBe("person");
expect(controllerName("admin/order_items")).toBe("Admin::OrderItemsController");
});
it("classifies files under app/", () => {
expect(railsFile("/app/app/controllers/admin/users_controller.rb")).toEqual({
kind: "controller",
root: "/app",
resource: "admin/users",
});
expect(railsFile("/app/app/views/users/index.html.erb")).toMatchObject({ kind: "view", file: "index.html.erb" });
expect(railsFile("/app/app/views/layouts/application.html.erb")).toBeNull();
expect(railsFile("/app/app/controllers/application_controller.rb")).toBeNull();
expect(railsFile("/app/app/models/concerns/taggable.rb")).toBeNull();
expect(railsFile("/app/lib/tasks/x.rb")).toBeNull();
});
it("finds the action at the caret", () => {
expect(actionAt(CONTROLLER, CONTROLLER.indexOf("User.all"))).toBe("index");
expect(actionAt(CONTROLLER, CONTROLLER.indexOf("before_action"))).toBeNull();
});
it("goes from an action to its views, and from a controller to all of them, its helper and model", async () => {
const at = CONTROLLER.indexOf("User.all");
const path = "/app/app/controllers/admin/users_controller.rb";
expect(await railsTargets(path, CONTROLLER, at, fs)).toEqual([
{ path: "/app/app/views/admin/users/index.html.erb", group: "view" },
{ path: "/app/app/helpers/admin/users_helper.rb", group: "helper", label: undefined },
{ path: "/app/app/models/user.rb", group: "model", label: undefined },
]);
const all = await railsTargets(path, CONTROLLER, 0, fs);
expect(all.filter((t) => t.group === "view").map((t) => t.path.split("/").pop())).toEqual([
"_form.html.erb",
"index.html.erb",
"show.html.erb",
]);
});
it("goes from a view to its action", async () => {
const [target] = await railsTargets("/app/app/views/admin/users/show.html.erb", "", 0, fs);
expect(target).toEqual({
path: "/app/app/controllers/admin/users_controller.rb",
group: "controller",
line: 7,
label: "Admin::UsersController#show",
});
const [partial] = await railsTargets("/app/app/views/admin/users/_form.html.erb", "", 0, fs);
expect(partial).toMatchObject({ line: undefined, label: "Admin::UsersController" });
});
it("goes from a model to its controller and migrations", async () => {
const targets = await railsTargets("/app/app/models/user.rb", "", 0, fs);
expect(targets.map((t) => [t.group, t.path.split("/").pop()])).toEqual([
["controller", "users_controller.rb"],
["migration", "20240101000000_create_users.rb"],
["migration", "20240102000000_add_email_to_users.rb"],
]);
});
});
+153
Переглянути файл
@@ -0,0 +1,153 @@
/**
* Rails' file conventions for Navigate › Related Symbol: a controller (and the action at the
* caret) with its views, helper and model; a view with its controller action; a model with its
* controller and migrations.
*/
export interface RailsFs {
/** The file names in `dir`, or null when it doesn't exist. */
list(dir: string): Promise<string[] | null>;
read(path: string): Promise<string | null>;
}
export type RailsGroup = "view" | "controller" | "helper" | "model" | "migration";
export interface RailsTarget {
path: string;
group: RailsGroup;
line?: number;
label?: string;
}
type RailsFile =
| { kind: "controller"; root: string; resource: string }
| { kind: "helper"; root: string; resource: string }
| { kind: "view"; root: string; resource: string; file: string }
| { kind: "model"; root: string; model: string };
const IRREGULAR: Record<string, string> = { person: "people", man: "men", woman: "women", child: "children" };
const IRREGULAR_SINGULAR = Object.fromEntries(Object.entries(IRREGULAR).map(([s, p]) => [p, s]));
export function pluralize(word: string): string {
if (IRREGULAR[word]) return IRREGULAR[word];
if (/[^aeiou]y$/.test(word)) return `${word.slice(0, -1)}ies`;
if (/(?:s|x|z|ch|sh)$/.test(word)) return `${word}es`;
return `${word}s`;
}
export function singularize(word: string): string {
if (IRREGULAR_SINGULAR[word]) return IRREGULAR_SINGULAR[word];
if (/[^aeiou]ies$/.test(word)) return `${word.slice(0, -3)}y`;
if (/(?:ss|x|z|ch|sh)es$/.test(word)) return word.slice(0, -2);
if (/[^s]s$/.test(word)) return word.slice(0, -1);
return word;
}
const camel = (s: string) => s.replace(/(?:^|_)([a-z0-9])/g, (_, c: string) => c.toUpperCase());
/** `admin/users` → `Admin::UsersController`. */
export function controllerName(resource: string): string {
return `${resource.split("/").map(camel).join("::")}Controller`;
}
export function railsFile(path: string): RailsFile | null {
const m = /^(.*)\/app\/(controllers|views|helpers|models)\/(.+)$/.exec(path);
if (!m) return null;
const [, root, dir, rest] = m as unknown as [string, string, string, string];
if (dir === "controllers") {
const c = /^(.+)_controller\.rb$/.exec(rest);
return c && c[1] !== "application" ? { kind: "controller", root, resource: c[1]! } : null;
}
if (dir === "helpers") {
const h = /^(.+)_helper\.rb$/.exec(rest);
return h && h[1] !== "application" ? { kind: "helper", root, resource: h[1]! } : null;
}
if (dir === "views") {
const slash = rest.lastIndexOf("/");
if (slash < 0) return null;
const resource = rest.slice(0, slash);
if (resource === "layouts" || resource.startsWith("layouts/")) return null;
return { kind: "view", root, resource, file: rest.slice(slash + 1) };
}
const model = /^(.+)\.rb$/.exec(rest);
return model && !model[1]!.startsWith("concerns/") ? { kind: "model", root, model: model[1]! } : null;
}
const DEF = /^\s*def\s+(?:self\.)?([A-Za-z_]\w*[!?]?)/;
/** The method whose `def` is nearest above `offset` (the action at the caret), if any. */
export function actionAt(text: string, offset: number): string | null {
const lines = text.slice(0, offset).split("\n");
for (let i = lines.length - 1; i >= 0; i--) {
const m = DEF.exec(lines[i]!);
if (m) return m[1]!;
if (/^\s*class\s/.test(lines[i]!)) return null;
}
return null;
}
/** The 0-based line of `def name` in `text`. */
export function defLine(text: string, name: string): number | undefined {
const i = text.split("\n").findIndex((l) => DEF.exec(l)?.[1] === name);
return i < 0 ? undefined : i;
}
/** The view's action: its name up to the first dot; partials (`_form`) have none. */
const viewAction = (file: string) => (file.startsWith("_") ? null : file.split(".")[0]!);
async function views(fs: RailsFs, root: string, resource: string, action: string | null): Promise<RailsTarget[]> {
const dir = `${root}/app/views/${resource}`;
const names = (await fs.list(dir)) ?? [];
return names
.filter((n) => action === null || n.startsWith(`${action}.`))
.sort()
.map((n) => ({ path: `${dir}/${n}`, group: "view" }));
}
async function existing(fs: RailsFs, path: string, group: RailsGroup, label?: string): Promise<RailsTarget[]> {
const dir = path.slice(0, path.lastIndexOf("/"));
const names = await fs.list(dir);
return names?.includes(path.slice(dir.length + 1)) ? [{ path, group, label }] : [];
}
async function controller(fs: RailsFs, root: string, resource: string, action: string | null): Promise<RailsTarget[]> {
const path = `${root}/app/controllers/${resource}_controller.rb`;
const text = await fs.read(path);
if (text === null) return [];
const line = action ? defLine(text, action) : undefined;
const name = controllerName(resource);
return [{ path, group: "controller", line, label: line === undefined ? name : `${name}#${action}` }];
}
const lastSegment = (resource: string) => resource.slice(resource.lastIndexOf("/") + 1);
export async function railsTargets(path: string, text: string, offset: number, fs: RailsFs): Promise<RailsTarget[]> {
const file = railsFile(path);
if (!file) return [];
const { root } = file;
switch (file.kind) {
case "controller": {
const action = actionAt(text, offset);
return [
...(await views(fs, root, file.resource, action)),
...(await existing(fs, `${root}/app/helpers/${file.resource}_helper.rb`, "helper")),
...(await existing(fs, `${root}/app/models/${singularize(lastSegment(file.resource))}.rb`, "model")),
];
}
case "view":
return [
...(await controller(fs, root, file.resource, viewAction(file.file))),
...(await existing(fs, `${root}/app/helpers/${file.resource}_helper.rb`, "helper")),
];
case "helper":
return [...(await controller(fs, root, file.resource, null)), ...(await views(fs, root, file.resource, null))];
case "model": {
const table = pluralize(lastSegment(file.model));
const migrations = ((await fs.list(`${root}/db/migrate`)) ?? [])
.filter((n) => new RegExp(`^\\d+_\\w*(?:create|to)_${table}\\.rb$`).test(n))
.sort()
.map((n): RailsTarget => ({ path: `${root}/db/migrate/${n}`, group: "migration" }));
return [...(await controller(fs, root, table, null)), ...migrations];
}
}
}
+37
Переглянути файл
@@ -0,0 +1,37 @@
/** Rails: Navigate › Related Symbol between controllers, actions, views, helpers, models and migrations. */
import { registerRelatedProvider } from "@/editor/relatedProviders";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { railsTargets, type RailsFs, type RailsGroup } from "./conventions";
const fs: RailsFs = {
list: async (dir) => {
try {
return (await call(commands.fsReadDir(dir))).filter((e) => e.kind !== "dir").map((e) => e.name);
} catch {
return null;
}
},
read: async (path) => {
try {
return await call(commands.fsReadText(path));
} catch {
return null;
}
},
};
const GROUPS: Record<RailsGroup, () => string> = {
view: () => tx("View"),
controller: () => tx("Controller"),
helper: () => tx("Helper"),
model: () => tx("Model"),
migration: () => tx("Migration"),
};
export function activate(): () => void {
return registerRelatedProvider(async (ctx) => {
const targets = await railsTargets(ctx.path, ctx.text, ctx.offset, fs);
return targets.map((t) => ({ path: t.path, line: t.line, label: t.label, group: GROUPS[t.group]() }));
});
}
+1
Переглянути файл
@@ -8,6 +8,7 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
GotoTypeDeclaration: "navigate.typeDeclaration",
GotoSuperMethod: "navigate.superMethod",
GotoTest: "navigate.gotoTest",
GotoRelated: "navigate.relatedSymbol",
GotoClass: "navigate.gotoClass",
GotoFile: "navigate.gotoFile",
GotoSymbol: "navigate.gotoSymbol",
+1
Переглянути файл
@@ -56,6 +56,7 @@ export const intellijMacos: Record<string, string[]> = {
"navigate.nextEditLocation": [],
"navigate.gotoTest": ["Meta+Shift+T"],
"navigate.superMethod": ["Meta+U"],
"navigate.relatedSymbol": ["Ctrl+Meta+Up"],
"navigate.nextMethod": ["Ctrl+Shift+Down"],
"navigate.previousMethod": ["Ctrl+Shift+Up"],
"navigate.nextOccurrence": ["Meta+Alt+Down"],
+1
Переглянути файл
@@ -57,6 +57,7 @@ export const intellijWindows: Record<string, string[]> = {
"navigate.nextEditLocation": [],
"navigate.gotoTest": ["Ctrl+Shift+T"],
"navigate.superMethod": ["Ctrl+U"],
"navigate.relatedSymbol": ["Ctrl+Alt+Home"],
"navigate.nextMethod": ["Alt+Down"],
"navigate.previousMethod": ["Alt+Up"],
"navigate.nextOccurrence": ["Ctrl+Alt+Down"],
+9 -1
Переглянути файл
@@ -2105,5 +2105,13 @@
"Editor mode": "Editor mode",
"JSON:": "JSON:",
"Accepts mcpServers, servers, or a single server JSON object.": "Accepts mcpServers, servers, or a single server JSON object.",
"Leave empty to enable for all agents, or pick specific coding agents.": "Leave empty to enable for all agents, or pick specific coding agents."
"Leave empty to enable for all agents, or pick specific coding agents.": "Leave empty to enable for all agents, or pick specific coding agents.",
"Related Symbol…": "Related Symbol…",
"Choose Target": "Choose Target",
"No related symbols": "No related symbols",
"Header": "Header",
"Controller": "Controller",
"Helper": "Helper",
"Model": "Model",
"Migration": "Migration"
}
+9 -1
Переглянути файл
@@ -8489,5 +8489,13 @@
"Editor mode": "编辑模式",
"JSON:": "JSON:",
"Accepts mcpServers, servers, or a single server JSON object.": "支持 mcpServers、servers 或单个服务器 JSON 对象。",
"Leave empty to enable for all agents, or pick specific coding agents.": "留空则对所有智能体启用,也可选择特定的编码智能体。"
"Leave empty to enable for all agents, or pick specific coding agents.": "留空则对所有智能体启用,也可选择特定的编码智能体。",
"Related Symbol…": "相关符号…",
"Choose Target": "选择目标",
"No related symbols": "没有相关符号",
"Header": "头文件",
"Controller": "控制器",
"Helper": "辅助模块",
"Model": "模型",
"Migration": "迁移"
}