M2.6: go-to popup for files, classes and symbols

One popup with Files / Classes / Symbols tabs (Tab switches), opened by
goto.fileOpen (Mod+P), goto.classOpen (Mod+Alt+C) and goto.symbolOpen
(Mod+T), each with an optional {query} for agents. Live debounced query
against goto.* with stale answers dropped, matched characters marked,
directory / namespace / container column, library rows labelled, an
indexing hint with progress and a re-query on indexReady. Enter or a
click opens through editor.reveal; Escape closes. An exclusive modal and
a launcher: any other command closes it.

goto.file items now carry `library` (PM decision). indexProgress and
indexReady join the ipc event union. Notes in plan/phpstorm/08-goto.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-17 17:03:06 +02:00
parent ef198f5f8f
commit 943ff889df
21 changed files with 1650 additions and 23 deletions

470
ui/src/stores/goto.ts Normal file
View file

@ -0,0 +1,470 @@
/**
* The go-to popup's state (M2.6): the mode (file, class, symbol), the query
* and the items the engine's `goto.*` commands returned for it.
*
* - **Live query:** {@link useGotoStore}'s `setQuery` waits
* {@link DEBOUNCE_MS} after the last keystroke and then runs the mode's
* `goto.*` command. Every query gets a sequence number; an answer that is
* not the newest one is dropped, so a slow answer never overwrites a
* newer list.
* - **Indexing:** while the engine reports `indexing: true` the popup shows
* a hint with the `indexProgress` count; `indexReady` re-runs the open
* query so the partial list fills up.
* - **Untrusted input:** answers and events come from the engine; items
* with missing or malformed fields are dropped and ranges are clamped to
* the text they mark.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { onEngineEvent, run } from "../ipc";
/** The popup's modes, in tab order. */
export const GOTO_MODES = ["file", "class", "symbol"] as const;
/** A popup mode. */
export type GotoMode = (typeof GOTO_MODES)[number];
/** Wait after the last keystroke before querying, in milliseconds. */
export const DEBOUNCE_MS = 60;
/** Items asked for per query. */
export const GOTO_LIMIT = 100;
/** Longest query sent, in UTF-16 code units. */
export const MAX_QUERY = 500;
/** One row of the popup. */
export interface GotoItem {
/** Stable key within one answer. */
key: string;
/** What the row shows first: the file name, or the symbol name. */
label: string;
/** Marked `[start, end)` ranges in {@link GotoItem.label}, UTF-16. */
labelMatches: [number, number][];
/** The second column: the directory, the namespace or the container. */
detail: string;
/** Marked ranges in {@link GotoItem.detail}. */
detailMatches: [number, number][];
/** Symbol kind (`class`, `method`…); null for files. */
kind: string | null;
/** Library code (below `vendor/`). */
library: boolean;
/** Project-relative path to open. */
path: string;
/** 0-based line to reveal; null keeps the file's cursor. */
line: number | null;
/** 0-based UTF-16 column to reveal. */
column: number | null;
}
/** Engine command each mode queries. */
const COMMAND: Record<GotoMode, string> = {
file: "goto.file",
class: "goto.class",
symbol: "goto.symbol",
};
/**
* Reads an object field as a non-empty string.
*
* @param value - an untrusted field.
*/
function text(value: unknown): string | null {
return typeof value === "string" && value !== "" ? value : null;
}
/**
* 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 file item: `[[start, end], ...]`, sorted, inside
* a text of `length` code units. Malformed pairs are dropped.
*
* @param value - an untrusted field.
* @param length - length of the matched text.
*/
export function readRanges(value: unknown, length: number): [number, number][] {
if (!Array.isArray(value)) {
return [];
}
const ranges: [number, number][] = [];
for (const pair of value as unknown[]) {
if (!Array.isArray(pair) || pair.length !== 2) {
continue;
}
const start = count(pair[0]);
const end = count(pair[1]);
if (start === null || end === null) {
continue;
}
const from = Math.min(start, length);
const to = Math.min(end, length);
if (to > from) {
ranges.push([from, to]);
}
}
return ranges.sort((a, b) => a[0] - b[0]);
}
/**
* Splits path ranges at the file name: the part in the name and the part
* in the directory, each relative to its own text.
*
* @param ranges - ranges in the whole path.
* @param split - where the file name starts in the path.
*/
function splitRanges(ranges: [number, number][], split: number): { dir: [number, number][]; name: [number, number][] } {
const dir: [number, number][] = [];
const name: [number, number][] = [];
for (const [start, end] of ranges) {
if (start < split) {
dir.push([start, Math.min(end, split)]);
}
if (end > split) {
name.push([Math.max(start, split) - split, end - split]);
}
}
return { dir, name };
}
/**
* Marks where the characters of `query` occur in `label`, in order and
* ignoring case, as the symbol answers carry no ranges. Query characters
* that do not occur are skipped; whitespace, `\`, `:` and `$` are ignored.
*
* @param label - the shown name.
* @param query - what the user typed.
* @returns merged `[start, end)` ranges in `label`.
*/
export function markSubsequence(label: string, query: string): [number, number][] {
const lower = label.toLowerCase();
const ranges: [number, number][] = [];
let at = 0;
for (const c of query.toLowerCase()) {
if (/[\s\\:$]/.test(c)) {
continue;
}
const found = lower.indexOf(c, at);
if (found < 0) {
continue;
}
const last = ranges[ranges.length - 1];
if (last && last[1] === found) {
last[1] = found + c.length;
} else {
ranges.push([found, found + c.length]);
}
at = found + c.length;
}
return ranges;
}
/**
* The part of a query that names a member: after `::` when present.
*
* @param query - what the user typed.
*/
function memberQuery(query: string): string {
const at = query.lastIndexOf("::");
return at >= 0 ? query.slice(at + 2) : query;
}
/**
* Turns one `goto.file` item into a row.
*
* @param value - the untrusted item.
* @param index - its position, for the key.
*/
export function fileItem(value: unknown, index: number): GotoItem | null {
if (typeof value !== "object" || value === null) {
return null;
}
const raw = value as Record<string, unknown>;
const path = text(raw.path);
if (path === null) {
return null;
}
const split = path.lastIndexOf("/") + 1;
const { dir, name } = splitRanges(readRanges(raw.matches, path.length), split);
return {
key: `${String(index)}:${path}`,
label: path.slice(split),
labelMatches: name,
detail: path.slice(0, split),
detailMatches: dir,
kind: null,
library: raw.library === true || path.startsWith("vendor/"),
path,
line: null,
column: null,
};
}
/**
* Turns one `goto.class` or `goto.symbol` item into a row.
*
* @param value - the untrusted item.
* @param index - its position, for the key.
* @param query - the query it answered, for the marks.
*/
export function symbolItem(value: unknown, index: number, query: string): GotoItem | null {
if (typeof value !== "object" || value === null) {
return null;
}
const raw = value as Record<string, unknown>;
const name = text(raw.name);
const path = text(raw.path);
if (name === null || path === null) {
return null;
}
const fqn = text(raw.fqn) ?? name;
const container = text(raw.container);
const namespace = fqn.endsWith(name) ? fqn.slice(0, fqn.length - name.length).replace(/\\$/, "") : fqn;
const detail = container ?? namespace;
return {
key: `${String(index)}:${fqn}:${path}`,
label: name,
labelMatches: markSubsequence(name, memberQuery(query)),
detail,
detailMatches: [],
kind: text(raw.kind),
library: raw.library === true,
path,
line: count(raw.line),
column: count(raw.column),
};
}
/** Store of the go-to popup. */
export const useGotoStore = defineStore("goto", () => {
/** Whether the popup is shown. */
const open = ref(false);
/** The mode. */
const mode = ref<GotoMode>("file");
/** What the user typed. */
const query = ref("");
/** The rows of the newest answer. */
const items = ref<GotoItem[]>([]);
/** Index of the selected row. */
const selected = ref(0);
/** Whether the newest answer said the index is still building. */
const indexing = ref(false);
/** The latest `indexProgress`, or null. */
const progress = ref<{ done: number; total: number } | null>(null);
/** Message of a refused query, or null. */
const error = ref<string | null>(null);
/** Whether a query is waiting or running. */
const busy = ref(false);
/** Bumped when the popup should focus its field. */
const focusRequest = ref(0);
/** Sequence number of the newest query. */
let sequence = 0;
/** The pending debounce timer. */
let timer: ReturnType<typeof setTimeout> | null = null;
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** The selected row, if any. */
const current = computed<GotoItem | undefined>(() => items.value[selected.value]);
/** Cancels a pending debounce. */
function cancelTimer(): void {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
/**
* Runs the mode's query now; an older answer arriving later is dropped.
*
* @returns once the answer is applied or dropped.
*/
async function search(): Promise<void> {
cancelTimer();
const mine = ++sequence;
const asked = query.value.slice(0, MAX_QUERY);
const askedMode = mode.value;
if (asked.trim() === "") {
items.value = [];
selected.value = 0;
error.value = null;
busy.value = false;
return;
}
busy.value = true;
const result = await run<unknown>(COMMAND[askedMode], { query: asked, limit: GOTO_LIMIT });
if (mine !== sequence) {
return;
}
busy.value = false;
if (!result.ok) {
items.value = [];
error.value = result.error.message;
return;
}
const answer = (typeof result.value === "object" && result.value !== null ? result.value : {}) as Record<
string,
unknown
>;
const raw = Array.isArray(answer.items) ? (answer.items as unknown[]) : [];
const rows = raw.map((item, i) => (askedMode === "file" ? fileItem(item, i) : symbolItem(item, i, asked)));
items.value = rows.filter((row): row is GotoItem => row !== null);
indexing.value = answer.indexing === true;
error.value = null;
if (selected.value >= items.value.length) {
selected.value = 0;
}
}
/** Queries after {@link DEBOUNCE_MS}, replacing a pending wait. */
function schedule(): void {
cancelTimer();
sequence++;
busy.value = true;
timer = setTimeout(() => {
timer = null;
void search();
}, DEBOUNCE_MS);
}
/**
* Sets the query and queries after the debounce.
*
* @param value - what the field holds now.
*/
function setQuery(value: string): void {
query.value = value;
selected.value = 0;
schedule();
}
/**
* Switches the mode and queries the same text in it at once.
*
* @param next - the mode.
*/
function setMode(next: GotoMode): void {
if (mode.value === next) {
return;
}
mode.value = next;
selected.value = 0;
items.value = [];
void search();
}
/**
* Moves to the next or previous mode, wrapping around.
*
* @param step - 1 for the next, -1 for the previous.
*/
function cycleMode(step: number): void {
const at = GOTO_MODES.indexOf(mode.value);
const next = GOTO_MODES[(at + step + GOTO_MODES.length) % GOTO_MODES.length] ?? "file";
setMode(next);
}
/**
* Shows the popup in `next` mode. A given query replaces the field and is
* queried at once; without one the previous text stays.
*
* @param next - the mode.
* @param initial - a query from the params, if any.
*/
async function show(next: GotoMode, initial?: string): Promise<void> {
const changed = mode.value !== next;
mode.value = next;
open.value = true;
focusRequest.value++;
if (initial !== undefined) {
query.value = initial;
}
if (changed || initial !== undefined) {
selected.value = 0;
items.value = [];
}
await search();
}
/** Hides the popup and drops any answer still on its way. */
function hide(): void {
cancelTimer();
sequence++;
busy.value = false;
open.value = false;
}
/**
* Moves the selection, wrapping around.
*
* @param step - rows to move, negative for up.
*/
function move(step: number): void {
const total = items.value.length;
if (total === 0) {
return;
}
selected.value = (selected.value + step + total) % total;
}
/** Subscribes to `indexProgress` and `indexReady`; idempotent. */
function start(): void {
if (unsubscribe) {
return;
}
unsubscribe = onEngineEvent((event) => {
if (event.kind === "indexProgress") {
const done = count(event.done);
const total = count(event.total);
if (done !== null && total !== null) {
progress.value = { done, total };
}
} else if (event.kind === "indexReady") {
progress.value = null;
if (open.value && indexing.value) {
void search();
} else {
indexing.value = false;
}
}
});
}
/** Ends the subscription and any pending query. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
cancelTimer();
}
return {
open,
mode,
query,
items,
selected,
indexing,
progress,
error,
busy,
focusRequest,
current,
search,
setQuery,
setMode,
cycleMode,
show,
hide,
move,
start,
stop,
};
});