дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
7
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1df5bc4296 | ||
|
|
a5280c50f7 | ||
|
|
dd0578979a | ||
|
|
e96b0483ac | ||
|
|
608b292510 | ||
|
|
dd6d83fd2c | ||
|
|
b89febd61f |
No files matched your search
@@ -197,28 +197,62 @@ fn software_term(lower: &str) -> bool {
|
||||
.is_some_and(|w| ["s", "x", "z", "ch", "sh"].iter().any(|e| w.ends_with(e)) && plural_of(w))
|
||||
}
|
||||
|
||||
/// Words of a custom dictionary file: a plain word list or a Hunspell `.dic`
|
||||
/// (leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<HashSet<String>> {
|
||||
type Cache = HashMap<PathBuf, (Option<SystemTime>, Arc<HashSet<String>>)>;
|
||||
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
|
||||
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
|
||||
let mut cache = CACHE.get_or_init(Default::default).lock();
|
||||
if let Some((at, words)) = cache.get(path)
|
||||
&& *at == modified
|
||||
{
|
||||
return words.clone();
|
||||
}
|
||||
let words: HashSet<String> = match std::fs::read_to_string(path) {
|
||||
Ok(text) => parse_word_list(&text),
|
||||
Err(e) => {
|
||||
tracing::debug!("custom dictionary {}: {e}", path.display());
|
||||
HashSet::new()
|
||||
/// A custom dictionary: a word list, or a Hunspell dictionary with its affix rules.
|
||||
enum CustomDictionary {
|
||||
Words(HashSet<String>),
|
||||
Hunspell(Box<spellbook::Dictionary>),
|
||||
}
|
||||
|
||||
impl CustomDictionary {
|
||||
/// Whether the lowercased `lower` is a word of it, in any case style.
|
||||
fn contains(&self, lower: &str) -> bool {
|
||||
match self {
|
||||
Self::Words(words) => words.contains(lower),
|
||||
Self::Hunspell(dict) => {
|
||||
dict.check(lower) || dict.check(&capitalize(lower)) || dict.check(&lower.to_uppercase())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.aff` next to a Hunspell `.dic` (`de_DE.dic` → `de_DE.aff`), if there is one.
|
||||
fn affix_file(path: &Path) -> Option<PathBuf> {
|
||||
if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dic")) {
|
||||
return None;
|
||||
}
|
||||
["aff", "AFF"].into_iter().map(|ext| path.with_extension(ext)).find(|aff| aff.is_file())
|
||||
}
|
||||
|
||||
/// A custom dictionary file: a Hunspell `.dic` with the `.aff` beside it, with
|
||||
/// its affix, compounding and case rules; otherwise a plain word list (a `.dic`
|
||||
/// alone: leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<CustomDictionary> {
|
||||
type Stamp = (Option<SystemTime>, Option<SystemTime>);
|
||||
type Cache = HashMap<PathBuf, (Stamp, Arc<CustomDictionary>)>;
|
||||
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
let aff = affix_file(path);
|
||||
let stamp = (modified(path), aff.as_deref().and_then(modified));
|
||||
if let Some((at, dict)) = CACHE.get_or_init(Default::default).lock().get(path)
|
||||
&& *at == stamp
|
||||
{
|
||||
return dict.clone();
|
||||
}
|
||||
let read = |p: &Path| {
|
||||
std::fs::read_to_string(p).map_err(|e| tracing::debug!("custom dictionary {}: {e}", p.display())).ok()
|
||||
};
|
||||
let words = Arc::new(words);
|
||||
cache.insert(path.to_path_buf(), (modified, words.clone()));
|
||||
words
|
||||
let text = read(path).unwrap_or_default();
|
||||
let hunspell = aff.as_deref().and_then(read).and_then(|aff| {
|
||||
spellbook::Dictionary::new(&aff, &text)
|
||||
.map_err(|e| tracing::warn!("Hunspell dictionary {}: {e}", path.display()))
|
||||
.ok()
|
||||
});
|
||||
let dict = Arc::new(match hunspell {
|
||||
Some(dict) => CustomDictionary::Hunspell(Box::new(dict)),
|
||||
None => CustomDictionary::Words(parse_word_list(&text)),
|
||||
});
|
||||
CACHE.get_or_init(Default::default).lock().insert(path.to_path_buf(), (stamp, dict.clone()));
|
||||
dict
|
||||
}
|
||||
|
||||
/// Lowercased words of a word list / Hunspell `.dic` text.
|
||||
@@ -238,7 +272,7 @@ pub fn parse_word_list(text: &str) -> HashSet<String> {
|
||||
#[derive(Default)]
|
||||
pub struct Speller {
|
||||
accepted: HashSet<String>,
|
||||
custom: Vec<Arc<HashSet<String>>>,
|
||||
custom: Vec<Arc<CustomDictionary>>,
|
||||
}
|
||||
|
||||
impl Speller {
|
||||
@@ -351,16 +385,31 @@ impl Speller {
|
||||
&& !near_word(lower, |w| english().check(w))
|
||||
}
|
||||
|
||||
/// Replacements for `word`, best first, in the word's case style.
|
||||
/// Replacements for `word`, best first, in the word's case style: from the
|
||||
/// English dictionary and the custom Hunspell dictionaries, the closest first.
|
||||
pub fn suggest(&self, word: &str, limit: usize) -> Vec<String> {
|
||||
let hunspell = self.custom.iter().filter_map(|d| match d.as_ref() {
|
||||
CustomDictionary::Hunspell(dict) => Some(dict.as_ref()),
|
||||
CustomDictionary::Words(_) => None,
|
||||
});
|
||||
let dicts: Vec<&spellbook::Dictionary> = std::iter::once(english()).chain(hunspell).collect();
|
||||
let mut out = Vec::new();
|
||||
english().suggest(word, &mut out);
|
||||
if out.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
|
||||
english().suggest(&word.to_lowercase(), &mut out);
|
||||
out = out.into_iter().map(|s| capitalize(&s)).collect();
|
||||
for dict in &dicts {
|
||||
let mut found = Vec::new();
|
||||
dict.suggest(word, &mut found);
|
||||
if found.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
|
||||
dict.suggest(&word.to_lowercase(), &mut found);
|
||||
found = found.into_iter().map(|s| capitalize(&s)).collect();
|
||||
}
|
||||
out.extend(found);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
out.retain(|s| s != word && seen.insert(s.clone()));
|
||||
if dicts.len() > 1 {
|
||||
// Stable: within a distance each dictionary keeps its own order, English first.
|
||||
let lower = word.to_lowercase();
|
||||
out.sort_by_key(|s| edit_distance(&lower, &s.to_lowercase()));
|
||||
}
|
||||
out.truncate(limit);
|
||||
out
|
||||
}
|
||||
@@ -416,6 +465,22 @@ impl Speller {
|
||||
}
|
||||
}
|
||||
|
||||
/// Levenshtein distance in characters.
|
||||
fn edit_distance(a: &str, b: &str) -> usize {
|
||||
let b: Vec<char> = b.chars().collect();
|
||||
let mut row: Vec<usize> = (0..=b.len()).collect();
|
||||
for (i, ca) in a.chars().enumerate() {
|
||||
let mut diagonal = row[0];
|
||||
row[0] = i + 1;
|
||||
for (j, cb) in b.iter().enumerate() {
|
||||
let next = (row[j + 1] + 1).min(row[j] + 1).min(diagonal + usize::from(ca != *cb));
|
||||
diagonal = row[j + 1];
|
||||
row[j + 1] = next;
|
||||
}
|
||||
}
|
||||
row[b.len()]
|
||||
}
|
||||
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut chars = s.chars();
|
||||
chars.next().into_iter().flat_map(char::to_uppercase).chain(chars).collect()
|
||||
@@ -736,6 +801,36 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunspell_custom_dictionaries_use_their_affix_rules() {
|
||||
let dir = std::env::temp_dir().join(format!("ide-spell-hunspell-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dic = dir.join("de_TEST.dic");
|
||||
std::fs::write(&dic, "3\nhaus/NZ\ntür/NZ\nschlüssel/Z\n").unwrap();
|
||||
std::fs::write(
|
||||
dir.join("de_TEST.aff"),
|
||||
"SET UTF-8\nTRY esianrtolcdugmphbyfvkwzäöüß\nCOMPOUNDFLAG Z\nSFX N Y 1\nSFX N 0 en .\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = Speller::new::<&str>([], std::slice::from_ref(&dic));
|
||||
// Affix rules, compounds and case styles of the .aff, not just the listed stems.
|
||||
for word in ["haus", "Haus", "hausen", "türen", "Haustür", "schlüsselhaus"] {
|
||||
assert!(s.is_correct(word), "{word}");
|
||||
}
|
||||
assert!(!s.is_correct("hauz"));
|
||||
assert!(!s.is_correct("schlüsselen"));
|
||||
assert!(s.suggest("Hauss", 5).iter().any(|w| w == "Haus"), "{:?}", s.suggest("Hauss", 5));
|
||||
// English still checks and suggests.
|
||||
assert!(s.is_correct("message"));
|
||||
assert!(s.suggest("mesage", 5).iter().any(|w| w == "message"));
|
||||
// Without its .aff, a .dic is a word list.
|
||||
std::fs::remove_file(dir.join("de_TEST.aff")).unwrap();
|
||||
let words = Speller::new::<&str>([], std::slice::from_ref(&dic));
|
||||
assert!(words.is_correct("haus"));
|
||||
assert!(!words.is_correct("hausen"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_ranges() {
|
||||
let s = Speller::default();
|
||||
|
||||
@@ -112,7 +112,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**,
|
||||
### Common fields
|
||||
|
||||
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Debugging is not available on run targets. See [SSH](/en/guide/remote/ssh).
|
||||
- **Working directory**: relative to the project root; empty means the project root.
|
||||
- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine.
|
||||
- **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off.
|
||||
- **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`).
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ Only types you add appear here: choose **Add Service › Run Configuration Type*
|
||||
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
|
||||
- Context menu: **Show in Run Tool Window**, **Show in Debug Tool Window**, **Edit Configuration…**, **Remove from Services**.
|
||||
|
||||
A configuration that ran shows its console in the detail pane. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
|
||||
A configuration that ran shows its console in the detail pane; one debugged from here shows the whole debugger there (Threads & Variables, Console, Memory), and a breakpoint keeps the Services tool window in front. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
|
||||
### 通用字段
|
||||
|
||||
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上不支持调试。参见 [SSH](/zh/guide/remote/ssh)。
|
||||
- **工作目录**:相对于项目根目录,留空即项目根目录。
|
||||
- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。
|
||||
- **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。
|
||||
- **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
|
||||
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
|
||||
- 右键菜单:**在运行工具窗口中显示**、**在调试工具窗口中显示**、**编辑配置…**、**从服务中移除**。
|
||||
|
||||
运行过的配置会在详情区显示其控制台。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
|
||||
运行过的配置会在详情区显示其控制台;从这里调试的配置在详情区显示完整的调试器(线程和变量、控制台、内存),命中断点时停留在服务工具窗口。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const first: AgentTask = {
|
||||
id: "context-first",
|
||||
title: "First conversation",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
const second: AgentTask = { ...first, id: "context-second", title: "Second conversation" };
|
||||
|
||||
for (const active of ["conversation", "file"] as const) {
|
||||
test(`an agent context menu keeps the current ${active} open`, async ({ workbench: page }) => {
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
|
||||
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toBeVisible();
|
||||
await page.evaluate(
|
||||
async ({ first, second }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const store = await import(storePath);
|
||||
const { commands } = await import(ipcPath);
|
||||
const { toolWindowService } = await import(contributionsPath);
|
||||
commands.agentChanges = async () => ({ status: "ok", data: [] });
|
||||
const entries: AgentEntry[] = [{ type: "agent", text: "The active conversation stays here." }];
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([
|
||||
[first.id, first],
|
||||
[second.id, second],
|
||||
]),
|
||||
entries: new Map([
|
||||
[first.id, entries],
|
||||
[second.id, []],
|
||||
]),
|
||||
composers: new Map([[first.id, { text: "Keep this unsent draft", files: [], images: [] }]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
homeOpen: false,
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
toolWindowService().show("agents", true);
|
||||
store.openTask(first.id);
|
||||
},
|
||||
{ first, second },
|
||||
);
|
||||
const firstTab = page.getByRole("tab", { name: first.title, exact: true });
|
||||
const fileTab = page.getByRole("tab", { name: "README.md", exact: true });
|
||||
await expect(firstTab).toHaveAttribute("aria-selected", "true");
|
||||
if (active === "file") await fileTab.click();
|
||||
const current = active === "file" ? fileTab : firstTab;
|
||||
const target = page.getByRole("tree", { name: "Agent tasks" }).getByText(second.title, { exact: true });
|
||||
await target.click({ button: "right" });
|
||||
await expect(page.getByRole("menuitem", { name: "Rename…", exact: true })).toBeVisible();
|
||||
await expect(current).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(current).toHaveAttribute("aria-selected", "true");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
return (await import(storePath)).composerDraft(id).text;
|
||||
}, first.id),
|
||||
)
|
||||
.toBe("Keep this unsent draft");
|
||||
await target.click();
|
||||
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
}
|
||||
@@ -17,7 +17,7 @@ func main() {
|
||||
[[language-servers]]
|
||||
name = "gopls"
|
||||
command = "gopls"
|
||||
initialization-options = { semanticTokens = true, vulncheck = "Imports" }
|
||||
initialization-options = { semanticTokens = true, vulncheck = "Imports", hints = { constantValues = true } }
|
||||
root-markers = ["go.work", "go.mod"]
|
||||
install-hint = "go install golang.org/x/tools/gopls@latest"
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { promptInput } from "@/workbench/inputDialogs";
|
||||
import { ContextMenuHost, dragSession, hideContextMenu } from "@/ui";
|
||||
import { AgentsHeaderActions, AgentsView } from "./AgentsView";
|
||||
import { SESSION_KIND, TASK_DRAG } from "./model";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { archiveTask, unarchiveTask, deleteTask, dockTask, openTask, useAgents } from "./store";
|
||||
import { taskActions, taskMenu, useAgentsHeaderMenu } from "./taskActions";
|
||||
import styles from "./Agents.module.css";
|
||||
@@ -140,6 +141,42 @@ function setup() {
|
||||
}
|
||||
|
||||
describe("Agents selection", () => {
|
||||
it.each([SESSION_KIND, "file"])("right-clicking a task keeps the current %s view open", (kind) => {
|
||||
editor.active = { kind, key: "current", data: { task: "one" } };
|
||||
setup();
|
||||
context("two");
|
||||
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
|
||||
expect(selectedTasks()).toEqual(["two"]);
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves a multi-selection when opening its context menu without activating a task", () => {
|
||||
setup();
|
||||
select("one");
|
||||
select("three", { shiftKey: true });
|
||||
vi.mocked(openTask).mockClear();
|
||||
context("two");
|
||||
expect(selectedTasks()).toEqual(["one", "two", "three"]);
|
||||
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats macOS Control-click as a context menu without opening the task", () => {
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
try {
|
||||
setup();
|
||||
fireEvent.mouseDown(row("two"), { button: 0, ctrlKey: true });
|
||||
fireEvent.contextMenu(row("two"), { button: 0, ctrlKey: true });
|
||||
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
usePlatform.setState({ os });
|
||||
}
|
||||
});
|
||||
|
||||
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
|
||||
setup();
|
||||
select("one");
|
||||
@@ -164,14 +201,24 @@ describe("Agents selection", () => {
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
|
||||
setup();
|
||||
select("one");
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one", "three"]);
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one"]);
|
||||
expect(openTask).toHaveBeenCalledTimes(1);
|
||||
it.each([
|
||||
{ os: "macos", modifier: "metaKey" },
|
||||
{ os: "windows", modifier: "ctrlKey" },
|
||||
{ os: "linux", modifier: "ctrlKey" },
|
||||
])("toggles individual tasks with $modifier on $os", ({ os, modifier }) => {
|
||||
const previousOs = usePlatform.getState().os;
|
||||
usePlatform.setState({ os });
|
||||
try {
|
||||
setup();
|
||||
select("one");
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one", "three"]);
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one"]);
|
||||
expect(openTask).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
usePlatform.setState({ os: previousOs });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -322,9 +322,10 @@ export function AgentsView() {
|
||||
})
|
||||
}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
onSelectionChange={(sel, lead, reason) => {
|
||||
setSelected(sel);
|
||||
if (!inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) showTask(lead.task.id);
|
||||
if (reason !== "contextMenu" && !inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id))
|
||||
showTask(lead.task.id);
|
||||
}}
|
||||
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
|
||||
onContextMenu={(n, sel, e) => {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { expressionAt } from "../editor/valueTooltip";
|
||||
|
||||
/** The expression around the `|` in `line`. */
|
||||
function at(line: string, calls: boolean) {
|
||||
const pos = line.indexOf("|");
|
||||
const view = new EditorView({ state: EditorState.create({ doc: line.replace("|", "") }) });
|
||||
const text = expressionAt(view, pos, { calls })?.text ?? null;
|
||||
view.destroy();
|
||||
return text;
|
||||
}
|
||||
|
||||
describe("expression at the mouse for Quick Evaluate (#4772)", () => {
|
||||
it("takes the call of the clicked method, arguments included", () => {
|
||||
expect(at("String n = vo.getChd|rnum();", true)).toBe("vo.getChdrnum()");
|
||||
expect(at('x = f|(a, g(b), "c)");', true)).toBe('f(a, g(b), "c)")');
|
||||
expect(at("x = list.g|et (i);", true)).toBe("list.get (i)");
|
||||
});
|
||||
|
||||
it("follows member chains through calls and indexing to the clicked member", () => {
|
||||
expect(at("a.getB().c|()", true)).toBe("a.getB().c()");
|
||||
expect(at("a.get|B().c()", true)).toBe("a.getB()");
|
||||
expect(at("items[i + 1].na|me", true)).toBe("items[i + 1].name");
|
||||
expect(at("a.b()[0].c|", true)).toBe("a.b()[0].c");
|
||||
});
|
||||
|
||||
it("leaves an unbalanced call as the bare member", () => {
|
||||
expect(at("vo.getChd|rnum(a,", true)).toBe("vo.getChdrnum");
|
||||
});
|
||||
|
||||
it("keeps plain hovers free of calls", () => {
|
||||
expect(at("String n = vo.getChd|rnum();", false)).toBe("vo.getChdrnum");
|
||||
expect(at("a.getB().c|()", false)).toBe("c");
|
||||
});
|
||||
});
|
||||
@@ -91,7 +91,7 @@ describe("paused editor evaluation", () => {
|
||||
view.dispatch({ selection: { anchor: 0, head: 5 } });
|
||||
expect(click().defaultPrevented).toBe(true);
|
||||
await vi.waitFor(() => expect(document.querySelector(".cm-lsp-hint")?.textContent).toContain("order.items = 42"));
|
||||
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(7, 10, "order.items", "hover");
|
||||
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(7, 10, "order.items", "watch");
|
||||
expect(view.state.selection.main.head).toBe(16);
|
||||
});
|
||||
|
||||
@@ -101,7 +101,7 @@ describe("paused editor evaluation", () => {
|
||||
session();
|
||||
view.dispatch({ selection: { anchor: 0, head: doc.length } });
|
||||
click();
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, doc, "hover"));
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, doc, "watch"));
|
||||
expect(view.state.selection.main.from).toBe(0);
|
||||
expect(view.state.selection.main.to).toBe(doc.length);
|
||||
await vi.waitFor(() =>
|
||||
@@ -114,7 +114,7 @@ describe("paused editor evaluation", () => {
|
||||
const text = "(total +\n order.items)";
|
||||
view.dispatch({ changes: { from: 0, to: doc.length, insert: text }, selection: { anchor: 0, head: text.length } });
|
||||
click();
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, text, "hover"));
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, text, "watch"));
|
||||
});
|
||||
|
||||
it("ignores an object response that arrives after the debugger resumes", async () => {
|
||||
|
||||
@@ -70,19 +70,35 @@ it.each([undefined, true, false])(
|
||||
);
|
||||
|
||||
it.each(["breakpoint", "function breakpoint", "exception", "pause"])(
|
||||
"reveals an in-place session on suspend (%s)",
|
||||
"reveals an in-place session in Services on suspend (%s)",
|
||||
async (reason) => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
await startSession(config("launch"), { show: false });
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
handleDebugEvent(42, { kind: "stopped", threadId: 1, reason, description: null, allThreadsStopped: true });
|
||||
expect(show).toHaveBeenCalledWith("debug");
|
||||
// Services shows the session's debugger in place (#4773).
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("services");
|
||||
expect(useDebug.getState().active).toBe(42);
|
||||
expect(useDebug.getState().sessions[42]).toMatchObject({ status: "paused", selectedThread: 1 });
|
||||
},
|
||||
);
|
||||
|
||||
it("reveals a session started elsewhere in the Debug tool window on suspend", async () => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
await startSession(config("launch"));
|
||||
show.mockClear();
|
||||
handleDebugEvent(42, {
|
||||
kind: "stopped",
|
||||
threadId: 1,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
allThreadsStopped: true,
|
||||
});
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("debug");
|
||||
});
|
||||
|
||||
it.each(["launch", "attach"])("awaits every file before %s can send configurationDone", async (request) => {
|
||||
const completed: string[] = [];
|
||||
const release: Array<() => void> = [];
|
||||
|
||||
@@ -208,7 +208,7 @@ function evaluateSeed(view: EditorView | undefined = activeEditor()?.view, pos?:
|
||||
const { state } = view;
|
||||
const sel = state.selection.main;
|
||||
if (!sel.empty && (pos == null || (sel.from <= pos && pos <= sel.to))) return state.sliceDoc(sel.from, sel.to);
|
||||
return expressionAt(view, pos ?? sel.head)?.text ?? "";
|
||||
return expressionAt(view, pos ?? sel.head, { calls: true })?.text ?? "";
|
||||
}
|
||||
|
||||
async function quickEvaluate(arg?: unknown) {
|
||||
@@ -234,7 +234,8 @@ async function quickEvaluate(arg?: unknown) {
|
||||
);
|
||||
};
|
||||
try {
|
||||
const value = await evaluate(expression, "hover", session);
|
||||
// Unlike a plain hover, an explicit Quick Evaluate may call methods (adapters refuse that for "hover").
|
||||
const value = await evaluate(expression, "watch", session);
|
||||
if (session && stillCurrent()) showQuickValue(view, pos, expression, value, session.id);
|
||||
} catch (e) {
|
||||
if (stillCurrent()) showHint(view, e instanceof Error ? e.message : String(e), { pos, tone: "error" });
|
||||
|
||||
@@ -19,8 +19,45 @@ import styles from "./editor.module.css";
|
||||
const BASE_HOVER = 100;
|
||||
const IDENT = /[\p{L}\p{N}_$]/u;
|
||||
|
||||
/** Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. */
|
||||
export function expressionAt(view: EditorView, pos: number): { from: number; to: number; text: string } | null {
|
||||
const OPEN: Record<string, string> = { ")": "(", "]": "[" };
|
||||
const CLOSE: Record<string, string> = { "(": ")", "[": "]" };
|
||||
|
||||
/** Index just past the bracket group opening at `i` (strings skipped), or -1 when it doesn't close on the line. */
|
||||
function closeOf(t: string, i: number): number {
|
||||
const stack: string[] = [];
|
||||
for (let j = i; j < t.length; j++) {
|
||||
const c = t[j]!;
|
||||
if (c === '"' || c === "'" || c === "`") {
|
||||
j++;
|
||||
while (j < t.length && t[j] !== c) j += t[j] === "\\" ? 2 : 1;
|
||||
if (j >= t.length) return -1;
|
||||
} else if (CLOSE[c]) stack.push(CLOSE[c]);
|
||||
else if (c === ")" || c === "]") {
|
||||
if (stack.pop() !== c) return -1;
|
||||
if (!stack.length) return j + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Index of the bracket opening the group that closes at `i - 1`, or -1. */
|
||||
function openOf(t: string, i: number): number {
|
||||
for (let start = i - 1; start >= 0; start--) {
|
||||
if (t[start] === OPEN[t[i - 1]!] && closeOf(t, start) === i) return start;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. With
|
||||
* `calls`, as for Quick Evaluate: member chains through calls and indexing (`a.getB().c`,
|
||||
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`).
|
||||
*/
|
||||
export function expressionAt(
|
||||
view: EditorView,
|
||||
pos: number,
|
||||
{ calls = false } = {},
|
||||
): { from: number; to: number; text: string } | null {
|
||||
const { state } = view;
|
||||
const sel = state.selection.main;
|
||||
if (!sel.empty && pos >= sel.from && pos <= sel.to) {
|
||||
@@ -33,7 +70,25 @@ export function expressionAt(view: EditorView, pos: number): { from: number; to:
|
||||
let end = start;
|
||||
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) return null;
|
||||
while (end < t.length && IDENT.test(t[end]!)) end++;
|
||||
while (start > 0 && (IDENT.test(t[start - 1]!) || (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")))) start--;
|
||||
for (;;) {
|
||||
while (start > 0 && IDENT.test(t[start - 1]!)) start--;
|
||||
if (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")) start--;
|
||||
else if (calls && t[start - 1] === "." && OPEN[t[start - 2] ?? ""]) {
|
||||
let open = openOf(t, start - 1);
|
||||
// `a.b()[0].c`: walk back over every group, then the name they follow.
|
||||
while (open > 0 && OPEN[t[open - 1]!]) open = openOf(t, open);
|
||||
if (open <= 0 || !IDENT.test(t[open - 1]!)) break;
|
||||
start = open;
|
||||
} else break;
|
||||
}
|
||||
if (calls) {
|
||||
let next = end;
|
||||
while (t[next] === " ") next++;
|
||||
if (t[next] === "(") {
|
||||
const close = closeOf(t, next);
|
||||
if (close > 0) end = close;
|
||||
}
|
||||
}
|
||||
const text = t.slice(start, end);
|
||||
if (!text || /^\d/.test(text)) return null;
|
||||
return { from: line.from + start, to: line.from + end, text };
|
||||
|
||||
@@ -79,6 +79,7 @@ function useLiveSessionCount(): number | null {
|
||||
export function activate(): () => void {
|
||||
useDebugRunSessions.setState({
|
||||
Console: lazyComponent(() => import("./ui/DebugConsole").then((m) => m.DebugServiceConsole)),
|
||||
View: lazyComponent(() => import("./ui/DebugToolWindow").then((m) => m.DebugServiceView)),
|
||||
});
|
||||
loadWatches(useProject.getState().project?.root ?? null);
|
||||
publishContext();
|
||||
@@ -88,7 +89,7 @@ export function activate(): () => void {
|
||||
loadJsBreakpoints(useProject.getState().project?.root ?? null);
|
||||
loadResponseOverrides(useProject.getState().project?.root ?? null);
|
||||
const disposers = [
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null, View: null }),
|
||||
registerDebugActions(),
|
||||
registerDebugTabActions(),
|
||||
registerDevToolsWindows(),
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
runOutput,
|
||||
SERVICES_WINDOW,
|
||||
toolWindowService,
|
||||
useDebugRunSessions,
|
||||
} from "@/workbench/contributions";
|
||||
@@ -77,6 +78,8 @@ export interface DebugSession {
|
||||
process: RunId | null;
|
||||
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
|
||||
pinned?: boolean;
|
||||
/** Started in place from the Services tool window (root sessions): its stops show it there, not in the Debug window. */
|
||||
inPlace?: boolean;
|
||||
status: SessionStatus;
|
||||
stoppedThread: number | null;
|
||||
stopReason: string | null;
|
||||
@@ -720,6 +723,7 @@ export async function startPreparedSession(
|
||||
adapter: config.debugAdapter ?? "",
|
||||
runConfig: config,
|
||||
pinned,
|
||||
inPlace: options.show === false,
|
||||
}),
|
||||
},
|
||||
console: { ...s.console, [id]: [] },
|
||||
@@ -821,6 +825,7 @@ export async function startSession(
|
||||
launch: options.rerunnable === false ? null : launch,
|
||||
process: options.process ?? null,
|
||||
pinned: preparation ? preparation.pinned : pinned,
|
||||
inPlace: options.show === false,
|
||||
status: cur.status === "starting" ? "running" : cur.status,
|
||||
},
|
||||
},
|
||||
@@ -984,13 +989,12 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
|
||||
if (!root.runConfig && !launch) return;
|
||||
if (isLive(root)) await stopSession(root.id);
|
||||
rerunOf = root.id;
|
||||
// A session debugged in place from Services reruns there too.
|
||||
const show = options.show ?? (root.inPlace ? false : undefined);
|
||||
try {
|
||||
if (root.runConfig)
|
||||
await executeAction(
|
||||
"run.debugConfig",
|
||||
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
|
||||
);
|
||||
else await startSession(launch!, { show: options.show });
|
||||
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
|
||||
else await startSession(launch!, { show });
|
||||
} finally {
|
||||
rerunOf = null;
|
||||
}
|
||||
@@ -1364,7 +1368,8 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
|
||||
void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1));
|
||||
const dbg = workflowSettings().debugger;
|
||||
try {
|
||||
if (dbg.showOnBreakpoint) toolWindowService().show("debug");
|
||||
// A session debugged in place from Services shows its debugger there (#4773).
|
||||
if (dbg.showOnBreakpoint) toolWindowService().show(rootOf(s).inPlace ? SERVICES_WINDOW : "debug");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@@ -353,3 +353,15 @@
|
||||
border-bottom: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.serviceView {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.serviceView > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
@@ -173,7 +173,35 @@ export function DebugTabs() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Services › a configuration being debugged: the same debugger as the Debug tool window, for
|
||||
* that session (#4773). `console` replaces the Console tab, e.g. with the console of the run the
|
||||
* debugger is attached to.
|
||||
*/
|
||||
export function DebugServiceView({ sessionId, console: consolePane }: { sessionId: number; console?: ReactNode }) {
|
||||
const shown = useDebug((s) => {
|
||||
const active = s.active != null ? s.sessions[s.active] : undefined;
|
||||
return !!active && rootOf(active).id === sessionId;
|
||||
});
|
||||
useEffect(() => {
|
||||
if (useDebug.getState().sessions[sessionId]) selectSession(sessionId);
|
||||
}, [sessionId]);
|
||||
// The toolbar acts on the active session: using this view makes its session the active one again.
|
||||
const reselect = () => {
|
||||
if (!shown && useDebug.getState().sessions[sessionId]) selectSession(sessionId);
|
||||
};
|
||||
return (
|
||||
<div className={styles.serviceView} onPointerDownCapture={reselect} onFocusCapture={reselect}>
|
||||
{shown && <DebugView consolePane={consolePane} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DebugToolWindow() {
|
||||
return <DebugView />;
|
||||
}
|
||||
|
||||
function DebugView({ consolePane }: { consolePane?: ReactNode }) {
|
||||
const tx = useTx();
|
||||
const active = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
|
||||
const muted = useBreakpoints((s) => s.muted);
|
||||
@@ -314,7 +342,7 @@ export function DebugToolWindow() {
|
||||
) : tab === "network" ? (
|
||||
<NetworkView key={active.id} session={active.id} />
|
||||
) : (
|
||||
<DebugConsole key={active.id} session={active} />
|
||||
(consolePane ?? <DebugConsole key={active.id} session={active} />)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { expandCwd } from "./cwdMacros";
|
||||
|
||||
const ctx = { root: "/work/app/", module: "services/api", home: "/Users/me" };
|
||||
|
||||
describe("working directory macros (#4755)", () => {
|
||||
it("expands the project, module and home folders", () => {
|
||||
expect(expandCwd("$PROJECT_DIR$/web", ctx)).toEqual({ cwd: "/work/app/web" });
|
||||
expect(expandCwd("$ContentRoot$", ctx)).toEqual({ cwd: "/work/app" });
|
||||
expect(expandCwd("$MODULE_DIR$/bin", ctx)).toEqual({ cwd: "/work/app/services/api/bin" });
|
||||
expect(expandCwd("$MODULE_WORKING_DIR$", ctx)).toEqual({ cwd: "/work/app/services/api" });
|
||||
expect(expandCwd("$USER_HOME$/scratch", ctx)).toEqual({ cwd: "/Users/me/scratch" });
|
||||
});
|
||||
|
||||
it("uses the project folder as the module folder when there is no module", () => {
|
||||
expect(expandCwd("$MODULE_DIR$", { ...ctx, module: null })).toEqual({ cwd: "/work/app" });
|
||||
expect(expandCwd("$MODULE_DIR$", { ...ctx, module: "/elsewhere/mod" })).toEqual({ cwd: "/elsewhere/mod" });
|
||||
});
|
||||
|
||||
it("leaves a path without macros as it is", () => {
|
||||
expect(expandCwd("server", ctx)).toEqual({ cwd: "server" });
|
||||
expect(expandCwd("/abs/$dollar", ctx)).toEqual({ cwd: "/abs/$dollar" });
|
||||
});
|
||||
|
||||
it("names an unknown macro and one without a value", () => {
|
||||
const unknown = expandCwd("$PROJECT_ROOT$/web", ctx);
|
||||
expect("error" in unknown && unknown.error).toContain("$PROJECT_ROOT$");
|
||||
expect("error" in unknown && unknown.error).toContain("$PROJECT_DIR$");
|
||||
const remote = expandCwd("$USER_HOME$", { ...ctx, home: null });
|
||||
expect(remote).toEqual({ error: "$USER_HOME$ is not available in a remote project." });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Path macros in a run configuration's working directory (`$PROJECT_DIR$/web`), expanded when
|
||||
* it runs or is debugged; the stored value keeps them, so the configuration moves with the project.
|
||||
*/
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isTauri, type RunConfig } from "@/platform/ipc";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
const MACRO = /\$([A-Za-z_][A-Za-z0-9_]*)\$/g;
|
||||
|
||||
/** The macros a working directory may use. */
|
||||
export const CWD_MACROS = ["PROJECT_DIR", "ContentRoot", "MODULE_DIR", "MODULE_WORKING_DIR", "USER_HOME"] as const;
|
||||
|
||||
export interface CwdContext {
|
||||
root: string;
|
||||
/** The configuration's module directory, absolute or relative to `root`. */
|
||||
module?: string | null;
|
||||
/** The user's home folder; null where it isn't known (a remote project). */
|
||||
home: string | null;
|
||||
}
|
||||
|
||||
const absolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
|
||||
const trimEnd = (p: string) => p.replace(/[\\/]+$/, "");
|
||||
const join = (root: string, p: string) => (absolute(p) ? p : `${trimEnd(root)}/${p.replace(/^\.[\\/]/, "")}`);
|
||||
|
||||
/** `cwd` with its macros replaced; an error names a macro that is unknown or has no value here. */
|
||||
export function expandCwd(cwd: string, ctx: CwdContext): { cwd: string } | { error: string } {
|
||||
let error: string | null = null;
|
||||
const module = ctx.module ? join(ctx.root, ctx.module) : ctx.root;
|
||||
const values: Record<string, string | null> = {
|
||||
PROJECT_DIR: ctx.root,
|
||||
ContentRoot: ctx.root,
|
||||
MODULE_DIR: module,
|
||||
MODULE_WORKING_DIR: module,
|
||||
USER_HOME: ctx.home,
|
||||
};
|
||||
const out = cwd.replace(MACRO, (all, name: string) => {
|
||||
const value = Object.hasOwn(values, name) ? values[name] : undefined;
|
||||
if (value) return trimEnd(value);
|
||||
const supported = CWD_MACROS.map((m) => `$${m}$`).join(", ");
|
||||
error ??=
|
||||
value === undefined
|
||||
? tx`Unknown macro ${all} in the working directory. Supported: ${supported}.`
|
||||
: tx`${all} is not available in a remote project.`;
|
||||
return all;
|
||||
});
|
||||
return error ? { error } : { cwd: out };
|
||||
}
|
||||
|
||||
let home: Promise<string | null> | null = null;
|
||||
const homeDir = () =>
|
||||
(home ??= isTauri()
|
||||
? import("@tauri-apps/api/path").then((m) => m.homeDir()).catch(() => null)
|
||||
: Promise.resolve(null));
|
||||
|
||||
/** `config` with the macros of its working directory expanded; throws when one can't be. */
|
||||
export async function withExpandedCwd(config: RunConfig): Promise<RunConfig> {
|
||||
const cwd = config.cwd;
|
||||
if (!cwd?.includes("$")) return config;
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!root) return config;
|
||||
const result = expandCwd(cwd, {
|
||||
root,
|
||||
module: config.module,
|
||||
home: isRemoteWindow() ? null : await homeDir(),
|
||||
});
|
||||
if ("error" in result) throw new Error(result.error);
|
||||
return { ...config, cwd: result.cwd };
|
||||
}
|
||||
|
||||
export function notifyCwdError(config: RunConfig, error: unknown) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
title: tx`Cannot start '${config.name}'`,
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
runContextAction,
|
||||
} from "./contextRun";
|
||||
import { runWithExecutor } from "./executors";
|
||||
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
|
||||
import { debugWithAgent, jdwpLaunch } from "./javaDebug";
|
||||
import { attachesToChild, debugAttachingToChild } from "./pluginAttach";
|
||||
import { RunDialogsOverlay } from "./dialogs";
|
||||
@@ -184,6 +185,11 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
|
||||
}
|
||||
|
||||
async function debugLaunch(config: RunConfig, chain: readonly string[], show?: boolean): Promise<void> {
|
||||
try {
|
||||
config = await withExpandedCwd(config);
|
||||
} catch (e) {
|
||||
return notifyCwdError(config, e);
|
||||
}
|
||||
if (!(await prepareLaunch(config, chain, show))) return;
|
||||
if (config.kind === UNITY_CONFIG_KIND) return showUnityAttach(config);
|
||||
// Python on a Docker / Compose target: debugpy in the container, the debugger attaches.
|
||||
|
||||
@@ -757,7 +757,7 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
// Re-render on session changes.
|
||||
useRun((s) => s.sessions);
|
||||
const debugViews = useDebugRunSessions();
|
||||
const Console = debugViews.Console;
|
||||
const { Console, View } = debugViews;
|
||||
const t = useT();
|
||||
const txTemplate = useTxTemplate();
|
||||
const r = resolve(item);
|
||||
@@ -773,11 +773,14 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
);
|
||||
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
|
||||
// come from this window's toolbar (the selection), so the console strip leaves them out.
|
||||
if (r.session?.run) {
|
||||
const execution = r.session;
|
||||
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
|
||||
}
|
||||
const execution = r.session?.run;
|
||||
const runConsole = execution && <SessionPanel key={execution.id} session={execution} showLifecycle={false} />;
|
||||
const d = r.session?.debug[0];
|
||||
// Being debugged: the whole debugger in place, as in IDEA's Services (#4773); the console of a
|
||||
// run the debugger is attached to stays its Console tab.
|
||||
if (d && View && (d.status !== "terminated" || !execution))
|
||||
return <View key={d.id} sessionId={d.id} console={runConsole} />;
|
||||
if (runConsole) return runConsole;
|
||||
if (d && Console)
|
||||
return (
|
||||
<div className={styles.debugConsole}>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* per-session `ConsoleModel`, batched per animation frame.
|
||||
*/
|
||||
import { withRunTarget } from "@/platform/runTargetSelection";
|
||||
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
|
||||
import { create } from "zustand";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import {
|
||||
@@ -847,6 +848,12 @@ async function startRunIn(
|
||||
options: StartRunOptions,
|
||||
): Promise<RunSession | null> {
|
||||
config = withRunTarget(config);
|
||||
try {
|
||||
config = await withExpandedCwd(config);
|
||||
} catch (e) {
|
||||
notifyCwdError(config, e);
|
||||
return null;
|
||||
}
|
||||
if (!options.launch && isCMakeBuild(config)) {
|
||||
await buildCMake(config.id, options.show !== false);
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { ToolWindowShownProvider, useServiceProviders, type ServiceTreeItem } from "@/workbench/contributions";
|
||||
import { ServicesTreeView } from "./ServicesTree";
|
||||
import { useServicesTree } from "./tree";
|
||||
@@ -54,19 +55,29 @@ function setup() {
|
||||
}
|
||||
|
||||
describe("Services selection → actions", () => {
|
||||
it.each(["ctrlKey", "metaKey"])("%s toggles rows and Run applies to the selection", (modifier) => {
|
||||
const { row, selected, toolbar } = setup();
|
||||
fireEvent.mouseDown(row("one"));
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["one", "two"]);
|
||||
expect(screen.getByTestId("detail")).toHaveTextContent("two");
|
||||
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
|
||||
expect(run.mock.calls).toEqual([["one"], ["two"]]);
|
||||
fireEvent.mouseDown(row("one"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["two"]);
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual([]);
|
||||
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
|
||||
it.each([
|
||||
{ os: "macos", modifier: "metaKey" },
|
||||
{ os: "windows", modifier: "ctrlKey" },
|
||||
{ os: "linux", modifier: "ctrlKey" },
|
||||
])("$modifier on $os toggles rows and Run applies to the selection", ({ os, modifier }) => {
|
||||
const previousOs = usePlatform.getState().os;
|
||||
usePlatform.setState({ os });
|
||||
try {
|
||||
const { row, selected, toolbar } = setup();
|
||||
fireEvent.mouseDown(row("one"));
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["one", "two"]);
|
||||
expect(screen.getByTestId("detail")).toHaveTextContent("two");
|
||||
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
|
||||
expect(run.mock.calls).toEqual([["one"], ["two"]]);
|
||||
fireEvent.mouseDown(row("one"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["two"]);
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual([]);
|
||||
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
|
||||
} finally {
|
||||
usePlatform.setState({ os: previousOs });
|
||||
}
|
||||
});
|
||||
|
||||
it("tells the provider which node became the lead selection", () => {
|
||||
|
||||
@@ -65,7 +65,7 @@ function SpellingPage() {
|
||||
<Row
|
||||
label="Dictionary files"
|
||||
stacked
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
>
|
||||
<GlobListEditor
|
||||
aria-label="Custom dictionaries"
|
||||
|
||||
@@ -93,6 +93,10 @@
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.nodeCount {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.detailIcon {
|
||||
flex: none;
|
||||
--icon-color: var(--fg-subtle);
|
||||
|
||||
@@ -1002,7 +1002,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
/>
|
||||
)}
|
||||
{label}
|
||||
{n.type === "group" && <span className={styles.detail}>{fileCount(n.files.length)}</span>}
|
||||
{n.type !== "file" && <span className={styles.nodeCount}>{fileCount(n.files.length)}</span>}
|
||||
{!staging && n.type === "file" && n.files[0] && isPartiallyStaged(n.files[0]) && (
|
||||
<span className={styles.partial} title={tx("Partially staged: only staged hunks are committed")}>
|
||||
<T>partial</T>
|
||||
|
||||
@@ -10,6 +10,7 @@ vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
|
||||
|
||||
import { ChangesTree } from "../CommitView";
|
||||
import { useVcs } from "../store";
|
||||
import { useCommit } from "../commitStore";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
const change = (path: string) => ({
|
||||
@@ -26,6 +27,7 @@ const row = (name: string) => screen.getByText(name).closest('[role="treeitem"]'
|
||||
describe("repository nodes in the changes tree", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useCommit.setState({ groupByDir: false, groupByRepo: true });
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
@@ -41,7 +43,7 @@ describe("repository nodes in the changes tree", () => {
|
||||
|
||||
it("shows the branch each repository is on and follows branch switches", () => {
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(row("orders").textContent).toBe("orders");
|
||||
expect(row("orders").textContent).toBe("orders1 file");
|
||||
act(() =>
|
||||
useVcs.setState({
|
||||
heads: {
|
||||
@@ -50,14 +52,35 @@ describe("repository nodes in the changes tree", () => {
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(row("orders").textContent).toBe("ordersfeature/ABC-123");
|
||||
expect(row("p").textContent).toBe("pmain");
|
||||
expect(row("orders").textContent).toBe("orders1 filefeature/ABC-123");
|
||||
expect(row("p").textContent).toBe("p1 filemain");
|
||||
act(() =>
|
||||
useVcs.setState({
|
||||
heads: { ...useVcs.getState().heads, "/p/orders": { head: null, headCommit: "abcdef0123456789" } },
|
||||
}),
|
||||
);
|
||||
expect(row("orders").textContent).toBe("ordersabcdef01");
|
||||
expect(row("orders").textContent).toBe("orders1 fileabcdef01");
|
||||
});
|
||||
|
||||
it("counts the files under each repository and each nested folder", () => {
|
||||
useCommit.setState({ groupByDir: true });
|
||||
const app = change("/p/App.kt");
|
||||
const order = change("/p/orders/src/Order.kt");
|
||||
const test = change("/p/orders/src/tests/OrderTest.kt");
|
||||
const data = change("/p/orders/src/tests/orders.json");
|
||||
useVcs.setState({ status: [app, order, test, data] });
|
||||
render(<ChangesTree mode="commit" />);
|
||||
|
||||
expect(row("p").textContent).toBe("p1 file");
|
||||
expect(row("orders").textContent).toBe("orders3 files");
|
||||
expect(row("src").textContent).toBe("src3 files");
|
||||
expect(row("tests").textContent).toBe("tests2 files");
|
||||
expect(row("Order.kt").textContent).toBe("Order.kt");
|
||||
|
||||
act(() => useVcs.setState({ status: [app, order, test] }));
|
||||
expect(row("orders").textContent).toBe("orders2 files");
|
||||
expect(row("src").textContent).toBe("src2 files");
|
||||
expect(row("tests").textContent).toBe("tests1 file");
|
||||
});
|
||||
|
||||
it("puts a decorative icon before the branch, on repository rows only", () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.",
|
||||
"Trust Folder": "Trust Folder",
|
||||
"No files selected": "No files selected",
|
||||
"{added} added": "{added} added",
|
||||
@@ -909,7 +910,6 @@
|
||||
"devcontainer up exited with {status}": "devcontainer up exited with {status}",
|
||||
"Select an item to view details": "Select an item to view details",
|
||||
"Select files in the Project view, Commit tool window, or open a file in the editor": "Select files in the Project view, Commit tool window, or open a file in the editor",
|
||||
|
||||
"Nothing to show": "Nothing to show",
|
||||
"IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory",
|
||||
"Invalid log stream configuration": "Invalid log stream configuration",
|
||||
@@ -2800,5 +2800,8 @@
|
||||
"Cannot download to {folder}": "Cannot download to {folder}",
|
||||
"Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer",
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\"",
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C)."
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).",
|
||||
"Unknown macro {all} in the working directory. Supported: {supported}.": "Unknown macro {all} in the working directory. Supported: {supported}.",
|
||||
"{all} is not available in a remote project.": "{all} is not available in a remote project.",
|
||||
"Cannot start '{name}'": "Cannot start '{name}'"
|
||||
}
|
||||
@@ -3244,7 +3244,6 @@
|
||||
"Accepted in every project.": "Aceptadas en todos los proyectos.",
|
||||
"Custom dictionaries": "Diccionarios personalizados",
|
||||
"Dictionary files": "Archivos de diccionario",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palabras en texto plano (una palabra por línea) o archivos .dic de Hunspell. Las rutas relativas se resuelven respecto a la raíz del proyecto y ~/ respecto a la carpeta personal.",
|
||||
"No custom dictionaries": "No hay diccionarios personalizados",
|
||||
"Dictionary path": "Ruta del diccionario",
|
||||
"Natural Languages": "Idiomas naturales",
|
||||
|
||||
@@ -3117,7 +3117,6 @@
|
||||
"Accepted in every project.": "Acceptés dans tous les projets.",
|
||||
"Custom dictionaries": "Dictionnaires personnalisés",
|
||||
"Dictionary files": "Fichiers de dictionnaire",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listes de mots en texte brut (un mot par ligne) ou fichiers Hunspell .dic. Les chemins relatifs sont résolus depuis la racine du projet, ~/ depuis le dossier personnel.",
|
||||
"No custom dictionaries": "Aucun dictionnaire personnalisé",
|
||||
"Dictionary path": "Chemin du dictionnaire",
|
||||
"Natural Languages": "Langues naturelles",
|
||||
|
||||
@@ -3293,7 +3293,6 @@
|
||||
"Accepted in every project.": "모든 프로젝트에서 허용됩니다.",
|
||||
"Custom dictionaries": "사용자 지정 사전",
|
||||
"Dictionary files": "사전 파일",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "일반 텍스트 단어 목록(한 줄에 한 단어) 또는 Hunspell .dic 파일. 상대 경로는 프로젝트 루트를, ~/는 홈 폴더를 기준으로 해결됩니다.",
|
||||
"No custom dictionaries": "사용자 지정 사전 없음",
|
||||
"Dictionary path": "사전 경로",
|
||||
"Natural Languages": "자연어",
|
||||
|
||||
@@ -3216,7 +3216,6 @@
|
||||
"Accepted in every project.": "Akceptowane we wszystkich projektach.",
|
||||
"Custom dictionaries": "Własne słowniki",
|
||||
"Dictionary files": "Pliki słowników",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listy słów w zwykłym tekście (jednosłowne w wierszu) lub pliki .dic Hunspell. Ścieżki względne są rozwiązywane względem katalogu głównego projektu, a ~/ względem folderu domowego.",
|
||||
"No custom dictionaries": "Brak własnych słowników",
|
||||
"Dictionary path": "Ścieżka słownika",
|
||||
"Natural Languages": "Języki naturalne",
|
||||
|
||||
@@ -3217,7 +3217,6 @@
|
||||
"Accepted in every project.": "Aceitas em todos os projetos.",
|
||||
"Custom dictionaries": "Dicionários personalizados",
|
||||
"Dictionary files": "Arquivos de dicionário",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palavras em texto simples (uma palavra por linha) ou arquivos .dic do Hunspell. Caminhos relativos são resolvidos em relação à raiz do projeto, ~/ em relação à pasta pessoal.",
|
||||
"No custom dictionaries": "Nenhum dicionário personalizado",
|
||||
"Dictionary path": "Caminho do dicionário",
|
||||
"Natural Languages": "Idiomas naturais",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个词)或 Hunspell .dic 文件;旁边有同名 .aff 的 .dic 还会接受其规则允许的变形和复合词。相对路径基于项目根目录解析,~/ 表示主目录。",
|
||||
"MCP server instructions": "MCP 服务器说明",
|
||||
"MCP tools (deferred)": "MCP 工具(延迟加载)",
|
||||
"System tools (deferred)": "系统工具(延迟加载)",
|
||||
@@ -4104,7 +4105,6 @@
|
||||
"Accepted in every project.": "在所有项目中接受。",
|
||||
"Custom dictionaries": "自定义词典",
|
||||
"Dictionary files": "词典文件",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个单词)或 Hunspell .dic 文件。相对路径相对于项目根目录解析,~/ 相对于主文件夹解析。",
|
||||
"No custom dictionaries": "没有自定义词典",
|
||||
"Dictionary path": "词典路径",
|
||||
"Natural Languages": "自然语言",
|
||||
@@ -5285,7 +5285,6 @@
|
||||
"Configuration…": "配置…",
|
||||
"No deployment server configured": "未配置部署服务器",
|
||||
"Select files in the Project view, Commit tool window, or open a file in the editor": "请在项目视图或提交工具窗口中选择文件,或在编辑器中打开文件",
|
||||
|
||||
"Upload to": "上传到",
|
||||
"Download from": "下载自",
|
||||
"Sync with Deployed to": "与已部署的同步",
|
||||
@@ -9160,5 +9159,8 @@
|
||||
"Cannot download to {folder}": "无法下载到 {folder}",
|
||||
"Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹",
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”",
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。"
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。",
|
||||
"Unknown macro {all} in the working directory. Supported: {supported}.": "工作目录中有未知的宏 {all}。支持:{supported}。",
|
||||
"{all} is not available in a remote project.": "{all} 在远程项目中不可用。",
|
||||
"Cannot start '{name}'": "无法启动“{name}”"
|
||||
}
|
||||
@@ -49,6 +49,35 @@ const labels = (tree: HTMLElement) =>
|
||||
.queryAllByRole("treeitem")
|
||||
.map((el) => el.textContent);
|
||||
|
||||
describe("Tree context-menu selection", () => {
|
||||
it.each([
|
||||
{ os: "windows", gesture: { button: 2 } },
|
||||
{ os: "macos", gesture: { button: 0, ctrlKey: true } },
|
||||
])("marks $os context-menu selection without changing ordinary activation", ({ os, gesture }) => {
|
||||
const previousOs = usePlatform.getState().os;
|
||||
usePlatform.setState({ os });
|
||||
try {
|
||||
const selection = vi.fn();
|
||||
const menu = vi.fn();
|
||||
const { tree, key, onActivate } = setup({ onSelectionChange: selection, onContextMenu: menu });
|
||||
const readme = within(tree).getByRole("treeitem", { name: "README.md" });
|
||||
fireEvent.mouseDown(readme, gesture);
|
||||
fireEvent.contextMenu(readme, gesture);
|
||||
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1], "contextMenu");
|
||||
expect(menu).toHaveBeenCalledWith(data[1], new Set(["README.md"]), expect.anything());
|
||||
expect(onActivate).not.toHaveBeenCalled();
|
||||
key("Home");
|
||||
expect(selection).toHaveBeenLastCalledWith(new Set(["src"]), data[0]);
|
||||
fireEvent.mouseDown(readme, { button: 0 });
|
||||
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1]);
|
||||
key("Enter");
|
||||
expect(onActivate).toHaveBeenCalledWith(data[1], expect.anything());
|
||||
} finally {
|
||||
usePlatform.setState({ os: previousOs });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tree directory context", () => {
|
||||
it("does not contribute virtual document URIs as filesystem directories", () => {
|
||||
const { key } = setup({ getDirectory: () => "jdt://contents/library.jar/package" });
|
||||
|
||||
@@ -104,7 +104,8 @@ export interface TreeProps<T> {
|
||||
|
||||
selected?: ReadonlySet<string>;
|
||||
defaultSelected?: Iterable<string>;
|
||||
onSelectionChange?: (selected: Set<string>, lead: T | null) => void;
|
||||
/** Context-menu selection can update the action target without navigating to it. */
|
||||
onSelectionChange?: (selected: Set<string>, lead: T | null, reason?: "contextMenu") => void;
|
||||
multiSelect?: boolean;
|
||||
|
||||
/** Enter / double-click on a leaf (or on nodes `activateExpandable` accepts). */
|
||||
@@ -426,22 +427,23 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
};
|
||||
|
||||
const commitSelection = useCallback(
|
||||
(next: Set<string>, leadKey: string | null) => {
|
||||
(next: Set<string>, leadKey: string | null, reason?: "contextMenu") => {
|
||||
if (!selectedControlled) setSelectedInner(next);
|
||||
setLead(leadKey);
|
||||
const leadRow = leadKey != null ? rows[indexOfKey.get(leadKey) ?? -1] : undefined;
|
||||
props.onSelectionChange?.(next, leadRow?.node ?? null);
|
||||
if (reason) props.onSelectionChange?.(next, leadRow?.node ?? null, reason);
|
||||
else props.onSelectionChange?.(next, leadRow?.node ?? null);
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[rows, indexOfKey, selectedControlled, props.onSelectionChange],
|
||||
);
|
||||
|
||||
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single") => {
|
||||
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single", reason?: "contextMenu") => {
|
||||
const row = rows[i];
|
||||
if (!row || row.loading) return;
|
||||
if (mode === "single" || !multiSelect) {
|
||||
setAnchor(row.key);
|
||||
commitSelection(new Set([row.key]), row.key);
|
||||
commitSelection(new Set([row.key]), row.key, reason);
|
||||
} else if (mode === "toggle") {
|
||||
const next = new Set(selected);
|
||||
if (next.has(row.key)) next.delete(row.key);
|
||||
@@ -649,8 +651,8 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
};
|
||||
|
||||
const onRowMouseDown = (e: MouseEvent, i: number) => {
|
||||
if (e.button === 2) {
|
||||
if (!selected.has(rows[i]!.key)) selectIndex(i);
|
||||
if (e.button === 2 || (e.button === 0 && e.ctrlKey && isMacHost())) {
|
||||
if (!selected.has(rows[i]!.key)) selectIndex(i, "single", "contextMenu");
|
||||
return;
|
||||
}
|
||||
if (e.button !== 0) return;
|
||||
|
||||
@@ -1980,7 +1980,9 @@ export const useDebugRunSessions = create<{
|
||||
sessions: DebugRunSession[];
|
||||
serviceSessions: DebugServiceSession[];
|
||||
Console: ComponentType<{ sessionId: number }> | null;
|
||||
}>(() => ({ sessions: [], serviceSessions: [], Console: null }));
|
||||
/** The whole debugger of a session (Services shows it in place); `console` replaces its Console tab. */
|
||||
View: ComponentType<{ sessionId: number; console?: ReactNode }> | null;
|
||||
}>(() => ({ sessions: [], serviceSessions: [], Console: null, View: null }));
|
||||
|
||||
/**
|
||||
* The Services tool window's badge: how many of its listed services are running.
|
||||
|
||||
Reference in new issue
Заблокувати користувача