дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 20:46:22 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7554507a6e |
No files matched your search
@@ -252,8 +252,6 @@ pub struct SmartKeysSettings {
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
pub smart_indent: bool,
|
||||
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
|
||||
pub insert_doc_stub: bool,
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
}
|
||||
@@ -269,7 +267,6 @@ impl Default for SmartKeysSettings {
|
||||
tab_out_of_pair: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
backspace_unindent: "autoindent".into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,11 +30,6 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
/// Unsaved text of the open document at `path`.
|
||||
fn buffer_text(&self, path: &Path) -> Option<String>;
|
||||
/// Up to `limit` files of the project index below `root` whose root-relative path satisfies
|
||||
/// `matches`; `None` when no index covers `root` yet (the caller walks the disk instead).
|
||||
fn indexed_files(&self, _root: &Path, _matches: &dyn Fn(&Path) -> bool, _limit: usize) -> Option<Vec<PathBuf>> {
|
||||
None
|
||||
}
|
||||
/// Version and text of the open document at `path`.
|
||||
fn document(&self, path: &Path) -> Option<(u64, String)>;
|
||||
/// Applies `edits` to the open document at `path` if it is still at
|
||||
@@ -464,19 +459,6 @@ impl HostApi for PluginApi {
|
||||
.build()
|
||||
.map_err(|e| HostError::Invalid(format!("{glob:?}: {e}")))?
|
||||
.compile_matcher();
|
||||
// Hidden files and folders are left out, as in the walk below.
|
||||
let visible = |rel: &Path| !rel.iter().any(|c| c.to_str().is_some_and(|c| c.starts_with('.')));
|
||||
// The project index already lists the files: walking a large tree on every call can take
|
||||
// longer than an editor provider's deadline (the plugin is then stopped as crashed).
|
||||
if let Some(files) = self
|
||||
.shared
|
||||
.workspace()
|
||||
.and_then(|w| w.indexed_files(root, &|rel| visible(rel) && matcher.is_match(rel), limit))
|
||||
{
|
||||
let mut out: Vec<String> = files.iter().map(|p| to_ipc(p)).collect();
|
||||
out.sort();
|
||||
return Ok(out);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (n, entry) in ignore::WalkBuilder::new(root).hidden(true).build().flatten().enumerate() {
|
||||
if n >= MAX_WALK || out.len() >= limit {
|
||||
@@ -756,12 +738,6 @@ impl PluginWorkspace for HostWorkspace {
|
||||
HostWorkspace::projects(self).iter().find_map(|p| p.documents.text_of(path))
|
||||
}
|
||||
|
||||
fn indexed_files(&self, root: &Path, matches: &dyn Fn(&Path) -> bool, limit: usize) -> Option<Vec<PathBuf>> {
|
||||
// The index of the project rooted at `root` (a workspace member's files are in its own).
|
||||
let project = HostWorkspace::projects(self).into_iter().find(|p| p.root == root)?;
|
||||
project.index.files_matching(root, matches, limit)
|
||||
}
|
||||
|
||||
fn document(&self, path: &Path) -> Option<(u64, String)> {
|
||||
let (project, doc) = self.open_document(path)?;
|
||||
let snap = project.documents.snapshot(doc).ok()?;
|
||||
@@ -845,60 +821,6 @@ mod tests {
|
||||
assert_eq!(api.vcs_status(&root).unwrap().unwrap().root, to_ipc(&root));
|
||||
}
|
||||
|
||||
/// A project index that lists `files` (root-relative), whatever is on disk.
|
||||
struct Indexed(PathBuf, Vec<&'static str>);
|
||||
impl PluginWorkspace for Indexed {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.0.clone()]
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
|
||||
Err(HostError::Stale)
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, _: &str) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
fn indexed_files(&self, root: &Path, matches: &dyn Fn(&Path) -> bool, limit: usize) -> Option<Vec<PathBuf>> {
|
||||
(root == self.0).then(|| {
|
||||
self.1.iter().map(Path::new).filter(|rel| matches(rel)).take(limit).map(|rel| root.join(rel)).collect()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_files_uses_the_project_index_when_there_is_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let api = api(&root, Arc::default());
|
||||
*api.shared.workspace.write() = Some(Arc::new(Indexed(
|
||||
root.clone(),
|
||||
vec!["src/b/UserMapper.xml", "src/a/OrderMapper.xml", ".idea/workspace.xml", "pom.xml"],
|
||||
)));
|
||||
// Listed by the index, not walked: none of these exist on disk.
|
||||
assert_eq!(
|
||||
api.find_files(&root, "**/*Mapper.xml", 10).unwrap(),
|
||||
[to_ipc(&root.join("src/a/OrderMapper.xml")), to_ipc(&root.join("src/b/UserMapper.xml"))]
|
||||
);
|
||||
assert_eq!(api.find_files(&root, "**/*.xml", 10).unwrap().len(), 3, "hidden folders are left out");
|
||||
assert_eq!(api.find_files(&root, "**/*.xml", 1).unwrap().len(), 1);
|
||||
// Another root: no index covers it, so the disk is walked.
|
||||
let other = root.join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
std::fs::write(other.join("a.xml"), "").unwrap();
|
||||
assert_eq!(api.find_files(&other, "*.xml", 10).unwrap(), [to_ipc(&other.join("a.xml"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn programs_run_only_as_approved() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -35,8 +35,6 @@ async fn opens_unity_without_generated_solutions_and_excludes_caches_from_the_in
|
||||
assert!(unity.projects.is_empty() && unity.solutions.is_empty());
|
||||
assert!(project.index.wait_idle(Duration::from_secs(20)));
|
||||
assert_eq!(project.index.find_files("Player.cs", 100).len(), 1);
|
||||
let listed = project.index.files_matching(&project.root, |rel| rel.ends_with("Player.cs"), 10).unwrap();
|
||||
assert_eq!(listed.len(), 1);
|
||||
for name in ["Cached.cs", "Temporary.cs", "Editor.log"] {
|
||||
assert!(project.index.find_files(name, 100).is_empty(), "indexed generated file {name}");
|
||||
}
|
||||
|
||||
@@ -197,28 +197,6 @@ impl ProjectIndex {
|
||||
matching::find_files(&d, &matching::Recents { paths: &recent }, query, limit)
|
||||
}
|
||||
|
||||
/// Up to `limit` indexed files below `dir` (VCS-ignored ones left out) whose path relative to
|
||||
/// `dir` satisfies `matches`: a file list without walking the disk. `None` while nothing is
|
||||
/// indexed yet (first scan without a cache).
|
||||
pub fn files_matching(&self, dir: &Path, matches: impl Fn(&Path) -> bool, limit: usize) -> Option<Vec<PathBuf>> {
|
||||
let d = self.shared.data.read();
|
||||
if d.file_count == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for file in d.files.iter().flatten().filter(|f| !f.ignored) {
|
||||
if out.len() >= limit {
|
||||
break;
|
||||
}
|
||||
if let Ok(rel) = file.path.strip_prefix(dir)
|
||||
&& matches(rel)
|
||||
{
|
||||
out.push(file.path.clone());
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Fuzzy search for folders that hold indexed files; `rel_path` ends in `/`.
|
||||
pub fn find_dirs(&self, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
matching::find_dirs(&self.shared.data.read(), query, limit)
|
||||
|
||||
@@ -136,12 +136,6 @@ impl ClientHandler {
|
||||
|
||||
fn show_message(&self, mgr: &LspManager, params: &Value) {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
// rust-analyzer built from source reports its own slow main-loop turns as errors, meant for
|
||||
// its developers (`poke_rust_analyzer_developer`); nothing for the user to act on.
|
||||
if text.starts_with("overly long loop turn") {
|
||||
tracing::warn!("[{}] {text}", self.server.name);
|
||||
return;
|
||||
}
|
||||
let level = match params.get("type").and_then(Value::as_u64) {
|
||||
Some(1) => NotifyLevel::Error,
|
||||
Some(2) => NotifyLevel::Warning,
|
||||
|
||||
@@ -954,11 +954,6 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
assert_eq!(v, Value::Null);
|
||||
assert!(peer.request::<_, Value>("unknown/method", Value::Null, None).await.is_err());
|
||||
|
||||
peer.notify(
|
||||
"window/showMessage",
|
||||
json!({ "type": 1, "message": "overly long loop turn took 113ms (event handling took 95ms): PrimeCaches" }),
|
||||
)
|
||||
.unwrap();
|
||||
peer.notify("window/showMessage", json!({ "type": 2, "message": "careful" })).unwrap();
|
||||
peer.notify("window/showMessage", json!({ "type": 3, "message": "info only" })).unwrap();
|
||||
peer.notify("window/logMessage", json!({ "type": 1, "message": "log" })).unwrap();
|
||||
@@ -967,10 +962,7 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
})
|
||||
.await;
|
||||
let notifies = h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Notify { .. })).count();
|
||||
assert_eq!(
|
||||
notifies, 2,
|
||||
"showMessageRequest error + showMessage warning; info and rust-analyzer's developer notices are not surfaced"
|
||||
);
|
||||
assert_eq!(notifies, 2, "showMessageRequest error + showMessage warning; info is not surfaced");
|
||||
|
||||
// Dynamically registered capability is now usable.
|
||||
s.respond(
|
||||
|
||||
@@ -32,7 +32,6 @@ const BUILD_FILES: &[&str] = &[
|
||||
"Pipfile",
|
||||
"requirements.txt",
|
||||
"package.json",
|
||||
"composer.json",
|
||||
];
|
||||
|
||||
/// Folder names that are (or contain) conventional roots.
|
||||
@@ -215,15 +214,6 @@ fn module_roots(root: &Path, rel: &str, files: &[String], out: &mut Vec<SourceFo
|
||||
}
|
||||
}
|
||||
|
||||
// Before `package.json`: a Laravel app's `tests/` is the PHP test root.
|
||||
if has("composer.json")
|
||||
&& let Ok(text) = std::fs::read_to_string(dir.join("composer.json"))
|
||||
{
|
||||
for (sub, kind) in composer_roots(&text) {
|
||||
add(&sub, kind, "composer.json");
|
||||
}
|
||||
}
|
||||
|
||||
if has("package.json") {
|
||||
// A JVM build's `src` holds source sets, not JavaScript.
|
||||
if !has("pom.xml") && !GRADLE_FILES.iter().any(|f| has(f)) {
|
||||
@@ -240,37 +230,6 @@ fn module_roots(root: &Path, rel: &str, files: &[String], out: &mut Vec<SourceFo
|
||||
}
|
||||
}
|
||||
|
||||
/// `autoload.psr-4` folders as Source roots and `autoload-dev.psr-4` ones as Test roots, relative to
|
||||
/// the `composer.json` folder; paths that leave it or point into `vendor/` are left out.
|
||||
fn composer_roots(text: &str) -> Vec<(String, RootKind)> {
|
||||
let Ok(json) = serde_json::from_str::<serde_json::Value>(text) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for (section, kind) in [("autoload", RootKind::Source), ("autoload-dev", RootKind::Test)] {
|
||||
let Some(map) = json.get(section).and_then(|a| a.get("psr-4")).and_then(|m| m.as_object()) else { continue };
|
||||
for value in map.values() {
|
||||
let paths: Vec<&str> = match value {
|
||||
serde_json::Value::String(p) => vec![p.as_str()],
|
||||
serde_json::Value::Array(a) => a.iter().filter_map(|p| p.as_str()).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
for path in paths {
|
||||
let parts: Vec<&str> = path.split(['/', '\\']).filter(|c| !c.is_empty() && *c != ".").collect();
|
||||
if path.starts_with(['/', '\\'])
|
||||
|| parts.iter().any(|c| *c == ".." || c.contains(':'))
|
||||
|| parts.first() == Some(&"vendor")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let sub = parts.join("/");
|
||||
if !out.iter().any(|(p, _)| *p == sub) {
|
||||
out.push((sub, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gradle's conventional `src/<set>/<lang>` folders that exist: `(set, lang)`.
|
||||
fn source_sets(dir: &Path) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
@@ -348,47 +307,6 @@ mod tests {
|
||||
assert!(roots.roots.iter().any(|r| r.path == "server/src" && r.kind == RootKind::Source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_psr4_folders_are_source_and_test_roots() {
|
||||
let dir = tree(&[
|
||||
"app/",
|
||||
"database/factories/",
|
||||
"database/seeders/",
|
||||
"lib/",
|
||||
"tests/",
|
||||
"vendor/acme/src/",
|
||||
"package.json",
|
||||
]);
|
||||
fs::write(
|
||||
dir.path().join("composer.json"),
|
||||
r#"{
|
||||
"autoload": { "psr-4": {
|
||||
"App\\": "app/",
|
||||
"Database\\Factories\\": "database/factories/",
|
||||
"Database\\Seeders\\": ["database/seeders/", "lib", "missing/"],
|
||||
"Vendored\\": "vendor/acme/src/",
|
||||
"Outside\\": "../elsewhere/"
|
||||
} },
|
||||
"autoload-dev": { "psr-4": { "Tests\\": "tests/" } }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut roots = summary(&detect(dir.path()));
|
||||
roots.sort();
|
||||
assert_eq!(
|
||||
roots,
|
||||
[
|
||||
"[email protected]",
|
||||
"database/[email protected]",
|
||||
"database/[email protected]",
|
||||
"[email protected]",
|
||||
"[email protected]",
|
||||
]
|
||||
);
|
||||
assert!(affects_roots(Path::new("composer.json")));
|
||||
assert!(composer_roots("not json").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_conventional_roots_and_target() {
|
||||
let dir = tree(&[
|
||||
|
||||
@@ -6870,8 +6870,6 @@ export type SmartKeysSettings = {
|
||||
/** Reformat on paste: `none` | `indentBlock` | `indentEachLine`. */
|
||||
reformatOnPaste?: string,
|
||||
smartIndent?: boolean,
|
||||
/** Enter › Insert documentation comment stub: Enter after `/**` closes the comment. */
|
||||
insertDocStub?: boolean,
|
||||
/** Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`. */
|
||||
backspaceUnindent?: string,
|
||||
};
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { undo, history } from "@codemirror/commands";
|
||||
import { enterInDocComment, phpDocTags } from "./docComment";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
|
||||
const slashStar = EditorState.languageData.of(() => [
|
||||
{ commentTokens: { line: "//", block: { open: "/*", close: "*/" } } },
|
||||
]);
|
||||
const hash = EditorState.languageData.of(() => [{ commentTokens: { line: "#" } }]);
|
||||
|
||||
/** `|` marks the caret. */
|
||||
function enter(text: string, language = "php", tokens = slashStar) {
|
||||
const at = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text.replace("|", ""),
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: [tokens, history()],
|
||||
}),
|
||||
});
|
||||
views.push(view);
|
||||
const handled = enterInDocComment(language)(view);
|
||||
const s = view.state;
|
||||
const caret = s.selection.main.head;
|
||||
return { handled, view, text: s.doc.sliceString(0, caret) + "|" + s.doc.sliceString(caret) };
|
||||
}
|
||||
|
||||
describe("Enter after /**", () => {
|
||||
it("lists a PHP function's parameters and return type, caret on the summary line", () => {
|
||||
const r = enter("/**|\nfunction f(int $a, $b): string {}\n/**\n * old\n */\nfunction g() {}");
|
||||
expect(r.handled).toBe(true);
|
||||
expect(r.text).toBe(
|
||||
"/**\n * |\n * @param int $a\n * @param $b\n * @return string\n */\nfunction f(int $a, $b): string {}\n/**\n * old\n */\nfunction g() {}",
|
||||
);
|
||||
undo(r.view);
|
||||
expect(r.view.state.doc.toString()).toBe(
|
||||
"/**\nfunction f(int $a, $b): string {}\n/**\n * old\n */\nfunction g() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the indentation of the /** line inside a class", () => {
|
||||
expect(
|
||||
enter("class A {\n /**|\n public static function make(?array $o = [], string ...$rest): ?static {}\n}")
|
||||
.text,
|
||||
).toBe(
|
||||
"class A {\n /**\n * |\n * @param ?array $o\n * @param string ...$rest\n * @return ?static\n */\n public static function make(?array $o = [], string ...$rest): ?static {}\n}",
|
||||
);
|
||||
});
|
||||
|
||||
it("gives constructors and void methods no @return; promoted parameters keep their type", () => {
|
||||
expect(phpDocTags("public function __construct(private int $a, #[Attr] readonly Foo&Bar $b) {}")).toEqual([
|
||||
"@param int $a",
|
||||
"@param Foo&Bar $b",
|
||||
]);
|
||||
expect(phpDocTags("function run(array &$x = array(1, 2), &$y): void {}")).toEqual(["@param array $x", "@param $y"]);
|
||||
expect(phpDocTags("abstract protected function find(int|string $id): ?Model;")).toEqual([
|
||||
"@param int|string $id",
|
||||
"@return ?Model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the comment with an empty summary above anything else, and in other /* */ languages", () => {
|
||||
expect(enter("/**|\nclass A {}").text).toBe("/**\n * |\n */\nclass A {}");
|
||||
expect(enter(" /**|\n\nconst x = 1;", "javascript").text).toBe(" /**\n * |\n */\n\nconst x = 1;");
|
||||
});
|
||||
|
||||
it("only breaks the line in an existing doc block, after other text, or without /* */ comments", () => {
|
||||
expect(enter("/**|\n * old\n */\nfunction f() {}").handled).toBe(false);
|
||||
expect(enter("$a = 1; /**|").handled).toBe(false);
|
||||
expect(enter("/** x|").handled).toBe(false);
|
||||
expect(enter("/**|", "python", hash).handled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Smart Keys › Enter › Insert documentation comment stub: Enter right after a `/**` that opens a
|
||||
* new comment closes it, the caret on the summary line. In PHP the stub of a function lists its
|
||||
* parameters (`@param`) and return type (`@return`), as PhpStorm does.
|
||||
*/
|
||||
import { EditorSelection } from "@codemirror/state";
|
||||
import type { Command } from "@codemirror/view";
|
||||
|
||||
/** `@param` / `@return` lines for the PHP function declared in `text` (the code below the `/**`). */
|
||||
export function phpDocTags(text: string): string[] {
|
||||
const m =
|
||||
/^\s*(?:#\[[^\]]*\]\s*)*(?:(?:abstract|final|public|protected|private|static)\s+)*function\s+&?\s*(\w+)\s*\(/.exec(
|
||||
text,
|
||||
);
|
||||
if (!m) return [];
|
||||
let depth = 1;
|
||||
let i = m[0].length;
|
||||
for (; i < text.length && depth > 0; i++) {
|
||||
const c = text[i];
|
||||
if (c === "(" || c === "[") depth++;
|
||||
else if (c === ")" || c === "]") depth--;
|
||||
}
|
||||
if (depth > 0) return [];
|
||||
const tags = splitTopLevel(text.slice(m[0].length, i - 1)).flatMap((param) => {
|
||||
const p = /^(?:#\[[^\]]*\]\s*)*(?:(?:public|protected|private|readonly)\s+)*([^$=.]*?)\s*(\.\.\.)?\s*(\$\w+)/.exec(
|
||||
param.trim(),
|
||||
);
|
||||
if (!p) return [];
|
||||
// `&$x` passes by reference: the `&` belongs to no type (`Foo&Bar` is an intersection).
|
||||
const type = p[1]!.replace(/&\s*$/, "").trim().replace(/\s+/g, " ");
|
||||
const name = (p[2] ?? "") + p[3];
|
||||
return [type ? `@param ${type} ${name}` : `@param ${name}`];
|
||||
});
|
||||
const ret = /^\s*:\s*([?\w\\|&() ]+?)\s*(?:\{|;|$)/.exec(text.slice(i));
|
||||
const type = ret?.[1]?.trim();
|
||||
if (type && type !== "void" && m[1] !== "__construct") tags.push(`@return ${type}`);
|
||||
return tags;
|
||||
}
|
||||
|
||||
function splitTopLevel(params: string): string[] {
|
||||
const out: string[] = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
for (let i = 0; i < params.length; i++) {
|
||||
const c = params[i];
|
||||
if (c === "(" || c === "[") depth++;
|
||||
else if (c === ")" || c === "]") depth--;
|
||||
else if (c === "," && depth === 0) {
|
||||
out.push(params.slice(start, i));
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
out.push(params.slice(start));
|
||||
return out.filter((p) => p.trim());
|
||||
}
|
||||
|
||||
/** The Enter command for documents of `language` (stub tags in PHP). */
|
||||
export function enterInDocComment(language: string | undefined): Command {
|
||||
return (view) => {
|
||||
const { state } = view;
|
||||
if (state.readOnly || state.selection.ranges.length !== 1) return false;
|
||||
const r = state.selection.main;
|
||||
if (!r.empty) return false;
|
||||
const block = state.languageDataAt<{ block?: { open: string; close: string } }>("commentTokens", r.head)[0]?.block;
|
||||
if (block?.open !== "/*" || block.close !== "*/") return false;
|
||||
const line = state.doc.lineAt(r.head);
|
||||
const before = line.text.slice(0, r.head - line.from);
|
||||
if (before.trim() !== "/**" || line.text.slice(r.head - line.from).trim()) return false;
|
||||
// A `/**` that already starts a doc block (the next line continues it) only breaks the line.
|
||||
const next = line.number < state.doc.lines ? state.doc.line(line.number + 1).text.trimStart() : "";
|
||||
if (next.startsWith("*")) return false;
|
||||
const indent = /^[ \t]*/.exec(before)![0];
|
||||
const br = state.lineBreak;
|
||||
const below = line.number < state.doc.lines ? state.sliceDoc(state.doc.line(line.number + 1).from) : "";
|
||||
const tags = language === "php" ? phpDocTags(below.slice(0, 4000)) : [];
|
||||
const summary = `${br}${indent} * `;
|
||||
const insert = summary + tags.map((t) => `${br}${indent} * ${t}`).join("") + `${br}${indent} */`;
|
||||
view.dispatch(
|
||||
state.update({
|
||||
changes: { from: r.head, insert },
|
||||
selection: EditorSelection.cursor(r.head + summary.length),
|
||||
scrollIntoView: true,
|
||||
userEvent: "input",
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
@@ -48,7 +48,6 @@ import {
|
||||
selectHumpRight,
|
||||
} from "./editing";
|
||||
import { enterInLineComment, lineCommentStyle, type LineCommentStyle } from "./comments";
|
||||
import { enterInDocComment } from "./docComment";
|
||||
import { skipClosingQuote, smartBackspace, smartBackspaceApplies, tabOut } from "./smartKeys";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
@@ -572,7 +571,6 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
{ key: "Home", run: cursorLineStart, shift: selectLineStart, preventDefault: true },
|
||||
{ mac: "Mod-ArrowLeft", run: cursorLineStart, shift: selectLineStart, preventDefault: true },
|
||||
);
|
||||
if (!o.readOnly && k.insertDocStub) keys.push({ key: "Enter", run: enterInDocComment(o.language) });
|
||||
if (!o.readOnly) keys.push({ key: "Enter", run: enterInLineComment });
|
||||
if (!k.smartIndent) keys.push({ key: "Enter", run: insertNewlineKeepIndent });
|
||||
if (k.backspaceUnindent === "none") keys.push({ key: "Backspace", run: deleteCharBackwardStrict });
|
||||
|
||||
@@ -262,24 +262,6 @@ describe("EditorController", () => {
|
||||
useProject.setState({ lightEdit: false });
|
||||
});
|
||||
|
||||
it("opens a file requested while the LightEdit session is being restored", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/x/a.txt": "a", "/y/b.md": "b", "/z/launch.lua": "l" }));
|
||||
ctrl.start();
|
||||
useProject.setState({ lightEdit: true });
|
||||
await ctrl.openFile("/x/a.txt", { focus: false });
|
||||
await ctrl.openFile("/y/b.md", { focus: false });
|
||||
useProject.setState({ lightEdit: false });
|
||||
// A launch with a file path: LightEdit starts and the file opens before the old tabs are back.
|
||||
useProject.setState({ lightEdit: true });
|
||||
await ctrl.openFile("/z/launch.lua", { focus: false });
|
||||
expect(openFilePaths(useTabs.getState())).toEqual(["/x/a.txt", "/y/b.md", "/z/launch.lua"]);
|
||||
const s = useTabs.getState();
|
||||
const active = s.panes[s.activePane]!;
|
||||
expect(active.tabs.find((t) => t.id === active.active)?.input.path).toBe("/z/launch.lua");
|
||||
await ctrl.closeEverything();
|
||||
useProject.setState({ lightEdit: false });
|
||||
});
|
||||
|
||||
it("closes a tab by its input key", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend());
|
||||
ctrl.start();
|
||||
|
||||
@@ -237,8 +237,6 @@ export class EditorController implements SlotHost {
|
||||
private selectionRequests = new Map<string, number>();
|
||||
private activationGeneration = 0;
|
||||
private admitting = false;
|
||||
/** Tabs restored from a saved session: not a user's activation, so a pending open still activates its tab. */
|
||||
private restoring = false;
|
||||
private closeRequests = 0;
|
||||
private projectTransition: Promise<void> = Promise.resolve();
|
||||
|
||||
@@ -271,7 +269,6 @@ export class EditorController implements SlotHost {
|
||||
prevTabs = s;
|
||||
if (
|
||||
!this.admitting &&
|
||||
!this.restoring &&
|
||||
(s.activePane !== prev.activePane || s.panes[s.activePane]?.active !== prev.panes[prev.activePane]?.active)
|
||||
)
|
||||
++this.activationGeneration;
|
||||
@@ -489,12 +486,7 @@ export class EditorController implements SlotHost {
|
||||
pane.tabs = pane.tabs.map((tab) => (documentLifecycle(tab.input, kinds) ? { ...tab, preview: false } : tab));
|
||||
this.restoredViews = new Map(Object.entries(session.files));
|
||||
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
|
||||
this.restoring = true;
|
||||
try {
|
||||
useTabs.setState(state, true);
|
||||
} finally {
|
||||
this.restoring = false;
|
||||
}
|
||||
useTabs.setState(state, true);
|
||||
for (const pane of Object.values(state.panes)) if (pane.active) void this.ensureSlot(pane.active);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { filterColumns } from "./ColumnsPopup";
|
||||
|
||||
const columns = ["id", "user_id", "name", "created_at", "username"].map((name) => ({ name, type: "TEXT" }));
|
||||
|
||||
describe("filterColumns", () => {
|
||||
it("lists every column for an empty query", () => {
|
||||
expect(filterColumns(columns, " ")).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it("puts prefix matches first, then other matches, ignoring case", () => {
|
||||
expect(filterColumns(columns, "US")).toEqual([1, 4]);
|
||||
expect(filterColumns(columns, "name")).toEqual([2, 4]);
|
||||
expect(filterColumns(columns, "_id")).toEqual([1]);
|
||||
});
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Go to Column in a table editor (⌘F12 / Ctrl+F12): the grid's columns, filtered as you type;
|
||||
* Enter selects that column's cell in the current row.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { Icon, Input, List, Popup, listNavigate } from "@/ui";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { GridColumn } from "./Grid";
|
||||
import styles from "./Database.module.css";
|
||||
|
||||
export function filterColumns(columns: readonly GridColumn[], query: string): number[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
const all = columns.map((_, i) => i);
|
||||
if (!q) return all;
|
||||
const starts = all.filter((i) => columns[i]!.name.toLowerCase().startsWith(q));
|
||||
const contains = all.filter((i) => !starts.includes(i) && columns[i]!.name.toLowerCase().includes(q));
|
||||
return [...starts, ...contains];
|
||||
}
|
||||
|
||||
export function ColumnsPopup(props: {
|
||||
anchor: { x: number; y: number };
|
||||
table: string;
|
||||
columns: readonly GridColumn[];
|
||||
onPick: (col: number) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [active, setActive] = useState(0);
|
||||
const shown = filterColumns(props.columns, query);
|
||||
const current = Math.min(active, shown.length - 1);
|
||||
const pick = (i: number) => {
|
||||
const col = shown[i];
|
||||
if (col !== undefined) props.onPick(col);
|
||||
};
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={props.anchor}
|
||||
placement="bottom"
|
||||
onClose={props.onClose}
|
||||
aria-label={tx`Columns of ${props.table}`}
|
||||
className={styles.columnsPopup}
|
||||
trapFocus
|
||||
>
|
||||
<Input
|
||||
autoFocus
|
||||
aria-label={tx("Search columns")}
|
||||
placeholder={tx`Columns of ${props.table}`}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setActive(0);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
pick(current);
|
||||
return;
|
||||
}
|
||||
const next = listNavigate(e.key, { items: shown, active: current });
|
||||
if (next !== null) {
|
||||
e.preventDefault();
|
||||
setActive(next);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<List
|
||||
items={shown}
|
||||
getKey={(col) => String(col)}
|
||||
activeIndex={current}
|
||||
onActiveChange={setActive}
|
||||
onActivate={(_, i) => pick(i)}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
rowHeight={22}
|
||||
aria-label={tx("Columns")}
|
||||
className={styles.columnsList}
|
||||
empty={<span>{tx("No matching columns")}</span>}
|
||||
renderItem={(col) => {
|
||||
const c = props.columns[col]!;
|
||||
return (
|
||||
<span className={styles.columnsRow}>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : c.foreignKey ? "db-column-fk" : "db-column"} size={16} />
|
||||
{c.name}
|
||||
{c.type && c.type !== "NULL" && <span className={styles.treeType}>{c.type}</span>}
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -90,7 +90,6 @@ export interface DataViewProps extends Pick<
|
||||
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
|
||||
searchOpen?: boolean;
|
||||
onSearchOpenChange?: (open: boolean) => void;
|
||||
revealColumn?: GridProps["revealColumn"];
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
@@ -201,7 +200,6 @@ export function DataView(props: DataViewProps) {
|
||||
isMatch={test ? (r, c) => matchSet.has(`${r}:${c}`) : undefined}
|
||||
currentMatch={currentMatch}
|
||||
onFind={onSearchOpenChange && openSearch}
|
||||
revealColumn={props.revealColumn}
|
||||
aria-label={props["aria-label"]}
|
||||
columns={columns}
|
||||
rowCount={shown}
|
||||
|
||||
@@ -823,25 +823,6 @@
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
/* Go to Column (ColumnsPopup.tsx). */
|
||||
.columnsPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
width: 320px;
|
||||
padding: 8px;
|
||||
}
|
||||
.columnsList {
|
||||
height: min(320px, 50vh);
|
||||
}
|
||||
.columnsRow {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.filterPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -57,8 +57,6 @@ export interface GridProps {
|
||||
currentMatch?: { row: number; col: number } | null;
|
||||
/** ⌘F / Ctrl+F in the grid (opens the search bar). */
|
||||
onFind?: () => void;
|
||||
/** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */
|
||||
revealColumn?: { col: number } | null;
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
@@ -162,37 +160,15 @@ export function Grid(props: GridProps) {
|
||||
estimateSize: () => ROW_H,
|
||||
overscan: 12,
|
||||
});
|
||||
/** Scrolls sideways so column `c` is visible (the first one with the row numbers). */
|
||||
const scrollColumnIntoView = (c: number) => {
|
||||
const el = scrollRef.current;
|
||||
if (!el || c < 0 || c >= widths.length) return;
|
||||
const left = c ? NUM_W + widths.slice(0, c).reduce((a, b) => a + b, 0) : 0;
|
||||
const right = NUM_W + widths.slice(0, c + 1).reduce((a, b) => a + b, 0);
|
||||
if (left < el.scrollLeft) el.scrollLeft = left;
|
||||
else if (right > el.scrollLeft + el.clientWidth) el.scrollLeft = Math.min(left, right - el.clientWidth);
|
||||
};
|
||||
const { currentMatch } = props;
|
||||
useEffect(() => {
|
||||
if (!currentMatch) return;
|
||||
const { row, col } = currentMatch;
|
||||
setSel({ r0: row, c0: col, r1: row, c1: col });
|
||||
virtualizer.scrollToIndex(row, { align: "auto" });
|
||||
scrollColumnIntoView(col);
|
||||
// Follows the match only, not the virtualizer's identity.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentMatch?.row, currentMatch?.col]);
|
||||
const { revealColumn } = props;
|
||||
useEffect(() => {
|
||||
if (!revealColumn || !rowCount) return;
|
||||
const { col } = revealColumn;
|
||||
const row = sel ? Math.min(sel.r1, rowCount - 1) : 0;
|
||||
setSel({ r0: row, c0: col, r1: row, c1: col });
|
||||
virtualizer.scrollToIndex(row, { align: "auto" });
|
||||
scrollColumnIntoView(col);
|
||||
scrollRef.current?.focus({ preventScroll: true });
|
||||
// Runs once per request.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [revealColumn]);
|
||||
const totalWidth = useMemo(() => NUM_W + widths.reduce((a, b) => a + b, 0), [widths]);
|
||||
const template = `${NUM_W}px ${widths.map((w) => `${w}px`).join(" ")}`;
|
||||
|
||||
@@ -279,7 +255,6 @@ export function Grid(props: GridProps) {
|
||||
const c = Math.max(0, Math.min(columns.length - 1, sel.c1 + m[1]));
|
||||
setSel(e.shiftKey ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c });
|
||||
virtualizer.scrollToIndex(r, { align: "auto" });
|
||||
scrollColumnIntoView(c);
|
||||
};
|
||||
|
||||
const onCellMouseDown = (e: MouseEvent, r: number, c: number) => {
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
import { Button, EmptyState, Icon, IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { SqlFilterInput } from "./SqlFilterInput";
|
||||
import { ColumnsPopup } from "./ColumnsPopup";
|
||||
import { DataView, ExtractorSelect, PanelToggle, exportMenu, type DataPanel } from "./DataView";
|
||||
import type { ExportFormat } from "./export";
|
||||
import {
|
||||
@@ -183,23 +182,12 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
const dirty = hasEdits(edits);
|
||||
// Submit / Revert actions (⌘↩ / ⌥⌘Z) reach the latest state through the handle.
|
||||
const viewRef = useRef<HTMLDivElement>(null);
|
||||
const handle = useRef<TableEditorHandle>({
|
||||
dirty: false,
|
||||
submit: () => {},
|
||||
revert: () => {},
|
||||
showColumns: () => {},
|
||||
}).current;
|
||||
const handle = useRef<TableEditorHandle>({ dirty: false, submit: () => {}, revert: () => {} }).current;
|
||||
handle.dirty = editable && dirty;
|
||||
handle.submit = () => {
|
||||
if (editable && dirty) void submit();
|
||||
};
|
||||
handle.revert = () => setEdits(emptyEdits());
|
||||
const [columnsAt, setColumnsAt] = useState<{ x: number; y: number } | null>(null);
|
||||
const [revealColumn, setRevealColumn] = useState<{ col: number } | null>(null);
|
||||
handle.showColumns = () => {
|
||||
const r = viewRef.current?.getBoundingClientRect();
|
||||
if (page && r) setColumnsAt({ x: r.left + r.width / 2, y: r.top + 48 });
|
||||
};
|
||||
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
|
||||
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
|
||||
const orderInvalid = orderDraft !== null && !parseOrderBy(orderDraft, names);
|
||||
@@ -351,7 +339,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
columns={gridColumns}
|
||||
rowCount={rowCount}
|
||||
fixedRows={loaded}
|
||||
revealColumn={revealColumn}
|
||||
value={value}
|
||||
panel={panel}
|
||||
onPanelChange={setPanel}
|
||||
@@ -379,18 +366,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{columnsAt && (
|
||||
<ColumnsPopup
|
||||
anchor={columnsAt}
|
||||
table={ref.table}
|
||||
columns={gridColumns}
|
||||
onPick={(col) => {
|
||||
setColumnsAt(null);
|
||||
setRevealColumn({ col });
|
||||
}}
|
||||
onClose={() => setColumnsAt(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -154,14 +154,6 @@ export function activate(): () => void {
|
||||
await executeInView(e.view, e.ctx.path);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "db.goToColumn",
|
||||
title: "Go to Column",
|
||||
category: "Tools",
|
||||
keywords: ["table editor", "file structure", "columns"],
|
||||
when: "dbTableEditorFocus",
|
||||
run: () => activeTableEditor()?.showColumns(),
|
||||
},
|
||||
{
|
||||
id: "db.submitChanges",
|
||||
title: "Submit",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* The table editor that has focus, for Submit / Revert (⌘↩ / ⌥⌘Z) and Go to Column (⌘F12). Not
|
||||
* while a text field has it: ⌘↩ there applies the field's own edit (the Value panel, the cell editor).
|
||||
* The table editor that has focus, for Submit / Revert (⌘↩ / ⌥⌘Z). Not while a text field has
|
||||
* it: ⌘↩ there applies the field's own edit (the Value panel, the cell editor).
|
||||
*/
|
||||
import { setContext } from "@/platform/context";
|
||||
|
||||
@@ -8,7 +8,6 @@ export interface TableEditorHandle {
|
||||
dirty: boolean;
|
||||
submit(): void;
|
||||
revert(): void;
|
||||
showColumns(): void;
|
||||
}
|
||||
|
||||
const handles = new WeakMap<Element, TableEditorHandle>();
|
||||
|
||||
@@ -365,120 +365,111 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.consoleArea}>
|
||||
<div
|
||||
className={styles.consoleToolbar}
|
||||
role="toolbar"
|
||||
aria-orientation="vertical"
|
||||
aria-label={tx("Console actions")}
|
||||
>
|
||||
<IconButton
|
||||
icon="search"
|
||||
iconSize={14}
|
||||
title="Find…"
|
||||
shortcut={formatBinding(hostBinding("Meta+F"))}
|
||||
pressed={findOpen}
|
||||
onClick={() => (findOpen ? closeFind() : openFind())}
|
||||
<div className={styles.console}>
|
||||
{findOpen && (
|
||||
<ConsoleFindBar
|
||||
query={query}
|
||||
onChange={changeQuery}
|
||||
options={findOptions}
|
||||
onOptionsChange={changeOptions}
|
||||
count={found.matches.length}
|
||||
active={activeIndex}
|
||||
overflow={found.overflow}
|
||||
invalid={found.invalid}
|
||||
inputRef={findInput}
|
||||
onNext={() => goToMatch(1)}
|
||||
onPrevious={() => goToMatch(-1)}
|
||||
onClose={closeFind}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
ref={scroller}
|
||||
className={clsx(styles.consoleOutput, ansi.palette, !softWrap && styles.noWrap)}
|
||||
onScroll={(e) => {
|
||||
if (programmatic.current) return;
|
||||
const el = e.currentTarget;
|
||||
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
if (atEnd !== stick.current) setFollow(atEnd);
|
||||
}}
|
||||
onContextMenu={onContextMenu}
|
||||
role="log"
|
||||
onKeyDown={onOutputKeyDown}
|
||||
aria-label={tx("Debug console")}
|
||||
tabIndex={0}
|
||||
>
|
||||
{!lines?.length && session.launch?.request === "attach" && (
|
||||
<T>The attached process may not provide standard output to the debugger.</T>
|
||||
)}
|
||||
<div ref={inner} className={styles.consoleInner} style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
const l = lines?.[item.index];
|
||||
if (!l) return null;
|
||||
return (
|
||||
<span
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className={clsx(styles.out, styles[`cat-${l.category}`])}
|
||||
style={{ transform: `translateY(${item.start}px)` }}
|
||||
>
|
||||
{findSegments(l.spans, marksByLine.get(item.index) ?? [], current).map(segmentNode)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.repl}>
|
||||
{interactive && (
|
||||
<>
|
||||
<span className={styles.prompt} aria-hidden>
|
||||
›
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className={styles.evalInput}
|
||||
onFocus={() => setConsoleHistoryBrowser(browseHistory)}
|
||||
onBlur={() => {
|
||||
setConsoleHistoryBrowser(null);
|
||||
completion.close();
|
||||
}}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
completion.onInput();
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={isLive(session) ? "Evaluate in the debug console" : "Session finished"}
|
||||
disabled={!isLive(session)}
|
||||
aria-label={tx("Debug console input")}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{completion.popup}
|
||||
</>
|
||||
)}
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
iconSize={14}
|
||||
title="Scroll to End"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
pressed={follow}
|
||||
onClick={() => setFollow((v) => !v)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="soft-wrap"
|
||||
iconSize={14}
|
||||
title="Soft-Wrap"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
pressed={softWrap}
|
||||
onClick={() => setWrapOverride(!softWrap)}
|
||||
/>
|
||||
<IconButton icon="trash" iconSize={14} title="Clear Console" onClick={() => clearConsole(session.id)} />
|
||||
</div>
|
||||
<div className={styles.console}>
|
||||
{findOpen && (
|
||||
<ConsoleFindBar
|
||||
query={query}
|
||||
onChange={changeQuery}
|
||||
options={findOptions}
|
||||
onOptionsChange={changeOptions}
|
||||
count={found.matches.length}
|
||||
active={activeIndex}
|
||||
overflow={found.overflow}
|
||||
invalid={found.invalid}
|
||||
inputRef={findInput}
|
||||
onNext={() => goToMatch(1)}
|
||||
onPrevious={() => goToMatch(-1)}
|
||||
onClose={closeFind}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
ref={scroller}
|
||||
className={clsx(styles.consoleOutput, ansi.palette, !softWrap && styles.noWrap)}
|
||||
onScroll={(e) => {
|
||||
if (programmatic.current) return;
|
||||
const el = e.currentTarget;
|
||||
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
|
||||
if (atEnd !== stick.current) setFollow(atEnd);
|
||||
}}
|
||||
onContextMenu={onContextMenu}
|
||||
role="log"
|
||||
onKeyDown={onOutputKeyDown}
|
||||
aria-label={tx("Debug console")}
|
||||
tabIndex={0}
|
||||
>
|
||||
{!lines?.length && session.launch?.request === "attach" && (
|
||||
<T>The attached process may not provide standard output to the debugger.</T>
|
||||
)}
|
||||
<div ref={inner} className={styles.consoleInner} style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
const l = lines?.[item.index];
|
||||
if (!l) return null;
|
||||
return (
|
||||
<span
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className={clsx(styles.out, styles[`cat-${l.category}`])}
|
||||
style={{ transform: `translateY(${item.start}px)` }}
|
||||
>
|
||||
{findSegments(l.spans, marksByLine.get(item.index) ?? [], current).map(segmentNode)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.repl}>
|
||||
{interactive && (
|
||||
<>
|
||||
<span className={styles.prompt} aria-hidden>
|
||||
›
|
||||
</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className={styles.evalInput}
|
||||
onFocus={() => setConsoleHistoryBrowser(browseHistory)}
|
||||
onBlur={() => {
|
||||
setConsoleHistoryBrowser(null);
|
||||
completion.close();
|
||||
}}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
completion.onInput();
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={isLive(session) ? "Evaluate in the debug console" : "Session finished"}
|
||||
disabled={!isLive(session)}
|
||||
aria-label={tx("Debug console input")}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{completion.popup}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Clear Console"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
onClick={() => clearConsole(session.id)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -218,23 +218,6 @@
|
||||
}
|
||||
|
||||
/* console */
|
||||
/* The Console tab: actions in a vertical strip on the left, as in the Run window. */
|
||||
.consoleArea {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
}
|
||||
.consoleToolbar {
|
||||
flex: none;
|
||||
width: 32px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 4px 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.console {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Settings › Project Structure (IDEA's module "Sources" tab): the content
|
||||
* root's Sources / Tests / Resources / Test Resources / Excluded folders.
|
||||
* Roots detected from build files (`pom.xml`, `build.gradle`, `Cargo.toml`,
|
||||
* `go.mod`, `pyproject.toml`, `package.json`, `composer.json`) apply until the user marks or
|
||||
* `go.mod`, `pyproject.toml`, `package.json`) apply until the user marks or
|
||||
* unmarks the folder (`projectStructure.*`, project scope). Roots drive the
|
||||
* project tree icons, package inference for new classes, the "Project
|
||||
* Production / Test Files" scopes, and Excluded folders are skipped by the
|
||||
@@ -330,7 +330,7 @@ export function ProjectStructurePage() {
|
||||
<div className={styles.note}>
|
||||
<T>
|
||||
{
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index)."
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index)."
|
||||
}
|
||||
</T>
|
||||
</div>
|
||||
|
||||
@@ -677,10 +677,7 @@ const SMART_KEYS = editorPage({
|
||||
},
|
||||
{
|
||||
title: "Enter",
|
||||
items: [
|
||||
{ t: "check", key: `${P}.smartKeys.smartIndent`, label: "Smart indent" },
|
||||
{ t: "check", key: `${P}.smartKeys.insertDocStub`, label: "Insert documentation comment stub" },
|
||||
],
|
||||
items: [{ t: "check", key: `${P}.smartKeys.smartIndent`, label: "Smart indent" }],
|
||||
},
|
||||
{
|
||||
title: "Backspace",
|
||||
|
||||
@@ -3,10 +3,8 @@ import {
|
||||
caretAfterReformat,
|
||||
expandIncludes,
|
||||
fragmentResolver,
|
||||
composerPsr4,
|
||||
inferGoPackage,
|
||||
inferJvmPackage,
|
||||
inferPhpNamespace,
|
||||
planFile,
|
||||
reformatsOnCreate,
|
||||
renderFileTemplate,
|
||||
@@ -94,58 +92,6 @@ describe("file naming", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PHP namespaces", () => {
|
||||
const psr4 = composerPsr4(
|
||||
JSON.stringify({
|
||||
autoload: { "psr-4": { "App\\": "src/", "Legacy\\": ["src/legacy/", "lib"] } },
|
||||
"autoload-dev": { "psr-4": { "App\\Tests\\": "./tests" } },
|
||||
}),
|
||||
);
|
||||
|
||||
it("reads autoload and autoload-dev PSR-4 maps", () => {
|
||||
expect(psr4).toEqual([
|
||||
["App\\", "src"],
|
||||
["Legacy\\", "src/legacy"],
|
||||
["Legacy\\", "lib"],
|
||||
["App\\Tests\\", "tests"],
|
||||
]);
|
||||
expect(composerPsr4("{ not json")).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the longest mapped folder and adds the folders below it", () => {
|
||||
expect(inferPhpNamespace("/src/Http", psr4)).toBe("App\\Http");
|
||||
expect(inferPhpNamespace("/src", psr4)).toBe("App");
|
||||
expect(inferPhpNamespace("/src/legacy/Billing", psr4)).toBe("Legacy\\Billing");
|
||||
expect(inferPhpNamespace("/tests/Service", psr4)).toBe("App\\Tests\\Service");
|
||||
expect(inferPhpNamespace("/config", psr4)).toBe("");
|
||||
expect(inferPhpNamespace("/src/my-dir", psr4)).toBe("");
|
||||
expect(inferPhpNamespace("/x", [["", ""]])).toBe("x");
|
||||
});
|
||||
|
||||
it("writes the namespace into PHP classes, and leaves it out without one", () => {
|
||||
const kinds = tpl("php-class").kinds;
|
||||
const cls = renderFileTemplate(kinds[0]!.body, {
|
||||
name: "UserController",
|
||||
fileName: "UserController.php",
|
||||
packageName: "App\\Http",
|
||||
});
|
||||
expect(cls.text).toBe("<?php\n\nnamespace App\\Http;\n\nclass UserController\n{\n \n}\n");
|
||||
const bare = renderFileTemplate(kinds[0]!.body, { name: "Foo", fileName: "Foo.php" });
|
||||
expect(bare.text).toBe("<?php\n\nclass Foo\n{\n \n}\n");
|
||||
const test = renderFileTemplate(kinds.find((k) => k.id === "test")!.body, {
|
||||
name: "MailerTest",
|
||||
fileName: "MailerTest.php",
|
||||
packageName: "App\\Tests\\Service",
|
||||
});
|
||||
expect(test.text).toBe(
|
||||
"<?php\n\nnamespace App\\Tests\\Service;\n\nuse PHPUnit\\Framework\\TestCase;\n\nfinal class MailerTest extends TestCase\n{\n public function testSomething(): void\n {\n \n }\n}\n",
|
||||
);
|
||||
expect(renderFileTemplate(tpl("php").kinds[0]!.body, { name: "bootstrap", fileName: "bootstrap.php" }).text).toBe(
|
||||
"<?php\n\n\n",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rendering", () => {
|
||||
it("substitutes variables and places the caret", () => {
|
||||
const kind = tpl("java").kinds[0]!;
|
||||
|
||||
@@ -233,11 +233,7 @@ function NameStep({
|
||||
{error ?? (
|
||||
<>
|
||||
{where}
|
||||
{template.packageStyle && pkg
|
||||
? template.packageStyle === "php"
|
||||
? ` · namespace ${pkg}`
|
||||
: ` · package ${pkg}`
|
||||
: ""}
|
||||
{template.packageStyle && pkg ? ` · package ${pkg}` : ""}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -31,11 +31,6 @@ export const BUILTIN_CODE_TEMPLATES: readonly TemplateFragment[] = [
|
||||
description: "TypeScript File › Test",
|
||||
body: 'it("works", () => {\n $END$\n});\n',
|
||||
},
|
||||
{
|
||||
name: "PHPUnit Test Method",
|
||||
description: "PHP Class › PHPUnit Test",
|
||||
body: "public function testSomething(): void\n{\n $END$\n}\n",
|
||||
},
|
||||
{
|
||||
name: "pytest Test Function",
|
||||
description: "Python File › Test (pytest)",
|
||||
@@ -154,49 +149,6 @@ export const BUILTIN_FILE_TEMPLATES: readonly FileTemplate[] = [
|
||||
defaultName: "go",
|
||||
kinds: [{ id: "module", label: "Module", body: "module $PROJECT_NAME$\n\ngo 1.20\n" }],
|
||||
},
|
||||
{
|
||||
id: "php",
|
||||
name: "PHP File",
|
||||
icon: "file-php",
|
||||
extension: "php",
|
||||
nameStyle: "asis",
|
||||
kinds: [{ id: "file", label: "File", body: "<?php\n\n$END$\n" }],
|
||||
},
|
||||
{
|
||||
id: "php-class",
|
||||
name: "PHP Class",
|
||||
icon: "class",
|
||||
extension: "php",
|
||||
nameStyle: "pascal",
|
||||
packageStyle: "php",
|
||||
kinds: [
|
||||
{
|
||||
id: "class",
|
||||
label: "Class",
|
||||
body: '<?php\n\nnamespace $PACKAGE$;\n\n#parse("File Header")\nclass $NAME$\n{\n $END$\n}\n',
|
||||
},
|
||||
{
|
||||
id: "interface",
|
||||
label: "Interface",
|
||||
body: '<?php\n\nnamespace $PACKAGE$;\n\n#parse("File Header")\ninterface $NAME$\n{\n $END$\n}\n',
|
||||
},
|
||||
{
|
||||
id: "trait",
|
||||
label: "Trait",
|
||||
body: '<?php\n\nnamespace $PACKAGE$;\n\n#parse("File Header")\ntrait $NAME$\n{\n $END$\n}\n',
|
||||
},
|
||||
{
|
||||
id: "enum",
|
||||
label: "Enum",
|
||||
body: '<?php\n\nnamespace $PACKAGE$;\n\n#parse("File Header")\nenum $NAME$\n{\n $END$\n}\n',
|
||||
},
|
||||
{
|
||||
id: "test",
|
||||
label: "PHPUnit Test",
|
||||
body: '<?php\n\nnamespace $PACKAGE$;\n\nuse PHPUnit\\Framework\\TestCase;\n\n#parse("File Header")\nfinal class $NAME$ extends TestCase\n{\n #parse("PHPUnit Test Method")\n}\n',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "java",
|
||||
name: "Java Class",
|
||||
|
||||
@@ -10,10 +10,8 @@ import { editorService, maybeEditorService, notifications } from "@/workbench/co
|
||||
import {
|
||||
GO_PACKAGE_RE,
|
||||
caretAfterReformat,
|
||||
composerPsr4,
|
||||
inferGoPackage,
|
||||
inferJvmPackage,
|
||||
inferPhpNamespace,
|
||||
planFile,
|
||||
reformatsOnCreate,
|
||||
renderFileTemplate,
|
||||
@@ -48,29 +46,10 @@ function packageRoots(): string[] {
|
||||
.map((r) => r.path);
|
||||
}
|
||||
|
||||
/** The namespace from the nearest composer.json between `directory` and the project root (PSR-4). */
|
||||
async function composerNamespace(directory: string, root: string | null): Promise<string> {
|
||||
if (!isTauri()) return "";
|
||||
let dir = directory.replace(/\/+$/, "");
|
||||
const top = root?.replace(/\/+$/, "") ?? null;
|
||||
for (;;) {
|
||||
let text: string | null = null;
|
||||
try {
|
||||
text = await call(commands.fsReadText(`${dir}/composer.json`));
|
||||
} catch {
|
||||
/* no composer.json here */
|
||||
}
|
||||
if (text !== null) return inferPhpNamespace(directory.slice(dir.length), composerPsr4(text));
|
||||
if (!top || dir === top || !dir.startsWith(`${top}/`)) return "";
|
||||
dir = dirname(dir);
|
||||
}
|
||||
}
|
||||
|
||||
export async function packageFor(t: FileTemplate, directory: string): Promise<string> {
|
||||
const root = useProject.getState().project?.root ?? null;
|
||||
if (t.packageStyle === "jvm") return inferJvmPackage(directory, root, packageRoots());
|
||||
if (t.packageStyle === "go") return inferGoPackage(directory, root, await siblingGoPackage(directory));
|
||||
if (t.packageStyle === "php") return composerNamespace(directory, root);
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface FileTemplate {
|
||||
extension: string;
|
||||
nameStyle: NameStyle;
|
||||
/** Package inference: `jvm` (Java/Kotlin source roots) or `go` (directory). */
|
||||
packageStyle?: "jvm" | "go" | "php";
|
||||
packageStyle?: "jvm" | "go";
|
||||
/** Dotted names (`com.acme.Foo`) create package directories. */
|
||||
dottedPackages?: boolean;
|
||||
kinds: FileTemplateKind[];
|
||||
@@ -223,47 +223,6 @@ export function inferGoPackage(directory: string, projectRoot: string | null, si
|
||||
|
||||
export const GO_PACKAGE_RE = /^\s*package\s+([A-Za-z_]\w*)/m;
|
||||
|
||||
/** `autoload.psr-4` and `autoload-dev.psr-4` of a composer.json: `[namespace prefix, folder]` (folder relative to it). */
|
||||
export function composerPsr4(json: string): Array<[string, string]> {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(json);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: Array<[string, string]> = [];
|
||||
for (const section of ["autoload", "autoload-dev"]) {
|
||||
const map = (data as Record<string, { "psr-4"?: Record<string, unknown> } | undefined> | null)?.[section]?.[
|
||||
"psr-4"
|
||||
];
|
||||
if (!map || typeof map !== "object") continue;
|
||||
for (const [prefix, value] of Object.entries(map)) {
|
||||
for (const dir of Array.isArray(value) ? value : [value])
|
||||
if (typeof dir === "string")
|
||||
out.push([prefix, dir.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "")]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP namespace for `directory` (relative to the composer.json folder): the PSR-4 prefix of the
|
||||
* longest mapped folder that contains it, then the folders below it (`App\\` + `src/` → `src/Http`
|
||||
* gives `App\Http`). Outside every mapping: no namespace.
|
||||
*/
|
||||
export function inferPhpNamespace(directory: string, psr4: ReadonlyArray<readonly [string, string]>): string {
|
||||
const rel = directory.split("/").filter(Boolean);
|
||||
let best: { prefix: string; depth: number } | null = null;
|
||||
for (const [prefix, dir] of psr4) {
|
||||
const segs = dir.split("/").filter((s) => s && s !== ".");
|
||||
if (segs.length > rel.length || segs.some((s, i) => s !== rel[i])) continue;
|
||||
if (!best || segs.length > best.depth) best = { prefix, depth: segs.length };
|
||||
}
|
||||
if (!best) return "";
|
||||
const parts = [...best.prefix.split("\\").filter(Boolean), ...rel.slice(best.depth)];
|
||||
return parts.every((p) => /^[A-Za-z_\x80-\uffff][\w\x80-\uffff]*$/.test(p)) ? parts.join("\\") : "";
|
||||
}
|
||||
|
||||
export interface FileTemplateVars {
|
||||
name: string;
|
||||
fileName: string;
|
||||
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
toggledCheck,
|
||||
type ChangeNode,
|
||||
} from "./changes";
|
||||
import { applyStash, commitChanges, deleteFiles, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { applyStash, commitChanges, deleteUnversioned, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { CommitOptionsPopup } from "./CommitOptions";
|
||||
import { DEFAULT_LIST_NAME, useChangelists, withListDefaults } from "./changelists";
|
||||
import { moveToChangelist } from "./changelistsUi";
|
||||
@@ -226,16 +226,14 @@ export function listMenu(id: string, active: boolean, files: readonly FileStatus
|
||||
}
|
||||
|
||||
/** Paths Delete… applies to: only when every selected file is unversioned (versioned ones are rolled back). */
|
||||
/** The selected files that still exist in the working tree (Delete… removes them from disk). */
|
||||
export function deletableFiles(nodes: ChangeNode[]): string[] {
|
||||
export function deletableUnversioned(nodes: ChangeNode[]): string[] {
|
||||
const files = filesOf(nodes);
|
||||
const onDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged);
|
||||
return files.length && files.every(onDisk) ? files.map((f) => f.path) : [];
|
||||
return files.length && files.every((f) => f.unstaged === "untracked") ? files.map((f) => f.path) : [];
|
||||
}
|
||||
|
||||
export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuItem[] {
|
||||
const files = filesOf(nodes);
|
||||
const deletable = deletableFiles(nodes);
|
||||
const deletable = deletableUnversioned(nodes);
|
||||
const paths = files.map((f) => f.path);
|
||||
const first = nodes.find((n) => n.type === "file");
|
||||
const untracked = files.filter((f) => f.unstaged === "untracked");
|
||||
@@ -256,16 +254,18 @@ export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuIte
|
||||
items.push(
|
||||
{ kind: "action", action: "vcs.rollback", arg: paths, label: "Rollback…" },
|
||||
...(untracked.length
|
||||
? [{ kind: "action" as const, action: "vcs.addToVcs", arg: untracked.map((f) => f.path) }]
|
||||
: []),
|
||||
...(deletable.length
|
||||
? [
|
||||
{
|
||||
label: "Delete…",
|
||||
icon: "trash",
|
||||
shortcut: formatBinding(isMacHost() ? "Backspace" : "Delete"),
|
||||
run: () => void deleteFiles(deletable),
|
||||
},
|
||||
{ kind: "action" as const, action: "vcs.addToVcs", arg: untracked.map((f) => f.path) },
|
||||
...(deletable.length
|
||||
? [
|
||||
{
|
||||
label: "Delete…",
|
||||
icon: "trash",
|
||||
shortcut: formatBinding(isMacHost() ? "Backspace" : "Delete"),
|
||||
run: () => void deleteUnversioned(deletable),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]
|
||||
: []),
|
||||
...(toIgnore.length
|
||||
@@ -534,7 +534,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
} else if ((e.key === "Delete" || e.key === "Backspace") && !e.metaKey) {
|
||||
const nodes = selectedNodes();
|
||||
const group = nodes.find((x) => x.type === "group" && x.changelist);
|
||||
const deletable = group ? [] : deletableFiles(nodes);
|
||||
const deletable = group ? [] : deletableUnversioned(nodes);
|
||||
if (group?.changelist) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -542,7 +542,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
} else if (deletable.length) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void deleteFiles(deletable);
|
||||
void deleteUnversioned(deletable);
|
||||
}
|
||||
} else if (e.key === "F4") {
|
||||
const n = selectedNodes().find((x) => x.type === "file");
|
||||
|
||||
+16
-16
@@ -13,11 +13,11 @@ vi.mock("../dialogs", async (original) => ({
|
||||
confirmDialog: mocks.confirm,
|
||||
}));
|
||||
|
||||
const { deletableFiles, nodeMenu } = await import("../CommitView");
|
||||
const { deleteFiles } = await import("../changeOps");
|
||||
const { deletableUnversioned, nodeMenu } = await import("../CommitView");
|
||||
const { deleteUnversioned } = await import("../changeOps");
|
||||
|
||||
const file = (rel: string, unstaged: FileStatus["unstaged"], staged: FileStatus["staged"] = null): ChangeNode => {
|
||||
const f: FileStatus = { path: `/p/${rel}`, relPath: rel, staged, unstaged, renamedFrom: null };
|
||||
const file = (rel: string, unstaged: FileStatus["unstaged"]): ChangeNode => {
|
||||
const f: FileStatus = { path: `/p/${rel}`, relPath: rel, staged: null, unstaged, renamedFrom: null };
|
||||
return { key: f.path, type: "file", label: rel, group: "unversioned", files: [f], path: f.path };
|
||||
};
|
||||
const deleteItem = (menu: MenuItem[]) =>
|
||||
@@ -29,30 +29,30 @@ beforeEach(() => {
|
||||
mocks.call.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
describe("Delete… in the Changes view", () => {
|
||||
it("is offered when every selected file is still on disk", () => {
|
||||
describe("Delete… for unversioned files", () => {
|
||||
it("is offered only when every selected file is unversioned", () => {
|
||||
expect(deleteItem(nodeMenu([file("a.txt", "untracked"), file("b.txt", "untracked")], ["/p"]))).toBeDefined();
|
||||
expect(deleteItem(nodeMenu([file("a.txt", "untracked"), file("c.txt", "modified")], ["/p"]))).toBeDefined();
|
||||
expect(deleteItem(nodeMenu([file("c.txt", "modified")], ["/p"]))).toBeDefined();
|
||||
expect(deleteItem(nodeMenu([file("d.txt", null, "added")], ["/p"]))).toBeDefined();
|
||||
expect(deleteItem(nodeMenu([file("c.txt", "modified"), file("e.txt", "deleted")], ["/p"]))).toBeUndefined();
|
||||
expect(deleteItem(nodeMenu([file("f.txt", null, "deleted")], ["/p"]))).toBeUndefined();
|
||||
expect(deleteItem(nodeMenu([file("a.txt", "untracked"), file("c.txt", "modified")], ["/p"]))).toBeUndefined();
|
||||
expect(deleteItem(nodeMenu([file("c.txt", "modified")], ["/p"]))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("shows the Delete key and gives the key handler the same paths", () => {
|
||||
expect(deleteItem(nodeMenu([file("a.txt", "untracked")], ["/p"]))).toMatchObject({ shortcut: "⌫" });
|
||||
expect(deletableFiles([file("a.txt", "untracked"), file("c.txt", "modified")])).toEqual(["/p/a.txt", "/p/c.txt"]);
|
||||
expect(deletableFiles([file("a.txt", "untracked"), file("e.txt", "deleted")])).toEqual([]);
|
||||
expect(deletableFiles([])).toEqual([]);
|
||||
expect(deletableUnversioned([file("a.txt", "untracked"), file("b.txt", "untracked")])).toEqual([
|
||||
"/p/a.txt",
|
||||
"/p/b.txt",
|
||||
]);
|
||||
expect(deletableUnversioned([file("a.txt", "untracked"), file("c.txt", "modified")])).toEqual([]);
|
||||
expect(deletableUnversioned([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("asks first, then deletes each file", async () => {
|
||||
mocks.confirm.mockResolvedValueOnce(false);
|
||||
await deleteFiles(["/p/a.txt"]);
|
||||
await deleteUnversioned(["/p/a.txt"]);
|
||||
expect(mocks.fsDelete).not.toHaveBeenCalled();
|
||||
|
||||
mocks.confirm.mockResolvedValueOnce(true);
|
||||
await deleteFiles(["/p/a.txt", "/p/b.txt"]);
|
||||
await deleteUnversioned(["/p/a.txt", "/p/b.txt"]);
|
||||
expect(mocks.fsDelete.mock.calls.map((c) => c[0])).toEqual(["/p/a.txt", "/p/b.txt"]);
|
||||
});
|
||||
});
|
||||
@@ -153,8 +153,7 @@ async function partialCommitFiles(paths: readonly string[]): Promise<{ files: Pa
|
||||
}
|
||||
|
||||
/** Delete… on unversioned files in the Changes view, as in IDEA: they move to the Trash. */
|
||||
/** Delete… in the Changes view: moves the files to the Trash (a tracked file then shows as deleted). */
|
||||
export async function deleteFiles(paths: readonly string[]) {
|
||||
export async function deleteUnversioned(paths: readonly string[]) {
|
||||
if (!paths.length) return;
|
||||
const question = paths.length === 1 ? tx`Delete '${baseName(paths[0]!)}'?` : tx`Delete ${paths.length} items?`;
|
||||
const ok = await confirmDialog({
|
||||
|
||||
@@ -152,7 +152,6 @@ export const EDITOR_EXTRA_DEFAULTS = {
|
||||
tabOutOfPair: true,
|
||||
reformatOnPaste: "indentEachLine",
|
||||
smartIndent: true,
|
||||
insertDocStub: true,
|
||||
backspaceUnindent: "autoindent",
|
||||
},
|
||||
codeEditing: {
|
||||
|
||||
@@ -50,7 +50,6 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"code.expandToLevel5": [],
|
||||
"refactor.extractMethod": ["Meta+Alt+M"],
|
||||
"navigate.fileStructure": ["Meta+O"],
|
||||
"db.goToColumn": ["Meta+O"],
|
||||
"find.inFile": [],
|
||||
"find.inPath": ["Ctrl+H"],
|
||||
"find.next": ["Meta+K"],
|
||||
|
||||
@@ -52,7 +52,6 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"code.expandToLevel5": [],
|
||||
"refactor.extractMethod": ["Shift+Alt+M"],
|
||||
"navigate.fileStructure": ["Ctrl+F3", "Ctrl+O"],
|
||||
"db.goToColumn": ["Ctrl+F3", "Ctrl+O"],
|
||||
"find.inFile": [],
|
||||
"find.inPath": ["Ctrl+H"],
|
||||
"find.next": ["Ctrl+K"],
|
||||
|
||||
@@ -41,7 +41,6 @@ const shared = [
|
||||
"find.popup.openResult",
|
||||
],
|
||||
["navigate.typeHierarchy", "db.editData"],
|
||||
["navigate.fileStructure", "db.goToColumn"],
|
||||
["find.replaceInFile", "agents.findInConversation", "vcs.log.goToRef"],
|
||||
["find.next", "find.popup.nextResult"],
|
||||
["find.previous", "find.popup.previousResult"],
|
||||
|
||||
@@ -353,7 +353,6 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"http.runAll": [],
|
||||
"db.execute": ["Meta+Enter"],
|
||||
// Table editor with pending changes (after `vcs.rollback`, so ⌥⌘Z reverts the table's edits there).
|
||||
"db.goToColumn": ["Meta+F12"],
|
||||
"db.submitChanges": ["Meta+Enter"],
|
||||
"db.revertChanges": ["Meta+Alt+Z"],
|
||||
"db.showToolWindow": [],
|
||||
|
||||
@@ -351,7 +351,6 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"http.runAll": [],
|
||||
"db.execute": ["Ctrl+Enter"],
|
||||
// Table editor with pending changes (after `vcs.rollback`, so Ctrl+Alt+Z reverts the table's edits there).
|
||||
"db.goToColumn": ["Ctrl+F12"],
|
||||
"db.submitChanges": ["Ctrl+Enter"],
|
||||
"db.revertChanges": ["Ctrl+Alt+Z"],
|
||||
"db.showToolWindow": [],
|
||||
|
||||
@@ -22,9 +22,6 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"navigate.implementation": ["Meta+F12"],
|
||||
"navigate.typeDeclaration": [],
|
||||
"navigate.fileStructure": ["Meta+Shift+O"],
|
||||
"db.goToColumn": ["Meta+Shift+O"],
|
||||
"db.submitChanges": ["Meta+Enter"],
|
||||
"db.revertChanges": ["Meta+Alt+Z"],
|
||||
"navigate.relatedSymbol": [],
|
||||
"navigate.nextError": ["F8"],
|
||||
"navigate.prevError": ["Shift+F8"],
|
||||
|
||||
@@ -3810,7 +3810,7 @@
|
||||
"JDK Location": "Ubicación del JDK",
|
||||
"Downloading JDK": "Descargando JDK",
|
||||
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "Use ; para separar patrones de nombres, * para cualquier cantidad de símbolos, ? para uno.",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "Las carpetas se detectan a partir de archivos de compilación (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marcar o desmarcar una carpeta anula la detección. Las carpetas excluidas se omiten en la vista Proyecto, Buscar en archivos y el índice (vuelva a abrir el proyecto para reindexar).",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "Las carpetas se detectan a partir de archivos de compilación (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marcar o desmarcar una carpeta anula la detección. Las carpetas excluidas se omiten en la vista Proyecto, Buscar en archivos y el índice (vuelva a abrir el proyecto para reindexar).",
|
||||
"Project virtualenv (auto-detect)": "Virtualenv del proyecto (detección automática)",
|
||||
"<No interpreter>": "<Sin intérprete>",
|
||||
"Package name or requirement, e.g. requests or django==5.1": "Nombre del paquete o requisito, p. ej., requests o django==5.1",
|
||||
|
||||
@@ -3676,7 +3676,7 @@
|
||||
"JDK Location": "Emplacement du JDK",
|
||||
"Downloading JDK": "Téléchargement du JDK",
|
||||
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "Utilisez ; pour séparer les motifs de noms, * pour un nombre quelconque de caractères, ? pour un seul.",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "Les dossiers sont détectés depuis les fichiers de build (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json) ; marquer ou démarquer un dossier remplace la détection. Les dossiers exclus sont ignorés par la vue Projet, Rechercher dans les fichiers et l'index (rouvrez le projet pour réindexer).",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "Les dossiers sont détectés depuis les fichiers de build (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json) ; marquer ou démarquer un dossier remplace la détection. Les dossiers exclus sont ignorés par la vue Projet, Rechercher dans les fichiers et l'index (rouvrez le projet pour réindexer).",
|
||||
"Project virtualenv (auto-detect)": "Virtualenv du projet (détection automatique)",
|
||||
"<No interpreter>": "<Aucun interpréteur>",
|
||||
"Package name or requirement, e.g. requests or django==5.1": "Nom de paquet ou contrainte, p. ex. requests ou django==5.1",
|
||||
|
||||
@@ -3789,7 +3789,7 @@
|
||||
"JDK Location": "JDK 위치",
|
||||
"Downloading JDK": "JDK 다운로드 중",
|
||||
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "이름 패턴은 ;로 구분하고, *는 임의 개수의 문자, ?는 한 문자와 일치합니다.",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "폴더는 빌드 파일(pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json)에서 감지되며, 폴더를 표시하거나 표시 해제하면 감지 결과가 재정의됩니다. 제외된 폴더는 프로젝트 뷰, 파일에서 찾기 및 인덱스에서 건너뜁니다(다시 인덱싱하려면 프로젝트를 다시 여세요).",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "폴더는 빌드 파일(pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json)에서 감지되며, 폴더를 표시하거나 표시 해제하면 감지 결과가 재정의됩니다. 제외된 폴더는 프로젝트 뷰, 파일에서 찾기 및 인덱스에서 건너뜁니다(다시 인덱싱하려면 프로젝트를 다시 여세요).",
|
||||
"Project virtualenv (auto-detect)": "프로젝트 virtualenv(자동 감지)",
|
||||
"<No interpreter>": "<인터프리터 없음>",
|
||||
"Package name or requirement, e.g. requests or django==5.1": "패키지 이름 또는 요구 사항, 예: requests 또는 django==5.1",
|
||||
|
||||
@@ -3779,7 +3779,7 @@
|
||||
"JDK Location": "Lokalizacja JDK",
|
||||
"Downloading JDK": "Pobieranie JDK",
|
||||
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "Użyj ; do rozdzielania wzorców nazw, * dla dowolnej liczby znaków, ? dla jednego znaku.",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "Foldery są wykrywane z plików budowania (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); ręczne zaznaczenie lub odznaczenie foldera zastępuje automatyczne wykrywanie. Wykluczone foldery są pomijane w widoku Projektu, wyszukiwaniu w plikach oraz przez indeks (otwórz projekt ponownie, aby reindeksować).",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "Foldery są wykrywane z plików budowania (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); ręczne zaznaczenie lub odznaczenie foldera zastępuje automatyczne wykrywanie. Wykluczone foldery są pomijane w widoku Projektu, wyszukiwaniu w plikach oraz przez indeks (otwórz projekt ponownie, aby reindeksować).",
|
||||
"Project virtualenv (auto-detect)": "Środowisko wirtualne projektu (automatyczne wykrywanie)",
|
||||
"<No interpreter>": "<No interpreter>",
|
||||
"Download JDK…": "Pobierz JDK…",
|
||||
|
||||
@@ -3782,7 +3782,7 @@
|
||||
"JDK Location": "Local do JDK",
|
||||
"Downloading JDK": "Baixando JDK",
|
||||
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "Use ; para separar padrões de nomes, * para qualquer quantidade de caracteres, ? para um.",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "As pastas são detectadas a partir de arquivos de build (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marcar ou desmarcar uma pasta substitui a detecção. Pastas excluídas são ignoradas pela visualização do Projeto, Localizar em arquivos e pelo índice (reabra o projeto para reindexar).",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "As pastas são detectadas a partir de arquivos de build (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marcar ou desmarcar uma pasta substitui a detecção. Pastas excluídas são ignoradas pela visualização do Projeto, Localizar em arquivos e pelo índice (reabra o projeto para reindexar).",
|
||||
"Project virtualenv (auto-detect)": "Virtualenv do projeto (detecção automática)",
|
||||
"<No interpreter>": "<Nenhum interpretador>",
|
||||
"Package name or requirement, e.g. requests or django==5.1": "Nome do pacote ou requisito, p. ex. requests ou django==5.1",
|
||||
|
||||
@@ -1153,7 +1153,6 @@
|
||||
"Issue navigation links": "问题导航链接",
|
||||
"Italic": "斜体",
|
||||
"JUnit 5 Test": "JUnit 5 测试",
|
||||
"PHPUnit Test": "PHPUnit 测试",
|
||||
"JUnit test": "JUnit 测试",
|
||||
"JVM options": "JVM 选项",
|
||||
"Jump outside closing bracket/quote with Tab": "使用 Tab 跳出右括号/引号",
|
||||
@@ -1936,7 +1935,6 @@
|
||||
"Run a configuration with coverage to see which lines its tests execute.": "使用覆盖率运行配置,即可查看其测试执行了哪些行。",
|
||||
"Run a request from an .http file with the gutter ▶ or ⌘↩.": "使用装订区域中的 ▶ 或 ⌘↩ 运行 .http 文件中的请求。",
|
||||
"Run actions": "运行操作",
|
||||
"Console actions": "控制台操作",
|
||||
"Run and Debug": "运行和调试",
|
||||
"Run code cleanup": "运行代码清理",
|
||||
"Run configurations": "运行配置",
|
||||
@@ -2176,7 +2174,6 @@
|
||||
"Smart Step Into": "智能步入",
|
||||
"Smart Step Into failed": "智能步入失败",
|
||||
"Smart indent": "智能缩进",
|
||||
"Insert documentation comment stub": "插入文档注释存根",
|
||||
"Soft": "软",
|
||||
"Soft Wraps": "软换行",
|
||||
"Soft-Wrap": "软换行",
|
||||
@@ -3335,7 +3332,6 @@
|
||||
"Rust File › Test module": "Rust 文件 › 测试模块",
|
||||
"TypeScript File › Test": "TypeScript 文件 › 测试",
|
||||
"Python File › Test (pytest)": "Python 文件 › 测试 (pytest)",
|
||||
"PHP Class › PHPUnit Test": "PHP 类 › PHPUnit 测试",
|
||||
"CSS File": "CSS 文件",
|
||||
"SCSS File": "SCSS 文件",
|
||||
"Sass File": "Sass 文件",
|
||||
@@ -3748,10 +3744,6 @@
|
||||
"Clear local filter": "清除本地筛选",
|
||||
"Search values": "搜索值",
|
||||
"No matching values": "没有匹配的值",
|
||||
"Go to Column": "转到列",
|
||||
"Columns of {table}": "{table} 的列",
|
||||
"Search columns": "搜索列",
|
||||
"No matching columns": "没有匹配的列",
|
||||
"Clear Filter": "清除筛选",
|
||||
"Clear Local Filter For All Columns": "清除所有列的本地筛选",
|
||||
"Value panel": "值面板",
|
||||
@@ -3875,7 +3867,7 @@
|
||||
"JDK Location": "JDK 位置",
|
||||
"Downloading JDK": "正在下载 JDK",
|
||||
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "使用 ; 分隔名称模式,* 匹配任意数量的字符,? 匹配单个字符。",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "文件夹根据构建文件(pom.xml、build.gradle、Cargo.toml、go.mod、pyproject.toml、package.json、composer.json)检测;标记或取消标记文件夹会覆盖检测结果。项目视图、在文件中查找和索引会跳过已排除的文件夹(重新打开项目以重新索引)。",
|
||||
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "文件夹根据构建文件(pom.xml、build.gradle、Cargo.toml、go.mod、pyproject.toml、package.json)检测;标记或取消标记文件夹会覆盖检测结果。项目视图、在文件中查找和索引会跳过已排除的文件夹(重新打开项目以重新索引)。",
|
||||
"Project virtualenv (auto-detect)": "项目 virtualenv(自动检测)",
|
||||
"<No interpreter>": "<无解释器>",
|
||||
"Package name or requirement, e.g. requests or django==5.1": "软件包名称或需求,例如 requests 或 django==5.1",
|
||||
|
||||
Reference in new issue
Заблокувати користувача