дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-17 15:15:40 +02:00
Порівняти коміти
8
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
ea6638b05e | ||
|
|
a91421c6e0 | ||
|
|
973f0a18a8 | ||
|
|
fb64f0cd26 | ||
|
|
34f2e18ff1 | ||
|
|
83a949ffe9 | ||
|
|
af8bd1afcd | ||
|
|
ce12f68613 |
No files matched your search
@@ -142,7 +142,7 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
}
|
||||
const FMT: &str = "{{json .}}";
|
||||
let (containers, images, volumes, networks) = std::thread::scope(|s| {
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK));
|
||||
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
|
||||
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
|
||||
@@ -226,6 +226,16 @@ fn lines<T: for<'de> Deserialize<'de>>(text: &str) -> impl Iterator<Item = T> +
|
||||
})
|
||||
}
|
||||
|
||||
/// The `docker ps --format` template: only the fields [`RawContainer`] reads. `{{json .}}`
|
||||
/// would also include `Size`, which makes the daemon compute every container's writable
|
||||
/// layer and can take tens of seconds.
|
||||
pub const PS_FORMAT: &str = concat!(
|
||||
r#"{"ID":{{json .ID}},"Names":{{json .Names}},"Image":{{json .Image}},"#,
|
||||
r#""Command":{{json .Command}},"State":{{json .State}},"Status":{{json .Status}},"#,
|
||||
r#""Ports":{{json .Ports}},"CreatedAt":{{json .CreatedAt}},"Labels":{{json .Labels}},"#,
|
||||
r#""Mounts":{{json .Mounts}},"Networks":{{json .Networks}}}"#,
|
||||
);
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawContainer {
|
||||
@@ -247,7 +257,7 @@ fn split_csv(raw: &str) -> Vec<String> {
|
||||
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// `docker ps -a --no-trunc --format '{{json .}}'`.
|
||||
/// `docker ps -a --no-trunc --format` [`PS_FORMAT`] (or `'{{json .}}'`).
|
||||
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
|
||||
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
|
||||
.map(|r| {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Parsing of recorded `docker … --format '{{json .}}'` output.
|
||||
|
||||
use ide_docker::{
|
||||
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
|
||||
parse_volumes,
|
||||
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
|
||||
parse_networks, parse_volumes,
|
||||
};
|
||||
|
||||
const PS: &str = include_str!("fixtures/ps.jsonl");
|
||||
@@ -10,6 +10,27 @@ const IMAGES: &str = include_str!("fixtures/images.jsonl");
|
||||
const VOLUMES: &str = include_str!("fixtures/volumes.jsonl");
|
||||
const NETWORKS: &str = include_str!("fixtures/networks.jsonl");
|
||||
|
||||
/// Fills `{{json .Field}}` placeholders of a `--format` template from a `{{json .}}` line.
|
||||
fn render(template: &str, line: &str) -> String {
|
||||
let fields: serde_json::Map<String, serde_json::Value> = serde_json::from_str(line).unwrap();
|
||||
let mut out = template.to_owned();
|
||||
while let Some(start) = out.find("{{json .") {
|
||||
let end = start + out[start..].find("}}").unwrap() + 2;
|
||||
let key = &out[start + "{{json .".len()..end - 2];
|
||||
let value = fields.get(key).unwrap_or_else(|| panic!("fixture lacks {key}"));
|
||||
out.replace_range(start..end, &value.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ps_format_carries_everything_the_parser_reads_but_size() {
|
||||
assert!(!PS_FORMAT.contains("Size"), "Size makes the daemon compute container sizes");
|
||||
let rendered: Vec<String> = PS.lines().filter(|l| l.starts_with('{')).map(|l| render(PS_FORMAT, l)).collect();
|
||||
assert_eq!(rendered.len(), 2);
|
||||
assert_eq!(parse_containers(&rendered.join("\n")), parse_containers(PS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn containers_with_compose_labels() {
|
||||
let c = parse_containers(PS);
|
||||
|
||||
@@ -529,9 +529,12 @@ pub enum CheckoutOutcome {
|
||||
LocalChanges {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// These untracked files (repository-relative paths) would be overwritten.
|
||||
/// These untracked files (repository-relative paths) would be overwritten by the
|
||||
/// checkout; with `removed`, they would be removed by it (tracked here, absent
|
||||
/// from the target).
|
||||
UntrackedFiles {
|
||||
files: Vec<String>,
|
||||
removed: bool,
|
||||
},
|
||||
/// Local branch `local` has commits that remote branch `remote` does not.
|
||||
LocalBranchAhead {
|
||||
|
||||
@@ -771,9 +771,14 @@ fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "local changes to the following files would be overwritten")
|
||||
}
|
||||
|
||||
/// Untracked files git refuses to overwrite, from its error message.
|
||||
fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "untracked working tree files would be")
|
||||
/// Untracked files git refuses to lose, from its error message: they would be *removed*
|
||||
/// by the checkout (tracked here, absent from the target) or *overwritten* by it (present
|
||||
/// in the target). Returns the files and whether they would be removed.
|
||||
fn refused_untracked(stderr: &str) -> Option<(Vec<String>, bool)> {
|
||||
if let Some(files) = listed_files(stderr, "untracked working tree files would be removed") {
|
||||
return Some((files, true));
|
||||
}
|
||||
Some((listed_files(stderr, "untracked working tree files would be")?, false))
|
||||
}
|
||||
|
||||
/// The branch git refused to check out or update because another worktree has it, from
|
||||
@@ -840,8 +845,8 @@ pub(crate) fn checkout_with(
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
|
||||
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
|
||||
}
|
||||
if let Some(files) = overwritten_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files });
|
||||
if let Some((files, removed)) = refused_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files, removed });
|
||||
}
|
||||
let Some(files) = overwritten_files(&stderr) else {
|
||||
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
|
||||
|
||||
@@ -2074,12 +2074,37 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("other", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()], removed: false });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("dir/new.txt"), "mine\n");
|
||||
}
|
||||
}
|
||||
|
||||
/// Untracked on disk but tracked on the current branch and gone from the target
|
||||
/// (as after `git rm --cached`): git refuses to *remove* the file, and the outcome
|
||||
/// says so (#3980).
|
||||
#[test]
|
||||
fn checkout_reports_untracked_files_it_would_remove() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("TEST.md", "hi\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["checkout", "-q", "-b", "feature/x"]);
|
||||
fx.git(&["rm", "-q", "TEST.md"]);
|
||||
fx.commit_all("remove TEST.md on feature/x");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
fx.git(&["rm", "--cached", "TEST.md"]);
|
||||
fx.write("TEST.md", "local dirty version\n");
|
||||
let repo = fx.repo();
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
// The refusal leaves the repository untouched, so both modes see the same state.
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("feature/x", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["TEST.md".into()], removed: true });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("TEST.md"), "local dirty version\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reword_keeps_local_changes_and_can_be_undone() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
@@ -180,29 +180,6 @@ unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: S
|
||||
|
||||
static APP: std::sync::OnceLock<AppHandle> = std::sync::OnceLock::new();
|
||||
|
||||
/// Escape the page leaves unhandled reaches the window as `cancelOperation:`, on which NSWindow
|
||||
/// leaves full screen, so pressing Escape once more after closing a popup left full screen. The
|
||||
/// IDE's windows answer it with nothing; View › Appearance › Toggle Full Screen (⌃⌘F) leaves it.
|
||||
pub fn keep_full_screen_on_escape() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| unsafe {
|
||||
let Some(class) = AnyClass::get(c"TaoWindow") else {
|
||||
tracing::warn!("no TaoWindow class: Escape leaves full screen");
|
||||
return;
|
||||
};
|
||||
let imp: Imp = std::mem::transmute(ignore_cancel_operation as CancelOperation);
|
||||
let class = class as *const AnyClass as *mut AnyClass;
|
||||
let added = objc2::ffi::class_addMethod(class, objc2::sel!(cancelOperation:), imp, c"v@:@".as_ptr());
|
||||
if !added.as_bool() {
|
||||
tracing::warn!("could not handle cancelOperation:");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type CancelOperation = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject);
|
||||
|
||||
unsafe extern "C-unwind" fn ignore_cancel_operation(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) {}
|
||||
|
||||
/// Whether AppKit is handling a key press right now. A menu item performed at this point
|
||||
/// was chosen by its key equivalent: a click, arrow keys plus Return and accessibility
|
||||
/// presses all run with a non-key current event.
|
||||
|
||||
@@ -730,8 +730,6 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
decorate_csd(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::page_swipe::install(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::macos::keep_full_screen_on_escape();
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window, app.try_state::<WindowsState>().is_some_and(|w| w.opens_project(window.label())));
|
||||
|
||||
@@ -3293,8 +3293,12 @@ export type CheckoutOptions = {
|
||||
export type CheckoutOutcome = { kind: "done" } |
|
||||
/** These local changes (repository-relative paths) would be overwritten. */
|
||||
{ kind: "localChanges"; files: string[] } |
|
||||
/** These untracked files (repository-relative paths) would be overwritten. */
|
||||
{ kind: "untrackedFiles"; files: string[] } |
|
||||
/**
|
||||
* These untracked files (repository-relative paths) would be overwritten by the
|
||||
* checkout; with `removed`, they would be removed by it (tracked here, absent
|
||||
* from the target).
|
||||
*/
|
||||
{ kind: "untrackedFiles"; files: string[]; removed: boolean } |
|
||||
/** Local branch `local` has commits that remote branch `remote` does not. */
|
||||
{ kind: "localBranchAhead"; local: string; remote: string } |
|
||||
/**
|
||||
|
||||
@@ -57,6 +57,7 @@ import { stringClipboard } from "./stringClipboard";
|
||||
import { filterCopiedText } from "./clipboard";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { codeLensPositions } from "./codeLens";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
|
||||
@@ -452,9 +453,10 @@ export function resetConfiguredEditorsFontZoom(origin: EditorView): void {
|
||||
/** Exported for tests: the ⌘/Ctrl+wheel handler of the prefs compartment. */
|
||||
export const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepConfiguredEditorsFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepConfiguredEditorsFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getIndentation } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("vue language mode", () => {
|
||||
@@ -23,4 +25,31 @@ describe("vue language mode", () => {
|
||||
expect(tree).toContain("Declaration");
|
||||
expect(tree).not.toContain("SassVariableName");
|
||||
});
|
||||
|
||||
it("indents the top-level <template>'s children only, not <script setup> or <style> code", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
|
||||
const doc = [
|
||||
"<template>",
|
||||
"<div>",
|
||||
"</div>",
|
||||
"</template>",
|
||||
'<script setup lang="ts">',
|
||||
"const a = 1",
|
||||
"function f() {",
|
||||
"return a",
|
||||
"}",
|
||||
"</script>",
|
||||
"<style>",
|
||||
".a { color: red; }",
|
||||
"</style>",
|
||||
].join("\n");
|
||||
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
|
||||
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
|
||||
expect(indent(2)).toBe(2);
|
||||
expect(indent(6)).toBe(0);
|
||||
expect(indent(7)).toBe(0);
|
||||
expect(indent(8)).toBe(2);
|
||||
expect(indent(10)).toBe(0);
|
||||
expect(indent(12)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -4,24 +4,38 @@
|
||||
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
|
||||
* colours.
|
||||
*/
|
||||
import { LanguageSupport } from "@codemirror/language";
|
||||
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { sassLanguage } from "@codemirror/lang-sass";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
|
||||
/**
|
||||
* WebStorm's Vue code style indents the children of the top-level `<template>` only: code in
|
||||
* `<script setup>` or `<style>` starts at the margin, as `npm create vue` writes it.
|
||||
*/
|
||||
function elementIndent(context: TreeIndentContext): number | null {
|
||||
const after = /^(\s*)(<\/)?/.exec(context.textAfter)!;
|
||||
const node = context.node;
|
||||
if (node.to <= context.pos + after[0].length) return context.continue();
|
||||
const tag = node.firstChild?.getChild("TagName");
|
||||
const flat =
|
||||
node.parent?.name === "Document" && !!tag && context.state.sliceDoc(tag.from, tag.to).toLowerCase() !== "template";
|
||||
return context.lineIndent(node.from) + (after[2] || flat ? 0 : context.unit);
|
||||
}
|
||||
|
||||
export function vueLanguage(): LanguageSupport {
|
||||
return vue({
|
||||
base: html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
],
|
||||
}),
|
||||
const base = html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
],
|
||||
});
|
||||
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
|
||||
return vue({ base: new LanguageSupport(language, base.support) });
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { EditorView } from "@codemirror/view";
|
||||
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
|
||||
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
|
||||
|
||||
const zoomOf = (view: EditorView) => view.state.field(fontZoom, false);
|
||||
|
||||
@@ -19,6 +20,7 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
return view;
|
||||
};
|
||||
beforeEach(() => {
|
||||
resetWheelZoomGesture();
|
||||
resetAllEditorsFontZoom();
|
||||
useProject.setState({ settings: null });
|
||||
});
|
||||
@@ -45,6 +47,16 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
expect(zoomOf(second)).toBe(-1);
|
||||
});
|
||||
|
||||
it("doesn't zoom from the inertia of a scroll when ⌘/Ctrl is pressed during it", () => {
|
||||
const view = makeView();
|
||||
const plain = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -40 });
|
||||
view.contentDOM.dispatchEvent(plain);
|
||||
const coasting = new WheelEvent("wheel", { bubbles: true, cancelable: true, metaKey: true, deltaY: -20 });
|
||||
view.contentDOM.dispatchEvent(coasting);
|
||||
expect(coasting.defaultPrevented).toBe(false);
|
||||
expect(zoomOf(view)).toBe(0);
|
||||
});
|
||||
|
||||
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
|
||||
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
|
||||
const first = makeView();
|
||||
|
||||
@@ -35,9 +35,14 @@ const hintField = StateField.define<Hint | null>({
|
||||
pos: h.pos,
|
||||
above: true,
|
||||
strictSide: false,
|
||||
create: () => {
|
||||
create: (view) => {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `cm-lsp-hint cm-lsp-hint-${h.tone}`;
|
||||
// Clicked or focused (a value tree expanded in it): the user works in the hint, so
|
||||
// it stays until an edit, a caret move or Escape.
|
||||
const keep = () => clearTimeout(timers.get(view));
|
||||
dom.addEventListener("pointerdown", keep);
|
||||
dom.addEventListener("focusin", keep);
|
||||
dom.setAttribute("role", "status");
|
||||
if (h.pending) dom.dataset.pending = "true";
|
||||
Object.assign(dom.dataset, h.data);
|
||||
@@ -63,7 +68,8 @@ const timers = new WeakMap<EditorView, ReturnType<typeof setTimeout>>();
|
||||
export function showHint(
|
||||
view: EditorView,
|
||||
content: Hint["content"],
|
||||
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number; pending?: boolean; data?: Hint["data"] } = {},
|
||||
/** `timeout: null`: the hint stays until an edit, a caret move or Escape. */
|
||||
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number | null; pending?: boolean; data?: Hint["data"] } = {},
|
||||
) {
|
||||
const pos = opts.pos ?? view.state.selection.main.head;
|
||||
const effects: StateEffect<unknown>[] = [
|
||||
@@ -72,6 +78,7 @@ export function showHint(
|
||||
if (!view.state.field(hintField, false)) effects.push(StateEffect.appendConfig.of(hintExtension()));
|
||||
view.dispatch({ effects });
|
||||
clearTimeout(timers.get(view));
|
||||
if (opts.timeout === null) return;
|
||||
timers.set(
|
||||
view,
|
||||
// Also while the view is hidden: it would show the hint again when its tab is shown.
|
||||
|
||||
@@ -3,6 +3,7 @@ import { create } from "zustand";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerFontZoomSurface, useEditorShown, useEditorTabId, useToolWindowShown } from "@/workbench/contributions";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
const MIN_FONT_ZOOM = -6;
|
||||
const MAX_FONT_ZOOM = 36;
|
||||
@@ -74,10 +75,12 @@ export function useAgentFontZoomSurface(
|
||||
if (!active || !el) return;
|
||||
const step = (delta: number) => stepAgentSurfaceFontZoom(surfaceKey, delta);
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
step(e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) step(zoom);
|
||||
};
|
||||
el.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
const release = registerFontZoomSurface(el, step, { isolated: true });
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const opened = vi.hoisted(() => [] as string[]);
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const doc = (path: string) => Promise.resolve({ status: "ok", data: { id: 3, path } });
|
||||
return {
|
||||
...ipc,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...ipc.commands,
|
||||
docOpen: (path: string) => (opened.push(`file ${path}`), doc(path)),
|
||||
docOpenVirtual: (uri: string) => (opened.push(`virtual ${uri}`), doc(uri)),
|
||||
docClose: () => Promise.resolve(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { withDocument } = await import("./ipc");
|
||||
|
||||
describe("withDocument", () => {
|
||||
it("opens a library type through its language server, a project file from disk", async () => {
|
||||
const uri = "jdt://contents/java.base/java.util/UUID.class?=demo/%5C/jdk%5C/lib%5C/jrt-fs.jar%60java.base";
|
||||
await withDocument(uri, async (doc) => doc);
|
||||
await withDocument("/p/src/App.java", async (doc) => doc);
|
||||
expect(opened).toEqual([`virtual ${uri}`, "file /p/src/App.java"]);
|
||||
});
|
||||
});
|
||||
@@ -134,7 +134,8 @@ export async function readManyFileLines(
|
||||
export async function withDocument<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
|
||||
const open = editorsFor(path)[0];
|
||||
if (open) return fn(open.ctx.doc);
|
||||
const info = await lspRequest(() => commands.docOpen(path));
|
||||
// Library types (`jdt://…`) are documents the language server provides, not files on disk.
|
||||
const info = await lspRequest(() => (isVirtualUri(path) ? commands.docOpenVirtual(path) : commands.docOpen(path)));
|
||||
try {
|
||||
return await fn(info.id);
|
||||
} finally {
|
||||
|
||||
@@ -176,6 +176,24 @@ describe("run config → launch config", () => {
|
||||
expect(extra(uv)).toMatchObject({ python: ["uv", "run", "python"], debugLauncherPython: "python" });
|
||||
});
|
||||
|
||||
it("debugpy: a Windows venv interpreter or tool path debugs with that interpreter", () => {
|
||||
usePlatform.setState({ os: "windows" });
|
||||
const venv = "C:\\work\\app\\.venv\\Scripts\\";
|
||||
const script = launchConfigFor(
|
||||
rc({ kind: "python", command: `${venv}python.exe`, args: ["main.py"], debugAdapter: "debugpy" }),
|
||||
"C:/work/app",
|
||||
)!;
|
||||
expect(extra(script).python).toBe(`${venv}python.exe`);
|
||||
expect(extra(script).module).toBeUndefined();
|
||||
expect(script.program).toBe("C:/work/app/main.py");
|
||||
|
||||
const pytest = launchConfigFor(
|
||||
rc({ kind: "pytest", command: `${venv}pytest.exe`, args: ["-x"], debugAdapter: "debugpy" }),
|
||||
"C:/work/app",
|
||||
)!;
|
||||
expect(extra(pytest)).toMatchObject({ module: "pytest", python: `${venv}python.exe` });
|
||||
});
|
||||
|
||||
it("js-debug: npm scripts run through the package manager, node scripts directly", () => {
|
||||
const npm = launchConfigFor(
|
||||
rc({ kind: "npm", command: "pnpm", args: ["run", "dev"], cwd: "web", debugAdapter: "js-debug" }),
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { DebugSessionId, Variable } from "@/bindings";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { valueHint } from "../editor/valueTooltip";
|
||||
|
||||
vi.mock("../ui/ValueHintTree", () => ({
|
||||
mountValueTree: (host: HTMLElement) => {
|
||||
host.append(Object.assign(document.createElement("div"), { className: "tree" }));
|
||||
return { unmount: () => {} };
|
||||
},
|
||||
}));
|
||||
|
||||
const session = 7 as DebugSessionId;
|
||||
const order: Variable = {
|
||||
name: "order",
|
||||
value: "Order@12",
|
||||
typeName: "Order",
|
||||
variablesReference: 3,
|
||||
evaluateName: "order",
|
||||
} as Variable;
|
||||
let view: EditorView;
|
||||
const expand = () => {
|
||||
const button = document.querySelector<HTMLButtonElement>("[aria-label='Expand value']")!;
|
||||
button.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
|
||||
button.click();
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
view = new EditorView({ state: EditorState.create({ doc: "order.total" }), parent: document.body });
|
||||
});
|
||||
afterEach(() => {
|
||||
view.destroy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("value hint", () => {
|
||||
it("keeps a hint whose value was expanded past the hint's timeout", () => {
|
||||
showHint(view, () => valueHint("order", order, session), { pos: 0, timeout: 4000 });
|
||||
expand();
|
||||
expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull();
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("hands an expanded hover hint to its pin instead of growing in place", () => {
|
||||
const pin = vi.fn();
|
||||
showHint(view, () => valueHint("order", order, session, 400, { pin }), { pos: 0 });
|
||||
expand();
|
||||
expect(pin).toHaveBeenCalled();
|
||||
expect(document.querySelector(".tree")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,11 +5,11 @@
|
||||
*/
|
||||
import type { EditorState, Extension } from "@codemirror/state";
|
||||
import type { DebugSessionId, Variable } from "@/bindings";
|
||||
import { hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { closeHoverTooltips, hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { hideHint, showHint } from "@/editor/lsp/hint";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { navigationModifierHeld } from "@/platform/navigationModifier";
|
||||
import { activeSession, evaluate } from "../state";
|
||||
import { activeSession, evaluate, useDebug } from "../state";
|
||||
import { inlineValue, shownValue } from "../values";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { iconMarkup, selectableText } from "@/ui";
|
||||
@@ -45,10 +45,20 @@ export function valueHint(
|
||||
value: Variable,
|
||||
session: DebugSessionId,
|
||||
max: number | null = 400,
|
||||
opts: { expanded?: boolean; pin?: () => void } = {},
|
||||
): { dom: HTMLElement; destroy: () => void } {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `${styles.valueTooltip} ${selectableText}`;
|
||||
let tree: { unmount(): void } | null = null;
|
||||
const expandTree = () => {
|
||||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||||
dom.replaceChildren();
|
||||
tree = mountValueTree(dom, expression, value, session);
|
||||
};
|
||||
if (value.variablesReference > 0 && opts.expanded) {
|
||||
expandTree();
|
||||
return { dom, destroy: () => tree?.unmount() };
|
||||
}
|
||||
if (value.variablesReference > 0) {
|
||||
// IDEA's value hint: the "+" expands the object into a variables tree in place.
|
||||
const expand = document.createElement("button");
|
||||
@@ -60,10 +70,9 @@ export function valueHint(
|
||||
expand.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
expand.addEventListener("click", () => {
|
||||
if (tree) return;
|
||||
if (opts.pin) return opts.pin();
|
||||
expand.remove();
|
||||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||||
dom.replaceChildren();
|
||||
tree = mountValueTree(dom, expression, value, session);
|
||||
expandTree();
|
||||
});
|
||||
dom.append(expand);
|
||||
}
|
||||
@@ -109,15 +118,48 @@ export function valueTooltip(): Extension {
|
||||
pos: expr.from,
|
||||
end: expr.to,
|
||||
above: true,
|
||||
create: () => {
|
||||
return valueHint(expr.text, value, session.id);
|
||||
},
|
||||
create: (view) =>
|
||||
valueHint(expr.text, value, session.id, 400, {
|
||||
// The tree outgrows the hint and may move to the other side of the line, away from the
|
||||
// mouse, which closed the hover tooltip before it could be reached. Like IDEA's value
|
||||
// popup it stays until Escape, a click in the editor or the next step.
|
||||
pin: () => {
|
||||
view.dispatch({ effects: closeHoverTooltips });
|
||||
showHint(view, () => pinnedTree(view, expr.text, value, session.id), {
|
||||
pos: expr.from,
|
||||
timeout: null,
|
||||
});
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
{ hoverTime: BASE_HOVER },
|
||||
);
|
||||
}
|
||||
|
||||
/** An expanded value tree, closed when its session leaves the stop it was evaluated in. */
|
||||
function pinnedTree(view: EditorView, expression: string, value: Variable, session: DebugSessionId) {
|
||||
const stop = useDebug.getState().stopSeq;
|
||||
const unsubscribe = useDebug.subscribe((s) => {
|
||||
if (s.stopSeq !== stop || s.sessions[session]?.status !== "paused") hideHint(view);
|
||||
});
|
||||
const hint = valueHint(expression, value, session, 400, { expanded: true });
|
||||
// The tree has the focus, so the editor's Escape doesn't reach the hint.
|
||||
hint.dom.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape" || e.defaultPrevented) return;
|
||||
e.preventDefault();
|
||||
hideHint(view);
|
||||
view.focus();
|
||||
});
|
||||
return {
|
||||
dom: hint.dom,
|
||||
destroy: () => {
|
||||
unsubscribe();
|
||||
hint.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const SELECTION_DELAY = 400;
|
||||
const MAX_SELECTION = 200;
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ function cargoLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
|
||||
};
|
||||
}
|
||||
|
||||
const PYTHON_NAME = /^python[\d.]*(\.exe)?$/;
|
||||
const PYTHON_NAME = /^python[\d.]*(\.exe)?$/i;
|
||||
|
||||
/** `python` on Windows (`python3` is at most a Store alias there, and venvs have no `python3.exe`), `python3` elsewhere. */
|
||||
function systemPython(): string {
|
||||
@@ -85,10 +85,10 @@ function systemPython(): string {
|
||||
|
||||
function pythonFor(rc: RunConfig, cwd: string): string {
|
||||
const cmd = rc.command;
|
||||
const name = cmd.split("/").pop() ?? cmd;
|
||||
if (PYTHON_NAME.test(name)) return resolveCommand(cmd, cwd);
|
||||
// A venv tool such as `.venv/bin/pytest`: use the interpreter next to it.
|
||||
if (cmd.includes("/")) return resolveCommand(cmd.slice(0, cmd.lastIndexOf("/") + 1) + "python", cwd);
|
||||
if (PYTHON_NAME.test(commandName(cmd))) return resolveCommand(cmd, cwd);
|
||||
// A venv tool such as `.venv/bin/pytest` or `.venv\Scripts\pytest.exe`: use the interpreter next to it.
|
||||
const dir = cmd.slice(0, Math.max(cmd.lastIndexOf("/"), cmd.lastIndexOf("\\")) + 1);
|
||||
if (dir) return resolveCommand(dir + (hostOs() === "windows" ? "python.exe" : "python"), cwd);
|
||||
return systemPython();
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ function debugpyLaunch(rc: RunConfig, cwd: string): LaunchConfig {
|
||||
subProcess: dbg.python.attachSubprocess,
|
||||
};
|
||||
if (dbg.python.gevent) extra.gevent = true;
|
||||
const name = (rc.command.split("/").pop() ?? rc.command).replace(/\.exe$/, "");
|
||||
const name = commandName(rc.command);
|
||||
let args = rc.args;
|
||||
let tool: string | null = PYTHON_NAME.test(name) ? null : name;
|
||||
if (PYTHON_RUNNERS.has(name) && args[0] === "run" && args[1]) {
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
openPluginDiff,
|
||||
type PluginContentEditorData,
|
||||
} from "./contentTab";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export function pluginContentEditorTitle(input: EditorInput): string {
|
||||
const s = sessions.get(input.key);
|
||||
@@ -171,9 +172,10 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
|
||||
|
||||
const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -26,6 +26,7 @@ import { boundedLog, type PluginLogEditorData } from "./logTab";
|
||||
import { logTabPtyBackend, webPtyBackend } from "./ptyBackend";
|
||||
import { outputKey, usePluginOutput } from "./outputStore";
|
||||
import { ptyBridge } from "./ptyBridge";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export const PLUGIN_LOG_EDITOR_KIND = "pluginLog";
|
||||
|
||||
@@ -42,9 +43,10 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
|
||||
|
||||
const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ import logStyles from "@/ui/LogPane.module.css";
|
||||
import { editorService, type EditorInput } from "@/workbench/contributions";
|
||||
import { isRunning } from "./model";
|
||||
import { connectionState, endpointOf, errorMessage, useServices } from "./store";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export const DOCKER_LOG_EDITOR_KIND = "dockerLog";
|
||||
|
||||
@@ -71,9 +72,10 @@ function isActionStroke(stroke: string | null, actionId: string): boolean {
|
||||
|
||||
const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
type TerminalFontSettings,
|
||||
MIN_CONTRAST_RATIO,
|
||||
} from "./theme";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
export interface TerminalSearchOptions {
|
||||
caseSensitive: boolean;
|
||||
@@ -464,10 +465,12 @@ export class TerminalSession {
|
||||
}
|
||||
|
||||
private onWheelZoom = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.stepFontSize(e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) this.stepFontSize(zoom);
|
||||
};
|
||||
|
||||
private onMiddleClick = (e: MouseEvent) => {
|
||||
|
||||
@@ -219,6 +219,34 @@ it("does not open the worktree when the checkout offer is declined", async () =>
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names the files git would remove when untracked ones block the checkout", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["TEST.md"], removed: true }));
|
||||
await checkoutBranch("feature/x");
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body: expect.stringContaining(
|
||||
"The following untracked working tree files would be removed by checkout:\nTEST.md",
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("still says overwritten when untracked files would be overwritten", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "untrackedFiles", files: ["dir/new.txt"], removed: false }));
|
||||
await checkoutBranch("feature/x");
|
||||
expect(mocks.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
level: "error",
|
||||
body: expect.stringContaining(
|
||||
"The following untracked working tree files would be overwritten by checkout:\ndir/new.txt",
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the branch when the worktree question is turned down", async () => {
|
||||
mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")]));
|
||||
mocks.confirm.mockResolvedValue(false);
|
||||
|
||||
@@ -104,11 +104,17 @@ async function performCheckout(
|
||||
return true;
|
||||
case "untrackedFiles": {
|
||||
const files = outcome.files.join("\n");
|
||||
// git refuses untracked files in two ways: they would be overwritten by the
|
||||
// checkout (present in the target), or removed by it (tracked here, absent
|
||||
// from the target); each names its files the way git's own message does.
|
||||
const body = outcome.removed
|
||||
? tx`The following untracked working tree files would be removed by checkout:\n${files}\nPlease move or remove them before you switch branches.`
|
||||
: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`;
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
title: "Untracked files prevent checkout",
|
||||
body: tx`The following untracked working tree files would be overwritten by checkout:\n${files}\nPlease move or remove them before you switch branches.`,
|
||||
body,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
|
||||
import styles from "./Markdown.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
/** Loaded local images by absolute path (data URLs), shared by all previews. */
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
@@ -380,11 +381,13 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
if ((e.target as Element | null)?.closest?.('.mermaid-output[data-zoomed="true"]')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
stepMarkdownPreviewFontZoom(path, root, e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom);
|
||||
};
|
||||
root.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
const release = registerFontZoomSurface(root, (delta) => stepMarkdownPreviewFontZoom(path, root, delta));
|
||||
|
||||
@@ -28,6 +28,7 @@ import { call, commands, isTauri } from "./platform/ipc";
|
||||
import { hideSplash } from "./platform/splash";
|
||||
import { prefetchLazyComponents } from "./ui";
|
||||
import { installWindowDrag } from "./workbench/window-drag";
|
||||
import { installFullscreenEscapeGuard } from "./workbench/fullscreenEscape";
|
||||
|
||||
if (import.meta.env.DEV && isTauri()) {
|
||||
// The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux
|
||||
@@ -71,6 +72,8 @@ if (aux?.kind === "settings") {
|
||||
activateSecondaryWindow();
|
||||
activateDeploymentWindowFeatures(aux.parent);
|
||||
} else {
|
||||
// Before the features' and the dispatcher's key handlers: it wraps the Escape they see.
|
||||
installFullscreenEscapeGuard();
|
||||
activateWorkbench();
|
||||
// `vite build --mode perf` is a production bundle for the performance harness (`perf/`).
|
||||
const perfBuild = import.meta.env.MODE === "perf";
|
||||
|
||||
@@ -7001,6 +7001,7 @@
|
||||
"Choose Declaration": "选择声明",
|
||||
"Go to mapping: {target}": "跳转到映射:{target}",
|
||||
"Untracked files prevent checkout": "未跟踪的文件阻止了签出",
|
||||
"The following untracked working tree files would be removed by checkout:\n{files}\nPlease move or remove them before you switch branches.": "签出将删除以下未跟踪的工作区文件:\n{files}\n请在切换分支前移动或删除它们。",
|
||||
"The following untracked working tree files would be overwritten by checkout:\n{files}\nPlease move or remove them before you switch branches.": "签出将覆盖以下未跟踪的工作区文件:\n{files}\n请在切换分支前移动或删除它们。",
|
||||
"Select Target Changelist": "选择目标更改列表",
|
||||
"Rebase undone": "已撤销变基",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { resetWheelZoomGesture, wheelZoomStep } from "./wheelZoom";
|
||||
|
||||
let t = 0;
|
||||
const wheel = (deltaY: number, mod = true, gap = 16) => {
|
||||
t += gap;
|
||||
return wheelZoomStep({ deltaY, metaKey: mod, ctrlKey: false, timeStamp: t });
|
||||
};
|
||||
|
||||
describe("wheelZoomStep", () => {
|
||||
beforeEach(() => {
|
||||
resetWheelZoomGesture();
|
||||
t = 1000;
|
||||
});
|
||||
|
||||
it("zooms in and out with ⌘ held from the start of the gesture", () => {
|
||||
expect(wheel(-4)).toBe(1);
|
||||
expect(wheel(-6)).toBe(1);
|
||||
expect(wheel(10, true, 500)).toBe(-1);
|
||||
});
|
||||
|
||||
it("leaves plain scrolling alone", () => {
|
||||
expect(wheel(-10, false)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps scrolling the inertia of a plain scroll when ⌘ is pressed during it", () => {
|
||||
expect(wheel(-40, false)).toBeNull();
|
||||
expect(wheel(-30)).toBeNull();
|
||||
expect(wheel(-20)).toBeNull();
|
||||
expect(wheel(-10, true, 500)).toBe(1);
|
||||
});
|
||||
|
||||
it("stops zooming once the deltas decay like inertia, without scrolling", () => {
|
||||
for (const d of [-8, -12, -15]) expect(wheel(d)).toBe(1);
|
||||
expect(wheel(-14)).toBe(1);
|
||||
expect(wheel(-12)).toBe(1);
|
||||
expect(wheel(-9)).toBe(1);
|
||||
expect(wheel(-6)).toBe(0);
|
||||
expect(wheel(-4)).toBe(0);
|
||||
expect(wheel(-5)).toBe(0);
|
||||
});
|
||||
|
||||
it("never swallows a plain wheel event, even during a zoom gesture", () => {
|
||||
expect(wheel(-10)).toBe(1);
|
||||
expect(wheel(-10, false)).toBeNull();
|
||||
});
|
||||
|
||||
it("gives the same answer for repeated calls with one event", () => {
|
||||
const e = { deltaY: -10, metaKey: true, ctrlKey: false, timeStamp: 5000 };
|
||||
expect(wheelZoomStep(e)).toBe(1);
|
||||
expect(wheelZoomStep(e)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* ⌘/Ctrl+wheel font zoom that ignores scroll inertia.
|
||||
*
|
||||
* WebViews don't expose macOS momentum phases, so a gesture is a run of wheel events
|
||||
* less than `GESTURE_GAP_MS` apart (momentum continues the run of the swipe that started it).
|
||||
* A run that started without ⌘/Ctrl (a scroll still coasting when ⌘ is pressed) never zooms
|
||||
* and keeps scrolling; a run that started with it stops zooming (and scrolling) once the deltas
|
||||
* keep shrinking, which is the inertia after the fingers left the trackpad. A wheel event
|
||||
* without ⌘/Ctrl always scrolls.
|
||||
*/
|
||||
|
||||
const GESTURE_GAP_MS = 150;
|
||||
/** Consecutive shrinking deltas after which the rest of the run is inertia. */
|
||||
const INERTIA_SHRINKS = 4;
|
||||
|
||||
type WheelLike = Pick<WheelEvent, "deltaY" | "metaKey" | "ctrlKey" | "timeStamp">;
|
||||
|
||||
let lastTime = Number.NEGATIVE_INFINITY;
|
||||
let run = { zoom: false, prev: 0, shrinks: 0, inertia: false };
|
||||
let lastEvent: WheelLike | null = null;
|
||||
let lastResult: number | null = null;
|
||||
|
||||
/**
|
||||
* The font zoom step for a wheel event: `1` / `-1` to zoom in / out, `0` for a ⌘/Ctrl
|
||||
* event of a zoom gesture that must neither zoom nor scroll (its inertia), `null` for one
|
||||
* that isn't a zoom (scroll as usual), which includes every event without ⌘/Ctrl. Repeated calls for one event agree.
|
||||
*/
|
||||
export function wheelZoomStep(e: WheelLike): number | null {
|
||||
if (e === lastEvent) return lastResult;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
const abs = Math.abs(e.deltaY);
|
||||
if (e.timeStamp - lastTime > GESTURE_GAP_MS) {
|
||||
run = { zoom: mod, prev: abs, shrinks: 0, inertia: false };
|
||||
} else {
|
||||
run.shrinks = abs < run.prev ? run.shrinks + 1 : 0;
|
||||
run.prev = abs;
|
||||
if (run.shrinks >= INERTIA_SHRINKS) run.inertia = true;
|
||||
}
|
||||
lastTime = e.timeStamp;
|
||||
lastEvent = e;
|
||||
lastResult = !mod || !run.zoom ? null : e.deltaY === 0 || run.inertia ? 0 : e.deltaY < 0 ? 1 : -1;
|
||||
return lastResult;
|
||||
}
|
||||
|
||||
// Track every wheel event, not only those reaching a zoom surface, so a scroll that started
|
||||
// elsewhere and coasts into one is still known as a scroll.
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("wheel", (e) => void wheelZoomStep(e), {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Tests: forget the current gesture. */
|
||||
export function resetWheelZoomGesture(): void {
|
||||
lastTime = Number.NEGATIVE_INFINITY;
|
||||
lastEvent = null;
|
||||
lastResult = null;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { installFullscreenEscapeGuard } from "./fullscreenEscape";
|
||||
|
||||
let fullscreen = true;
|
||||
let dispose = () => {};
|
||||
const escape = (target: EventTarget) => {
|
||||
const e = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
|
||||
target.dispatchEvent(e);
|
||||
return e;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
fullscreen = true;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
dispose = installFullscreenEscapeGuard(window, () => fullscreen);
|
||||
});
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
describe("Escape in full screen", () => {
|
||||
it("is marked handled when nothing handles it, so the window stays in full screen", () => {
|
||||
expect(escape(document.body).defaultPrevented).toBe(true);
|
||||
});
|
||||
|
||||
it("is marked handled when a handler stops it", () => {
|
||||
const popup = document.body.appendChild(document.createElement("div"));
|
||||
popup.addEventListener("keydown", (e) => e.stopPropagation());
|
||||
expect(escape(popup).defaultPrevented).toBe(true);
|
||||
// The next key press is not affected by a listener left behind.
|
||||
fullscreen = false;
|
||||
expect(escape(document.body).defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("reaches other handlers not yet default-prevented", () => {
|
||||
let seen: boolean | null = null;
|
||||
const onKey = (e: KeyboardEvent) => (seen = e.defaultPrevented);
|
||||
window.addEventListener("keydown", onKey);
|
||||
escape(document.body);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
expect(seen).toBe(false);
|
||||
});
|
||||
|
||||
it("is left alone outside full screen and on other systems", () => {
|
||||
fullscreen = false;
|
||||
expect(escape(document.body).defaultPrevented).toBe(false);
|
||||
fullscreen = true;
|
||||
usePlatform.setState({ os: "windows" });
|
||||
expect(escape(document.body).defaultPrevented).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* macOS: an Escape key press the page leaves unhandled (not default-prevented) goes back from
|
||||
* WebKit to AppKit as the web view's `cancelOperation:`, and AppKit answers it in a full-screen
|
||||
* window by leaving full screen, so pressing Escape once more after closing a popup dropped the
|
||||
* IDE out of full screen. While this window is in full screen, Escape is marked handled after
|
||||
* everything else has seen it; View › Appearance › Toggle Full Screen (⌃⌘F) leaves full screen.
|
||||
*/
|
||||
import { commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
|
||||
/** Installs the guard on `target`; `isFullscreen` is this window's state (tests pass their own). */
|
||||
export function installFullscreenEscapeGuard(
|
||||
target: Window = window,
|
||||
isFullscreen: () => boolean = trackFullscreen(),
|
||||
): () => void {
|
||||
const onCapture = (e: KeyboardEvent) => {
|
||||
if (e.key !== "Escape" || e.isComposing || usePlatform.getState().os !== "macos" || !isFullscreen()) return;
|
||||
// Runs last in the bubble phase: handlers that check `defaultPrevented` see the event as it was.
|
||||
const handled = () => e.preventDefault();
|
||||
target.addEventListener("keydown", handled, { once: true });
|
||||
// A handler that stops the event has handled it; the bubble listener above won't run then.
|
||||
for (const name of ["stopPropagation", "stopImmediatePropagation"] as const) {
|
||||
const stop = e[name].bind(e);
|
||||
e[name] = () => {
|
||||
target.removeEventListener("keydown", handled);
|
||||
e.preventDefault();
|
||||
stop();
|
||||
};
|
||||
}
|
||||
};
|
||||
// Capture on the window before anything else is installed: it runs first.
|
||||
target.addEventListener("keydown", onCapture, true);
|
||||
return () => target.removeEventListener("keydown", onCapture, true);
|
||||
}
|
||||
|
||||
function trackFullscreen(): () => boolean {
|
||||
let fullscreen = false;
|
||||
if (!isTauri()) return () => fullscreen;
|
||||
const sync = () =>
|
||||
void commands
|
||||
.windowIsFullscreen()
|
||||
.then((on) => (fullscreen = on))
|
||||
.catch(() => {});
|
||||
sync();
|
||||
onIdeEvent("windowFullscreenChanged", sync);
|
||||
return () => fullscreen;
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача