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:
parent
ef198f5f8f
commit
943ff889df
21 changed files with 1650 additions and 23 deletions
|
|
@ -2,8 +2,8 @@
|
|||
/**
|
||||
* Root component: mounts the main window layout with the editor area; the
|
||||
* slogan shows while no tab is open, and the restore dialog for unsaved
|
||||
* texts from the recovery journal, the toast stack, the command palette
|
||||
* and the settings dialog. Loads product information from the engine on
|
||||
* texts from the recovery journal, the toast stack, the command palette,
|
||||
* the go-to popup and the settings dialog. Loads product information from the engine on
|
||||
* mount, starts showing notifications, following the theme (see
|
||||
* `theme.ts`; a failed theme report raises an error toast) and the global
|
||||
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
|
||||
|
|
@ -13,6 +13,7 @@ import { onMounted, onUnmounted } from "vue";
|
|||
import { useCommandsStore } from "./commands/store";
|
||||
import CommandPalette from "./components/palette/CommandPalette.vue";
|
||||
import EditorArea from "./components/editor/EditorArea.vue";
|
||||
import GotoPopup from "./components/goto/GotoPopup.vue";
|
||||
import MainLayout from "./components/layout/MainLayout.vue";
|
||||
import NotificationStack from "./components/notifications/NotificationStack.vue";
|
||||
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
|
||||
|
|
@ -57,6 +58,7 @@ onUnmounted(() => {
|
|||
</MainLayout>
|
||||
<RecoveryDialog />
|
||||
<CommandPalette />
|
||||
<GotoPopup />
|
||||
<SettingsDialog />
|
||||
<NotificationStack />
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
/**
|
||||
* The modal rule (M1.15): at most one modal is open at a time.
|
||||
*
|
||||
* - **Exclusive modals:** the command palette, the settings dialog and the
|
||||
* close question of a dirty tab. Opening one closes the one that is open
|
||||
* - **Exclusive modals:** the command palette, the go-to popup (M2.6), the
|
||||
* settings dialog and the close question of a dirty tab. Opening one closes the one that is open
|
||||
* (the close question closes as Cancel). Each reports itself with
|
||||
* {@link useModalsStore}'s `opened` and `closed`; the close question is
|
||||
* followed from the editor store, so the editor needs no code for it.
|
||||
|
|
@ -14,14 +14,15 @@
|
|||
* - **The palette is a launcher:** running any command other than
|
||||
* `palette.open` closes it first (see `store.ts` › `execute`), so a
|
||||
* `uiCommand` from the control channel never leaves it open behind
|
||||
* what the command shows.
|
||||
* what the command shows. The go-to popup is a launcher too: any command
|
||||
* but the go-to open commands closes it.
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { ref, watch } from "vue";
|
||||
import { useEditorStore } from "../stores/editor";
|
||||
|
||||
/** The exclusive modals. */
|
||||
export type ModalId = "palette" | "settings" | "closePrompt";
|
||||
export type ModalId = "palette" | "goto" | "settings" | "closePrompt";
|
||||
|
||||
/** Store of the open exclusive modal. */
|
||||
export const useModalsStore = defineStore("modals", () => {
|
||||
|
|
|
|||
|
|
@ -54,6 +54,9 @@ export interface PaletteEntry {
|
|||
/** Most recently run commands remembered. */
|
||||
export const MAX_RECENT = 20;
|
||||
|
||||
/** The UI commands that open the go-to popup, which therefore keep it open. */
|
||||
const GOTO_OPEN = new Set(["goto.fileOpen", "goto.classOpen", "goto.symbolOpen"]);
|
||||
|
||||
/**
|
||||
* Reads the command list from the engine, keeping well-formed entries.
|
||||
*
|
||||
|
|
@ -184,7 +187,8 @@ export const useCommandsStore = defineStore("commands", () => {
|
|||
* Runs a command the user chose (keyboard or palette): through its
|
||||
* handler if a component supplied one, else through the engine. A
|
||||
* disabled command does nothing. A failure raises an error toast. Any
|
||||
* command but `palette.open` closes the palette before it runs.
|
||||
* command but `palette.open` closes the palette before it runs, and any
|
||||
* command but the go-to open commands closes the go-to popup.
|
||||
*
|
||||
* @param id - the command id.
|
||||
* @param params - the params.
|
||||
|
|
@ -197,6 +201,9 @@ export const useCommandsStore = defineStore("commands", () => {
|
|||
if (id !== "palette.open") {
|
||||
modals.dismiss("palette");
|
||||
}
|
||||
if (!GOTO_OPEN.has(id)) {
|
||||
modals.dismiss("goto");
|
||||
}
|
||||
const handler = handlers.get(id);
|
||||
if (handler) {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@ export interface UiCommandSpec {
|
|||
export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
||||
{ id: "editor.reveal", labelKey: "command.editor.reveal" },
|
||||
{ id: "find.open", labelKey: "command.find.open", defaultShortcut: "Mod+Alt+F" },
|
||||
{ id: "goto.classOpen", labelKey: "command.goto.classOpen", defaultShortcut: "Mod+Alt+C" },
|
||||
{ id: "goto.fileOpen", labelKey: "command.goto.fileOpen", defaultShortcut: "Mod+P" },
|
||||
{ id: "goto.symbolOpen", labelKey: "command.goto.symbolOpen", defaultShortcut: "Mod+T" },
|
||||
{ id: "palette.open", labelKey: "command.palette.open", defaultShortcut: "Mod+Shift+P" },
|
||||
{ id: "settings.open", labelKey: "command.settings.open", defaultShortcut: "Mod+," },
|
||||
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", defaultShortcut: "Mod+1" },
|
||||
|
|
|
|||
563
ui/src/components/goto/GotoPopup.vue
Normal file
563
ui/src/components/goto/GotoPopup.vue
Normal file
|
|
@ -0,0 +1,563 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The go-to popup (M2.6): find a file, a class or a symbol by name and
|
||||
* jump to it.
|
||||
*
|
||||
* - **Modes:** Files, Classes and Symbols, shown as tabs. `goto.fileOpen`
|
||||
* (`Mod+P`), `goto.classOpen` (`Mod+Alt+C`) and `goto.symbolOpen`
|
||||
* (`Mod+T`) open it in their mode; Tab and Shift+Tab, or a click on a
|
||||
* tab, switch the mode and keep the text. Each command takes an optional
|
||||
* `{query}`, so an agent can open the popup with a query.
|
||||
* - **Rows:** the matched characters are marked, the directory, namespace
|
||||
* or container is shown beside the name, and library items (vendor) are
|
||||
* dimmed and labelled. A hint shows while the index is still building.
|
||||
* - **Keys:** arrows move the selection, Enter opens it through
|
||||
* `editor.reveal` (files keep their cursor, symbols put it on the name),
|
||||
* Escape or a click outside closes.
|
||||
* - **One modal at a time** (see `commands/modals.ts`): opening the popup
|
||||
* closes the palette or the settings, and opening one of those closes
|
||||
* the popup.
|
||||
* - State lives in `stores/goto.ts`; the go-to commands need an open project.
|
||||
*/
|
||||
import {
|
||||
Box,
|
||||
Component,
|
||||
FileCode,
|
||||
Hash,
|
||||
ListOrdered,
|
||||
Puzzle,
|
||||
SquareFunction,
|
||||
Variable,
|
||||
} from "@lucide/vue";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, type Component as VueComponent } from "vue";
|
||||
import { useModalsStore } from "../../commands/modals";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import type { JsonValue } from "../../ipc";
|
||||
import { GOTO_MODES, useGotoStore, type GotoItem, type GotoMode } from "../../stores/goto";
|
||||
import { useProjectStore } from "../../stores/project";
|
||||
import { segments } from "./marks";
|
||||
|
||||
const goto = useGotoStore();
|
||||
const modals = useModalsStore();
|
||||
const commands = useCommandsStore();
|
||||
const project = useProjectStore();
|
||||
|
||||
/** The search field. */
|
||||
const input = ref<HTMLInputElement | null>(null);
|
||||
/** The list. */
|
||||
const list = ref<HTMLElement | null>(null);
|
||||
/** The element that had the focus before the popup opened. */
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
/** Withdraws the command handlers; set while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
/** UI command that opens each mode. */
|
||||
const OPEN_COMMAND: Record<GotoMode, string> = {
|
||||
file: "goto.fileOpen",
|
||||
class: "goto.classOpen",
|
||||
symbol: "goto.symbolOpen",
|
||||
};
|
||||
|
||||
/**
|
||||
* The tab label of a mode.
|
||||
*
|
||||
* @param mode - the mode.
|
||||
*/
|
||||
function modeLabel(mode: GotoMode): string {
|
||||
switch (mode) {
|
||||
case "file":
|
||||
return t("goto.mode.file");
|
||||
case "class":
|
||||
return t("goto.mode.class");
|
||||
case "symbol":
|
||||
return t("goto.mode.symbol");
|
||||
}
|
||||
}
|
||||
|
||||
/** The field's placeholder in the current mode. */
|
||||
const placeholder = computed(() => {
|
||||
switch (goto.mode) {
|
||||
case "file":
|
||||
return t("goto.placeholder.file");
|
||||
case "class":
|
||||
return t("goto.placeholder.class");
|
||||
case "symbol":
|
||||
return t("goto.placeholder.symbol");
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The icon of a row.
|
||||
*
|
||||
* @param item - the row.
|
||||
*/
|
||||
function iconOf(item: GotoItem): VueComponent {
|
||||
switch (item.kind) {
|
||||
case null:
|
||||
return FileCode;
|
||||
case "interface":
|
||||
return Component;
|
||||
case "trait":
|
||||
return Puzzle;
|
||||
case "enum":
|
||||
case "enumCase":
|
||||
return ListOrdered;
|
||||
case "function":
|
||||
case "method":
|
||||
return SquareFunction;
|
||||
case "property":
|
||||
return Variable;
|
||||
case "constant":
|
||||
return Hash;
|
||||
default:
|
||||
return Box;
|
||||
}
|
||||
}
|
||||
|
||||
/** The line under the field: the indexing hint, an error or nothing. */
|
||||
const hint = computed<string | null>(() => {
|
||||
if (goto.error !== null) {
|
||||
return goto.error;
|
||||
}
|
||||
if (!goto.indexing) {
|
||||
return null;
|
||||
}
|
||||
const progress = goto.progress;
|
||||
return progress && progress.total > 0
|
||||
? t("goto.indexingProgress", { done: progress.done, total: progress.total })
|
||||
: t("goto.indexing");
|
||||
});
|
||||
|
||||
/** The text shown when there are no rows, or null while rows show. */
|
||||
const emptyText = computed<string | null>(() => {
|
||||
if (goto.items.length > 0) {
|
||||
return null;
|
||||
}
|
||||
if (goto.query.trim() === "") {
|
||||
return t("goto.empty.prompt");
|
||||
}
|
||||
return goto.busy ? null : t("goto.empty.noMatches");
|
||||
});
|
||||
|
||||
/** DOM id of the selected row, for `aria-activedescendant`. */
|
||||
const activeId = computed(() => (goto.items.length > 0 ? `lt-goto-${String(goto.selected)}` : undefined));
|
||||
|
||||
/**
|
||||
* Reads the optional `query` of a command's params.
|
||||
*
|
||||
* @param params - the params; untrusted when an agent sent them.
|
||||
*/
|
||||
function queryOf(params: JsonValue): string | undefined {
|
||||
if (typeof params === "object" && params !== null && !Array.isArray(params)) {
|
||||
const query = params.query;
|
||||
return typeof query === "string" ? query : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the popup in a mode.
|
||||
*
|
||||
* @param mode - the mode.
|
||||
* @param params - the command's params, maybe with a `query`.
|
||||
*/
|
||||
async function show(mode: GotoMode, params: JsonValue): Promise<void> {
|
||||
modals.opened("goto", close);
|
||||
if (!goto.open) {
|
||||
const active = document.activeElement;
|
||||
returnFocus = active instanceof HTMLElement ? active : null;
|
||||
}
|
||||
const searching = goto.show(mode, queryOf(params));
|
||||
await nextTick();
|
||||
input.value?.focus();
|
||||
input.value?.select();
|
||||
await searching;
|
||||
}
|
||||
|
||||
/** Closes the popup and gives the focus back. */
|
||||
function close(): void {
|
||||
if (!goto.open) {
|
||||
return;
|
||||
}
|
||||
goto.hide();
|
||||
modals.closed("goto");
|
||||
returnFocus?.focus();
|
||||
returnFocus = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a row's file at its position; the popup closes first.
|
||||
*
|
||||
* @param item - the row.
|
||||
*/
|
||||
function choose(item: GotoItem | undefined): void {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
close();
|
||||
const params: JsonValue =
|
||||
item.line === null ? { path: item.path } : { path: item.path, line: item.line, column: item.column ?? 0 };
|
||||
void commands.execute("editor.reveal", params);
|
||||
}
|
||||
|
||||
/** Keeps the selected row in view. */
|
||||
function scrollSelected(): void {
|
||||
void nextTick(() => {
|
||||
const row = list.value?.querySelector<HTMLElement>(`#lt-goto-${String(goto.selected)}`);
|
||||
row?.scrollIntoView({ block: "nearest" });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the search field.
|
||||
*
|
||||
* @param event - the key press.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
goto.move(1);
|
||||
scrollSelected();
|
||||
break;
|
||||
case "ArrowUp":
|
||||
goto.move(-1);
|
||||
scrollSelected();
|
||||
break;
|
||||
case "PageDown":
|
||||
goto.move(10);
|
||||
scrollSelected();
|
||||
break;
|
||||
case "PageUp":
|
||||
goto.move(-10);
|
||||
scrollSelected();
|
||||
break;
|
||||
case "Tab":
|
||||
goto.cycleMode(event.shiftKey ? -1 : 1);
|
||||
break;
|
||||
case "Enter":
|
||||
choose(goto.current);
|
||||
break;
|
||||
case "Escape":
|
||||
close();
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches the mode from a tab click and keeps the focus in the field.
|
||||
*
|
||||
* @param mode - the tab's mode.
|
||||
*/
|
||||
function pickMode(mode: GotoMode): void {
|
||||
goto.setMode(mode);
|
||||
input.value?.focus();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => goto.focusRequest,
|
||||
() => {
|
||||
void nextTick(() => input.value?.focus());
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
goto.start();
|
||||
const hasProject = (): boolean => project.root !== null;
|
||||
withdraw = GOTO_MODES.map((mode) =>
|
||||
commands.provide(OPEN_COMMAND[mode], { run: (params) => show(mode, params), enabled: hasProject }),
|
||||
);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const fn of withdraw) {
|
||||
fn();
|
||||
}
|
||||
withdraw = [];
|
||||
goto.stop();
|
||||
});
|
||||
|
||||
defineExpose({ show, close });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="goto.open"
|
||||
class="goto"
|
||||
data-test="goto"
|
||||
@mousedown.self.prevent="close()"
|
||||
>
|
||||
<div
|
||||
class="goto__dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('goto.label')"
|
||||
>
|
||||
<div
|
||||
class="goto__modes"
|
||||
role="tablist"
|
||||
:aria-label="t('goto.modes')"
|
||||
>
|
||||
<button
|
||||
v-for="mode in GOTO_MODES"
|
||||
:key="mode"
|
||||
type="button"
|
||||
class="goto__mode"
|
||||
:class="{ 'goto__mode--active': mode === goto.mode }"
|
||||
role="tab"
|
||||
:aria-selected="mode === goto.mode"
|
||||
tabindex="-1"
|
||||
:data-mode="mode"
|
||||
data-test="goto-mode"
|
||||
@mousedown.prevent
|
||||
@click="pickMode(mode)"
|
||||
>
|
||||
{{ modeLabel(mode) }}
|
||||
</button>
|
||||
<span class="goto__switch">{{ t("goto.switchHint") }}</span>
|
||||
</div>
|
||||
<input
|
||||
ref="input"
|
||||
:value="goto.query"
|
||||
class="goto__input"
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-autocomplete="list"
|
||||
aria-expanded="true"
|
||||
aria-controls="lt-goto-list"
|
||||
:aria-activedescendant="activeId"
|
||||
:aria-label="placeholder"
|
||||
:placeholder="placeholder"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
data-test="goto-input"
|
||||
@input="goto.setQuery(($event.target as HTMLInputElement).value)"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<p
|
||||
v-if="hint !== null"
|
||||
class="goto__hint"
|
||||
:class="{ 'goto__hint--error': goto.error !== null }"
|
||||
role="status"
|
||||
data-test="goto-hint"
|
||||
>
|
||||
{{ hint }}
|
||||
</p>
|
||||
<ul
|
||||
id="lt-goto-list"
|
||||
ref="list"
|
||||
class="goto__list"
|
||||
role="listbox"
|
||||
:aria-label="t('goto.label')"
|
||||
>
|
||||
<li
|
||||
v-for="(item, index) in goto.items"
|
||||
:id="`lt-goto-${String(index)}`"
|
||||
:key="item.key"
|
||||
class="goto__row"
|
||||
:class="{
|
||||
'goto__row--selected': index === goto.selected,
|
||||
'goto__row--library': item.library,
|
||||
}"
|
||||
role="option"
|
||||
:aria-selected="index === goto.selected"
|
||||
:data-path="item.path"
|
||||
data-test="goto-row"
|
||||
@mousemove="goto.selected = index"
|
||||
@mousedown.prevent
|
||||
@click="choose(item)"
|
||||
>
|
||||
<component
|
||||
:is="iconOf(item)"
|
||||
class="goto__icon"
|
||||
:size="14"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span
|
||||
class="goto__label"
|
||||
data-test="goto-label"
|
||||
><template
|
||||
v-for="(part, i) in segments(item.label, item.labelMatches)"
|
||||
:key="i"
|
||||
><mark
|
||||
v-if="part.mark"
|
||||
class="goto__mark"
|
||||
>{{ part.text }}</mark><template v-else>{{ part.text }}</template></template></span>
|
||||
<span
|
||||
class="goto__detail"
|
||||
data-test="goto-detail"
|
||||
><template
|
||||
v-for="(part, i) in segments(item.detail, item.detailMatches)"
|
||||
:key="i"
|
||||
><mark
|
||||
v-if="part.mark"
|
||||
class="goto__mark"
|
||||
>{{ part.text }}</mark><template v-else>{{ part.text }}</template></template></span>
|
||||
<span
|
||||
v-if="item.library"
|
||||
class="goto__library"
|
||||
data-test="goto-library"
|
||||
>{{ t("goto.library") }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p
|
||||
v-if="emptyText !== null"
|
||||
class="goto__empty"
|
||||
role="status"
|
||||
data-test="goto-empty"
|
||||
>
|
||||
{{ emptyText }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.goto {
|
||||
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;
|
||||
}
|
||||
|
||||
.goto__dialog {
|
||||
width: min(680px, 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: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.goto__modes {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 4px 8px 0;
|
||||
}
|
||||
|
||||
.goto__mode {
|
||||
padding: 4px 10px;
|
||||
font: inherit;
|
||||
color: var(--lt-fg-muted);
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.goto__mode--active {
|
||||
color: var(--lt-fg);
|
||||
border-bottom-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.goto__switch {
|
||||
margin-left: auto;
|
||||
font-size: 0.85em;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.goto__input {
|
||||
padding: 8px 12px;
|
||||
font: inherit;
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-editor-bg);
|
||||
border: none;
|
||||
border-top: 1px solid var(--lt-border);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.goto__hint {
|
||||
margin: 0;
|
||||
padding: 4px 12px;
|
||||
font-size: 0.85em;
|
||||
color: var(--lt-fg-muted);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.goto__hint--error {
|
||||
color: var(--lt-error);
|
||||
}
|
||||
|
||||
.goto__list {
|
||||
margin: 0;
|
||||
padding: 4px 0;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.goto__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 3px 12px;
|
||||
cursor: default;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.goto__row--selected {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.goto__icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.goto__label {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.goto__detail {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.goto__mark {
|
||||
color: inherit;
|
||||
background: var(--lt-editor-match-bg);
|
||||
font-weight: 700;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.goto__row--library .goto__label {
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.goto__library {
|
||||
flex-shrink: 0;
|
||||
padding: 0 6px;
|
||||
font-size: 0.8em;
|
||||
color: var(--lt-fg-muted);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.goto__row--selected .goto__detail,
|
||||
.goto__row--selected .goto__library {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.goto__empty {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
</style>
|
||||
41
ui/src/components/goto/marks.ts
Normal file
41
ui/src/components/goto/marks.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
* Splits a text into plain and marked pieces for the go-to popup's match
|
||||
* highlighting.
|
||||
*/
|
||||
|
||||
/** A piece of a row's text. */
|
||||
export interface Segment {
|
||||
/** The characters. */
|
||||
text: string;
|
||||
/** Whether they matched the query. */
|
||||
mark: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuts `text` at the given ranges.
|
||||
*
|
||||
* @param text - the shown text.
|
||||
* @param ranges - `[start, end)` UTF-16 ranges, sorted; overlapping or
|
||||
* out-of-range parts are ignored.
|
||||
* @returns the pieces in order; empty for an empty text.
|
||||
*/
|
||||
export function segments(text: string, ranges: readonly (readonly [number, number])[]): Segment[] {
|
||||
const out: Segment[] = [];
|
||||
let at = 0;
|
||||
for (const [start, end] of ranges) {
|
||||
const from = Math.max(start, at);
|
||||
const to = Math.min(end, text.length);
|
||||
if (to <= from) {
|
||||
continue;
|
||||
}
|
||||
if (from > at) {
|
||||
out.push({ text: text.slice(at, from), mark: false });
|
||||
}
|
||||
out.push({ text: text.slice(from, to), mark: true });
|
||||
at = to;
|
||||
}
|
||||
if (at < text.length) {
|
||||
out.push({ text: text.slice(at), mark: false });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -2,6 +2,9 @@
|
|||
"app.statusBar.version": "{name} {version}",
|
||||
"command.editor.reveal": "Reveal Cursor in Editor",
|
||||
"command.find.open": "Find in Files…",
|
||||
"command.goto.classOpen": "Go to Class…",
|
||||
"command.goto.fileOpen": "Go to File…",
|
||||
"command.goto.symbolOpen": "Go to Symbol…",
|
||||
"command.key.alt": "Alt",
|
||||
"command.key.cmd": "Cmd",
|
||||
"command.key.ctrl": "Ctrl",
|
||||
|
|
@ -51,6 +54,20 @@
|
|||
"find.status.running": "Searching… {matches} matches in {files} files",
|
||||
"find.status.truncated": "Stopped at {matches} matches; narrow the query or the files to see the rest",
|
||||
"find.toolWindow.title": "Find",
|
||||
"goto.empty.noMatches": "Nothing matches",
|
||||
"goto.empty.prompt": "Type a name",
|
||||
"goto.indexing": "Indexing… results may be incomplete",
|
||||
"goto.indexingProgress": "Indexing {done} of {total} files… results may be incomplete",
|
||||
"goto.label": "Go to",
|
||||
"goto.library": "library",
|
||||
"goto.mode.class": "Classes",
|
||||
"goto.mode.file": "Files",
|
||||
"goto.mode.symbol": "Symbols",
|
||||
"goto.modes": "What to find",
|
||||
"goto.placeholder.class": "Class, interface, trait or enum name",
|
||||
"goto.placeholder.file": "File name or path",
|
||||
"goto.placeholder.symbol": "Function, method, property or constant; Class::member",
|
||||
"goto.switchHint": "Tab switches",
|
||||
"notification.close": "Close notification",
|
||||
"notification.command.failed": "{command} failed: {message}",
|
||||
"notification.project.notLocal": "The chosen folder is not on this computer: {reason}",
|
||||
|
|
|
|||
|
|
@ -90,6 +90,22 @@ export type EngineEventPayload =
|
|||
kind: "outlineChanged";
|
||||
/** Buffer whose outline changed; unchecked, it comes from the engine. */
|
||||
id: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "indexProgress";
|
||||
/** Files indexed so far; unchecked, it comes from the engine. */
|
||||
done: unknown;
|
||||
/** Files found to index; unchecked. */
|
||||
total: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "indexReady";
|
||||
/** Files in the index; unchecked, it comes from the engine. */
|
||||
files: unknown;
|
||||
/** Symbols in the index; unchecked. */
|
||||
symbols: unknown;
|
||||
/** Build time in milliseconds; unchecked. */
|
||||
elapsedMs: unknown;
|
||||
};
|
||||
|
||||
/** Callback receiving engine events. */
|
||||
|
|
|
|||
470
ui/src/stores/goto.ts
Normal file
470
ui/src/stores/goto.ts
Normal 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,
|
||||
};
|
||||
});
|
||||
471
ui/tests/goto/GotoPopup.test.ts
Normal file
471
ui/tests/goto/GotoPopup.test.ts
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
/**
|
||||
* Tests of the go-to popup (M2.6): the three open commands and their
|
||||
* shortcuts, the debounced live query against `goto.*` with stale answers
|
||||
* dropped, match marks, the path / namespace / container column, library
|
||||
* rows, the indexing hint and the re-query on `indexReady`, opening through
|
||||
* `editor.reveal`, Escape, mode switching, the one-modal rule against the
|
||||
* palette, and the parsing helpers of the store. The engine is a fake
|
||||
* behind the mocked Tauri `invoke` and `listen`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent, h } from "vue";
|
||||
|
||||
const invoke = vi.hoisted(() => vi.fn());
|
||||
const listen = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
vi.mock("@tauri-apps/api/event", () => ({ listen }));
|
||||
|
||||
import { useModalsStore } from "../../src/commands/modals";
|
||||
import { useCommandsStore } from "../../src/commands/store";
|
||||
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||
import GotoPopup from "../../src/components/goto/GotoPopup.vue";
|
||||
import { segments } from "../../src/components/goto/marks";
|
||||
import CommandPalette from "../../src/components/palette/CommandPalette.vue";
|
||||
import {
|
||||
DEBOUNCE_MS,
|
||||
fileItem,
|
||||
markSubsequence,
|
||||
readRanges,
|
||||
symbolItem,
|
||||
useGotoStore,
|
||||
} from "../../src/stores/goto";
|
||||
import { useProjectStore } from "../../src/stores/project";
|
||||
|
||||
/** A pending answer of the fake engine. */
|
||||
interface Deferred {
|
||||
/** Answers with a value. */
|
||||
resolve: (value: unknown) => void;
|
||||
}
|
||||
|
||||
/** Every `engine_execute` call, in order. */
|
||||
let calls: { command: string; params: Record<string, unknown> }[];
|
||||
/** Answers of the go-to commands by command id; a function answers per query. */
|
||||
let answers: Map<string, (params: Record<string, unknown>) => unknown>;
|
||||
/** Go-to calls held back until the test resolves them, when set. */
|
||||
let held: Deferred[] | null;
|
||||
/** The engine event callbacks, one per subscription. */
|
||||
let listeners: ((payload: unknown) => void)[];
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components, unmounted after each test. */
|
||||
let mounted: VueWrapper[];
|
||||
/** Params of every `editor.reveal` the stand-in editor ran. */
|
||||
let revealed: unknown[];
|
||||
|
||||
/** The fake engine's listing: the registered UI commands. */
|
||||
function listing(): unknown[] {
|
||||
const registered = calls.find((c) => c.command === "ui.registerCommands")?.params as
|
||||
| { commands: { id: string; labelKey: string; defaultShortcut?: string }[] }
|
||||
| undefined;
|
||||
return (registered?.commands ?? []).map((c) => ({
|
||||
id: c.id,
|
||||
label: c.labelKey,
|
||||
labelKey: c.labelKey,
|
||||
menuPath: null,
|
||||
defaultShortcut: c.defaultShortcut ?? null,
|
||||
params: "",
|
||||
enabled: true,
|
||||
ui: true,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an engine event to every subscriber.
|
||||
*
|
||||
* @param payload - the event.
|
||||
*/
|
||||
async function emit(payload: unknown): Promise<void> {
|
||||
for (const listener of listeners) {
|
||||
listener(payload);
|
||||
}
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** Waits out the debounce and lets the answers arrive. */
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, DEBOUNCE_MS + 20));
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/**
|
||||
* Presses a key on the focused element (or the body).
|
||||
*
|
||||
* @param init - key event properties.
|
||||
*/
|
||||
async function press(init: KeyboardEventInit): Promise<void> {
|
||||
const target = document.activeElement ?? document.body;
|
||||
target.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** A focusable button standing in for the editor. */
|
||||
const Host = defineComponent({
|
||||
setup: () => () => h("button", { id: "host-button" }, "host"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Mounts the popup (and the palette) next to a focusable button, opens a
|
||||
* project, provides a stand-in `editor.reveal` and starts the commands.
|
||||
*
|
||||
* @param withProject - whether a project is open.
|
||||
*/
|
||||
async function mountPopup(withProject = true): Promise<VueWrapper> {
|
||||
const host = mount(Host, { attachTo: document.body });
|
||||
const palette = mount(CommandPalette, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
const wrapper = mount(GotoPopup, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(host, palette, wrapper);
|
||||
if (withProject) {
|
||||
useProjectStore(pinia).root = { path: "/p", name: "p" };
|
||||
}
|
||||
const commands = useCommandsStore(pinia);
|
||||
commands.provide("editor.reveal", {
|
||||
run: (params) => {
|
||||
revealed.push(params);
|
||||
},
|
||||
});
|
||||
await commands.start();
|
||||
await flushPromises();
|
||||
(host.element as HTMLElement).focus();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Types into the popup's field.
|
||||
*
|
||||
* @param wrapper - the popup.
|
||||
* @param text - the query.
|
||||
*/
|
||||
async function type(wrapper: VueWrapper, text: string): Promise<void> {
|
||||
await wrapper.find("[data-test=goto-input]").setValue(text);
|
||||
await settle();
|
||||
}
|
||||
|
||||
/**
|
||||
* The visible rows as `label | detail`.
|
||||
*
|
||||
* @param wrapper - the popup.
|
||||
*/
|
||||
function rows(wrapper: VueWrapper): string[] {
|
||||
return wrapper
|
||||
.findAll("[data-test=goto-row]")
|
||||
.map((row) => `${row.find("[data-test=goto-label]").text()} | ${row.find("[data-test=goto-detail]").text()}`);
|
||||
}
|
||||
|
||||
/** Calls of one engine command. */
|
||||
function callsOf(command: string): Record<string, unknown>[] {
|
||||
return calls.filter((c) => c.command === command).map((c) => c.params);
|
||||
}
|
||||
|
||||
/** Two files, one of them in vendor. */
|
||||
const FILES = {
|
||||
items: [
|
||||
{ path: "src/Models/User.php", score: 90, matches: [[11, 15]], library: false },
|
||||
{ path: "vendor/acme/User.php", score: 80, matches: [[11, 15]], library: true },
|
||||
],
|
||||
indexing: false,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
calls = [];
|
||||
answers = new Map([["goto.file", () => FILES]]);
|
||||
held = null;
|
||||
listeners = [];
|
||||
mounted = [];
|
||||
revealed = [];
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||
listeners.push((payload) => {
|
||||
callback({ payload });
|
||||
});
|
||||
return Promise.resolve(() => undefined);
|
||||
});
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (cmd === "engine_list_commands") {
|
||||
return Promise.resolve(listing());
|
||||
}
|
||||
if (cmd === "engine_execute" && args) {
|
||||
calls.push({ command: args.command, params: args.params });
|
||||
const answer = answers.get(args.command);
|
||||
if (answer) {
|
||||
const value = answer(args.params);
|
||||
if (held) {
|
||||
const queue = held;
|
||||
return new Promise((resolve) => {
|
||||
queue.push({
|
||||
resolve: () => {
|
||||
resolve(value);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
return Promise.resolve(value);
|
||||
}
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useCommandsStore(pinia).stop();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
describe("go-to commands", () => {
|
||||
it("registers three open commands with Lutra's shortcuts", () => {
|
||||
const shortcuts = Object.fromEntries(
|
||||
UI_COMMANDS.filter((c) => c.id.startsWith("goto.")).map((c) => [c.id, c.defaultShortcut]),
|
||||
);
|
||||
expect(shortcuts).toEqual({ "goto.classOpen": "Mod+Alt+C", "goto.fileOpen": "Mod+P", "goto.symbolOpen": "Mod+T" });
|
||||
});
|
||||
|
||||
it("opens in file mode with Ctrl+P and focuses the field", async () => {
|
||||
const wrapper = await mountPopup();
|
||||
await press({ key: "p", code: "KeyP", ctrlKey: true });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(true);
|
||||
expect(document.activeElement).toBe(wrapper.find("[data-test=goto-input]").element);
|
||||
expect(wrapper.find(".goto__mode--active").attributes("data-mode")).toBe("file");
|
||||
expect(wrapper.find("[data-test=goto-empty]").text()).toBe("Type a name");
|
||||
expect(useModalsStore(pinia).current).toBe("goto");
|
||||
});
|
||||
|
||||
it("is disabled without a project", async () => {
|
||||
const wrapper = await mountPopup(false);
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("opens from a uiCommand with a query and searches at once", async () => {
|
||||
answers.set("goto.class", () => ({
|
||||
items: [
|
||||
{ name: "User", fqn: "App\\Models\\User", kind: "class", path: "src/Models/User.php", line: 3, column: 12, library: false },
|
||||
],
|
||||
indexing: false,
|
||||
}));
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.classOpen", params: { query: "usr" } });
|
||||
expect(callsOf("goto.class")).toEqual([{ query: "usr", limit: 100 }]);
|
||||
expect(rows(wrapper)).toEqual(["User | App\\Models"]);
|
||||
expect(wrapper.findAll("mark").map((m) => m.text())).toEqual(["Us", "r"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("live query", () => {
|
||||
it("debounces typing, marks the matched characters and dims library rows", async () => {
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
const input = wrapper.find("[data-test=goto-input]");
|
||||
await input.setValue("u");
|
||||
await input.setValue("us");
|
||||
await input.setValue("user");
|
||||
await settle();
|
||||
expect(callsOf("goto.file")).toEqual([{ query: "user", limit: 100 }]);
|
||||
expect(rows(wrapper)).toEqual(["User.php | src/Models/", "User.php | vendor/acme/"]);
|
||||
expect(wrapper.findAll("[data-test=goto-row]")[0]?.find("mark").text()).toBe("User");
|
||||
const library = wrapper.findAll("[data-test=goto-row]")[1];
|
||||
expect(library?.classes()).toContain("goto__row--library");
|
||||
expect(library?.find("[data-test=goto-library]").text()).toBe("library");
|
||||
expect(wrapper.findAll("[data-test=goto-library]")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("drops an answer that arrives after a newer one", async () => {
|
||||
answers.set("goto.file", (params) => ({
|
||||
items: [{ path: `src/${String(params.query)}.php`, score: 1, matches: [], library: false }],
|
||||
indexing: false,
|
||||
}));
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
held = [];
|
||||
const queue = held;
|
||||
await type(wrapper, "old");
|
||||
await type(wrapper, "new");
|
||||
expect(queue).toHaveLength(2);
|
||||
queue[1]?.resolve(null);
|
||||
await flushPromises();
|
||||
queue[0]?.resolve(null);
|
||||
await flushPromises();
|
||||
expect(rows(wrapper)).toEqual(["new.php | src/"]);
|
||||
});
|
||||
|
||||
it("shows no matches, and an error from the engine", async () => {
|
||||
answers.set("goto.file", () => ({ items: [], indexing: false }));
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
await type(wrapper, "zzz");
|
||||
expect(wrapper.find("[data-test=goto-empty]").text()).toBe("Nothing matches");
|
||||
invoke.mockImplementationOnce(() => Promise.reject(Object.assign(new Error("x"), { code: "disabled", message: "no project" })));
|
||||
await type(wrapper, "zzzz");
|
||||
expect(wrapper.find("[data-test=goto-hint]").text()).toBe("no project");
|
||||
});
|
||||
|
||||
it("shows the indexing hint with progress and re-queries on indexReady", async () => {
|
||||
let indexing = true;
|
||||
answers.set("goto.file", () => ({ ...FILES, items: indexing ? FILES.items.slice(0, 1) : FILES.items, indexing }));
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: { query: "user" } });
|
||||
expect(wrapper.find("[data-test=goto-hint]").text()).toBe("Indexing… results may be incomplete");
|
||||
await emit({ kind: "indexProgress", done: 120, total: 400 });
|
||||
expect(wrapper.find("[data-test=goto-hint]").text()).toBe("Indexing 120 of 400 files… results may be incomplete");
|
||||
expect(rows(wrapper)).toHaveLength(1);
|
||||
indexing = false;
|
||||
await emit({ kind: "indexReady", files: 400, symbols: 900, elapsedMs: 50 });
|
||||
expect(callsOf("goto.file")).toHaveLength(2);
|
||||
expect(rows(wrapper)).toHaveLength(2);
|
||||
expect(wrapper.find("[data-test=goto-hint]").exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("keyboard and opening", () => {
|
||||
it("opens a file with Enter through editor.reveal and gives the focus back", async () => {
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: { query: "user" } });
|
||||
await press({ key: "ArrowDown" });
|
||||
await press({ key: "Enter" });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
|
||||
expect(revealed).toEqual([{ path: "vendor/acme/User.php" }]);
|
||||
expect(document.activeElement?.id).toBe("host-button");
|
||||
expect(useModalsStore(pinia).current).toBe(null);
|
||||
});
|
||||
|
||||
it("reveals a symbol at its line and column on click", async () => {
|
||||
answers.set("goto.symbol", () => ({
|
||||
items: [
|
||||
{ name: "find", fqn: "App\\User::find", kind: "method", container: "App\\User", path: "src/User.php", line: 7, column: 20, library: false },
|
||||
],
|
||||
indexing: false,
|
||||
}));
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.symbolOpen", params: { query: "User::fi" } });
|
||||
expect(rows(wrapper)).toEqual(["find | App\\User"]);
|
||||
expect(wrapper.findAll("mark").map((m) => m.text())).toEqual(["fi"]);
|
||||
await wrapper.find("[data-test=goto-row]").trigger("click");
|
||||
expect(revealed).toEqual([{ path: "src/User.php", line: 7, column: 20 }]);
|
||||
});
|
||||
|
||||
it("switches modes with Tab and keeps the text", async () => {
|
||||
answers.set("goto.class", () => ({ items: [], indexing: false }));
|
||||
answers.set("goto.symbol", () => ({ items: [], indexing: false }));
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: { query: "user" } });
|
||||
await press({ key: "Tab" });
|
||||
expect(wrapper.find(".goto__mode--active").attributes("data-mode")).toBe("class");
|
||||
await press({ key: "Tab" });
|
||||
await press({ key: "Tab", shiftKey: true });
|
||||
expect(wrapper.find(".goto__mode--active").attributes("data-mode")).toBe("class");
|
||||
expect(callsOf("goto.class").map((p) => p.query)).toEqual(["user", "user"]);
|
||||
expect(callsOf("goto.symbol").map((p) => p.query)).toEqual(["user"]);
|
||||
await wrapper.find("[data-mode=file]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(wrapper.find(".goto__mode--active").attributes("data-mode")).toBe("file");
|
||||
expect((wrapper.find("[data-test=goto-input]").element as HTMLInputElement).value).toBe("user");
|
||||
});
|
||||
|
||||
it("closes with Escape and on a click outside", async () => {
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
await press({ key: "Escape" });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
await wrapper.find("[data-test=goto]").trigger("mousedown");
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("never stacks with the palette", async () => {
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "palette.open", params: {} });
|
||||
expect(document.querySelector("[data-test=palette]")).not.toBeNull();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: {} });
|
||||
expect(document.querySelector("[data-test=palette]")).toBeNull();
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(true);
|
||||
await emit({ kind: "uiCommand", id: "palette.open", params: {} });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
|
||||
expect(useModalsStore(pinia).current).toBe("palette");
|
||||
});
|
||||
});
|
||||
|
||||
describe("launcher", () => {
|
||||
it("closes when another command runs, also from the control channel", async () => {
|
||||
const wrapper = await mountPopup();
|
||||
await emit({ kind: "uiCommand", id: "goto.fileOpen", params: { query: "user" } });
|
||||
await emit({ kind: "uiCommand", id: "goto.classOpen", params: {} });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(true);
|
||||
await emit({ kind: "uiCommand", id: "editor.reveal", params: { path: "src/Models/User.php" } });
|
||||
expect(wrapper.find("[data-test=goto]").exists()).toBe(false);
|
||||
expect(revealed).toEqual([{ path: "src/Models/User.php" }]);
|
||||
expect(useModalsStore(pinia).current).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsing", () => {
|
||||
it("clamps and drops malformed ranges", () => {
|
||||
expect(readRanges([[2, 4], [9, 99], [5, 5], ["a", 1], [1], null], 10)).toEqual([
|
||||
[2, 4],
|
||||
[9, 10],
|
||||
]);
|
||||
expect(readRanges("x", 10)).toEqual([]);
|
||||
});
|
||||
|
||||
it("splits path marks at the file name and marks vendor as library", () => {
|
||||
expect(fileItem({ path: "vendor/a/Bc.php", matches: [[7, 12]] }, 0)).toMatchObject({
|
||||
label: "Bc.php",
|
||||
labelMatches: [[0, 3]],
|
||||
detail: "vendor/a/",
|
||||
detailMatches: [[7, 9]],
|
||||
library: true,
|
||||
line: null,
|
||||
});
|
||||
expect(fileItem({ path: "" }, 0)).toBeNull();
|
||||
expect(fileItem("nope", 0)).toBeNull();
|
||||
});
|
||||
|
||||
it("reads symbol items and drops bad ones", () => {
|
||||
expect(symbolItem({ name: "f", path: "a.php", line: -1, column: 1.5 }, 0, "f")).toMatchObject({
|
||||
label: "f",
|
||||
detail: "",
|
||||
line: null,
|
||||
column: null,
|
||||
kind: null,
|
||||
});
|
||||
expect(symbolItem({ name: 3, path: "a.php" }, 0, "f")).toBeNull();
|
||||
});
|
||||
|
||||
it("marks query characters in order, ignoring case", () => {
|
||||
expect(markSubsequence("UserRepository", "urep")).toEqual([
|
||||
[0, 1],
|
||||
[3, 4],
|
||||
[5, 7],
|
||||
]);
|
||||
expect(markSubsequence("$email", "$em")).toEqual([[1, 3]]);
|
||||
expect(markSubsequence("abc", "x")).toEqual([]);
|
||||
});
|
||||
|
||||
it("cuts text into marked segments", () => {
|
||||
expect(segments("abcdef", [[1, 3], [2, 4], [5, 9]])).toEqual([
|
||||
{ text: "a", mark: false },
|
||||
{ text: "bc", mark: true },
|
||||
{ text: "d", mark: true },
|
||||
{ text: "e", mark: false },
|
||||
{ text: "f", mark: true },
|
||||
]);
|
||||
expect(segments("", [])).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores a stale answer after the popup closed", async () => {
|
||||
const goto = useGotoStore(pinia);
|
||||
held = [];
|
||||
const queue = held;
|
||||
const pending = goto.show("file", "user");
|
||||
goto.hide();
|
||||
queue[0]?.resolve(null);
|
||||
await pending;
|
||||
expect(goto.items).toEqual([]);
|
||||
expect(goto.open).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -122,7 +122,7 @@ describe("en.json", () => {
|
|||
it("uses flat dotted keys of known areas with string values", () => {
|
||||
for (const [key, value] of Object.entries(en)) {
|
||||
expect(key).toMatch(
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|structure)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
);
|
||||
expect(typeof value).toBe("string");
|
||||
expect(value.trim()).not.toBe("");
|
||||
|
|
|
|||
|
|
@ -261,6 +261,9 @@ describe("CommandPalette", () => {
|
|||
"project.close",
|
||||
"palette.open",
|
||||
"find.open",
|
||||
"goto.classOpen",
|
||||
"goto.fileOpen",
|
||||
"goto.symbolOpen",
|
||||
"project.openDialog",
|
||||
"app.quit",
|
||||
"editor.reveal",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue