M3.5: go to definition, find references and rename through Phpactor

Engine (`cmd/lsp_nav.rs`, on the pending outcomes of 20d1d28):
- `lsp.definition` (F12) and `lsp.references` (Shift+F12, sorted, with
  line previews) return project-relative locations; locations outside
  the project, such as PHAR stubs and symlink escapes, are dropped.
- `lsp.prepareRename` uses the word at the cursor when the server has
  no prepareProvider.
- `lsp.rename` (F2) applies the workspace edit (`lsp_nav/edit.rs`):
  1. Check everything first: inside the project, ranges fit (UTF-16,
     CRLF), open buffers unchanged since the request, no file
     operations, no incomplete edit.
  2. Write closed files atomically through the VFS, restoring earlier
     writes when a later one fails.
  3. Change open buffers through `buffer.edit` (dirty, undoable).
  4. Send each written file to Phpactor as didOpen/didSave/didClose
     plus didChangeWatchedFiles; without this its index kept the old
     names. Then the summary notification `notification.lsp.renamed`.

UI (`components/editor/nav/`):
- Mod+click goes to the definition, with a pointer cursor while Mod is
  held.
- A location picker for several definitions (exclusive modal).
- A References tab in the bottom panel, grouped by file.
- An inline rename field with a use/file count (exclusive modal).
- `BufferSync.beginUndoableRemote` puts the engine's rename edit into
  the editor history as one undo step per buffer.
- Catalog strings and tokens only.

