дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
569bbb89df | ||
|
|
995a9563f7 | ||
|
|
893d9af6e6 | ||
|
|
73496669e7 | ||
|
|
add914f7fb | ||
|
|
0fd0f08865 | ||
|
|
054d2ba517 | ||
|
|
738dc12ef7 |
No files matched your search
@@ -15,6 +15,9 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
Some(doc) => (doc, false),
|
||||
None => (docs.open(path)?.id, true),
|
||||
};
|
||||
// A buffer without unsaved changes (open only for the search preview, or a clean
|
||||
// tab) is saved like a closed file; one the user is editing is left unsaved.
|
||||
let save = transient || !docs.is_dirty(doc)?;
|
||||
let result = (|| {
|
||||
// Recompute if the user typed between reading the text and applying.
|
||||
for _ in 0..3 {
|
||||
@@ -27,7 +30,7 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
continue;
|
||||
}
|
||||
docs.apply_edits(doc, &edits)?;
|
||||
if transient {
|
||||
if save {
|
||||
docs.save(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
@@ -46,8 +49,8 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
///
|
||||
/// Edits go through the document layer as one patch per file, so open editors
|
||||
/// update live and undo the whole file's replacements in one step. Unsaved
|
||||
/// editor buffers are replaced in place and left unsaved; files that were not
|
||||
/// open are opened transiently, saved and closed.
|
||||
/// editor buffers are replaced in place and left unsaved; other open documents
|
||||
/// are saved, and files that were not open are opened transiently, saved and closed.
|
||||
///
|
||||
/// With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
/// scope is searched again without the limit and every match in it is replaced,
|
||||
|
||||
@@ -146,3 +146,52 @@ async fn replace_all_covers_matches_past_the_limit() {
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4202: a file the search preview holds open (no unsaved changes) is saved like a closed
|
||||
/// one; a buffer with unsaved edits is replaced in place and left for the editor to save.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query("TOKEN", false),
|
||||
"DONE".into(),
|
||||
false,
|
||||
vec![],
|
||||
true,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
|
||||
assert_eq!(disk("previewed.txt"), "DONE\n");
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -45,14 +45,16 @@ If navigation, search or highlighting doesn't match the files, rebuild the cache
|
||||
|
||||
The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen may show an unknown-publisher warning. Choose **More info**, then **Run anyway**. See [Install](/en/guide/install#windows).
|
||||
|
||||
## The window stays blank on Linux
|
||||
## The window stays blank or stops responding on Linux
|
||||
|
||||
WebKitGTK's DMA-BUF renderer fails on Wayland with the NVIDIA driver. OpenIDEA detects this combination and sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` itself. If you see a blank or broken window in another setup, quit OpenIDEA and start it from a terminal with that variable set, for example:
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
|
||||
|
||||
## OpenIDEA exits at startup with a data directory error
|
||||
|
||||
`OPENIDEA_LOCAL_DATA_DIR` is set to a relative path or to a folder that can't be written. Fix or remove the variable. See [Move the local data](/en/reference/data-directories#move-the-local-data).
|
||||
|
||||
@@ -45,14 +45,16 @@ Java 语言服务器(jdtls)会分析它导入的每个模块,所以大型
|
||||
|
||||
Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen 可能提示“未知发布者”。点击 **更多信息**,再点击 **仍要运行**。参见[安装](/zh/guide/install)。
|
||||
|
||||
## Linux 上窗口一片空白
|
||||
## Linux 上窗口空白或无响应
|
||||
|
||||
在使用 NVIDIA 驱动的 Wayland 会话中,WebKitGTK 的 DMA-BUF 渲染器会出错。OpenIDEA 检测到这种组合时会自动设置 `WEBKIT_DISABLE_DMABUF_RENDERER=1`。如果在其他环境下也出现空白或显示异常的窗口,先退出 OpenIDEA,再在终端中带上这个变量启动,例如:
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
|
||||
|
||||
## 启动时提示数据目录错误并退出
|
||||
|
||||
`OPENIDEA_LOCAL_DATA_DIR` 被设成了相对路径或不可写的文件夹。修正或删除这个变量即可。参见[数据目录与日志](/zh/reference/data-directories)。
|
||||
|
||||
@@ -1295,8 +1295,8 @@ export const commands = {
|
||||
*
|
||||
* Edits go through the document layer as one patch per file, so open editors
|
||||
* update live and undo the whole file's replacements in one step. Unsaved
|
||||
* editor buffers are replaced in place and left unsaved; files that were not
|
||||
* open are opened transiently, saved and closed.
|
||||
* editor buffers are replaced in place and left unsaved; other open documents
|
||||
* are saved, and files that were not open are opened transiently, saved and closed.
|
||||
*
|
||||
* With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
* scope is searched again without the limit and every match in it is replaced,
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import type { Diagnostic, InspectEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { installInspectionProfileSync, resetInspection, runInspection, useInspection } from "./inspect";
|
||||
import {
|
||||
installInspectionProfileSync,
|
||||
rerunInspection,
|
||||
resetInspection,
|
||||
runInspection,
|
||||
useInspection,
|
||||
} from "./inspect";
|
||||
|
||||
const mock = vi.hoisted(() => ({ channel: null as null | { onmessage: (event: InspectEvent) => void } }));
|
||||
const mock = vi.hoisted(() => ({
|
||||
channel: null as null | { onmessage: (event: InspectEvent) => void },
|
||||
scopes: [] as unknown[],
|
||||
active: "/p/a.ts",
|
||||
}));
|
||||
vi.mock("@/editor/api", async (original) => ({
|
||||
...(await original<object>()),
|
||||
activeEditor: () => ({ ctx: { path: mock.active, virtual: false } }),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
@@ -14,7 +28,8 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
isTauri: () => true,
|
||||
call: (value: unknown) => value,
|
||||
commands: {
|
||||
inspectCode: (_id: unknown, _scope: unknown, channel: typeof mock.channel) => {
|
||||
inspectCode: (_id: unknown, scope: unknown, channel: typeof mock.channel) => {
|
||||
mock.scopes.push(scope);
|
||||
mock.channel = channel;
|
||||
return Promise.resolve();
|
||||
},
|
||||
@@ -97,3 +112,17 @@ it("retains initially disabled diagnostics and uses edits made during streaming"
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("reruns the file the results are for, not the file now active", async () => {
|
||||
mock.scopes = [];
|
||||
mock.active = "/p/a.ts";
|
||||
await runInspection({ kind: "file", directory: "" }, "default");
|
||||
mock.active = "/p/b.ts";
|
||||
rerunInspection();
|
||||
await vi.waitFor(() => expect(mock.scopes).toHaveLength(2));
|
||||
expect(mock.scopes).toEqual([
|
||||
{ kind: "files", paths: ["/p/a.ts"] },
|
||||
{ kind: "files", paths: ["/p/a.ts"] },
|
||||
]);
|
||||
expect(useInspection.getState().scopeLabel).toBe("File /p/a.ts");
|
||||
});
|
||||
@@ -200,7 +200,8 @@ export async function runInspection(choice: ScopeChoice, profileId: ProfileId =
|
||||
summary: null,
|
||||
error: null,
|
||||
scopeLabel: describeScope(choice, scope),
|
||||
last: choice,
|
||||
// Rerun repeats this run's scope: "Current file" stays the file inspected now.
|
||||
last: choice.kind === "file" && scope.kind === "files" ? { ...choice, file: scope.paths[0] } : choice,
|
||||
profile: profileId,
|
||||
excluded: new Set(),
|
||||
});
|
||||
|
||||
@@ -15,6 +15,8 @@ export interface ScopeChoice {
|
||||
directory: string;
|
||||
/** Name of the custom scope for `custom` (`@/platform/search`). */
|
||||
custom?: string;
|
||||
/** The file `file` resolved to, so a rerun inspects it again rather than the file now active. */
|
||||
file?: string;
|
||||
}
|
||||
|
||||
export const SCOPE_LABELS: Record<ScopeKind, string> = {
|
||||
@@ -58,7 +60,7 @@ export async function resolveScope(choice: ScopeChoice): Promise<SearchScope | s
|
||||
case "directory":
|
||||
return choice.directory.trim() ? { kind: "directory", path: choice.directory.trim() } : "Choose a directory";
|
||||
case "file": {
|
||||
const file = currentFile();
|
||||
const file = choice.file ?? currentFile();
|
||||
return file ? { kind: "files", paths: [file] } : "No file is open";
|
||||
}
|
||||
case "changed": {
|
||||
|
||||
@@ -25,6 +25,7 @@ import { isDistractionFree, useDistractionFree } from "@/workbench/distractionFr
|
||||
import { orderStatusItems } from "@/workbench/StatusBar";
|
||||
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
|
||||
import { useToolWindowLayouts } from "@/workbench/toolwindows/layouts";
|
||||
import { toolWindowsRestorable, useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { hostOs, type HostOs } from "./host";
|
||||
|
||||
export const MENU_EVENT = "openidea://menu";
|
||||
@@ -100,7 +101,11 @@ export function menuAccelerator(binding: string): string | undefined {
|
||||
export function buildMenuConfig(os: HostOs): MenuConfig {
|
||||
const labels: Record<string, string> = {};
|
||||
// Per-window state some labels follow (View › Appearance › Enter / Exit Distraction Free Mode).
|
||||
const params = { os, distractionFree: isDistractionFree() ? "on" : "off" };
|
||||
const params = {
|
||||
os,
|
||||
distractionFree: isDistractionFree() ? "on" : "off",
|
||||
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
|
||||
};
|
||||
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
|
||||
const accelerators: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
@@ -265,6 +270,10 @@ export function installMenuBridge(): () => void {
|
||||
useDistractionFree.subscribe((s, prev) => {
|
||||
if (s.active !== prev.active) push();
|
||||
}),
|
||||
// Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them.
|
||||
useToolWindowLayout.subscribe((s, prev) => {
|
||||
if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push();
|
||||
}),
|
||||
useContributions.subscribe((s, prev) => {
|
||||
if (s.toolWindows !== prev.toolWindows || s.statusItems !== prev.statusItems) push();
|
||||
}),
|
||||
|
||||
@@ -149,19 +149,27 @@ export function activate(): () => void {
|
||||
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
|
||||
let settled: LibraryGroup[] = [];
|
||||
let request: RequestId | undefined;
|
||||
/** The project whose libraries are shown (and `settled`). */
|
||||
let shownFor: string | null = null;
|
||||
const clear = () => {
|
||||
disposeRoot();
|
||||
disposeReadOnly();
|
||||
disposeRoot = disposeReadOnly = () => {};
|
||||
shown = "";
|
||||
settled = [];
|
||||
shownFor = null;
|
||||
};
|
||||
const refresh = () => {
|
||||
const id = ++seq;
|
||||
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
|
||||
request = undefined;
|
||||
if (!useProject.getState().project || useProject.getState().project?.trusted === false || !isTauri())
|
||||
return clear();
|
||||
const project = useProject.getState().project;
|
||||
if (!project || project.trusted === false || !isTauri()) return clear();
|
||||
// Another project's libraries must not show (or fill in) while this one's are discovered.
|
||||
if (shownFor !== project.root) {
|
||||
clear();
|
||||
shownFor = project.root;
|
||||
}
|
||||
let collected: LibraryGroup[] = [];
|
||||
const show = (groups: LibraryGroup[]) => {
|
||||
if (id !== seq) return;
|
||||
|
||||
@@ -4,6 +4,8 @@ import type { LibraryGroup } from "@/bindings";
|
||||
const results: LibraryGroup[][] = [];
|
||||
/** Batches the next request streams before it answers. */
|
||||
const streamed: LibraryGroup[][] = [];
|
||||
/** The next request never answers (discovery still running). */
|
||||
let hang = false;
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
Channel: class {
|
||||
@@ -19,6 +21,7 @@ vi.mock("@/bindings", () => ({
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
call: (request: [string, { onmessage: (v: unknown) => void }]) => {
|
||||
for (const batch of streamed.splice(0)) request[1].onmessage(batch);
|
||||
if (hang) return new Promise(() => {});
|
||||
return Promise.resolve(results.shift() ?? []);
|
||||
},
|
||||
isCancelled: () => false,
|
||||
@@ -67,4 +70,20 @@ describe("External Libraries refresh", () => {
|
||||
dispose();
|
||||
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
|
||||
});
|
||||
|
||||
it("drops the previous project's libraries while the next project's are discovered", async () => {
|
||||
const project = (root: string) => ({ root, trusted: true }) as ReturnType<typeof useProject.getState>["project"];
|
||||
useProject.setState({ project: project("/p") });
|
||||
results.push([rust("1.0.19")]);
|
||||
const dispose = activate();
|
||||
await vi.waitFor(() => expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(true));
|
||||
hang = true;
|
||||
try {
|
||||
useProject.setState({ project: project("/q") });
|
||||
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
|
||||
} finally {
|
||||
hang = false;
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -91,6 +91,13 @@
|
||||
outline: 1px solid var(--fg-muted);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
.flame:focus {
|
||||
outline: none;
|
||||
}
|
||||
.flame:focus .current {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.c1 {
|
||||
background: var(--flame-1);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import type { Profile, ProfileMode } from "@/platform/ipc";
|
||||
import { useI18n } from "@/platform/i18n";
|
||||
import { ProfilerTabs, ProfilerView } from "./ProfilerView";
|
||||
@@ -48,6 +48,26 @@ describe("ProfilerView", () => {
|
||||
expect(screen.getByText("async-profiler · 610.4 MB allocated")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("moves through the flame graph and zooms with the keyboard", () => {
|
||||
addSnapshot("App", profile("cpu", 100));
|
||||
render(<ProfilerView />);
|
||||
const graph = screen.getByRole("tree", { name: "Flame graph" });
|
||||
expect(graph.tabIndex).toBe(0);
|
||||
const current = () =>
|
||||
document.getElementById(graph.getAttribute("aria-activedescendant")!)?.getAttribute("aria-label");
|
||||
expect(current()).toBe("all (100 ms)");
|
||||
fireEvent.keyDown(graph, { key: "ArrowUp" });
|
||||
expect(current()).toBe("Main.run");
|
||||
fireEvent.keyDown(graph, { key: "Enter" });
|
||||
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
|
||||
fireEvent.keyDown(graph, { key: "ArrowUp" });
|
||||
expect(current()).toBe("Main.work");
|
||||
fireEvent.keyDown(graph, { key: "ArrowDown" });
|
||||
expect(current()).toBe("Main.run");
|
||||
fireEvent.keyDown(graph, { key: "Escape" });
|
||||
expect(screen.queryByText("Zoomed into Main.run")).toBeNull();
|
||||
});
|
||||
|
||||
it("marks the allocated type in the flame graph and the method list", () => {
|
||||
addSnapshot("App", profile("allocations", 640_000_000));
|
||||
const flame = render(<ProfilerView />);
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* (click to zoom, search highlights), the call tree (top-down) and the method
|
||||
* list (self / total). Double-click opens a frame's source when known.
|
||||
*/
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { Profile } from "@/platform/ipc";
|
||||
import { EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { colorSlot, flameLayout, formatWeight, frameLocation, matchingFrames, share } from "./model";
|
||||
import { colorSlot, flameLayout, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model";
|
||||
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
|
||||
import styles from "./Profiler.module.css";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -96,6 +96,28 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]);
|
||||
// The frame the keyboard is on: arrows move it, Enter zooms into it, F4 opens its source.
|
||||
const [current, setCurrent] = useState(0);
|
||||
const shown = layout.rects.some((r) => r.node === current) ? current : focus;
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
const moves: Record<string, Parameters<typeof flameStep>[2]> = {
|
||||
ArrowUp: "deeper",
|
||||
ArrowDown: "shallower",
|
||||
ArrowLeft: "previous",
|
||||
ArrowRight: "next",
|
||||
};
|
||||
const move = moves[e.key];
|
||||
if (move) setCurrent(flameStep(layout.rects, shown, move));
|
||||
else if (e.key === "Enter") setFocus(shown);
|
||||
else if (e.key === "Escape" && focus !== 0) setFocus(0);
|
||||
else if (e.key === "F4") openFrame(profile, profile.nodes[shown]!.frame);
|
||||
else return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
useEffect(() => {
|
||||
ref.current?.querySelector(`[data-node="${shown}"]`)?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [shown]);
|
||||
const matches = useMemo(() => matchingFrames(profile, query), [profile, query]);
|
||||
const unit = profile.unit;
|
||||
const total = profile.total ?? 0;
|
||||
@@ -109,7 +131,15 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.flameScroll} ref={ref}>
|
||||
<div className={styles.flame} style={{ height: layout.depth * ROW }} role="tree" aria-label={tx("Flame graph")}>
|
||||
<div
|
||||
className={styles.flame}
|
||||
style={{ height: layout.depth * ROW }}
|
||||
role="tree"
|
||||
aria-label={tx("Flame graph")}
|
||||
tabIndex={0}
|
||||
aria-activedescendant={`flame-frame-${shown}`}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{width > 0 &&
|
||||
layout.rects.map((r) => {
|
||||
const node = profile.nodes[r.node]!;
|
||||
@@ -120,17 +150,24 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
||||
return (
|
||||
<div
|
||||
key={r.node}
|
||||
id={`flame-frame-${r.node}`}
|
||||
data-node={r.node}
|
||||
role="treeitem"
|
||||
aria-label={label}
|
||||
aria-selected={r.node === shown}
|
||||
className={clsx(
|
||||
styles.frame,
|
||||
r.node === shown && styles.current,
|
||||
styles[`c${colorSlot(frame.name)}`],
|
||||
frame.kind === "allocatedType" && styles.typeFrame,
|
||||
matches && (matches.has(node.frame) ? styles.match : styles.dim),
|
||||
)}
|
||||
style={{ left: r.x * width, width: Math.max(w - 1, 1), bottom: r.depth * ROW }}
|
||||
title={`${frame.kind === "allocatedType" ? `${tx("Allocated type")}\n` : ""}${frame.name}${location ? ` (${location})` : ""}\nTotal: ${formatWeight(node.total ?? 0, unit)} (${share(node.total ?? 0, total)})\nSelf: ${formatWeight(node.selfWeight ?? 0, unit)}`}
|
||||
onClick={() => setFocus(r.node)}
|
||||
onClick={() => {
|
||||
setCurrent(r.node);
|
||||
setFocus(r.node);
|
||||
}}
|
||||
onDoubleClick={() => openFrame(profile, node.frame)}
|
||||
>
|
||||
{w > 28 && <span className={styles.frameText}>{label}</span>}
|
||||
|
||||
@@ -110,6 +110,34 @@ export function flameLayout(profile: Profile, focus = 0, minWidth = 0.002): { re
|
||||
return { rects, depth: maxDepth + 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard moves in the flame graph from the frame `node`: `deeper` to its widest callee,
|
||||
* `shallower` to its caller, `previous` / `next` to the neighbouring frame on its row.
|
||||
*/
|
||||
export function flameStep(
|
||||
rects: readonly FlameRect[],
|
||||
node: number,
|
||||
move: "deeper" | "shallower" | "previous" | "next",
|
||||
): number {
|
||||
const at = rects.find((r) => r.node === node);
|
||||
if (!at) return rects[0]?.node ?? node;
|
||||
switch (move) {
|
||||
case "deeper": {
|
||||
const inside = rects.filter((r) => r.depth === at.depth + 1 && r.x >= at.x && r.x < at.x + at.width);
|
||||
return inside.reduce<FlameRect | undefined>((a, r) => (!a || r.width > a.width ? r : a), undefined)?.node ?? node;
|
||||
}
|
||||
case "shallower":
|
||||
// A callee starts inside its caller's span.
|
||||
return rects.find((r) => r.depth === at.depth - 1 && r.x <= at.x && at.x < r.x + r.width)?.node ?? node;
|
||||
case "previous":
|
||||
case "next": {
|
||||
const row = rects.filter((r) => r.depth === at.depth).sort((a, b) => a.x - b.x);
|
||||
const i = row.indexOf(at) + (move === "next" ? 1 : -1);
|
||||
return row[i]?.node ?? node;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parentCache = new WeakMap<Profile, Int32Array>();
|
||||
|
||||
/** Parent node of every node (-1 for the root). */
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
allocationProfilerSupports,
|
||||
colorSlot,
|
||||
flameLayout,
|
||||
flameStep,
|
||||
formatWeight,
|
||||
frameLocation,
|
||||
matchingFrames,
|
||||
@@ -108,3 +109,22 @@ describe("profiler model", () => {
|
||||
expect(colorSlot("main")).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("flameStep", () => {
|
||||
// root (0) → a (1, 60%) and b (2, 40%); a → c (3)
|
||||
const rects = [
|
||||
{ node: 0, depth: 0, x: 0, width: 1 },
|
||||
{ node: 1, depth: 1, x: 0, width: 0.6 },
|
||||
{ node: 2, depth: 1, x: 0.6, width: 0.4 },
|
||||
{ node: 3, depth: 2, x: 0, width: 0.5 },
|
||||
];
|
||||
it("goes to the widest callee, the caller and the neighbours on a row", () => {
|
||||
expect(flameStep(rects, 0, "deeper")).toBe(1);
|
||||
expect(flameStep(rects, 1, "next")).toBe(2);
|
||||
expect(flameStep(rects, 2, "next")).toBe(2);
|
||||
expect(flameStep(rects, 2, "previous")).toBe(1);
|
||||
expect(flameStep(rects, 2, "deeper")).toBe(2);
|
||||
expect(flameStep(rects, 3, "shallower")).toBe(1);
|
||||
expect(flameStep(rects, 2, "shallower")).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { _addEditor, _removeEditor, editorContributions, type EditorDocContext }
|
||||
import { findExtension, findNext, findPrevious, makeQuery, setFindOpen, type FindOptions } from "@/editor/core/cm/find";
|
||||
import { fontZoom } from "@/editor/core/cm/prefs";
|
||||
import { seedFind, useFindOptions, useFindSessions, type FindTarget } from "@/editor/core/view/FindBar";
|
||||
import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, SELECTION_MATCH_HIGHLIGHT } from "./highlight";
|
||||
import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, SELECTION_MATCH_HIGHLIGHT, previewSelectionOf } from "./highlight";
|
||||
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
|
||||
import { MarkdownEditor } from "./MarkdownEditor";
|
||||
import { useMarkdownModes } from "./modes";
|
||||
@@ -306,3 +306,25 @@ describe("Markdown preview search & selection highlights", () => {
|
||||
expect(view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to)).toBe("second");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a word selected in the preview", () => {
|
||||
it("drops the space a Windows double-click adds after the word", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = "<p>Manage <strong>Order</strong> items</p>";
|
||||
document.body.append(root);
|
||||
try {
|
||||
const strong = root.querySelector("strong")!.firstChild!;
|
||||
const after = root.querySelector("strong")!.nextSibling!;
|
||||
const range = document.createRange();
|
||||
range.setStart(strong, 0);
|
||||
range.setEnd(after, 1);
|
||||
const sel = window.getSelection()!;
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
expect(previewSelectionOf(root)?.text).toBe("Order");
|
||||
expect(sel.toString()).toBe("Order");
|
||||
} finally {
|
||||
root.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -276,9 +276,24 @@ export function previewSelectionOf(root: HTMLElement): { text: string; range: Ra
|
||||
if (typeof window === "undefined") return null;
|
||||
const sel = window.getSelection();
|
||||
if (!sel || sel.isCollapsed || sel.rangeCount !== 1) return null;
|
||||
const range = sel.getRangeAt(0);
|
||||
let range = sel.getRangeAt(0);
|
||||
if (!root.contains(range.commonAncestorContainer)) return null;
|
||||
const text = sel.toString();
|
||||
let text = sel.toString();
|
||||
// Double-clicking a word on Windows selects the space after it too; the word is what was meant.
|
||||
const trailing = /^\S+(\s+)$/.exec(text)?.[1];
|
||||
if (trailing) {
|
||||
text = text.slice(0, -trailing.length);
|
||||
const end = range.endContainer;
|
||||
if (end.nodeType === Node.TEXT_NODE && range.endOffset >= trailing.length) {
|
||||
const trimmed = range.cloneRange();
|
||||
trimmed.setEnd(end, range.endOffset - trailing.length);
|
||||
if (trimmed.toString() === text) {
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(trimmed);
|
||||
range = trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (text.length < MIN_SELECTION_LENGTH || text.length > MAX_SELECTION_LENGTH || text.includes("\n") || !text.trim())
|
||||
return null;
|
||||
return { text, range: range.cloneRange() };
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { FloatingToolbar, IconButton } from "@/ui";
|
||||
import { browserIcon, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
|
||||
import { browserIcon, isWebResource, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
|
||||
import styles from "./Web.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -68,19 +69,23 @@ function WebPreview({ path }: { path: string }) {
|
||||
};
|
||||
}, [path]);
|
||||
|
||||
// Saved edits anywhere in the project (scripts, styles) reload the page.
|
||||
// Saved edits to the page or the project's web resources (scripts, styles, images) reload it;
|
||||
// other files (notes, sources the page doesn't load) leave its state alone.
|
||||
useEffect(() => {
|
||||
const scope = root ?? path.slice(0, path.lastIndexOf("/"));
|
||||
const affects = (p: string) => p === path || ((p.startsWith(scope + "/") || p === scope) && isWebResource(p));
|
||||
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();
|
||||
if ([...e.created, ...e.modified, ...e.removed].some(affects)) reload();
|
||||
});
|
||||
const offDirty = onIdeEvent("docDirty", (e) => {
|
||||
if (!e.dirty) reload();
|
||||
if (e.dirty) return;
|
||||
const saved = [...useEditorRegistry.getState().editors].find((ed) => ed.ctx.doc === e.doc)?.ctx.path;
|
||||
if (!saved || affects(saved)) reload();
|
||||
});
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { ProjectInfo, Settings } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { textEditorWrapperFor, useTextEditorWrappers } from "@/workbench/contributions";
|
||||
import { isHtmlPath, isWebPath } from "./browsers";
|
||||
import { isHtmlPath, isWebPath, isWebResource } from "./browsers";
|
||||
import { activate } from "./index";
|
||||
|
||||
const types = (patterns: string[], removedPatterns: string[] = []) => ({ patterns, removedPatterns, hashbangs: [] });
|
||||
@@ -69,3 +69,12 @@ describe("HTML files follow File Types", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("web resources", () => {
|
||||
it("are what a page loads, so the built-in preview reloads for them only", () => {
|
||||
for (const path of ["/p/index.html", "/p/app.css", "/p/main.js", "/p/data.json", "/p/logo.svg", "/p/a.woff2"])
|
||||
expect(isWebResource(path), path).toBe(true);
|
||||
for (const path of ["/p/notes.txt", "/p/README.md", "/p/src/Main.java"])
|
||||
expect(isWebResource(path), path).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -59,3 +59,12 @@ export async function openInBrowser(path: string, browser: string | null = null)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Files a page can load besides markup: styles, scripts, data, images, fonts, media. */
|
||||
const WEB_RESOURCE =
|
||||
/\.(css|m?js|cjs|jsx|tsx?|json|map|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|otf|eot|wasm|mp3|mp4|webm|ogg|wav)$/i;
|
||||
|
||||
/** A change to it can change what the built-in preview shows (it reloads for these only). */
|
||||
export function isWebResource(path: string): boolean {
|
||||
return isHtmlPath(path) || WEB_RESOURCE.test(path);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, render } from "@testing-library/react";
|
||||
|
||||
type Handler = (e: unknown) => void;
|
||||
const handlers = new Map<string, Handler[]>();
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
onIdeEvent: (kind: string, h: Handler) => {
|
||||
handlers.set(kind, [...(handlers.get(kind) ?? []), h]);
|
||||
return () =>
|
||||
handlers.set(
|
||||
kind,
|
||||
(handlers.get(kind) ?? []).filter((x) => x !== h),
|
||||
);
|
||||
},
|
||||
}));
|
||||
vi.mock("./browsers", async (original) => ({
|
||||
...(await original<typeof import("./browsers")>()),
|
||||
webUrl: async () => "http://127.0.0.1/p/page.html",
|
||||
}));
|
||||
|
||||
const { WebEditor } = await import("./WebEditor");
|
||||
const { useWebPreview } = await import("./browsers");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
|
||||
const emit = (kind: string, e: unknown) => act(() => handlers.get(kind)?.forEach((h) => h(e)));
|
||||
const fsChanged = (modified: string[]) => emit("fsChanged", { created: [], modified, removed: [] });
|
||||
|
||||
describe("the built-in HTML preview", () => {
|
||||
afterEach(cleanup);
|
||||
|
||||
it("reloads for the page and its web resources, not for unrelated files", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
useWebPreview.setState({ "/p/page.html": true });
|
||||
const { container } = render(
|
||||
<WebEditor path="/p/page.html" tabId="t">
|
||||
<div />
|
||||
</WebEditor>,
|
||||
);
|
||||
await act(async () => {});
|
||||
const frame = () => container.querySelector("iframe");
|
||||
const first = frame();
|
||||
expect(first).toBeTruthy();
|
||||
fsChanged(["/p/notes.txt", "/p/README.md"]);
|
||||
act(() => vi.advanceTimersByTime(1000));
|
||||
expect(frame()).toBe(first);
|
||||
fsChanged(["/p/style.css"]);
|
||||
act(() => vi.advanceTimersByTime(1000));
|
||||
expect(frame()).not.toBe(first);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -93,14 +93,20 @@ function translated(key: string): string | undefined {
|
||||
}
|
||||
|
||||
/** Catalog key, else the source-text catalog; `undefined` when untranslated. */
|
||||
function localized(key: string, text: string | undefined): string | undefined {
|
||||
function localized(key: string | null, text: string | undefined): string | undefined {
|
||||
if (!text) return undefined;
|
||||
const v = translated(key) ?? tx(text);
|
||||
const v = (key === null ? undefined : translated(key)) ?? tx(text);
|
||||
return v === text ? undefined : v;
|
||||
}
|
||||
|
||||
function localize(action: Action): Action {
|
||||
const title = action.verbatim ? undefined : localized(`action.${action.id}`, action.title);
|
||||
/** Titles that follow state ({@link retitleAction}), as written (English). */
|
||||
const titleOverrides = new Map<string, string>();
|
||||
|
||||
function localize(source: Action): Action {
|
||||
const override = titleOverrides.get(source.id);
|
||||
const action = override ? { ...source, title: override } : source;
|
||||
// An override is text, not the id's catalog entry (which names the registered title).
|
||||
const title = action.verbatim ? undefined : localized(override ? null : `action.${action.id}`, action.title);
|
||||
const description = localized(`action.${action.id}.description`, action.description);
|
||||
const category = localized(`action.category.${action.category}`, action.category);
|
||||
if (!title && !description && !category) return action;
|
||||
@@ -118,6 +124,19 @@ useI18n.subscribe((s, prev) => {
|
||||
useActions.setState({ actions: new Map([...sources].map(([id, a]) => [id, localize(a)])) });
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows action `id` as `title` (English, translated through the text catalog) while its
|
||||
* state calls for it, e.g. Hide All Tool Windows as "Restore Tool Windows"; `undefined`
|
||||
* returns to the registered title.
|
||||
*/
|
||||
export function retitleAction(id: string, title: string | undefined) {
|
||||
if (titleOverrides.get(id) === title) return;
|
||||
if (title) titleOverrides.set(id, title);
|
||||
else titleOverrides.delete(id);
|
||||
const source = sources.get(id);
|
||||
if (source) useActions.setState((s) => ({ actions: new Map(s.actions).set(id, localize(source)) }));
|
||||
}
|
||||
|
||||
/** Adds `action` to the written sources; returns a disposer that removes it. */
|
||||
function addSource(action: Action): () => void {
|
||||
sources.set(action.id, action);
|
||||
|
||||
@@ -331,7 +331,7 @@
|
||||
"menu.toolwindow.debug": "Debug",
|
||||
"menu.toolwindow.find": "Find",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "Hide All Tool Windows",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restore Tool Windows} other {Hide All Tool Windows}}",
|
||||
"menu.toolwindow.problems": "Problems",
|
||||
"menu.toolwindow.project": "Project",
|
||||
"menu.toolwindow.run": "Run",
|
||||
|
||||
@@ -269,7 +269,7 @@
|
||||
"menu.toolwindow.debug": "Depuración",
|
||||
"menu.toolwindow.find": "Buscar",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "Ocultar todas las ventanas de herramientas",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurar ventanas de herramientas} other {Ocultar todas las ventanas de herramientas}}",
|
||||
"menu.toolwindow.problems": "Problemas",
|
||||
"menu.toolwindow.project": "Proyecto",
|
||||
"menu.toolwindow.run": "Ejecución",
|
||||
|
||||
@@ -268,7 +268,7 @@
|
||||
"menu.toolwindow.debug": "Débogage",
|
||||
"menu.toolwindow.find": "Recherche",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "Masquer toutes les fenêtres d'outils",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurer les fenêtres d'outils} other {Masquer toutes les fenêtres d'outils}}",
|
||||
"menu.toolwindow.problems": "Problèmes",
|
||||
"menu.toolwindow.project": "Projet",
|
||||
"menu.toolwindow.run": "Exécution",
|
||||
|
||||
@@ -275,7 +275,7 @@
|
||||
"menu.toolwindow.debug": "디버그",
|
||||
"menu.toolwindow.find": "찾기",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "모든 도구 창 숨기기",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {도구 창 복원} other {모든 도구 창 숨기기}}",
|
||||
"menu.toolwindow.problems": "문제",
|
||||
"menu.toolwindow.project": "프로젝트",
|
||||
"menu.toolwindow.run": "실행",
|
||||
|
||||
@@ -269,7 +269,7 @@
|
||||
"menu.toolwindow.debug": "Debug",
|
||||
"menu.toolwindow.find": "Znajdź",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "Ukryj wszystkie okna narzędziowe",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Przywróć okna narzędziowe} other {Ukryj wszystkie okna narzędziowe}}",
|
||||
"menu.toolwindow.problems": "Problemy",
|
||||
"menu.toolwindow.project": "Projekt",
|
||||
"menu.toolwindow.run": "Uruchom",
|
||||
|
||||
@@ -267,7 +267,7 @@
|
||||
"menu.toolwindow.debug": "Depurar",
|
||||
"menu.toolwindow.find": "Localizar",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "Ocultar todas as janelas de ferramentas",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurar janelas de ferramentas} other {Ocultar todas as janelas de ferramentas}}",
|
||||
"menu.toolwindow.problems": "Problemas",
|
||||
"menu.toolwindow.project": "Projeto",
|
||||
"menu.toolwindow.run": "Executar",
|
||||
|
||||
@@ -2485,5 +2485,6 @@
|
||||
"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}'"
|
||||
"{name} did not exist at label '{label}'": "{name} did not exist at label '{label}'",
|
||||
"Restore Tool Windows": "Restore Tool Windows"
|
||||
}
|
||||
@@ -8859,5 +8859,6 @@
|
||||
"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} 尚不存在"
|
||||
"{name} did not exist at label '{label}'": "标签“{label}”时 {name} 尚不存在",
|
||||
"Restore Tool Windows": "恢复工具窗口"
|
||||
}
|
||||
@@ -331,7 +331,7 @@
|
||||
"menu.toolwindow.debug": "调试",
|
||||
"menu.toolwindow.find": "查找",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "隐藏所有工具窗口",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {恢复工具窗口} other {隐藏所有工具窗口}}",
|
||||
"menu.toolwindow.problems": "问题",
|
||||
"menu.toolwindow.project": "项目",
|
||||
"menu.toolwindow.run": "运行",
|
||||
|
||||
@@ -8,12 +8,17 @@ import { usePlatform } from "@/platform/platformInfo";
|
||||
import { Icon, MenuList, Popup, type MenuItem } from "@/ui";
|
||||
import menuStyles from "@/ui/Menu.module.css";
|
||||
import { isDistractionFree } from "./distractionFree";
|
||||
import { toolWindowsRestorable } from "./toolwindows/store";
|
||||
import styles from "./TitleBar.module.css";
|
||||
|
||||
function label(id: string, fallback: string): string {
|
||||
const key = `menu.${id}`;
|
||||
if (lookup(key) === undefined) return fallback;
|
||||
return t(key, { os: usePlatform.getState().os, distractionFree: isDistractionFree() ? "on" : "off" });
|
||||
return t(key, {
|
||||
os: usePlatform.getState().os,
|
||||
distractionFree: isDistractionFree() ? "on" : "off",
|
||||
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
|
||||
});
|
||||
}
|
||||
|
||||
type Submenu = Extract<MenuNode, { kind: "submenu" }>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { registerAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { registerAction, registerActions, retitleAction, type Action } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { formatMessage, tx } from "@/platform/i18n";
|
||||
import { occurrenceNavigator, showStatusInfo, useContributions } from "../contributions";
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
lastUsedToolWindow,
|
||||
resizeActiveToolWindow,
|
||||
setToolWindowViewMode,
|
||||
toolWindowsRestorable,
|
||||
useToolWindowLayout,
|
||||
toggleMaximizeToolWindow,
|
||||
viewModeOf,
|
||||
@@ -213,7 +214,13 @@ export function installToolWindowActions(): () => void {
|
||||
};
|
||||
|
||||
const disposeStatic = registerActions([
|
||||
{ id: "toolwindow.hideAll", title: "Hide All Tool Windows", category: "Window", run: hideAllToolWindows },
|
||||
{
|
||||
id: "toolwindow.hideAll",
|
||||
title: "Hide All Tool Windows",
|
||||
category: "Window",
|
||||
keywords: ["restore tool windows"],
|
||||
run: hideAllToolWindows,
|
||||
},
|
||||
{
|
||||
id: "toolwindow.jumpToLast",
|
||||
title: "Jump to Last Tool Window",
|
||||
@@ -312,9 +319,17 @@ export function installToolWindowActions(): () => void {
|
||||
})),
|
||||
]);
|
||||
|
||||
// Pressed again with every window hidden, Hide All restores them: its title says so.
|
||||
const retitleHideAll = () =>
|
||||
retitleAction("toolwindow.hideAll", toolWindowsRestorable() ? "Restore Tool Windows" : undefined);
|
||||
retitleHideAll();
|
||||
const unsubscribeHideAll = useToolWindowLayout.subscribe(retitleHideAll);
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
unsubscribeLayouts();
|
||||
unsubscribeHideAll();
|
||||
retitleAction("toolwindow.hideAll", undefined);
|
||||
disposeStatic();
|
||||
perWindow.forEach((e) => e.dispose());
|
||||
perWindow.clear();
|
||||
|
||||
@@ -243,6 +243,21 @@ describe("tool window persistence", () => {
|
||||
});
|
||||
|
||||
describe("tool window actions", () => {
|
||||
it("titles Hide All Tool Windows 'Restore Tool Windows' while it would restore them", async () => {
|
||||
const dispose = installToolWindowActions();
|
||||
try {
|
||||
showToolWindow("terminal");
|
||||
expect(getAction("toolwindow.hideAll")?.title).toBe("Hide All Tool Windows");
|
||||
await executeAction("toolwindow.hideAll");
|
||||
expect(getAction("toolwindow.hideAll")?.title).toBe("Restore Tool Windows");
|
||||
await executeAction("toolwindow.hideAll");
|
||||
expect(isToolWindowVisible("terminal")).toBe(true);
|
||||
expect(getAction("toolwindow.hideAll")?.title).toBe("Hide All Tool Windows");
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("registers toolwindow.<id> and generic actions", async () => {
|
||||
const dispose = installToolWindowActions();
|
||||
expect(getAction("toolwindow.terminal")?.title).toBe("Terminal");
|
||||
|
||||
@@ -557,6 +557,13 @@ export function focusToolWindow(id: string) {
|
||||
update({ focusRequest: { id, seq: ++focusSeq }, lastActive: id }, false);
|
||||
}
|
||||
|
||||
/** Whether Hide All Tool Windows would now restore the windows it hid (nothing visible, a stash kept). */
|
||||
export function toolWindowsRestorable(
|
||||
s: Pick<ToolWindowLayoutState, "visible" | "stashed"> = useToolWindowLayout.getState(),
|
||||
) {
|
||||
return !!s.stashed && !SLOTS.some((slot) => s.visible[slot]);
|
||||
}
|
||||
|
||||
/** Hides every visible window; called again with nothing visible, restores them. */
|
||||
export function hideAllToolWindows() {
|
||||
const s = useToolWindowLayout.getState();
|
||||
|
||||
Reference in new issue
Заблокувати користувача