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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 70843d998a Merge remote-tracking branch 'origin/main' into fix/services-detail-layout 2026-11-19 21:37:09 +08:00
l0ng-ai 2265497b18 fix(navigation): keep File Structure filters readable (#4522)
The File Structure popup is 540px wide and its filter options wrap onto further rows instead of being clipped at narrow window widths; the filter field uses the UI font.
2026-11-19 21:34:39 +08:00
l0ng-ai 7f33640895 feat(markdown): run code blocks and command lines from the gutter (#4530)
Markdown files get gutter run icons like IDEA's Markdown command runner: shell code blocks run in a new terminal tab from their fence, and code block lines run when a Run Anything provider recognizes them (Maven/Gradle lines, run configuration names; providers gain accepts()). Languages & Frameworks > Markdown > Commands toggles detection and picks the folder (asking when unset and the project and file folder differ). Untrusted projects get no icons.
2026-11-19 21:17:16 +08:00
l0ng-ai a57e12dbc5 fix(http): don't rescan Spring routes on every keystroke (#4525)
Typing in a Java/Kotlin file rescanned every Spring mapping source once per keystroke: Feign navigation dropped the route index on each docChanged (it already overlays unsaved text), and editor endpoint icons re-queried every provider, Spring included, on each change though they show only plugin endpoints. Typing now keeps the disk index; icons ask only plugin providers after typing pauses.
2026-11-19 21:07:43 +08:00
l0ng-ai 0180ad81af fix(services): give service details more room 2026-11-19 21:01:22 +08:00
l0ng-ai b3f8cec272 fix(updates): don't hold the update lock while asking which window is focused (#4523)
The automatic update announcement held updates.ready while asking a window whether it is focused (a main-thread round trip); a window starting up ran app_update_window_ready on the main thread and waited for the same lock, freezing startup with no window. The focused and live windows are now read before taking the lock.
2026-11-19 21:01:13 +08:00
l0ng-ai e44e389571 fix(vcs): improve Commit panel layout and message typography (#4518)
The Commit panel wraps change actions into groups when the pane is narrow, so Expand All and Collapse All stay visible, and Commit and Push… wraps its label instead of cutting it. The commit message uses the editor's font family, size, weight and line height.
2026-11-19 20:58:36 +08:00
l0ng-ai 0cf0e93d92 fix(settings): give settings forms more room (#4515)
Settings starts with 22.5% of its width for navigation instead of a fixed 240px, giving the current form more room at the default window size while leaving space for long labels such as Build, Execution, Deployment. A user-resized divider is still remembered.
2026-11-19 20:56:59 +08:00
l0ng-ai c7ad3459c4 fix(vcs): fit Git Log controls in narrow panes (#4512)
Git Log gives the text filter its own row when the commit pane gets narrow; the other filters stay in More Filters and the action buttons wrap inside the pane, so Refresh, View Options and Go to Hash/Branch/Tag stay usable with the branch and details panes open.
2026-11-19 20:56:31 +08:00
35 змінених файлів з 930 додано та 257 видалено

No files matched your search

+21 -1
Переглянути файл
@@ -1194,11 +1194,31 @@ pub struct ArduinoSettings {
}
/// Languages & Frameworks › Markdown. Like IDEA's, it is application-level only.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MarkdownSettings {
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
/// Where those commands run; unset asks when the project and the file's folder differ.
pub command_directory: Option<MarkdownCommandDirectory>,
}
impl Default for MarkdownSettings {
fn default() -> Self {
Self { preview_font_size: None, run_commands: true, command_directory: None }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "lowercase")]
pub enum MarkdownCommandDirectory {
/// The project's root folder.
Project,
/// The Markdown file's parent folder.
File,
}
impl LanguagesSettings {
+56
Переглянути файл
@@ -98,3 +98,59 @@ test("commit message history opens above the message without an empty icon colum
expect(Math.abs(menuBox!.x - messageBox!.x)).toBeLessThan(2);
await expect(row.locator("span")).toHaveCount(1);
});
test("the Commit changes toolbar fits a narrow side pane", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ path);
layout.moveToolWindow("commit", "left");
layout.setToolWindowSize("left", 164);
});
const panel = page.getByRole("region", { name: "Commit", exact: true });
const toolbar = panel.getByRole("toolbar", { name: "Changes" });
await expect(toolbar).toBeVisible();
const clipped = await toolbar.evaluate((bar) => {
const bounds = bar.getBoundingClientRect();
return [...bar.querySelectorAll("button")].flatMap((button) => {
const box = button.getBoundingClientRect();
return box.right > bounds.right + 1 || box.bottom > bounds.bottom + 1 ? [button.ariaLabel] : [];
});
});
expect(clipped).toEqual([]);
const push = panel.getByRole("button", { name: "Commit and Push…" });
const overflow = await push.locator("span").evaluate((label) => label.scrollWidth - label.clientWidth);
expect(overflow).toBeLessThanOrEqual(1);
await toolbar.getByRole("button", { name: "Collapse All" }).click();
await expect(panel.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
test("the commit message uses the configured editor typography", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
const message = page.getByRole("textbox", { name: "Commit message" });
await expect(message).toBeFocused();
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const settings = useProject.getState().settings;
useProject.setState({
settings: {
...settings,
editor: {
...settings?.editor,
fontFamily: "Fira Code",
fallbackFont: "Maple Mono NF CN",
fontSize: 17,
lineHeight: 28,
fontWeight: 500,
},
},
});
});
await expect(message).toHaveCSS("font-size", "17px");
await expect(message).toHaveCSS("line-height", "28px");
await expect(message).toHaveCSS("font-weight", "500");
await expect(message).toHaveCSS("font-family", /"Fira Code".*"Maple Mono NF CN"/);
});
+54
Переглянути файл
@@ -0,0 +1,54 @@
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
test("File Structure keeps symbol filters readable at desktop and minimum window widths", async ({
workbench: page,
}) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } };
const field = {
name: "orderCount",
kind: "field",
visibility: "private",
range,
selection_range: range,
children: [],
};
window.__ipc.handlers.doc_outline = () => [
{ name: "OrderController", kind: "class", range, selection_range: range, children: [field] },
];
window.__ipc.handlers.lsp_type_hierarchy = () => [];
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("navigate.fileStructure");
});
const dialog = page.getByRole("dialog", { name: "File Structure" });
const fields = dialog.getByRole("checkbox", { name: "Show fields" });
await expect(dialog.getByRole("checkbox", { name: "Show inherited members" })).toBeVisible();
for (const width of [400, 1000]) {
await page.setViewportSize({ width, height: 600 });
const clipped = await dialog.evaluate((element) => {
const labels = [...element.querySelectorAll("label")].filter((label) =>
label.querySelector('input[type="checkbox"]'),
);
const row = labels[0]!.parentElement!.getBoundingClientRect();
return labels.flatMap((label) => {
const range = document.createRange();
range.selectNodeContents(label);
const box = range.getBoundingClientRect();
return box.top < row.top - 1 || box.right > row.right + 1 || box.bottom > row.bottom + 1
? [label.textContent]
: [];
});
});
expect(clipped).toEqual([]);
}
// The dialog scales in when it opens: wait for its settled width.
await expect.poll(async () => Math.round((await dialog.boundingBox())!.width)).toBe(540);
const field = dialog.getByRole("treeitem", { name: "orderCount" });
await expect(field).toBeVisible();
await fields.uncheck();
await expect(field).toBeHidden();
});
+27
Переглянути файл
@@ -94,3 +94,30 @@ test("a second click on a Git Log toolbar button closes its popup", async ({ wor
await expect(row).toBeHidden();
}
});
test("Git Log keeps filters and actions inside the commit pane at the minimum window width", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 400, height: 500 });
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const clippedButtons = () =>
toolbar.evaluate((el) => {
const bar = el.getBoundingClientRect();
return Array.from(el.querySelectorAll("button"))
.filter((button) => {
if (getComputedStyle(button).visibility === "hidden") return false;
const box = button.getBoundingClientRect();
return box.width > 0 && (box.right > bar.right + 1 || box.bottom > bar.bottom + 1);
})
.map((button) => button.getAttribute("aria-label"));
});
await expect.poll(clippedButtons).toEqual([]);
const search = toolbar.getByRole("textbox", { name: "Filter by message" });
await expect(search).toBeVisible();
expect((await search.boundingBox())!.width).toBeGreaterThan(12);
await toolbar.getByRole("button", { name: "View Options" }).click();
await expect(page.getByRole("menuitemcheckbox", { name: "Tag Names" })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "More Filters" }).click();
await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible();
});
+45
Переглянути файл
@@ -48,6 +48,51 @@ async function move(page: Page, source: string, target: string) {
await page.mouse.up();
}
test("Services favors details and stacks the panes when docked to the side", async ({ workbench: page }) => {
await configure(page);
const services = page.getByRole("region", { name: "Services", exact: true });
const items = services.locator("[data-panel][id=services-items]");
const detail = services.locator("[data-panel][id=services-detail]");
const handle = services.locator("[data-separator]");
const share = async (axis: "width" | "height") => {
const treeSize = (await items.boundingBox())![axis];
return treeSize / (treeSize + (await detail.boundingBox())![axis]);
};
const dock = (anchor: "bottom" | "right" | "left") =>
page.evaluate(async (anchor) => {
const path = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ path);
moveToolWindow("services", anchor);
if (anchor !== "bottom") setToolWindowSize(anchor, 280);
}, anchor);
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
await expect.poll(() => share("width")).toBeCloseTo(0.3, 2);
await handle.press("ArrowRight");
await expect.poll(() => share("width")).toBeGreaterThan(0.31);
const bottom = await share("width");
for (const anchor of ["right", "left"] as const) {
await dock(anchor);
await expect(handle).toHaveAttribute("aria-orientation", "horizontal");
const treeBox = (await items.boundingBox())!;
const detailBox = (await detail.boundingBox())!;
expect(detailBox.width).toBeCloseTo(treeBox.width, 0);
expect(detailBox.y).toBeGreaterThanOrEqual(treeBox.y + treeBox.height - 1);
await expect.poll(() => share("height")).toBeCloseTo(0.3, 2);
}
await handle.press("ArrowDown");
await expect.poll(() => share("height")).toBeGreaterThan(0.31);
const side = await share("height");
await dock("bottom");
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
await expect.poll(() => share("width")).toBeCloseTo(bottom, 2);
await dock("right");
await expect(handle).toHaveAttribute("aria-orientation", "horizontal");
await expect.poll(() => share("height")).toBeCloseTo(side, 2);
});
test("service pointer ordering works for Java and npm and survives reload", async ({ workbench: page }) => {
await configure(page);
const tree = page.getByRole("tree", { name: "Services", exact: true });
+1
Переглянути файл
@@ -72,6 +72,7 @@ test("settings sidebar resizes with mouse and keyboard and remembers its width",
await expect(handle).toBeVisible();
const sidebar = dialog.locator("#navigation");
const initial = (await sidebar.boundingBox())!.width;
expect(initial / (await dialog.getByTestId("settings").boundingBox())!.width).toBeCloseTo(0.225, 2);
const box = (await handle.boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
+5 -2
Переглянути файл
@@ -139,11 +139,14 @@ fn announce_available(app: &AppHandle) {
return;
}
let state = app.state::<AppState>();
// Asking a window whether it is focused waits for the main thread, where
// `app_update_window_ready` takes `ready`: never hold the lock across it.
let focused = crate::windows::target_window(app);
let live = crate::windows::project_window_labels(app);
let owner = {
let mut ready = state.updates.ready.lock();
ready.retain(|label| app.get_webview_window(label).is_some());
let focused = crate::windows::target_window(app);
ready_owner(focused.as_ref().map(|window| window.label()), &crate::windows::project_window_labels(app), &ready)
ready_owner(focused.as_ref().map(|window| window.label()), &live, &ready)
};
let Some(owner) = owner else { return };
let update = {
+13
Переглянути файл
@@ -8237,10 +8237,23 @@ export type ManifestDependency = {
to: number,
};
export type MarkdownCommandDirectory =
/** The project's root folder. */
"project" |
/** The Markdown file's parent folder. */
"file";
/** Languages & Frameworks › Markdown. Like IDEA's, it is application-level only. */
export type MarkdownSettings = {
/** Preview (and notebook Markdown cell) font size in px; unset follows the editor font size. */
previewFontSize?: number | null,
/**
* "Detect commands that can be run right from Markdown files": gutter run icons on
* shell code blocks and on command lines in code blocks.
*/
runCommands?: boolean,
/** Where those commands run; unset asks when the project and the file's folder differ. */
commandDirectory?: MarkdownCommandDirectory | null,
};
/** A marketplace entry with what is installed. */
+4
Переглянути файл
@@ -97,4 +97,8 @@ export const buildToolsRunAnything: RunAnythingProvider = {
const tool = lineTool(line);
return !!tool && executeBuildLine(tool, line);
},
accepts(line) {
const tool = lineTool(line);
return !!tool && (tool === "maven" ? parseGoalLine(line) : parseTaskLine(line)).length > 0;
},
};
+32 -2
Переглянути файл
@@ -1,9 +1,10 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { CompletionContext } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useProject } from "@/platform/project";
import { registerEndpointProvider, searchEndpoints, type EndpointEntry } from "@/workbench/contributions";
import { completionTarget, endpointCompletion, renderEndpoint } from "./endpoints";
import { completionTarget, endpointCompletion, endpointEditorExtension, renderEndpoint } from "./endpoints";
const route: EndpointEntry = {
method: "GET",
@@ -70,4 +71,33 @@ describe("shared HTTP endpoints", () => {
useProject.setState(previous);
}
});
it("asks only plugin providers for editor icons, once typing pauses", async () => {
vi.useFakeTimers();
const previous = useProject.getState();
useProject.setState({ project: { root: "/p" } as NonNullable<typeof previous.project> });
const scan = vi.fn(async () => [route]);
const plugin = vi.fn(async () => [{ ...route, pluginId: "demo", path: "/p/Users.java" }]);
const disposeScan = registerEndpointProvider({ id: "http.spring", endpoints: scan });
const disposePlugin = registerEndpointProvider({ id: "plugin:demo", endpoints: plugin });
const ctx = { doc: 1, path: "/p/Users.java", language: "java", uiMode: null, readOnly: false };
const view = new EditorView({
state: EditorState.create({ doc: "class Users {}", extensions: endpointEditorExtension(ctx) }),
});
try {
await vi.runAllTimersAsync();
plugin.mockClear();
for (const ch of "abc") view.dispatch({ changes: { from: 0, insert: ch } });
expect(plugin).not.toHaveBeenCalled();
await vi.runAllTimersAsync();
expect(plugin).toHaveBeenCalledTimes(1);
expect(scan).not.toHaveBeenCalled();
} finally {
view.destroy();
disposeScan();
disposePlugin();
useProject.setState(previous);
vi.useRealTimers();
}
});
});
+14 -3
Переглянути файл
@@ -72,6 +72,9 @@ export async function endpointCompletion(context: CompletionContext): Promise<Co
};
}
const REFRESH_DELAY = 300;
const isPluginProvider = (id: string) => id.startsWith("plugin:");
type Mark = { pos: number; endpoints: EndpointEntry[] };
const setMarks = StateEffect.define<Mark[]>();
const marks = StateField.define<Mark[]>({
@@ -112,18 +115,25 @@ export function endpointEditorExtension(ctx: EditorDocContext): Extension {
destroyed = false;
unsubscribe: () => void;
projectUnsubscribe: () => void;
timer: ReturnType<typeof setTimeout> | undefined;
constructor(readonly view: EditorView) {
this.unsubscribe = onEndpointsChanged(() => this.refresh());
this.projectUnsubscribe = useProject.subscribe(() => this.refresh());
this.projectUnsubscribe = useProject.subscribe((state, previous) => {
if (state.project !== previous.project) this.refresh();
});
this.refresh();
}
update(u: { docChanged: boolean }) {
if (u.docChanged) this.refresh();
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => this.refresh(), REFRESH_DELAY);
}
refresh() {
clearTimeout(this.timer);
const seq = ++this.seq;
const root = useProject.getState().project?.root ?? null;
void searchEndpoints(root).then((entries) => {
// Only plugin endpoints get icons here; built-in providers (Spring) scan the project.
void searchEndpoints(root, isPluginProvider).then((entries) => {
if (this.destroyed || seq !== this.seq) return;
const byLine = new Map<number, EndpointEntry[]>();
for (const e of entries) {
@@ -136,6 +146,7 @@ export function endpointEditorExtension(ctx: EditorDocContext): Extension {
}
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
this.unsubscribe();
this.projectUnsubscribe();
}
+9
Переглянути файл
@@ -101,6 +101,15 @@ describe("core service-aware Feign navigation", () => {
expect(await resolve()).toEqual([]); // Current source revalidation rejects the cached target.
});
it("keeps the disk index while a controller is edited", async () => {
await resolve();
for (let version = 2; version < 6; version++) {
_emitEditorEvent({ type: "docChanged", doc: 9, path: users, baseVersion: version - 1, version, changes: [] });
await resolve();
}
expect(commands.springRouteSources).toHaveBeenCalledTimes(1);
});
it("overlays recently edited unsaved controllers absent from the disk index", async () => {
await resolve();
const path = "/p/users/src/main/kotlin/Added.kt";
+13 -5
Переглянути файл
@@ -39,12 +39,16 @@ function inside(project: ProjectInfo, path: string): boolean {
async function read(path: string): Promise<string> {
return editorsFor(path)[0]?.view.state.doc.toString() ?? (await call(commands.fsReadText(path)));
}
function invalidate() {
/** Forgets resolved targets and service names; the disk route index stays. */
function refresh() {
epoch++;
serviceNames.clear();
clearRouteIndex();
invalidateNavigationProviders();
}
function invalidate() {
refresh();
clearRouteIndex();
}
function named(module: string): Promise<string | null> {
let pending = serviceNames.get(module);
@@ -155,9 +159,13 @@ export function registerFeignNavigation(): () => void {
(!isRouteSource(event.path) && !isServiceConfiguration(event.path))
)
return;
if (event.type === "docChanged" && isRouteSource(event.path)) {
if (changedSources.size < 256) changedSources.add(event.path);
} else if (event.type === "docClosed" || event.type === "docSaved") changedSources.delete(event.path);
if (event.type === "docChanged") {
if (isRouteSource(event.path) && changedSources.size < 256) changedSources.add(event.path);
// Unsaved text is overlaid on the disk index: typing must not rescan the project.
refresh();
return;
}
changedSources.delete(event.path);
invalidate();
});
const projects = useProject.subscribe((state, previous) => {
+2
Переглянути файл
@@ -71,6 +71,7 @@ import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { markdownCommandGutter } from "./markdownCommands";
import { gradleDelegation } from "./gradleRun";
import { activateStackTrace, useStackTraces } from "./stackTrace";
import { clearRuntimeCache } from "./runtimes";
@@ -485,6 +486,7 @@ export function activate(): () => void {
}),
registerEditorContribution({ id: "run.targets", order: 55, extensions: runGutter }),
registerEditorContribution({ id: "run.npmScripts", order: 58, extensions: npmGutter }),
registerEditorContribution({ id: "run.markdownCommands", order: 58, extensions: markdownCommandGutter }),
registerEditorContribution({ id: "run.launchSettings", order: 58, extensions: launchSettingsGutter }),
registerMenuGroup({
id: "run.context",
+70
Переглянути файл
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it } from "vitest";
import { useProject } from "@/platform/project";
import { commandMenuItems, markdownCommands, trimPrompt, type CommandEntry } from "./markdownCommands";
const accepts = (line: string) => /^(mvn|\.\/gradlew) /.test(line);
describe("Markdown commands", () => {
it("runs shell blocks from their fence and recognized command lines from any block", () => {
const text = [
"## Setup",
"```shell",
"$ mise install # tools",
"",
"mvn test",
"```",
"```java",
"mvn not a command here? still a recognized line",
"```",
"~~~text",
"./gradlew build",
"~~~",
].join("\n");
expect(markdownCommands(text, accepts).map((e) => [e.kind, e.line, e.lines])).toEqual([
["block", 1, ["mise install", "mvn test"]],
["line", 4, ["mvn test"]],
["line", 7, ["mvn not a command here? still a recognized line"]],
["line", 10, ["./gradlew build"]],
]);
});
it("ignores blocks without commands, other languages and unclosed fences' closing rules", () => {
expect(markdownCommands("```bash\n# only a comment\n```", accepts)).toEqual([]);
expect(markdownCommands("```python\nprint(1)\n```", accepts)).toEqual([]);
// A shorter closing fence doesn't close a longer one.
expect(markdownCommands("````sh\nls\n```\npwd\n````", accepts)[0]?.lines).toEqual(["ls", "```", "pwd"]);
});
it("keeps quoted # and PowerShell lines as written", () => {
expect(trimPrompt(['echo "a # b" # note', "$ git log #x", "#!/bin/sh"])).toEqual(['echo "a # b"', "git log"]);
expect(markdownCommands("```powershell\n$env:X = 1 # keep\n```", accepts)[0]?.lines).toEqual(["$env:X = 1 # keep"]);
});
});
describe("Markdown command menu", () => {
const block: CommandEntry = { kind: "block", name: "block:1", line: 1, lines: ["make build"] };
afterEach(() => useProject.setState({ project: null, settings: null }));
const open = (commandDirectory?: string) =>
useProject.setState({
project: { root: "/p", name: "p", settings: {}, trusted: true, isGit: false },
settings: { languages: { markdown: { commandDirectory } } } as never,
});
it("asks for the folder when the project and the file's folder differ", async () => {
open();
expect((await commandMenuItems(block, "/p/docs/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run from Project Root Directory",
"Run from Parent Directory of Current File (docs)",
]);
expect((await commandMenuItems(block, "/p/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run in Terminal",
]);
});
it("uses the configured folder", async () => {
open("file");
expect((await commandMenuItems(block, "/p/docs/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run in Terminal",
]);
});
});
+135
Переглянути файл
@@ -0,0 +1,135 @@
/**
* Run icons in Markdown files, like IDEA's Markdown command runner: ▶ on a shell
* code block's opening fence runs the block in a new terminal tab, and ▶ on a
* line of any code block runs it when a Run Anything provider recognizes the
* command (`mvn test`, `./gradlew build`, a run configuration's name).
*/
import type { Extension } from "@codemirror/state";
import type { EditorDocContext } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { markdownCommandSettings } from "@/platform/languageSettings";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { runAnythingProviderList } from "@/workbench/contributions";
import { entryGutter, type ScriptEntry } from "./npmGutter";
const SHELL = new Set(["sh", "bash", "zsh", "shell", "shellscript", "shell-script", "console"]);
const POWERSHELL = new Set(["powershell", "pwsh", "ps1"]);
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/;
export interface CommandEntry extends ScriptEntry {
kind: "block" | "line";
/** What runs: the block's commands, or the line's. */
lines: string[];
}
/** `line` without a trailing `# comment` outside quotes. */
function stripComment(line: string): string {
let single = false;
let double = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (c === "'" && !double) single = !single;
else if (c === '"' && !single) double = !double;
else if (c === "#" && !single && !double && (i === 0 || /\s/.test(line[i - 1]!))) return line.slice(0, i).trimEnd();
}
return line;
}
/** Shell lines without a leading `$` prompt or trailing comments; empty lines dropped. */
export function trimPrompt(lines: readonly string[]): string[] {
return lines.map((line) => stripComment(line.startsWith("$") ? line.slice(1) : line).trim()).filter(Boolean);
}
/**
* The runnable places of Markdown `text`: shell code blocks (on their opening fence)
* and code block lines `accepts` recognizes as commands.
*/
export function markdownCommands(text: string, accepts: (line: string) => boolean): CommandEntry[] {
const lines = text.split("\n");
const out: CommandEntry[] = [];
for (let i = 0; i < lines.length; i++) {
const open = FENCE.exec(lines[i]!);
if (!open) continue;
const marker = open[1]!;
const language = open[2]!.toLowerCase();
const close = new RegExp(`^ {0,3}${marker[0] === "`" ? "`" : "~"}{${marker.length},}\\s*$`);
let end = i + 1;
while (end < lines.length && !close.test(lines[end]!)) end++;
const body = lines.slice(i + 1, end).map((l) => l.replace(/\r$/, ""));
if (SHELL.has(language) || POWERSHELL.has(language)) {
const commands = POWERSHELL.has(language) ? body.filter((l) => l.trim()) : trimPrompt(body);
if (commands.length) out.push({ kind: "block", name: `block:${i}`, line: i, lines: commands });
}
body.forEach((raw, k) => {
const [command] = trimPrompt([raw]);
if (command && accepts(command))
out.push({ kind: "line", name: `line:${command}`, line: i + 1 + k, lines: [command] });
});
i = end;
}
return out;
}
/** Whether a Run Anything provider runs `line` as a command it recognizes. */
function accepted(line: string): boolean {
return runAnythingProviderList().some((p) => !!p.accepts?.(line));
}
async function runLine(line: string) {
for (const p of runAnythingProviderList()) if (p.accepts?.(line) && p.execute && (await p.execute(line))) return;
}
const parentDir = (path: string) => path.slice(0, Math.max(path.lastIndexOf("/"), 0)) || "/";
/** The folders a block may run in: the setting's, or both when it asks and they differ. */
function directories(path: string): { project: string; file: string } | string | null {
const { project, settings } = useProject.getState();
if (!project?.root) return null;
const file = parentDir(path);
const choice = markdownCommandSettings(settings).commandDirectory;
if (choice === "file") return file;
if (choice === "project" || file === project.root) return project.root;
return { project: project.root, file };
}
function runBlock(lines: string[], cwd: string) {
void executeAction("terminal.runLines", { lines, cwd });
}
export async function commandMenuItems(entry: ScriptEntry, path: string): Promise<MenuItem[]> {
const command = entry as CommandEntry;
if (command.kind === "line") {
const line = command.lines[0]!;
return [{ label: tx`Run '${line}'`, icon: "run", run: () => void runLine(line) }];
}
const dirs = directories(path);
if (!dirs) return [];
const shown = typeof dirs === "string" ? "" : dirs.file.slice(dirs.project.length + 1) || dirs.file;
if (typeof dirs === "string")
return [{ label: tx`Run in Terminal`, icon: "terminal", run: () => runBlock(command.lines, dirs) }];
return [
{ label: tx`Run from Project Root Directory`, icon: "terminal", run: () => runBlock(command.lines, dirs.project) },
{
label: tx`Run from Parent Directory of Current File (${shown})`,
icon: "terminal",
run: () => runBlock(command.lines, dirs.file),
},
];
}
export function markdownCommandGutter(ctx: EditorDocContext): Extension {
const { project, settings } = useProject.getState();
if (!project?.trusted || !markdownCommandSettings(settings).runCommands) return [];
return entryGutter(
ctx,
/\.(md|markdown)$/i,
(text) => markdownCommands(text, accepted),
commandMenuItems,
(entry) => {
const command = entry as CommandEntry;
return command.kind === "block" ? tx`Run in Terminal` : tx`Run '${command.lines[0]!}'`;
},
);
}
+4 -2
Переглянути файл
@@ -312,6 +312,7 @@ class ScriptMarker extends GutterMarker {
readonly entry: ScriptEntry,
readonly path: string,
readonly menu: EntryMenu,
readonly title: (entry: ScriptEntry) => string,
) {
super();
}
@@ -322,7 +323,7 @@ class ScriptMarker extends GutterMarker {
const el = document.createElement("button");
el.type = "button";
el.className = styles.runMarker ?? "";
el.title = tx`Run '${this.entry.name}'`;
el.title = this.title(this.entry);
el.setAttribute("aria-label", el.title);
el.innerHTML = gutterIconMarkup("gutter-run") ?? "";
el.addEventListener("click", () => {
@@ -350,6 +351,7 @@ export function entryGutter(
file: RegExp,
entries: (text: string) => ScriptEntry[],
menu: EntryMenu,
title: (entry: ScriptEntry) => string = (entry) => tx`Run '${entry.name}'`,
): Extension {
const path = ctx.path;
if (ctx.virtual || !file.test(path) || !useProject.getState().project?.root) return [];
@@ -394,7 +396,7 @@ export function entryGutter(
markers: (view) =>
runIconsShown()
? RangeSet.of(
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu).range(e.pos)),
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu, title).range(e.pos)),
true,
)
: RangeSet.empty,
+1
Переглянути файл
@@ -30,6 +30,7 @@ export const runConfigsRunAnything: RunAnythingProvider = {
group: "Run Configurations",
order: 10,
items: (query) => matchingConfigs(useRun.getState().configs, query).map(item),
accepts: (line) => useRun.getState().configs.some((c) => c.name === line.trim()),
execute(line) {
const config = useRun.getState().configs.find((c) => c.name === line.trim());
if (!config) return false;
+7 -7
Переглянути файл
@@ -101,14 +101,12 @@
border: 0;
outline: none;
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
font-family: var(--font-ui);
font-size: var(--fs-ui);
caret-color: var(--accent);
}
.filter::placeholder {
color: var(--fg-faint);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.filterStatus {
color: var(--fg-muted);
@@ -125,10 +123,12 @@
}
.popupOptions {
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: center;
gap: var(--space-3);
height: 26px;
padding: 0 12px;
gap: var(--space-1) var(--space-3);
min-height: 32px;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border-popup);
font-size: var(--fs-small);
}
+1 -1
Переглянути файл
@@ -471,7 +471,7 @@ function FileStructureDialog() {
<Dialog
open
onClose={close}
width={460}
width={540}
position="top"
transparentBackdrop
aria-label="File Structure"
+13 -3
Переглянути файл
@@ -23,6 +23,7 @@ import {
type TreeReorder,
} from "@/ui";
import {
SERVICES_WINDOW,
useServiceProviders,
useToolWindowShown,
serviceProviders,
@@ -30,6 +31,7 @@ import {
type ServiceTreeItem,
type ServiceItemAction,
} from "@/workbench/contributions";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import {
addServiceMenu,
clearProviderRoots,
@@ -88,6 +90,9 @@ export function ServicesTreeView() {
const selectedKey = useServicesTree((s) => s.selectedKey);
const selectedKeys = useServicesTree((s) => s.selectedKeys);
const expanded = useServicesTree((s) => s.expanded);
const anchor = useToolWindowLayout((s) => s.placements[SERVICES_WINDOW]?.anchor ?? "bottom");
const sideDocked = anchor !== "bottom";
const orientation = sideDocked ? "vertical" : "horizontal";
const addRef = useRef<HTMLButtonElement>(null);
const filterRef = useRef<HTMLButtonElement>(null);
@@ -219,8 +224,13 @@ export function ServicesTreeView() {
</button>
</div>
) : (
<SplitGroup orientation="horizontal" className={styles.split} storageKey="openidea.services.detailSplit">
<SplitPanel id="services-items" defaultSize="40%" minSize="160px">
<SplitGroup
key={orientation}
orientation={orientation}
className={styles.split}
storageKey={sideDocked ? "openidea.services.detailSplit.vertical" : "openidea.services.detailSplit"}
>
<SplitPanel id="services-items" defaultSize="30%" minSize={sideDocked ? "80px" : "160px"}>
<div className={styles.tree}>
<Tree<ServiceTreeItem>
key={location}
@@ -274,7 +284,7 @@ export function ServicesTreeView() {
<SplitHandle />
<SplitPanel
id="services-detail"
minSize="200px"
minSize={sideDocked ? "120px" : "200px"}
// The panel library puts `overflow: auto` inline; the detail content
// (a console, a log) owns its scrolling, so the pane must not add a second
// bar. A column flex box lets that content fill the pane.
+1 -1
Переглянути файл
@@ -321,7 +321,7 @@ export function SettingsLayout() {
return (
<SplitGroup id="settings" orientation="horizontal" storageKey="openidea.settings.layout" className={styles.layout}>
<SplitPanel id="navigation" defaultSize="240px" minSize="160px" maxSize="40%" className={styles.sidebar}>
<SplitPanel id="navigation" defaultSize="22.5%" minSize="160px" maxSize="40%" className={styles.sidebar}>
<SearchField
data-autofocus
className={styles.search}
+42 -18
Переглянути файл
@@ -1,5 +1,5 @@
import { useId } from "react";
import { NumberInput, Row, Section } from "../components/Form";
import { NumberInput, Row, Section, Select, SettingToggle } from "../components/Form";
import { useSetting } from "../components/context";
/** Languages & Frameworks › Markdown, after IDEA's: application-level, preview font size follows the editor font until set. */
@@ -7,24 +7,48 @@ export function MarkdownPage() {
const id = useId();
const [size, setSize] = useSetting<number | null>("languages.markdown.previewFontSize");
const [editorSize] = useSetting<number>("editor.fontSize");
const [runCommands] = useSetting<boolean>("languages.markdown.runCommands");
const [directory, setDirectory] = useSetting<"project" | "file" | null>("languages.markdown.commandDirectory");
return (
<Section title="Preview">
<Row
label="Preview font size"
htmlFor={id}
hint="Also used by Markdown cells in Jupyter notebooks. Defaults to the editor font size, independent of the UI font size."
>
<NumberInput
id={id}
value={size ?? editorSize}
onChange={setSize}
min={8}
max={72}
integer
unit="px"
aria-label="Preview font size"
<>
<Section title="Preview">
<Row
label="Preview font size"
htmlFor={id}
hint="Also used by Markdown cells in Jupyter notebooks. Defaults to the editor font size, independent of the UI font size."
>
<NumberInput
id={id}
value={size ?? editorSize}
onChange={setSize}
min={8}
max={72}
integer
unit="px"
aria-label="Preview font size"
/>
</Row>
</Section>
<Section title="Commands">
<SettingToggle
k="languages.markdown.runCommands"
label="Detect commands that can be run right from Markdown files"
/>
</Row>
</Section>
<Row label="Run commands from" disabled={!runCommands}>
<Select<"project" | "file">
value={directory ?? ("" as "project")}
options={DIRECTORY_OPTIONS}
onChange={setDirectory}
disabled={!runCommands}
aria-label="Run commands from"
/>
</Row>
</Section>
</>
);
}
const DIRECTORY_OPTIONS = [
{ value: "project", label: "Project directory" },
{ value: "file", label: "Markdown file parent directory" },
] as const;
+1 -1
Переглянути файл
@@ -169,7 +169,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [
title: "Markdown",
group: LANGUAGES_GROUP,
order: 400,
keywords: ["markdown", "preview", "font size", "jupyter", "notebook"],
keywords: ["markdown", "preview", "font size", "jupyter", "notebook", "run commands", "code block"],
component: MarkdownPage,
},
{
+19
Переглянути файл
@@ -199,6 +199,25 @@ export function activate(): () => void {
focusActiveSoon();
},
},
{
id: "terminal.runLines",
title: "Run Lines in Terminal",
description: "Opens a shell tab and types `{ lines, name?, cwd? }` into it.",
category: "Terminal",
icon: "terminal",
when: "projectOpen",
hidden: true,
run: async ({ arg }) => {
const a = arg as { lines?: unknown; name?: unknown; cwd?: unknown } | undefined;
const lines = Array.isArray(a?.lines) ? a.lines.filter((x): x is string => typeof x === "string") : [];
const cwd = (typeof a?.cwd === "string" && a.cwd) || projectRoot();
if (!lines.length || !cwd) return;
const rt = await loadTerminalRuntime();
rt.newTabRunning(cwd, typeof a?.name === "string" && a.name ? a.name : undefined, lines);
toolWindowService().show(WINDOW, true);
focusActiveSoon();
},
},
{
id: "terminal.runCommand",
title: "Run Command in Terminal",
+1
Переглянути файл
@@ -6,6 +6,7 @@ export {
closeAll,
detachTab,
newTab,
newTabRunning,
pluginSession,
syncTerminalProject,
tabTitle,
+8
Переглянути файл
@@ -247,6 +247,14 @@ export function newTab(cwd: string, name?: string, command?: SessionOptions["com
return tab;
}
/** Opens a shell tab at `cwd` and types `lines` into it, each followed by Return. */
export function newTabRunning(cwd: string, name: string | undefined, lines: readonly string[]): TerminalTab {
const tab = newTab(cwd, name);
// Sent once the shell's PTY exists (the session buffers input until then).
getSession(tab.session)?.input(lines.map((line) => `${line}\r`).join(""));
return tab;
}
export function newTabAt(dir: string): TerminalTab {
return newTab(dir, basename(dir) || "Local");
}
+25 -10
Переглянути файл
@@ -26,6 +26,20 @@
gap: var(--space-0-5);
padding: 0 6px;
}
.changesToolbar {
height: auto;
min-height: 32px;
flex-wrap: wrap;
column-gap: var(--space-2);
padding-block: var(--space-0-5);
}
.changesTools {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
max-width: 100%;
}
.sep {
width: 1px;
height: 16px;
@@ -106,13 +120,12 @@
}
.commitBar {
flex: none;
height: 32px;
min-height: 32px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
padding: 0 6px 0 12px;
white-space: nowrap;
overflow: hidden;
gap: var(--space-0-5) var(--space-1);
padding: var(--space-0-5) 6px var(--space-0-5) 12px;
}
.grow {
flex: 1;
@@ -121,6 +134,7 @@
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: var(--fs-tiny);
white-space: nowrap;
}
.lineLenWarn {
color: var(--warning);
@@ -136,8 +150,6 @@
border-top: 1px solid var(--border);
outline: none;
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: var(--lh-code);
-webkit-user-select: text;
user-select: text;
@@ -164,7 +176,6 @@
display: flex;
align-items: center;
gap: var(--space-2);
/* A narrow panel moves Commit and Push… to its own row rather than cutting its label. */
flex-wrap: wrap;
padding: 8px 6px 10px 10px;
white-space: nowrap;
@@ -175,10 +186,14 @@
.commitActions > .pushButton {
flex: 0 1 auto;
min-width: 0;
min-height: var(--h-button, 28px);
height: auto;
padding: var(--space-1) var(--space-3);
line-height: 1.3;
}
.pushButton > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
overflow-wrap: anywhere;
}
.stashList {
flex: 1;
+82 -61
Переглянути файл
@@ -18,7 +18,9 @@ import {
import { tx, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, dirname } from "@/platform/project";
import { fontWeightOf } from "@/platform/editorSettings";
import { resolveMonoFont } from "@/platform/fonts";
import { basename, dirname, useProject } from "@/platform/project";
import { isTestFile, useEffectiveRoots } from "@/platform/projectRoots";
import {
Button,
@@ -763,68 +765,79 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
return (
<div className={styles.changes}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Changes")}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshNow()} />
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<IconButton
ref={viewRef}
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={() =>
viewRef.current &&
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
...(staging
? []
: [{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) }]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
{ label: "Show Diff Preview", checked: diffPreview, run: () => setDiffPreview(!diffPreview) },
]
: []),
// Not in the Commit dialog, whose files always open as source.
...(mode === "dialog" ? [] : doubleClickMenu(doubleClickOpensDiff)),
])
}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
<div className={clsx(styles.toolbar, styles.changesToolbar)} role="toolbar" aria-label={tx("Changes")}>
<div className={styles.changesTools}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshNow()} />
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<IconButton
icon="editor-preview"
title="Preview Diff"
ref={viewRef}
icon="eye"
title="View Options"
size="small"
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
aria-haspopup="menu"
onClick={() =>
viewRef.current &&
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
...(staging
? []
: [
{
label: "Staging State",
checked: groupByStaging,
run: () => setGroupByStaging(!groupByStaging),
},
]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
{ label: "Show Diff Preview", checked: diffPreview, run: () => setDiffPreview(!diffPreview) },
]
: []),
// Not in the Commit dialog, whose files always open as source.
...(mode === "dialog" ? [] : doubleClickMenu(doubleClickOpensDiff)),
])
}
/>
)}
<span className={styles.sep} />
{mode !== "dialog" && (
<IconButton icon="locate" title="Select Opened File" size="small" onClick={selectOpened} />
)}
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setCollapsed(new Set())} />
<IconButton
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() => setCollapsed(new Set([...byKey.values()].filter((n) => n.type !== "file").map((n) => n.key)))}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
<IconButton
icon="editor-preview"
title="Preview Diff"
size="small"
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
/>
)}
</div>
<div className={styles.changesTools}>
{mode !== "dialog" && (
<IconButton icon="locate" title="Select Opened File" size="small" onClick={selectOpened} />
)}
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setCollapsed(new Set())} />
<IconButton
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() =>
setCollapsed(new Set([...byKey.values()].filter((n) => n.type !== "file").map((n) => n.key)))
}
/>
</div>
</div>
{mode !== "dialog" && <OperationBanner />}
<div
@@ -1133,6 +1146,8 @@ export function CommitMessageField({
}
const cfg = useWorkflowSettings((s) => s.vcs.commit);
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const first = message.split("\n")[0] ?? "";
const tooLong = cfg.limitSubject && first.length > cfg.subjectLimit;
const problems = messageProblems(message, cfg).filter((p) => !p.startsWith("Subject line"));
@@ -1182,7 +1197,13 @@ export function CommitMessageField({
data-autofocus={autoFocus ? "" : undefined}
className={clsx(styles.message, !showMargin && styles.noMargin, emptyError && styles.messageError)}
aria-invalid={emptyError || undefined}
style={{ ["--guide" as string]: `${margin}ch` }}
style={{
["--guide" as string]: `${margin}ch`,
fontFamily: family,
fontSize: size,
fontWeight: fontWeightOf(editor?.fontWeight, 400),
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={message}
placeholder={tx("Commit Message")}
aria-label={tx("Commit message")}
+37 -4
Переглянути файл
@@ -14,6 +14,7 @@
min-height: 0;
}
.log {
container: git-log / inline-size;
height: 100%;
min-height: 0;
display: flex;
@@ -75,14 +76,32 @@
/* filters */
.filters {
gap: var(--space-1);
padding: 0 8px 0 6px;
height: auto;
min-height: 32px;
flex-wrap: wrap;
justify-content: flex-end;
gap: var(--space-0-5) var(--space-1);
padding: var(--space-0-5) 8px var(--space-0-5) 6px;
min-width: 0;
overflow: hidden;
}
.filterControls,
.filterActions {
display: flex;
align-items: center;
gap: var(--space-1);
}
.filterControls {
flex: 1 1 260px;
min-width: 0;
}
.filterActions {
flex-wrap: wrap;
justify-content: flex-end;
max-width: 100%;
}
.textFilter {
flex: 0 1 260px;
min-width: 100px;
min-width: min(100px, 60%);
}
.filterGroup {
position: relative;
@@ -96,6 +115,20 @@
.filterHidden {
visibility: hidden;
}
@container git-log (max-width: 320px) {
.filterControls,
.filterActions {
display: contents;
}
.textFilter {
flex: 1 0 100%;
}
/* Keep the filters measurable for the overflow menu. */
.filterGroup {
position: absolute;
width: 0;
}
}
.filterButton {
flex: none;
height: 24px;
+131 -128
Переглянути файл
@@ -293,55 +293,57 @@ export function FilterBar() {
return (
<div className={styles.filters} role="toolbar" aria-label={tx("Log filters")}>
{!showBranches && (
<IconButton icon="chevron-right" title="Show Branches" size="small" action="vcs.log.showBranches" />
)}
<SearchField
className={styles.textFilter}
value={text}
onChange={setText}
placeholder="Text or hash"
aria-label="Filter by message"
toggles={[
{
id: "regex",
icon: "regex",
title: "Regex",
pressed: filters.regex,
onToggle: (regex) => setLogFilters({ regex }),
},
{
id: "case",
icon: "case",
title: "Match Case",
pressed: filters.matchCase,
onToggle: (matchCase) => setLogFilters({ matchCase }),
},
]}
/>
<span ref={groupRef} className={styles.filterGroup}>
{logFilters.map((f, i) => (
<FilterButton key={f.label} {...f} hidden={i >= hiddenFrom} />
))}
</span>
{hiddenFrom < logFilters.length && (
<IconButton
icon="chevron-right"
title="More Filters"
size="small"
aria-haspopup="menu"
onClick={(e) => {
const anchor = e.currentTarget;
menuBelow(
anchor,
logFilters.slice(hiddenFrom).map((f) => ({
label: f.value ? `${tx(f.label)}: ${f.value}` : f.label,
run: () => f.onOpen(anchor),
})),
);
}}
<div className={styles.filterControls}>
{!showBranches && (
<IconButton icon="chevron-right" title="Show Branches" size="small" action="vcs.log.showBranches" />
)}
<SearchField
className={styles.textFilter}
value={text}
onChange={setText}
placeholder="Text or hash"
aria-label="Filter by message"
toggles={[
{
id: "regex",
icon: "regex",
title: "Regex",
pressed: filters.regex,
onToggle: (regex) => setLogFilters({ regex }),
},
{
id: "case",
icon: "case",
title: "Match Case",
pressed: filters.matchCase,
onToggle: (matchCase) => setLogFilters({ matchCase }),
},
]}
/>
)}
<span ref={groupRef} className={styles.filterGroup}>
{logFilters.map((f, i) => (
<FilterButton key={f.label} {...f} hidden={i >= hiddenFrom} />
))}
</span>
{hiddenFrom < logFilters.length && (
<IconButton
icon="chevron-right"
title="More Filters"
size="small"
aria-haspopup="menu"
onClick={(e) => {
const anchor = e.currentTarget;
menuBelow(
anchor,
logFilters.slice(hiddenFrom).map((f) => ({
label: f.value ? `${tx(f.label)}: ${f.value}` : f.label,
run: () => f.onOpen(anchor),
})),
);
}}
/>
)}
</div>
{dropdown}
{branchAnchor && (
<BranchFilterPopup
@@ -356,88 +358,89 @@ export function FilterBar() {
onSelectMany={() => void selectBranches()}
/>
)}
<span className={styles.grow} />
<IconButton
icon="bookmark"
title="Bookmarked Commits"
size="small"
disabled={!Object.keys(bookmarks).length}
onClick={(e) =>
menuBelow(
e,
Object.entries(bookmarks).map(([key, summary]) => ({
label: summary,
run: () => {
const split = key.lastIndexOf("\0");
void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined);
<div className={styles.filterActions}>
<IconButton
icon="bookmark"
title="Bookmarked Commits"
size="small"
disabled={!Object.keys(bookmarks).length}
onClick={(e) =>
menuBelow(
e,
Object.entries(bookmarks).map(([key, summary]) => ({
label: summary,
run: () => {
const split = key.lastIndexOf("\0");
void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined);
},
})),
)
}
/>
<IconButton
icon="plus"
title="Open Another Log Tab"
size="small"
onClick={(e) =>
menuBelow(e, [
{
label: "In Tool Window",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`);
},
},
})),
)
}
/>
<IconButton
icon="plus"
title="Open Another Log Tab"
size="small"
onClick={(e) =>
menuBelow(e, [
{
label: "In Tool Window",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`);
{
label: "In Editor",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor");
},
},
},
{
label: "In Editor",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor");
},
},
{ label: "External Repository…", run: openExternalLog },
])
}
/>
<IconButton
icon="clock"
title="Recent Filters"
size="small"
onClick={(e) =>
menuBelow(
e,
recentLogFilters().map((filters) => ({
label:
[
filters.range,
filters.branches.join(", "),
filters.authors.join(", "),
filters.text,
filters.path,
filters.paths?.join(", "),
filters.date?.label,
]
.filter(Boolean)
.join(" · ") || tx("All commits"),
run: () => setLogFilters(filters),
})),
)
}
/>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
<IconButton
icon="sort"
title="Graph Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, graphOptionsMenu(useLogOptions.getState()))}
/>
<IconButton
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, viewOptionsMenu(useLogOptions.getState()))}
/>
<IconButton icon="search" title="Go to Hash/Branch/Tag" size="small" action="vcs.log.goToRef" />
{ label: "External Repository…", run: openExternalLog },
])
}
/>
<IconButton
icon="clock"
title="Recent Filters"
size="small"
onClick={(e) =>
menuBelow(
e,
recentLogFilters().map((filters) => ({
label:
[
filters.range,
filters.branches.join(", "),
filters.authors.join(", "),
filters.text,
filters.path,
filters.paths?.join(", "),
filters.date?.label,
]
.filter(Boolean)
.join(" · ") || tx("All commits"),
run: () => setLogFilters(filters),
})),
)
}
/>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
<IconButton
icon="sort"
title="Graph Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, graphOptionsMenu(useLogOptions.getState()))}
/>
<IconButton
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, viewOptionsMenu(useLogOptions.getState()))}
/>
<IconButton icon="search" title="Go to Hash/Branch/Tag" size="small" action="vcs.log.goToRef" />
</div>
</div>
);
}
+25 -4
Переглянути файл
@@ -238,8 +238,14 @@ export interface LanguagesValid {
updateSnapshots: boolean;
};
};
/** Preview font size in px; `null` follows the editor font size. */
markdown: { previewFontSize: number | null };
markdown: {
/** Preview font size in px; `null` follows the editor font size. */
previewFontSize: number | null;
/** Run icons on shell code blocks and command lines. */
runCommands: boolean;
/** Where commands run; `null` asks when the project and the file's folder differ. */
commandDirectory: "project" | "file" | null;
};
}
export interface ProjectStructureValid {
@@ -329,7 +335,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
updateSnapshots: false,
},
},
markdown: { previewFontSize: null },
markdown: { previewFontSize: null, runCommands: true, commandDirectory: null },
};
export const DEFAULT_PROJECT_STRUCTURE: ProjectStructureValid = {
@@ -510,7 +516,14 @@ export function validateLanguages(raw: unknown): LanguagesValid {
updateSnapshots: bool(maven.updateSnapshots, d.java.maven.updateSnapshots),
},
},
markdown: { previewFontSize: previewSize(markdown.previewFontSize) },
markdown: {
previewFontSize: previewSize(markdown.previewFontSize),
runCommands: bool(markdown.runCommands, d.markdown.runCommands),
commandDirectory:
markdown.commandDirectory === "project" || markdown.commandDirectory === "file"
? markdown.commandDirectory
: null,
},
};
}
@@ -528,6 +541,14 @@ export function markdownPreviewFontSize(settings: unknown): number {
);
}
/** Languages & Frameworks › Markdown › Commands of `settings`. */
export function markdownCommandSettings(
settings: unknown,
): Pick<LanguagesValid["markdown"], "runCommands" | "commandDirectory"> {
const markdown = validateLanguages(obj(settings).languages).markdown;
return { runCommands: markdown.runCommands, commandDirectory: markdown.commandDirectory };
}
/** Reactive `markdownPreviewFontSize` of the open project. */
export function useMarkdownPreviewFontSize(): number {
return useProject((s) => markdownPreviewFontSize(s.settings));
+9 -1
Переглянути файл
@@ -2664,5 +2664,13 @@
"The agent's default": "The agent's default",
"Commit messages are short: a fast model with low effort is usually enough.": "Commit messages are short: a fast model with low effort is usually enough.",
"Change Project Color…": "Change Project Color…",
"Project Color": "Project Color"
"Project Color": "Project Color",
"Run Lines in Terminal": "Run Lines in Terminal",
"Opens a shell tab and types `{ lines, name?, cwd? }` into it.": "Opens a shell tab and types `{ lines, name?, cwd? }` into it.",
"Run in Terminal": "Run in Terminal",
"Run from Project Root Directory": "Run from Project Root Directory",
"Run from Parent Directory of Current File ({shown})": "Run from Parent Directory of Current File ({shown})",
"Detect commands that can be run right from Markdown files": "Detect commands that can be run right from Markdown files",
"Run commands from": "Run commands from",
"Markdown file parent directory": "Markdown file parent directory"
}
+9 -1
Переглянути файл
@@ -9039,5 +9039,13 @@
"The agent's default": "智能体的默认值",
"Commit messages are short: a fast model with low effort is usually enough.": "提交信息很短,通常用快速模型配低推理强度就够了。",
"Change Project Color…": "更改项目颜色…",
"Project Color": "项目颜色"
"Project Color": "项目颜色",
"Run Lines in Terminal": "在终端中运行多行命令",
"Opens a shell tab and types `{ lines, name?, cwd? }` into it.": "打开一个 Shell 终端标签页并输入 `{ lines, name?, cwd? }`。",
"Run in Terminal": "在终端中运行",
"Run from Project Root Directory": "从项目根目录运行",
"Run from Parent Directory of Current File ({shown})": "从当前文件的父目录运行({shown})",
"Detect commands that can be run right from Markdown files": "检测可以直接从 Markdown 文件运行的命令",
"Run commands from": "运行命令的目录",
"Markdown file parent directory": "Markdown 文件的父目录"
}
+13 -2
Переглянути файл
@@ -1817,6 +1817,11 @@ export interface RunAnythingProvider {
items(query: string): RunAnythingItem[];
/** Runs `line` when it belongs to this provider (`mvn clean`); false leaves it to the next one. */
execute?(line: string): boolean | Promise<boolean>;
/**
* Whether `execute` runs `line` as a command this provider recognizes (cheap,
* synchronous): Markdown offers run icons for such lines in code blocks.
*/
accepts?(line: string): boolean;
}
const runAnythingProviders = new Map<string, RunAnythingProvider>();
@@ -1883,9 +1888,15 @@ export function registerEndpointProvider(p: EndpointProvider): () => void {
};
}
export async function searchEndpoints(root: string | null): Promise<EndpointEntry[]> {
/** Endpoints of every provider, or of those `provider` accepts (by provider id). */
export async function searchEndpoints(
root: string | null,
provider: (id: string) => boolean = () => true,
): Promise<EndpointEntry[]> {
if (!root) return [];
const results = await Promise.allSettled([...endpointProviders.values()].map(async (p) => p.endpoints(root)));
const results = await Promise.allSettled(
[...endpointProviders.values()].filter((p) => provider(p.id)).map(async (p) => p.endpoints(root)),
);
return results.flatMap((result) => (result.status === "fulfilled" ? result.value : []));
}