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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2ab0d55c80 fix(vue): don't indent code in top-level <script> and <style> blocks
Pressing Enter in <script setup> indented the new line one level, because
the HTML base indents every element's children. WebStorm's Vue code style
indents the children of the top-level <template> only, so code in
<script> and <style> starts at the margin, as npm create vue writes it.

Fixes #3982
2026-11-17 21:10:26 +08:00
l0ng-ai 34f2e18ff1 fix(macos): keep full screen when Escape goes unhandled (#4006)
Escape the page leaves unhandled goes back from WebKit as the web view's doCommandBySelector:(cancelOperation:), run through NSView's own implementation, which leaves full screen directly; the window-level cancelOperation: hook from #3134 was never reached and is removed. In macOS full screen the workbench now marks Escape handled after every key handler has seen it (also when one stops it); Ctrl+Cmd+F leaves full screen.

Refs #3970, #3104
2026-11-17 20:58:44 +08:00
l0ng-ai 83a949ffe9 fix(debugger): keep an expanded value hint open (#4004)
Expanding an object in the debugger's value hint grew it into a variables tree that no longer fit above the line, so the tooltip moved below it, away from the mouse, and the hover tooltip closed as soon as the mouse moved towards it. An expanded hover hint is now shown pinned at the expression until Escape, a click in the editor, an edit or the next step; hints shown with a timeout (selection, quick evaluate, inline values) are kept once clicked or focused.

Refs #3970
2026-11-17 20:39:19 +08:00
l0ng-ai af8bd1afcd fix(debugger): debug Python with a Windows venv interpreter given by its path (#3999)
debugpyLaunch split the run configuration's command only at '/', so a Windows venv interpreter path (C:\...\.venv\Scripts\python.exe) fell back to a bare python from PATH and was passed as the module to run; when that python could not start, debugpy's launcher never connected ("Timed out waiting for launcher to connect"). Command names now split at both separators, and a venv tool given by a backslash path debugs with the python.exe next to it.

Fixes #3907
2026-11-17 20:29:12 +08:00
l0ng-ai ce12f68613 fix(hierarchy): load library types' levels from their language server (#3998)
The type hierarchy's withDocument opened every node from disk, so library types (jdt:// URIs) failed with os error 2: look-ahead loads failed silently, leaving expand arrows on every JDK type, and expanding one showed "failed to load". Library URIs now open as virtual documents.

Fixes #3409
2026-11-17 20:24:37 +08:00
l0ng-ai 77996f17e7 fix(terminal): open file:// links in the editor (#3996)
Compiler output such as Kotlin's "file:///develop/app/src/A.kt:15:56 Unresolved
reference" was linked as a URL and handed to the system opener: in a remote
window it failed with "Not allowed to open url", and locally it opened the file
in another app. A file:// URL is now a file location with its line and column,
opened in the editor on the machine the terminal runs on, as the Run console
already does.

Refs #3447
2026-11-17 20:12:33 +08:00
l0ng-ai bacdd3e5c3 fix(run): detect Spring Boot apps that inherit the plugin or use a meta-annotation (#3995)
Project detection only treated a module as Spring Boot when its own build file
applied the plugin, so microservice modules that inherit spring-boot-maven-plugin
from the parent POM's <build><plugins> (or Gradle's subprojects block) were missing
from Run configurations and Services until their main class was run once. And only
the literal @SpringBootApplication marked an application class, not
@SpringCloudApplication or a project annotation carrying @SpringBootApplication, so
the gutter's Run created a plain Application configuration.

A module now applies Spring Boot through its own build or a build above it
(pluginManagement alone doesn't apply it). Application classes are recognised by
@SpringBootApplication, @SpringCloudApplication, or a project annotation declared
with either (resolved through imports and the modules' main source roots). The
gutter reuses the Spring Boot kind of the detected configuration with the same id.

Fixes #3916
2026-11-17 20:10:43 +08:00
16 змінених файлів з 368 додано та 58 видалено

No files matched your search

-23
Переглянути файл
@@ -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.
-2
Переглянути файл
@@ -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())));
+29
Переглянути файл
@@ -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);
});
});
+28 -14
Переглянути файл
@@ -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) });
}
+9 -2
Переглянути файл
@@ -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.
+29
Переглянути файл
@@ -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"]);
});
});
+2 -1
Переглянути файл
@@ -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 {
+18
Переглянути файл
@@ -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" }),
+55
Переглянути файл
@@ -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();
});
});
+51 -9
Переглянути файл
@@ -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;
+6 -6
Переглянути файл
@@ -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]) {
+25 -1
Переглянути файл
@@ -34,11 +34,35 @@ export function trimUrl(url: string): string {
}
}
/**
* A `file://` URL (compiler output such as Kotlin's `file:///src/A.kt:15:56`) as a file location:
* it opens in the editor, on the machine the terminal runs on, like a plain path.
*/
function fileUrlTarget(url: string): { path: string; line?: number; col?: number } | null {
const m = /^file:\/\/[^/]*(\/.*?)(?::(\d+)(?::(\d+))?)?$/i.exec(url);
if (!m) return null;
let path: string;
try {
path = decodeURIComponent(m[1]!);
} catch {
return null;
}
// `file:///C:/x` is the Windows path `C:/x`.
if (/^\/[A-Za-z]:\//.test(path)) path = path.slice(1);
return { path, line: m[2] ? Number(m[2]) : undefined, col: m[3] ? Number(m[3]) : undefined };
}
export function findTerminalLinks(text: string): TerminalLink[] {
const links: TerminalLink[] = [];
for (const m of text.matchAll(URL_RE)) {
const url = trimUrl(m[0]);
links.push({ kind: "url", start: m.index, end: m.index + url.length, text: url, url });
const end = m.index + url.length;
const file = fileUrlTarget(url);
links.push(
file
? { kind: "file", start: m.index, end, text: url, ...file }
: { kind: "url", start: m.index, end, text: url, url },
);
}
const overlaps = (s: number, e: number) => links.some((l) => s < l.end && e > l.start);
for (const m of text.matchAll(FILE_RE)) {
+13
Переглянути файл
@@ -99,6 +99,19 @@ describe("terminal links", () => {
expect(findTerminalLinks("12:30 http://localhost:3000").map((l) => l.kind)).toEqual(["url"]);
});
it("opens file:// URLs as file locations", () => {
const line = "[ERROR] file:///develop/mc/src/main/kotlin/top/A%20B.kt:15:56 Unresolved reference 'x'.";
expect(findTerminalLinks(line)).toEqual([
expect.objectContaining({ kind: "file", path: "/develop/mc/src/main/kotlin/top/A B.kt", line: 15, col: 56 }),
]);
expect(findTerminalLinks("see file:///C:/work/a.kt:3")).toEqual([
expect.objectContaining({ kind: "file", path: "C:/work/a.kt", line: 3, col: undefined }),
]);
expect(findTerminalLinks("file://host/srv/x.txt")).toEqual([
expect.objectContaining({ kind: "file", path: "/srv/x.txt", line: undefined }),
]);
});
it("trims trailing punctuation from URLs", () => {
expect(trimUrl("https://a.dev/x.")).toBe("https://a.dev/x");
expect(trimUrl("https://a.dev/(x)")).toBe("https://a.dev/(x)");
+3
Переглянути файл
@@ -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";
+53
Переглянути файл
@@ -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);
});
});
+47
Переглянути файл
@@ -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;
}