diff --git a/README.md b/README.md index 0595253..6b95a6e 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ claude mcp add lutra -- lutra mcp ## Status -**Pre-alpha (2026-10-16): M1 done.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; find in files, go to file/class/symbol and PHP language features come next. With M1 done, about 13 agent hours remain to the MVP (M2 and M3, estimated after calibrating on the first cycle). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, +**Pre-alpha (2026-10-16): M1 done.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 (under way) adds find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); PHP language features come next. With M1 done, about 13 agent hours remain to the MVP (M2 and M3, estimated after calibrating on the first cycle). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, [`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list. **First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files, diff --git a/ROADMAP.md b/ROADMAP.md index 2eebce5..1332a56 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha (M1 done)** · next: M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate)) -> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-17 · **Change:** minor (M2.7: Structure tool window) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-17 · **Change:** minor (M2.6: go-to popup) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md). @@ -13,7 +13,7 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in | | Value | Kind | |---|---|---| | **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **<1%** (project tool window, editor tabs; no inventory to count against yet) | estimated | -| **Feature depth** (weighted by use, scored by behaviour) | **~2.6%** (Editor core 10% × weight 12, Navigation 4% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Settings 7% × weight 1, of 101) | estimated | +| **Feature depth** (weighted by use, scored by behaviour) | **~3.2%** (Editor core 10% × weight 12, Navigation 10% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Settings 7% × weight 1, of 101) | estimated | | **To MVP (M3)** | **~13 h left** (M1 done in ~5.6 h measured: C1 2.5 h, C2 3.1 h; M2 ~5 h, M3 ~8 h); was ~190 h before calibration | estimated (×0.1; C1 factor 0.07, C2 factor 0.10) | | **To full parity** | **~330 h** if the speed of cycles C1 and C2 holds (range 300–3,300 h; deep areas such as type inference and inspections have no data yet) | estimated | @@ -25,7 +25,7 @@ Dimension hours overlap: language, framework and tooling hours are part of the f | Dimension | % | One agent (h) | Doc | |---|---:|---:|---| -| Features (depth) | ~2.6% | ~2,902 | [target-app-parity.md](docs/target-app-parity.md) | +| Features (depth) | ~3.2% | ~2,896 | [target-app-parity.md](docs/target-app-parity.md) | | UI/UX fidelity | 1% (est.) | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) | | PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) | | Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) | @@ -43,7 +43,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a |---|---:|---:| | Editor core (buffers, undo, multi-caret, folding, soft wrap) | 10% (est.) | ~104 | | Project view, VFS, file watching | 8% (est.) | ~40 | -| Navigation (go to class/file/symbol, recent files, structure) | 4% | ~108 | +| Navigation (go to class/file/symbol, recent files, structure) | 10% (est.) | ~102 | | Search and replace (in file, in project, structural) | 8% (est.) | ~70 | | Code completion | 0% | ~250 | | Inspections and quick-fixes | 0% | ~300 | @@ -76,6 +76,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | What landed | |---|---| +| 2026-10-17 | M2.6: go to any file, class or symbol by name: `Mod+P`, `Mod+Alt+C` and `Mod+T` open one popup with Files, Classes and Symbols tabs (Tab switches); results update as you type with the matched letters marked, library code is labelled, a hint shows while the index is still building, and Enter jumps there. Agents can open it with a query. | | 2026-10-17 | M2.7: a Structure tool window next to Project (new left stripe, `Mod+2`) shows the classes, functions, methods, properties and constants of the active PHP file as a tree that follows tabs and edits; click or Enter jumps to the declaration. The file is reparsed in the background, so big files never stall typing. | | 2026-10-17 | M2.4: Find in files has a window: `Mod+Alt+F` opens a bottom panel with the selection or the word at the cursor as the query; results stream in grouped by file with the hit highlighted, with match case, whole words, regex and file globs; Enter or a click jumps to the match; a new search cancels the old one. | | 2026-10-16 | M2.2: PHP files are highlighted (with the HTML around ` 0); + let library: Vec<&Value> = files["items"] + .as_array() + .unwrap() + .iter() + .map(|item| &item["library"]) + .collect(); + assert_eq!(library, vec![&json!(false), &json!(false), &json!(true)]); let classes = run(&mut engine, "goto.class", json!({"query": "user"})); assert_eq!( diff --git a/docs/architecture.md b/docs/architecture.md index 12f99c6..42bfd1d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index and the Structure tool window · **Last updated:** 2026-10-17 +> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup · **Last updated:** 2026-10-17 ## Overview @@ -252,7 +252,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - Queries: `Index` (a `BTreeMap` by path, so a directory's files drop with one range) answers `find_files`, `find_classes` and `find_symbols`. Every whitespace-separated query word must match fuzzily (fzf-style scoring, smart case, no other special syntax); queries are capped at 256 characters and 1,000 results. Files: a query without `/` (a `\` counts as `/`) is matched against the file name first with double weight, else the path; match ranges are merged UTF-16 ranges in the path. Classes: by name, by FQN when the query has a `\`. Symbols: by name; `Class::member` matches the container's short name (FQN with a `\`) and the member separately, `Class::` lists members. Order: project before library, higher score, shorter name, byte order. Indexes over 20,000 files plus symbols are scanned on `default_threads()` threads, each keeping its own best hits. - Engine (`cmd/goto.rs`): `State::index` holds the index of the open project. `goto::sync` runs on every `Engine::pump_vfs` and before every index command: it starts the build and the updater when a project is open and the index belongs to another root (or none), drops them without a project (dropping cancels the threads; `project.close` also drops it at once), merges up to 4,096 updates, emits `indexProgress {done, total}` at most every 250 ms while building and `indexReady {files, symbols, elapsedMs}` at the end, and re-indexes buffers. The engine lock is held only for inserts and queries; walking and parsing never run under it. Updater results that arrive while the build runs mark their paths, and later build results for those paths are ignored, so a buffer edit or a disk change is never overwritten by the stale build. - Incremental sources: `workspace::pump` hands the VFS events to `goto::note_disk_changes` (removed paths dropped at once, created or modified files re-read, created directories and rename targets rescanned); the watcher is not recursive, so only watched directories (root, listed, pinned) report changes. A buffer whose version changed is re-indexed from its text when its path is in the index (or the build still runs); while it is dirty, disk changes for it are ignored; closing it dirty re-reads the file. -- Commands: `index.status` → `{state: "idle"|"indexing", files, symbols}` (idle and zero without a project). `goto.file {query, limit?}` → `{items: [{path, score, matches: [[start, end]]}], indexing}`; `goto.class` → `{items: [{name, fqn, kind, path, line, column, library}], indexing}`; `goto.symbol` → the same plus `container` (FQN or `null`), for functions, methods, properties, constants and enum cases. `limit` defaults to 50 (at most 1,000); an empty query returns no items. The go-to commands are disabled without a project; none has a menu path or shortcut yet (M2.6 adds the popup). +- Commands: `index.status` → `{state: "idle"|"indexing", files, symbols}` (idle and zero without a project). `goto.file {query, limit?}` → `{items: [{path, score, matches: [[start, end]], library}], indexing}` (`library` added by M2.6, PM decision: vendor files, as in class and symbol items); `goto.class` → `{items: [{name, fqn, kind, path, line, column, library}], indexing}`; `goto.symbol` → the same plus `container` (FQN or `null`), for functions, methods, properties, constants and enum cases. `limit` defaults to 50 (at most 1,000); an empty query returns no items. The go-to commands are disabled without a project; none has a menu path or shortcut; the popup's UI commands do (below). - Measured (release, Windows 11, 8 cores / 16 threads, 15 workers, generated `lutra_testkit::generate_php_project(20_000)`: 20,001 files, 19,000 PHP of ~5 KB, 87.7 MB, 324,080 symbols): build 3.9–4.2 s on an idle machine (target < 5 s met), 4.6–5.7 s while other agents' builds ran; the walk takes 25–35 ms and the first batch arrives after ~30 ms, so the parse dominates (~21 MB/s over 15 workers, ~1.4 MB/s per worker). Queries on the full index, median of 7: `goto.class` 2–4 ms, `goto.symbol` 7–11 ms, `Class::member` 11–12 ms, `goto.file` 2 ms (single-threaded before the parallel scan: `goto.symbol` 72–100 ms). `cargo test --release -p lutra-index --test perf -- --ignored --nocapture` repeats it. - Live check over the control channel against the running app (debug build, port 7825, generated 6,002-file project with gitignored `vendor/` and `var/`): `index.status` answered `indexing` right after `project.open`, a go-to query during the build returned `indexing: true`, 25 `indexProgress` events at least 251 ms apart, `indexReady` after 8.2 s (debug build: the tree-sitter C code and the workers are unoptimised) with 6,002 files and 62,000 symbols; `goto.file`, `goto.class` (vendor marked `library`), `goto.symbol` with `Class::member` answered in 5–25 ms; the gitignored `var/` class was absent; a `buffer.edit` renaming a class and a file created on disk were found within a second; `project.close` reset the status to idle. @@ -263,6 +263,16 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - **UI:** `MainLayout.vue` has a left stripe (a vertical tab list, Lucide `FolderTree` and `ListTree`) with Project and Structure; the left tool window shows one of them, both stay mounted while it is open (`v-show`). Clicking the shown one's tab or running its command again hides the window. UI commands `view.toggleProjectTree` (`Mod+1`) and `view.toggleStructure` (`Mod+2`, Lutra's own). `ui/src/components/structure/structure.ts` (Pinia `structure`, started by the window) follows the editor's active tab and `outlineChanged` for that buffer, drops answers overtaken by a newer request, validates the untrusted outline (depth cap 64, at most 50,000 items) and remembers collapsed nodes per buffer by the path of kinds and names. `StructureToolWindow.vue` is a WAI-ARIA tree: kind icons from Lucide coloured with `--lt-syntax-*` tokens, the name and the signature; arrows, Home/End, Left/Right fold, Enter or a click jumps through `editor.reveal` to the start of the name; empty states for no file, no declarations, still parsing and too large. - **Measured** (release, Windows 11, generated 1 MB PHP file with 16,281 outline items, other builds running): `buffer.edit` under the lock at most 0.07–0.25 ms, `pump_vfs` at most 3.8 ms; first outline 0.9–1.3 s after `file.open` (full parse ~0.75 s plus outline); edit to `outlineChanged` 0.43–0.76 s (200 ms debounce, incremental reparse 9–14 ms, outline with JSON 0.2–0.3 s, pump interval). `syntax.outline` itself takes 82 ms on that file, because the engine deep-copies the stored JSON into the command result; typing is not blocked by it (the editor syncs asynchronously), but the engine lock is. Typical files (10–50 KB) are a few milliseconds end to end. `cargo test --release -p lutra-engine --test syntax -- --ignored --nocapture` repeats it. +### Go-to popup (M2.6) + +- `ui/src/components/goto/GotoPopup.vue` (mounted in `App.vue`) with the state in `ui/src/stores/goto.ts`. One popup, three modes (`file`, `class`, `symbol`) as tabs; Tab / Shift+Tab or a click switches the mode and re-runs the same text in it. +- UI commands `goto.fileOpen` (`Mod+P`), `goto.classOpen` (`Mod+Alt+C`), `goto.symbolOpen` (`Mod+T`), each with an optional `{query}` so an agent can open the popup on a query over `uiCommand`; enabled only while a project is open. The shortcuts are Lutra's own. +- Live query: typing waits 60 ms after the last keystroke, then runs the mode's `goto.*` with `limit: 100`; every query takes a sequence number, and an answer that is not the newest is dropped (also after the popup closed). Mode switches and a `{query}` from the params query at once. +- Rows: file items split `matches` at the file name (name marked in the label, directory in the second column); class and symbol answers carry no ranges, so the popup marks the query's characters in order in the name (after `::` for `Class::member`). The second column is the namespace, or the container for members. `library: true` rows are dimmed and labelled. Untrusted fields are checked; malformed items and ranges are dropped or clamped. +- Indexing: `indexing: true` shows a hint with the latest `indexProgress {done, total}`; `indexReady` re-runs the open query. +- Opening: Enter or a click closes the popup (focus goes back) and runs `editor.reveal` with `{path}` for files (the file's cursor stays) or `{path, line, column}` for symbols. The popup is an exclusive modal (`ModalId` `goto` in `commands/modals.ts`). Like the palette it is a launcher: running any command other than the three open commands closes it (`commands/store.ts` › `execute`), so an agent's `editor.reveal` never leaves it open. +- Live check (debug build, bundled UI, port 7826, temp project with 34 files and a `vendor/` folder): `goto.fileOpen {query: "user"}` listed the two project files before the vendor one with its `library` label; `goto.classOpen {query: "usr"}` and `goto.symbolOpen {query: "User::find"}` switched the tab with marks shown; `palette.open` then `goto.fileOpen` left only the popup; an `editor.reveal` of the symbol item closed the popup and put the cursor on `find`. `goto.file` answered in < 1 ms over the control channel. Enter and clicks cannot be sent over the control channel; Vitest covers them. + ## Decisions (M0) | Question | Decision | Why | @@ -280,6 +290,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | M2.6: go-to popup (store, debounce and stale drop, modes, `editor.reveal`), `library` on `goto.file` items | | 2026-10-17 | minor | M2.7: per-buffer syntax tree off the engine lock, `syntax.outline`, `outlineChanged`, left stripe, Structure tool window | | 2026-10-17 | minor | M2.5: symbol index (`crates/index`: parallel build, updater, fuzzy queries), `index.status`, `goto.file`/`goto.class`/`goto.symbol`, `indexProgress`/`indexReady` via the pump, timing | | 2026-10-17 | minor | M2.4: bottom panel, Find tool window (store, event race, one search at a time), `find.open` | diff --git a/docs/gaps.md b/docs/gaps.md index b379a16..10fc3c6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index and go-to commands); G14 English UI catalog in place · **Last updated:** 2026-10-17 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G14 English UI catalog in place · **Last updated:** 2026-10-17 Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. @@ -31,7 +31,7 @@ G11 progress: M1.7 added the crash-recovery journal: unsaved buffers are written G14 progress: M1.11 moved every UI string in `ui/src` into the English catalog `ui/src/i18n/en.json` behind `t(key, params?)`, enforced by `vue/no-bare-strings-in-template` and a catalog test. Messages the engine sends (`EngineError.message`, the slogan from `app.about`) are still English text; they need message keys with params before a second language can cover them. -G5 progress: M2.3 landed the find-in-files backend: `crates/search` (parallel walk with the project's ignore rules, literal or regex, case, whole word, globs, binary and size skips, match cap, cancel) and the engine commands `search.find` / `search.cancel` with streamed `searchResults` and `searchDone` events; dirty buffers are searched in their buffer text. First result on a generated 20k-file tree 10–43 ms (release, measured). M2.4 added the Find tool window in a new bottom panel (options, globs, grouped and highlighted results, counts, cancel, truncated hint, keyboard navigation, `editor.reveal`, `find.open` `Mod+Alt+F` with prefill). M2.5 added the first symbol index (`crates/index`: every project file, PHP declarations from tree-sitter outlines, vendor as library, parallel build off the engine lock, incremental on disk and buffer changes, cancelled on project close) and the commands `index.status`, `goto.file`, `goto.class`, `goto.symbol` with `indexProgress`/`indexReady` events; a generated 20k-file project (88 MB of PHP) indexes in 3.9–4.2 s (release, measured, target 5 s), queries take 2–12 ms. Open in G5: replace in files, scopes and history, the go-to popup (M2.6), an index that survives restarts, changes in directories the non-recursive watcher does not watch, usages. +G5 progress: M2.3 landed the find-in-files backend: `crates/search` (parallel walk with the project's ignore rules, literal or regex, case, whole word, globs, binary and size skips, match cap, cancel) and the engine commands `search.find` / `search.cancel` with streamed `searchResults` and `searchDone` events; dirty buffers are searched in their buffer text. First result on a generated 20k-file tree 10–43 ms (release, measured). M2.4 added the Find tool window in a new bottom panel (options, globs, grouped and highlighted results, counts, cancel, truncated hint, keyboard navigation, `editor.reveal`, `find.open` `Mod+Alt+F` with prefill). M2.5 added the first symbol index (`crates/index`: every project file, PHP declarations from tree-sitter outlines, vendor as library, parallel build off the engine lock, incremental on disk and buffer changes, cancelled on project close) and the commands `index.status`, `goto.file`, `goto.class`, `goto.symbol` with `indexProgress`/`indexReady` events; a generated 20k-file project (88 MB of PHP) indexes in 3.9–4.2 s (release, measured, target 5 s), queries take 2–12 ms. M2.6 added the go-to popup (Files / Classes / Symbols tabs, `Mod+P`, `Mod+Alt+C`, `Mod+T`, live fuzzy results with marked characters, library rows labelled, indexing hint, `editor.reveal`). Open in G5: replace in files, scopes and history, go-to extras (recent files on an empty query, a non-project toggle, `:line`, file-type filter), an index that survives restarts, changes in directories the non-recursive watcher does not watch, usages. Known smaller items from M0: @@ -43,6 +43,7 @@ Known smaller items from M0: | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | G5: go-to popup (M2.6) | | 2026-10-17 | minor | G4: Structure tool window (M2.7); G12: raw-JSON command results | | 2026-10-17 | minor | G5: symbol index and go-to commands (M2.5) | | 2026-10-17 | minor | G5: Find tool window (M2.4) | diff --git a/docs/roadmap.md b/docs/roadmap.md index 6cf86a4..7c29651 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -8,7 +8,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t |---|---|---|---:| | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) | | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) | -| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | in progress (C3: M2.2 highlighting and `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.7 Structure tool window) | ~5 | +| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | in progress (C3: M2.2 highlighting and `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index, M2.6 go-to popup, M2.7 Structure tool window) | ~5 | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | | M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 | @@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | M2.6 go-to popup | | 2026-10-17 | minor | M2.7 Structure tool window | | 2026-10-17 | minor | M2.4 Find tool window | | 2026-10-16 | minor | M2 in progress: M2.2 highlighting and `editor.reveal` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a87ad69..8bc9746 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity -> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and go-to commands, the Structure tool window · **Last updated:** 2026-10-17 · **Target:** PhpStorm 2026.x +> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window · **Last updated:** 2026-10-17 · **Target:** PhpStorm 2026.x ## How this is measured @@ -14,7 +14,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour |---|---:|---:|---|---:|---| | Editor core | 12 | 10% (est.) | semantic highlighting and a colour scheme editor, code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~104 (est.) | M2.2: syntax highlighting by file extension (`ui/src/components/editor/language.ts`): PHP with embedded HTML/CSS/JS through `@codemirror/lang-php` (Lezer), plus HTML, CSS, JS/TS, JSON, YAML, Markdown; spans carry `lt-syntax-*` classes coloured only by the eleven `--lt-syntax-*` tokens of both themes (Lutra's own palette, ≥ 4.5:1 on the editor background and active line, contrast test). `editor.reveal {path, line, column}` opens, activates, places the cursor (UTF-16 column, CRLF-safe) and centres it; agents reach it as a UI command. Checked in the app on Windows 11 (bundled UI, control channel): PHP with embedded HTML in dark and light, `editor.reveal` into a closed CRLF file (last line, then line 302 centred). Vitest: language per extension, classes on spans for PHP/HTML and the other languages, reveal on open and closed files, CRLF mapping, clamping, bad params. keystroke to highlight on a 1 MB PHP file 3.0–11.4 ms median (jsdom, JavaScript work only, measured, not yet in the WebView). M2.1: `crates/syntax` parses PHP with tree-sitter (incremental reparse from `lutra_text` edits) and computes folding ranges (brace blocks, arrays, comments, heredocs, `use` runs); library only, nothing visible in the editor yet, so the score is unchanged. Tests: outline/folding snapshots for five PHP 8.3 fixtures, proptests (random bytes and token soups never panic, reparse equals a fresh parse, undo round trip). 1 MB parse 364–553 ms, reparse after one keystroke 7–11 ms (release, measured, machine busy). M1.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `/recovery//` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) | | Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). M1.12: a folder that cannot be opened from the picker or the command line (including `unsaved_changes` when switching projects) and stopped file watching show as toasts instead of stderr (`apps/lutra-desktop/src/host.rs`, `ui/src/stores/notifications.ts`, `ui/tests/notifications/`, 19 Vitest tests; live check pending, gaming mode); score unchanged. Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not | -| Navigation | 10 | 4% (est.) | the go-to popup (M2.6), find usages, go to declaration, recent files and locations, navigation history, File Structure popup, Structure speed search, sorting and filters (visibility, inherited members), autoscroll from the caret, navigation bar, bookmarks (M1.8: a command palette over commands only; M2.5: go-to backend without UI) | ~108 (est.) | M2.7: Structure tool window (`ui/src/components/structure/`) in a new left stripe with Project | Structure: the active tab's outline as a tree with Lucide kind icons and signatures, follows the active tab and edits (`outlineChanged`), click or Enter jumps through `editor.reveal`, arrows fold, `view.toggleStructure` `Mod+2`; engine `syntax.outline {id}` from a per-buffer tree-sitter tree reparsed off the engine lock on a worker thread (200 ms debounce). Tests: 11 engine unit tests, engine integration tests with a proptest of random edit sequences (end at a fresh parse's outline), a control-channel test (`crates/control/tests/syntax.rs`), 13 Vitest tests (`ui/tests/structure/`). Checked in the app on Windows 11 (bundled UI, control port 7827): a class file with namespace, interface, enum, trait, class with promoted property and a function; `outlineChanged` 149 ms after `file.open`, `view.toggleStructure` shows the tree, a jump to `find` centres line 62, an added method appears about 0.3 s after `buffer.edit` (debug build). Rows were not clicked in the app (the control channel has no input method); click and Enter are covered by Vitest. 1 MB file: `buffer.edit` ≤ 0.25 ms and `pump_vfs` ≤ 3.8 ms under the lock, edit to `outlineChanged` 0.43–0.76 s, `syntax.outline` 82 ms (release, measured). Graded against `plan/phpstorm/09-structure.md`. M2.5: symbol index in `crates/index` (every project file listed, `.php` parsed in parallel from tree-sitter outlines, vendor marked library, incremental on disk and buffer changes, capped at 200,000 files) and the engine commands `index.status`, `goto.file`, `goto.class`, `goto.symbol` (fuzzy, file names weighted, `Class::member`, project before library, partial results with `indexing: true`), events `indexProgress`/`indexReady`; 20k-file / 88 MB generated project indexed in 3.9–4.2 s (release, measured), queries 2–12 ms; tests `crates/index/tests/`, `crates/engine/tests/goto.rs`, `crates/control/tests/goto.rs`; not reachable from the UI yet (M2.6). M2.1: file outline in `crates/syntax` (namespaces braced and unbraced, classes, interfaces, traits, enums with cases, functions, methods, properties incl. promoted ones, constants; UTF-16 ranges and short signatures), the base for the Structure window (M2.7) and the symbol index (M2.5); not reachable from the UI yet, score unchanged. M1.8: `ui/src/components/palette/`, `ui/src/commands/` (fuzzy ranking, recent commands, global keymap), Vitest `ui/tests/palette/`, `ui/tests/commands/` | +| Navigation | 10 | 10% (est.) | go-to: recent files on an empty query, a non-project toggle (library items always show), file-type filter, `:line` suffixes, actions and text tabs, sending the list to Find; find usages, go to declaration, recent files and locations, navigation history, File Structure popup, Structure speed search, sorting and filters (visibility, inherited members), autoscroll from the caret, navigation bar, bookmarks (M1.8: a command palette over commands only) | ~102 (est.) | M2.6: go-to popup `ui/src/components/goto/` with Files / Classes / Symbols tabs (Tab and Shift+Tab or a click switch, the text stays), UI commands `goto.fileOpen` `Mod+P`, `goto.classOpen` `Mod+Alt+C`, `goto.symbolOpen` `Mod+T` (optional `{query}` for agents), live query against `goto.*` (60 ms debounce, stale answers dropped), matched characters marked, directory / namespace / container column, library rows dimmed and labelled (`goto.file` items now carry `library`), an indexing hint with progress and a re-query on `indexReady`, Enter or a click opens through `editor.reveal`, Escape closes, one modal at a time; Vitest `ui/tests/goto/`, live-checked in the app (port 7826). M2.7: Structure tool window (`ui/src/components/structure/`) in a new left stripe with Project | Structure: the active tab's outline as a tree with Lucide kind icons and signatures, follows the active tab and edits (`outlineChanged`), click or Enter jumps through `editor.reveal`, arrows fold, `view.toggleStructure` `Mod+2`; engine `syntax.outline {id}` from a per-buffer tree-sitter tree reparsed off the engine lock on a worker thread (200 ms debounce). Tests: 11 engine unit tests, engine integration tests with a proptest of random edit sequences (end at a fresh parse's outline), a control-channel test (`crates/control/tests/syntax.rs`), 13 Vitest tests (`ui/tests/structure/`). Checked in the app on Windows 11 (bundled UI, control port 7827): a class file with namespace, interface, enum, trait, class with promoted property and a function; `outlineChanged` 149 ms after `file.open`, `view.toggleStructure` shows the tree, a jump to `find` centres line 62, an added method appears about 0.3 s after `buffer.edit` (debug build). Rows were not clicked in the app (the control channel has no input method); click and Enter are covered by Vitest. 1 MB file: `buffer.edit` ≤ 0.25 ms and `pump_vfs` ≤ 3.8 ms under the lock, edit to `outlineChanged` 0.43–0.76 s, `syntax.outline` 82 ms (release, measured). Graded against `plan/phpstorm/09-structure.md`. M2.5: symbol index in `crates/index` (every project file listed, `.php` parsed in parallel from tree-sitter outlines, vendor marked library, incremental on disk and buffer changes, capped at 200,000 files) and the engine commands `index.status`, `goto.file`, `goto.class`, `goto.symbol` (fuzzy, file names weighted, `Class::member`, project before library, partial results with `indexing: true`), events `indexProgress`/`indexReady`; 20k-file / 88 MB generated project indexed in 3.9–4.2 s (release, measured), queries 2–12 ms; tests `crates/index/tests/`, `crates/engine/tests/goto.rs`, `crates/control/tests/goto.rs`; reached from the UI by M2.6. M2.1: file outline in `crates/syntax` (namespaces braced and unbraced, classes, interfaces, traits, enums with cases, functions, methods, properties incl. promoted ones, constants; UTF-16 ranges and short signatures), the base for the Structure window (M2.7) and the symbol index (M2.5); not reachable from the UI yet, score unchanged. M1.8: `ui/src/components/palette/`, `ui/src/commands/` (fuzzy ranking, recent commands, global keymap), Vitest `ui/tests/palette/`, `ui/tests/commands/` | | Search and replace | 6 | 8% (est.) | find in the current file, replace in files and in a file, scopes (module, directory, open files, custom), comment/string filters, search history, a tab per search, grouping options, merging matches on one line, find in path from the tree, structural search | ~70 (est.) | M2.4 Find tool window in a new resizable, collapsible bottom panel: query with case / whole word / regex toggles, include and exclude globs, streamed results grouped by file (sorted) with the match highlighted in the line preview, counts and elapsed time, cancel, a truncated hint, a refused regex or glob shown in place; Enter or click opens the match through `editor.reveal`, arrow keys / Page / Home / End walk the results; `find.open` (`Mod+Alt+F`, Lutra's own) prefills the selection or the word at the cursor, `find.open {query}` from an agent searches at once; a new search cancels the running one. Tests: 26 Vitest store and component tests (`ui/tests/find/FindToolWindow.test.ts`). Live check (bundled-ui debug build, control port 7824, 3-file temp project): `find.open {query}` over `uiCommand` showed 14 matches in 3 files (vendor included) grouped and highlighted in 17 ms; with `*.php` include 2 matches; revealing a result's position opened the file at the match; `find.open` without params prefilled the word at the cursor; a bad regex showed the engine's message in place (screenshots read, measured). Opening a result by mouse or Enter is covered by Vitest only (the control channel cannot click). M2.3 backend: `crates/search` (parallel `ignore` walk + `grep-searcher`: literal/regex, case, whole word, include/exclude globs, project ignore rules with `vendor/` searched and `node_modules` skipped, binary and > 8 MiB files skipped, match cap, cancel) and engine `search.find` / `search.cancel` with `searchResults` / `searchDone` events through the pump; dirty buffers are searched in their buffer text. Tests: 9 library tests incl. a property test of random queries and file bytes (`crates/search/tests/search.rs`), 3 preview/column unit tests, 4 engine tests (`crates/engine/tests/search.rs`), a TCP control-channel test (find → results → done, invalid regex, cancel; `crates/control/tests/search.rs`). 20k-file generated tree, release: first result 10–43 ms, full walk 0.66–1.43 s (measured); live over the control channel against the running app: first result 55 ms, done 386 ms on a 5,900-file project (debug build, measured) | | Code completion | 10 | 0% | everything | ~250 (est.) | — | | Inspections and quick-fixes | 8 | 0% | everything | ~300 (est.) | — | @@ -63,6 +63,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated); | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | M2.6: Navigation 4% → 10% (est.), go-to popup; hours 108 → 102 | | 2026-10-17 | minor | M2.7: Navigation 0% → 4% (est.), Structure tool window; hours 112 → 108 | | 2026-10-17 | minor | M2.5: Navigation evidence (symbol index and go-to commands, no UI), score unchanged at 0%, hours 120 → 112 | | 2026-10-17 | minor | M2.4: Search and replace 0% → 8% (est.), Find tool window; hours 76 → 70 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d3c881b..a921e25 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity checklist -> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), left stripe and Structure tool window (M2.7) · **Last updated:** 2026-10-17 +> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7) · **Last updated:** 2026-10-17 - [ ] Main window: tool window stripes, editor area, status bar, navigation bar - M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence. @@ -27,6 +27,8 @@ - [ ] Structure tool window - M2.7 (2026-10-17): in the left tool window, chosen from the new stripe (Project | Structure); the active tab's declarations (namespaces, class-likes, functions, methods, properties, constants, enum cases) as a WAI-ARIA tree with Lucide kind icons in syntax colours and the short signature; follows the active tab and edits; click or Enter jumps to the name (`editor.reveal`), arrows walk and fold, collapsed nodes kept per file; empty states for no file, no declarations, still reading, too large. `view.toggleStructure` `Mod+2`. Checked in the app on Windows 11 over the control channel (tree, jump to a method, tree updated after an edit; no clicks, the control channel cannot send input). Missing: speed search, sorting and filters, visibility markers, inherited members, autoscroll from the caret, the File Structure popup, VCS colours, running tests from an entry. - [ ] Problems tool window +- [ ] Go to file / class / symbol popup + - M2.6 (2026-10-17): one popup with Files / Classes / Symbols tabs (Tab / Shift+Tab or a click; the text stays), opened by `goto.fileOpen` `Mod+P`, `goto.classOpen` `Mod+Alt+C`, `goto.symbolOpen` `Mod+T` (Lutra's own keys) or by an agent with `{query}`; live fuzzy results (60 ms debounce, stale answers dropped) with matched characters marked, a Lucide icon per kind, the directory, namespace or container beside the name, library (vendor) rows dimmed with a label; an indexing hint with progress, re-queried on `indexReady`; arrows / Page keys move, Enter or a click opens through `editor.reveal`, Escape or a click outside closes; an exclusive modal. Checked in the running app. Missing: recent files on an empty query, a non-project toggle, file-type filter, `:line` suffixes, preview, more tabs (actions, text), sending results to Find. - [ ] Find tool window - M2.4 (2026-10-17): docked in the new bottom panel (resizable by pointer and keyboard, collapses to its header, closes; results kept while closed). Query field with case / whole word / regex toggles (`aria-pressed`), include and exclude globs, status line with counts and time, cancel, truncated hint, refused query as an alert; results grouped by file with the match highlighted, a listbox with keyboard navigation; Enter or click reveals the match. `find.open` `Mod+Alt+F`. Missing: tabs per search, grouping options, a preview pane, expand/collapse per file, rerun and next/previous occurrence buttons, context menu, export, history. - [ ] Terminal tool window @@ -36,6 +38,7 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | Go-to popup partial (M2.6) | | 2026-10-17 | minor | Structure tool window partial, left stripe (M2.7) | | 2026-10-17 | minor | Find tool window partial, bottom panel (M2.4) | | 2026-10-16 | minor | Editor syntax highlighting partial; `editor.reveal` (M2.2) | diff --git a/ui/src/App.vue b/ui/src/App.vue index 0f13c7a..01b1a30 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -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(() => { + diff --git a/ui/src/commands/modals.ts b/ui/src/commands/modals.ts index cda8e42..51bba41 100644 --- a/ui/src/commands/modals.ts +++ b/ui/src/commands/modals.ts @@ -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", () => { diff --git a/ui/src/commands/store.ts b/ui/src/commands/store.ts index 0b57c3c..43b003a 100644 --- a/ui/src/commands/store.ts +++ b/ui/src/commands/store.ts @@ -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 { diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index 2c4c88e..fbdcfec 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -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" }, diff --git a/ui/src/components/goto/GotoPopup.vue b/ui/src/components/goto/GotoPopup.vue new file mode 100644 index 0000000..bfcc38b --- /dev/null +++ b/ui/src/components/goto/GotoPopup.vue @@ -0,0 +1,563 @@ + + + + + diff --git a/ui/src/components/goto/marks.ts b/ui/src/components/goto/marks.ts new file mode 100644 index 0000000..334e7f2 --- /dev/null +++ b/ui/src/components/goto/marks.ts @@ -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; +} diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index fba0390..7005cd8 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -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}", diff --git a/ui/src/ipc.ts b/ui/src/ipc.ts index f60542d..c3f0b2e 100644 --- a/ui/src/ipc.ts +++ b/ui/src/ipc.ts @@ -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. */ diff --git a/ui/src/stores/goto.ts b/ui/src/stores/goto.ts new file mode 100644 index 0000000..47c0b04 --- /dev/null +++ b/ui/src/stores/goto.ts @@ -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 = { + 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; + 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; + 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("file"); + /** What the user typed. */ + const query = ref(""); + /** The rows of the newest answer. */ + const items = ref([]); + /** 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(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 | null = null; + /** Ends the event subscription; set while started. */ + let unsubscribe: (() => void) | null = null; + + /** The selected row, if any. */ + const current = computed(() => 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 { + 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(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 { + 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, + }; +}); diff --git a/ui/tests/goto/GotoPopup.test.ts b/ui/tests/goto/GotoPopup.test.ts new file mode 100644 index 0000000..4a3e3c2 --- /dev/null +++ b/ui/tests/goto/GotoPopup.test.ts @@ -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 }[]; +/** Answers of the go-to commands by command id; a function answers per query. */ +let answers: Map) => 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 { + for (const listener of listeners) { + listener(payload); + } + await flushPromises(); +} + +/** Waits out the debounce and lets the answers arrive. */ +async function settle(): Promise { + 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 { + 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 { + 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 { + 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[] { + 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 }) => { + 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); + }); +}); diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 60f76c4..daba624 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -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(""); diff --git a/ui/tests/palette/CommandPalette.test.ts b/ui/tests/palette/CommandPalette.test.ts index 0e43efb..a07905b 100644 --- a/ui/tests/palette/CommandPalette.test.ts +++ b/ui/tests/palette/CommandPalette.test.ts @@ -261,6 +261,9 @@ describe("CommandPalette", () => { "project.close", "palette.open", "find.open", + "goto.classOpen", + "goto.fileOpen", + "goto.symbolOpen", "project.openDialog", "app.quit", "editor.reveal",