M2.4: Find tool window in a new bottom panel
- Bottom panel under editor and project tree (resizable, collapsible,
closable) for Find and later tool windows.
- Find store: search.find with options and include/exclude globs, results
streamed and sorted by file, events held until the searchId answer, a
new search cancels the running one, refused queries shown in place.
- Find tool window: toggles, counts, cancel, truncated hint, highlighted
previews, keyboard navigation, Enter or click runs editor.reveal.
- UI command find.open (Mod+Alt+F) with prefill from the selection or the
word at the cursor; find.open {query} from agents searches at once.
- 26 Vitest tests; progress docs and architecture updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
864a468b34
commit
097bbd9409
16 changed files with 1923 additions and 25 deletions
469
ui/src/stores/find.ts
Normal file
469
ui/src/stores/find.ts
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
/**
|
||||
* The Find tool window's state (M2.4): the query and its options, the
|
||||
* running search and its results, grouped by file.
|
||||
*
|
||||
* - **Searching:** {@link useFindStore}'s `search` runs `search.find` and
|
||||
* keeps the returned `searchId`. Results arrive as `searchResults` events
|
||||
* (one per file, in no fixed order; the store keeps files sorted by path)
|
||||
* and end with `searchDone`. Events of other searches are ignored. Events
|
||||
* that arrive while `search.find` has not answered yet are held and
|
||||
* replayed once the id is known, because events and command results
|
||||
* travel on different channels.
|
||||
* - **One search at a time:** a new search cancels the running one
|
||||
* (`search.cancel`); the engine does not do that by itself.
|
||||
* - **Errors:** a refused search (`invalid_params` for a bad regex or glob)
|
||||
* shows its message in the window, not as a toast.
|
||||
* - **Opening:** `open` shows the panel, takes the query from the params
|
||||
* (an agent's `find.open {query}` searches at once) or from the editor
|
||||
* (selection or word at the cursor) and asks the window to focus its field.
|
||||
* - **Untrusted input:** event fields are checked; malformed matches are
|
||||
* dropped.
|
||||
*/
|
||||
import type { EditorState } from "@codemirror/state";
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import { t } from "../i18n";
|
||||
import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../ipc";
|
||||
import { useEditorStore } from "./editor";
|
||||
|
||||
/** One match as the window shows it. */
|
||||
export interface FindMatch {
|
||||
/** 0-based line. */
|
||||
line: number;
|
||||
/** 0-based column in UTF-16 code units. */
|
||||
column: number;
|
||||
/** Length of the match in UTF-16 code units, at least 1. */
|
||||
length: number;
|
||||
/** The line, or a window of it around the match. */
|
||||
preview: string;
|
||||
/** Start of the match inside {@link FindMatch.preview}. */
|
||||
previewColumn: number;
|
||||
}
|
||||
|
||||
/** The matches of one file. */
|
||||
export interface FindFile {
|
||||
/** Project-relative path. */
|
||||
path: string;
|
||||
/** Matches in line order. */
|
||||
matches: FindMatch[];
|
||||
}
|
||||
|
||||
/** Totals of a finished search, from `searchDone`. */
|
||||
export interface FindSummary {
|
||||
/** Files with matches. */
|
||||
files: number;
|
||||
/** Matches. */
|
||||
matches: number;
|
||||
/** Whether the match cap left matches out. */
|
||||
truncated: boolean;
|
||||
/** Whether the search was cancelled. */
|
||||
cancelled: boolean;
|
||||
/** Wall time in milliseconds. */
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
/** A match in the flat result order, for keyboard navigation. */
|
||||
export interface FindRow {
|
||||
/** Stable key: path and match index. */
|
||||
key: string;
|
||||
/** Path of the file. */
|
||||
path: string;
|
||||
/** The match. */
|
||||
match: FindMatch;
|
||||
}
|
||||
|
||||
/** Longest query taken from the editor selection, in UTF-16 code units. */
|
||||
export const MAX_PREFILL = 1000;
|
||||
|
||||
/** Most events held while `search.find` has not answered. */
|
||||
const MAX_EARLY_EVENTS = 5000;
|
||||
|
||||
/**
|
||||
* The query `find.open` takes from an editor: the main selection if it is
|
||||
* not empty and has no line break, else the word at the cursor.
|
||||
*
|
||||
* @param state - the active editor state, if any.
|
||||
* @returns the text, or null when there is nothing to take.
|
||||
*/
|
||||
export function prefillFrom(state: EditorState | undefined): string | null {
|
||||
if (!state) {
|
||||
return null;
|
||||
}
|
||||
const { from, to, head } = state.selection.main;
|
||||
if (from !== to && to - from <= MAX_PREFILL) {
|
||||
const text = state.sliceDoc(from, to);
|
||||
if (!/[\r\n]/.test(text) && text.trim() !== "") {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
const word = state.wordAt(head);
|
||||
return word ? state.sliceDoc(word.from, word.to) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a comma-separated list of globs.
|
||||
*
|
||||
* @param text - what the user typed, for example `*.php, src/**`.
|
||||
*/
|
||||
export function splitGlobs(text: string): string[] {
|
||||
return text
|
||||
.split(",")
|
||||
.map((glob) => glob.trim())
|
||||
.filter((glob) => glob !== "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a non-negative integer field.
|
||||
*
|
||||
* @param value - an untrusted field.
|
||||
*/
|
||||
function count(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the matches of a `searchResults` event, dropping malformed ones and
|
||||
* clamping the highlight into the preview.
|
||||
*
|
||||
* @param raw - the untrusted `matches` field.
|
||||
*/
|
||||
export function toMatches(raw: unknown): FindMatch[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
const out: FindMatch[] = [];
|
||||
for (const item of raw as unknown[]) {
|
||||
if (typeof item !== "object" || item === null) {
|
||||
continue;
|
||||
}
|
||||
const m = item as Record<string, unknown>;
|
||||
const line = count(m.line);
|
||||
const column = count(m.column);
|
||||
const length = count(m.length);
|
||||
const previewColumn = count(m.previewColumn);
|
||||
if (line === null || column === null || length === null || previewColumn === null || typeof m.preview !== "string") {
|
||||
continue;
|
||||
}
|
||||
const start = Math.min(previewColumn, m.preview.length);
|
||||
out.push({ line, column, length: Math.max(1, length), preview: m.preview, previewColumn: start });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index at which a path belongs in a list sorted by path.
|
||||
*
|
||||
* @param files - files sorted by path.
|
||||
* @param path - the path to place.
|
||||
*/
|
||||
function insertionIndex(files: readonly FindFile[], path: string): number {
|
||||
let low = 0;
|
||||
let high = files.length;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
const other = files[mid]?.path ?? "";
|
||||
if (other < path) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/** Store of the Find tool window. */
|
||||
export const useFindStore = defineStore("find", () => {
|
||||
const editor = useEditorStore();
|
||||
/** Whether the panel exists in the layout (after the first `find.open`). */
|
||||
const visible = ref(false);
|
||||
/** Whether the panel is expanded (false: collapsed to its header). */
|
||||
const expanded = ref(true);
|
||||
/** The query text. */
|
||||
const query = ref("");
|
||||
/** Whether the query is a regular expression. */
|
||||
const regex = ref(false);
|
||||
/** Whether case matters. */
|
||||
const caseSensitive = ref(false);
|
||||
/** Whether only whole words match. */
|
||||
const wholeWord = ref(false);
|
||||
/** Include globs, comma-separated. */
|
||||
const include = ref("");
|
||||
/** Exclude globs, comma-separated. */
|
||||
const exclude = ref("");
|
||||
/** Id of the current search, null before the engine answered. */
|
||||
const searchId = ref<number | null>(null);
|
||||
/** Whether a search is running. */
|
||||
const running = ref(false);
|
||||
/** Files with matches, sorted by path; replaced on every change. */
|
||||
const files = shallowRef<FindFile[]>([]);
|
||||
/** Totals once the search ended. */
|
||||
const summary = ref<FindSummary | null>(null);
|
||||
/** Message of a refused search or cancel, shown in the window. */
|
||||
const error = ref<string | null>(null);
|
||||
/** Key of the selected row, see {@link FindRow}. */
|
||||
const selectedKey = ref<string | null>(null);
|
||||
/** Bumped when the window should focus and select its query field. */
|
||||
const focusRequest = ref(0);
|
||||
/** Counter of searches started, so a late answer of an older one is dropped. */
|
||||
let generation = 0;
|
||||
/** Whether `search.find` was sent and has not answered. */
|
||||
let awaitingId = false;
|
||||
/** Search events that arrived while {@link awaitingId}. */
|
||||
let early: EngineEventPayload[] = [];
|
||||
/** Ends the event subscription; set while started. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** Every match in display order. */
|
||||
const rows = computed<FindRow[]>(() =>
|
||||
files.value.flatMap((file) =>
|
||||
file.matches.map((match, i) => ({ key: `${file.path}\u0000${String(i)}`, path: file.path, match })),
|
||||
),
|
||||
);
|
||||
|
||||
/** Matches received so far. */
|
||||
const matchCount = computed(() => rows.value.length);
|
||||
|
||||
/** Index of the selected row in {@link rows}, -1 if none. */
|
||||
const selectedIndex = computed(() => rows.value.findIndex((row) => row.key === selectedKey.value));
|
||||
|
||||
/** Drops the results of the previous search. */
|
||||
function clearResults(): void {
|
||||
files.value = [];
|
||||
summary.value = null;
|
||||
selectedKey.value = null;
|
||||
error.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one file's matches.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @param matches - its matches.
|
||||
*/
|
||||
function addFile(path: string, matches: FindMatch[]): void {
|
||||
if (matches.length === 0) {
|
||||
return;
|
||||
}
|
||||
const next = [...files.value];
|
||||
const at = insertionIndex(next, path);
|
||||
const same = next[at];
|
||||
if (same?.path === path) {
|
||||
next[at] = { path, matches: [...same.matches, ...matches] };
|
||||
} else {
|
||||
next.splice(at, 0, { path, matches });
|
||||
}
|
||||
files.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a search event of the current search.
|
||||
*
|
||||
* @param event - a `searchResults` or `searchDone` event.
|
||||
*/
|
||||
function apply(event: EngineEventPayload): void {
|
||||
if (event.kind === "searchResults") {
|
||||
if (typeof event.path === "string" && event.path !== "") {
|
||||
addFile(event.path, toMatches(event.matches));
|
||||
}
|
||||
} else if (event.kind === "searchDone") {
|
||||
running.value = false;
|
||||
summary.value = {
|
||||
files: count(event.files) ?? files.value.length,
|
||||
matches: count(event.matches) ?? matchCount.value,
|
||||
truncated: event.truncated === true,
|
||||
cancelled: event.cancelled === true,
|
||||
elapsedMs: count(event.elapsedMs) ?? 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an engine event.
|
||||
*
|
||||
* @param event - the engine event.
|
||||
*/
|
||||
function onEvent(event: EngineEventPayload): void {
|
||||
if (event.kind === "searchResults" || event.kind === "searchDone") {
|
||||
if (searchId.value !== null && event.searchId === searchId.value) {
|
||||
apply(event);
|
||||
} else if (awaitingId && early.length < MAX_EARLY_EVENTS) {
|
||||
early.push(event);
|
||||
}
|
||||
} else if (event.kind === "projectClosed" || event.kind === "projectOpened") {
|
||||
generation += 1;
|
||||
awaitingId = false;
|
||||
early = [];
|
||||
searchId.value = null;
|
||||
running.value = false;
|
||||
clearResults();
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks the engine to stop the running search; its `searchDone` follows. */
|
||||
async function cancel(): Promise<void> {
|
||||
const id = searchId.value;
|
||||
if (!running.value || id === null) {
|
||||
return;
|
||||
}
|
||||
const result = await run("search.cancel", { searchId: id });
|
||||
if (!result.ok) {
|
||||
error.value = result.error.message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a search for the current query and options, cancelling the
|
||||
* running one. An empty query only clears the results.
|
||||
*/
|
||||
async function search(): Promise<void> {
|
||||
void cancel();
|
||||
generation += 1;
|
||||
const mine = generation;
|
||||
clearResults();
|
||||
searchId.value = null;
|
||||
running.value = false;
|
||||
early = [];
|
||||
if (query.value === "") {
|
||||
awaitingId = false;
|
||||
return;
|
||||
}
|
||||
running.value = true;
|
||||
awaitingId = true;
|
||||
const params: JsonValue = {
|
||||
query: query.value,
|
||||
regex: regex.value,
|
||||
caseSensitive: caseSensitive.value,
|
||||
wholeWord: wholeWord.value,
|
||||
include: splitGlobs(include.value),
|
||||
exclude: splitGlobs(exclude.value),
|
||||
};
|
||||
const result = await run<unknown>("search.find", params);
|
||||
const answer = result.ok && typeof result.value === "object" && result.value !== null ? (result.value as Record<string, unknown>) : null;
|
||||
const id = answer ? count(answer.searchId) : null;
|
||||
if (mine !== generation) {
|
||||
if (id !== null) {
|
||||
void run("search.cancel", { searchId: id });
|
||||
}
|
||||
return;
|
||||
}
|
||||
awaitingId = false;
|
||||
const held = early;
|
||||
early = [];
|
||||
if (!result.ok) {
|
||||
running.value = false;
|
||||
error.value = result.error.message;
|
||||
return;
|
||||
}
|
||||
if (id === null) {
|
||||
running.value = false;
|
||||
error.value = t("common.error.unexpectedResult", { command: "search.find" });
|
||||
return;
|
||||
}
|
||||
searchId.value = id;
|
||||
for (const event of held) {
|
||||
if ("searchId" in event && event.searchId === id) {
|
||||
apply(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the panel and focuses its query field: the UI command
|
||||
* `find.open`. With a string `query` param (agents) it takes that query
|
||||
* and searches at once; otherwise it takes the editor's selection or the
|
||||
* word at the cursor, if any, and waits for Enter.
|
||||
*
|
||||
* @param params - the command params; untrusted.
|
||||
*/
|
||||
async function open(params: unknown = {}): Promise<void> {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
visible.value = true;
|
||||
expanded.value = true;
|
||||
focusRequest.value += 1;
|
||||
if (typeof p.query === "string") {
|
||||
query.value = p.query;
|
||||
if (typeof p.regex === "boolean") regex.value = p.regex;
|
||||
if (typeof p.caseSensitive === "boolean") caseSensitive.value = p.caseSensitive;
|
||||
if (typeof p.wholeWord === "boolean") wholeWord.value = p.wholeWord;
|
||||
if (typeof p.include === "string") include.value = p.include;
|
||||
if (typeof p.exclude === "string") exclude.value = p.exclude;
|
||||
await search();
|
||||
return;
|
||||
}
|
||||
const id = editor.activeId;
|
||||
const prefill = prefillFrom(id === null ? undefined : editor.syncOf(id)?.state);
|
||||
if (prefill !== null && prefill !== query.value) {
|
||||
query.value = prefill;
|
||||
error.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hides the panel; the results stay for the next `find.open`. */
|
||||
function hide(): void {
|
||||
visible.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the selection through the rows.
|
||||
*
|
||||
* @param delta - rows to move; clamped at both ends.
|
||||
*/
|
||||
function move(delta: number): void {
|
||||
const list = rows.value;
|
||||
if (list.length === 0) {
|
||||
return;
|
||||
}
|
||||
const from = selectedIndex.value;
|
||||
const to = from < 0 ? (delta > 0 ? 0 : list.length - 1) : Math.min(list.length - 1, Math.max(0, from + delta));
|
||||
selectedKey.value = list[to]?.key ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a row.
|
||||
*
|
||||
* @param key - its key, see {@link FindRow}.
|
||||
*/
|
||||
function select(key: string): void {
|
||||
selectedKey.value = key;
|
||||
}
|
||||
|
||||
/** Starts listening to search events. Starting twice is a no-op. */
|
||||
function start(): void {
|
||||
unsubscribe ??= onEngineEvent(onEvent);
|
||||
}
|
||||
|
||||
/** Stops listening. */
|
||||
function stop(): void {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}
|
||||
|
||||
return {
|
||||
visible,
|
||||
expanded,
|
||||
query,
|
||||
regex,
|
||||
caseSensitive,
|
||||
wholeWord,
|
||||
include,
|
||||
exclude,
|
||||
searchId,
|
||||
running,
|
||||
files,
|
||||
summary,
|
||||
error,
|
||||
selectedKey,
|
||||
focusRequest,
|
||||
rows,
|
||||
matchCount,
|
||||
selectedIndex,
|
||||
search,
|
||||
cancel,
|
||||
open,
|
||||
hide,
|
||||
move,
|
||||
select,
|
||||
start,
|
||||
stop,
|
||||
};
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue