mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
fix(editor): preview regex replacements at the match (#4967)
- Show the expanded replacement beneath the current match in file-level regex Replace when the result differs from the template. The preview uses the same replacement calculation as Replace Next. - Use a compact monospace balloon that preserves line breaks and stays within the editor width. It follows the selected match and leaves focus in the toolbar.
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("regex replacement previews the expanded result beside the selected match", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1200, height: 760 });
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.press("Meta+a");
|
||||
await page.keyboard.insertText("ledger:USD:104\nledger:EUR:82\nstatus:posted\n");
|
||||
await content.press("Meta+r");
|
||||
const bar = page.getByRole("search", { name: "Replace in file" });
|
||||
const find = bar.getByRole("textbox", { name: "Find" });
|
||||
const replace = bar.getByRole("textbox", { name: "Replace" });
|
||||
await bar.getByRole("button", { name: "Regex" }).click();
|
||||
await find.fill("ledger:([A-Z]{3}):(\\d+)");
|
||||
await replace.fill("$2 $1");
|
||||
|
||||
const preview = page.getByRole("tooltip", { name: "Replacement preview" });
|
||||
await expect(preview).toHaveText("104 USD");
|
||||
await expect(preview).toBeInViewport({ ratio: 1 });
|
||||
const current = editor.locator(".cm-openidea-findMatch-current").first();
|
||||
const match = (await current.boundingBox())!;
|
||||
const balloon = (await preview.boundingBox())!;
|
||||
expect(balloon.y).toBeGreaterThanOrEqual(match.y + match.height);
|
||||
expect(balloon.y - match.y - match.height).toBeLessThan(20);
|
||||
await expect(replace).toBeFocused();
|
||||
await expect(preview.locator("code")).toHaveCSS("font-size", "13px");
|
||||
|
||||
await page.setViewportSize({ width: 630, height: 510 });
|
||||
await replace.fill("$2 ".repeat(110) + "$1");
|
||||
await expect(preview).toContainText("104 104");
|
||||
await expect(preview).toBeInViewport({ ratio: 1 });
|
||||
const narrowPane = (await editor.boundingBox())!;
|
||||
const narrowBalloon = (await preview.boundingBox())!;
|
||||
expect(narrowBalloon.x + narrowBalloon.width).toBeLessThanOrEqual(narrowPane.x + narrowPane.width + 1);
|
||||
|
||||
await replace.fill("$2 $1");
|
||||
await find.press("Enter");
|
||||
await expect(preview).toHaveText("82 EUR");
|
||||
await expect(find).toBeFocused();
|
||||
await expect(content).toContainText("ledger:EUR:82");
|
||||
await replace.press("Enter");
|
||||
await expect(content).toContainText("82 EUR");
|
||||
await expect(content).not.toContainText("ledger:EUR:82");
|
||||
await expect(preview).toHaveText("104 USD");
|
||||
await find.press("Escape");
|
||||
await expect(preview).toHaveCount(0);
|
||||
await expect(bar).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
.preview:global(.cm-tooltip) {
|
||||
width: max-content;
|
||||
max-width: min(400px, var(--find-preview-width, 100vw), calc(100vw - 16px));
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border: 1px solid var(--border-popup);
|
||||
border-radius: var(--radius-popup);
|
||||
background: var(--bg-popup);
|
||||
color: var(--fg);
|
||||
box-shadow: var(--shadow-popup);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.preview :global(.cm-tooltip-arrow)::before {
|
||||
border-top-color: var(--border-popup);
|
||||
border-bottom-color: var(--border-popup);
|
||||
}
|
||||
|
||||
.preview :global(.cm-tooltip-arrow)::after {
|
||||
border-top-color: var(--bg-popup);
|
||||
border-bottom-color: var(--bg-popup);
|
||||
}
|
||||
|
||||
.code {
|
||||
display: -webkit-box;
|
||||
overflow: hidden;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
tab-size: 4;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 6;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, Prec } from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, Prec, StateEffect } from "@codemirror/state";
|
||||
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
|
||||
import { setSearchQuery } from "@codemirror/search";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
replaceNext,
|
||||
setFindScope,
|
||||
setFindOpen,
|
||||
setReplacePreview,
|
||||
type FindOptions,
|
||||
} from "./find";
|
||||
|
||||
@@ -171,6 +172,30 @@ describe("find in selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("replacement preview", () => {
|
||||
it("uses the scoped match, hides excluded matches, and respects the editor becoming read-only", () => {
|
||||
const line = "unposted:\n";
|
||||
const v = make(
|
||||
"posted:USD\n" + line,
|
||||
{ search: "posted:([A-Z]*)", regexp: true, replace: "$1" },
|
||||
{ from: 11, to: 11 + line.length },
|
||||
);
|
||||
const preview = () => v.dom.querySelector('[aria-label="Replacement preview"]')?.textContent;
|
||||
v.dispatch({ effects: [setFindOpen.of(true), setReplacePreview.of(false)] });
|
||||
findNext(v);
|
||||
expect(preview()).toBe("Empty replacement");
|
||||
|
||||
const { from, to } = v.state.selection.main;
|
||||
v.dispatch({ effects: toggleFindExcluded.of({ from, to }) });
|
||||
expect(preview()).toBeUndefined();
|
||||
v.dispatch({ effects: toggleFindExcluded.of({ from, to }) });
|
||||
expect(preview()).toBe("Empty replacement");
|
||||
|
||||
v.dispatch({ effects: StateEffect.appendConfig.of(EditorState.readOnly.of(true)) });
|
||||
expect(preview()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("plain-text queries", () => {
|
||||
it("match regex syntax and line breaks literally, case-insensitively", () => {
|
||||
const v = make("a.b(c)[d]$ x A.B(C)[D]$ axb\nend\n1 + 1 = 2", { search: "a.b(c)[d]$" });
|
||||
|
||||
@@ -19,7 +19,15 @@ import {
|
||||
type Extension,
|
||||
type SelectionRange,
|
||||
} from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
Decoration,
|
||||
EditorView,
|
||||
showTooltip,
|
||||
ViewPlugin,
|
||||
type DecorationSet,
|
||||
type Tooltip,
|
||||
type ViewUpdate,
|
||||
} from "@codemirror/view";
|
||||
import {
|
||||
SearchQuery,
|
||||
findNext as cmFindNext,
|
||||
@@ -30,12 +38,15 @@ import {
|
||||
setSearchQuery,
|
||||
} from "@codemirror/search";
|
||||
import { scrollbarMarks, type ScrollbarMark } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import type { LineMatch } from "@/platform/ipc";
|
||||
import { contextAccepts, preserveCase, type SearchContext } from "@/platform/search";
|
||||
import { literalKindAt, literalsExtension } from "./literals";
|
||||
import styles from "./FindPreview.module.css";
|
||||
|
||||
export const setFindOpen = StateEffect.define<boolean>();
|
||||
export const setFindMarks = StateEffect.define<number[]>();
|
||||
export const setReplacePreview = StateEffect.define<boolean | null>();
|
||||
|
||||
/** "In Selection": the range Find / Replace is limited to (IDEA's selection scope). */
|
||||
export interface FindScope {
|
||||
@@ -217,6 +228,7 @@ export function findExtension(): Extension {
|
||||
findScope,
|
||||
findExcluded,
|
||||
findMarks,
|
||||
replacePreview,
|
||||
literalsExtension,
|
||||
Prec.highest(findHighlighter),
|
||||
];
|
||||
@@ -381,6 +393,76 @@ function insertFor(state: EditorState, query: SearchQuery, m: Match, preserve: b
|
||||
return preserve ? preserveCase(state.sliceDoc(m.from, m.to), insert) : insert;
|
||||
}
|
||||
|
||||
function previewAtSelection(state: EditorState, preserve: boolean): Tooltip | null {
|
||||
const query = getSearchQuery(state);
|
||||
const { from, to } = state.selection.main;
|
||||
const scope = state.field(findScope, false);
|
||||
if (!query.valid || !query.regexp || state.readOnly || from === to) return null;
|
||||
if (scope && (from < scope.from || to > scope.to)) return null;
|
||||
|
||||
// Replace Next starts at the selection in the unscoped CodeMirror path. The
|
||||
// scoped and preserve-case paths use the non-overlapping matches in the scope.
|
||||
const start = scope?.from ?? (preserve ? 0 : from);
|
||||
const cursor = query.getCursor(state, start, scope?.to ?? state.doc.length);
|
||||
const deadline = performance.now() + 8;
|
||||
let scanned = 0;
|
||||
for (let next = cursor.next(); !next.done; next = cursor.next()) {
|
||||
const match = next.value as Match;
|
||||
if (match.from > from) return null;
|
||||
if (match.from === from && match.to === to) {
|
||||
const text = insertFor(state, query, match, preserve);
|
||||
return text !== query.replace ? replacementTooltip(from, text) : null;
|
||||
}
|
||||
if (++scanned % 128 === 0 && performance.now() > deadline) return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function replacementTooltip(pos: number, text: string): Tooltip {
|
||||
return {
|
||||
pos,
|
||||
arrow: true,
|
||||
create(view) {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = styles.preview!;
|
||||
dom.setAttribute("role", "tooltip");
|
||||
dom.setAttribute("aria-label", tx("Replacement preview"));
|
||||
const code = document.createElement("code");
|
||||
code.className = styles.code!;
|
||||
const clipped = Array.from(text.slice(0, 1000)).slice(0, 500).join("");
|
||||
code.textContent = !text ? tx("Empty replacement") : clipped.length < text.length ? `${clipped}…` : clipped;
|
||||
dom.append(code);
|
||||
const fit = () => dom.style.setProperty("--find-preview-width", `${view.dom.clientWidth}px`);
|
||||
fit();
|
||||
const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(fit);
|
||||
observer?.observe(view.dom);
|
||||
return { dom, destroy: () => observer?.disconnect() };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const replacePreview = StateField.define<{ preserve: boolean | null; tooltip: Tooltip | null }>({
|
||||
create: () => ({ preserve: null, tooltip: null }),
|
||||
update(value, tr) {
|
||||
let preserve = value.preserve;
|
||||
let refresh = tr.docChanged || !!tr.selection || tr.reconfigured;
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setReplacePreview)) {
|
||||
preserve = effect.value;
|
||||
refresh = true;
|
||||
} else if (effect.is(setFindOpen) && !effect.value) {
|
||||
preserve = null;
|
||||
refresh = true;
|
||||
} else if (effect.is(setSearchQuery) || effect.is(setFindScope) || effect.is(toggleFindExcluded)) {
|
||||
refresh = true;
|
||||
}
|
||||
}
|
||||
if (!refresh || (preserve === null && value.preserve === null)) return value;
|
||||
return { preserve, tooltip: preserve === null ? null : previewAtSelection(tr.state, preserve) };
|
||||
},
|
||||
provide: (field) => showTooltip.from(field, (value) => value.tooltip),
|
||||
});
|
||||
|
||||
/** Replaces the selected match (if it is one) and selects the next match. */
|
||||
export function replaceNext(view: EditorView, preserve = false): boolean {
|
||||
const { state } = view;
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
setFindOpen,
|
||||
setFindScope,
|
||||
setQuery,
|
||||
setReplacePreview,
|
||||
type FindOptions,
|
||||
type FindScope,
|
||||
} from "../cm/find";
|
||||
@@ -440,14 +441,16 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
shown.current = { target, version, opts, inChanges };
|
||||
const valid = !opts.regexp || regexValid(opts.search);
|
||||
setQuery(view, valid ? { ...opts, inChanges } : { ...opts, search: "" });
|
||||
view.dispatch({ effects: setFindOpen.of(true) });
|
||||
view.dispatch({
|
||||
effects: [setFindOpen.of(true), setReplacePreview.of(replace && opts.regexp ? !!opts.preserveCase : null)],
|
||||
});
|
||||
if (changed && valid && opts.search && useFindPreferences.getState().scrollToResults) {
|
||||
const from = view.state.selection.main.from;
|
||||
view.dispatch({ selection: { anchor: from } });
|
||||
findNext(view);
|
||||
}
|
||||
recount(target);
|
||||
}, [opts, target, version, inChanges]);
|
||||
}, [opts, target, version, inChanges, replace]);
|
||||
|
||||
// Keep the counter current while the document / selection changes.
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
{
|
||||
"At breakpoint": "At breakpoint",
|
||||
"Replacement preview": "Replacement preview",
|
||||
"Empty replacement": "Empty replacement",
|
||||
"Build and Run": "Build and Run",
|
||||
"Gradle runtime": "Gradle runtime",
|
||||
"Open diff as editor tab": "Open diff as editor tab",
|
||||
|
||||
@@ -2576,6 +2576,8 @@
|
||||
"Replace template": "替换模板",
|
||||
"Replace this occurrence only": "仅替换此匹配项",
|
||||
"Replace with": "替换为",
|
||||
"Replacement preview": "替换预览",
|
||||
"Empty replacement": "替换为空",
|
||||
"Replacements": "替换项",
|
||||
"Reports errors and warnings from language servers.": "报告来自语言服务器的错误和警告。",
|
||||
"Repository": "仓库",
|
||||
|
||||
Reference in New Issue
Block a user