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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 7540ef29b7 fix(vcs): no Commit File… in the changes tree with the staging area
With the staging area the commit takes the whole index, so Commit File… on a
staged file only focused the message and committed every staged file. The
item is left out of the changes tree's menu while the staging area is on, as
the staging tree has no per-file commit.

Fixes #4153
2026-11-18 18:39:44 +08:00
41 змінених файлів з 95 додано та 830 видалено

No files matched your search

+1 -19
Переглянути файл
@@ -536,9 +536,7 @@ impl PathMap {
let abs = if p.is_absolute() {
p.to_path_buf()
} else {
// rustc prints workspace members' files relative to the workspace root, above
// the member's manifest directory (`base`) when a member is built on its own.
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
in_base.unwrap_or_else(|| cwd.join(p))
};
let abs = normalize(&abs);
@@ -1305,22 +1303,6 @@ mod tests {
assert_eq!(identifier_len("x é_1 c", 2), 3);
}
#[test]
fn resolves_a_member_build_s_workspace_relative_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
write(&root, "client/src/main.rs", "fn main() {}\n");
write(&root, "client/src/lib.rs", "\n");
write(&root, "src/lib.rs", "\n");
let map = PathMap { root: root.clone(), canonical: None };
let member = root.join("client");
let base = member.to_str();
// Build Module runs in the member; rustc names its files from the workspace root.
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
// A crate built from its own directory names them from there.
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
}
// Uses Unix absolute paths for the canonical root.
#[cfg(unix)]
#[test]
-45
Переглянути файл
@@ -65,28 +65,6 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
parsed
}
/// rust-analyzer publishes its own analysis next to `cargo check`'s (flycheck): one type
/// mismatch then arrives as `rust-analyzer(E0308)` and `rustc(E0308)`. Its own entry is
/// dropped when the compiler reports the same code and severity over an overlapping range.
fn drop_compiler_duplicates(diagnostics: &mut Vec<lsp::Diagnostic>) {
let overlaps = |a: &lsp::Range, b: &lsp::Range| a.start <= b.end && b.start <= a.end;
let compiler: Vec<(lsp::Range, Option<lsp::NumberOrString>, Option<lsp::DiagnosticSeverity>)> = diagnostics
.iter()
.filter(|d| d.source.as_deref() == Some("rustc") && d.code.is_some())
.map(|d| (d.range, d.code.clone(), d.severity))
.collect();
if compiler.is_empty() {
return;
}
diagnostics.retain(|d| {
d.source.as_deref() != Some("rust-analyzer")
|| d.code.is_none()
|| !compiler
.iter()
.any(|(range, code, severity)| code == &d.code && severity == &d.severity && overlaps(range, &d.range))
});
}
impl ClientHandler {
pub fn new(mgr: Weak<LspManager>, server: Arc<Server>, generation: u64) -> Self {
Self { mgr, server, generation }
@@ -315,7 +293,6 @@ impl ClientHandler {
}
};
params.diagnostics = lenient_diagnostics(&self.server.name, raw.unwrap_or(Value::Null));
drop_compiler_duplicates(&mut params.diagnostics);
let Some(path) = uri_to_path(params.uri.as_str())
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
else {
@@ -724,28 +701,6 @@ mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
#[test]
fn rust_analyzer_s_own_entry_yields_to_the_compiler_s_for_the_same_error() {
let diagnostic = |source: &str, code: &str, line: u32, severity| lsp::Diagnostic {
range: lsp::Range::new(lsp::Position::new(line, 21), lsp::Position::new(line, 27)),
severity: Some(severity),
code: Some(lsp::NumberOrString::String(code.into())),
source: Some(source.into()),
message: format!("{source} {code}"),
..Default::default()
};
let error = lsp::DiagnosticSeverity::ERROR;
let mut items = vec![
diagnostic("rust-analyzer", "E0308", 1, error),
diagnostic("rustc", "E0308", 1, error),
diagnostic("rust-analyzer", "E0308", 5, error),
diagnostic("rust-analyzer", "unused_variables", 1, lsp::DiagnosticSeverity::WARNING),
];
drop_compiler_duplicates(&mut items);
let left: Vec<_> = items.iter().map(|d| (d.message.as_str(), d.range.start.line)).collect();
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
}
#[test]
fn tsserver_aborts_are_out_of_memory() {
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
+2 -31
Переглянути файл
@@ -121,14 +121,7 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
if bytes.iter().take(8192).any(|b| *b == 0) {
return None;
}
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
}
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
/// record the document's text, so a file read from disk must match it to dedupe, and
/// Revert writes it back through the document, which adds the file's BOM and line endings.
fn document_text(text: &str) -> std::borrow::Cow<'_, str> {
ide_text::normalize_line_endings(text.strip_prefix('\u{feff}').unwrap_or(text))
String::from_utf8(bytes).ok()
}
impl LocalHistory {
@@ -345,10 +338,7 @@ impl LocalHistory {
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
}
match fs::read(self.blob_path(id)) {
Ok(bytes) => {
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
Ok(document_text(&text).into_owned())
}
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Err(IdeError::not_found(format!("history snapshot {id} not found")))
}
@@ -542,25 +532,6 @@ mod tests {
}
}
#[test]
fn a_file_read_from_disk_matches_the_saved_document_text() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
fs::create_dir_all(&root).unwrap();
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let a = root.join("a.txt");
// A save records the document's text; the file on disk has a BOM and CRLF.
fs::write(&a, b"\xEF\xBB\xBFheader\r\nbody\r\n").unwrap();
h.record(&a, "header\nbody\n", "Saved").unwrap();
assert!(h.record_file(&a, "External change", false).unwrap());
let list = h.list(&a).unwrap();
assert_eq!(list.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Saved"], "no second revision");
// A snapshot stored with its BOM before reads back as document text.
h.record(&a, "\u{feff}old\r\n", "External change").unwrap();
let old = &h.list(&a).unwrap()[0];
assert_eq!(h.content(&old.id).unwrap(), "old\n");
}
#[test]
fn events_labels_and_deletions() {
let tmp = tempfile::tempdir().unwrap();
+1 -16
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
import { t } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { confirm } from "@/workbench/messages";
@@ -166,18 +166,3 @@ describe("editor kinds' isBusy on tab-limit eviction", () => {
}
});
});
describe("Close non-modified files first", () => {
it("keeps a tab with a VCS change, as Close Unmodified Tabs does", async () => {
controller = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));
controller.start();
useProject.setState({ settings: { editor: { tabs: { tabLimit: 2, closingPolicy: "unchanged" } } } as never });
setFileDecorations("vcs", new Map([["/p/a.ts", { color: "modified" }]]));
try {
for (const path of ["/p/a.ts", "/p/b.ts", "/p/c.ts"]) await controller.openFile(path);
expect(pane().tabs.map((tab) => tab.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
} finally {
setFileDecorations("vcs", new Map());
}
});
});
+9 -14
Переглянути файл
@@ -272,14 +272,6 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
}
}
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
function tabModified(tab: Tab): boolean {
return (
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color))
);
}
export class EditorController implements SlotHost {
manager: DocumentManager;
readonly slots = new Map<string, EditorSlot>();
@@ -395,11 +387,10 @@ export class EditorController implements SlotHost {
// Untitled buffers belong to the window, not a project: their tabs
// survive the switch (the backend carries them into the new
// registry) and their slots rebuild against the carried documents.
// Closing to Welcome drops them; the leave guard already asked about them.
const carriedUntitled: Tab[] = [];
let carriedActive: string | null = null;
const cs = useTabs.getState();
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
for (const pane of Object.values(cs.panes)) {
for (const tab of pane.tabs) {
if (isUntitledUri(tab.input.path ?? "")) {
carriedUntitled.push(tab);
@@ -1449,7 +1440,8 @@ export class EditorController implements SlotHost {
paneId,
prefs.tabLimit,
prefs.closingPolicy,
tabModified,
(tab) =>
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
keep ?? current.panes[paneId]?.active ?? undefined,
protect,
)
@@ -1733,10 +1725,13 @@ export class EditorController implements SlotHost {
protect: (tab) => tab.pinned,
});
}
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
closeUnmodified(paneId: string): Promise<boolean> {
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
protect: (tab) => tab.pinned || tabModified(tab),
const modified = (tab: Tab) =>
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color));
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, modified) : s), {
protect: (tab) => tab.pinned || modified(tab),
});
}
closeReadOnly(paneId: string): Promise<boolean> {
-14
Переглянути файл
@@ -15,7 +15,6 @@ const { serializeSession } = await import("./model/session");
const { useDocMeta } = await import("./model/document");
const { save } = await import("@/platform/dialog");
const editorKinds = await import("@/workbench/contributions");
const { useProject } = await import("@/platform/project");
let ctrl: InstanceType<typeof EditorController> | null = null;
let backend: MemoryBackend;
@@ -159,19 +158,6 @@ describe("untitled editor input", () => {
expect([...backend.files.keys()]).toEqual(["/p/main.rs"]);
});
it("follows the window into another project but not to the Welcome screen", async () => {
const project = (root: string) => ({ root, name: root, trusted: true, isGit: false, settings: {} }) as never;
try {
await ctrl!.openUntitled({ focus: false });
useProject.setState({ project: project("/a") });
expect(activeTab().input.kind).toBe("untitled");
useProject.setState({ project: null });
expect(Object.values(useTabs.getState().panes).flatMap((p) => p.tabs)).toEqual([]);
} finally {
useProject.setState({ project: null });
}
});
it("reuses the buffer for a re-opened untitled name and shares it across tabs", async () => {
const info = await backend.openUntitled(null);
const twice = await backend.openUntitled("untitled:Untitled-1");
-14
Переглянути файл
@@ -36,20 +36,6 @@ describe("Go to Test / Test Subject", () => {
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/FooTest.java");
});
it("uses the top-level class at the caret when a file declares several", async () => {
const files = [
"/p/src/main/java/a/Widget.java",
"/p/src/test/java/a/WidgetTest.java",
"/p/src/test/java/a/HelperTest.java",
];
const d = { ...deps(files), classAtCaret: async () => "Helper" };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", d);
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/HelperTest.java");
const other = { ...deps(files), classAtCaret: async () => null };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", other);
expect(other.open).toHaveBeenCalledWith("/p/src/test/java/a/WidgetTest.java");
});
it("goes back from a test to its subject", async () => {
const d = deps(["/p/src/main/java/a/Foo.java", "/p/src/test/java/a/FooTest.java"]);
await gotoTestOrSubject("/p/src/test/java/a/FooTest.java", "", d);
+1 -14
Переглянути файл
@@ -36,19 +36,6 @@ export interface TestNavDeps {
/** Create New Test… in `directory` (file templates), or a Rust test module in the file itself. */
createTest: (req: { directory: string; name: string; extension: string; subject: string }) => void;
createRustTestModule: () => void;
/** Name of the top-level class, interface, enum or object around the caret, if any. */
classAtCaret?: () => Promise<string | null>;
}
/** Languages whose files are named after a class but may declare several top-level ones. */
const CLASS_FILE = /\.(java|kt|scala|groovy|cs)$/;
/** The file name as the class at the caret would have it (`Helper.java` inside `Widget.java`), else the file's own. */
async function subjectFileName(path: string, deps: TestNavDeps): Promise<string> {
const name = basename(path);
if (!CLASS_FILE.test(name) || !deps.classAtCaret) return name;
const cls = await deps.classAtCaret().catch(() => null);
return cls ? cls + splitName(name).ext : name;
}
const isRustIntegrationTest = (path: string) => path.endsWith(".rs") && /\/tests\/[^/]+\.rs$/.test(path);
@@ -101,7 +88,7 @@ function relLabel(root: string | null, path: string) {
export async function gotoTestOrSubject(path: string, text: string, deps: TestNavDeps): Promise<void> {
const roots = deps.roots();
const root = deps.projectRoot();
const name = await subjectFileName(path, deps);
const name = basename(path);
const rank = (paths: string[]) => rankCandidates(path, paths, belowRoot(root, roots));
if (isTestSide(path, roots)) {
+1 -5
Переглянути файл
@@ -22,7 +22,7 @@ import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { headerSourceItems } from "./headerSource";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, topLevelTypeAt, type SuperDeps } from "./structureNav";
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
import { tx } from "@/platform/i18n";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
@@ -150,10 +150,6 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
})),
}),
hint: (text) => showHint(view, text),
classAtCaret: async () => {
const outline = await call(commands.docOutline(ctx.doc));
return topLevelTypeAt(outline, offsetToPos(view.state.doc, view.state.selection.main.head))?.name ?? null;
},
createTest: ({ directory, name, extension }) =>
void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
createRustTestModule: () => {
+1 -10
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { HierarchyItem, OutlineItem, SymbolKind } from "@/platform/ipc";
import { memberAt, methodStop, methodStops, superMethods, topLevelTypeAt } from "./structureNav";
import { memberAt, methodStop, methodStops, superMethods } from "./structureNav";
const r = (l1: number, l2: number) => ({ start: { line: l1, col: 0 }, end: { line: l2, col: 1 } });
function item(name: string, kind: SymbolKind, from: number, to: number, children: OutlineItem[] = []): OutlineItem {
@@ -100,12 +100,3 @@ describe("Super Method", () => {
expect(await lines("eat")).toEqual([2, 4]);
});
});
describe("topLevelTypeAt", () => {
it("answers the outermost type, through namespaces, and nothing outside a type", () => {
expect(topLevelTypeAt(OUTLINE, { line: 13, col: 2 })?.name).toBe("Foo");
expect(topLevelTypeAt(OUTLINE, { line: 23, col: 0 })).toBeNull();
const ns = [item("App", "namespace", 0, 30, [item("Widget", "class", 1, 10), item("Helper", "class", 12, 20)])];
expect(topLevelTypeAt(ns, { line: 15, col: 0 })?.name).toBe("Helper");
});
});
-11
Переглянути файл
@@ -36,17 +36,6 @@ export function methodStop(outline: readonly OutlineItem[], caret: Pos, dir: 1 |
return null;
}
/** The outermost type around `caret`, looking through namespaces and packages (C#, Kotlin scripts). */
export function topLevelTypeAt(outline: readonly OutlineItem[], caret: Pos): OutlineItem | null {
let level: readonly OutlineItem[] = outline;
for (;;) {
const hit = level.find((i) => inside(i, caret));
if (!hit) return null;
if (hit.kind !== "namespace" && hit.kind !== "package") return TYPES.has(hit.kind) ? hit : null;
level = hit.children;
}
}
export interface CaretMember {
/** Innermost method at the caret. */
method: OutlineItem | null;
+2 -19
Переглянути файл
@@ -192,20 +192,6 @@ describe("replacing a project in this window", () => {
expect(useProject.getState().project?.root).toBe("/local");
});
it("asks about trust before leaving, so Don't Open keeps the current project running", async () => {
useProject.setState({
...projectState("/a"),
settings: { general: { openProjectIn: "same" } },
} as never);
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await openProjectWithPolicy("/b");
expect(confirmProjectTrust).toHaveBeenCalledWith("/b", "local");
expect(confirmLeaveProject).not.toHaveBeenCalled();
expect(openProject).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
});
it("opens the local project when its path matches the remote root", async () => {
useProject.setState({
...projectState("/same"),
@@ -806,14 +792,11 @@ describe("trust is asked before a new project window opens", () => {
expect(windowOpenProject).toHaveBeenCalled();
});
it("asks once this window takes the project, before leaving its current one", async () => {
it("asks only once, from openProject, when the project opens in this window", async () => {
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
await openProjectInWindow("/p/b", false);
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
expect(confirmProjectTrust).toHaveBeenCalledOnce();
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
);
expect(confirmProjectTrust).not.toHaveBeenCalled();
expect(openProject).toHaveBeenCalledWith("/p/b");
});
});
-7
Переглянути файл
@@ -57,13 +57,6 @@ async function openHere(path: string): Promise<boolean> {
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
const wsl = await commands.wslResolve(path).catch(() => null);
try {
// Asked before leaving, so Don't Open keeps the current project and its processes running.
if (!wsl) await confirmProjectTrust(path, "local");
} catch (e) {
openFailed(path, e);
return false;
}
if (!(await confirmLeaveProject(!wsl))) return false;
try {
if (wsl) await connectRemote(wsl.target, wsl.path);
-57
Переглянути файл
@@ -1,57 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { provideEditorService } from "@/workbench/contributions";
import { addBreakpoint, useBreakpoints } from "../breakpoints/store";
import { DebuggerOverlays } from "../ui/Overlays";
import { useOverlays } from "../ui/popoverStore";
const openFile = vi.fn(async () => undefined);
provideEditorService({ openFile } as never);
const path = "/p/main.py";
describe("the Breakpoints dialog", () => {
beforeEach(() => {
openFile.mockClear();
useBreakpoints.setState({ byFile: {}, status: {}, muted: false });
const first = addBreakpoint(path, 2, { condition: "value == 2" });
addBreakpoint(path, 6);
useOverlays.setState({ breakpoints: { id: first.id } } as never);
});
afterEach(() => {
cleanup();
act(() => useOverlays.setState({ breakpoints: null } as never));
});
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
const clickRow = (name: string, detail: number) => {
fireEvent.mouseDown(row(name), { button: 0 });
fireEvent.click(row(name), { detail });
};
const breakpointAt = (line: number) => useBreakpoints.getState().byFile[path]!.find((b) => b.line === line)!;
it("selects a breakpoint on click and goes to its source on double-click", () => {
render(<DebuggerOverlays />);
clickRow("main.py:7", 1);
expect(openFile).not.toHaveBeenCalled();
// Its details show beside the list.
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
clickRow("main.py:3", 2);
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
});
it("saves the condition being typed when the dialog closes or another breakpoint is shown", () => {
render(<DebuggerOverlays />);
fireEvent.change(condition(), { target: { value: "value == 1" } });
fireEvent.click(within(dialog()).getByRole("button", { name: "Done" }));
expect(breakpointAt(2).condition).toBe("value == 1");
act(() => useOverlays.setState({ breakpoints: { id: breakpointAt(2).id } } as never));
fireEvent.change(condition(), { target: { value: "value == 3" } });
clickRow("main.py:7", 1);
expect(breakpointAt(2).condition).toBe("value == 3");
});
});
+10 -58
Переглянути файл
@@ -179,19 +179,12 @@ function BreakpointFields({
const commitText = () => {
const d = draft.current;
const cond = d.condition.trim() || null;
const changes = {
if (cond) pushHistory("condition", cond);
updateBreakpoint(path, bp.id, {
condition: cond,
hitCondition: d.hitCondition.trim() || null,
logMessage: d.logEval ? d.logMessage.trim() || null : null,
};
if (
changes.condition === (bp.condition ?? null) &&
changes.hitCondition === (bp.hitCondition ?? null) &&
changes.logMessage === (bp.logMessage ?? null)
)
return;
if (cond) pushHistory("condition", cond);
updateBreakpoint(path, bp.id, changes);
});
};
useEffect(() => {
if (!commitRef) return;
@@ -403,13 +396,9 @@ function BreakpointsDialog() {
}, [byFile, methods, fields]);
const items = rows.filter((r) => r.type !== "section");
const [selected, setSelected] = useState<string | null>(null);
// The shown breakpoint's typed fields, saved before it is closed or another one is shown:
// Enter on Done and a click on a row don't blur them.
const commitRef = useRef<(() => void) | null>(null);
const open = !!state;
const current = items.find((r) => r.key === (selected ?? state?.id)) ?? items[0];
const close = () => {
commitRef.current?.();
setSelected(null);
useOverlays.setState({ breakpoints: null });
};
@@ -459,14 +448,8 @@ function BreakpointsDialog() {
isSection={(r) => r.type === "section"}
renderSection={(r) => <div className={styles.exceptionAdapter}>{r.type === "section" ? r.label : ""}</div>}
activeIndex={current ? rows.indexOf(current) : -1}
onActiveChange={(i) => {
commitRef.current?.();
setSelected(rows[i]?.key ?? null);
}}
// A click selects; double-click or Enter goes to the source.
onActivate={(r, _i, e) => {
if (e.type === "keydown" || e.detail > 1) goTo(r);
}}
onActiveChange={(i) => setSelected(rows[i]?.key ?? null)}
onActivate={(r) => goTo(r)}
aria-label="All breakpoints"
className={styles.bpList}
empty={
@@ -539,9 +522,9 @@ function BreakpointsDialog() {
</div>
<div className={styles.bpDetail}>
{current?.type === "line" ? (
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} />
) : current?.type === "special" ? (
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} />
) : null}
</div>
</div>
@@ -596,15 +579,7 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
);
}
function BreakpointDetail({
row,
onGo,
commitRef,
}: {
row: BpRow;
onGo: () => void;
commitRef: MutableRefObject<(() => void) | null>;
}) {
function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
const { path, bp } = row;
const st = useBreakpoints((s) => s.status[bp.id]);
return (
@@ -622,7 +597,7 @@ function BreakpointDetail({
</Button>
</div>
{st && <div className={styles.statusLine}>{st.verified ? tx("Verified") : (st.message ?? "Not verified")}</div>}
<BreakpointFields path={path} bp={bp} commitRef={commitRef} />
<BreakpointFields path={path} bp={bp} />
<Checkbox
checked={!!bp.temporary}
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
@@ -632,34 +607,11 @@ function BreakpointDetail({
);
}
function SpecialDetail({
bp,
onGo,
commitRef,
}: {
bp: SpecialBreakpoint;
onGo: () => void;
commitRef: MutableRefObject<(() => void) | null>;
}) {
function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }) {
const st = useSpecialBreakpoints((s) => s.status[bp.id]);
const [name, setName] = useState(bp.kind === "method" ? bp.name : bp.label);
const [condition, setCondition] = useState(bp.condition ?? "");
const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
const draft = useRef({ name, condition, hitCondition });
useEffect(() => {
draft.current = { name, condition, hitCondition };
commitRef.current = () => {
const d = draft.current;
updateSpecial(bp.id, {
name: d.name.trim(),
condition: d.condition.trim() || null,
hitCondition: d.hitCondition.trim() || null,
});
};
return () => {
commitRef.current = null;
};
});
return (
<div className={styles.detail}>
<div className={styles.bpTitle}>
+1 -4
Переглянути файл
@@ -86,7 +86,6 @@ import {
VIEW_MODES,
autoExpand,
clearRevealRequest,
explainHiddenPath,
loadDir,
loadOutline,
revealPath,
@@ -518,7 +517,7 @@ export function ProjectView() {
// Select a revealed path once its row exists.
useEffect(() => {
if (!revealRequest) return;
const { path, focus, seq, explain } = revealRequest;
const { path, focus, seq } = revealRequest;
const exact = model.keyOfPath.get(path);
const loadingAncestors = info.pending.some((p) => p === path || isInside(path, p));
if (!exact && loadingAncestors) return;
@@ -529,8 +528,6 @@ export function ProjectView() {
handle.current?.reveal(key);
revealing.current = false;
if (focus) handle.current?.focus();
const shown = model.byKey.get(key)?.path;
if (explain && !exact && shown) explainHiddenPath(path, shown);
}, [revealRequest, model, info]);
// Autoscroll from source: follow the active editor.
+1 -1
Переглянути файл
@@ -108,7 +108,7 @@ export function selectInProjectView(path?: string | null, focus = true) {
if (!target) return false;
if (!modeShows(target)) setViewMode("project");
showProjectView(focus);
return revealPath(target, focus, true);
return revealPath(target, focus);
}
/**
-28
Переглянути файл
@@ -7,8 +7,6 @@ import {
reloadLoadedDirs,
currentModel,
expandAll,
explainHiddenPath,
hidingOption,
initProjectTree,
loadDir,
revealPath,
@@ -20,7 +18,6 @@ import {
} from "./store";
import { beginNew, commitEditing, copySelection, paste, transfer } from "./operations";
import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
import { provideNotificationService } from "@/workbench/contributions";
const ROOT = "/p";
let fs: MemoryFs;
@@ -322,28 +319,3 @@ it("keeps the primary first and sorts attachments by name", () => {
initProjectTree("/ws", "Workspace", ["/z", "/c", "/a"]);
expect(currentModel().roots.map((n) => n.path)).toEqual(["/a", "/c", "/z"]);
});
describe("a file the view options hide", () => {
const entry = (name: string, ignored = false) => ({ name, path: `/p/${name}`, isDir: true, ignored }) as never;
it("names the option that hides it below the shown ancestor, and offers to turn it on", () => {
useProjectTree.setState({ listings: new Map([["/p", [entry("build", true), entry("src")]]]) });
setViewOption("showExcluded", false);
expect(hidingOption("/p/build/out.txt", "/p")).toBe("showExcluded");
expect(hidingOption("/p/.git/config", "/p")).toBe(
useProjectTree.getState().options.showHidden ? null : "showHidden",
);
expect(hidingOption("/p/src/a.ts", "/p")).toBeNull();
const notify = vi.fn();
provideNotificationService({ notify } as never);
explainHiddenPath("/p/build/out.txt", "/p");
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "out.txt is hidden because Show Excluded Files is off" }),
);
notify.mock.calls[0]![0].actions[0].run();
expect(useProjectTree.getState().options.showExcluded).toBe(true);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/build/out.txt");
expect(hidingOption("/p/build/out.txt", "/p")).toBeNull();
});
});
+3 -46
Переглянути файл
@@ -10,9 +10,6 @@ import { commands, type FileEntry, type OutlineItem } from "@/bindings";
import { withDocument } from "@/editor/lsp/files";
import { IpcError } from "@/platform/ipc";
import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { ipcPath } from "@/platform/paths";
import {
DEFAULT_TREE_OPTIONS,
@@ -125,8 +122,7 @@ interface ProjectTreeState {
editing: Editing | null;
clipboard: Clipboard | null;
/** A path to select (and scroll to) once its row is visible. */
/** `explain`: say which view option hides the path when only an ancestor can be selected. */
revealRequest: { path: string; focus: boolean; seq: number; explain?: boolean } | null;
revealRequest: { path: string; focus: boolean; seq: number } | null;
/** Folder key highlighted as drop target. */
dropTarget: string | null;
mode: ViewMode;
@@ -639,7 +635,7 @@ export function dropOutlines(paths: readonly string[]) {
let revealSeq = 0;
/** Expands the ancestors of `path` and selects it once visible. */
export function revealPath(requested: string, focus = false, explain = false) {
export function revealPath(requested: string, focus = false) {
const { expanded } = get();
const project = get().root;
if (!project) return false;
@@ -672,7 +668,7 @@ export function revealPath(requested: string, focus = false, explain = false) {
changed = true;
}
if (changed) setExpanded(next);
set({ revealRequest: { path, focus, seq: ++revealSeq, ...(explain ? { explain } : {}) } });
set({ revealRequest: { path, focus, seq: ++revealSeq } });
for (const a of folders) void loadDir(a);
return true;
}
@@ -738,45 +734,6 @@ function groupAncestors(model: TreeModel, key: string): string[] {
}
}
/**
* The view option that hides `path` below its shown ancestor `shown`: a hidden name
* (Show Hidden Files) or an ignored entry (Show Excluded Files). Null when no option does.
*/
export function hidingOption(path: string, shown: string): "showHidden" | "showExcluded" | null {
const { listings, options } = get();
if (!isSameOrInside(path, shown) || path === shown) return null;
let dir = shown;
for (const name of path.slice(shown.length + 1).split("/")) {
if (isIgnoredName(name)) return options.showHidden ? null : "showHidden";
if (listings.get(dir)?.find((e) => e.name === name)?.ignored) return options.showExcluded ? null : "showExcluded";
dir = `${dir}/${name}`;
}
return null;
}
const OPTION_TITLES = { showHidden: "Show Hidden Files", showExcluded: "Show Excluded Files" } as const;
/** Select Opened File reached only `shown`: say which option hides `path`, offering to turn it on. */
export function explainHiddenPath(path: string, shown: string) {
const option = hidingOption(path, shown);
if (!option) return;
const title = OPTION_TITLES[option];
notifications().notify({
level: "info",
key: "project.hiddenPath",
title: tx`${nameOf(path)} is hidden because ${title} is off`,
actions: [
{
label: tx(title),
run: () => {
setViewOption(option, true);
revealPath(path, true);
},
},
],
});
}
export function clearRevealRequest(seq: number) {
if (get().revealRequest?.seq === seq) set({ revealRequest: null });
}
+1 -27
Переглянути файл
@@ -140,14 +140,6 @@ function TrustSettings() {
setError(String(e));
}
};
const trust = async (path: string) => {
try {
await call(commands.projectTrustSet(path, true, false));
await refresh();
} catch (e) {
setError(String(e));
}
};
const addLocation = async () => {
try {
const { open } = await import("@/platform/dialog");
@@ -177,24 +169,6 @@ function TrustSettings() {
</Button>
</div>
))}
{decisions?.restricted.length ? (
<>
<h3>
<T>Restricted projects</T>
</h3>
<p className={styles.hint}>
<T>These projects open in Restricted Mode, even inside a trusted location.</T>
</p>
{decisions.restricted.map((path) => (
<div className={styles.row} key={path}>
<span className={styles.path}>{path}</span>
<Button onClick={() => void trust(path)}>
<T>Trust</T>
</Button>
</div>
))}
</>
) : null}
<div className={styles.sectionHead}>
<h3>
<T>Trusted locations</T>
@@ -204,7 +178,7 @@ function TrustSettings() {
</Button>
</div>
<p className={styles.hint}>
<T>Every project inside a trusted location is trusted without asking, unless it is a restricted project.</T>
<T>Every project inside a trusted location is trusted without asking.</T>
</p>
{decisions?.locations.map((path) => (
<div className={styles.row} key={path}>
+1 -5
Переглянути файл
@@ -58,13 +58,9 @@
justify-content: space-between;
gap: var(--space-3);
}
.content h3 {
.sectionHead h3 {
margin: 0;
}
.content > h3,
.sectionHead {
margin-top: var(--space-3);
}
.hint {
color: var(--fg-secondary);
}
+1 -19
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { executeAction } from "@/platform/actions";
import { emitLocalIdeEvent } from "@/platform/ipc";
@@ -165,24 +165,6 @@ it("adds a picked folder as a trusted location from settings", async () => {
expect(addLocation).toHaveBeenCalledTimes(1);
});
it("lists restricted projects, which a trusted location doesn't cover, and trusts one from settings", async () => {
const Page = useSettingsPages.getState().pages.get("projectTrust")!.component!;
listDecisions.mockResolvedValue({
status: "ok",
data: { projects: [], locations: ["/projects"], restricted: ["/projects/app"] },
});
render(<Page />);
expect(await screen.findByRole("heading", { name: "Restricted projects" })).toBeTruthy();
listDecisions.mockResolvedValue({
status: "ok",
data: { projects: ["/projects/app"], locations: ["/projects"], restricted: [] },
});
fireEvent.click(screen.getByRole("button", { name: "Trust" }));
await waitFor(() => expect(screen.queryByRole("heading", { name: "Restricted projects" })).toBeNull());
expect(decide).toHaveBeenCalledWith("/projects/app", true, false);
expect(screen.getByText("/projects/app")).toBeTruthy();
});
it.each(["Trust Project", "Preview in Restricted Mode"])(
"keeps a local opening's trust decision on the client: %s",
async (button) => {
+3 -15
Переглянути файл
@@ -36,7 +36,6 @@ import {
import { selectedTarget } from "./sessionTargets";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
type Row =
/** A labelled group, or a thin separator when `label` is empty. */
@@ -112,16 +111,6 @@ function anchorElement(): Element | { x: number; y: number } {
}
/** Run/Debug configuration chooser popup (⌃⌥R), anchored to the title bar widget. */
/** Deletes a configuration from the chooser once the user confirms, as IDEA's popup asks first. */
async function askDeleteConfig(config: RunConfig) {
const ok = await confirm({
title: "Confirmation",
message: tx`Are you sure you want to delete ${config.name}?`,
ok: "Delete",
});
if (ok) await deleteConfig(config.id);
}
export function ConfigChooserOverlay() {
const open = useRun((s) => s.chooserOpen);
if (!open) return null;
@@ -261,11 +250,10 @@ function ConfigChooser() {
e.key === "Delete" &&
row?.type === "config" &&
canDeleteConfig(row.config.id) &&
input().selectionStart === query.length &&
input().selectionEnd === query.length
input().selectionStart === query.length
) {
e.preventDefault();
void askDeleteConfig(row.config);
void deleteConfig(row.config.id);
return;
}
if (numbers.size && !e.altKey && !e.ctrlKey && !e.metaKey && /^Digit[1-9]$|^Numpad[1-9]$/.test(e.code)) {
@@ -298,7 +286,7 @@ function ConfigChooser() {
{ kind: "header", label: "Configuration" },
{ label: "Edit…", icon: "edit", run: () => activate(row, "edit") },
{ label: pinned.includes(c.id) ? "Unpin" : "Pin", icon: "pin", run: () => togglePinned(c.id) },
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void askDeleteConfig(c) }] : []),
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void deleteConfig(c.id) }] : []),
];
};
const openMenu = (c: RunConfig, at: Element) => setMenu({ name: c.name, anchor: at, items: menuItems(c) });
+3 -29
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
const ipc = vi.hoisted(() => ({
runSaveConfigs: vi.fn(),
@@ -17,7 +17,6 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { MessagesHost } from "@/workbench/messages";
import { EditConfigsOverlay } from "./EditConfigsDialog";
import { ConfigChooserOverlay } from "./ConfigChooser";
import {
@@ -142,39 +141,14 @@ it("keeps other temporary and non-temporary configurations on removal", async ()
expect(useRun.getState().configs.map((c) => c.id)).toEqual(expect.arrayContaining(["npm:app", other.id]));
});
it("chooser popup Delete removes the selected detection once confirmed", async () => {
it("chooser popup Delete removes the selected detection", async () => {
useRun.setState({ chooserOpen: true, editorOpen: false });
render(
<>
<ConfigChooserOverlay />
<MessagesHost />
</>,
);
render(<ConfigChooserOverlay />);
fireEvent.keyDown(document.querySelector("input[data-autofocus]")!, { key: "Delete" });
const ask = await screen.findByRole("dialog", { name: "Confirmation" });
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
fireEvent.click(within(ask).getByRole("button", { name: "Delete" }));
await waitFor(() => expect(ipc.runSaveConfigs).toHaveBeenCalledWith([], ["npm:app"]));
await waitFor(() => expect(useRun.getState().configs).toEqual([]));
});
it("chooser popup Delete edits the search text when the caret is not at its end", async () => {
useRun.setState({ chooserOpen: true, editorOpen: false });
render(
<>
<ConfigChooserOverlay />
<MessagesHost />
</>,
);
const input = document.querySelector<HTMLInputElement>("input[data-autofocus]")!;
fireEvent.change(input, { target: { value: "app" } });
input.setSelectionRange(1, 1);
fireEvent.keyDown(input, { key: "Delete" });
await act(async () => {});
expect(screen.queryByRole("dialog", { name: "Confirmation" })).toBeNull();
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
});
it("Cancel discards a pending detected removal", () => {
render(<EditConfigsOverlay />);
fireEvent.click(screen.getByRole("button", { name: "Remove Configuration" }));
+2 -2
Переглянути файл
@@ -357,8 +357,8 @@ export function nodeMenu(
},
{ kind: "separator" as const },
]),
// The node itself, like double-click: under Staged or Unstaged its side of the index.
opts?.roots && first
// Under the modal interface the node itself, like double-click, in the front window.
vcsDiffInFront() && opts?.roots && first
? {
label: "Show Diff",
icon: "diff",
+1 -14
Переглянути файл
@@ -23,9 +23,6 @@ const isLabel = (e: HistoryEntry) => e.kind === "label";
const time = (e: HistoryEntry) => e.timestampMs ?? 0;
/** Per file, the newest snapshot recorded before `at` (the state at a label). */
/** The backend's label of the snapshot taken when a file is deleted (`ide-workspace::history::DELETED`). */
const DELETED = "Deleted";
export function snapshotsBefore(entries: readonly HistoryEntry[], at: number): Map<string, HistoryEntry> {
const out = new Map<string, HistoryEntry>();
for (const e of entries) {
@@ -116,17 +113,7 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
);
return;
}
// A file whose last revision before the label is its deletion was absent then: nothing to restore.
const recorded = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
const targets = recorded.filter((e) => e.label !== DELETED);
if (!view.folder && fileAtLabel?.label === DELETED) {
notifications().notify({
level: "info",
title: tx`${baseName(path)} did not exist at label '${current.label}'`,
key: "localHistory.revert",
});
return;
}
const targets = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
if (!targets.length) {
notifications().notify({
level: "info",
+2 -6
Переглянути файл
@@ -294,14 +294,10 @@ describe("Changes tree diffs follow the commit interface setting (#1863)", () =>
expect(openFile).not.toHaveBeenCalled();
});
// The row's own diff (under Staged or Unstaged, its side of the index), in an editor tab.
it("opens the node's diff in an editor tab with the non-modal interface", async () => {
it("keeps the Show Diff action item with the non-modal interface", () => {
modal(false);
const menu = nodeMenu([node], ["/p"], { roots: [node] });
const show = menu.find((m) => m.kind !== "separator" && "label" in m && m.label === "Show Diff");
(show as { run: () => void }).run();
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
expect(openDiffDialog).not.toHaveBeenCalled();
expect(menu).toContainEqual({ kind: "action", action: "vcs.showDiff", arg: "/p/src/a.ts" });
});
});
+6 -5
Переглянути файл
@@ -95,14 +95,15 @@ describe("Local History", () => {
expect(list).toHaveTextContent("src/gone.ts");
expect(screen.getByText(/Label 'Before Git checkout' · 2 files recorded before it/)).toBeInTheDocument();
// Revert at the label restores every file's last revision before it; a file
// deleted before the label was absent then and stays absent.
// Revert at the label restores every file's last revision before it.
fireEvent.click(screen.getByRole("button", { name: "Revert" }));
const confirm = await screen.findByRole("dialog", { name: "Revert" });
expect(confirm).toHaveTextContent("Revert 1 files under src to label 'Before Git checkout'?");
fireEvent.click(within(confirm).getByRole("button", { name: "Revert" }));
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(1));
expect(historyRestore).toHaveBeenCalledWith("/p/src/a.ts", id("e"));
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(2));
expect(historyRestore.mock.calls.map((c) => c.join(" ")).sort()).toEqual([
`/p/src/a.ts ${id("e")}`,
`/p/src/gone.ts ${id("d")}`,
]);
// A deleted file's row offers Restore.
fireEvent.click(within(list).getAllByRole("option")[1]!);
-32
Переглянути файл
@@ -1,32 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { BranchInfo } from "@/bindings";
import { installOperationNoticeExpiry } from "../operations";
import { useVcs } from "../store";
const { expire } = vi.hoisted(() => ({ expire: vi.fn() }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: vi.fn(), expire }),
}));
const branch = (operation: string | null) => ({ head: "main", operation }) as unknown as BranchInfo;
let dispose: () => void;
beforeEach(() => {
expire.mockClear();
useVcs.setState({ branch: branch("merge") });
dispose = installOperationNoticeExpiry();
});
afterEach(() => dispose());
it("expires the conflict notice once the merge it offers to commit or abort is over", () => {
useVcs.setState({ branch: branch("merge") });
expect(expire).not.toHaveBeenCalled();
useVcs.setState({ branch: branch(null) });
expect(expire).toHaveBeenCalledWith("vcs.conflicts");
});
it("keeps it while an operation is still in progress", () => {
useVcs.setState({ branch: branch("rebase") });
expect(expire).not.toHaveBeenCalled();
});
-24
Переглянути файл
@@ -18,7 +18,6 @@ import { useChangelists } from "../changelists";
import { useCommit } from "../commitStore";
import { inclusionChecks, isCommitAll, stagingChecks } from "../staging";
import { useVcs } from "../store";
import { provideEditorService } from "@/workbench/contributions";
const file = (rel: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"]): FileStatus => ({
path: `/p/${rel}`,
@@ -131,29 +130,6 @@ describe("staging operations of the tree's nodes", () => {
]).toEqual([true, false]);
});
it("shows a row's side of the index from Show Diff: HEAD ↔ Index under Staged, Index ↔ working copy under Unstaged", async () => {
useSettings(true);
const openInput = vi.fn(async () => undefined);
provideEditorService({ openInput } as never);
const show = (node: (typeof roots)[number]) => {
const menu = nodeMenu([node], [], { roots });
(menu.find((m) => "label" in m && m.label === "Show Diff") as { run: () => void }).run();
};
const sides = () => {
const data = (openInput.mock.calls.at(-1) as unknown as [{ data: { left: unknown; right: unknown } }])[0].data;
return [data.left, data.right];
};
show(group("staged").children!.find((n) => n.label === "Partial.kt")!);
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
expect(sides()).toEqual([
{ type: "rev", rev: "HEAD" },
{ type: "rev", rev: ":0", label: "Index" },
]);
show(group("unstaged").children!.find((n) => n.label === "Partial.kt")!);
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(2));
expect(sides()).toEqual([{ type: "rev", rev: ":0", label: "Index" }, { type: "worktree" }]);
});
it("has no Commit File…: a commit takes the whole index", () => {
useSettings(true);
const labels = (items: MenuItem[]) => items.map((i) => ("label" in i ? i.label : null));
+5 -10
Переглянути файл
@@ -60,7 +60,6 @@ import {
showWorktrees,
} from "./gitMenuDialogs";
import { currentRepo, refreshNow, repoName, repoOf, statusOf, useVcs } from "./store";
import { stagingAreaOn } from "./staging";
import { showSyncCommitsForCurrent } from "./SyncCommitsPopup";
import { tx } from "@/platform/i18n";
@@ -434,24 +433,21 @@ export function registerVcsActions(): () => void {
}
if (await showDirectoryWorkingDiff(paths)) return;
const state = useVcs.getState();
// The tree the Commit tool window shows: with the staging area, Staged / Unstaged and no lists.
const staging = stagingAreaOn();
const tree = buildChangeTree(
state.status,
state.root ?? "",
useCommit.getState().groupByDir,
staging ? undefined : useChangelists.getState().state,
useChangelists.getState().state,
state.roots,
useCommit.getState().groupByStaging || staging,
useCommit.getState().groupByStaging,
undefined,
useCommit.getState().groupByRepo,
useCommit.getState().showUnversionedSeparately,
);
// The selected rows while the tree has focus: a file under Staged or Unstaged diffs that side.
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
// The modal interface has one front diff window (#1863): a file with its group
// as the F7 chain, or several selected files as the chain.
if (isModalCommit()) {
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
const [first] = targets;
const data =
targets.length > 1
@@ -465,9 +461,8 @@ export function registerVcsActions(): () => void {
await openVcsDiff({ ...data, line });
return;
}
for (const target of targets.slice(0, 5)) {
const data = typeof target === "string" ? groupDiffData(tree, target) : changeNodeDiffData(tree, target);
await openDiff({ ...data, line }, { preview: targets.length === 1 });
for (const path of paths.slice(0, 5)) {
await openDiff({ ...groupDiffData(tree, path), line }, { preview: paths.length === 1 });
}
},
},
+1 -2
Переглянути файл
@@ -20,7 +20,7 @@ import { registerVcsActions } from "./actions";
import { installChangelists } from "./changelists";
import { registerHistoryActions, trackOperationContext } from "./historyActions";
import { registerLogPaneActions } from "./logPaneActions";
import { controlLabel, controlOperation, inProgress, installOperationNoticeExpiry } from "./operations";
import { controlLabel, controlOperation, inProgress } from "./operations";
import { annotationsShown, blameSlot } from "./blame";
import { activateRevisionAnnotations } from "./annotateRevisionProvider";
import { inlineBlame } from "./inlineBlame";
@@ -195,7 +195,6 @@ export function activate(): () => void {
useCommit.setState({ signOff: workflowSettings().vcs.git.signOff });
const disposers = [
installVcsStore(),
installOperationNoticeExpiry(),
installRootSync(),
installGitLog(),
installDiagnosticsTracking(),
-11
Переглянути файл
@@ -56,17 +56,6 @@ export function inProgress(op: string | null | undefined = useVcs.getState().bra
return op === "rebase" || op === "merge" || op === "cherry-pick" || op === "revert" || op === "am" ? op : null;
}
/**
* Expires the conflict notices (key `vcs.conflicts`: Merge conflicts, All conflicts resolved) once
* the merge / rebase / cherry-pick they offer to continue or abort is over, however it ended.
*/
export function installOperationNoticeExpiry(): () => void {
return useVcs.subscribe((s, prev) => {
if (inProgress(prev.branch?.operation) && !inProgress(s.branch?.operation))
notifications().expire?.("vcs.conflicts");
});
}
/** "Rebasing main", "Merging", "Cherry-picking"… for the branch widget and banner. */
export function operationTitle(op: InProgress, head: string | null): string {
if (!head)
-70
Переглянути файл
@@ -1,70 +0,0 @@
import { act, cleanup, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { _emitEditorEvent } from "@/editor/api";
import { commands, emitLocalIdeEvent } from "@/platform/ipc";
import { WebEditor } from "./WebEditor";
import { togglePreview, useWebPreview } from "./browsers";
const path = "/project/site/index.html";
const url = "http://127.0.0.1:43210/token/project/site/index.html";
const style = "/project/shared/main.css";
const script = "/project/site/app.js";
const frame = () => screen.getByTitle("HTML preview");
const save = (path: string) => _emitEditorEvent({ type: "docSaved", doc: 1, path });
const change = (...modified: string[]) => emitLocalIdeEvent({ type: "fsChanged", created: [], modified, removed: [] });
describe("HTML preview reload", () => {
let html: string;
beforeEach(async () => {
html = '<link rel="stylesheet" href="../shared/main.css?version=1"><script src="app.js" defer></script>';
vi.spyOn(commands, "webUrl").mockResolvedValue({ status: "ok", data: url });
vi.spyOn(commands, "fsReadText").mockImplementation(async () => ({ status: "ok", data: html }));
togglePreview(path, true);
render(
<WebEditor path={path} tabId="page">
HTML editor
</WebEditor>,
);
await screen.findByTitle("HTML preview");
vi.useFakeTimers();
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
useWebPreview.setState({}, true);
});
async function after(event: () => void) {
await act(async () => {
event();
await vi.advanceTimersByTimeAsync(300);
});
return frame();
}
it("keeps the same iframe after unrelated files are saved, including unlinked web assets", async () => {
const original = frame();
expect(
await after(() => change("/project/site/notes.txt", "/project/site/unused.css", "/project/other.html")),
).toBe(original);
expect(await after(() => save("/project/site/unused.js"))).toBe(original);
expect(await after(() => emitLocalIdeEvent({ type: "docDirty", doc: 2, dirty: false }))).toBe(original);
});
it("reloads when linked CSS or JS changes and refreshes dependencies on HTML save", async () => {
const original = frame();
const afterStyle = await after(() => change(style));
expect(afterStyle).not.toBe(original);
const afterScript = await after(() => save(script));
expect(afterScript).not.toBe(afterStyle);
html = '<base href="../shared/"><script src="replacement.js"></script>';
const afterPage = await after(() => save(path));
expect(afterPage).not.toBe(afterScript);
expect(await after(() => change(script, style))).toBe(afterPage);
expect(await after(() => change("/project/shared/replacement.js"))).not.toBe(afterPage);
});
});
+30 -49
Переглянути файл
@@ -5,11 +5,10 @@
*/
import { useEffect, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import { onEditorEvent } from "@/editor/api";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { FloatingToolbar, IconButton } from "@/ui";
import { browserIcon, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
import { previewResources } from "./previewResources";
import styles from "./Web.module.css";
import { tx } from "@/platform/i18n";
@@ -47,7 +46,7 @@ export function WebEditor({ path, children }: { path: string; tabId: string; chi
</div>
</FloatingToolbar>
</div>
{preview && <WebPreview key={path} path={path} />}
{preview && <WebPreview path={path} />}
</div>
);
}
@@ -56,58 +55,40 @@ function WebPreview({ path }: { path: string }) {
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [seq, setSeq] = useState(0);
const root = useProject((s) => s.project?.root ?? null);
useEffect(() => {
let live = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let pageUrl: string | null = null;
let resources = new Set([path]);
let scan = 0;
let pageChanged = false;
const updateResources = async (url: string) => {
const id = ++scan;
const next = await call(commands.fsReadText(path))
.then((html) => previewResources(path, url, html))
.catch(() => new Set([path]));
if (!live || scan !== id) return false;
resources = next;
return true;
};
void webUrl(path)
.then(async (url) => {
if (!live) return;
pageUrl = url;
await updateResources(url);
if (live) setUrl(url);
})
.catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
const changed = (paths: readonly string[]) => {
if (!paths.some((changedPath) => resources.has(changedPath))) return;
pageChanged ||= paths.includes(path);
clearTimeout(timer);
timer = setTimeout(() => {
if (!pageUrl) return;
if (pageChanged) {
pageChanged = false;
void updateResources(pageUrl).then((current) => {
if (current) setSeq((n) => n + 1);
});
} else setSeq((n) => n + 1);
}, RELOAD_DELAY);
};
const offFs = onIdeEvent("fsChanged", (e) => changed([...e.created, ...e.modified, ...e.removed]));
const offSaved = onEditorEvent((e) => {
if (e.type === "docSaved") changed([e.path]);
});
webUrl(path).then(
(u) => live && setUrl(u),
(e: unknown) => live && setError(e instanceof Error ? e.message : String(e)),
);
return () => {
live = false;
clearTimeout(timer);
offFs();
offSaved();
};
}, [path]);
// Saved edits anywhere in the project (scripts, styles) reload the page.
useEffect(() => {
const scope = root ?? path.slice(0, path.lastIndexOf("/"));
let timer: ReturnType<typeof setTimeout> | undefined;
const reload = () => {
clearTimeout(timer);
timer = setTimeout(() => setSeq((n) => n + 1), RELOAD_DELAY);
};
const offFs = onIdeEvent("fsChanged", (e) => {
if ([...e.created, ...e.modified, ...e.removed].some((p) => p === scope || p.startsWith(scope + "/"))) reload();
});
const offDirty = onIdeEvent("docDirty", (e) => {
if (!e.dirty) reload();
});
return () => {
clearTimeout(timer);
offFs();
offDirty();
};
}, [path, root]);
if (error) return <div className={clsx(styles.preview, styles.message)}>{error}</div>;
if (!url) return <div className={styles.preview} />;
return (
-59
Переглянути файл
@@ -1,59 +0,0 @@
const LOADABLE_LINKS = new Set(["stylesheet", "icon", "manifest", "preload", "prefetch", "modulepreload"]);
function relativePath(pathname: string): string | null {
try {
const segments = pathname.split("/").map(decodeURIComponent);
return segments.some((part) => /[/\\:\0]/.test(part)) ? null : segments.filter(Boolean).join("/");
} catch {
return null;
}
}
/** Local resources referenced by a page inside the built-in server's URL namespace. */
export function previewResources(path: string, url: string, html: string): Set<string> {
const resources = new Set([path]);
const page = new URL(url);
// The first two URL segments are the server token and the served directory's key.
const prefix = page.pathname.split("/").slice(0, 3).join("/") + "/";
const pagePath = relativePath(page.pathname.slice(prefix.length));
if (!pagePath || !path.endsWith(`/${pagePath}`)) return resources;
const directory = path.slice(0, -pagePath.length);
const template = document.createElement("template");
template.innerHTML = html;
const doc = template.content;
let base = page;
try {
base = new URL(doc.querySelector("base[href]")?.getAttribute("href") ?? "", page);
} catch {
// Invalid base URLs leave relative resources on the page URL.
}
const add = (reference: string | null) => {
if (!reference?.trim() || reference.trimStart().startsWith("#")) return;
try {
const resource = new URL(reference, base);
if (resource.origin !== page.origin || !resource.pathname.startsWith(prefix)) return;
const relative = relativePath(resource.pathname.slice(prefix.length));
if (relative) resources.add(directory + relative);
} catch {
// The browser ignores invalid resource URLs too.
}
};
for (const element of doc.querySelectorAll("[src]")) add(element.getAttribute("src"));
for (const element of doc.querySelectorAll("link[href]")) {
if (
element
.getAttribute("rel")
?.toLowerCase()
.split(/\s+/)
.some((rel) => LOADABLE_LINKS.has(rel))
)
add(element.getAttribute("href"));
}
for (const element of doc.querySelectorAll("video[poster]")) add(element.getAttribute("poster"));
for (const element of doc.querySelectorAll("object[data]")) add(element.getAttribute("data"));
for (const element of doc.querySelectorAll("svg image, svg use"))
add(element.getAttribute("href") ?? element.getAttribute("xlink:href"));
return resources;
}
+1 -5
Переглянути файл
@@ -274,11 +274,7 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
open(items[current]);
return;
}
// Delete removes the selected project only when it has no text to delete: the caret is at the end
// of the query (⌘⌫: the query is empty). Otherwise it edits the query.
const field = e.currentTarget;
const atEnd = field.selectionStart === field.value.length && field.selectionEnd === field.value.length;
if (((e.key === "Delete" && atEnd) || (e.key === "Backspace" && e.metaKey && !field.value)) && items[current]) {
if ((e.key === "Delete" || (e.key === "Backspace" && e.metaKey)) && items[current]) {
e.preventDefault();
void askRemoveRecent(items[current]!.project);
return;
-12
Переглянути файл
@@ -137,18 +137,6 @@ describe("Welcome › Projects", () => {
expect(selectedName()).toBe("py-demo");
});
it("leaves Delete to the search text while the caret has text after it", async () => {
await renderWelcome();
const search = screen.getByLabelText("Search projects") as HTMLInputElement;
fireEvent.change(search, { target: { value: "acme" } });
search.setSelectionRange(1, 1);
fireEvent.keyDown(search, { key: "Delete" });
expect(screen.queryByRole("dialog", { name: "Remove Recent Project" })).toBeNull();
search.setSelectionRange(4, 4);
fireEvent.keyDown(search, { key: "Delete" });
expect(screen.getByRole("dialog", { name: "Remove Recent Project" })).toBeTruthy();
});
it("offers Open in New Window in the row menu when the action exists", async () => {
const dispose = registerActions([{ id: "file.openInNewWindow", title: "Open in New Window", run: () => {} }]);
await renderWelcome();
+1 -8
Переглянути файл
@@ -2478,12 +2478,5 @@
"Alignment": "Alignment",
"Align key-value pairs": "Align key-value pairs",
"Align consecutive assignments": "Align consecutive assignments",
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.",
"Are you sure you want to delete {name}?": "Are you sure you want to delete {name}?",
"Every project inside a trusted location is trusted without asking, unless it is a restricted project.": "Every project inside a trusted location is trusted without asking, unless it is a restricted project.",
"Restricted projects": "Restricted projects",
"These projects open in Restricted Mode, even inside a trusted location.": "These projects open in Restricted Mode, even inside a trusted location.",
"Trust": "Trust",
"{name} is hidden because {title} is off": "{name} is hidden because {title} is off",
"{name} did not exist at label '{label}'": "{name} did not exist at label '{label}'"
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines."
}
+2 -8
Переглянути файл
@@ -3793,6 +3793,7 @@
"(empty line)": "(空行)",
"Name cannot be empty": "名称不能为空",
"Every scope needs a name": "每个范围都需要名称",
"Every project inside a trusted location is trusted without asking.": "受信任的位置内的每个项目都会被信任,不再询问。",
"Scopes": "范围",
"Add Scope": "添加范围",
"Remove Scope": "移除范围",
@@ -8852,12 +8853,5 @@
"Alignment": "对齐",
"Align key-value pairs": "对齐键值对",
"Align consecutive assignments": "对齐连续赋值",
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。",
"Are you sure you want to delete {name}?": "确定要删除 {name} 吗?",
"Every project inside a trusted location is trusted without asking, unless it is a restricted project.": "受信任的位置内的每个项目都会被信任,不再询问;受限项目除外。",
"Restricted projects": "受限项目",
"These projects open in Restricted Mode, even inside a trusted location.": "这些项目即使位于受信任的位置内,也以受限模式打开。",
"Trust": "信任",
"{name} is hidden because {title} is off": "{name} 已隐藏,因为“{title}”已关闭",
"{name} did not exist at label '{label}'": "标签“{label}”时 {name} 尚不存在"
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。"
}
+2 -5
Переглянути файл
@@ -1,7 +1,6 @@
import { showBackgroundTasks } from "./StatusBar";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { isCancelled, isTauri } from "@/platform/ipc";
import { confirmProjectTrust } from "@/platform/projectTrust";
import { isTauri } from "@/platform/ipc";
import { closeProject, confirmLeaveProject, openProject, useProject } from "@/platform/project";
import { runSearchFieldCommand, showContextMenu } from "@/ui";
import { showCustomizeToolbar } from "./MainToolbarDialog";
@@ -33,12 +32,10 @@ export async function openProjectDialog() {
await executeAction("file.openProjectPath", path);
return;
}
if (!(await confirmLeaveProject())) return;
try {
await confirmProjectTrust(path, "local");
if (!(await confirmLeaveProject())) return;
await openProject(path);
} catch (e) {
if (isCancelled(e)) return;
notify({ level: "error", title: "Could not open project", body: e instanceof Error ? e.message : String(e) });
}
}