дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
67b5b2def7 | ||
|
|
07df51f308 | ||
|
|
38ff63658e | ||
|
|
7dbce43c88 | ||
|
|
f68d8f499a |
No files matched your search
@@ -252,6 +252,8 @@ 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,
|
||||
}
|
||||
@@ -267,6 +269,7 @@ 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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,12 @@ 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,6 +954,11 @@ 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();
|
||||
@@ -962,7 +967,10 @@ 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 is not surfaced");
|
||||
assert_eq!(
|
||||
notifies, 2,
|
||||
"showMessageRequest error + showMessage warning; info and rust-analyzer's developer notices are not surfaced"
|
||||
);
|
||||
|
||||
// Dynamically registered capability is now usable.
|
||||
s.respond(
|
||||
|
||||
@@ -6870,6 +6870,8 @@ 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,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* 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,6 +48,7 @@ import {
|
||||
selectHumpRight,
|
||||
} from "./editing";
|
||||
import { enterInLineComment, lineCommentStyle, type LineCommentStyle } from "./comments";
|
||||
import { enterInDocComment } from "./docComment";
|
||||
import { skipClosingQuote, smartBackspace, smartBackspaceApplies, tabOut } from "./smartKeys";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
@@ -571,6 +572,7 @@ 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 });
|
||||
|
||||
@@ -365,111 +365,120 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
|
||||
};
|
||||
|
||||
return (
|
||||
<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 className={styles.consoleArea}>
|
||||
<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}
|
||||
className={styles.consoleToolbar}
|
||||
role="toolbar"
|
||||
aria-orientation="vertical"
|
||||
aria-label={tx("Console actions")}
|
||||
>
|
||||
{!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="search"
|
||||
iconSize={14}
|
||||
title="Find…"
|
||||
shortcut={formatBinding(hostBinding("Meta+F"))}
|
||||
pressed={findOpen}
|
||||
onClick={() => (findOpen ? closeFind() : openFind())}
|
||||
/>
|
||||
<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"
|
||||
title="Clear Console"
|
||||
size="small"
|
||||
iconSize={12}
|
||||
onClick={() => clearConsole(session.id)}
|
||||
/>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -218,6 +218,23 @@
|
||||
}
|
||||
|
||||
/* 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;
|
||||
|
||||
@@ -677,7 +677,10 @@ const SMART_KEYS = editorPage({
|
||||
},
|
||||
{
|
||||
title: "Enter",
|
||||
items: [{ t: "check", key: `${P}.smartKeys.smartIndent`, label: "Smart indent" }],
|
||||
items: [
|
||||
{ t: "check", key: `${P}.smartKeys.smartIndent`, label: "Smart indent" },
|
||||
{ t: "check", key: `${P}.smartKeys.insertDocStub`, label: "Insert documentation comment stub" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Backspace",
|
||||
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
toggledCheck,
|
||||
type ChangeNode,
|
||||
} from "./changes";
|
||||
import { applyStash, commitChanges, deleteUnversioned, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { applyStash, commitChanges, deleteFiles, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { CommitOptionsPopup } from "./CommitOptions";
|
||||
import { DEFAULT_LIST_NAME, useChangelists, withListDefaults } from "./changelists";
|
||||
import { moveToChangelist } from "./changelistsUi";
|
||||
@@ -226,14 +226,16 @@ 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). */
|
||||
export function deletableUnversioned(nodes: ChangeNode[]): string[] {
|
||||
/** The selected files that still exist in the working tree (Delete… removes them from disk). */
|
||||
export function deletableFiles(nodes: ChangeNode[]): string[] {
|
||||
const files = filesOf(nodes);
|
||||
return files.length && files.every((f) => f.unstaged === "untracked") ? files.map((f) => f.path) : [];
|
||||
const onDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged);
|
||||
return files.length && files.every(onDisk) ? files.map((f) => f.path) : [];
|
||||
}
|
||||
|
||||
export function nodeMenu(nodes: ChangeNode[], repos: readonly string[]): MenuItem[] {
|
||||
const files = filesOf(nodes);
|
||||
const deletable = deletableUnversioned(nodes);
|
||||
const deletable = deletableFiles(nodes);
|
||||
const paths = files.map((f) => f.path);
|
||||
const first = nodes.find((n) => n.type === "file");
|
||||
const untracked = files.filter((f) => f.unstaged === "untracked");
|
||||
@@ -254,18 +256,16 @@ 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
|
||||
? [
|
||||
{ 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),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Delete…",
|
||||
icon: "trash",
|
||||
shortcut: formatBinding(isMacHost() ? "Backspace" : "Delete"),
|
||||
run: () => void deleteFiles(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 ? [] : deletableUnversioned(nodes);
|
||||
const deletable = group ? [] : deletableFiles(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 deleteUnversioned(deletable);
|
||||
void deleteFiles(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 { deletableUnversioned, nodeMenu } = await import("../CommitView");
|
||||
const { deleteUnversioned } = await import("../changeOps");
|
||||
const { deletableFiles, nodeMenu } = await import("../CommitView");
|
||||
const { deleteFiles } = await import("../changeOps");
|
||||
|
||||
const file = (rel: string, unstaged: FileStatus["unstaged"]): ChangeNode => {
|
||||
const f: FileStatus = { path: `/p/${rel}`, relPath: rel, staged: null, unstaged, renamedFrom: null };
|
||||
const file = (rel: string, unstaged: FileStatus["unstaged"], staged: FileStatus["staged"] = null): ChangeNode => {
|
||||
const f: FileStatus = { path: `/p/${rel}`, relPath: rel, staged, 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… for unversioned files", () => {
|
||||
it("is offered only when every selected file is unversioned", () => {
|
||||
describe("Delete… in the Changes view", () => {
|
||||
it("is offered when every selected file is still on disk", () => {
|
||||
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"]))).toBeUndefined();
|
||||
expect(deleteItem(nodeMenu([file("c.txt", "modified")], ["/p"]))).toBeUndefined();
|
||||
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();
|
||||
});
|
||||
|
||||
it("shows the Delete key and gives the key handler the same paths", () => {
|
||||
expect(deleteItem(nodeMenu([file("a.txt", "untracked")], ["/p"]))).toMatchObject({ shortcut: "⌫" });
|
||||
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([]);
|
||||
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([]);
|
||||
});
|
||||
|
||||
it("asks first, then deletes each file", async () => {
|
||||
mocks.confirm.mockResolvedValueOnce(false);
|
||||
await deleteUnversioned(["/p/a.txt"]);
|
||||
await deleteFiles(["/p/a.txt"]);
|
||||
expect(mocks.fsDelete).not.toHaveBeenCalled();
|
||||
|
||||
mocks.confirm.mockResolvedValueOnce(true);
|
||||
await deleteUnversioned(["/p/a.txt", "/p/b.txt"]);
|
||||
await deleteFiles(["/p/a.txt", "/p/b.txt"]);
|
||||
expect(mocks.fsDelete.mock.calls.map((c) => c[0])).toEqual(["/p/a.txt", "/p/b.txt"]);
|
||||
});
|
||||
});
|
||||
@@ -153,7 +153,8 @@ 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. */
|
||||
export async function deleteUnversioned(paths: readonly string[]) {
|
||||
/** 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[]) {
|
||||
if (!paths.length) return;
|
||||
const question = paths.length === 1 ? tx`Delete '${baseName(paths[0]!)}'?` : tx`Delete ${paths.length} items?`;
|
||||
const ok = await confirmDialog({
|
||||
|
||||
@@ -152,6 +152,7 @@ export const EDITOR_EXTRA_DEFAULTS = {
|
||||
tabOutOfPair: true,
|
||||
reformatOnPaste: "indentEachLine",
|
||||
smartIndent: true,
|
||||
insertDocStub: true,
|
||||
backspaceUnindent: "autoindent",
|
||||
},
|
||||
codeEditing: {
|
||||
|
||||
@@ -1935,6 +1935,7 @@
|
||||
"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": "运行配置",
|
||||
@@ -2174,6 +2175,7 @@
|
||||
"Smart Step Into": "智能步入",
|
||||
"Smart Step Into failed": "智能步入失败",
|
||||
"Smart indent": "智能缩进",
|
||||
"Insert documentation comment stub": "插入文档注释存根",
|
||||
"Soft": "软",
|
||||
"Soft Wraps": "软换行",
|
||||
"Soft-Wrap": "软换行",
|
||||
|
||||
Reference in new issue
Заблокувати користувача