Fake LSP server: `--script FILE` with scripted capabilities and
answers (additive next to M3.4's arms).

Tests:
- `crates/engine/tests/lsp_nav.rs` (fake): definition; bad positions;
  references; prepareRename; a multi-file rename incl. a closed CRLF
  file; refusals for outside the project, a bad range, a stale buffer,
  bad names and no server.
- The ignored real-Phpactor test covers definition, references and a
  rename and back across 3 files.
- Vitest `ui/tests/nav/`.

Live (Phpactor 2026.06.25.0, Windows, port 7935, tick on):
- definition 93 ms cold / 7-18 ms warm
- references ~140 ms
- prepareRename ~11 ms
- rename 28-59 ms
- index follows written files in 140 ms
- Phpactor 57 MB working set, ~1.6% of a core while ticking idle

Gate: 13 steps, 197 s, Vitest 484 + 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-22 18:50:15 +02:00
parent b3fd7c6478
commit 578160a2ba
28 changed files with 3730 additions and 34 deletions

View file

@ -0,0 +1,29 @@
<script setup lang="ts">
/**
* Mounts the navigation overlays (M3.5), the location picker and the
* inline rename field, and starts the nav store, which supplies the
* context of `lsp.definition`, `lsp.references` and `lsp.rename` and the
* Mod+click handler. The References tab lives in the bottom panel
* (`MainLayout.vue`).
*/
import { onBeforeUnmount, onMounted } from "vue";
import { activeView } from "./navExtension";
import { useNavStore } from "./nav";
import NavPicker from "./NavPicker.vue";
import RenameInput from "./RenameInput.vue";
const nav = useNavStore();
onMounted(() => {
nav.start(activeView);
});
onBeforeUnmount(() => {
nav.stop();
});
</script>
<template>
<NavPicker />
<RenameInput />
</template>

View file

@ -0,0 +1,219 @@
<script setup lang="ts">
/**
* The location picker of Go to Definition (M3.5): shown when the language
* server reports several declarations. Each row has the file name, its
* directory and the 1-based line. Up/Down, Page Up/Down, Home and End move
* the selection; Enter or a click reveals it; Escape or a click outside
* closes the picker. An exclusive modal (the one-modal rule, `modals.ts`).
*/
import { FileCode } from "@lucide/vue";
import { nextTick, ref, watch } from "vue";
import { t } from "../../../i18n";
import { baseName } from "../../../stores/editor";
import { useNavStore, type NavLocation } from "./nav";
const nav = useNavStore();
/** The list element, which holds the focus. */
const list = ref<HTMLElement | null>(null);
/** Rows moved by Page Up and Page Down. */
const PAGE = 10;
/**
* The directory part of a path, empty at the root.
*
* @param path - project-relative path.
*/
function dirName(path: string): string {
const slash = path.lastIndexOf("/");
return slash < 0 ? "" : path.slice(0, slash);
}
/**
* The 1-based line of a location, for people.
*
* @param item - the location.
*/
function lineOf(item: NavLocation): string {
return t("nav.picker.line", { line: String(item.range.start.line + 1) });
}
/**
* Keyboard handling of the list.
*
* @param event - the key press.
*/
function onKeydown(event: KeyboardEvent): void {
const count = nav.picker?.items.length ?? 0;
const moves: Record<string, number> = {
ArrowDown: 1,
ArrowUp: -1,
PageDown: PAGE,
PageUp: -PAGE,
Home: -count,
End: count,
};
const delta = moves[event.key];
if (delta !== undefined) {
nav.movePicker(delta);
scrollSelected();
} else if (event.key === "Enter") {
void nav.choosePicked();
} else if (event.key === "Escape") {
nav.closePicker();
} else {
return;
}
event.preventDefault();
event.stopPropagation();
}
/** Keeps the selected row in view. */
function scrollSelected(): void {
void nextTick(() => {
const row = list.value?.querySelector<HTMLElement>(`#lt-nav-pick-${String(nav.picker?.selected ?? 0)}`);
if (row && typeof row.scrollIntoView === "function") {
row.scrollIntoView({ block: "nearest" });
}
});
}
watch(
() => nav.picker !== null,
(open) => {
if (open) {
void nextTick(() => list.value?.focus());
}
},
);
</script>
<template>
<div
v-if="nav.picker"
class="nav-picker"
data-test="nav-picker"
@mousedown.self.prevent="nav.closePicker()"
>
<div
class="nav-picker__dialog"
role="dialog"
aria-modal="true"
:aria-label="t('nav.picker.title', { name: nav.picker.symbol })"
>
<p class="nav-picker__title">
{{ t("nav.picker.title", { name: nav.picker.symbol }) }}
</p>
<ul
ref="list"
class="nav-picker__list"
role="listbox"
tabindex="0"
:aria-label="t('nav.picker.title', { name: nav.picker.symbol })"
:aria-activedescendant="`lt-nav-pick-${String(nav.picker.selected)}`"
data-test="nav-picker-list"
@keydown="onKeydown"
>
<li
v-for="(item, index) in nav.picker.items"
:id="`lt-nav-pick-${String(index)}`"
:key="`${item.path}:${String(item.range.start.line)}:${String(item.range.start.column)}`"
class="nav-picker__row"
:class="{ 'nav-picker__row--selected': index === nav.picker.selected }"
role="option"
:aria-selected="index === nav.picker.selected"
data-test="nav-picker-row"
@mousemove="nav.picker.selected = index"
@mousedown.prevent
@click="nav.choosePicked(index)"
>
<FileCode
class="nav-picker__icon"
:size="14"
aria-hidden="true"
/>
<span class="nav-picker__name">{{ baseName(item.path) }}</span>
<span class="nav-picker__dir">{{ dirName(item.path) }}</span>
<span class="nav-picker__line">{{ lineOf(item) }}</span>
</li>
</ul>
</div>
</div>
</template>
<style scoped>
.nav-picker {
position: fixed;
inset: 0;
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 12vh;
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
z-index: 30;
}
.nav-picker__dialog {
width: min(560px, 90vw);
max-height: 60vh;
display: flex;
flex-direction: column;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
overflow: hidden;
}
.nav-picker__title {
margin: 0;
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
font-weight: 600;
border-bottom: 1px solid var(--lt-border);
}
.nav-picker__list {
margin: 0;
padding: var(--lt-space-s, 4px) 0;
list-style: none;
overflow-y: auto;
outline: none;
}
.nav-picker__row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
padding: 3px var(--lt-space-m, 8px);
white-space: nowrap;
cursor: default;
}
.nav-picker__row--selected {
background: var(--lt-editor-selection-bg);
}
.nav-picker__icon {
flex-shrink: 0;
color: var(--lt-fg-muted);
}
.nav-picker__dir {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--lt-fg-muted);
}
.nav-picker__line {
flex-shrink: 0;
color: var(--lt-fg-muted);
}
.nav-picker__row--selected .nav-picker__dir,
.nav-picker__row--selected .nav-picker__line {
color: var(--lt-fg);
}
</style>

View file

