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

...
Автор SHA1 Повідомлення Дата
l0ng-ai e062aa5d8b Merge remote-tracking branch 'origin/main' into perf-smooth 2026-11-20 09:12:02 +08:00
l0ng-ai 737afc6a8d Keep keymap search and shortcuts readable in narrow settings (#4632)
Keymap settings group the scheme selector with its actions and move the search controls to a second line in narrow settings; long action names scroll inside the tree. Verified with e2e keymapLayout/compactSettingsControls, settings vitest and typecheck.
2026-11-20 09:11:52 +08:00
l0ng-ai 18e964a9af perf(vcs): keep the Git tool window still while the window is resized
WebKit could not relayout and repaint the log's rows, graph and branch tree at
every step of a window drag, so resizing stuttered with the Log tab shown.
The tool window now keeps its size on its own layer during the drag and
follows the window once it pauses for 150 ms.
2026-11-20 09:09:57 +08:00
l0ng-ai 9ac18ed576 Merge remote-tracking branch 'origin/main' into perf-smooth 2026-11-20 08:29:26 +08:00
l0ng-ai 6bf75155b6 Keep hierarchy symbols and source context readable (#4630)
Hierarchy view keeps symbol names and source context readable in narrow panes. Verified with e2e hierarchyLayout, code-insight vitest and typecheck.
2026-11-20 08:26:29 +08:00
l0ng-ai bbedf7e1f6 Make Inspections panes fit narrow settings windows (#4629)
Inspections settings panes resize and fit narrow settings windows. Verified with e2e inspectionsLayout/settingsFormLayout, full vitest and typecheck.
2026-11-20 08:26:21 +08:00
l0ng-ai 42fd0fa8e0 Organize Code Style settings into tabs (#4627)
Code Style settings are organized into tabs. Verified with e2e codeStyleLayout, settings vitest and typecheck.
2026-11-20 08:22:50 +08:00
l0ng-ai 97a41ae983 Give line bookmark text room in the tool window (#4624)
Bookmarks tool window rows give line bookmark text room. Verified with e2e bookmarkTreeLayout, search vitest and typecheck.
2026-11-20 08:22:42 +08:00
l0ng-ai f29903b698 Give the Stash dialog room for branch names and messages (#4623)
Stash dialog gives branch names and the message field room. Verified with e2e stashDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:35 +08:00
l0ng-ai 610fe23f88 Make the Pull dialog fit long branch names (#4622)
Pull dialog wraps long branch names instead of overflowing. Verified with e2e pullDialogLayout, vcs vitest and typecheck.
2026-11-20 08:22:26 +08:00
l0ng-ai 59376b9718 Improve the Update Project dialog layout (#4621)
Update Project dialog options and actions lay out cleanly at any width. Verified with e2e updateProject, vcs vitest and typecheck.
2026-11-20 08:22:18 +08:00
l0ng-ai 170fd735dd fix(vcs): keep clone fields usable in narrow dialogs (#4618)
Clone dialog fields stay usable and inside the dialog in narrow windows. Verified with e2e cloneLayout, vcs vitest and typecheck.
2026-11-20 08:22:11 +08:00
l0ng-ai b1cf69bd05 perf(ui): smoother editor scrolling, tab switching and first file open
- Drop selectors that restyle whole subtrees on sibling insertions or focus
  changes (universal sibling selectors, `:focus ::selection`,
  `:not(:focus-within)`), patch @codemirror/view's base theme the same way,
  and add a test that keeps them out of src/.
- Measure the editor's space width once per font instead of per indent guide /
  rendered doc line; share one tooltip host under document.body.
- Build tab context menus only while open.
- Cache parsed SVG icons and clone them instead of re-parsing markup.
- Prewarm an off-screen editor at idle so the first file open doesn't compile
  and mount the editor setup.
- Project tree: compile ignored-name patterns into exact / suffix / regex
  checks, reuse one collator, and stat directory entries in parallel in
  ide-vfs.
- perf harness: wait for a settled selection before the tree key press.
2026-11-20 08:18:10 +08:00
l0ng-ai e0ae9e764c fix(app): fit the New Project wizard in narrow windows (#4617)
The New Project wizard's template form fits narrow windows and keeps edits when resized. Verified with e2e newProjectLayout, app vitest and typecheck.
2026-11-20 08:07:19 +08:00
l0ng-ai 19c1b72650 fix(settings): fit SDK details within Project Structure (#4616)
Project Structure SDK details now wrap and stay inside the pane in narrow windows; the Home Path row reuses the shared path field. Verified with e2e projectSdkLayout/sdkFieldLayout, settings vitest and typecheck.
2026-11-20 07:53:11 +08:00
lleviathe 06ff2e51c3 fix(editor): even out the spacing of editor tabs (#4606)
Editor tabs sit 4px apart and keep an 18px close slot at one edge: before the icon when the close button is on the left, after the label when it is on the right, so switching sides no longer resizes tabs. The drag ghost keeps the strip's classes so it renders with the same layout. Verified with e2e editorTabClose/editor, src/ui vitest, typecheck, and both close positions in the app.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 07:52:02 +08:00
l0ng-ai 6ae31b8148 test(keymap): list Shelve/Unshelve Silently in the VS Code and Eclipse presets (#4628)
#4620 added vcs.shelveSilently and vcs.unshelveSilently to the IntelliJ keymaps only, so the check that the VS Code preset covers every IntelliJ action id failed on main. Both the VS Code (macOS) and Eclipse (Windows) presets now list them unbound, like the other changelist actions.
2026-11-20 07:42:36 +08:00
Mansur Akhmadiтаmansur-akhmadi 3783b601b5 feat(vcs): copy a path from its repository's root in Copy Path/Reference… (#4626)
Copy Path/Reference... gains Path From Repository Root, as in IDEA: each selected path relative to the root of the Git repository holding it (innermost for nested repositories, a repository root as '.'), one per line, through the same copyPath menu group the hosting link uses. Paths outside every repository are left out, and the item is hidden when none is inside one.

Closes #4625

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 07:38:35 +08:00
l0ng-ai 37044dcd89 fix(vcs): give Local History diffs room in narrow panes (#4613)
Local History gave its revision list a fixed share of the pane, so in narrow panes the diff had little room and long labels were clipped. The list and diff are now a resizable split with sensible minimums, revision rows truncate with full text in tooltips, and the diff keeps room in narrow panes.
2026-11-20 07:37:21 +08:00
l0ng-ai 1a2adab237 fix(editor): align Reformat Code dialog groups and controls (#4611)
The Reformat Code dialog's option groups and controls were laid out ad hoc, so labels and checkboxes misaligned and the scope group wrapped awkwardly. The dialog now uses shared dialog fieldsets with aligned groups and controls, the same as the other analysis dialogs.
2026-11-20 07:12:25 +08:00
l0ng-ai 9ed87d77a7 fix(project-tree): make the Move dialog readable in narrow windows (#4609)
The Move dialog's title, target field and validation were laid out for a wide window, so in narrow ones the path and Browse button were clipped. The dialog now names what it moves (file, directory or N items), the target row wraps with its Browse button, and invalid targets (a folder into itself, the same directory) are explained inline.
2026-11-20 06:55:23 +08:00
92 змінених файлів з 3490 додано та 1068 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -5017,6 +5017,7 @@ dependencies = [
"ignore",
"notify",
"parking_lot",
"rayon",
"rustix",
"serde",
"serde_json",
+1
Переглянути файл
@@ -22,6 +22,7 @@ parking_lot.workspace = true
zip.workspace = true
flate2.workspace = true
tar.workspace = true
rayon.workspace = true
[dev-dependencies]
tempfile.workspace = true
+48 -41
Переглянути файл
@@ -10,6 +10,7 @@ mod rules;
mod watch;
use ide_core::{IdeError, IdeResult};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::cmp::Ordering;
@@ -133,51 +134,57 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
let excludes = ExcludeMatcher::new(excludes);
let mut entries: Vec<(bool, FileEntry)> = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = match entry {
Ok(e) => e,
let paths: Vec<PathBuf> = fs::read_dir(dir)?
.filter_map(|entry| match entry {
Ok(e) => Some(e.path()),
Err(e) => {
tracing::debug!("read_dir {}: {e}", dir.display());
continue;
None
}
};
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let Ok(lmeta) = fs::symlink_metadata(&path) else { continue };
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
(EntryKind::Symlink, m, Some(target))
})
.collect();
// One stat per entry dominates a large folder (and every stat is a round trip on a network
// share): stat in parallel; small folders stay on this thread.
let mut entries: Vec<(bool, FileEntry)> = paths
.into_par_iter()
.with_min_len(256)
.filter_map(|path| {
let name = path.file_name()?.to_string_lossy().into_owned();
let lmeta = fs::symlink_metadata(&path).ok()?;
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
(EntryKind::Symlink, m, Some(target))
}
Err(_) => (EntryKind::Symlink, lmeta, None),
}
Err(_) => (EntryKind::Symlink, lmeta, None),
}
} else if lmeta.is_dir() {
(EntryKind::Dir, lmeta, None)
} else {
(EntryKind::File, lmeta, None)
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
entries.push((
is_dir,
FileEntry {
hidden: name.starts_with('.'),
size: if is_dir { 0 } else { meta.len() },
mtime_ms: mtime_ms(&meta),
name,
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
));
}
entries.sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
} else if lmeta.is_dir() {
(EntryKind::Dir, lmeta, None)
} else {
(EntryKind::File, lmeta, None)
};
let is_dir = meta.is_dir();
let rel = path.strip_prefix(&base).unwrap_or(&path);
let excluded = excludes.is_excluded(rel);
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
Some((
is_dir,
FileEntry {
hidden: name.starts_with('.'),
size: if is_dir { 0 } else { meta.len() },
mtime_ms: mtime_ms(&meta),
name,
path: path.into(),
kind,
ignored,
excluded,
target_kind,
},
))
})
.collect();
entries.par_sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
Ok(entries.into_iter().map(|(_, e)| e).collect())
}
+61
Переглянути файл
@@ -0,0 +1,61 @@
import { expect, test } from "./fixtures";
test("line bookmarks keep their code or description readable in the dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 880, height: 640 });
const name = "QuarterlySettlementReconciliationCoordinator.ts";
const path = `/dev/acme-api/${name}`;
const code = "reconcileCheckoutOrders();";
const description = "Review settlement totals";
await page.evaluate(
async ({ path, code }) => {
const backendModule = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
docBackend().files.set(path, [...Array(27).fill("// Settlement rules"), code, "verifyTotals();", ""].join("\n"));
const services = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ services);
await editorService().openFile(path);
},
{ path, code },
);
await expect(page.locator(".cm-content")).toContainText(code);
await page.evaluate(
async ({ path, description }) => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("navigate.toggleBookmark", { path, line: 27 });
await executeAction("navigate.toggleBookmark", { path, line: 29 });
const bookmarkModule = "/src/features/search/bookmarks/store.ts";
const { assignMnemonic, updateBookmarks } = await import(/* @vite-ignore */ bookmarkModule);
updateBookmarks((items: unknown[]) => assignMnemonic(items, path, 28, "verifyTotals();", "4", description));
await executeAction("toolwindow.bookmarks");
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
setToolWindowSize("left", 240);
},
{ path, description },
);
const tree = page.getByRole("tree", { name: "Bookmarks" });
await expect(tree.getByText(name, { exact: true })).toBeVisible();
const snippet = tree.getByText(code, { exact: true });
await expect.poll(() => snippet.evaluate((el) => el.clientWidth)).toBeGreaterThanOrEqual(105);
await expect(tree.getByText("28:", { exact: true })).toBeVisible();
await expect(tree.getByText("29:", { exact: true })).toBeVisible();
await expect(tree.getByText(description, { exact: true })).toBeVisible();
await expect(tree.getByText("(empty line)", { exact: true })).toBeVisible();
expect(await tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
const row = tree.getByRole("treeitem").filter({ hasText: code });
await row.click();
await page.keyboard.press("Enter");
await expect
.poll(() =>
page.evaluate(async () => {
const module = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ module);
const cursor = editorService().activeCursor();
return { path: cursor?.path, line: cursor?.line };
}),
)
.toEqual({ path, line: 27 });
});
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const REPO = "https://example.test/team/billing-service.git";
test("Clone Repository keeps URL, directory, and depth usable when the dialog narrows", async ({ workbench: page }) => {
await stubDesktop(page);
await page.setViewportSize({ width: 440, height: 620 });
await page.evaluate(async (repo) => {
window.__ipc.handlers["plugin:dialog|open"] = () => "/dev/workspaces";
window.__ipc.handlers.vcs_clone = () => new Promise(() => {});
const contributionsPath = "/src/workbench/contributions.ts";
const { registerCloneSource } = await import(/* @vite-ignore */ contributionsPath);
registerCloneSource({ id: "team", label: "Team repositories", icon: "branch", component: () => null });
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("vcs.clone", repo);
}, REPO);
const dialog = page.getByRole("dialog", { name: "Clone Repository" });
const sources = dialog.getByRole("complementary", { name: "Clone source" });
const url = dialog.getByRole("textbox", { name: "URL:" });
await expect(url).toHaveValue(REPO);
await expect.poll(async () => (await url.boundingBox())!.width).toBeGreaterThan(180);
const form = dialog.locator("form");
const position = () =>
form.evaluate((el) => {
const source = el.parentElement!.querySelector("aside")!.getBoundingClientRect();
const body = el.getBoundingClientRect();
return { below: body.top >= source.bottom, beside: body.left >= source.right };
});
await expect.poll(async () => (await position()).below).toBe(true);
expect(await form.evaluate((el) => el.scrollWidth === el.clientWidth)).toBe(true);
await dialog.getByRole("button", { name: "Browse…" }).click();
const directory = dialog.getByRole("textbox", { name: "Directory:" });
await expect(directory).toHaveValue("/dev/workspaces/billing-service");
const shallow = dialog.getByRole("checkbox", { name: /^Shallow clone/ });
const depth = dialog.getByRole("spinbutton", { name: "Clone depth" });
await expect(depth).toBeDisabled();
await shallow.check();
await depth.fill("0");
const clone = dialog.getByRole("button", { name: "Clone", exact: true });
await expect(clone).toBeDisabled();
await depth.fill("3");
await page.setViewportSize({ width: 1050, height: 750 });
await expect.poll(async () => (await position()).beside).toBe(true);
await sources.getByRole("button", { name: "Team repositories" }).click();
await expect(url).toBeHidden();
await sources.getByRole("button", { name: "Repository URL" }).click();
await expect(url).toHaveValue(REPO);
await expect(directory).toHaveValue("/dev/workspaces/billing-service");
await expect(depth).toHaveValue("3");
await page.setViewportSize({ width: 440, height: 620 });
await clone.click();
await expect
.poll(() => ipcCalls(page, "vcs_clone"))
.toEqual([expect.objectContaining({ url: REPO, dest: "/dev/workspaces/billing-service", depth: 3 })]);
});
+53
Переглянути файл
@@ -0,0 +1,53 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Code Style keeps settings reachable by tab, keyboard, and search in a narrow pane", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 620, height: 720 });
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.languages = () => [
{ id: "typescript", name: "TypeScript", indent: { tabSize: 2, insertSpaces: true }, lineComment: "//" },
];
const languageList = "/src/platform/languageList.ts";
(await import(/* @vite-ignore */ languageList)).languageListChanged();
});
const search = dialog.getByRole("textbox", { name: "Search settings" });
await search.fill("typescript");
await dialog.getByRole("treeitem", { name: "TypeScript", exact: true, level: 3 }).click();
await search.clear();
const tabs = dialog.getByRole("tablist", { name: "Code Style" });
const indents = tabs.getByRole("tab", { name: "Tabs and Indents" });
const wrapping = tabs.getByRole("tab", { name: "Wrapping", exact: true });
const comments = tabs.getByRole("tab", { name: "Comment Code" });
await expect(indents).toHaveAttribute("aria-selected", "true");
const size = dialog.getByRole("textbox", { name: "Tab size", exact: true });
const indent = dialog.getByRole("textbox", { name: "Indent", exact: true });
await expect(indent).toBeVisible();
expect((await indent.boundingBox())!.x).toBeCloseTo((await size.boundingBox())!.x, 0);
await size.fill("6");
await indents.press("ArrowRight");
await expect(wrapping).toBeFocused();
await expect(dialog.getByRole("textbox", { name: "Hard wrap at", exact: true })).toBeVisible();
await expect(size).toBeHidden();
await search.fill("TypeScript line comment at first column");
await expect(comments).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("checkbox", { name: "Line comment at first column" })).toBeVisible();
await indents.click();
await expect(size).toHaveValue("6");
await page.setViewportSize({ width: 520, height: 720 });
const body = dialog.locator("[class*='pageBody']");
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(dialog.getByRole("button", { name: "Copy to Project", exact: true })).toBeVisible();
await search.fill("do not format");
await dialog.getByRole("treeitem", { name: "Code Style", exact: true, level: 2 }).click();
await expect(dialog.getByRole("tab", { name: "Formatter", exact: true })).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("listbox", { name: "Do not format" })).toBeVisible();
});
+90
Переглянути файл
@@ -0,0 +1,90 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, test } from "./fixtures";
async function setTabs(page: Page, tabs: Record<string, unknown>) {
await page.evaluate(async (tabs) => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { settings } = useProject.getState();
useProject.setState({
settings: { ...settings, editor: { ...settings?.editor, tabs: { ...settings?.editor?.tabs, ...tabs } } },
});
}, tabs);
}
const box = async (locator: Locator) => (await locator.boundingBox())!;
const closeOf = (tab: Locator) => tab.locator("..").getByRole("button", { name: "Close Tab", exact: true });
test("a close button on the right keeps a narrow slot on every tab", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "build.gradle.kts");
const strip = page.getByRole("tablist", { name: "Editor tabs" });
const idle = strip.getByRole("tab", { name: "README.md" });
const label = await box(idle.locator(":scope > span"));
const idleTab = await box(idle.locator(".."));
expect(idleTab.x + idleTab.width - (label.x + label.width)).toBeCloseTo(18, 0);
const selected = strip.getByRole("tab", { name: "build.gradle.kts" });
const close = await box(closeOf(selected));
const tab = await box(selected.locator(".."));
const text = await box(selected.locator(":scope > span"));
expect(close.x).toBeGreaterThanOrEqual(text.x + text.width - 0.5);
expect(close.x + close.width).toBeLessThanOrEqual(tab.x + tab.width + 0.5);
expect(tab.x - (idleTab.x + idleTab.width)).toBeCloseTo(4, 0);
});
for (const closeButtonPosition of ["right", "left"]) {
test(`a dragged tab's ghost keeps the tab's layout, close button ${closeButtonPosition}`, async ({
workbench: page,
}) => {
await openFromTree(page, "README.md");
await openFromTree(page, "build.gradle.kts");
await setTabs(page, { closeButtonPosition });
const selected = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "build.gradle.kts" });
const tab = await box(selected.locator(".."));
const close = await box(closeOf(selected));
await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2);
await page.mouse.down();
await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2 + 40, { steps: 4 });
const ghost = page.locator('[aria-hidden="true"]:has([data-tab-close])');
const copy = await box(ghost);
const copyClose = await box(ghost.locator("[data-tab-close] button"));
expect(copy.width).toBeCloseTo(tab.width, 0);
expect(copyClose.x - copy.x).toBeCloseTo(close.x - tab.x, 0);
expect(copyClose.x + copyClose.width).toBeLessThanOrEqual(copy.x + copy.width + 0.5);
await page.keyboard.press("Escape");
await page.mouse.up();
await expect(ghost).toHaveCount(0);
});
}
test("a close button on the left keeps a narrow slot before the icon", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "build.gradle.kts");
await setTabs(page, { closeButtonPosition: "left" });
const strip = page.getByRole("tablist", { name: "Editor tabs" });
// The selected and the hovered tab show their button in an 18px slot before the icon, which stays visible.
const selected = strip.getByRole("tab", { name: "build.gradle.kts" });
const other = strip.getByRole("tab", { name: "README.md" });
await other.hover();
for (const tab of [selected, other]) {
const icon = tab.locator(":scope > :first-child");
await expect(icon).toHaveCSS("opacity", "1");
await expect(closeOf(tab)).toHaveCSS("opacity", "1");
const slot = await box(tab.locator(".."));
const close = await box(closeOf(tab));
const glyph = await box(icon);
const label = await box(tab.locator(":scope > span"));
expect(close.x + close.width).toBeLessThanOrEqual(glyph.x + 0.5);
expect(glyph.x - slot.x).toBeCloseTo(18, 0);
expect(slot.x + slot.width - (label.x + label.width)).toBeCloseTo(8, 0);
}
// Without file icons the close button keeps its own place before the label.
await setTabs(page, { showFileIcon: false });
await expect(selected.locator("svg, img")).toHaveCount(0);
const label = await box(selected.locator(":scope > span"));
const slot = await box(closeOf(selected));
expect(slot.x + slot.width).toBeLessThanOrEqual(label.x + 0.5);
});
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const root = "/dev/acme-api";
const name = `InternationalSettlement${"Reconciliation".repeat(10)}.txt`;
const destination = `archive/Approved${"Settlement".repeat(11)}`;
test("keeps a long source name and destination readable while moving a file", async ({ workbench: page }) => {
await page.evaluate(
async ({ root, name, destination }) => {
const fsModule = "/src/features/project-tree/fs.ts";
const { projectFs } = await import(/* @vite-ignore */ fsModule);
const storeModule = "/src/features/project-tree/store.ts";
const { loadDir } = await import(/* @vite-ignore */ storeModule);
const fs = projectFs(root);
await fs.createFile(`${root}/${name}`);
await fs.createDir(`${root}/archive`);
await fs.createDir(`${root}/${destination}`);
await loadDir(root, true);
},
{ root, name, destination },
);
await page.getByRole("treeitem", { name, exact: true }).click();
await page.keyboard.press("F6");
const dialog = page.getByRole("dialog", { name: "Move", exact: true });
const field = dialog.getByRole("textbox", { name: "Target directory" });
await expect(field).toBeFocused();
await page.setViewportSize({ width: 470, height: 480 });
await expect
.poll(() => dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
expect(
await field.evaluate((el: HTMLInputElement) => el.value.slice(el.selectionStart ?? 0, el.selectionEnd ?? 0)),
).toBe("acme-api");
const submit = dialog.getByRole("button", { name: "Refactor", exact: true });
await expect(submit).toBeDisabled();
await field.fill(destination);
await expect(dialog.getByText(destination, { exact: true })).toBeVisible();
await expect(submit).toBeInViewport({ ratio: 1 });
await dialog.getByRole("checkbox", { name: "Search for references" }).uncheck();
await dialog.getByRole("checkbox", { name: "Search in comments and strings" }).uncheck();
await submit.click();
await expect(dialog).toBeHidden();
await expect
.poll(() =>
page.evaluate(
async ({ root, destination }) => {
const fsModule = "/src/features/project-tree/fs.ts";
const { projectFs } = await import(/* @vite-ignore */ fsModule);
return (await projectFs(root).readDir(`${root}/${destination}`)).map((entry: { name: string }) => entry.name);
},
{ root, destination },
),
)
.toEqual([name]);
});
test("browses for a destination and keeps the current path on cancel", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.file_dialog_needs_gtk = () => false;
let chosen: string | null = null;
window.__ipc.handlers["plugin:dialog|open"] = () => {
const result = chosen;
chosen = "C:\\Projects\\Invoice Archive";
return result;
};
});
await page.keyboard.press("F6");
const dialog = page.getByRole("dialog", { name: "Move", exact: true });
const field = dialog.getByRole("textbox", { name: "Target directory" });
const browse = dialog.getByRole("button", { name: "Browse for target directory", exact: true });
await browse.click();
await expect.poll(() => ipcCalls(page, "plugin:dialog|open")).toHaveLength(1);
await expect(field).toHaveValue(root);
await browse.click();
await expect(field).toHaveValue("C:/Projects/Invoice Archive");
await expect(dialog.getByRole("button", { name: "Refactor", exact: true })).toBeEnabled();
await field.fill("C:/");
await expect(dialog.getByText("C:/", { exact: true })).toBeVisible();
await field.fill("/");
await expect(dialog.getByText("/", { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
+98
Переглянути файл
@@ -0,0 +1,98 @@
import type { EditorView } from "@codemirror/view";
import { expect, stubDesktop, test } from "./fixtures";
test("Hierarchy keeps source context and controls reachable in a narrow dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 940, height: 680 });
const path = "/dev/acme-api/QuarterlySettlementReconciliationCoordinator.ts";
const caller = "reconcileQuarterlySettlementForMerchantOrders";
const context = "Checkout and settlement coordinator";
await page.evaluate(
async ({ path, caller }) => {
const backend = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backend);
docBackend().files.set(
path,
[
"function settleOrder() {}",
"",
`function ${caller}() {`,
" settleOrder();",
" settleOrder();",
"}",
`function flushSettlementQueue() { ${caller}(); }`,
].join("\n"),
);
const service = "/src/workbench/contributions.ts";
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
},
{ path, caller },
);
const editor = page.locator(".cm-content");
await expect(editor).toContainText("settleOrder");
await editor.evaluate((el) => {
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
view.dispatch({ selection: { anchor: 11 } });
view.focus();
});
await stubDesktop(page);
await page.evaluate(
async ({ path, caller, context }) => {
const range = (line: number, col: number) => ({ start: { line, col }, end: { line, col: col + 5 } });
const item = (name: string, line: number, detail: string, fromRanges: ReturnType<typeof range>[]) => ({
name,
path,
detail,
kind: "function",
range: range(line, 0),
selectionRange: range(line, 9),
fromRanges,
});
window.__ipc.handlers.lsp_call_hierarchy = ({ pos }) => {
const line = (pos as { line: number }).line;
return {
items:
line === 0
? [item(caller, 2, context, [range(3, 2), range(4, 2)])]
: [item("flushSettlementQueue", 6, "Queue processing", [range(6, 34)])],
incomplete: null,
};
};
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.callHierarchy");
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("right", 136);
},
{ path, caller, context },
);
const tree = page.getByRole("tree", { name: "Call hierarchy" });
const row = tree.getByRole("treeitem").filter({ hasText: caller });
await expect(row).toBeVisible();
const detail = row.getByText(context, { exact: true });
await expect.poll(() => detail.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
expect((await row.getByText("(2 calls)", { exact: true }).boundingBox())!.x).toBeLessThan(
(await detail.boundingBox())!.x,
);
const toolbar = page.getByRole("toolbar", { name: "Hierarchy actions" });
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await tree.evaluate((el) => {
el.scrollLeft = el.scrollWidth;
});
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(100);
await tree.evaluate((el) => {
el.scrollLeft = 0;
});
await row.click({ position: { x: 90, y: 12 } });
await page.keyboard.press("ArrowRight");
await expect(tree.getByRole("treeitem").filter({ hasText: "flushSettlementQueue" })).toBeVisible();
await page.keyboard.press("Enter");
await expect
.poll(() =>
page.evaluate(async () => {
const service = "/src/workbench/contributions.ts";
const cursor = (await import(/* @vite-ignore */ service)).editorService().activeCursor();
return { path: cursor?.path, line: cursor?.line, col: cursor?.col };
}),
)
.toEqual({ path, line: 3, col: 2 });
});
+52
Переглянути файл
@@ -0,0 +1,52 @@
import { expect, test } from "./fixtures";
test("Inspections keeps the selected rule and its controls usable as the pane changes width", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 620, height: 720 });
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await page.evaluate(async () => {
const path = "/src/features/settings/model/staging.ts";
(await import(/* @vite-ignore */ path)).selectPage("editor.inspections");
});
const search = dialog.getByRole("textbox", { name: "Search inspections" });
await search.fill("typo");
const tree = dialog.getByRole("tree", { name: "Inspections" });
const typo = tree.getByRole("treeitem", { name: /Typo/ });
await typo.click();
const body = dialog.locator("[class*='pageBody']");
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const resize = dialog.getByRole("separator", { name: "Resize inspection panes" });
const details = dialog.getByRole("region", { name: "Inspection details" });
await expect(resize).toHaveAttribute("aria-orientation", "horizontal");
await expect(details.getByRole("heading", { name: "Typo" })).toBeVisible();
const narrowTree = await tree.boundingBox();
const narrowDetails = await details.boundingBox();
expect(narrowDetails!.y).toBeGreaterThan(narrowTree!.y + narrowTree!.height);
await expect(details.getByRole("separator", { name: "Resize inspection description" })).toHaveAttribute(
"aria-orientation",
"horizontal",
);
const severity = details.getByRole("button", { name: "Severity" });
const severityBox = await severity.boundingBox();
expect(severityBox!.y + severityBox!.height).toBeLessThan(narrowDetails!.y + narrowDetails!.height);
await severity.click();
await page.getByRole("option", { name: "Warning", exact: true }).click();
const code = details.getByRole("checkbox", { name: "Process code" });
await code.uncheck();
await expect(severity).toHaveText("Warning");
await page.setViewportSize({ width: 1040, height: 740 });
await expect(resize).toHaveAttribute("aria-orientation", "vertical");
const width = (await tree.boundingBox())!.width;
await resize.press("ArrowRight");
await expect.poll(async () => (await tree.boundingBox())!.width).toBeGreaterThan(width + 5);
await expect(typo).toHaveAttribute("aria-selected", "true");
await expect(severity).toHaveText("Warning");
await expect(code).not.toBeChecked();
});
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { expect, test } from "./fixtures";
test("Keymap fits a narrow Settings pane and keeps shortcut editing reachable", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1080, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
const search = settings.getByRole("textbox", { name: "Search actions" });
const expand = settings.getByRole("button", { name: "Expand All", exact: true });
await expect(search).toBeVisible();
const wideSearch = (await search.boundingBox())!;
const wideExpand = (await expand.boundingBox())!;
expect(wideExpand.x).toBeLessThan(wideSearch.x);
expect(Math.abs(wideExpand.y - wideSearch.y)).toBeLessThan(8);
await page.setViewportSize({ width: 520, height: 760 });
const narrowSearch = (await search.boundingBox())!;
const narrowExpand = (await expand.boundingBox())!;
expect(narrowSearch.y).toBeGreaterThan(narrowExpand.y + narrowExpand.height);
const body = settings.locator("[class*='pageBody']");
const fitPane = () =>
expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await fitPane();
await search.fill("Reformat Code");
const tree = settings.getByRole("tree", { name: "Actions", exact: true });
const action = tree
.getByRole("treeitem")
.filter({ hasText: /Reformat Code/ })
.first();
await action.click();
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: /Keyboard Shortcut: Reformat Code/ });
await recorder.getByRole("textbox", { name: "First stroke" }).press("Control+Alt+Shift+F8");
await expect(recorder.getByText("No conflicts")).toBeVisible();
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await expect(action.locator("kbd").filter({ hasText: "F8" })).toHaveCount(1);
const title = action.getByText(/Reformat Code/).first();
await expect.poll(() => title.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await tree.evaluate((el) => {
el.scrollLeft = el.scrollWidth;
});
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(0);
await fitPane();
await settings.getByRole("button", { name: "Find Actions by Shortcut" }).click();
await settings.getByRole("textbox", { name: "Find actions by shortcut" }).press("Control+Alt+Shift+F8");
await expect(action).toBeVisible();
await fitPane();
await settings.getByRole("button", { name: "Apply", exact: true }).click();
await expect(settings.getByRole("button", { name: "Apply", exact: true })).toBeDisabled();
});
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("Local History gives the diff room and keeps revision selection across layouts", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1180, height: 700 });
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const file = "/dev/acme-api/build.gradle.kts";
const entries = [
{ id: "after", path: file, timestampMs: 2000, label: "Saved", size: 31, kind: "snapshot" },
{ id: "before", path: file, timestampMs: 1000, label: "Original", size: 34, kind: "snapshot" },
];
window.__ipc.handlers.history_list_dir = () => ({ entries, deleted: [] });
window.__ipc.handlers.history_content = ({ id }) =>
id === "before" ? 'val reportMode = "summary"\n' : 'val reportMode = "detailed"\n';
window.__ipc.handlers.vcs_file_mode = () => null;
window.__ipc.handlers.fs_probe = () => ({ size: 32, binary: false, tooLarge: false });
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.localHistory", file);
});
const revisions = page.getByRole("listbox", { name: "Revisions" });
await expect(revisions.getByRole("option", { name: /Saved/ })).toBeVisible();
const separator = page.getByRole("separator", { name: "Revisions" });
await expect(separator).toHaveAttribute("aria-orientation", "vertical");
const initialWidth = (await revisions.boundingBox())!.width;
await separator.press("ArrowLeft");
await expect.poll(async () => (await revisions.boundingBox())!.width).toBeLessThan(initialWidth);
const original = revisions.getByRole("option", { name: /^Original/ });
await original.click();
await expect(original).toHaveAttribute("aria-selected", "true");
await expect.poll(async () => ipcCalls(page, "history_content")).toContainEqual({ id: "before" });
await page.setViewportSize({ width: 480, height: 620 });
await expect(separator).toHaveAttribute("aria-orientation", "horizontal");
await expect(original).toHaveAttribute("aria-selected", "true");
const diff = page.locator(".cm-mergeView").filter({ hasText: "summary" });
await expect(diff).toBeVisible();
const listBox = (await revisions.boundingBox())!;
const diffBox = (await diff.boundingBox())!;
expect(diffBox.y).toBeGreaterThanOrEqual(listBox.y + listBox.height);
expect(diffBox.width).toBeGreaterThanOrEqual(listBox.width - 2);
await page.setViewportSize({ width: 1180, height: 700 });
await expect(separator).toHaveAttribute("aria-orientation", "vertical");
await expect(original).toHaveAttribute("aria-selected", "true");
});
+110
Переглянути файл
@@ -0,0 +1,110 @@
import type { GeneratorInfo } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const java: GeneratorInfo = {
id: "java",
name: "Java",
group: "Java",
icon: "project-java",
order: 1,
description: "A plain Java application built with Maven or Gradle.",
git: true,
dynamic: false,
fields: [
{
id: "build",
label: "Build system:",
default: "maven",
hint: "",
visible: {},
kind: {
type: "choice",
segmented: true,
options: [
{ value: "maven", label: "Maven" },
{ value: "gradle", label: "Gradle" },
],
},
},
{
id: "jdk",
label: "JDK:",
default: "",
hint: "",
visible: {},
kind: { type: "sdk", sdk: "jdk" },
},
],
};
const empty: GeneratorInfo = {
...java,
id: "empty",
name: "Empty Project",
group: "Project",
description: "",
fields: [],
};
test("New Project fits the template form in a narrow window and preserves edits when resized", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.setViewportSize({ width: 490, height: 570 });
await page.evaluate(
async (catalog) => {
const handlers = window.__ipc.handlers;
handlers.scaffold_catalog = () => catalog;
handlers.sdk_detect = () => [];
handlers.scaffold_requirements = () => [];
handlers.scaffold_create = () => new Promise(() => {});
handlers["plugin:dialog|open"] = () => "/dev/workspaces";
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("file.newProject");
},
[empty, java],
);
const dialog = page.getByRole("dialog", { name: "New Project" });
const generators = dialog.getByRole("listbox", { name: "Generators" });
await generators.getByRole("option", { name: "Java", exact: true }).click();
const form = dialog.locator("form");
const hasNoHorizontalOverflow = (el: Element) => el.scrollWidth === el.clientWidth;
expect(await form.evaluate(hasNoHorizontalOverflow)).toBe(true);
await expect(dialog.getByRole("separator", { name: "Generators" })).toHaveAttribute("aria-orientation", "horizontal");
await dialog.getByRole("textbox", { name: "Name:" }).fill("Billing Service");
await dialog.getByRole("button", { name: "Browse…" }).click();
await expect(dialog.getByRole("textbox", { name: "Location:" })).toHaveValue("/dev/workspaces");
const gradle = dialog.getByRole("button", { name: "Gradle" });
await gradle.click();
await expect(gradle).toHaveAttribute("aria-pressed", "true");
await page.setViewportSize({ width: 1040, height: 750 });
const handle = dialog.getByRole("separator", { name: "Generators" });
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
const originalWidth = (await generators.boundingBox())!.width;
await handle.press("ArrowRight");
await expect.poll(async () => (await generators.boundingBox())!.width).toBeGreaterThan(originalWidth);
await expect(generators.getByRole("option", { name: "Java", exact: true })).toHaveAttribute("aria-selected", "true");
await expect(dialog.getByRole("textbox", { name: "Name:" })).toHaveValue("Billing Service");
await expect(gradle).toHaveAttribute("aria-pressed", "true");
await page.setViewportSize({ width: 490, height: 570 });
await dialog.getByRole("button", { name: "Create", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "scaffold_create"))
.toEqual([
expect.objectContaining({
req: {
generator: "java",
location: "/dev/workspaces",
name: "Billing Service",
git: true,
values: { build: "gradle", jdk: "" },
},
}),
]);
});
+47
Переглянути файл
@@ -0,0 +1,47 @@
import { expect, stubDesktop, test } from "./fixtures";
const JDK_PATH = "/opt/jdks/corretto-21.0.8";
const LONG_NAME = "AmazonCorretto21".repeat(6);
test("Project Structure SDKs keeps selection and selected details usable in a compact dialog", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.setViewportSize({ width: 520, height: 720 });
await page.evaluate(
async ({ path, name }) => {
const sdk = { path, name, version: "21.0.8", source: "system", home: path, extra: null };
window.__ipc.handlers.sdk_detect = ({ kind }) =>
kind === "jdk"
? [sdk]
: kind === "python"
? [{ ...sdk, path: "/usr/bin/python3", home: "/usr/bin", name: "Python 3.12", version: "3.12.2" }]
: [];
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("file.projectStructure", "sdks");
},
{ path: JDK_PATH, name: LONG_NAME },
);
const dialog = page.getByRole("dialog", { name: "Project Structure" });
const list = dialog.getByRole("listbox", { name: "SDKs" });
const details = dialog.getByRole("region", { name: "SDK Details" });
await expect(list.getByRole("option", { name: /Python 3.12/ })).toBeVisible();
await expect(details.getByText(LONG_NAME, { exact: true })).toBeVisible();
const content = dialog.locator("[class*='psDialogBody']");
expect(await content.evaluate((el) => el.scrollWidth)).toBe(await content.evaluate((el) => el.clientWidth));
const path = details.getByRole("textbox", { name: "SDK home path" });
await expect(path).toHaveValue(JDK_PATH);
await expect(details.getByText("21.0.8", { exact: true })).toBeVisible();
const useSdk = details.getByRole("button", { name: "Use as Project SDK" });
await useSdk.click();
await expect(useSdk).toBeDisabled();
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeEnabled();
await list.getByRole("option", { name: /Python 3.12/ }).click();
await expect(path).toHaveValue("/usr/bin/python3");
await expect(details.getByText("3.12.2", { exact: true })).toBeVisible();
await expect(useSdk).toHaveCount(0);
});
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Pull fits the remote branch picker and keeps flags accessible in a narrow window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 380, height: 580 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/checkout-reconciliation";
const second = `${root}/billing-and-transaction-settlement`;
const branch = {
head: "main",
upstream: "origin/main",
headCommit: "c1",
behind: 1,
ahead: 0,
operation: null,
};
const h = window.__ipc.handlers;
h.vcs_roots = () => [root, second].map((root) => ({ root, ...branch }));
h.vcs_branch_info = () => branch;
h.vcs_status = () => [];
h.vcs_log = () => [];
h.vcs_remotes = () => [
{ name: "origin", url: "/git/checkout-reconciliation.git" },
{ name: "settlement-integration", url: "/git/settlement.git" },
];
h.vcs_branches = () =>
["origin/main", "origin/release/month-end-international-settlement-reconciliation"].map((name) => ({
name,
commit: "c1",
current: false,
remote: true,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
}));
h.vcs_remote = () => new Promise(() => {});
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: second, roots: [root, second], branch });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.pull");
});
const dialog = page.getByRole("dialog", { name: "Pull to main" });
const branch = dialog.getByRole("button", { name: "Remote branch" });
await expect(branch).toHaveText("main");
const body = dialog.locator("[data-dialog-body]");
await expect.poll(() => branch.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThanOrEqual(250);
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
await branch.press("s");
await page.getByRole("option", { name: "release/month-end-international-settlement-reconciliation" }).click();
await expect(branch).toContainText("month-end-international-settlement-reconciliation");
const modify = dialog.getByRole("button", { name: "Modify options" });
await modify.press("Enter");
await page.getByRole("menuitemcheckbox", { name: "--ff-only" }).click();
await expect(dialog.locator("code", { hasText: "--ff-only" })).toBeVisible();
await modify.press("Enter");
await expect(page.getByRole("menuitemcheckbox", { name: "--ff-only" })).toBeChecked();
await expect(page.getByRole("menuitemcheckbox", { name: "--no-commit" })).toBeDisabled();
await page.keyboard.press("Escape");
await expect(modify).toBeFocused();
await dialog.getByRole("button", { name: "Pull", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_remote"))
.toMatchObject([
{
repo: "/dev/checkout-reconciliation/billing-and-transaction-settlement",
op: {
op: "pullFrom",
remote: "origin",
branches: ["release/month-end-international-settlement-reconciliation"],
rebase: false,
options: { ffOnly: true },
},
},
]);
});
+55
Переглянути файл
@@ -0,0 +1,55 @@
import { expect, openFromTree, test } from "./fixtures";
test("Reformat File aligns scope and option controls and supports arrow-key scope changes", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-line").first().click();
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.evaluate(async () => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("code.reformatDialog");
});
const dialog = page.getByRole("dialog", { name: /Reformat File/ });
const scope = dialog.getByRole("group", { name: "Scope" });
const selected = scope.getByRole("radio", { name: "Selected text" });
await expect(selected).toBeChecked();
await expect(scope.getByRole("radio").first()).toHaveAccessibleName("Selected text");
await selected.press("ArrowDown");
await expect(scope.getByRole("radio", { name: "Whole file" })).toBeChecked();
const optimize = dialog.getByRole("group", { name: "Options" }).getByRole("checkbox", { name: "Optimize imports" });
expect((await selected.boundingBox())!.x).toBeCloseTo((await optimize.boundingBox())!.x, 0);
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
test("Reformat Code keeps long targets and the file mask usable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 340, height: 460 });
const target = "InternationalSettlementReconciliation".repeat(4);
await page.evaluate(async (target) => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("code.reformatFiles", { directories: [`/dev/acme-api/${target}`] });
}, target);
const dialog = page.getByRole("dialog", { name: "Reformat Code", exact: true });
await expect(dialog.getByText(target, { exact: true })).toBeVisible();
const body = dialog.locator("[data-dialog-body]");
expect(await body.evaluate((el) => el.scrollWidth)).toBe(await body.evaluate((el) => el.clientWidth));
await expect(
dialog.getByRole("group", { name: "Options" }).getByRole("checkbox", { name: "Include subdirectories" }),
).toBeChecked();
const filters = dialog.getByRole("group", { name: "Filters" });
const mask = filters.getByRole("textbox", { name: "File mask" });
await expect(mask).toBeDisabled();
await filters.getByText("File mask:", { exact: true }).click();
await mask.fill("*.java");
await expect(mask).toHaveValue("*.java");
await dialog.getByRole("button", { name: "Cancel" }).click();
await expect(dialog).toBeHidden();
});
+60
Переглянути файл
@@ -0,0 +1,60 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Stash wraps the current branch and accepts a multiline message in a narrow window", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 380, height: 590 });
await stubDesktop(page);
const root = "/dev/settlement-engine";
const head = "release/QuarterlyInternationalSettlementReconciliationAndAuthorizationForMerchantOperations";
await page.evaluate(
async ({ root, head }) => {
const branch = { head, headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null };
const h = window.__ipc.handlers;
h.vcs_branch_info = () => branch;
h.vcs_roots = () => [{ root, ...branch }];
h.vcs_status = () => [];
h.vcs_stashes = () => [];
h.vcs_stash_push = () => null;
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.stash");
},
{ root, head },
);
const dialog = page.getByRole("dialog", { name: "Stash", exact: true });
await expect(dialog.getByText(`Current branch: ${head}`)).toBeVisible();
const body = dialog.locator("[data-dialog-body]");
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
const message = dialog.getByRole("textbox", { name: "Message", exact: true });
await expect(message).toBeFocused();
await message.fill("Set aside settlement work");
await message.press("End");
await message.press("Enter");
await expect(message).toHaveValue("Set aside settlement work\n");
await message.pressSequentially("Continue after the release.");
expect(await ipcCalls(page, "vcs_stash_push")).toEqual([]);
await dialog.getByRole("checkbox", { name: "Keep index" }).check();
await dialog.getByRole("checkbox", { name: "Include untracked files" }).check();
await message.press("Control+Enter");
await expect(dialog).toBeHidden();
await expect
.poll(() => ipcCalls(page, "vcs_stash_push"))
.toEqual([
{
repo: root,
message: "Set aside settlement work\nContinue after the release.",
keepIndex: true,
includeUntracked: true,
paths: null,
},
]);
});
+54
Переглянути файл
@@ -71,3 +71,57 @@ test("shows Update failures from the branch menu even when VCS notifications are
await expect(page.getByText(/untracked working tree files would be overwritten by merge/)).toBeVisible();
expect(await ipcCalls(page, "vcs_remote")).toHaveLength(1);
});
test("Update Project wraps long tracking branches and keeps its options reachable", async ({ workbench: page }) => {
await stubDesktop(page);
await page.setViewportSize({ width: 360, height: 580 });
const local = "release/" + "InternationalSettlementReconciliation".repeat(3);
await page.evaluate(async (head) => {
const root = "/dev/acme-api";
const branch = { head, upstream: `origin/${head}`, behind: 1, ahead: 1, operation: null, headCommit: "c1" };
const h = window.__ipc.handlers;
h.vcs_branch_info = () => branch;
h.vcs_roots = () => [{ root, head, headCommit: "c1", operation: null }];
h.settings_set = () => null;
h.vcs_remote = () => new Promise(() => {});
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.update");
}, local);
const dialog = page.getByRole("dialog", { name: "Update Project", exact: true });
await expect(dialog.getByText(`Update ${local} from origin/${local} (1 incoming)`)).toBeVisible();
const body = dialog.locator("[data-dialog-body]");
const width = await body.evaluate((el) => ({ scroll: el.scrollWidth, available: el.clientWidth }));
expect(width.scroll).toBe(width.available);
const reset = dialog.getByRole("button", { name: "Reset to the Remote Branch" });
await expect(reset).toBeVisible();
expect(
await reset.evaluate(
(el) => el.getBoundingClientRect().right <= el.closest('[role="dialog"]')!.getBoundingClientRect().right,
),
).toBe(true);
const merge = dialog.getByRole("radio", { name: /^Merge incoming changes/ });
const rebase = dialog.getByRole("radio", { name: /^Rebase the current branch/ });
await expect(merge).toBeChecked();
await merge.press("ArrowDown");
await expect(rebase).toBeChecked();
await dialog.getByRole("checkbox", { name: "Don't show again" }).check();
await dialog.getByRole("button", { name: "OK", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_remote"))
.toEqual([expect.objectContaining({ op: { op: "pull", rebase: true } })]);
expect(await ipcCalls(page, "settings_set")).toEqual(
expect.arrayContaining([
expect.objectContaining({ key: "vcs.git.updateMethod", value: '"rebase"' }),
expect.objectContaining({ key: "vcs.confirmation.showUpdateOptions", value: "false" }),
]),
);
});
+30
Переглянути файл
@@ -0,0 +1,30 @@
diff --git a/dist/index.cjs b/dist/index.cjs
index b20aa9d84be6ff4b85b126bdd930065277668a26..e677ab06ca9668407e202979e14b75ab7641d6b1 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -9675,7 +9675,9 @@ const hideNativeSelection = state.Prec.highest(EditorView.theme({
"& :focus": {
caretColor: "initial !important",
...drawMainRange ? {
- "&::selection, & ::selection": {
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
+ // whole subtree of every element that gains or loses focus.
+ "&::selection": {
backgroundColor: "Highlight !important"
}
} : {}
diff --git a/dist/index.js b/dist/index.js
index 216f754db06f65f7f17f056b47d8f6fab45067bf..22282993239d836ea1da19af10ccfc61b6480cc5 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -9670,7 +9670,9 @@ const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.th
"& :focus": {
caretColor: "initial !important",
...drawMainRange ? {
- "&::selection, & ::selection": {
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
+ // whole subtree of every element that gains or loses focus.
+ "&::selection": {
backgroundColor: "Highlight !important"
}
} : {}
+34 -25
Переглянути файл
@@ -323,6 +323,18 @@ const scroll: Scenario = {
},
};
/**
* Runs an action without a default shortcut from a key press: the press is the measured input,
* and the action runs in its handler, as from a key binding. Pause is bound to nothing.
*/
async function runActionOnKey(h: Harness, id: string) {
await h.page.evaluate((id) => {
const probe = (window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf;
addEventListener("keydown", () => void probe.runAction(id), { capture: true, once: true });
}, id);
await h.page.keyboard.press("Pause");
}
/**
* Git Log with 20,000 commits on branching lanes, loaded page by page as the
* backend does (150 ms a page, like `git log`): showing it, walking the
@@ -339,12 +351,7 @@ const gitLog: Scenario = {
).__openideaPerf.fakeGitLog(20_000, 150),
);
const showMs = await h.measure(
() =>
h.page.evaluate(() =>
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
"vcs.showLog",
),
),
() => runActionOnKey(h, "vcs.showLog"),
'[role="listbox"][aria-label="Commits"]',
"order flow step 0",
);
@@ -430,16 +437,13 @@ const resizePanels: Scenario = {
await h.page.evaluate(() =>
(window as never as { __openideaPerf: { fakeGitLog(n: number): void } }).__openideaPerf.fakeGitLog(2_000),
);
await h.measure(
() =>
h.page.evaluate(() =>
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
"vcs.showLog",
),
),
'[role="listbox"][aria-label="Commits"]',
"order flow step 0",
await h.page.evaluate(() =>
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
"vcs.showLog",
),
);
// Set-up, not measured: the splitters are dragged once the log is shown.
await h.inPage((p) => p.waitShown('[role="listbox"][aria-label="Commits"]', "order flow step 0", 10_000));
const refresh = await h.refreshMs();
const drag = async (name: string, dx: number, dy: number) => {
const box = (await h.page.getByRole("separator", { name }).boundingBox())!;
@@ -560,7 +564,9 @@ const agentTabs: Scenario = {
window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise<boolean> } }
).__openideaPerf.runAction("agents.openSampleConversations", { tasks: 2, turns: 150 }),
);
const shown = (n: number) => `[data-editor-focus] span[title="Sample task ${n}"]`;
// The conversation shown: its requests end with its task's title.
const SHOWN = "[data-editor-focus] [data-message]";
const title = (n: number) => `(Sample task ${n})`;
// Both conversations get their earlier entries painted in background batches, also the
// first one, hidden behind the second as soon as it opened.
await h.page.waitForFunction(
@@ -575,25 +581,28 @@ const agentTabs: Scenario = {
// Rows painted while hidden are laid out the first time their conversation shows.
for (const n of [1, 2]) {
await h.page.getByRole("tab", { name: `Sample task ${n}` }).click();
await h.page.locator(shown(n)).waitFor();
await h.page
.locator(SHOWN, { hasText: title(n) })
.first()
.waitFor();
await h.page.waitForTimeout(300);
}
// WebKit restyles a hidden conversation in full when it is shown again (Chromium keeps its
// style): what bounds that there is the history's DOM, and rows skipping rendering off screen.
const { conversationNodes, rowsAlwaysRendered } = await h.page.evaluate((selector) => {
const conversation = document.querySelector(selector)!.closest("[data-editor-focus]")!;
const conversation = document.querySelector(selector)!;
const rows = [...conversation.querySelector("[data-message]")!.parentElement!.children];
return {
conversationNodes: conversation.querySelectorAll("*").length,
rowsAlwaysRendered: rows.filter((r) => getComputedStyle(r).contentVisibility !== "auto").length,
};
}, shown(2));
}, "[data-editor-focus]");
const t0 = await h.now();
const before = await h.counters();
const switches: number[] = [];
for (let i = 0; i < 10; i++) {
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), shown(i % 2 ? 2 : 1)));
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), SHOWN, title(i % 2 ? 2 : 1)));
await h.page.waitForTimeout(150);
}
const work = Harness.delta(before, await h.counters());
@@ -602,10 +611,7 @@ const agentTabs: Scenario = {
// Scrolling up from the end, a step at a time: how far the text under the pointer moves
// beyond the scroll itself.
const scrollJumps = await h.page.evaluate(async (selector) => {
const stream = document
.querySelector(selector)!
.closest("[data-editor-focus]")!
.querySelector("[data-message]")!.parentElement!;
const stream = document.querySelector(selector)!.parentElement!;
const frame = () => new Promise(requestAnimationFrame);
stream.scrollTop = stream.scrollHeight;
await frame();
@@ -626,7 +632,7 @@ const agentTabs: Scenario = {
}
stream.scrollTop = stream.scrollHeight;
return jumps;
}, shown(2));
}, SHOWN);
const refresh = await h.refreshMs();
const box = (await h.page.locator("[data-editor-focus]").boundingBox())!;
@@ -732,6 +738,9 @@ const projectTree: Scenario = {
async run(h) {
const generated = h.page.locator('[role="treeitem"][aria-level="2"]', { hasText: "generated" }).first();
await generated.click();
// Measure from a settled selection: a key pressed in the click's own frame also pays for that frame.
await generated.and(h.page.locator('[aria-selected="true"]')).waitFor();
await h.page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
const expandMs = await h.measure(
() => h.page.keyboard.press("ArrowRight"),
'[role="tree"][aria-label="Project"]',
Створено
+20 -24
Переглянути файл
@@ -7,6 +7,9 @@ settings:
overrides:
mermaid>katex: ^0.18.2
patchedDependencies:
'@codemirror/view': 0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5
importers:
.:
@@ -61,7 +64,7 @@ importers:
version: 6.7.6
'@codemirror/view':
specifier: ^6.43.14
version: 6.43.14
version: 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@floating-ui/react-dom':
specifier: ^2.1.9
version: 2.1.9([email protected]([email protected]))([email protected])
@@ -85,7 +88,7 @@ importers:
version: 1.2.0
'@replit/codemirror-vim':
specifier: 6.4.0
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))
'@tanstack/react-virtual':
specifier: ^3.14.21
version: 3.14.21([email protected]([email protected]))([email protected])
@@ -591,7 +594,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxc-parser/[email protected]':
resolution: {integrity: sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==}
@@ -1069,7 +1071,6 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==}
@@ -1083,14 +1084,12 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==}
@@ -1864,7 +1863,6 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
@@ -1878,14 +1876,12 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
[email protected]:
resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
[email protected]:
resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
@@ -2391,14 +2387,14 @@ snapshots:
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@codemirror/[email protected]':
@@ -2438,7 +2434,7 @@ snapshots:
'@codemirror/lang-javascript': 6.2.5
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/css': 1.3.9
'@lezer/html': 1.3.13
@@ -2454,7 +2450,7 @@ snapshots:
'@codemirror/language': 6.13.1
'@codemirror/lint': 6.9.7
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/javascript': 1.5.6
@@ -2464,7 +2460,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11
@@ -2488,7 +2484,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11
@@ -2499,7 +2495,7 @@ snapshots:
'@codemirror/lang-html': 6.4.12
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/markdown': 1.8.0
@@ -2562,7 +2558,7 @@ snapshots:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/xml': 1.0.6
@@ -2606,7 +2602,7 @@ snapshots:
dependencies:
'@codemirror/state': 6.7.6
'@codemirror/streamparser': 6.0.0
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11
@@ -2619,21 +2615,21 @@ snapshots:
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
crelt: 1.0.7
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@lezer/highlight': 1.2.5
style-mod: 4.1.4
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
crelt: 1.0.7
'@codemirror/[email protected]':
@@ -2642,7 +2638,7 @@ snapshots:
'@codemirror/[email protected]': {}
'@codemirror/[email protected]':
'@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)':
dependencies:
'@codemirror/state': 6.7.6
crelt: 1.0.7
@@ -3105,13 +3101,13 @@ snapshots:
'@replit/[email protected]': {}
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))':
dependencies:
'@codemirror/commands': 6.11.1
'@codemirror/language': 6.13.1
'@codemirror/search': 6.7.2
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
'@replit/codemirror-vim-core': 0.1.0
'@rolldown/[email protected]':
+2
Переглянути файл
@@ -3,3 +3,5 @@ allowBuilds:
overrides:
# GHSA-238p-pmpm-9mq7 (fixed in 0.18.2); mermaid 12.1 still asks for katex ^0.16.
mermaid>katex: ^0.18.2
patchedDependencies:
"@codemirror/view": patches/@codemirror__view.patch
+3 -1
Переглянути файл
@@ -51,7 +51,9 @@ class CornerInset {
private measure() {
const corner = this.corner;
if (!corner) return;
// A hidden tab's view is detached and measures 0: keeping the inset spares every line
// a restyle when the tab hides and another when it shows again.
if (!corner || !this.view.dom.isConnected) return;
const width = corner.getBoundingClientRect().width;
let inset = width > 0 ? round(width) + CORNER_GAP : 0;
// A narrow window or a wide corner: keep at least half of the width for text.
+2 -26
Переглянути файл
@@ -20,16 +20,12 @@ import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension }
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { getIndentUnit, matchBrackets, syntaxTree } from "@codemirror/language";
import { LINE_INSET } from "./lineInset";
import { SPACE, spaceWidth } from "./spaceWidth";
import { BRACKET_COLORS, LONG_LINE, bracketScanner, type BracketScanner } from "./rainbowBrackets";
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
const GUIDE_SHIFT = 2;
/** One column of indentation: a space in the editor font, as measured by the guides plugin. */
const SPACE = "var(--openidea-space, 1ch)";
const SPACE_SAMPLE = 64;
/** Number of `--openidea-guide-<n>` rainbow colours; deeper guides repeat them. */
export const GUIDE_COLORS = 5;
@@ -325,37 +321,20 @@ function build(
}
export const indentGuides: Extension = [
spaceWidth,
ViewPlugin.fromClass(
class {
decorations: DecorationSet;
private probe: HTMLElement;
private brackets: BracketCache[] = [];
/** Guide variables of each decorated line, by its start: code lens rows above it repeat them. */
private lineVars = new Map<number, { images: string; positions: string }>();
private scanner: BracketScanner | null;
constructor(readonly view: EditorView) {
// Inherits the editor font from the scroller, outside the content CodeMirror observes;
// the measured width goes on the scroller, where lines and code lens rows pick it up.
this.probe = document.createElement("span");
this.probe.setAttribute("aria-hidden", "true");
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
this.probe.textContent = " ".repeat(SPACE_SAMPLE);
view.scrollDOM.appendChild(this.probe);
const scanner = bracketScanner(view);
this.scanner = scanner;
this.decorations = build(view, scanner, this.brackets, this.lineVars);
this.measure();
this.syncLenses();
}
measure() {
this.view.requestMeasure({
key: this,
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SPACE_SAMPLE,
write: (width, view) => {
if (width > 0) view.scrollDOM.style.setProperty("--openidea-space", `${+width.toFixed(3)}px`);
},
});
}
/** Gives code lens rows the guides of the line they annotate, once they are in the DOM. */
syncLenses() {
this.view.requestMeasure({
@@ -379,15 +358,12 @@ export const indentGuides: Extension = [
});
}
destroy() {
this.probe.remove();
this.view.scrollDOM.style.removeProperty("--openidea-space");
for (const el of this.view.contentDOM.querySelectorAll<HTMLElement>(".cm-openidea-lens")) {
el.style.removeProperty("--openidea-guide-images");
el.style.removeProperty("--openidea-guide-positions");
}
}
update(u: ViewUpdate) {
if (u.geometryChanged) this.measure();
const scanner = bracketScanner(u.view);
// A new scanner (rainbow brackets toggled or reconfigured) may colour blocks differently.
const bracketsChanged = scanner !== this.scanner;
+31
Переглянути файл
@@ -0,0 +1,31 @@
import { afterEach, expect, it, vi } from "vitest";
import { registerEditorContribution } from "@/editor/api";
import { prewarmEditor } from "./prewarm";
afterEach(() => vi.unstubAllGlobals());
it("builds an off-screen editor with embedded contributions only, then removes it", () => {
let frame: FrameRequestCallback | undefined;
vi.stubGlobal("requestAnimationFrame", (f: FrameRequestCallback) => ((frame = f), 1));
const seen: string[] = [];
const offEmbedded = registerEditorContribution({
id: "test.embedded",
embedded: true,
extensions: (ctx) => (seen.push(`embedded ${ctx.doc}`), []),
});
const offFile = registerEditorContribution({
id: "test.file",
extensions: () => (seen.push("file"), []),
});
try {
prewarmEditor();
expect(document.querySelectorAll(".cm-editor")).toHaveLength(1);
expect(seen).toEqual(["embedded -1"]);
frame!(0);
expect(document.querySelector(".cm-editor")).toBeNull();
expect(document.body.children).toHaveLength(0);
} finally {
offEmbedded();
offFile();
}
});
+55
Переглянути файл
@@ -0,0 +1,55 @@
import { EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { editorContributions, type EditorDocContext } from "@/editor/api";
import { baseExtensions } from "./setup";
/**
* Builds and drops an off-screen editor with the file editors' setup, so the first file opened
* does not also pay for compiling the editor code and mounting its stylesheets. The document is
* virtual and empty, and only contributions that accept such editors (`embedded`) take part:
* nothing reaches a language server or the file system.
*/
export function prewarmEditor(): void {
const host = document.createElement("div");
host.setAttribute("aria-hidden", "true");
host.style.cssText = "position:fixed;left:-10000px;top:0;width:480px;height:240px;visibility:hidden;contain:strict";
document.body.appendChild(host);
const ctx: EditorDocContext = {
doc: -1,
path: "prewarm.txt",
language: "plaintext",
uiMode: null,
readOnly: true,
virtual: true,
};
const contributions: Extension[] = [];
for (const c of editorContributions()) {
if (!c.embedded) continue;
try {
contributions.push(c.extensions(ctx));
} catch {
// Warming is best effort: the real editor reports a failing contribution.
}
}
const view = new EditorView({
parent: host,
state: EditorState.create({
doc: "",
extensions: baseExtensions({
ctx,
settings: undefined,
info: undefined,
language: null,
docLength: 0,
indent: { tabSize: 4, insertSpaces: true },
wrapOverride: false,
contributions,
}),
}),
});
// One frame so its measure pass runs too, then nothing of it is left behind.
requestAnimationFrame(() => {
view.destroy();
host.remove();
});
}
+1 -1
Переглянути файл
@@ -189,7 +189,7 @@ it("indents by the code's character width, so a font size change keeps it in lin
const v = open(true, ["class A {", "\t/**", "\t * Books.", "\t */", "\tvoid book() {}", "}"].join("\n"));
const body = v.dom.querySelector<HTMLElement>(".cm-openidea-renderedDoc")!;
// A tab is a tab size of columns, not one character.
expect(body.style.marginLeft).toContain(`${v.state.tabSize} * var(--openidea-doc-char`);
expect(body.style.marginLeft).toContain(`${v.state.tabSize} * var(--openidea-space`);
});
it("forgets a flip whose comment is deleted, so the feature turns off again", async () => {
+14 -20
Переглянути файл
@@ -61,6 +61,7 @@ import { tx, useI18n } from "@/platform/i18n";
import { loadMarkdown, markupToHtml } from "@/editor/lsp/markdown";
import { hasContent, renderDoc, type DocComment, type DocStyle, type RenderedDoc } from "./docRender";
import { LINE_INSET } from "./lineInset";
import { SPACE, spaceWidth } from "./spaceWidth";
/** The file's default: render its doc comments or not. */
export const renderDocComments = Facet.define<boolean, boolean>({
@@ -320,9 +321,9 @@ class DocWidget extends WidgetType {
const titles = doc.sections.map(sectionTitle);
const dom = document.createElement("div");
dom.className = "cm-openidea-renderedDoc";
// In the code's character width, which `docMetrics` keeps current: the DOM stays
// right through a font size change or zoom, which does not draw the widget again.
const left = `(${this.indent} * var(--openidea-doc-char, 1ch) + ${LINE_INSET}px)`;
// In columns of the code's font (`spaceWidth`): the DOM stays right through a font
// size change or zoom, which does not draw the widget again.
const left = `(${this.indent} * ${SPACE} + ${LINE_INSET}px)`;
dom.style.marginLeft = `calc${left}`;
// The content is as wide as its longest line; the comment wraps at the visible width instead.
dom.style.maxWidth = `calc(var(--openidea-doc-width, 100%) - ${left} - ${DOC_RIGHT_GAP}px)`;
@@ -827,12 +828,10 @@ export function toggleRenderedViewAtCaret(view: EditorView): boolean {
const DOC_RIGHT_GAP = 24;
/**
* Publishes on the content the visible width of the text area, `--openidea-doc-width`,
* and the code's character width, `--openidea-doc-char`. A block widget is as wide as
* the content, which without soft wraps is as wide as the longest line, so a rendered
* comment needs the first to wrap where the reader can see, as IDEA's does; it indents
* by the second, which a font size change or zoom changes. Horizontal scrolling leaves
* both unchanged.
* Publishes on the content the visible width of the text area, `--openidea-doc-width`.
* A block widget is as wide as the content, which without soft wraps is as wide as the
* longest line, so a rendered comment needs it to wrap where the reader can see.
* Scrolling leaves it unchanged, so lines are not restyled while scrolling.
*/
const docMetrics = ViewPlugin.fromClass(
class {
@@ -845,18 +844,12 @@ const docMetrics = ViewPlugin.fromClass(
measure() {
this.view.requestMeasure({
key: this,
read: (view) => ({
width: view.scrollDOM.clientWidth - view.contentDOM.offsetLeft,
char: view.defaultCharacterWidth,
}),
write: ({ width, char }, view) => {
read: (view) => view.scrollDOM.clientWidth - view.contentDOM.offsetLeft,
write: (width, view) => {
const style = view.contentDOM.style;
const widthValue = `${Math.max(0, Math.floor(width))}px`;
if (style.getPropertyValue("--openidea-doc-width") !== widthValue)
style.setProperty("--openidea-doc-width", widthValue);
const charValue = `${char}px`;
if (style.getPropertyValue("--openidea-doc-char") !== charValue)
style.setProperty("--openidea-doc-char", charValue);
const value = `${Math.max(0, Math.floor(width))}px`;
if (style.getPropertyValue("--openidea-doc-width") !== value)
style.setProperty("--openidea-doc-width", value);
},
});
}
@@ -947,5 +940,6 @@ export const renderedDocsExtension: Extension = [
markdownReady,
languageWatcher,
docMetrics,
spaceWidth,
docsTheme,
];
+51
Переглянути файл
@@ -0,0 +1,51 @@
/**
* The editor font's space width, published on the scroller as `--openidea-space`
* for anything laid out in columns of indentation (indent guides, code lens rows,
* rendered doc comments). A space is measured, not `ch`: in a proportional font it
* is narrower than "0". The probe's text is fixed, so the value only changes with
* the font, its size or zoom; `defaultCharacterWidth` is sampled from whichever
* line is in view and drifts while scrolling, and an inherited variable that
* changes restyles every line.
*/
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
/** One column of indentation, as a CSS length. */
export const SPACE = "var(--openidea-space, 1ch)";
const SAMPLE = 64;
/** Shared by every extension that lays out by `SPACE`; CodeMirror installs it once. */
export const spaceWidth = ViewPlugin.fromClass(
class {
private probe: HTMLElement;
private written = "";
constructor(readonly view: EditorView) {
// Inherits the editor font from the scroller, outside the content CodeMirror observes.
this.probe = document.createElement("span");
this.probe.setAttribute("aria-hidden", "true");
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
this.probe.textContent = " ".repeat(SAMPLE);
view.scrollDOM.appendChild(this.probe);
this.measure();
}
measure() {
this.view.requestMeasure({
key: this,
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SAMPLE,
write: (width, view) => {
const value = `${+width.toFixed(3)}px`;
if (width <= 0 || value === this.written) return;
this.written = value;
view.scrollDOM.style.setProperty("--openidea-space", value);
},
});
}
update(u: ViewUpdate) {
if (u.geometryChanged) this.measure();
}
destroy() {
this.probe.remove();
this.view.scrollDOM.style.removeProperty("--openidea-space");
}
},
);
+16 -2
Переглянути файл
@@ -61,6 +61,20 @@ export interface Reveal {
const KEPT_VIEWS = 8;
const keptSlots: EditorSlot[] = [];
/**
* Holds the visible tabs' tooltip layers. A layer added to `document.body` itself on every
* tab switch would change which element is the body's last child, and Chromium then
* restyles the whole workbench (`:last-child` rules); inside this host it restyles nothing else.
*/
let tooltipHost: HTMLElement | null = null;
function tooltipHostElement(): HTMLElement {
if (!tooltipHost?.isConnected) {
tooltipHost = document.createElement("div");
document.body.appendChild(tooltipHost);
}
return tooltipHost;
}
export class EditorSlot {
private stored: EditorState;
private historyTarget: WorkspaceHistoryTarget;
@@ -70,7 +84,7 @@ export class EditorSlot {
/** The view kept, detached from the document, while the tab is hidden. */
private kept: EditorView | null = null;
/**
* The tab's tooltips (hints, hover, completion…). They live outside the view, in `document.body`,
* The tab's tooltips (hints, hover, completion…). They live outside the view, under `document.body`,
* so they leave the page with the view when the tab is hidden instead of floating over the next tab.
*/
private readonly tooltipLayer = typeof document === "undefined" ? null : document.createElement("div");
@@ -207,7 +221,7 @@ export class EditorSlot {
mount(parent: HTMLElement): EditorView {
if (this.view) return this.view;
if (this.tooltipLayer && !this.tooltipLayer.isConnected) document.body.appendChild(this.tooltipLayer);
if (this.tooltipLayer && !this.tooltipLayer.isConnected) tooltipHostElement().appendChild(this.tooltipLayer);
const kept = this.kept;
let view: EditorView;
if (kept) {
+2 -1
Переглянути файл
@@ -568,7 +568,8 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
anchor={moreRef}
placement="bottom-end"
aria-label="Tab actions"
items={ctrl.tabMenu(paneId, tab)}
// Built when shown: every tab render (each open and switch) would otherwise assemble the whole menu.
items={open ? ctrl.tabMenu(paneId, tab) : []}
/>
</div>
);
-27
Переглянути файл
@@ -553,33 +553,6 @@
}
/* Dialog bodies get no padding of their own; wrap the groups like Analysis dialogs' .form. */
.reformatBody {
display: flex;
flex-direction: column;
gap: 10px;
padding: 14px;
}
.reformatGroup {
margin: 0;
padding: 0;
border: 0;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.reformatLegend {
margin-bottom: 6px;
padding: 0;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.reformatOption {
display: flex;
align-items: center;
gap: var(--space-1-5);
font-size: var(--fs-ui);
}
.pasteImports {
display: flex;
flex-direction: column;
+6 -6
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import type { Location } from "@/bindings";
const openFile = vi.fn(async () => undefined);
@@ -19,7 +19,6 @@ const { closePopup, openPopup, useLspPopup } = await import("./popupStore");
const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
const { mountHoverDoc } = await import("./DocView");
const { hoverSource } = await import("./hover");
import popupStyles from "./Popups.module.css";
import { registerImportsOnPasteActions } from "./importsOnPaste";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
@@ -352,7 +351,7 @@ describe("quick definition popup", () => {
});
describe("reformat dialog", () => {
it("wraps its content in the padded body", () => {
it("offers only whole-file formatting when the editor has no selection", () => {
const onRun = vi.fn();
openPopup({
kind: "reformat",
@@ -363,9 +362,10 @@ describe("reformat dialog", () => {
onRun,
});
render(<LspPopups />);
const body = screen.getByRole("dialog", { name: "Reformat File" }).querySelector("[data-dialog-body]")!;
expect(body.firstElementChild).toHaveClass(popupStyles.reformatBody!);
expect(body.firstElementChild!.querySelectorAll("fieldset")).toHaveLength(2);
const scope = within(screen.getByRole("group", { name: "Scope" }));
expect(scope.getByRole("radio", { name: "Selected text" })).toBeDisabled();
expect(scope.getByRole("radio", { name: "Whole file" })).toBeChecked();
expect(within(screen.getByRole("group", { name: "Options" })).getByRole("checkbox")).not.toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "Run" }));
expect(onRun).toHaveBeenCalledWith({ selectionOnly: false, optimizeImports: false });
});
+21 -25
Переглянути файл
@@ -11,6 +11,7 @@ import {
List,
MenuList,
Popup,
Radio,
Select,
Spinner,
SymbolBadge,
@@ -35,6 +36,7 @@ import { renderCode } from "./markdown";
import { describeSummary } from "./workspaceEdit";
import { useUsagesStatus } from "./navigation";
import styles from "./Popups.module.css";
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
import { tx } from "@/platform/i18n";
import { executeAction } from "@/platform/actions";
@@ -681,7 +683,7 @@ function ReformatDialog({ popup }: { popup: Extract<LspPopup, { kind: "reformat"
open
onClose={closePopup}
title={popup.title}
width={380}
width={400}
buttons={[
{
label: "Run",
@@ -695,33 +697,27 @@ function ReformatDialog({ popup }: { popup: Extract<LspPopup, { kind: "reformat"
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.reformatBody}>
<fieldset className={styles.reformatGroup}>
<legend className={styles.reformatLegend}>
<div className={fieldsetStyles.body}>
<fieldset className={fieldsetStyles.group}>
<legend className={fieldsetStyles.legend}>
<T>Scope</T>
</legend>
<label className={styles.reformatOption}>
<input
type="radio"
name="reformat-scope"
checked={!selectionOnly}
onChange={() => setSelectionOnly(false)}
/>
<T>Whole file</T>
</label>
<label className={clsx(styles.reformatOption, !popup.hasSelection && styles.disabled)}>
<input
type="radio"
name="reformat-scope"
checked={selectionOnly}
disabled={!popup.hasSelection}
onChange={() => setSelectionOnly(true)}
/>
<T>Selected text</T>
</label>
<Radio
name="reformat-scope"
checked={selectionOnly}
disabled={!popup.hasSelection}
onChange={() => setSelectionOnly(true)}
label="Selected text"
/>
<Radio
name="reformat-scope"
checked={!selectionOnly}
onChange={() => setSelectionOnly(false)}
label="Whole file"
/>
</fieldset>
<fieldset className={styles.reformatGroup}>
<legend className={styles.reformatLegend}>
<fieldset className={fieldsetStyles.group}>
<legend className={fieldsetStyles.legend}>
<T>Options</T>
</legend>
<Checkbox
+5 -3
Переглянути файл
@@ -232,8 +232,10 @@
.conversationRow[data-measured] {
content-visibility: auto;
}
/* Keep turns distinct and the work within a turn close to its author. */
.stream > * + * {
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every
DOM insertion anywhere in the window, which costs every editor scroll frame. */
.stream > :where(:not(:first-child)) {
margin-top: var(--space-4);
}
.stream > [data-process] + [data-process] {
@@ -336,7 +338,7 @@
.agentAuthor > .role {
margin-bottom: 0;
}
.agentAuthor + * {
:where(.conversationRow[data-author]) > :nth-child(2) {
margin-top: calc(var(--space-2) / 2);
}
.conversationRow > .process,
+6 -5
Переглянути файл
@@ -29,7 +29,7 @@ function task(id: string, title: string, cwd: string): AgentTask {
}
/** A turn as agents work: a request, reasoning, a run of tool calls, then a reply with code. */
function turn(cwd: string, i: number): AgentEntry[] {
function turn(cwd: string, i: number, title: string): AgentEntry[] {
const file = (k: number) => `${cwd}/src/orders/Order${(i + k) % 40}.kt`;
const tools: AgentEntry[] = Array.from({ length: 10 }, (_, k) => {
// Tool titles as agents report them (commands and paths, not UI text).
@@ -49,7 +49,8 @@ function turn(cwd: string, i: number): AgentEntry[] {
};
});
// What a user and an agent wrote (conversation content, not UI text).
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests`;
// Ends with the task's title, so each conversation shown can be told apart.
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests (${title})`;
const reasoning = `The payment client throws on timeouts; retrying belongs in the service (turn ${i}).`;
return [
{
@@ -94,14 +95,14 @@ function turn(cwd: string, i: number): AgentEntry[] {
/** Opens `count` tasks of `turns` turns each (14 entries a turn), the last one shown. */
export function openSampleConversations(count: number, turns: number) {
const cwd = useProject.getState().project?.root ?? "/";
const entries = Array.from({ length: turns }, (_, i) => turn(cwd, i)).flat();
const s = useAgents.getState();
const tasks = new Map(s.tasks);
const all = new Map(s.entries);
const ids = Array.from({ length: count }, (_, n) => `sample-${n + 1}`);
ids.forEach((id, n) => {
tasks.set(id, task(id, `Sample task ${n + 1}`, cwd));
all.set(id, entries);
const title = `Sample task ${n + 1}`;
tasks.set(id, task(id, title, cwd));
all.set(id, Array.from({ length: turns }, (_, i) => turn(cwd, i, title)).flat());
});
useAgents.setState({ tasks, entries: all });
for (const id of ids) openTask(id);
+1
Переглянути файл
@@ -559,6 +559,7 @@ export function Stream({
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
+15
Переглянути файл
@@ -199,6 +199,21 @@
align-items: center;
gap: var(--space-2);
}
.reformatSubject {
overflow-wrap: anywhere;
font-size: var(--fs-ui);
font-weight: 600;
}
.reformatMask {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
}
.reformatMaskInput {
flex: 1 1 12ch;
min-width: 0;
}
.languageSelect {
min-width: 180px;
}
+41 -30
Переглянути файл
@@ -29,6 +29,7 @@ import {
type StructuralForm,
} from "./structural";
import styles from "./Analysis.module.css";
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
@@ -168,40 +169,50 @@ function ReformatCodeDialog({ targets, onClose }: { targets: readonly ReformatTa
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
<div className={styles.hint}>{subject}</div>
{targets.some((t) => t.dir) && (
<div className={fieldsetStyles.body}>
<div className={styles.reformatSubject}>{subject}</div>
<fieldset className={fieldsetStyles.group}>
<legend className={fieldsetStyles.legend}>
<T>Options</T>
</legend>
<Checkbox
checked={options.recursive}
onChange={(recursive) => setOptions({ ...options, recursive })}
label="Include subdirectories"
checked={options.optimizeImports}
onChange={(optimizeImports) => setOptions({ ...options, optimizeImports })}
label="Optimize imports"
/>
)}
<Checkbox
checked={options.optimizeImports}
onChange={(optimizeImports) => setOptions({ ...options, optimizeImports })}
label="Optimize imports"
/>
<Checkbox
checked={options.changedTextOnly}
onChange={(changedTextOnly) => setOptions({ ...options, changedTextOnly })}
label="Only VCS changed text"
/>
<div className={styles.fieldRow}>
<Checkbox
checked={options.useMask}
onChange={(useMask) => setOptions({ ...options, useMask })}
label="File mask:"
checked={options.changedTextOnly}
onChange={(changedTextOnly) => setOptions({ ...options, changedTextOnly })}
label="Only VCS changed text"
/>
<Input
className={styles.grow}
value={options.mask}
disabled={!options.useMask}
placeholder="*.sh, *.py"
onChange={(e) => setOptions({ ...options, mask: e.target.value })}
aria-label="File mask"
/>
</div>
{targets.some((t) => t.dir) && (
<Checkbox
checked={options.recursive}
onChange={(recursive) => setOptions({ ...options, recursive })}
label="Include subdirectories"
/>
)}
</fieldset>
<fieldset className={fieldsetStyles.group}>
<legend className={fieldsetStyles.legend}>
<T>Filters</T>
</legend>
<div className={styles.reformatMask}>
<Checkbox
checked={options.useMask}
onChange={(useMask) => setOptions({ ...options, useMask })}
label="File mask:"
/>
<Input
className={styles.reformatMaskInput}
value={options.mask}
disabled={!options.useMask}
placeholder="*.sh, *.py"
onChange={(e) => setOptions({ ...options, mask: e.target.value })}
aria-label="File mask"
/>
</div>
</fieldset>
<div className={styles.hint}>
<T>Files are reformatted by their language's formatter and saved; files without one are skipped.</T>
</div>
+140 -78
Переглянути файл
@@ -21,7 +21,20 @@ import {
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { Button, Checkbox, Dialog, Icon, Input, Select, type SelectOption, T, hasIcon } from "@/ui";
import {
Checkbox,
Dialog,
Icon,
IconButton,
Input,
Select,
SplitGroup,
SplitHandle,
SplitPanel,
type SelectOption,
T,
hasIcon,
} from "@/ui";
import { effectiveValues, fieldError, isVisible, type Values } from "./newProjectTemplate";
import { defaultProjectDirectory, openProjectInWindow } from "./windows";
import styles from "./newProject.module.css";
@@ -116,6 +129,20 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
const [requirements, setRequirements] = useState<Requirement[]>([]);
const [jdks, setJdks] = useState<Sdk[] | null>(null);
const [job, setJob] = useState<Job | null>(null);
const layout = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
const configuring = job === null;
useEffect(() => {
const el = layout.current;
if (!configuring || !el || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(([entry]) => {
const width = entry?.contentRect.width;
if (width) setStacked(width < 580);
});
observer.observe(el);
return () => observer.disconnect();
}, [configuring]);
useEffect(() => {
if (initialLocation()) return;
@@ -265,8 +292,19 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.layout}>
<div className={styles.sidebar}>
<SplitGroup
className={styles.layout}
elementRef={layout}
orientation={stacked ? "vertical" : "horizontal"}
storageKey="openidea.newProject.layout"
>
<SplitPanel
id="new-project-generators"
defaultSize="25%"
minSize={stacked ? "28%" : "148px"}
maxSize="45%"
className={styles.sidebar}
>
<Input
className={styles.search}
value={query}
@@ -286,6 +324,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
role="option"
aria-selected={g.id === selected}
className={styles.entry}
title={tx(g.name)}
onClick={() => setSelected(g.id)}
>
<Icon name={hasIcon(g.icon) ? g.icon : "folder"} />
@@ -295,82 +334,95 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
</div>
))}
</div>
</div>
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void createProject();
}}
>
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
<div className={styles.grid}>
<label className={styles.label} htmlFor="np-name">
<T>Name:</T>
</label>
<Input
id="np-name"
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => setName(e.target.value)}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
</label>
<div className={styles.inline}>
<Input id="np-location" value={location} onChange={(e) => setLocation(e.target.value)} />
<Button onClick={() => void browse()} disabled={!isTauri()}>
<T>Browse…</T>
</Button>
</div>
<span />
<div className={styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
<>
<span />
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
</>
)}
{visibleFields.map((f) => (
<FieldRow
key={f.id}
field={f}
value={values[f.id] ?? ""}
onChange={(v) => setValue(f.id, v)}
jdks={jdks}
</SplitPanel>
<SplitHandle aria-label={tx("Generators")} />
<SplitPanel id="new-project-form" defaultSize="75%">
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void createProject();
}}
>
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
<div className={styles.grid}>
<label className={styles.label} htmlFor="np-name">
<T>Name:</T>
</label>
<Input
id="np-name"
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => setName(e.target.value)}
/>
))}
{loadingDynamic && (
<>
<span />
<div className={styles.hint}>
<T>Loading options…</T>
</div>
</>
)}
{dynamicError && (
<>
<span />
<div className={styles.error}>{txTemplate(dynamicError)}</div>
</>
)}
</div>
{missing.map((r) => (
<div key={r.program} className={styles.missing}>
<Icon name="warning" />
<span>
{r.found
? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.`
: tx`${r.program} is not installed.`}{" "}
{r.hint && tx(r.hint)}
</span>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
</label>
<div className={styles.location}>
<Input
id="np-location"
variant="bare"
className={styles.locationInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton
icon="folder-open"
title="Browse…"
size="small"
onClick={() => void browse()}
disabled={!isTauri()}
/>
</div>
<span />
<div className={styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
<>
<span />
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
</>
)}
{visibleFields.map((f) => (
<FieldRow
key={f.id}
field={f}
value={values[f.id] ?? ""}
onChange={(v) => setValue(f.id, v)}
jdks={jdks}
/>
))}
{loadingDynamic && (
<>
<span />
<div className={styles.hint}>
<T>Loading options…</T>
</div>
</>
)}
{dynamicError && (
<>
<span />
<div className={styles.error}>{txTemplate(dynamicError)}</div>
</>
)}
</div>
))}
</form>
</div>
{missing.map((r) => (
<div key={r.program} className={styles.missing}>
<Icon name="warning" />
<span>
{r.found
? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.`
: tx`${r.program} is not installed.`}{" "}
{r.hint && tx(r.hint)}
</span>
</div>
))}
</form>
</SplitPanel>
</SplitGroup>
</Dialog>
);
}
@@ -420,6 +472,7 @@ function FieldRow({
control = (
<Select
id={id}
className={styles.fieldSelect}
value={value}
options={kind.options.map((o) => ({ value: o.value, label: o.label }))}
onChange={onChange}
@@ -438,7 +491,16 @@ function FieldRow({
})),
];
if (value && !options.some((o) => o.value === value)) options.push({ value, label: value, verbatim: true });
control = <Select id={id} value={value} options={options} onChange={onChange} aria-label={tx(field.label)} />;
control = (
<Select
id={id}
className={styles.fieldSelect}
value={value}
options={options}
onChange={onChange}
aria-label={tx(field.label)}
/>
);
} else if (kind.type === "dependencies")
control = <DependencyPicker id={id} groups={kind.groups} value={value} onChange={onChange} />;
else
+59 -24
Переглянути файл
@@ -2,39 +2,42 @@
.dialog {
height: min(602px, calc(100vh - 48px));
}
.dialog [data-dialog-body] {
overflow: hidden;
}
.dialog [data-dialog-footer] {
border-top: 1px solid var(--border);
}
.layout {
display: grid;
grid-template-columns: 220px 1fr;
height: 100%;
min-height: 0;
}
.sidebar {
display: flex;
flex-direction: column;
min-height: 0;
border-right: 1px solid var(--border);
background: var(--bg-island);
}
.search {
margin: 8px;
flex: none;
margin: var(--space-2);
}
.list {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 0 4px 8px;
padding: 0 var(--space-1) var(--space-2);
}
.groupLabel {
padding: 8px 8px 4px;
padding: var(--space-2) var(--space-2) var(--space-1);
color: var(--fg-subtle);
font-size: var(--fs-small);
font-weight: 600;
overflow-wrap: anywhere;
}
.entry {
display: flex;
align-items: center;
gap: var(--space-2);
width: 100%;
height: 26px;
padding: 0 8px;
height: var(--h-list-row);
padding: 0 var(--space-2);
border: 0;
border-radius: var(--radius-control, 4px);
background: transparent;
@@ -42,6 +45,12 @@
font: inherit;
text-align: left;
}
.entry > span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.entry:hover {
background: var(--bg-hover);
}
@@ -54,33 +63,50 @@
outline-offset: -2px;
}
.form {
flex: 1;
display: flex;
flex-direction: column;
gap: 10px;
gap: var(--space-3);
min-width: 0;
min-height: 0;
overflow-y: auto;
padding: 16px;
overflow: auto;
padding: var(--space-4);
font-size: var(--fs-ui);
}
.description {
color: var(--fg-subtle);
overflow-wrap: anywhere;
}
.grid {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
grid-template-columns: fit-content(38%) minmax(0, 1fr);
align-items: center;
gap: var(--space-2) var(--space-3);
}
.label {
color: var(--fg);
white-space: nowrap;
overflow-wrap: anywhere;
}
.inline {
.location {
display: flex;
gap: var(--space-2);
align-items: center;
padding-inline-end: var(--space-1);
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
}
.inline > :first-child {
.location:focus-within {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.location .locationInput {
flex: 1;
min-width: 0;
padding-inline: var(--space-2);
}
.fieldSelect {
max-width: 100%;
}
.hint,
.fieldHint {
@@ -112,17 +138,22 @@
}
.segmented {
display: inline-flex;
flex-wrap: wrap;
max-width: 100%;
border-radius: var(--radius-control, 4px);
box-shadow: inset 0 0 0 1px var(--border-button);
}
.segmented button {
height: var(--h-field, 28px);
padding: 0 14px;
min-height: var(--h-field, 28px);
min-width: 0;
max-width: 100%;
padding: var(--space-1) var(--space-3);
border: 0;
border-radius: inherit;
background: transparent;
color: var(--fg);
font: inherit;
overflow-wrap: anywhere;
}
.segmented button[aria-pressed="true"] {
background: var(--bg-tab-selected);
@@ -147,14 +178,18 @@
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 22px;
padding: 0 6px 0 8px;
min-height: 22px;
min-width: 0;
max-width: 100%;
padding: 0 var(--space-1-5) 0 var(--space-2);
border: 1px solid var(--border);
border-radius: 11px;
background: var(--bg-control);
color: var(--fg);
font: inherit;
font-size: var(--fs-small);
overflow-wrap: anywhere;
text-align: left;
}
.chip:hover {
background: var(--bg-control-hover);
+11 -15
Переглянути файл
@@ -10,18 +10,18 @@
background: none;
}
.toolbar {
height: 32px;
min-height: var(--h-header);
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) var(--space-1-5);
}
.toolbarGroup {
display: flex;
align-items: center;
gap: var(--space-0-5);
padding: 0 6px;
}
.sep {
width: 1px;
height: 16px;
margin: 0 4px;
background: var(--border);
}
.note {
flex: none;
@@ -29,6 +29,7 @@
font-size: var(--fs-small);
font-style: italic;
color: var(--fg-subtle);
overflow-wrap: anywhere;
}
.body {
flex: 1;
@@ -49,17 +50,12 @@
white-space: nowrap;
}
.name {
color: var(--fg);
}
.detail {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
color: var(--fg-strong);
}
.muted {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.error {
flex: none;
+49 -43
Переглянути файл
@@ -106,35 +106,37 @@ function HierarchyToolbar() {
const autoscroll = useHierarchyOptions((s) => s.autoscroll);
return (
<div className={styles.toolbar} role="toolbar" aria-label={tx("Hierarchy actions")}>
<IconButton
icon="arrow-up"
size="small"
iconSize={16}
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
pressed={direction === "incoming"}
onClick={() => setDirection("incoming")}
/>
<IconButton
icon="arrow-down"
size="small"
iconSize={16}
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
pressed={direction === "outgoing"}
onClick={() => setDirection("outgoing")}
/>
<span className={styles.sep} />
<div className={styles.toolbarGroup}>
<IconButton
icon="arrow-up"
size="small"
iconSize={16}
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
pressed={direction === "incoming"}
onClick={() => setDirection("incoming")}
/>
<IconButton
icon="arrow-down"
size="small"
iconSize={16}
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
pressed={direction === "outgoing"}
onClick={() => setDirection("outgoing")}
/>
</div>
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshHierarchy} />
<span className={styles.sep} />
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
<IconButton
icon="autoscroll-to-source"
size="small"
iconSize={16}
title="Autoscroll to Source"
pressed={autoscroll}
onClick={() => useHierarchyOptions.setState({ autoscroll: !autoscroll })}
/>
<div className={styles.toolbarGroup}>
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
<IconButton
icon="autoscroll-to-source"
size="small"
iconSize={16}
title="Autoscroll to Source"
pressed={autoscroll}
onClick={() => useHierarchyOptions.setState({ autoscroll: !autoscroll })}
/>
</div>
</div>
);
}
@@ -183,13 +185,9 @@ export function HierarchyView() {
const renderNode = (n: Node, _state: TreeRowState) => {
if (n.kind === "root") {
return (
<span className={styles.row}>
<span className={styles.row} title={`${root.name}\n${relativePath(projectRoot, root.path)}:${root.line + 1}`}>
<SymbolBadge kind={mode === "call" ? "function" : "class"} />
<span className={styles.name}>{root.name}</span>
{root.detail && <span className={styles.detail}>{root.detail}</span>}
<span className={styles.muted}>
{basename(root.path)}:{root.line + 1}
</span>
{loading && <Spinner size={12} />}
{failed.has(ROOT_ID) && (
<span className={styles.error}>
@@ -199,35 +197,42 @@ export function HierarchyView() {
{!loading && !failed.has(ROOT_ID) && children.get(ROOT_ID)?.length === 0 && (
<span className={styles.muted}>{noneFoundLabel(mode, direction)}</span>
)}
{root.detail && <span className={styles.muted}>{root.detail}</span>}
<span className={styles.muted}>
{basename(root.path)}:{root.line + 1}
</span>
</span>
);
}
const { item } = n.node;
const calls = item.fromRanges.length;
return (
<span className={styles.row} title={relativePath(projectRoot, item.path)}>
<span
className={styles.row}
title={`${item.name}\n${relativePath(projectRoot, item.path)}:${item.selectionRange.start.line + 1}`}
>
<SymbolBadge kind={badgeKind(item.kind)} />
<span className={styles.name}>{item.name}</span>
{item.detail && <span className={styles.detail}>{item.detail}</span>}
<span className={styles.muted}>
{basename(item.path)}:{item.selectionRange.start.line + 1}
</span>
{calls > 1 && <span className={styles.muted}>{tx`(${calls} calls)`}</span>}
{n.node.recursion && (
<span className={styles.muted}>
<T>recursive</T>
</span>
)}
{notes.has(n.id) && (
<span className={styles.muted} title={notes.get(n.id)}>
{notes.get(n.id)}
</span>
)}
{failed.has(n.id) && (
<span className={styles.error}>
<T>failed to load</T>
</span>
)}
{item.detail && <span className={styles.muted}>{item.detail}</span>}
<span className={styles.muted}>
{basename(item.path)}:{item.selectionRange.start.line + 1}
</span>
{notes.has(n.id) && (
<span className={styles.muted} title={notes.get(n.id)}>
{notes.get(n.id)}
</span>
)}
</span>
);
};
@@ -244,6 +249,7 @@ export function HierarchyView() {
<Tree<Node>
key={generation}
aria-label={mode === "call" ? "Call hierarchy" : "Type hierarchy"}
horizontalScroll
roots={roots}
getKey={(n) => n.id}
getLabel={(n) => (n.kind === "root" ? root.name : n.node.item.name)}
+1 -1
Переглянути файл
@@ -37,7 +37,7 @@
flex: none;
align-items: center;
}
.stack > * + * {
.stack > :where(:not(:first-child)) {
margin-left: calc(var(--overlap) * -1);
}
.stack > .ringed + .ringed {
+1 -1
Переглянути файл
@@ -115,7 +115,7 @@
flex: 1 1 50%;
min-width: 0;
}
.body > * + * {
.body > :where(:not(:first-child)) {
border-left: 1px solid var(--border);
}
.hidden {
+54
Переглянути файл
@@ -10,6 +10,60 @@
font-size: var(--fs-ui);
}
.moveForm {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
}
.moveSubject {
color: var(--fg-emphasis);
font-size: var(--fs-ui);
font-weight: 600;
overflow-wrap: anywhere;
}
.moveDestination {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: var(--space-1) var(--space-2);
}
.moveDestination > .fieldLabel {
line-height: var(--h-field);
}
.moveControls {
display: flex;
flex: 1 1 244px;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.moveField {
display: flex;
align-items: center;
gap: var(--space-1);
}
.moveField input {
flex: 1 1 0;
}
.moveField button {
flex: none;
}
.movePath {
color: var(--fg-subtle);
font-size: var(--fs-small);
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
.fieldLabel {
color: var(--fg);
font-size: var(--fs-ui);
+87 -35
Переглянути файл
@@ -6,7 +6,10 @@
import { useEffect, useRef, useState } from "react";
import { create } from "zustand";
import type { FileMove } from "@/bindings";
import { Checkbox, Dialog, Input, Spinner, T } from "@/ui";
import { Checkbox, Dialog, IconButton, Input, Spinner, T } from "@/ui";
import { choosePath } from "@/platform/choosePath";
import { isTauri } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
import { runFileRefactoring, type FileRefactorOptions } from "./fileRefactor";
import {
isSameOrInside,
@@ -253,31 +256,59 @@ function RenameDialog({ request }: { request: Extract<FileRefactorRequest, { kin
/** Folder `typed` (absolute, or relative to the project root). */
function resolveTarget(typed: string, root: string): string {
const t = typed.trim().replace(/\/+$/, "");
if (!t) return root;
return t.startsWith("/") || /^[A-Za-z]:[\\/]/.test(t) ? t : joinPath(root, t);
const value = ipcPath(typed.trim());
if (!value) return root;
const absolute = value.startsWith("/") || /^[A-Za-z]:\//.test(value);
const isRoot = /^(?:[A-Za-z]:)?\/+$/.test(value);
const path = value.replace(/\/+$/, isRoot ? "/" : "");
return absolute ? path : joinPath(root, path);
}
function MoveDialog({ request }: { request: Extract<FileRefactorRequest, { kind: "move" }> }) {
const root = useProjectTree((s) => s.root) ?? "";
const [target, setTarget] = useState(request.target);
const [options, setOptions] = useState(() => loadOptions("move"));
const [browsing, setBrowsing] = useState(false);
const [browseError, setBrowseError] = useState<string | null>(null);
const field = useRef<HTMLInputElement>(null);
const { busy, run, cancel } = useSearch();
useEffect(() => {
const input = field.current;
const path = request.target.replace(/[\\/]+$/, "");
if (!input || !path || /^[A-Za-z]:$/.test(path)) return;
const start = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1;
input.setSelectionRange(start, path.length);
input.scrollLeft = input.scrollWidth;
}, [request.target]);
const dest = resolveTarget(target, root);
const moves: FileMove[] = request.paths
.filter((p) => parentOf(p) !== dest)
.map((p) => ({ from: p, to: joinPath(dest, nameOf(p)) }));
.map((from) => ({ from, to: joinPath(dest, nameOf(from)) }))
.filter((move) => move.from !== move.to);
const error = request.paths.some((p) => isSameOrInside(dest, p))
? "Cannot move a folder into itself"
? tx("Cannot move a folder into itself")
: !moves.length
? "Already in this directory"
? tx("Already in this directory")
: null;
const subject =
request.paths.length === 1
? `Move ${request.dir || useProjectTree.getState().listings.has(request.paths[0]!) ? "directory" : "file"} '${nameOf(request.paths[0]!)}'`
: `Move ${request.paths.length} items`;
const single = request.paths.length === 1 ? request.paths[0]! : null;
const subject = single
? request.dir || useProjectTree.getState().listings.has(single)
? tx`Move directory '${nameOf(single)}'`
: tx`Move file '${nameOf(single)}'`
: tx`Move ${request.paths.length} items`;
const browse = async () => {
setBrowsing(true);
setBrowseError(null);
try {
const picked = await choosePath({ directory: true, title: tx("Select Target Directory"), defaultPath: dest });
if (picked !== null) setTarget(ipcPath(picked));
} catch (e) {
setBrowseError(e instanceof Error ? e.message : String(e));
} finally {
setBrowsing(false);
}
};
const submit = async () => {
if (busy || error) return;
if (busy || browsing || error) return;
saveOptions("move", options);
const status = await run(moves, options, "Move");
if (status !== "done") return;
@@ -291,38 +322,59 @@ function MoveDialog({ request }: { request: Extract<FileRefactorRequest, { kind:
width={520}
footerStart={busy ? <Busy /> : undefined}
buttons={[
{ label: "Refactor", role: "default", disabled: busy || !!error, onClick: () => void submit() },
{ label: "Refactor", role: "default", disabled: busy || browsing || !!error, onClick: () => void submit() },
{ label: "Cancel", role: "cancel", onClick: cancel },
]}
>
<form
className={styles.form}
className={styles.moveForm}
onSubmit={(e) => {
e.preventDefault();
void submit();
}}
>
<div className={styles.subject}>{subject}</div>
<label className={styles.fieldLabel} htmlFor="file-move-target">
<T>To directory:</T>
</label>
<Input
id="file-move-target"
autoFocus
mono
value={target}
disabled={busy}
invalid={!!error}
aria-label="Target directory"
onChange={(e) => setTarget(e.target.value)}
/>
<div className={styles.hint}>{relativeTo(root, dest) || (dest === root ? tx("Project root") : dest)}</div>
{error && (
<div className={styles.error} role="alert">
{error}
<div className={styles.moveSubject}>{subject}</div>
<div className={styles.moveDestination}>
<label className={styles.fieldLabel} htmlFor="file-move-target">
<T>To directory:</T>
</label>
<div className={styles.moveControls}>
<div className={styles.moveField}>
<Input
id="file-move-target"
ref={field}
data-autofocus
mono
value={target}
disabled={busy}
invalid={!!error}
aria-label="Target directory"
aria-describedby="file-move-preview"
onChange={(e) => {
setBrowseError(null);
setTarget(e.target.value);
}}
/>
{isTauri() && (
<IconButton
icon="folder-open"
title={tx("Browse for target directory")}
disabled={busy || browsing}
onClick={() => void browse()}
/>
)}
</div>
<div className={styles.movePath} id="file-move-preview" title={dest}>
{relativeTo(root, dest) || (dest === root ? tx("Project root") : dest)}
</div>
{(browseError ?? error) && (
<div className={styles.error} role="alert">
{browseError ?? error}
</div>
)}
<Options value={options} onChange={setOptions} move disabled={busy} />
</div>
)}
<Options value={options} onChange={setOptions} move disabled={busy} />
</div>
</form>
</Dialog>
);
+7 -3
Переглянути файл
@@ -107,6 +107,9 @@ type ResolvedNode = Exclude<MemNode, { kind: "symlink" }>;
const err = (kind: "notFound" | "alreadyExists" | "invalidInput", message: string) => new IpcError({ kind, message });
/** Created once: building a collator costs more than sorting a small folder with it. */
const naturalOrder = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
/** The tree's own notion (see `isDirEntry`): a folder, or a link to one. */
const isFolder = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.size === 0);
@@ -161,13 +164,14 @@ export class MemoryFs implements ProjectFs {
const { path, node } = this.resolve(at);
if (!node) throw err("notFound", `${path} not found`);
if (node.kind !== "dir") throw err("invalidInput", `${at} is not a directory`);
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
// A child is excluded when its folder is, or when it is itself an excluded path.
const inExcluded = [...this.ignored].some((i) => path === i || isInside(path, i));
return (
this.childrenOf(path)
.map((p) => {
const c = this.nodes.get(p)!;
const name = nameOf(p);
const excluded = [...this.ignored].some((i) => p === i || isInside(p, i));
const excluded = inExcluded || this.ignored.has(p);
if (c.kind === "symlink") {
const t = this.resolve(p);
return {
@@ -195,7 +199,7 @@ export class MemoryFs implements ProjectFs {
} satisfies FileEntry;
})
// Folders first, counting a link to a folder as a folder (the backend's ordering).
.sort((a, b) => Number(isFolder(b)) - Number(isFolder(a)) || collator.compare(a.name, b.name))
.sort((a, b) => Number(isFolder(b)) - Number(isFolder(a)) || naturalOrder.compare(a.name, b.name))
);
}
+6
Переглянути файл
@@ -17,6 +17,7 @@
flex: none;
}
.label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -38,6 +39,11 @@
white-space: pre;
color: var(--fg-subtle);
}
.lineNumber {
flex: none;
color: var(--fg-subtle);
font-variant-numeric: tabular-nums;
}
.mnemonic {
flex: none;
display: inline-flex;
+30 -15
Переглянути файл
@@ -286,7 +286,9 @@ export function BookmarksView() {
return (
<span className={styles.node}>
<Icon name="toolwindow-bookmarks" size={16} className={styles.icon} />
<span className={clsx(styles.label, n.isDefault && styles.defaultList)}>{n.list.name}</span>
<span className={clsx(styles.label, n.isDefault && styles.defaultList)} title={n.list.name}>
{n.list.name}
</span>
<span className={styles.meta}>
{t("search.bookmarks.count", { count: n.count })}
{n.isDefault ? tx(" · default") : ""}
@@ -297,7 +299,9 @@ export function BookmarksView() {
return (
<span className={styles.node}>
<Icon name="folder" size={16} className={styles.icon} />
<span className={styles.label}>{n.name}</span>
<span className={styles.label} title={n.path}>
{n.name}
</span>
<span className={styles.meta}>{n.dir}</span>
</span>
);
@@ -305,38 +309,49 @@ export function BookmarksView() {
return (
<span className={styles.node}>
<Icon name={fileIconName(n.name)} size={16} className={styles.icon} />
<span className={styles.label}>{n.name}</span>
<span className={styles.label} title={n.path}>
{n.name}
</span>
{n.bookmarked && <Icon name="bookmark" size={12} className={styles.icon} label="Bookmarked file" />}
<span className={styles.meta}>{n.dir}</span>
</span>
);
case "mark":
case "mark": {
const { bookmark } = n;
const line = bookmark.line + 1;
const label = bookmarkLabel(bookmark) || tx("(empty line)");
const isCommit = bookmark.path.startsWith("git-log:");
const fileAndLine = `${basename(bookmark.path)}:${line}`;
return (
<span className={styles.node}>
{n.bookmark.mnemonic ? (
<span className={styles.mnemonic} aria-label={`Mnemonic ${n.bookmark.mnemonic}`}>
{n.bookmark.mnemonic}
{bookmark.mnemonic ? (
<span className={styles.mnemonic} aria-label={`Mnemonic ${bookmark.mnemonic}`}>
{bookmark.mnemonic}
</span>
) : (
<Icon name="bookmark" size={16} className={styles.icon} />
)}
{n.bookmark.description ? (
{isCommit && !bookmark.description ? (
<>
<span className={styles.label}>{n.bookmark.description}</span>
<span className={styles.meta}>
{basename(n.bookmark.path)}:{n.bookmark.line + 1}
</span>
<span className={styles.label}>{fileAndLine}</span>
<span className={styles.code}>{label}</span>
</>
) : (
<>
<span className={styles.label}>
{basename(n.bookmark.path)}:{n.bookmark.line + 1}
{!isCommit && (
<span className={styles.lineNumber} title={`${bookmark.path}:${line}`}>
{line}:
</span>
)}
<span className={styles.label} title={label}>
{label}
</span>
<span className={styles.code}>{n.bookmark.text.trim() || tx("(empty line)")}</span>
{isCommit && <span className={styles.meta}>{fileAndLine}</span>}
</>
)}
</span>
);
}
}
}}
/>
+51 -39
Переглянути файл
@@ -1,15 +1,26 @@
.page {
display: flex;
flex-direction: column;
gap: var(--space-2);
height: 100%;
min-height: 420px;
min-height: 0;
min-width: 0;
}
.presetRow {
.presetRow,
.toolbar {
display: flex;
flex: none;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--space-1) var(--space-2);
}
.presetGroup {
display: flex;
align-items: center;
gap: 10px;
min-height: 30px;
margin-bottom: 6px;
flex: 0 1 328px;
min-width: 0;
gap: var(--space-2);
}
.presetLabel {
flex: none;
@@ -17,7 +28,7 @@
color: var(--fg);
}
.presetSelect {
min-width: 220px;
flex: 1;
}
.spacer {
flex: 1;
@@ -25,37 +36,44 @@
.modifiedNote {
color: var(--fg-subtle);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.toolbar {
.treeActions,
.filterGroup {
display: flex;
align-items: center;
gap: var(--space-0-5);
margin-bottom: 6px;
gap: var(--space-1);
}
.search {
flex: 1;
max-width: 360px;
margin-right: 4px;
.treeActions {
flex: none;
}
.filterGroup {
flex: 1 1 300px;
min-width: 0;
max-width: 392px;
}
.search,
.shortcutFilter {
flex: 1;
max-width: 360px;
min-width: 0;
}
.shortcutFilter {
display: flex;
align-items: center;
gap: var(--space-0-5);
height: var(--h-control);
margin-right: 4px;
padding: 0 2px 0 8px;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
gap: var(--space-1);
height: var(--h-field);
padding: 0 var(--space-1) 0 var(--space-2);
background: var(--bg-field);
border-radius: var(--radius-control);
box-shadow: inset 0 0 0 1px var(--border-button);
}
.shortcutFilter:focus-within {
box-shadow: inset 0 0 0 1px var(--accent);
box-shadow: inset 0 0 0 1px var(--focus-ring);
}
.leading {
flex: none;
color: var(--fg-subtle);
margin-right: 4px;
}
.filterRecorder {
flex: 1;
@@ -67,6 +85,11 @@
box-shadow: none;
outline: none;
}
.filterRecorder > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.treeWrap {
flex: 1;
@@ -75,7 +98,7 @@
flex-direction: column;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border);
padding: 2px 0;
padding-block: var(--space-0-5);
}
.empty {
padding: 8px 12px;
@@ -97,26 +120,21 @@
}
.actionIcon {
display: inline-flex;
flex: none;
width: 14px;
color: var(--fg-subtle);
}
.actionTitle {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1 0 auto;
}
.modified {
color: var(--accent);
}
.bindings {
display: inline-flex;
gap: var(--space-1);
padding-right: 10px;
}
.kbd {
color: var(--fg-muted);
flex: none;
gap: var(--space-2);
padding-inline: var(--space-2);
}
/* recorder */
@@ -221,12 +239,6 @@
font-size: var(--fs-small);
}
.toolbarSep {
width: 1px;
height: 16px;
margin: 0 4px;
background: var(--border);
}
.conflictsLabel {
color: var(--fg);
padding-top: 4px;
+82 -78
Переглянути файл
@@ -373,26 +373,27 @@ export function KeymapPage() {
return (
<div className={styles.page}>
<div className={styles.presetRow}>
<span className={styles.presetLabel}>
<SearchLabel text="Keymap:" />
</span>
<Select
value={selectedId}
aria-label="Keymap"
className={styles.presetSelect}
options={keymapOptions}
onChange={selectKeymap}
/>
<IconButton
ref={gearRef}
icon="settings"
title="Show Scheme Actions"
onClick={() => {
const r = gearRef.current?.getBoundingClientRect();
showContextMenu(r ? { x: r.left, y: r.bottom + 2 } : { x: 0, y: 0 }, gearMenu());
}}
/>
<span className={styles.spacer} />
<div className={styles.presetGroup}>
<span className={styles.presetLabel}>
<SearchLabel text="Keymap:" />
</span>
<Select
value={selectedId}
aria-label="Keymap"
className={styles.presetSelect}
options={keymapOptions}
onChange={selectKeymap}
/>
<IconButton
ref={gearRef}
icon="settings"
title="Show Scheme Actions"
onClick={() => {
const r = gearRef.current?.getBoundingClientRect();
showContextMenu(r ? { x: r.left, y: r.bottom + 2 } : { x: 0, y: 0 }, gearMenu());
}}
/>
</div>
{overrideCount > 0 && (
<span className={styles.modifiedNote}>
{overrideCount === 1 ? tx`${overrideCount} modified action` : tx`${overrideCount} modified actions`}
@@ -401,68 +402,71 @@ export function KeymapPage() {
</div>
<div className={styles.toolbar}>
{byShortcut ? (
<div className={styles.shortcutFilter}>
<Icon name="keyboard" size={14} className={styles.leading} />
<StrokeRecorder
autoFocus
chord
value={shortcut}
onChange={setShortcut}
placeholder="Press a shortcut to find actions"
aria-label="Find actions by shortcut"
className={styles.filterRecorder}
/>
{shortcut && (
<IconButton icon="close" title="Clear" size="small" iconSize={12} onClick={() => setShortcut("")} />
)}
</div>
) : (
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder="Search actions"
aria-label="Search actions"
<div className={styles.treeActions}>
<IconButton icon="expand-all" title="Expand All" onClick={() => setCollapsed(new Set())} />
<IconButton icon="collapse-all" title="Collapse All" onClick={() => setCollapsed(new Set(allGroups))} />
<IconButton
icon="plus"
title="Add Keyboard Shortcut"
disabled={!leadAction}
onClick={() => {
if (!leadAction) return;
setRecordMouse(false);
setRecordFor(leadAction);
}}
/>
)}
<IconButton
icon="keyboard"
title="Find Actions by Shortcut"
pressed={byShortcut}
onClick={() => {
setByShortcut((v) => !v);
setShortcut("");
}}
/>
<IconButton
icon="filter"
title="Clear Filtering"
disabled={!filtering}
onClick={() => {
setQuery("");
setShortcut("");
}}
/>
<span className={styles.toolbarSep} aria-hidden />
<IconButton icon="expand-all" title="Expand All" onClick={() => setCollapsed(new Set())} />
<IconButton icon="collapse-all" title="Collapse All" onClick={() => setCollapsed(new Set(allGroups))} />
<span className={styles.spacer} />
<IconButton
icon="plus"
title="Add Keyboard Shortcut"
disabled={!leadAction}
onClick={() => {
if (!leadAction) return;
setRecordMouse(false);
setRecordFor(leadAction);
}}
/>
</div>
<div className={styles.filterGroup}>
{byShortcut ? (
<div className={styles.shortcutFilter}>
<Icon name="keyboard" size={14} className={styles.leading} />
<StrokeRecorder
autoFocus
chord
value={shortcut}
onChange={setShortcut}
placeholder="Press a shortcut to find actions"
aria-label="Find actions by shortcut"
className={styles.filterRecorder}
/>
{shortcut && (
<IconButton icon="close" title="Clear" size="small" iconSize={12} onClick={() => setShortcut("")} />
)}
</div>
) : (
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder="Search actions"
aria-label="Search actions"
/>
)}
<IconButton
icon="keyboard"
title="Find Actions by Shortcut"
pressed={byShortcut}
onClick={() => {
setByShortcut((v) => !v);
setShortcut("");
}}
/>
<IconButton
icon="filter"
title="Clear Filtering"
disabled={!filtering}
onClick={() => {
setQuery("");
setShortcut("");
}}
/>
</div>
</div>
<div className={styles.treeWrap}>
<Tree<KNode>
aria-label="Actions"
horizontalScroll
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "group" ? n.name : n.action.title)}
@@ -507,7 +511,7 @@ export function KeymapPage() {
<span className={styles.catName}>{n.name}</span>
</span>
) : (
<span className={styles.actionRow}>
<span className={styles.actionRow} title={n.action.title}>
<span className={styles.actionIcon}>{n.action.icon && <Icon name={n.action.icon} size={14} />}</span>
<HighlightedText
className={clsx(styles.actionTitle, n.modified && styles.modified)}
@@ -517,7 +521,7 @@ export function KeymapPage() {
/>
<span className={styles.bindings}>
{n.bindings.map((b) => (
<Kbd key={b} binding={b} className={styles.kbd} />
<Kbd key={b} binding={b} />
))}
</span>
</span>
+44 -66
Переглянути файл
@@ -1790,6 +1790,7 @@ function ArtifactsSection() {
function SdksSection() {
const byKind = useSdks((s) => s.byKind);
const homeId = useId();
const [downloading, setDownloading] = useState(false);
const [selectedKey, setSelectedKey] = useState<string>("");
const [projectJdk, setProjectJdk] = useProjectSetting<string>("languages.java.jdk");
@@ -1860,7 +1861,7 @@ function SdksSection() {
return (
<div className={styles.page}>
<div className={styles.splitLayout}>
<div className={clsx(styles.splitLayout, styles.sdkLayout)}>
<div className={styles.sideList}>
<div className={styles.tableToolbar}>
<IconButton
@@ -1902,6 +1903,7 @@ function SdksSection() {
type="button"
role="option"
aria-selected={activeSdk?.key === r.key}
title={`${r.name}\n${tildify(r.path)}`}
className={clsx(styles.sideItem, activeSdk?.key === r.key && styles.sideItemActive)}
onClick={() => setSelectedKey(r.key)}
>
@@ -1914,73 +1916,49 @@ function SdksSection() {
</div>
<div className={styles.detailPane}>
{activeSdk ? (
{activeSdk && (
<Section title="SDK Details">
<div className={styles.psModuleHeader}>
<span className={styles.badge}>{activeSdk.kindLabel}</span>
<span className={styles.psModuleTitle}>{activeSdk.name}</span>
{activeSdk.version && <span className={styles.versionCell}>{activeSdk.version}</span>}
<span className={styles.spacer} />
{activeSdk.kind === "jdk" && (
<Button
size="small"
variant="secondary"
disabled={projectJdk === activeSdk.path}
onClick={() => setProjectJdk(activeSdk.path)}
>
<T>Use as Project SDK</T>
</Button>
)}
</div>
<Row label="SDK home path">
<Input readOnly value={tildify(activeSdk.path)} title={activeSdk.path} />
</Row>
<dl className={styles.sdkProperties}>
<dt>
<T>Name</T>
</dt>
<dd className={styles.sdkName}>{activeSdk.name}</dd>
<dt>
<T>Type</T>
</dt>
<dd>{activeSdk.kindLabel}</dd>
<dt>
<T>Version</T>
</dt>
<dd className={styles.versionCell}>{activeSdk.version || "—"}</dd>
<dt>
<label htmlFor={homeId}>
<T>SDK home path</T>
</label>
</dt>
<dd>
<Input
id={homeId}
className={styles.sdkHome}
readOnly
value={tildify(activeSdk.path)}
title={activeSdk.path}
/>
</dd>
</dl>
{activeSdk.kind === "jdk" && (
<Button
className={styles.sdkAction}
size="small"
variant="secondary"
disabled={projectJdk === activeSdk.path}
onClick={() => setProjectJdk(activeSdk.path)}
>
<T>Use as Project SDK</T>
</Button>
)}
</Section>
) : null}
<div className={styles.tablePanel}>
<div className={styles.tableScroll}>
<table className={styles.table}>
<thead>
<tr>
<th>
<T>Type</T>
</th>
<th>
<T>Name</T>
</th>
<th>
<T>Version</T>
</th>
<th>
<T>Home Path</T>
</th>
</tr>
</thead>
<tbody>
{rows.length === 0 && (
<tr>
<td colSpan={4} className={styles.empty}>
<T>No SDK installations detected yet.</T>
</td>
</tr>
)}
{rows.map((r) => (
<tr key={r.key} onClick={() => setSelectedKey(r.key)}>
<td>
<span className={styles.badge}>{r.kindLabel}</span>
</td>
<td>{r.name}</td>
<td className={styles.versionCell}>{r.version || "—"}</td>
<td className={styles.path} title={r.path}>
{tildify(r.path)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
</div>
{downloading && (
+49
Переглянути файл
@@ -519,6 +519,55 @@
gap: 10px;
min-width: 0;
}
.sdkLayout {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
min-height: 0;
}
.sdkLayout > .sideList {
flex: 1 1 160px;
min-width: 0;
}
.sdkLayout > .detailPane {
flex: 3 1 280px;
}
.sdkLayout .sideItems {
max-height: min(360px, 42vh);
}
.sdkLayout .error {
overflow-wrap: anywhere;
}
.sdkProperties {
display: grid;
grid-template-columns: fit-content(40%) minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
margin: 0;
font-size: var(--fs-ui);
overflow-wrap: anywhere;
}
.sdkProperties dd {
margin: 0;
min-width: 0;
}
.sdkName {
color: var(--fg-strong);
font-weight: 600;
}
.sdkHome {
width: 100%;
}
.sdkLayout .sdkAction {
justify-self: start;
max-width: 100%;
height: auto;
min-height: var(--h-control);
margin-top: var(--space-3);
padding-block: var(--space-1);
line-height: 1.3;
white-space: normal;
}
.entryList {
display: flex;
flex-direction: column;
+10 -24
Переглянути файл
@@ -1,40 +1,26 @@
.page {
display: flex;
flex-direction: column;
min-width: 0;
max-width: 760px;
}
.scheme {
display: inline-flex;
display: flex;
flex: 1 1 100%;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
min-width: 0;
}
.tabs {
display: flex;
gap: var(--space-1);
margin: 8px 0 4px;
margin: var(--space-2) 0 var(--space-2);
border-bottom: 1px solid var(--border);
font-size: var(--fs-ui);
}
.tab {
height: 26px;
padding: 0 10px;
border: none;
border-bottom: 2px solid transparent;
background: none;
color: var(--fg-secondary);
font: inherit;
cursor: default;
}
.tab:hover {
color: var(--fg);
}
.tabOn {
color: var(--fg);
border-bottom-color: var(--accent);
}
.tab:focus-visible {
outline: none;
box-shadow: inset 0 0 0 1px var(--accent);
.panel {
min-width: 0;
padding-bottom: var(--space-3);
}
+52 -25
Переглянути файл
@@ -2,21 +2,30 @@
display: flex;
flex-direction: column;
height: 100%;
min-width: 0;
min-height: 420px;
}
.profileRow {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
gap: var(--space-1) var(--space-3);
min-height: 30px;
margin-bottom: 8px;
margin-bottom: var(--space-2);
}
.profileSelect {
min-width: 220px;
.profileControls {
display: flex;
align-items: center;
gap: var(--space-2);
max-width: 100%;
min-width: 0;
}
.profileRow > span {
.profileControls > span {
flex: none;
white-space: nowrap;
}
.profileControls > .profileSelect {
width: 220px;
min-width: 0;
}
.toolbar {
display: flex;
@@ -26,24 +35,19 @@
}
.search {
flex: 1;
min-width: 0;
max-width: 320px;
margin-right: 4px;
margin-right: var(--space-1);
}
.split {
flex: 1;
min-width: 520px;
min-height: 0;
display: flex;
gap: var(--space-3);
min-width: 0;
}
.treeWrap {
flex: 3;
min-width: 0;
display: flex;
flex-direction: column;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border);
padding: 2px 0;
padding: var(--space-0-5) 0;
}
.empty {
padding: 8px 12px;
@@ -80,13 +84,20 @@
flex: none;
}
.details {
flex: 2;
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: 10px;
padding: 2px 4px;
overflow: auto;
gap: var(--space-2);
padding: var(--space-3);
}
.detailTitle {
margin: 0;
color: var(--fg-strong);
font-size: var(--fs-ui);
font-weight: 600;
overflow-wrap: anywhere;
}
.description {
margin: 0;
@@ -95,19 +106,34 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.severityRow {
.descriptionPane,
.optionsPane {
min-height: 0;
overflow: auto;
}
.descriptionPane {
padding-bottom: var(--space-2);
}
.optionsPane {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding-top: var(--space-2);
}
.severityRow {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding-top: 10px;
border-top: 1px solid var(--border);
}
.options {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
margin: 0;
padding: 10px 0 0;
padding: var(--space-2) 0 0;
border: none;
border-top: 1px solid var(--border);
min-width: 0;
@@ -115,11 +141,12 @@
.options legend {
float: left;
width: 100%;
padding: 0 0 4px;
padding: 0 0 var(--space-1);
color: var(--fg-muted);
}
.levelSelect {
min-width: 160px;
width: 160px;
max-width: 100%;
}
.profileLevel {
color: var(--fg-subtle);
+90 -49
Переглянути файл
@@ -5,7 +5,7 @@
* chosen one is in effect for the project (editor highlighting, Problems,
* Inspect Code).
*/
import { useEffect, useId, useMemo, useRef, useState, type MouseEvent } from "react";
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import {
BUILTIN_INSPECTIONS,
@@ -34,6 +34,9 @@ import {
Input,
SearchField,
Select,
SplitGroup,
SplitHandle,
SplitPanel,
T,
Tree,
showContextMenu,
@@ -92,6 +95,19 @@ function expandableKeys(nodes: readonly InspectionNode[], out = new Set<string>(
}
export function InspectionsPage() {
const pageRef = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const page = pageRef.current;
if (!page) return;
const measure = () => setStacked(page.clientWidth < 560);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(page);
return () => observer.disconnect();
}, []);
const hasProject = useProject((s) => !!s.project);
const newProjects = useSettingsDialog((s) => s.newProjects);
const projectAvailable = hasProject && !newProjects;
@@ -223,20 +239,22 @@ export function InspectionsPage() {
};
return (
<div className={styles.page}>
<div ref={pageRef} className={styles.page}>
<div className={styles.profileRow}>
<span>
<T>Profile:</T>
</span>
<Select
className={styles.profileSelect}
aria-label="Inspection profile"
value={profileId}
options={profileOptions}
onChange={(v) => setChosen(v)}
disabled={profileOptions.length < 2}
/>
<IconButton icon="settings" title="Profile Actions" onClick={gearMenu} />
<div className={styles.profileControls}>
<span>
<T>Profile:</T>
</span>
<Select
className={styles.profileSelect}
aria-label="Inspection profile"
value={profileId}
options={profileOptions}
onChange={(v) => setChosen(v)}
disabled={profileOptions.length < 2}
/>
<IconButton icon="settings" title="Profile Actions" onClick={gearMenu} />
</div>
<span className={styles.profileLevel}>
<T>{location.level === "project" ? "Stored in Project" : "Stored in IDE"}</T>
</span>
@@ -265,8 +283,16 @@ export function InspectionsPage() {
/>
</div>
<div className={styles.split}>
<div
<SplitGroup
id="inspection-panes"
className={styles.split}
orientation={stacked ? "vertical" : "horizontal"}
storageKey="openidea.settings.inspections.layout"
>
<SplitPanel
id="inspection-tree"
defaultSize="50%"
minSize="35%"
className={styles.treeWrap}
onKeyDown={(e) => {
// Space toggles the selected inspection, as in IDEA.
@@ -309,9 +335,12 @@ export function InspectionsPage() {
</div>
}
/>
</div>
<Details node={selected} overrides={overrides} onChange={setOverrides} />
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize inspection panes")} />
<SplitPanel id="inspection-details" defaultSize="50%" minSize="35%">
<Details node={selected} overrides={overrides} onChange={setOverrides} />
</SplitPanel>
</SplitGroup>
{nameDialog && (
<ProfileNameDialog
@@ -435,38 +464,50 @@ function Details({
overrides: ProfileOverrides;
onChange: (o: ProfileOverrides) => void;
}) {
if (!node) {
return (
<div className={styles.details}>
<p className={styles.description}>
<T>Select an inspection to see its description and change its severity.</T>
</p>
</div>
);
}
const id = node.id;
const id = node?.id;
const description = (
<p className={styles.description}>
<T>{node?.description ?? "Select an inspection to see its description and change its severity."}</T>
</p>
);
return (
<div className={styles.details}>
<p className={styles.description}>
<T>{node.description}</T>
</p>
{id && (
<div className={styles.severityRow}>
<span>
<T>Severity:</T>
</span>
<Select
className={styles.levelSelect}
aria-label="Severity"
value={overrides[id]?.severity ?? AS_REPORTED}
options={LEVEL_OPTIONS}
disabled={!isEnabled(overrides, id)}
onChange={(v) => onChange(setLevel(overrides, id, v === AS_REPORTED ? undefined : (v as InspectionLevel)))}
/>
</div>
<section className={styles.details} aria-label={tx("Inspection details")}>
{node && (
<h3 className={styles.detailTitle}>
<T>{node.name}</T>
</h3>
)}
{id && <InspectionOptions id={id} overrides={overrides} onChange={onChange} />}
</div>
{id ? (
<SplitGroup id="inspection-rule" className={styles.split} orientation="vertical">
<SplitPanel id="inspection-description" defaultSize="45%" minSize="25%">
<div className={styles.descriptionPane}>{description}</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize inspection description")} />
<SplitPanel id="inspection-options" defaultSize="55%" minSize="25%">
<div className={styles.optionsPane}>
<div className={styles.severityRow}>
<span>
<T>Severity:</T>
</span>
<Select
className={styles.levelSelect}
aria-label="Severity"
value={overrides[id]?.severity ?? AS_REPORTED}
options={LEVEL_OPTIONS}
disabled={!isEnabled(overrides, id)}
onChange={(v) =>
onChange(setLevel(overrides, id, v === AS_REPORTED ? undefined : (v as InspectionLevel)))
}
/>
</div>
<InspectionOptions id={id} overrides={overrides} onChange={onChange} />
</div>
</SplitPanel>
</SplitGroup>
) : (
<div className={styles.descriptionPane}>{description}</div>
)}
</section>
);
}
+85 -68
Переглянути файл
@@ -12,10 +12,17 @@ import { Button, Checkbox, Input, type SelectOption, T } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings";
import { NATIVE_TO_ASCII_ACTION } from "../../nativeToAscii";
import { NumberInput, Row, Select } from "../../components/Form";
import { FormGroup, NumberInput, Row, Select, Toggle } from "../../components/Form";
import { useSetting } from "../../components/context";
import type { PageSpec } from "../spec";
import { CODE_STYLE_SCOPE, CodeStyleMain, SchemeRow, formatterLabels } from "./codeStyleScheme";
import {
CODE_STYLE_SCOPE,
CodeStyleMain,
CodeStyleTabs,
SchemeRow,
formatterLabels,
type CodeStyleTab,
} from "./codeStyleScheme";
import { editorPage, sectionLabels, type EditorSection } from "./kit";
import styles from "./Editor.module.css";
import { tx } from "@/platform/i18n";
@@ -131,7 +138,19 @@ const OTHER = {
...SCHEME_SCOPE,
};
/** Tabs and Indents of one language: overrides on top of the language definition. */
const INDENTS = {
id: "indents",
label: "Tabs and Indents",
keywords: ["Tab size", "Indent", "Use tab character"],
};
const WRAPPING = { id: "wrapping", label: "Wrapping", keywords: ["Hard wrap at"] };
const COMMENTS = {
id: "comments",
label: "Comment Code",
keywords: ["Line comment at first column", "Add a space at line comment start"],
};
/** Code Style overrides on top of the language definition. */
function LanguageStyle({ lang }: { lang: LanguageInfo }) {
const [all, setAll] = useSetting<Record<string, LanguageCodeStyle>>("editor.codeStyle.languages");
const [tabSize] = useSetting<number>("editor.tabSize");
@@ -156,42 +175,38 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
delete next[lang.id];
setAll(next);
};
return (
<div className={styles.page}>
<SchemeRow />
{lang.id === "java" && <JavaFormatter style={own} onChange={set} />}
<section aria-label={tx("Tabs and Indents")}>
<div className={styles.previewTitle}>
<T>Tabs and Indents</T>
</div>
<div className={styles.check}>
<Checkbox checked={eff.useTab} onChange={(v) => set({ useTab: v })} label="Use tab character" />
</div>
<Row label="Tab size">
<NumberInput
value={eff.tabSize}
onChange={(n) => set({ tabSize: n })}
min={1}
max={16}
integer
aria-label="Tab size"
/>
</Row>
<Row label="Indent">
<NumberInput
value={eff.indent}
onChange={(n) => set({ indent: n })}
min={1}
max={16}
integer
aria-label="Indent"
/>
</Row>
</section>
<section aria-label={tx("Wrapping")}>
<div className={styles.previewTitle}>
<T>Wrapping</T>
</div>
const tabs: CodeStyleTab[] = [
{
...INDENTS,
content: (
<FormGroup>
<Toggle checked={eff.useTab} onChange={(v) => set({ useTab: v })} label="Use tab character" />
<Row label="Tab size">
<NumberInput
value={eff.tabSize}
onChange={(n) => set({ tabSize: n })}
min={1}
max={16}
integer
aria-label="Tab size"
/>
</Row>
<Row label="Indent">
<NumberInput
value={eff.indent}
onChange={(n) => set({ indent: n })}
min={1}
max={16}
integer
aria-label="Indent"
/>
</Row>
</FormGroup>
),
},
{
...WRAPPING,
content: (
<Row label="Hard wrap at" hint="Shown as the right margin guide in the editor.">
<NumberInput
value={eff.hardWrapAt}
@@ -203,7 +218,33 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
unit="columns"
/>
</Row>
</section>
),
},
];
if (lang.lineComment) {
tabs.push({
...COMMENTS,
content: (
<>
<Toggle
checked={eff.lineCommentAtFirstColumn}
onChange={(v) => set({ lineCommentAtFirstColumn: v })}
label="Line comment at first column"
/>
<Toggle
checked={eff.lineCommentAddSpace}
onChange={(v) => set({ lineCommentAddSpace: v })}
label="Add a space at line comment start"
/>
</>
),
});
}
return (
<div className={styles.page}>
<SchemeRow />
{lang.id === "java" && <JavaFormatter style={own} onChange={set} />}
<CodeStyleTabs tabs={tabs} />
{lang.id === "php" && (
<section aria-label={tx("Alignment")}>
<div className={styles.previewTitle}>
@@ -230,27 +271,6 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
</div>
</section>
)}
{lang.lineComment && (
<section aria-label={tx("Comment Code")}>
<div className={styles.previewTitle}>
<T>Comment Code</T>
</div>
<div className={styles.check}>
<Checkbox
checked={eff.lineCommentAtFirstColumn}
onChange={(v) => set({ lineCommentAtFirstColumn: v })}
label="Line comment at first column"
/>
</div>
<div className={styles.check}>
<Checkbox
checked={eff.lineCommentAddSpace}
onChange={(v) => set({ lineCommentAddSpace: v })}
label="Add a space at line comment start"
/>
</div>
</section>
)}
<div className={styles.schemeRow}>
<Button size="small" disabled={!all?.[lang.id]} onClick={reset}>
<T>Reset to Language Defaults</T>
@@ -337,13 +357,10 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
...SCHEME_SCOPE,
keywords: [
"Scheme",
"Tabs and Indents",
"Tab size",
"Indent",
"Use tab character",
"Hard wrap at",
"Comment Code",
"Line comment at first column",
...[INDENTS, WRAPPING, ...(lang.lineComment ? [COMMENTS] : [])].flatMap(({ label, keywords }) => [
label,
...keywords,
]),
...(lang.id === "java"
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
: []),
+78 -30
Переглянути файл
@@ -4,17 +4,16 @@
* and its language pages (`scopeGroup`); "Copy to Project" / "Copy to IDE"
* stage every Code Style value in the other scope.
*/
import { useState } from "react";
import clsx from "clsx";
import { Button, T, type SelectOption } from "@/ui";
import { useId, useState, type ReactNode } from "react";
import { Button, T, Tabs, type SelectOption } from "@/ui";
import { useProject } from "@/platform/project";
import { GlobListEditor, Row, Select } from "../../components/Form";
import { usePageContext, useSetting } from "../../components/context";
import { usePageContext, useSearchQuery, useSetting } from "../../components/context";
import { labelMatches, queryTerms } from "../../model/pages";
import { setPageScope, stage, stagedValue, useSettingsDialog, type Scope } from "../../model/staging";
import { EditorSections, sectionLabels, type EditorSection } from "./kit";
import { PluginFormattersSection } from "./pluginFormatters";
import styles from "./CodeStyle.module.css";
import { tx } from "@/platform/i18n";
export const CODE_STYLE_SCOPE = "editor.codeStyle";
@@ -115,39 +114,88 @@ export const FORMATTER_SECTIONS: EditorSection[] = [
],
},
];
const FORMATTER_LABELS = [...sectionLabels(FORMATTER_SECTIONS), "Plugin Formatters"];
type Tab = "general" | "formatter";
export interface CodeStyleTab {
id: string;
label: string;
keywords: readonly string[];
content: ReactNode;
}
export function CodeStyleTabs({ tabs }: { tabs: CodeStyleTab[] }) {
const query = useSearchQuery();
const prefix = useId();
const [selection, select] = useState({ id: tabs[0]!.id, query: "" });
let active = tabs.find((tab) => tab.id === selection.id)?.id ?? tabs[0]!.id;
if (query !== selection.query) {
const terms = queryTerms(query);
let best = 0;
for (const tab of tabs) {
const labels = [tab.label, ...tab.keywords];
const score = terms.filter((term) => labels.some((label) => labelMatches(label, term))).length;
if (score > best) {
active = tab.id;
best = score;
}
}
}
return (
<>
<Tabs
aria-label="Code Style"
variant="compact"
layout="wrap"
className={styles.tabs}
items={tabs.map(({ id, label }) => ({ id, label }))}
activeId={active}
panelIdPrefix={prefix}
onSelect={(id) => select({ id, query })}
/>
{tabs.map(({ id, content }) => (
<div
key={id}
role="tabpanel"
id={`${prefix}-panel-${id}`}
aria-labelledby={`${prefix}-tab-${id}`}
className={styles.panel}
hidden={id !== active}
>
{id === active && content}
</div>
))}
</>
);
}
/** Code Style: Scheme, then the General / Formatter tabs. */
export function CodeStyleMain({ general }: { general: EditorSection[] }) {
const [tab, setTab] = useState<Tab>("general");
const tabs: Array<[Tab, string]> = [
["general", "General"],
["formatter", "Formatter"],
];
return (
<div className={styles.page}>
<SchemeRow />
<div className={styles.tabs} role="tablist" aria-label={tx("Code Style")}>
{tabs.map(([id, label]) => (
<button
key={id}
type="button"
role="tab"
aria-selected={tab === id}
className={clsx(styles.tab, tab === id && styles.tabOn)}
onClick={() => setTab(id)}
>
<T>{label}</T>
</button>
))}
</div>
<div role="tabpanel">
<EditorSections sections={tab === "general" ? general : FORMATTER_SECTIONS} />
{tab === "formatter" && <PluginFormattersSection />}
</div>
<CodeStyleTabs
tabs={[
{
id: "general",
label: "General",
keywords: sectionLabels(general),
content: <EditorSections sections={general} />,
},
{
id: "formatter",
label: "Formatter",
keywords: FORMATTER_LABELS,
content: (
<>
<EditorSections sections={FORMATTER_SECTIONS} />
<PluginFormattersSection />
</>
),
},
]}
/>
</div>
);
}
export const formatterLabels = () => ["Scheme", "Formatter", ...sectionLabels(FORMATTER_SECTIONS), "Plugin Formatters"];
export const formatterLabels = () => ["Scheme", "Formatter", ...FORMATTER_LABELS];
+15 -1
Переглянути файл
@@ -1,7 +1,16 @@
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, T, Tabs } from "@/ui";
import {
EmptyState,
IconButton,
SplitGroup,
SplitHandle,
SplitPanel,
T,
Tabs,
useFrozenWhileWindowResizes,
} from "@/ui";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { spanStyle } from "@/ui/ansi";
import clsx from "clsx";
@@ -68,6 +77,10 @@ export function GitToolWindow() {
const { shown } = useGitTabs();
const available = useVcs((s) => s.available);
const external = useGitLog((s) => s.logTabs.some((t) => t.id === s.tab && t.readOnly));
// The log's rows, graph and branch tree are too much for WebKit to relayout at every step of a
// window drag; they follow the window once it stops.
const root = useRef<HTMLDivElement>(null);
useFrozenWhileWindowResizes(root);
if (!available && !external)
return (
<EmptyState title="Version control is not configured">
@@ -76,6 +89,7 @@ export function GitToolWindow() {
);
return (
<div
ref={root}
className={styles.root}
role="tabpanel"
id={`openidea-git-panel-${shown}`}
+43 -32
Переглянути файл
@@ -5,6 +5,9 @@
display: flex;
background: var(--bg-app);
}
.resizable {
min-width: 0;
}
.sidebar {
flex: none;
width: 260px;
@@ -18,7 +21,7 @@
display: flex;
align-items: center;
gap: var(--space-2);
padding: 0 8px 0 12px;
padding: 0 var(--space-2) 0 var(--space-3);
border-bottom: 1px solid var(--border);
}
.title {
@@ -26,6 +29,14 @@
color: var(--fg-emphasis);
font-weight: 500;
}
.resizable .title {
min-width: 0;
font-size: var(--fs-ui);
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.list {
flex: 1;
}
@@ -35,14 +46,36 @@
min-width: 0;
gap: var(--space-0-5);
}
.time {
color: var(--fg-emphasis);
.resizable .entry {
width: 100%;
line-height: 1.2;
}
.label {
color: var(--fg-subtle);
font-size: var(--fs-small);
.primaryRow {
display: flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-strong);
font-size: var(--fs-ui);
}
.primary,
.meta,
.path,
.deletedPath {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.meta,
.path,
.deletedPath {
color: var(--fg-muted);
font-size: var(--fs-small);
}
.meta {
font-variant-numeric: tabular-nums;
}
.deletedPath {
text-decoration: line-through;
}
.diff {
flex: 1;
@@ -51,33 +84,11 @@
flex-direction: column;
}
.message {
padding: 16px;
padding: var(--space-4);
color: var(--fg-faint);
text-align: center;
}
.path,
.deletedPath {
color: var(--fg);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.deletedPath {
color: var(--fg-muted);
text-decoration: line-through;
}
.labelRow {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
color: var(--fg-muted);
}
.labelName {
font-size: var(--fs-small);
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
.resizable .message {
white-space: normal;
overflow-wrap: anywhere;
}
+49 -25
Переглянути файл
@@ -7,7 +7,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import type { HistoryEntry } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { relativePath, useProject } from "@/platform/project";
import { Button, Icon, List, Spinner, T } from "@/ui";
import { Button, Icon, List, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { notifications, type EditorInput } from "@/workbench/contributions";
import { DiffEditor } from "./DiffEditor";
import { confirmDialog } from "./dialogs";
@@ -70,6 +70,19 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
const anchor = useRef(0);
const previous = useRef(0);
const pointer = useRef(false);
const container = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useEffect(() => {
const el = container.current;
if (!el || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(([entry]) => {
const width = entry?.contentRect.width;
if (width) setStacked(width < 620);
});
observer.observe(el);
return () => observer.disconnect();
}, []);
const load = useCallback(() => {
call(commands.historyListDir(path))
@@ -197,9 +210,17 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
const revertLabel = current && !isLabel(current) && view?.deleted.has(current.path) ? "Restore" : "Revert";
return (
<div className={styles.root}>
<div
className={styles.sidebar}
<SplitGroup
elementRef={container}
className={`${styles.root} ${styles.resizable}`}
orientation={stacked ? "vertical" : "horizontal"}
storageKey="openidea.localHistory.layout"
>
<SplitPanel
id="revisions"
defaultSize="28%"
minSize={stacked ? "24%" : "160px"}
maxSize="52%"
onMouseDownCapture={(e) => {
pointer.current = e.button === 0 && !!(e.target as Element).closest('[role="option"]');
}}
@@ -253,7 +274,7 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
setExtra(new Set());
}
}}
rowHeight={view.folder ? 52 : 38}
rowHeight={view.folder ? 56 : 44}
aria-label="Revisions"
className={styles.list}
empty={
@@ -261,33 +282,36 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
{view.folder ? tx`No local history for this folder yet` : tx`No local history for this path yet`}
</span>
}
renderItem={(e) =>
isLabel(e) ? (
renderItem={(e) => {
const label = isLabel(e);
const pathText = !label && view.folder ? relativePath(root, e.path) || baseName(e.path) : null;
return (
<span className={styles.entry}>
<span className={styles.time}>{formatTime(e.timestampMs)}</span>
<span className={styles.labelRow}>
<Icon name="bookmark" size={12} />
<span className={styles.labelName}>{e.label}</span>
<span className={styles.primaryRow}>
{label && <Icon name="bookmark" size={12} />}
<span className={styles.primary} title={e.label}>
{e.label}
</span>
</span>
</span>
) : (
<span className={styles.entry}>
<span className={styles.time}>{formatTime(e.timestampMs)}</span>
{view.folder && (
<span className={view.deleted.has(e.path) ? styles.deletedPath : styles.path}>
{relativePath(root, e.path) || baseName(e.path)}
{pathText && (
<span className={view.deleted.has(e.path) ? styles.deletedPath : styles.path} title={pathText}>
{pathText}
</span>
)}
<span className={styles.label}>
{e.label} · {formatSize(e.size)}
<span className={styles.meta}>
{formatTime(e.timestampMs)}
{!label && ` · ${formatSize(e.size)}`}
</span>
</span>
)
}
);
}}
/>
)}
</div>
<div className={styles.diff}>{detail}</div>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Revisions")} />
<SplitPanel id="preview" defaultSize="72%">
{detail}
</SplitPanel>
</SplitGroup>
);
}
+55
Переглянути файл
@@ -0,0 +1,55 @@
.form {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-4);
font-size: var(--fs-ui);
}
.source,
.command {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
min-width: 0;
}
.source > .repository {
flex: 1 1 124px;
}
.command,
.noRemotes {
flex: 4 1 352px;
}
.verb {
flex: none;
color: var(--fg-secondary);
font-family: var(--font-mono);
white-space: nowrap;
}
.command > .remote {
flex: 1 1 104px;
}
.command > .branch {
flex: 3 1 208px;
}
.flags {
display: flex;
flex-wrap: wrap;
gap: var(--space-1);
}
.flags > code {
padding: var(--space-0-5) var(--space-1-5);
border-radius: var(--radius-control);
background: var(--bg-field);
color: var(--fg-secondary);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
+89
Переглянути файл
@@ -0,0 +1,89 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { registerAction, registerActions } from "@/platform/actions";
import { clearContext, setContext } from "@/platform/context";
import { menuGroupItems, provideNotificationService } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
import { copyRepositoryPathActions, registerCopyRepositoryPath } from "../copyRepositoryPath";
import { useVcs } from "../store";
const writeText = vi.fn(async (_text: string) => undefined);
const hint = vi.fn();
const notify = vi.fn();
const disposers: Array<() => void> = [];
type Item = Extract<MenuItem, { kind?: "item" }>;
const items = (paths: string[]) =>
menuGroupItems("copyPath", { paths }).filter(
(i): i is Item => i.kind !== "separator" && "run" in i && i.id === "vcs.copyRepositoryPath",
);
const preview = (paths: string[]) => items(paths)[0]?.preview;
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("navigator", { clipboard: { writeText }, userAgent: navigator.userAgent });
provideNotificationService({ notify });
setContext("vcsAvailable", true);
useVcs.setState({ roots: ["/w/api", "/w/web", "/w/api/third_party/lib"] });
disposers.push(
registerActions(copyRepositoryPathActions),
registerCopyRepositoryPath(),
registerAction({ id: "editor.showHint", title: "Hint", run: ({ arg }) => hint(arg) }),
);
});
afterEach(() => {
disposers
.splice(0)
.reverse()
.forEach((dispose) => dispose());
useVcs.setState({ roots: [] });
clearContext("vcsAvailable");
vi.unstubAllGlobals();
});
describe("Copy Path/Reference… › Path From Repository Root", () => {
it("offers the file's path from its repository's root and copies it", async () => {
const [item] = items(["/w/api/internal/server.go"]);
expect(item).toMatchObject({
id: "vcs.copyRepositoryPath",
label: "Path From Repository Root",
preview: "internal/server.go",
});
item!.run!();
await vi.waitFor(() => expect(hint).toHaveBeenCalledWith({ text: "Copied internal/server.go" }));
expect(writeText).toHaveBeenCalledExactlyOnceWith("internal/server.go");
});
it("uses the innermost repository and gives each path its own repository, one per line", () => {
expect(preview(["/w/api/third_party/lib/a.go"])).toBe("a.go");
expect(preview(["/w/api/main.go", "/w/web/src/app.ts"])).toBe("main.go\nsrc/app.ts");
});
it("copies a repository's root as '.' and ignores a trailing slash", () => {
expect(preview(["/w/api"])).toBe(".");
expect(preview(["/w/api/"])).toBe(".");
expect(preview(["/w/api/third_party/lib"])).toBe(".");
expect(preview(["/w/web/src/"])).toBe("src");
});
it("leaves out paths outside every repository, and offers nothing when none is inside one", () => {
expect(preview(["/w/api/a.go", "/w/notes.md", "/w/web/b.ts"])).toBe("a.go\nb.ts");
expect(items(["/w/notes.md"])).toEqual([]);
expect(items(["/w/api2/a.go"])).toEqual([]);
expect(items(["/w/notes.md", "/w/api2/a.go"])).toEqual([]);
expect(items([])).toEqual([]);
useVcs.setState({ roots: [] });
expect(items(["/w/api/a.go"])).toEqual([]);
});
it("reports a clipboard it cannot write to", async () => {
writeText.mockRejectedValueOnce(new Error("denied"));
items(["/w/api/a.go"])[0]!.run!();
await vi.waitFor(() =>
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", title: "Cannot access the clipboard", body: "denied" }),
),
);
expect(hint).not.toHaveBeenCalled();
});
});
+30 -16
Переглянути файл
@@ -1,5 +1,5 @@
/** Local change operations: commit, rollback, add, stash. */
import { useEffect, useState } from "react";
import { useEffect, useId, useState } from "react";
import type { FileStatus, Stash } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
@@ -367,7 +367,9 @@ function StashDialog({
const [message, setMessage] = useState("");
const [keepIndex, setKeepIndex] = useState(false);
const [includeUntracked, setIncludeUntracked] = useState(false);
const showRepo = useVcs((s) => pickRepo && s.roots.length > 1);
const branch = useBranchInfo(repo)?.head ?? null;
const messageId = useId();
const submit = () => onDone({ repo, message: message.trim(), keepIndex, includeUntracked });
return (
<Dialog
@@ -381,26 +383,38 @@ function StashDialog({
]}
>
<form
className={styles.form}
className={`${styles.form} ${styles.stashForm}`}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
{pickRepo && <RepoPicker repo={repo} onChange={setRepo} />}
{branch && <div className={styles.hint}>{tx`Current branch: ${branch}`}</div>}
<label className={styles.fieldLabel}>
<T>Message:</T>
</label>
<Input
data-autofocus
aria-label="Message"
placeholder="WIP"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<Checkbox checked={keepIndex} onChange={setKeepIndex} label="Keep index" />
<Checkbox checked={includeUntracked} onChange={setIncludeUntracked} label="Include untracked files" />
{showRepo && (
<div className={styles.stashRepo}>
<T>Repository:</T>
<RepoPicker repo={repo} onChange={setRepo} />
</div>
)}
{branch && <div className={styles.stashBranch}>{tx`Current branch: ${branch}`}</div>}
<div className={styles.stashMessage}>
<label htmlFor={messageId}>
<T>Message:</T>
</label>
<textarea
id={messageId}
className={styles.textarea}
data-autofocus
aria-label={tx("Message")}
placeholder={tx("WIP")}
rows={3}
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
</div>
<div className={styles.stashOptions}>
<Checkbox checked={keepIndex} onChange={setKeepIndex} label="Keep index" />
<Checkbox checked={includeUntracked} onChange={setIncludeUntracked} label="Include untracked files" />
</div>
</form>
</Dialog>
);
+67 -53
Переглянути файл
@@ -25,52 +25,61 @@
display: flex;
}
.sidebar {
flex: 0 0 224px;
padding: 8px 0;
flex: 0 0 200px;
padding: var(--space-2) 0;
border-right: 1px solid var(--border);
background: color-mix(in srgb, var(--bg-dialog, var(--bg-elev)) 96%, var(--fg-strong));
overflow: auto;
}
.sourceItem {
min-height: 44px;
min-height: var(--h-row);
display: flex;
align-items: flex-start;
gap: 10px;
padding: 9px 14px;
align-items: center;
gap: var(--space-2);
padding: var(--space-1) var(--space-3);
width: 100%;
border: 0;
background: none;
color: var(--fg-strong);
font: inherit;
text-align: left;
cursor: default;
}
.sourceItem[data-selected] {
background: var(--bg-tree-selected);
}
.sourceName {
font-weight: 600;
line-height: 22px;
min-width: 0;
overflow-wrap: anywhere;
font-weight: 500;
font-size: var(--fs-ui);
line-height: 1.4;
}
.form {
--clone-label-width: 112px;
--clone-field-gap: var(--space-3);
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-4);
padding: 28px 24px;
gap: var(--space-3);
overflow: auto;
padding: var(--space-4);
font-size: var(--fs-ui);
}
.versionRow,
.fieldRow {
display: grid;
grid-template-columns: 112px minmax(0, 1fr);
grid-template-columns: var(--clone-label-width) minmax(0, 1fr);
align-items: center;
gap: 10px var(--space-3);
gap: var(--clone-field-gap);
}
.versionRow {
grid-template-columns: 112px 138px minmax(0, 1fr);
}
.versionRow > label,
.fieldRow > label {
color: var(--fg-strong);
text-align: right;
overflow-wrap: anywhere;
}
.versionSelect {
width: 138px;
width: min(138px, 100%);
}
.comboField {
min-width: 0;
@@ -89,7 +98,7 @@
.fieldInput {
flex: 1;
height: 100%;
padding: 0 8px;
padding-inline: var(--space-2);
background: transparent;
}
.fieldButton {
@@ -101,16 +110,27 @@
.shallowRow {
min-width: 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
padding-left: 124px;
gap: var(--space-2);
}
.shallowRow,
.feedback {
padding-inline-start: calc(var(--clone-label-width) + var(--clone-field-gap));
}
.depthGroup {
display: inline-flex;
align-items: center;
gap: var(--space-2);
max-width: 100%;
min-width: 0;
overflow-wrap: anywhere;
}
.depthInput {
width: 84px;
}
.feedback {
min-width: 0;
padding-left: 124px;
}
.progress {
display: flex;
@@ -127,44 +147,38 @@
color: var(--fg-subtle);
font-size: var(--fs-small);
line-height: 1.5;
overflow-wrap: anywhere;
}
.error {
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
@media (max-width: 720px) {
.sidebar {
flex-basis: 172px;
}
.form {
padding-inline: 16px;
}
.versionRow,
.fieldRow {
grid-template-columns: 86px minmax(0, 1fr);
}
.versionRow {
grid-template-columns: 86px 118px minmax(0, 1fr);
}
.versionSelect {
width: 118px;
}
.shallowRow,
.feedback {
padding-left: 98px;
}
.layout[data-compact] {
flex-direction: column;
}
.sidebar .sourceItem {
width: 100%;
border: 0;
background: none;
font: inherit;
text-align: left;
cursor: default;
.layout[data-compact] .sidebar {
flex: 0 1 auto;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
gap: var(--space-1);
max-height: min(120px, 32%);
padding: var(--space-1);
border-right: 0;
border-bottom: 1px solid var(--border);
}
.sidebar .sourceItem[data-selected] {
background: var(--bg-tree-selected);
.layout[data-compact] .sourceItem {
width: auto;
max-width: 100%;
border-radius: var(--radius-row);
}
.layout[data-compact] .form {
--clone-label-width: 104px;
}
.layout[data-compact] .shallowRow {
padding-inline-start: 0;
}
.sidebar .sourceItem:focus-visible {
outline: 2px solid var(--focus-ring);
+33 -17
Переглянути файл
@@ -130,6 +130,8 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
const [error, setError] = useState<string | null>(null);
const request = useRef<number | null>(null);
const urlField = useRef<HTMLDivElement>(null);
const layout = useRef<HTMLDivElement>(null);
const [compact, setCompact] = useState(false);
const [recentUrls] = useState(readRecentUrls);
const sources = cloneSourceList(useCloneSources((s) => s.sources));
const source = sources.find((s) => s.id === sourceId);
@@ -142,6 +144,17 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
};
}, []);
useEffect(() => {
const el = layout.current;
if (!el || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(([entry]) => {
const width = entry?.contentRect.width;
if (width) setCompact(width < 580);
});
observer.observe(el);
return () => observer.disconnect();
}, []);
const dir = customDir ?? joinPath(parent, cloneDirName(url));
const depth = shallow ? parseCloneDepth(depthInput) : null;
const invalid = validateClone(url, dir) ?? (shallow && depth === null ? "Enter a positive number of commits" : null);
@@ -231,7 +244,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
{ label: "Cancel", role: "cancel", onClick: cancel },
]}
>
<div className={styles.layout}>
<div ref={layout} className={styles.layout} data-compact={compact || undefined}>
<aside className={styles.sidebar} aria-label={tx("Clone source")}>
{[{ id: "url", label: "Repository URL", icon: "branch" }, ...sources].map((s) => (
<button
@@ -243,7 +256,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
disabled={busy}
onClick={() => setSourceId(s.id)}
>
<Icon name={s.icon} size={22} />
<Icon name={s.icon} size={16} />
<span className={styles.sourceName}>
<T>{s.label}</T>
</span>
@@ -264,11 +277,12 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
</div>
) : (
<>
<div className={styles.versionRow}>
<label id="vcs-clone-version-label">
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-version">
<T>Version control:</T>
</label>
<Select
id="vcs-clone-version"
aria-label="Version control"
className={styles.versionSelect}
value="git"
@@ -337,19 +351,21 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
onChange={setShallow}
label={<T>Shallow clone with a history truncated to</T>}
/>
<Input
aria-label="Clone depth"
className={styles.depthInput}
type="number"
inputMode="numeric"
min={1}
step={1}
value={depthInput}
disabled={busy || !shallow}
invalid={shallow && depth === null}
onChange={(e) => setDepthInput(e.target.value)}
/>
<T>commits</T>
<div className={styles.depthGroup}>
<Input
aria-label="Clone depth"
className={styles.depthInput}
type="number"
inputMode="numeric"
min={1}
step={1}
value={depthInput}
disabled={busy || !shallow}
invalid={shallow && depth === null}
onChange={(e) => setDepthInput(e.target.value)}
/>
<T>commits</T>
</div>
</div>
<div className={styles.feedback}>
+83
Переглянути файл
@@ -48,6 +48,51 @@
flex-direction: column;
gap: var(--space-0-5);
}
.updateForm {
min-width: 0;
gap: var(--space-3);
padding: var(--space-4);
font-size: var(--fs-ui);
overflow-wrap: anywhere;
}
.updateOptions {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-inline-size: 0;
margin: 0;
padding: var(--space-2) 0 0;
border: 0;
border-top: 1px solid var(--border-popup);
}
.updateOptions > legend {
padding: 0 var(--space-2) 0 0;
color: var(--fg-strong);
font-weight: 600;
}
.updateOptions .updateRadio {
align-items: flex-start;
}
.updateCommand {
color: var(--fg-subtle);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
.updateActions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2) var(--space-3);
min-width: 0;
}
.updateActions .updateReset {
max-width: 100%;
min-height: var(--h-button);
height: auto;
padding-block: var(--space-1);
line-height: 1.3;
white-space: normal;
}
.fileList {
max-height: 260px;
overflow: auto;
@@ -357,6 +402,44 @@
outline: none;
border-color: var(--focus-ring);
}
.stashForm {
gap: var(--space-3);
padding: var(--space-4);
font-size: var(--fs-ui);
}
.stashRepo {
display: flex;
align-items: center;
gap: var(--space-2);
color: var(--fg-secondary);
}
.stashRepo > button {
flex: 1;
}
.stashBranch {
color: var(--fg-secondary);
line-height: 1.5;
overflow-wrap: anywhere;
}
.stashMessage {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.stashMessage > label {
color: var(--fg-strong);
font-weight: 600;
}
.stashMessage > textarea {
min-width: 0;
padding: var(--space-2);
line-height: 1.5;
}
.stashOptions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
}
/* Interactive rebase dialog. */
.rebaseList {
max-height: 360px;
+69
Переглянути файл
@@ -0,0 +1,69 @@
/**
* Copy Path/Reference… › Path From Repository Root: each path relative to the root of the
* Git repository holding it, one per line.
*/
import { executeAction, type Action } from "@/platform/actions";
import { writeClipboardText } from "@/platform/clipboard";
import { tx } from "@/platform/i18n";
import { notifications, registerMenuGroup } from "@/workbench/contributions";
import { rootOf, stripSlash } from "./model";
import { useVcs } from "./store";
/** The paths inside a repository, each from its root; null when none is. */
function repositoryPaths(paths: readonly string[]): string | null {
const { roots } = useVcs.getState();
const relative: string[] = [];
for (const path of paths.map(stripSlash)) {
// A nested repository's own root is its root, not a folder of the outer one.
const root = roots.includes(path) ? path : rootOf(path, roots);
if (root) relative.push(path.slice(root.length + 1) || ".");
}
return relative.length ? relative.join("\n") : null;
}
async function copy(text: string) {
try {
await writeClipboardText(text);
void executeAction("editor.showHint", { text: tx`Copied ${text}` });
} catch (error) {
notifications().notify({
level: "error",
title: tx("Cannot access the clipboard"),
body: error instanceof Error ? error.message : String(error),
});
}
}
export const copyRepositoryPathActions: Action[] = [
{
id: "vcs.copyRepositoryPath",
title: "Copy Path From Repository Root",
category: "Git",
icon: "copy",
when: "vcsAvailable",
hidden: true,
run: ({ arg }) => {
const text = Array.isArray(arg) ? repositoryPaths(arg as string[]) : null;
if (text) void copy(text);
},
},
];
export function registerCopyRepositoryPath(): () => void {
return registerMenuGroup({
id: "vcs.copyRepositoryPath",
menus: ["copyPath"],
items: (_menu, { paths }) => {
const text = repositoryPaths(paths);
if (!text) return [];
return [
{
id: "vcs.copyRepositoryPath",
label: "Path From Repository Root",
preview: text,
run: () => void executeAction("vcs.copyRepositoryPath", paths),
},
];
},
});
}
+91 -40
Переглянути файл
@@ -6,18 +6,21 @@ import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import {
Button,
Checkbox,
Dialog,
HighlightedText,
Icon,
IconButton,
Input,
Menu,
Select,
T,
Tree,
useSanitizedField,
type SelectOption,
type SelectProps,
type MenuItem,
} from "@/ui";
import { sortLocal, sortRemote } from "./branches";
import { conflictActions, openConflictsInstead, validateBranchName } from "./branchOps";
@@ -33,6 +36,7 @@ import {
type RepoWorktrees,
} from "./worktrees";
import styles from "./common.module.css";
import pullStyles from "./PullDialog.module.css";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -73,16 +77,8 @@ const FLAG_LABELS: Array<[MergeFlag, string]> = [
["noCommit", "--no-commit"],
];
function MergeFlags({
on,
setOn,
rebase = false,
}: {
on: Set<MergeFlag>;
setOn: (next: Set<MergeFlag>) => void;
rebase?: boolean;
}) {
const disabled = disabledMergeFlags(on, rebase);
function MergeFlags({ on, setOn }: { on: Set<MergeFlag>; setOn: (next: Set<MergeFlag>) => void }) {
const disabled = disabledMergeFlags(on);
return (
<div className={styles.optionGrid} role="group" aria-label={tx("Merge options")}>
{FLAG_LABELS.map(([flag, label]) => (
@@ -141,12 +137,21 @@ export function showPullDialog(repo?: string | null) {
}
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
export function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
export function RepoPicker({
repo,
onChange,
className,
}: {
repo: string | null;
onChange: (root: string) => void;
className?: string;
}) {
const [roots] = useState(() => useVcs.getState().roots);
if (roots.length < 2) return null;
return (
<Select
aria-label="Repository"
className={className}
value={repo ?? roots[0] ?? null}
options={roots.map((root) => ({ value: root, label: repoName(root), verbatim: true }))}
onChange={onChange}
@@ -181,6 +186,8 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
const [chosenBranch, setBranch] = useState<string | null>(null);
const [rebase, setRebase] = useState(false);
const [flags, setFlags] = useState<Set<MergeFlag>>(() => new Set());
const [optionsOpen, setOptionsOpen] = useState(false);
const optionsRef = useRef<HTMLButtonElement>(null);
const chooseRepo = (root: string) => {
if (root === repo) return;
@@ -215,6 +222,25 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
: preferred && remoteBranches.includes(preferred)
? preferred
: (remoteBranches[0] ?? null);
const disabledFlags = disabledMergeFlags(flags, rebase);
const selectedFlags = rebase
? ["--rebase"]
: FLAG_LABELS.filter(([flag]) => flags.has(flag)).map(([, label]) => label);
const options: MenuItem[] = [
{ label: "--rebase", verbatim: true, checked: rebase, run: () => setRebase(!rebase) },
...FLAG_LABELS.map(([flag, label]) => ({
label,
verbatim: true,
checked: flags.has(flag),
disabled: disabledFlags.has(flag) && !flags.has(flag),
run: () => {
const next = new Set(flags);
if (next.has(flag)) next.delete(flag);
else next.add(flag);
setFlags(next);
},
})),
];
const run = async () => {
if (!remote) return;
@@ -238,44 +264,69 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
open
title={tx`Pull to ${info?.head ?? "HEAD"}`}
onClose={onClose}
width={460}
width={640}
footerStart={
<>
<Button
ref={optionsRef}
variant="ghost"
aria-haspopup="menu"
aria-expanded={optionsOpen}
onClick={() => setOptionsOpen(!optionsOpen)}
>
<T>Modify options</T>
<Icon name="chevron-down" size={12} />
</Button>
<Menu
open={optionsOpen}
onClose={() => setOptionsOpen(false)}
anchor={optionsRef}
placement="top-start"
aria-label="Modify options"
items={options}
/>
</>
}
buttons={[
{ label: "Pull", role: "default", disabled: !remote, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
{remotes && !remotes.length ? (
<>
<RepoPicker repo={repo} onChange={chooseRepo} />
<div className={styles.hint}>
<div className={pullStyles.form}>
<div className={pullStyles.source}>
<RepoPicker repo={repo} onChange={chooseRepo} className={pullStyles.repository} />
{remotes && !remotes.length ? (
<div className={clsx(styles.hint, pullStyles.noRemotes)}>
<T>No remotes are configured. Add one with Git › Manage Remotes….</T>
</div>
</>
) : (
<div className={styles.fieldRow}>
<RepoPicker repo={repo} onChange={chooseRepo} />
<Select
aria-label="Remote"
value={remote}
options={(remotes ?? []).map((r) => ({ value: r.name, label: r.name, detail: r.url }))}
onChange={setRemote}
/>
<BranchSelect
aria-label="Remote branch"
className={styles.grow}
value={branch}
placeholder="Branch"
options={remoteBranches.map((b) => ({ value: b, label: b, icon: "branch" }))}
onChange={setBranch}
/>
) : (
<div className={pullStyles.command}>
<code className={pullStyles.verb}>git pull</code>
<Select
aria-label="Remote"
className={pullStyles.remote}
value={remote}
options={(remotes ?? []).map((r) => ({ value: r.name, label: r.name, verbatim: true, detail: r.url }))}
onChange={setRemote}
/>
<BranchSelect
aria-label="Remote branch"
className={pullStyles.branch}
value={branch}
renderValue={(option) => (option ? <span title={option.label}>{option.label}</span> : <T>Branch</T>)}
options={remoteBranches.map((b) => ({ value: b, label: b, icon: "branch", verbatim: true }))}
onChange={setBranch}
/>
</div>
)}
</div>
{selectedFlags.length > 0 && (
<div className={pullStyles.flags} role="group" aria-label={tx("Options:")}>
{selectedFlags.map((label) => (
<code key={label}>{label}</code>
))}
</div>
)}
<div className={styles.fieldLabel}>
<T>Options:</T>
</div>
<Checkbox label="--rebase" checked={rebase} onChange={setRebase} />
<MergeFlags on={flags} setOn={setFlags} rebase={rebase} />
<div className={styles.hint}>
<T>Uncommitted changes are stashed before the pull and restored afterwards.</T>
</div>
+3
Переглянути файл
@@ -54,6 +54,7 @@ import { existsOnDisk, installVcsStore, onConflictsAppeared, onConflictsCleared,
import { installRootSync } from "./rootSync";
import { tx } from "@/platform/i18n";
import { openOnRemoteActions, registerOpenOnRemote } from "./openOnRemote";
import { copyRepositoryPathActions, registerCopyRepositoryPath } from "./copyRepositoryPath";
import { activateSettingsPages } from "./settingsPages";
/** The Resolve/Continue/Abort buttons exist in the title bar only while there is something to resolve. */
@@ -230,6 +231,8 @@ export function activate(): () => void {
registerVcsActions(),
registerActions(openOnRemoteActions),
registerOpenOnRemote(),
registerActions(copyRepositoryPathActions),
registerCopyRepositoryPath(),
registerHistoryActions(),
registerLogPaneActions(),
activateSettingsPages(),
+38 -25
Переглянути файл
@@ -5,7 +5,7 @@ import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { workflowSettings, type UpdateMethod } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { Button, Checkbox, Dialog, Input, List, Select, Spinner, T, Tree } from "@/ui";
import { Button, Checkbox, Dialog, Input, List, Radio, Select, Spinner, T, Tree } from "@/ui";
import { ask } from "@/workbench/messages";
import { openDialog } from "./dialogs";
import { saveVcsSetting } from "./settingsUi";
@@ -94,9 +94,10 @@ function UpdateDialog({ repos, onClose }: UpdateDialogProps) {
onClose={onClose}
width={single ? 540 : 420}
footerStart={
<>
<div className={styles.updateActions}>
{single && (
<Button
className={styles.updateReset}
onClick={() => {
onClose();
void resetToRemoteBranch();
@@ -106,40 +107,52 @@ function UpdateDialog({ repos, onClose }: UpdateDialogProps) {
</Button>
)}
<Checkbox checked={hide} onChange={setHide} label="Don't show again" />
</>
</div>
}
buttons={[
{ label: "OK", role: "default", autoFocus: true, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form} role="radiogroup" aria-label={tx("Update type")}>
<div className={`${styles.form} ${styles.updateForm}`}>
<div className={styles.hint}>
{branch?.upstream
? `Update ${branch.head ?? "HEAD"} from ${branch.upstream}${branch.behind ? ` (${branch.behind} incoming)` : ""}`
: tx("The current branch has no tracked branch; git pull may fail.")}
</div>
<div className={styles.fieldLabel}>
<T>Update type:</T>
</div>
<label className={styles.radioRow}>
<input type="radio" name="update" checked={!rebase} onChange={() => setRebase(false)} />
<span className={styles.radioText}>
<T>Merge incoming changes into the current branch</T>
<span className={styles.hint}>
<T>git pull --no-rebase --ff</T>
</span>
</span>
</label>
<label className={styles.radioRow}>
<input type="radio" name="update" checked={rebase} onChange={() => setRebase(true)} />
<span className={styles.radioText}>
<T>Rebase the current branch on top of incoming changes</T>
<span className={styles.hint}>
<T>git pull --rebase</T>
</span>
</span>
</label>
<fieldset className={styles.updateOptions} aria-label={tx("Update type")}>
<legend>
<T>Update type:</T>
</legend>
<Radio
className={styles.updateRadio}
name="update"
checked={!rebase}
onChange={() => setRebase(false)}
label={
<span className={styles.radioText}>
<T>Merge incoming changes into the current branch</T>
<code className={styles.updateCommand}>
<T>git pull --no-rebase --ff</T>
</code>
</span>
}
/>
<Radio
className={styles.updateRadio}
name="update"
checked={rebase}
onChange={() => setRebase(true)}
label={
<span className={styles.radioText}>
<T>Rebase the current branch on top of incoming changes</T>
<code className={styles.updateCommand}>
<T>git pull --rebase</T>
</code>
</span>
}
/>
</fieldset>
<div className={styles.hint}>
<T>Uncommitted changes are stashed before the update and restored afterwards.</T>
</div>
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { afterEach, expect, it } from "vitest";
import { isIgnoredName } from "./ignoredNames";
import { useProject } from "./project";
const initial = useProject.getState();
afterEach(() => useProject.setState(initial, true));
function withNames(ignoredNames: string[]) {
useProject.setState({ settings: { files: { ignoredNames } } } as never);
}
it("matches the defaults by exact name and by wildcard", () => {
expect(isIgnoredName(".git")).toBe(true);
expect(isIgnoredName("module.pyc")).toBe(true);
expect(isIgnoredName("notes.txt~")).toBe(true);
expect(isIgnoredName("module.py")).toBe(false);
expect(isIgnoredName("pyc")).toBe(false);
});
it("anchors every wildcard and keeps other pattern characters literal", () => {
withNames(["*.log", "build?", "a+b.(x)"]);
expect(isIgnoredName("server.log")).toBe(true);
expect(isIgnoredName("server.log.1")).toBe(false);
expect(isIgnoredName("build1")).toBe(true);
expect(isIgnoredName("build12")).toBe(false);
expect(isIgnoredName("a+b.(x)")).toBe(true);
expect(isIgnoredName("aab.x")).toBe(false);
});
it("follows the setting when it changes, and ignores entries with a path", () => {
withNames(["dist", "out/*"]);
expect(isIgnoredName("dist")).toBe(true);
expect(isIgnoredName(".git")).toBe(false);
expect(isIgnoredName("out")).toBe(false);
withNames([]);
expect(isIgnoredName("dist")).toBe(false);
});
+18 -6
Переглянути файл
@@ -23,28 +23,40 @@ export const DEFAULT_IGNORED_NAMES: readonly string[] = [
"desktop.ini",
];
let cached: { names: readonly string[]; exact: Set<string>; wildcards: RegExp[] } | null = null;
interface Compiled {
names: readonly string[];
exact: Set<string>;
suffixes: string[];
wildcards: RegExp | null;
}
function compile(names: readonly string[]) {
let cached: Compiled | null = null;
function compile(names: readonly string[]): Compiled {
const exact = new Set<string>();
const wildcards: RegExp[] = [];
const suffixes: string[] = [];
const patterns: string[] = [];
for (const raw of names) {
const n = raw.trim();
if (!n || n.includes("/")) continue;
if (!/[*?]/.test(n)) exact.add(n);
// `*.pyc` (every default pattern): a suffix test, without a regex that retries `.*` at each position.
else if (/^\*[^*?]+$/.test(n)) suffixes.push(n.slice(1));
else {
const body = n
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*")
.replace(/\?/g, ".");
wildcards.push(new RegExp(`^${body}$`, "s"));
patterns.push(body);
}
}
return { names, exact, wildcards };
// One alternation: a folder of thousands of entries tests each name once, not once per pattern.
const wildcards = patterns.length ? new RegExp(`^(?:${patterns.join("|")})$`, "s") : null;
return { names, exact, suffixes, wildcards };
}
export function isIgnoredName(name: string): boolean {
const names = useProject.getState().settings?.files?.ignoredNames ?? DEFAULT_IGNORED_NAMES;
const m = cached?.names === names ? cached : (cached = compile(names));
return m.exact.has(name) || m.wildcards.some((re) => re.test(name));
return m.exact.has(name) || m.suffixes.some((s) => name.endsWith(s)) || !!m.wildcards?.test(name);
}
+2
Переглянути файл
@@ -160,6 +160,8 @@ export const eclipseWindows: Record<string, string[]> = {
"vcs.changelist.edit": ["Shift+Alt+R"],
"toolwindow.services": ["Shift+Alt+H"],
"vcs.changelist.move": [],
"vcs.shelveSilently": [],
"vcs.unshelveSilently": [],
"navigate.gotoBookmark1": [],
"toolwindow.resizeLeft": [],
"toolwindow.resizeRight": [],
+2
Переглянути файл
@@ -332,6 +332,8 @@ export const vscodeMacos: Record<string, string[]> = {
"view.quickSwitchScheme": [],
// Commit tool window (change lists) and Git log; keyWhen limits them to those tool windows.
"vcs.changelist.move": [],
"vcs.shelveSilently": [],
"vcs.unshelveSilently": [],
"vcs.changelist.edit": [],
"vcs.log.copyRevision": [],
"vcs.log.goToRef": [],
+14 -1
Переглянути файл
@@ -1,4 +1,7 @@
{
"Inspection details": "Inspection details",
"Resize inspection panes": "Resize inspection panes",
"Resize inspection description": "Resize inspection description",
"Table actions": "Table actions",
"Table pages": "Table pages",
"Problems actions": "Problems actions",
@@ -721,7 +724,6 @@
"Packaging Artifacts": "Packaging Artifacts",
"Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.": "Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.",
"Detected Build Web Artifacts": "Detected Build Web Artifacts",
"Home Path": "Home Path",
"No SDK installations detected yet.": "No SDK installations detected yet.",
"SDK Details": "SDK Details",
"Use as Project SDK": "Use as Project SDK",
@@ -885,6 +887,7 @@
"Start Fresh": "Start Fresh",
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.",
"Copy Path From Source Root": "Copy Path From Source Root",
"Copy Path From Repository Root": "Copy Path From Repository Root",
"Escape text on paste in string literals": "Escape text on paste in string literals",
"Always": "Always",
"Never": "Never",
@@ -900,6 +903,7 @@
"Copy Path with Line Number": "Copy Path with Line Number",
"1 line": "1 line",
"Path From Source Root": "Path From Source Root",
"Path From Repository Root": "Path From Repository Root",
"Paste preview": "Paste preview",
"Add Imports on Paste": "Add Imports on Paste",
"Select imports to add to the pasted code:": "Select imports to add to the pasted code:",
@@ -2486,6 +2490,8 @@
"{length} selected items": "{length} selected items",
"Include subdirectories": "Include subdirectories",
"Only VCS changed text": "Only VCS changed text",
"Options": "Options",
"Filters": "Filters",
"Files are reformatted by their language's formatter and saved; files without one are skipped.": "Files are reformatted by their language's formatter and saved; files without one are skipped.",
"No changed files to reformat": "No changed files to reformat",
"No files to reformat": "No files to reformat",
@@ -2739,6 +2745,13 @@
"{description}; JVM options: {flags}": "{description}; JVM options: {flags}",
"Sorting Options": "Sorting Options",
"Sort by Duration": "Sort by Duration",
"Move file '{name}'": "Move file '{name}'",
"Move directory '{name}'": "Move directory '{name}'",
"Move {count} items": "Move {count} items",
"Browse for target directory": "Browse for target directory",
"Select Target Directory": "Select Target Directory",
"Cannot move a folder into itself": "Cannot move a folder into itself",
"Already in this directory": "Already in this directory",
"Resize left merge pane": "Resize left merge pane",
"Resize right merge pane": "Resize right merge pane",
"Database and schema": "Database and schema",
+13 -1
Переглянути файл
@@ -1,4 +1,7 @@
{
"Inspection details": "检查详情",
"Resize inspection panes": "调整检查窗格大小",
"Resize inspection description": "调整检查说明窗格大小",
"Table actions": "表数据操作",
"Table pages": "表数据分页",
"Problems actions": "问题操作",
@@ -2282,7 +2285,6 @@
"Packaging Artifacts": "打包构件",
"Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.": "配置用于打包和应用服务器部署的 JAR、WAR 或展开式 WAR 构件。",
"Detected Build Web Artifacts": "检测到的构建 Web 构件",
"Home Path": "主目录路径",
"No SDK installations detected yet.": "尚未检测到已安装的 SDK。",
"SDK Details": "SDK 详情",
"Use as Project SDK": "设为项目 SDK",
@@ -7312,6 +7314,7 @@
"Start Fresh": "重新开始",
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "这会清空整个对话,并使用此消息启动全新的智能体会话。智能体已修改的文件保持不变。",
"Path From Source Root": "相对于源根的路径",
"Path From Repository Root": "相对于仓库根的路径",
"Paste preview": "粘贴预览",
"Filter clipboard history": "筛选剪贴板历史",
"Add Imports": "添加导入",
@@ -7326,6 +7329,7 @@
"Clipboard history": "剪贴板历史",
"Select imports to add to the pasted code:": "选择要为粘贴的代码添加的导入:",
"Copy Path From Source Root": "复制相对于源根的路径",
"Copy Path From Repository Root": "复制相对于仓库根的路径",
"Copied {text}": "已复制 {text}",
"Reference": "引用",
"Insert imports on paste": "粘贴时插入导入",
@@ -8875,6 +8879,7 @@
"{length} selected items": "已选择 {length} 项",
"Include subdirectories": "包含子目录",
"Only VCS changed text": "仅 VCS 更改的文本",
"Filters": "筛选条件",
"Files are reformatted by their language's formatter and saved; files without one are skipped.": "文件由各自语言的格式化程序重新格式化并保存;没有格式化程序的文件将被跳过。",
"No changed files to reformat": "没有需要重新格式化的已更改文件",
"No files to reformat": "没有需要重新格式化的文件",
@@ -9109,6 +9114,13 @@
"{description}; JVM options: {flags}": "{description};JVM 选项:{flags}",
"Sorting Options": "排序选项",
"Sort by Duration": "按持续时间排序",
"Move file '{name}'": "移动文件「{name}」",
"Move directory '{name}'": "移动目录「{name}」",
"Move {count} items": "移动 {count} 个项目",
"Browse for target directory": "浏览目标目录",
"Select Target Directory": "选择目标目录",
"Cannot move a folder into itself": "不能将文件夹移动到自身目录中",
"Already in this directory": "已在此目录中",
"Resize left merge pane": "调整左侧合并窗格宽度",
"Resize right merge pane": "调整右侧合并窗格宽度",
"Database and schema": "数据库和 schema",
+55
Переглянути файл
@@ -0,0 +1,55 @@
// @vitest-environment node
/**
* Selectors that make Chromium restyle whole subtrees on unrelated DOM changes. Blink checks a
* selector whose last part is universal (`*`, or only pseudo-classes) against every element, so:
*
* - `x > * + *` / `x ~ *` flags every parent as having children styled by their siblings, and any
* insertion then restyles the next sibling's whole subtree (an editor scroll inserts lines and
* gutters every frame);
* - `:focus *` / `:hover ::selection` makes every focus or hover change restyle the subtree of the
* element it happens on, wherever that element is;
* - `x:not(:focus-within) .y` makes WebKit restyle the whole window on every focus change (write the
* default style for `x .y` and override it with `x:focus-within .y`).
*
* Name the element instead (`x > :not(:first-child)`, `x > .item + .item`, `x:focus .label`).
*/
import { readdirSync, readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { expect, it } from "vitest";
const SRC = resolve(import.meta.dirname, "..");
function stylesheets(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const path = join(dir, e.name);
if (e.isDirectory()) return stylesheets(path);
return e.name.endsWith(".css") ? [path] : [];
});
}
/** A compound selector with no type, class, id or attribute: `*`, `:not(…)`, `::selection`. */
const UNIVERSAL = String.raw`(?:\*|(?=:))(?::{1,2}[\w-]+(?:\([^)]*\))?)*`;
const SIBLING = new RegExp(String.raw`[+~]\s*${UNIVERSAL}\s*$`);
const STATE_DESCENDANT = new RegExp(
String.raw`:(?:focus|focus-within|focus-visible|hover|active)[^\s>+~]*[\s>]+${UNIVERSAL}\s*$`,
);
const NEGATED_STATE = /:not\(:(?:focus|focus-within|focus-visible|hover|active)\)[^\s>+~]*[\s>+~]/;
it("no selector restyles whole subtrees on sibling insertions or focus changes", () => {
const costly: string[] = [];
for (const path of stylesheets(SRC)) {
const css = readFileSync(path, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");
for (const prelude of css.matchAll(/([^{};]+)\{/g)) {
const text = prelude[1]!.trim();
if (text.startsWith("@")) continue;
for (const selector of text.split(/,(?![^(]*\))/)) {
const s = selector.trim().replace(/:global\(([^)]*)\)/g, "$1");
// Combinators inside `:has(…)` relate other elements, not this one's ancestors.
const outer = s.replace(/:has\((?:[^()]|\([^()]*\))*\)/g, "");
if (SIBLING.test(s) || STATE_DESCENDANT.test(s) || NEGATED_STATE.test(outer))
costly.push(`${path.slice(SRC.length + 1)}: ${s}`);
}
}
}
expect(costly).toEqual([]);
});
+24
Переглянути файл
@@ -0,0 +1,24 @@
.body {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-4);
font-size: var(--fs-ui);
}
.group {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-inline-size: 0;
margin: 0;
padding: var(--space-2) 0 0;
border: 0;
border-block-start: 1px solid var(--border-popup);
}
.legend {
padding: 0 var(--space-2) 0 0;
color: var(--fg-strong);
font-weight: 600;
}
+6 -2
Переглянути файл
@@ -58,10 +58,14 @@
.active:hover {
background: var(--bg-tree-selected);
}
/* A focusable list that lost focus shows the inactive selection, like IDEA's JList. */
.list[tabindex="0"]:not(:focus-within) .active {
/* A focusable list shows the inactive selection until it holds focus. Not `:not(:focus-within)`:
WebKit then restyles the whole window on every focus change. */
.list[tabindex="0"] .active {
background: var(--bg-tree-selected-inactive);
}
.list[tabindex="0"]:focus-within .active {
background: var(--bg-tree-selected);
}
.section {
padding: 0 8px;
color: var(--fg-muted);
+31
Переглянути файл
@@ -277,6 +277,37 @@
padding: 0 var(--tab-inline-padding, 10px) 0 2px;
}
/* Editor tabs in a row sit 4px apart; wrapped rows keep their row gap. */
.editor:not(.vertical) .scroller {
column-gap: var(--space-1);
}
/* Every closable tab keeps a close slot at one edge (IDEA), cut to what the close glyph needs: 18px, a 2px
inset and the 16px button. The label side keeps the 8px inset, so the side doesn't change a tab's width. */
.editor:not(.vertical) .closeSlot {
position: absolute;
top: 0;
bottom: 0;
right: 2px;
width: auto;
margin: 0;
}
.editor:not(.vertical) .close {
width: 16px;
}
.editor:not(.vertical) .closeSlot .modified {
left: 5px;
}
.editor:not(.vertical, .closeLeft) .closable .tabButton {
padding-right: 18px;
}
.editor.closeLeft:not(.vertical) .closeSlot {
right: auto;
left: 2px;
}
.editor.closeLeft:not(.vertical) .closable .tabButton {
padding-left: 18px;
}
/* drag & drop: the dragged tab is an empty slot the other tabs make room for (IDEA) */
.tab.dragging,
.tab.dragging:hover {
+5 -2
Переглянути файл
@@ -358,7 +358,10 @@ describe("Tabs drag & drop", () => {
hit = strip("Terminal sessions");
pointer(window, "pointermove", 60);
expect(dragged).toHaveClass(styles.dragging!);
const ghost = document.body.lastElementChild as HTMLElement;
// The ghost sits in a copy of the strip's classes, so the strip's tab rules still lay it out.
const context = document.body.lastElementChild as HTMLElement;
expect(context.className).toBe(strip("Terminal sessions").parentElement!.className);
const ghost = context.firstElementChild as HTMLElement;
expect(ghost).toHaveAttribute("aria-hidden", "true");
expect(ghost.style.position).toBe("fixed");
expect(shown("Terminal sessions")).toEqual(["Local", "Local (2)", "Local (3)"]);
@@ -378,7 +381,7 @@ describe("Tabs drag & drop", () => {
.map((b) => b.textContent),
).toEqual(["Local (2)", "Local", "Local (3)"]);
expect(tab("Terminal sessions", "Local")).not.toHaveClass(styles.dragging!);
expect(document.body.lastElementChild).not.toBe(ghost);
expect(context.isConnected).toBe(false);
});
it("puts the slot back when the pointer leaves the strip and drops nothing on Escape", () => {
+10 -10
Переглянути файл
@@ -362,18 +362,16 @@ export function Tabs({
)
: null;
const marker = dragging === null ? drop : null;
const stripClass = clsx(
styles.strip,
styles[variant],
vertical ? styles.vertical : layout !== "scroll" && styles[layout],
closePosition === "left" && styles.closeLeft,
className,
);
return (
<div
className={clsx(
styles.strip,
styles[variant],
vertical ? styles.vertical : layout !== "scroll" && styles[layout],
closePosition === "left" && styles.closeLeft,
className,
)}
ref={stripRef}
>
<div className={stripClass} ref={stripRef}>
{vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
<div
ref={scrollRef}
@@ -422,6 +420,8 @@ export function Tabs({
e.currentTarget,
{ type: dnd.type, payload: dnd.payload(item.id) },
{
// The ghost keeps the strip's layout rules (close slot, insets).
ghostContext: stripClass,
onStart: () => {
draggingRef.current = item.id;
setDragging(item.id);
+16 -1
Переглянути файл
@@ -2,11 +2,26 @@
import { iconMarkupOrFallback, type IconName } from "./icons";
import spinnerStyles from "./Spinner.module.css";
/** Parsed markup, cloned into each node: widgets rebuild the same few icons on every render. */
const parsed = new Map<string, HTMLElement>();
export function iconNode(name: IconName | (string & {}), size = 16, className?: string): HTMLElement {
const span = document.createElement("span");
span.className = className ? `cm-openidea-icon ${className}` : "cm-openidea-icon";
span.setAttribute("aria-hidden", "true");
span.innerHTML = iconMarkupOrFallback(name, size);
const markup = iconMarkupOrFallback(name, size);
// Markup with ids is unique to this node (ids are never shared): nothing to reuse.
if (markup.includes('id="')) {
span.innerHTML = markup;
return span;
}
let source = parsed.get(markup);
if (!source) {
source = document.createElement("span");
source.innerHTML = markup;
parsed.set(markup, source);
}
span.append(...Array.from(source.childNodes, (n) => n.cloneNode(true)));
return span;
}
+21 -2
Переглянути файл
@@ -21,7 +21,7 @@
* - Element ids (clip paths) are made unique per instance: WebKit can't resolve
* references into `display: none` subtrees, so ids must never be shared.
*/
import { useId, useMemo, type CSSProperties } from "react";
import { useId, useLayoutEffect, useMemo, useRef, type CSSProperties } from "react";
import clsx from "clsx";
import { create } from "zustand";
import styles from "./icons.module.css";
@@ -839,6 +839,20 @@ const EMPTY: Prepared = { viewBox: "0 0 16 16", html: "", hasIds: false, mono: t
const withIds = (p: Prepared, prefix: string) => (p.hasIds ? p.html.replace(/__ID__/g, prefix) : p.html);
/** Parsed markup by source, cloned into each icon: a tree or list mounts dozens of the same icon
* per frame, and parsing `innerHTML` for each one costs more than the rest of the row. */
const parsed = new Map<string, SVGSVGElement>();
function fillIcon(svg: SVGSVGElement, html: string, shared: boolean) {
let source = shared ? parsed.get(html) : undefined;
if (!source) {
source = document.createElementNS("http://www.w3.org/2000/svg", "svg");
source.innerHTML = html;
if (shared) parsed.set(html, source);
}
svg.replaceChildren(...Array.from(source.childNodes, (n) => n.cloneNode(true)));
}
// ---------------------------------------------------------------------------
/** Largest `data:` image accepted as an icon (an avatar or a status badge a plugin fetched). */
@@ -887,11 +901,17 @@ function SvgIcon({ name, size = 16, className, style, label }: IconProps) {
const path = iconPath(name);
const p = (path && prepare(path, size >= 18)) || prepare(ICONS.file, size >= 18) || EMPTY;
const html = useMemo(() => withIds(p, `i${uid.replace(/[^a-zA-Z0-9_-]/g, "")}-`), [p, uid]);
const ref = useRef<SVGSVGElement>(null);
useLayoutEffect(() => {
// Markup with per-instance ids is unique to this icon: nothing to share.
if (ref.current) fillIcon(ref.current, html, !p.hasIds);
}, [html, p.hasIds]);
if (!path && name.startsWith("symbol-")) {
return <SymbolBadge kind={name.slice(7)} className={className} style={style} />;
}
return (
<svg
ref={ref}
className={clsx(styles.icon, p.mono && styles.mono, className)}
style={style}
width={size}
@@ -902,7 +922,6 @@ function SvgIcon({ name, size = 16, className, style, label }: IconProps) {
role={label ? "img" : undefined}
aria-label={label}
focusable="false"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}
+1
Переглянути файл
@@ -42,6 +42,7 @@ export { selectableText, copyMenuFor, copyText } from "./selectableText";
export { selectReadingPane, useSelectionBoundary } from "./useSelectionBoundary";
export { lockDragCursor, type DragCursor } from "./dragCursor";
export { useSanitizedField } from "./useSanitizedField";
export { useFrozenWhileWindowResizes } from "./useFrozenWhileWindowResizes";
export * from "./rowSelection";
export * from "./LogPane";
export * from "./Chip";
+31
Переглянути файл
@@ -48,6 +48,37 @@ describe("startPointerDrag with a reordered macOS tap", () => {
expect(onEnd).toHaveBeenCalledWith(true, expect.objectContaining({ x: 60 }));
});
it.each([
["dropped", () => fire("pointerup", 0, 40, 0)],
["cancelled with Escape", () => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }))],
])("wraps the ghost in its source's context and removes both when %s", (_, end) => {
const source = document.body.appendChild(document.createElement("div"));
startPointerDrag(
{ button: 0, clientX: 0, clientY: 0, altKey: false },
source,
{ type: "t", payload: "" },
{ ghostContext: "strip editor" },
);
fire("pointermove", 1, 40, 0);
const ghost = document.querySelector<HTMLElement>("[aria-hidden]")!;
const context = ghost.parentElement!;
expect(context.parentElement).toBe(document.body);
expect([...context.classList]).toEqual(["strip", "editor"]);
expect(context.style.display).toBe("contents");
expect(ghost.style.position).toBe("fixed");
end();
expect(context.isConnected).toBe(false);
expect(document.body.children).toHaveLength(1);
});
it("puts the ghost straight into the body without a context", () => {
start();
fire("pointermove", 1, 40, 0);
expect(document.querySelector("[aria-hidden]")!.parentElement).toBe(document.body);
fire("pointerup", 0, 40, 0);
expect(document.querySelector("[aria-hidden]")).toBeNull();
});
it("clears a text selection that began before the drag threshold (#3334)", () => {
const text = document.body.appendChild(document.createElement("p"));
text.textContent = "dragging a file must not select this";
+14 -2
Переглянути файл
@@ -158,11 +158,17 @@ export function startPointerDrag(
onEnd?: (dragged: boolean, drop?: PointerDrop) => void;
/** Not subject to "Drag-and-drop with Alt pressed only" (tabs and stripe buttons). */
always?: boolean;
/**
* Classes of the container `source` is styled by (a tab strip's): the ghost is wrapped in a
* `display: contents` element carrying them, so the container's descendant rules still match it.
*/
ghostContext?: string;
} = {},
) {
if (e.button !== 0 || (!opts.always && requiresAlt() && !e.altKey)) return;
const start = { x: e.clientX, y: e.clientY };
let ghost: HTMLElement | null = null;
let context: HTMLElement | null = null;
let endDrag: (() => void) | null = null;
const session = dragSession(data);
const onMove = (ev: PointerEvent) => {
@@ -185,7 +191,13 @@ export function startPointerDrag(
width: `${r.width}px`,
height: `${r.height}px`,
});
document.body.appendChild(ghost);
if (opts.ghostContext) {
context = document.createElement("div");
context.className = opts.ghostContext;
context.style.display = "contents";
context.appendChild(ghost);
}
document.body.appendChild(context ?? ghost);
endDrag = beginDrag();
opts.onStart?.();
}
@@ -217,7 +229,7 @@ export function startPointerDrag(
window.removeEventListener("pointerup", onUp);
window.removeEventListener("pointercancel", onCancel);
window.removeEventListener("keydown", onKey, true);
ghost?.remove();
(context ?? ghost)?.remove();
endDrag?.();
};
const onCancel = () => {
+52
Переглянути файл
@@ -0,0 +1,52 @@
import { act, render } from "@testing-library/react";
import { useRef } from "react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { WINDOW_RESIZE_SETTLE_MS, useFrozenWhileWindowResizes } from "./useFrozenWhileWindowResizes";
function Frozen() {
const ref = useRef<HTMLDivElement>(null);
useFrozenWhileWindowResizes(ref);
return (
<div data-testid="parent">
<div ref={ref} data-testid="view" />
</div>
);
}
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("keeps the view at its size while the window resizes and releases it once the drag pauses", () => {
const { getByTestId } = render(<Frozen />);
const view = getByTestId("view");
const parent = getByTestId("parent");
view.getBoundingClientRect = () => ({ width: 300, height: 120 }) as DOMRect;
act(() => void window.dispatchEvent(new Event("resize")));
expect(view.style.width).toBe("300px");
expect(view.style.height).toBe("120px");
expect(view.style.flexGrow).toBe("0");
expect(parent.style.overflow).toBe("hidden");
// Still dragging: the size taken at the start stays.
view.getBoundingClientRect = () => ({ width: 200, height: 80 }) as DOMRect;
act(() => vi.advanceTimersByTime(WINDOW_RESIZE_SETTLE_MS - 1));
act(() => void window.dispatchEvent(new Event("resize")));
act(() => vi.advanceTimersByTime(WINDOW_RESIZE_SETTLE_MS - 1));
expect(view.style.width).toBe("300px");
act(() => vi.advanceTimersByTime(1));
expect(view.style.width).toBe("");
expect(view.style.height).toBe("");
expect(view.style.flex).toBe("");
expect(parent.style.overflow).toBe("");
});
it("releases the view when it unmounts mid-drag", () => {
const { getByTestId, unmount } = render(<Frozen />);
const parent = getByTestId("parent");
act(() => void window.dispatchEvent(new Event("resize")));
expect(parent.style.overflow).toBe("hidden");
unmount();
expect(parent.style.overflow).toBe("");
});
+45
Переглянути файл
@@ -0,0 +1,45 @@
import { useEffect, type RefObject } from "react";
/** How long the window must keep its size before a frozen element follows it. */
export const WINDOW_RESIZE_SETTLE_MS = 150;
/**
* While the window is being resized, keeps the element at the size it had when the drag started,
* on its own layer and clipped by its parent, then lets it take the new size once the drag pauses.
* For dense views that WebKit cannot lay out and paint at every step of a live resize: their pixels
* are moved instead of redrawn, so the rest of the window keeps up with the pointer.
*/
export function useFrozenWhileWindowResizes(ref: RefObject<HTMLElement | null>): void {
useEffect(() => {
let frozen: { el: HTMLElement; parent: HTMLElement | null; parentOverflow: string } | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
const release = () => {
clearTimeout(timer);
if (!frozen) return;
const { el, parent, parentOverflow } = frozen;
for (const p of ["width", "height", "flex", "will-change"]) el.style.removeProperty(p);
if (parent) parent.style.overflow = parentOverflow;
frozen = null;
};
const onResize = () => {
const el = ref.current;
if (!frozen && el?.isConnected) {
const { width, height } = el.getBoundingClientRect();
const parent = el.parentElement;
frozen = { el, parent, parentOverflow: parent?.style.overflow ?? "" };
el.style.setProperty("width", `${width}px`, "important");
el.style.setProperty("height", `${height}px`, "important");
el.style.setProperty("flex", "none", "important");
el.style.setProperty("will-change", "transform");
if (parent) parent.style.overflow = "hidden";
}
clearTimeout(timer);
timer = setTimeout(release, WINDOW_RESIZE_SETTLE_MS);
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
release();
};
}, [ref]);
}
+16 -1
Переглянути файл
@@ -58,8 +58,23 @@ export function mountWindowRoot(View: ComponentType, { prefetchLazy = false }: {
function App() {
useEffect(() => {
hideSplash();
if (!prefetchLazy) return;
// The first file opened would otherwise also build the editor setup cold.
const warm = () => {
if (!document.querySelector(".cm-editor"))
void import("./editor/core/cm/prewarm").then((m) => m.prewarmEditor());
};
const idle =
typeof requestIdleCallback === "function"
? requestIdleCallback(warm, { timeout: 2000 })
: window.setTimeout(warm, 500);
// Views split out of the start-up bundle load in the background once the UI is up.
if (prefetchLazy) return prefetchLazyComponents();
const stopPrefetch = prefetchLazyComponents();
return () => {
if (typeof cancelIdleCallback === "function") cancelIdleCallback(idle);
else window.clearTimeout(idle);
stopPrefetch();
};
}, []);
return <View />;
}