@ -0,0 +1,312 @@
<script setup lang="ts">
/**
* The References tool window (M3.5), a tab of the bottom panel: the uses
* Find References found, grouped by file.
*
* - **Header line:** the symbol and the count, "Searching…" while the
* request runs, or the failure.
* - **List:** one group per file (name, directory, count), then its uses
* with the 1-based line and the line text, the name highlighted.
* Up/Down, Page Up/Down, Home and End move the selection; Enter or a
* click reveals the use through `editor.reveal`.
* - State lives in the nav store, so it is kept while the tab is hidden.
*/
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { t } from "../../../i18n";
import { baseName } from "../../../stores/editor";
import { useNavStore, type ReferenceItem } from "./nav";
const nav = useNavStore();
/** The list element. */
const list = ref<HTMLElement | null>(null);
/** Rows moved by Page Up and Page Down. */
const PAGE = 10;
/** The line above the list. */
const status = computed(() => {
if (nav.searching) {
return t("nav.references.searching", { name: nav.symbol });
}
if (nav.referencesError !== null) {
return t("nav.references.failed", { message: nav.referencesError });
}
if (nav.references.length === 0) {
return t("nav.references.none", { name: nav.symbol });
}
const files = new Set(nav.references.map((item) => item.path)).size;
return t("nav.references.summary", {
name: nav.symbol,
uses: String(nav.references.length),
files: String(files),
});
});
/** A file with its references and their indexes in the flat list. */
interface ReferenceGroup {
/** Project-relative path. */
path: string;
/** The references with their flat index. */
rows: { item: ReferenceItem; index: number }[];
}
/** The references grouped by file. */
const groups = computed<ReferenceGroup[]>(() => {
const out: ReferenceGroup[] = [];
nav.references.forEach((item, index) => {
const last = out[out.length - 1];
if (last?.path === item.path) {
last.rows.push({ item, index });
} else {
out.push({ path: item.path, rows: [{ item, index }] });
}
});
return out;
});
/**
* The DOM id of a row.
*
* @param index - the row's index in the flat list.
*/
function optionId(index: number): string {
return `reference-row-${String(index)}`;
}
/**
* The directory part of a path, empty at the root.
*
* @param path - project-relative path.
*/
function dirName(path: string): string {
const slash = path.lastIndexOf("/");
return slash < 0 ? "" : path.slice(0, slash);
}
/**
* The preview split around the name: before, the name, after. A preview
* whose column does not fit shows unsplit.
*
* @param item - the reference.
*/
function parts(item: ReferenceItem): { before: string; name: string; after: string } {
const { start, end } = item.range;
const length = start.line === end.line ? end.column - start.column : 0;
const from = item.previewColumn;
if (from > item.preview.length || length <= 0) {
return { before: item.preview, name: "", after: "" };
}
return {
before: item.preview.slice(0, from),
name: item.preview.slice(from, from + length),
after: item.preview.slice(from + length),
};
}
/**
* Reveals a reference.
*
* @param item - the reference.
*/
function openRow(item: ReferenceItem): void {
nav.select(item.key);
void nav.reveal(item);
}
/**
* Keyboard navigation in the list.
*
* @param event - the key event.
*/
function onListKey(event: KeyboardEvent): void {
const count = nav.references.length;
const moves: Record<string, number> = {
ArrowDown: 1,
ArrowUp: -1,
PageDown: PAGE,
PageUp: -PAGE,
Home: -count,
End: count,
};
const delta = moves[event.key];
if (delta !== undefined) {
event.preventDefault();
nav.move(delta);
} else if (event.key === "Enter") {
const item = nav.references[nav.selectedIndex];
if (item) {
event.preventDefault();
openRow(item);
}
}
}
/** Takes the focus Find References asked for, once. */
async function takeFocus(): Promise<void> {
if (!nav.focusPending) {
return;
}
nav.focusPending = false;
await nextTick();
list.value?.focus();
}
watch(() => nav.focusRequest, takeFocus);
onMounted(() => {
void takeFocus();
});
watch(
() => nav.selectedIndex,
async (index) => {
await nextTick();
const element = index < 0 ? null : document.getElementById(optionId(index));
if (element && typeof element.scrollIntoView === "function") {
element.scrollIntoView({ block: "nearest" });
}
},
);
</script>
<template>
<div
class="references"
data-test="references"
>
<div
class="references__status"
role="status"
data-test="references-status"
>
{{ status }}
</div>
<div
ref="list"
class="references__list"
role="listbox"
tabindex="0"
:aria-label="t('nav.references.label')"
:aria-activedescendant="nav.selectedIndex >= 0 ? optionId(nav.selectedIndex) : undefined"
data-test="references-list"
@keydown="onListKey"
>
<div
v-for="group in groups"
:key="group.path"
role="group"
:aria-label="group.path"
>
<div
class="references__file"
data-test="references-file"
>
<span class="references__file-name">{{ baseName(group.path) }}</span>
<span class="references__file-dir">{{ dirName(group.path) }}</span>
<span class="references__file-count">{{ group.rows.length }}</span>
</div>
<div
v-for="{ item, index } in group.rows"
:id="optionId(index)"
:key="item.key"
role="option"
class="references__row"
:class="{ 'references__row--selected': nav.selectedKey === item.key }"
:aria-selected="nav.selectedKey === item.key"
data-test="references-row"
@click="openRow(item)"
>
<span class="references__line">{{ item.range.start.line + 1 }}</span>
<span class="references__preview">{{ parts(item).before }}<mark class="references__name">{{ parts(item).name }}</mark>{{ parts(item).after }}</span>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.references {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.references__status {
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
color: var(--lt-fg-muted);
}
.references__list {
flex: 1;
min-height: 0;
overflow: auto;
border-top: 1px solid var(--lt-border);
outline: none;
}
.references__list:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.references__file {
display: flex;
align-items: baseline;
gap: var(--lt-space-m, 8px);
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
white-space: nowrap;
}
.references__file-name {
font-weight: 600;
}
.references__file-dir {
overflow: hidden;
text-overflow: ellipsis;
color: var(--lt-fg-muted);
}
.references__file-count {
margin-left: auto;
color: var(--lt-fg-muted);
}
.references__row {
display: flex;
align-items: baseline;
gap: var(--lt-space-m, 8px);
padding: 0 var(--lt-space-m, 8px) 0 var(--lt-space-l, 24px);
white-space: nowrap;
cursor: pointer;
}
.references__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.references__row--selected,
.references__row--selected:hover {
background: var(--lt-editor-selection-bg);
}
.references__line {
flex: none;
min-width: 3ch;
text-align: right;
color: var(--lt-fg-muted);
}
.references__preview {
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--lt-font-mono);
}
.references__name {
color: inherit;
background: var(--lt-editor-match-bg);
border-radius: 2px;
}
</style>

View file

@ -0,0 +1,168 @@
<script setup lang="ts">
/**
* The inline rename field (M3.5): placed over the symbol in the editor,
* prefilled with the current name (selected). Below it a line tells how
* many uses in how many files will change (counted with Find References)
* or why the rename failed. Enter applies the new name, Escape or leaving
* the field cancels. An exclusive modal (the one-modal rule, `modals.ts`).
*/
import { computed, nextTick, ref, watch } from "vue";
import { t } from "../../../i18n";
import { useNavStore } from "./nav";
const nav = useNavStore();
/** The input element. */
const input = ref<HTMLInputElement | null>(null);
/** Where the field goes: over the symbol, or near the top without a view. */
const style = computed(() => {
const anchor = nav.rename?.anchor;
return anchor
? { left: `${String(Math.max(0, anchor.left - 4))}px`, top: `${String(Math.max(0, anchor.top - 4))}px` }
: { left: "50%", top: "12vh", transform: "translateX(-50%)" };
});
/** The line under the field. */
const hint = computed(() => {
const r = nav.rename;
if (!r) {
return "";
}
if (r.error !== null) {
return r.error;
}
if (r.busy) {
return t("nav.rename.busy");
}
if (r.preview === null) {
return t("nav.rename.counting");
}
return t("nav.rename.preview", { uses: String(r.preview.uses), files: String(r.preview.files) });
});
/**
* Keyboard handling of the field.
*
* @param event - the key press.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Enter") {
void nav.commitRename();
} else if (event.key === "Escape") {
nav.cancelRename();
} else {
return;
}
event.preventDefault();
event.stopPropagation();
}
/** Cancels when the focus leaves the field, unless the rename runs. */
function onBlur(): void {
if (nav.rename && !nav.rename.busy) {
nav.cancelRename();
}
}
/**
* Takes the typed text.
*
* @param event - the input event.
*/
function onInput(event: Event): void {
if (nav.rename && event.target instanceof HTMLInputElement) {
nav.rename.value = event.target.value;
nav.rename.error = null;
}
}
watch(
() => nav.rename !== null,
(open) => {
if (open) {
void nextTick(() => {
input.value?.focus();
input.value?.select();
});
}
},
);
</script>
<template>
<div
v-if="nav.rename"
class="rename"
:style="style"
role="dialog"
:aria-label="t('nav.rename.label', { name: nav.rename.placeholder })"
data-test="rename"
>
<input
ref="input"
class="rename__input"
:class="{ 'rename__input--error': nav.rename.error !== null }"
type="text"
:value="nav.rename.value"
:readonly="nav.rename.busy"
:aria-label="t('nav.rename.label', { name: nav.rename.placeholder })"
:aria-describedby="'lt-rename-hint'"
spellcheck="false"
autocomplete="off"
data-test="rename-input"
@input="onInput"
@keydown="onKeydown"
@blur="onBlur"
>
<p
id="lt-rename-hint"
class="rename__hint"
:class="{ 'rename__hint--error': nav.rename.error !== null }"
role="status"
data-test="rename-hint"
>
{{ hint }}
</p>
</div>
</template>
<style scoped>
.rename {
position: fixed;
z-index: 30;
display: flex;
flex-direction: column;
min-width: 220px;
background: var(--lt-bg);
border: 1px solid var(--lt-accent);
border-radius: var(--lt-radius, 4px);
overflow: hidden;
}
.rename__input {
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
font-family: var(--lt-font-mono);
font-size: var(--lt-font-size-editor);
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: none;
outline: none;
}
.rename__input--error {
box-shadow: inset 0 -2px 0 var(--lt-error);
}
.rename__hint {
margin: 0;
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
font-size: 0.85em;
color: var(--lt-fg-muted);
border-top: 1px solid var(--lt-border);
}
.rename__hint--error {
color: var(--lt-error);
}
</style>

View file

@ -0,0 +1,621 @@
/**
* Navigation and rename through the language server (M3.5).
*
* - **Go to Definition** (`lsp.definition`, F12 or Mod+click): one location
* is revealed at once (`editor.reveal`); several open the location picker
* ({@link NavPicker}, an exclusive modal under the one-modal rule); none
* raises an info toast.
* - **Find References** (`lsp.references`, Shift+F12): the result fills the
* References tab of the bottom panel, grouped by file; a click or Enter
* reveals the use.
* - **Rename** (`lsp.rename`, F2): `lsp.prepareRename` first; a position
* that cannot be renamed raises an info toast. Otherwise an inline field
* over the symbol ({@link RenameInput}) takes the new name and shows how
* many uses will change (from `lsp.references`). Enter applies it, Escape
* cancels. Open buffers become dirty and one undo in each reverts it
* ({@link BufferSync.beginUndoableRemote}); closed files are written by
* the engine, which reports a summary notification.
*
* The engine commands are the ones the keymap and palette list; this store
* supplies their context (buffer id and cursor position) with
* `commands.provide`. Requests go through `runWaiting`, after the active
* buffer's edits reached the engine. Results come from the engine and,
* through it, from Phpactor: they are read defensively.
*/
import type { EditorView } from "@codemirror/view";
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { useModalsStore } from "../../../commands/modals";
import { t } from "../../../i18n";
import { runWaiting, type EngineError, type JsonValue } from "../../../ipc";
import { useEditorStore } from "../../../stores/editor";
import { useNotificationsStore } from "../../../stores/notifications";
import { positionOf } from "../engineText";
import { setDefinitionHandler } from "./navExtension";
/** The engine commands this store supplies context for. */
export const NAV_COMMANDS = {
definition: "lsp.definition",
references: "lsp.references",
prepareRename: "lsp.prepareRename",
rename: "lsp.rename",
} as const;
/** Most locations kept from one answer. */
export const MAX_LOCATIONS = 10_000;
/** A 0-based line and UTF-16 column. */
export interface NavPosition {
/** Line. */
line: number;
/** Column in UTF-16 code units. */
column: number;
}
/** A range in a file. */
export interface NavRange {
/** Start. */
start: NavPosition;
/** End (exclusive). */
end: NavPosition;
}
/** A location in a project file. */
export interface NavLocation {
/** Project-relative path with `/`. */
path: string;
/** The range. */
range: NavRange;
}
/** A use found by Find References. */
export interface ReferenceItem extends NavLocation {
/** Stable key: path and position. */
key: string;
/** The trimmed line text. */
preview: string;
/** Column of the range start inside {@link preview}. */
previewColumn: number;
}
/** The location picker's state. */
export interface PickerState {
/** The name the locations belong to, for the title. */
symbol: string;
/** The locations. */
items: NavLocation[];
/** Index of the selected one. */
selected: number;
}
/** The inline rename field's state. */
export interface RenameState {
/** The buffer. */
id: number;
/** Where the request was made. */
position: NavPosition;
/** The range of the current name. */
range: NavRange;
/** The current name. */
placeholder: string;
/** The typed name. */
value: string;
/** Uses that change and their files; null while counting or unknown. */
preview: { uses: number; files: number } | null;
/** Whether the rename runs. */
busy: boolean;
/** Why the last attempt failed. */
error: string | null;
/** Where the field goes, in viewport pixels; null without a view. */
anchor: { left: number; top: number } | null;
}
/**
* Reads a position; null if malformed.
*
* @param raw - untrusted `{line, column}`.
*/
function toPosition(raw: unknown): NavPosition | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const { line, column } = raw as Record<string, unknown>;
const ok = (n: unknown): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0;
return ok(line) && ok(column) ? { line, column } : null;
}
/**
* Reads a range; null if malformed.
*
* @param raw - untrusted `{start, end}`.
*/
export function toRange(raw: unknown): NavRange | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
const start = toPosition(r.start);
const end = toPosition(r.end);
return start && end ? { start, end } : null;
}
/**
* Reads the `locations` of a definition or references answer.
*
* @param raw - the untrusted command result.
* @returns the well-formed locations, at most {@link MAX_LOCATIONS}.
*/
export function toLocations(raw: unknown): NavLocation[] {
const list = typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>).locations : null;
if (!Array.isArray(list)) {
return [];
}
const out: NavLocation[] = [];
for (const entry of list as unknown[]) {
if (out.length >= MAX_LOCATIONS || typeof entry !== "object" || entry === null) {
continue;
}
const e = entry as Record<string, unknown>;
const range = toRange(e.range);
if (typeof e.path === "string" && e.path !== "" && range) {
out.push({ path: e.path, range });
}
}
return out;
}
/**
* Reads the answer of `lsp.references`.
*
* @param raw - the untrusted command result.
*/
export function toReferences(raw: unknown): ReferenceItem[] {
const list = typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>).locations : null;
if (!Array.isArray(list)) {
return [];
}
const out: ReferenceItem[] = [];
for (const entry of list as unknown[]) {
if (out.length >= MAX_LOCATIONS || typeof entry !== "object" || entry === null) {
continue;
}
const e = entry as Record<string, unknown>;
const range = toRange(e.range);
if (typeof e.path !== "string" || e.path === "" || !range) {
continue;
}
const preview = typeof e.preview === "string" ? e.preview : "";
const column = typeof e.previewColumn === "number" && e.previewColumn >= 0 ? e.previewColumn : 0;
const { line, column: start } = range.start;
const key = `${e.path}:${String(line)}:${String(start)}#${String(out.length)}`;
out.push({ path: e.path, range, key, preview, previewColumn: column });
}
return out;
}
/**
* Reads the answer of `lsp.prepareRename`.
*
* @param raw - the untrusted command result.
* @returns the range and current name, or null when the position cannot
* be renamed.
*/
export function toRenameable(raw: unknown): { range: NavRange; placeholder: string } | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
const range = toRange(r.range);
return range && typeof r.placeholder === "string" && r.placeholder !== "" ? { range, placeholder: r.placeholder } : null;
}
/**
* Number of distinct files among locations.
*
* @param items - the locations.
*/
export function fileCount(items: readonly NavLocation[]): number {
return new Set(items.map((item) => item.path)).size;
}
/**
* The line and UTF-16 column of a document position.
*
* @param view - the editor view (or anything with its `state.doc`).
* @param pos - the position.
*/
function lineColumn(view: Pick<EditorView, "state">, pos: number): NavPosition {
const line = view.state.doc.lineAt(pos);
return { line: line.number - 1, column: pos - line.from };
}
/** The nav store. */
export const useNavStore = defineStore("nav", () => {
const editor = useEditorStore();
const commands = useCommandsStore();
const modals = useModalsStore();
const notifications = useNotificationsStore();
/** The location picker, open while set. */
const picker = ref<PickerState | null>(null);
/** The inline rename field, open while set. */
const rename = ref<RenameState | null>(null);
/** Whether the References tab is shown in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while References is shown. */
const expanded = ref(true);
/** The name the shown references belong to. */
const symbol = ref("");
/** The shown references, sorted by path and position. */
const references = shallowRef<ReferenceItem[]>([]);
/** Whether a Find References request runs. */
const searching = ref(false);
/** Why the last Find References failed. */
const referencesError = ref<string | null>(null);
/** Key of the selected reference. */
const selectedKey = ref<string | null>(null);
/** Bumped when the References window should take the focus. */
const focusRequest = ref(0);
/** Whether a focus request waits for the window. */
const focusPending = ref(false);
/** Index of the selected reference, -1 if none. */
const selectedIndex = computed(() => references.value.findIndex((item) => item.key === selectedKey.value));
/**
* The active buffer and its cursor, after its edits reached the engine.
*
* @returns the buffer id, the cursor and the name under it, or null
* without an active tab.
*/
async function cursor(): Promise<{ id: number; position: NavPosition; word: string } | null> {
const id = editor.activeId;
const sync = id === null ? undefined : editor.syncOf(id);
if (id === null || !sync) {
return null;
}
await sync.idle();
const state = sync.state;
const head = state.selection.main.head;
const word = state.wordAt(head);
return {
id,
position: lineColumn({ state }, head),
word: word ? state.sliceDoc(word.from, word.to) : "",
};
}
/**
* Shows an engine failure as an error toast.
*
* @param command - the command id.
* @param error - the error.
*/
function fail(command: string, error: EngineError): void {
notifications.notifyError(command, error);
}
/**
* Reveals a location in the editor.
*
* @param location - the location.
*/
async function reveal(location: NavLocation): Promise<void> {
const { line, column } = location.range.start;
await commands.execute("editor.reveal", { path: location.path, line, column });
}
/** Go to Definition at the cursor. */
async function definition(): Promise<void> {
const at = await cursor();
if (!at) {
return;
}
const result = await runWaiting(NAV_COMMANDS.definition, { id: at.id, position: { ...at.position } });
if (!result.ok) {
fail(NAV_COMMANDS.definition, result.error);
return;
}
const items = toLocations(result.value);
const first = items[0];
if (!first) {
notifications.notify({ level: "info", message: t("nav.definition.none", { name: at.word || "?" }) });
return;
}
if (items.length === 1) {
await reveal(first);
return;
}
openPicker(at.word, items);
}
/**
* Opens the location picker.
*
* @param name - the symbol's name, for the title.
* @param items - the locations.
*/
function openPicker(name: string, items: NavLocation[]): void {
modals.opened("navPicker", closePicker);
picker.value = { symbol: name, items, selected: 0 };
}
/** Closes the location picker. */
function closePicker(): void {
picker.value = null;
modals.closed("navPicker");
}
/**
* Moves the picker's selection, clamped.
*
* @param delta - rows to move; positive is down.
*/
function movePicker(delta: number): void {
const p = picker.value;
if (!p || p.items.length === 0) {
return;
}
p.selected = Math.min(p.items.length - 1, Math.max(0, p.selected + delta));
}
/**
* Reveals a picker entry and closes the picker.
*
* @param index - the entry; the selected one when omitted.
*/
async function choosePicked(index?: number): Promise<void> {
const p = picker.value;
const item = p ? p.items[index ?? p.selected] : undefined;
closePicker();
if (item) {
await reveal(item);
}
}
/** Find References at the cursor. */
async function findReferences(): Promise<void> {
const at = await cursor();
if (!at) {
return;
}
symbol.value = at.word;
searching.value = true;
referencesError.value = null;
showReferences();
const result = await runWaiting(NAV_COMMANDS.references, { id: at.id, position: { ...at.position } });
searching.value = false;
if (!result.ok) {
references.value = [];
referencesError.value = result.error.message;
fail(NAV_COMMANDS.references, result.error);
return;
}
references.value = toReferences(result.value);
selectedKey.value = references.value[0]?.key ?? null;
}
/** Shows the References tab and asks it to take the focus. */
function showReferences(): void {
visible.value = true;
expanded.value = true;
focusPending.value = true;
focusRequest.value += 1;
}
/** Hides the References tab; the results stay. */
function hide(): void {
visible.value = false;
}
/**
* Selects a reference.
*
* @param key - its key, or null.
*/
function select(key: string | null): void {
selectedKey.value = key;
}
/**
* Moves the reference selection, clamped.
*
* @param delta - rows to move; positive is down.
*/
function move(delta: number): void {
const list = references.value;
if (list.length === 0) {
return;
}
const from = selectedIndex.value < 0 ? (delta > 0 ? -1 : list.length) : selectedIndex.value;
selectedKey.value = list[Math.min(list.length - 1, Math.max(0, from + delta))]?.key ?? null;
}
/**
* Where the rename field goes: over the start of `range` in the active
* view.
*
* @param view - the editor view, if any.
* @param range - the name's range.
*/
function anchorOf(view: EditorView | null, range: NavRange): { left: number; top: number } | null {
if (!view) {
return null;
}
const pos = positionOf(view.state.doc, range.start.line, range.start.column);
const coords = view.coordsAtPos(pos);
return coords ? { left: coords.left, top: coords.top } : null;
}
/**
* Starts a rename at the cursor: asks the server whether the name can be
* renamed and opens the inline field.
*
* @param view - the editor view to place the field in.
*/
async function startRename(view: EditorView | null): Promise<void> {
const at = await cursor();
if (!at) {
return;
}
const prepared = await runWaiting(NAV_COMMANDS.prepareRename, { id: at.id, position: { ...at.position } });
if (!prepared.ok) {
fail(NAV_COMMANDS.prepareRename, prepared.error);
return;
}
const target = toRenameable(prepared.value);
if (!target) {
notifications.notify({ level: "info", message: t("nav.rename.notHere") });
return;
}
modals.opened("rename", cancelRename);
rename.value = {
id: at.id,
position: at.position,
range: target.range,
placeholder: target.placeholder,
value: target.placeholder,
preview: null,
busy: false,
error: null,
anchor: anchorOf(view, target.range),
};
void countUses(at.id, at.position);
}
/**
* Fills the rename field's preview with the number of uses and files.
*
* @param id - the buffer.
* @param position - the symbol's position.
*/
async function countUses(id: number, position: NavPosition): Promise<void> {
const result = await runWaiting(NAV_COMMANDS.references, { id, position: { ...position } });
const current = rename.value;
if (!result.ok || !current || current.id !== id) {
return;
}
const items = toLocations(result.value);
current.preview = { uses: items.length, files: fileCount(items) };
}
/** Closes the rename field without renaming. */
function cancelRename(): void {
rename.value = null;
modals.closed("rename");
}
/**
* Applies the typed name. An unchanged or empty name just closes the
* field. Open buffers take the edit as one undoable step each.
*/
async function commitRename(): Promise<void> {
const current = rename.value;
if (!current || current.busy) {
return;
}
const name = current.value.trim();
if (name === "" || name === current.placeholder) {
cancelRename();
return;
}
current.busy = true;
current.error = null;
const syncs = editor.tabs.map((tab) => editor.syncOf(tab.id)).filter((s) => s !== undefined);
for (const sync of syncs) {
sync.beginUndoableRemote();
}
const params: JsonValue = { id: current.id, position: { ...current.position }, newName: name };
const result = await runWaiting<{ files?: unknown }>(NAV_COMMANDS.rename, params);
const versions = new Map<number, number>();
if (result.ok && Array.isArray(result.value.files)) {
for (const file of result.value.files as unknown[]) {
const f = file as Record<string, unknown> | null;
if (typeof f?.bufferId === "number" && typeof f.version === "number") {
versions.set(f.bufferId, f.version);
}
}
}
for (const sync of syncs) {
sync.endUndoableRemote(versions.get(sync.id) ?? null);
}
if (rename.value !== current) {
return;
}
if (!result.ok) {
current.busy = false;
current.error = result.error.message;
return;
}
cancelRename();
}
/** Runs Go to Definition at a Mod+click; the cursor is at the click already. */
function onModClick(): void {
void commands.execute(NAV_COMMANDS.definition);
}
/** Withdraws the command handlers; filled while started. */
let withdraw: (() => void)[] = [];
/**
* Supplies the commands' context and the Mod+click handler.
*
* @param view - returns the active editor view, for placing the rename
* field.
*/
function start(view: () => EditorView | null): void {
if (withdraw.length > 0) {
return;
}
const hasTab = (): boolean => editor.activeId !== null;
withdraw = [
commands.provide(NAV_COMMANDS.definition, { run: definition, enabled: hasTab }),
commands.provide(NAV_COMMANDS.references, { run: findReferences, enabled: hasTab }),
commands.provide(NAV_COMMANDS.rename, { run: () => startRename(view()), enabled: hasTab }),
];
setDefinitionHandler(onModClick);
}
/** Withdraws everything {@link start} supplied. */
function stop(): void {
for (const fn of withdraw) {
fn();
}
withdraw = [];
setDefinitionHandler(null);
}
return {
picker,
rename,
visible,
expanded,
symbol,
references,
searching,
referencesError,
selectedKey,
selectedIndex,
focusRequest,
focusPending,
definition,
openPicker,
closePicker,
movePicker,
choosePicked,
findReferences,
showReferences,
hide,
select,
move,
reveal,
startRename,
cancelRename,
commitRename,
start,
stop,
};
});

View file

@ -0,0 +1,105 @@
/**
* The editor side of navigation (M3.5): Mod+click on a name runs Go to
* Definition there, and the view showing the active tab is remembered so
* the inline rename field can be placed over the symbol.
*
* The extension knows nothing about the engine: the nav store registers a
* handler with {@link setDefinitionHandler}. `Mod` is Cmd on macOS and
* Ctrl elsewhere, as in the keymap.
*/
import { EditorView, ViewPlugin } from "@codemirror/view";
import type { Extension } from "@codemirror/state";
import { isMac } from "../../../commands/keymap";
/** Receives the document position of a Mod+click. */
export type DefinitionHandler = (view: EditorView, pos: number) => void;
/** The registered handler, or null. */
let handler: DefinitionHandler | null = null;
/** The view that showed a buffer last; one view serves every tab. */
let currentView: EditorView | null = null;
/**
* Registers what a Mod+click does.
*
* @param next - the handler, or null to remove it.
*/
export function setDefinitionHandler(next: DefinitionHandler | null): void {
handler = next;
}
/** The editor view showing the active tab, if one is mounted. */
export function activeView(): EditorView | null {
return currentView;
}
/**
* Whether a mouse event holds `Mod` and nothing else that changes a click.
*
* @param event - the mouse event.
* @param mac - whether `Mod` means Cmd.
*/
export function isModClick(event: MouseEvent, mac: boolean): boolean {
const mod = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
return event.button === 0 && mod && !event.altKey && !event.shiftKey;
}
/** Remembers the view while it exists. */
const trackView = ViewPlugin.define((view) => {
currentView = view;
return {
destroy(): void {
if (currentView === view) {
currentView = null;
}
},
};
});
/** Mod+click: moves the cursor to the click and asks for the definition. */
const modClick = EditorView.domEventHandlers({
mousedown(event, view) {
if (!handler || !isModClick(event, isMac())) {
return false;
}
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) {
return false;
}
event.preventDefault();
view.dispatch({ selection: { anchor: pos }, userEvent: "select.pointer" });
handler(view, pos);
return true;
},
});
/** A pointer cursor over the text while `Mod` is held, hinting at Mod+click. */
const modCursor = EditorView.theme({
"&.lt-nav-mod .cm-content": { cursor: "pointer" },
});
/** Toggles {@link modCursor}'s class with the modifier key. */
const modTracker = EditorView.domEventHandlers({
keydown(event, view) {
if (event.key === (isMac() ? "Meta" : "Control")) {
view.dom.classList.add("lt-nav-mod");
}
return false;
},
keyup(event, view) {
if (event.key === (isMac() ? "Meta" : "Control")) {
view.dom.classList.remove("lt-nav-mod");
}
return false;
},
blur(_event, view) {
view.dom.classList.remove("lt-nav-mod");
return false;
},
});
/** The navigation extensions of an editor state. */
export function navExtensions(): Extension {
return [trackView, modClick, modCursor, modTracker];
}