PM: merge M2.4 Find tool window
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
7811dc2925
16 changed files with 1923 additions and 25 deletions
10
ROADMAP.md
10
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-16 · **Change:** minor (M2.2: syntax highlighting, `editor.reveal`) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-17 · **Change:** minor (M2.4: Find tool window) · **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) | **~1.7%** (Editor core 10% × weight 12, Project view 8% × weight 6, Settings 7% × weight 1, of 101) | estimated |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~2.2%** (Editor core 10% × weight 12, 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) | ~1.6% | ~2,920 | [target-app-parity.md](docs/target-app-parity.md) |
|
||||
| Features (depth) | ~2.2% | ~2,914 | [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) |
|
||||
|
|
@ -44,7 +44,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) | 0% | ~120 |
|
||||
| Search and replace (in file, in project, structural) | 0% | ~80 |
|
||||
| Search and replace (in file, in project, structural) | 8% (est.) | ~70 |
|
||||
| Code completion | 0% | ~250 |
|
||||
| Inspections and quick-fixes | 0% | ~300 |
|
||||
| Refactoring | 0% | ~250 |
|
||||
|
|
@ -76,6 +76,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
|||
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 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 `<?php` blocks), and so are HTML, CSS, JS/TS, JSON, YAML and Markdown, in Lutra's own colours for both themes, each readable at 4.5:1 or better; `editor.reveal` jumps to a file position for the coming Find, Go-to and Structure windows and for agents. |
|
||||
| 2026-10-16 | M1.9b, M1 done: a settings dialog (`Mod+,`) built from the engine's settings, with search, a control per type, reset to default and inline errors; changes apply at once and follow edits from agents live; the theme picker switches at once and the editor font size applies to the editor. |
|
||||
| 2026-10-16 | M1.8: a command palette (`Mod+Shift+P`) finds every command by fuzzy match, recent ones first, with shortcuts shown and unavailable ones dimmed; one global keymap serves engine and UI commands (`Mod+1` toggles the project tree); agents can trigger UI commands over the control channel. |
|
||||
|
|
@ -92,6 +93,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-17 | minor | M2.4: Search and replace 8%, feature depth ~2.2% |
|
||||
| 2026-10-16 | minor | M2.2: Editor core 10%, feature depth ~1.7% |
|
||||
| 2026-10-16 | minor | Cycle C2 review: M1 measured at ~5.6 h, C2 factor 0.10 confirms ×0.1 |
|
||||
| 2026-10-16 | minor | M1.9b: M1 done, stage line, Settings row 7% (est.), progress log |
|
||||
|
|
|
|||
|
|
@ -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 · **Last updated:** 2026-10-16
|
||||
> **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 and the Find tool window · **Last updated:** 2026-10-17
|
||||
|
||||
## Overview
|
||||
|
||||
|
|
@ -176,7 +176,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- **Listing:** `listCommands` returns one list in id order: engine commands and UI commands. `CommandInfo` has `ui: bool`; UI commands also carry `labelKey`, use it as `label` (the engine has no English for them) and are always `enabled` as far as the engine knows.
|
||||
- **Running from outside:** `Engine::execute` on a UI command id queues `uiCommand {id, params}` and returns `null` (params are passed on unchanged). The desktop publishes the event to the window and to control subscribers like any other. The frontend runs the command, so `engine.execute palette.open` over the control channel opens the palette. A `uiCommand` the frontend cannot run (no handler, or disabled) becomes a warning toast.
|
||||
- **Frontend:** `ui/src/commands/`:
|
||||
- `uiCommands.ts` lists the UI commands: `editor.reveal` (no shortcut, M2.2), `palette.open` `Mod+Shift+P`, `settings.open` `Mod+,`, `view.toggleProjectTree` `Mod+1`.
|
||||
- `uiCommands.ts` lists the UI commands: `editor.reveal` (no shortcut, M2.2), `find.open` `Mod+Alt+F` (M2.4), `palette.open` `Mod+Shift+P`, `settings.open` `Mod+,`, `view.toggleProjectTree` `Mod+1`.
|
||||
- `keymap.ts` parses Lutra notation and matches by key code (letters, digits and US punctuation by `code`, so Alt and Shift layout effects don't matter). It also formats shortcuts for display with catalog modifier names.
|
||||
- `rank.ts` ranks for the palette.
|
||||
- `store.ts` (Pinia `commands`) holds the merged list, the keymap, the handlers and the recent commands.
|
||||
|
|
@ -232,6 +232,17 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- Engine: `search.find {query, regex?, caseSensitive?, wholeWord?, include?, exclude?, maxResults?}` (disabled without a project) snapshots the text of every dirty buffer as an overlay (searched instead of the file; only for files the walk visits), starts the search and returns `{searchId}` at once. Searches run outside the engine lock. Each search's results wait in its own channel in `State::searches`; `Engine::pump_vfs` drains them (`cmd::search::pump`) into `searchResults` events (one per file) and a final `searchDone`. Hosts already publish the pump's events, so the desktop (pump every 100 ms) and the control channel get them without new plumbing; there are at most 10 batches per second and at most 500 `searchResults` per pump (`MAX_RESULTS_PER_PUMP`), which keeps a control subscriber's queue of 4096 events from overflowing; the rest wait for the next pump. `search.cancel {searchId}` returns `{cancelled}` (false once the search ended) and the search still ends with `searchDone {cancelled: true}`. Starting a search does not cancel older ones. A search whose project is no longer open is cancelled by the next pump, its remaining results are dropped and it ends with `cancelled: true`.
|
||||
- Measured (release, Windows 11, 16 threads, generated 20,006-file tree from `lutra_testkit::generate_search_tree`, other builds running): common literal `function` first result 10–43 ms, capped at 10,000 matches after 112–209 ms; a rare literal (full walk, 376 files) first result 17–22 ms, total 0.66–1.43 s (the first round cold); `function` with the 100,000 cap 0.53 s. Through the engine add up to one pump interval (100 ms) before results reach clients. Live check over the control channel against the running app (debug build, 5,900-file project with a dirty buffer): `search.find` answered in 4.5 ms, first `searchResults` line after 55 ms, `searchDone` after 386 ms; vendor hits present, `var/`, `node_modules` and the binary file absent; the dirty buffer's text was found; `search.cancel` ended a search with `cancelled: true`.
|
||||
|
||||
### Find tool window (M2.4)
|
||||
|
||||
- **Bottom panel:** `ui/src/components/layout/BottomPanel.vue`, under the editor and the left tool window, above the status bar: header with title, collapse/expand and close; a splitter on the top edge (pointer, or Up/Down with Shift for larger steps; 80–900 px, at most 75 % of the window). Height is view state of `MainLayout.vue`; later bottom tool windows (Problems, Terminal) reuse it. Only Find lives there today, so the panel shows while the Find store's `visible` is set; a tab strip comes with the second tool window.
|
||||
- **Store:** `ui/src/stores/find.ts` (Pinia `find`, started by the main layout) holds the query, the options (`regex`, `caseSensitive`, `wholeWord`, include/exclude as comma-separated globs), the current `searchId`, the files with their matches (a `shallowRef`, replaced per event, kept sorted by path because files arrive in no fixed order), the `searchDone` summary and an inline error.
|
||||
- **One search at a time:** a new search cancels the running one with `search.cancel` (the engine does not); results of other searches are ignored, and the answer of a search overtaken by a newer one is dropped and cancelled.
|
||||
- **Event race:** events and the `search.find` answer travel on different channels (Tauri event vs. invoke response), and the pump may publish results before the answer arrives. While `search.find` has not answered, search events are held (at most 5,000) and replayed for the returned id.
|
||||
- **Errors:** a refused search (`invalid_params` for a bad regex or glob) shows its message under the fields (`role="alert"`, `aria-invalid`), not as a toast.
|
||||
- **Untrusted fields:** non-integer positions or a non-string preview drop the match; the highlight is clamped into the preview. `projectOpened`/`projectClosed` clear everything.
|
||||
- **Window:** `ui/src/components/find/FindToolWindow.vue`. Enter in a field searches, a toggle repeats the last search, cancel while running. The status line shows counts while streaming, then matches, files and elapsed time, "No matches" or "Cancelled"; a truncated search adds a hint. Results are a listbox with `aria-activedescendant`: file headers (name, directory, count) and one option per match (1-based line number, preview without leading indentation, the match in a `<mark>` with `--lt-editor-match-bg`). Down in a field enters the list; Up/Down, Page Up/Down (10), Home, End move; Enter or a click runs `editor.reveal {path, line, column}` through the command store. Every match is rendered; with the default cap of 10,000 that stays a plain DOM list (virtual scrolling is a follow-up if it shows up as slow).
|
||||
- **`find.open`** (UI command, `Mod+Alt+F`, Lutra's own; provided by `MainLayout.vue`, so it works before the panel exists): shows and expands the panel and focuses and selects the query field. Without params it takes the main selection (single line, at most 1,000 characters) or else the word at the cursor of the active editor state (`prefillFrom`), and waits for Enter. With a string `query` (and optional `regex`, `caseSensitive`, `wholeWord`, `include`, `exclude`), as an agent sends it through `uiCommand`, it searches at once. The panel is a tool window, not a modal: it is not part of the modal rule.
|
||||
|
||||
## Decisions (M0)
|
||||
|
||||
| Question | Decision | Why |
|
||||
|
|
@ -249,6 +260,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-17 | minor | M2.4: bottom panel, Find tool window (store, event race, one search at a time), `find.open` |
|
||||
| 2026-10-16 | minor | M2.2: highlighting by file extension (Lezer), `--lt-syntax-*` tokens and classes, `editor.reveal`, keystroke-to-highlight measurement |
|
||||
| 2026-10-16 | minor | M2.3: find in files backend (`crates/search`, `search.find`/`search.cancel`, `searchResults`/`searchDone` via the pump) |
|
||||
| 2026-10-16 | minor | M2.1: syntax layer (tree-sitter PHP parser, incremental reparse, outline, folding, size cap, timing) |
|
||||
|
|
|
|||
|
|
@ -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); G14 English UI catalog in place · **Last updated:** 2026-10-16
|
||||
> **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); G5 under way (search backend, Find tool window); 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). Open in G5: the Find tool window (M2.4), replace in files, the symbol index and go-to (M2.5, M2.6).
|
||||
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). Open in G5: scopes, history and replace in files, the symbol index and go-to (M2.5, M2.6).
|
||||
|
||||
Known smaller items from M0:
|
||||
|
||||
|
|
@ -43,6 +43,7 @@ Known smaller items from M0:
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-17 | minor | G5: Find tool window (M2.4) |
|
||||
| 2026-10-16 | minor | G4: Lezer highlighting and `editor.reveal` (M2.2) |
|
||||
| 2026-10-16 | minor | G5: find-in-files backend (M2.3) |
|
||||
| 2026-10-16 | minor | G4 note: tree-sitter syntax library, outline and folding (M2.1) |
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Milestones
|
||||
|
||||
> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-16
|
||||
> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-17
|
||||
|
||||
Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 are scaled ×0.1; M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value).
|
||||
|
||||
|
|
@ -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`) | ~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) | ~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.4 Find tool window |
|
||||
| 2026-10-16 | minor | M2 in progress: M2.2 highlighting and `editor.reveal` |
|
||||
| 2026-10-16 | minor | Cycle C2 review: M1 hours measured |
|
||||
| 2026-10-16 | minor | M1.9b settings dialog; M1 done |
|
||||
|
|
|
|||
|
|
@ -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 · **Last updated:** 2026-10-16 · **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 · **Last updated:** 2026-10-17 · **Target:** PhpStorm 2026.x
|
||||
|
||||
## How this is measured
|
||||
|
||||
|
|
@ -15,7 +15,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 `<data_dir>/recovery/<project-id>/` 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 | 0% | everything (M1.8: a command palette over commands only, no go-to-file/class/symbol yet; score unchanged) | ~120 (est.) | 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 | 0% (est.) | everything a user sees: Find in Files tool window (M2.4), replace in files, scopes, file masks UI, search history, find in path from the tree, structural search; the backend below has no UI yet, so the score stays 0% | ~76 (est.) | 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) |
|
||||
| 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.) | — |
|
||||
| Refactoring | 7 | 0% | everything | ~250 (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.4: Search and replace 0% → 8% (est.), Find tool window; hours 76 → 70 |
|
||||
| 2026-10-16 | minor | M2.2: Editor core 9% → 10% (est.), syntax highlighting and `editor.reveal` |
|
||||
| 2026-10-16 | minor | M2.3: Search and replace evidence (find-in-files backend, no UI), score unchanged at 0%, hours 80 → 76 |
|
||||
| 2026-10-16 | minor | M2.1: Editor core and Navigation evidence (tree-sitter parse, outline, folding library), scores unchanged |
|
||||
|
|
|
|||
|
|
@ -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) · **Last updated:** 2026-10-16
|
||||
> **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) · **Last updated:** 2026-10-17
|
||||
|
||||
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
||||
- M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4).
|
||||
|
|
@ -26,6 +26,7 @@
|
|||
- [ ] Structure tool window
|
||||
- [ ] Problems tool window
|
||||
- [ ] 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
|
||||
- [ ] Git tool window
|
||||
|
||||
|
|
@ -33,6 +34,7 @@
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-17 | minor | Find tool window partial, bottom panel (M2.4) |
|
||||
| 2026-10-16 | minor | Editor syntax highlighting partial; `editor.reveal` (M2.2) |
|
||||
| 2026-10-16 | patch | Palette and restore dialog: modal rule, restore dialog follows outside restores (M1.15) |
|
||||
| 2026-10-16 | minor | Settings dialog partial; theme picker and editor font size (M1.9b) |
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export interface UiCommandSpec {
|
|||
/** The frontend's UI commands. */
|
||||
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: "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" },
|
||||
|
|
|
|||
566
ui/src/components/find/FindToolWindow.vue
Normal file
566
ui/src/components/find/FindToolWindow.vue
Normal file
|
|
@ -0,0 +1,566 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The Find tool window (M2.4), shown in the bottom panel: a query field
|
||||
* with case, whole-word and regex toggles, include and exclude globs
|
||||
* (comma-separated), a status line with counts, and the results grouped by
|
||||
* file with the match highlighted in the line preview.
|
||||
*
|
||||
* - **Searching:** Enter in any field or the search button starts a search;
|
||||
* toggling an option repeats the last one. The cancel button stops a
|
||||
* running search. A refused query (bad regex or glob) shows its message
|
||||
* under the fields.
|
||||
* - **Results:** a listbox of matches; Up/Down, Page Up/Down, Home and End
|
||||
* move the selection, Down in a field moves into the list. Enter or a
|
||||
* click opens the match through the command `editor.reveal`.
|
||||
* - State lives in the Find store (`stores/find.ts`), so the results survive
|
||||
* closing the panel.
|
||||
*/
|
||||
import { CaseSensitive, CircleStop, Regex, Search, WholeWord } from "@lucide/vue";
|
||||
import { computed, nextTick, onMounted, ref, watch } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { baseName } from "../../stores/editor";
|
||||
import { useFindStore, type FindMatch, type FindRow } from "../../stores/find";
|
||||
|
||||
const find = useFindStore();
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** The query field. */
|
||||
const queryInput = ref<HTMLInputElement | null>(null);
|
||||
/** The result list. */
|
||||
const list = ref<HTMLElement | null>(null);
|
||||
|
||||
/** Rows moved by Page Up and Page Down. */
|
||||
const PAGE = 10;
|
||||
|
||||
/** The status line under the fields. */
|
||||
const status = computed(() => {
|
||||
const counts = { matches: String(find.matchCount), files: String(find.files.length) };
|
||||
if (find.running) {
|
||||
return t("find.status.running", counts);
|
||||
}
|
||||
const done = find.summary;
|
||||
if (!done) {
|
||||
return find.error === null ? t("find.status.idle") : "";
|
||||
}
|
||||
const totals = { matches: String(done.matches), files: String(done.files), ms: String(done.elapsedMs) };
|
||||
if (done.cancelled) {
|
||||
return t("find.status.cancelled", totals);
|
||||
}
|
||||
return done.matches === 0 ? t("find.status.none") : t("find.status.done", totals);
|
||||
});
|
||||
|
||||
/**
|
||||
* The DOM id of a row's option element.
|
||||
*
|
||||
* @param index - the row's index in the flat list.
|
||||
*/
|
||||
function optionId(index: number): string {
|
||||
return `find-row-${String(index)}`;
|
||||
}
|
||||
|
||||
/** A file with its rows and their indexes in the flat list. */
|
||||
interface FindGroup {
|
||||
/** Project-relative path. */
|
||||
path: string;
|
||||
/** The file's rows with their flat index. */
|
||||
rows: { row: FindRow; index: number }[];
|
||||
}
|
||||
|
||||
/** The rows grouped by file, in display order. */
|
||||
const groups = computed<FindGroup[]>(() => {
|
||||
const out: FindGroup[] = [];
|
||||
find.rows.forEach((row, index) => {
|
||||
const last = out[out.length - 1];
|
||||
if (last?.path === row.path) {
|
||||
last.rows.push({ row, index });
|
||||
} else {
|
||||
out.push({ path: row.path, rows: [{ row, index }] });
|
||||
}
|
||||
});
|
||||
return out;
|
||||
});
|
||||
|
||||
/**
|
||||
* The preview split around the match, without leading indentation.
|
||||
*
|
||||
* @param match - the match.
|
||||
* @returns the text before, the match and the text after.
|
||||
*/
|
||||
function parts(match: FindMatch): { before: string; hit: string; after: string } {
|
||||
const text = match.preview;
|
||||
const lead = Math.min(text.length - text.trimStart().length, match.previewColumn);
|
||||
const end = Math.min(text.length, match.previewColumn + match.length);
|
||||
return {
|
||||
before: text.slice(lead, match.previewColumn),
|
||||
hit: text.slice(match.previewColumn, end),
|
||||
after: text.slice(end),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory part of a path, empty at the root.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
*/
|
||||
function dirName(path: string): string {
|
||||
const slash = path.lastIndexOf("/");
|
||||
return slash < 0 ? "" : path.slice(0, slash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a match in the editor.
|
||||
*
|
||||
* @param row - the row.
|
||||
*/
|
||||
function openRow(row: FindRow): void {
|
||||
find.select(row.key);
|
||||
void commands.execute("editor.reveal", { path: row.path, line: row.match.line, column: row.match.column });
|
||||
}
|
||||
|
||||
/** Starts a search for the fields' current values. */
|
||||
function submit(): void {
|
||||
void find.search();
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles an option and repeats the last search, if there was one.
|
||||
*
|
||||
* @param option - which option.
|
||||
*/
|
||||
function toggle(option: "caseSensitive" | "wholeWord" | "regex"): void {
|
||||
find[option] = !find[option];
|
||||
if (find.query !== "" && (find.running || find.summary !== null || find.error !== null)) {
|
||||
void find.search();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves from a field into the result list.
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function onFieldKey(event: KeyboardEvent): void {
|
||||
if (event.key === "ArrowDown" && find.rows.length > 0) {
|
||||
event.preventDefault();
|
||||
if (find.selectedIndex < 0) {
|
||||
find.move(1);
|
||||
}
|
||||
list.value?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard navigation in the result list.
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function onListKey(event: KeyboardEvent): void {
|
||||
const moves: Record<string, number> = {
|
||||
ArrowDown: 1,
|
||||
ArrowUp: -1,
|
||||
PageDown: PAGE,
|
||||
PageUp: -PAGE,
|
||||
Home: -Infinity,
|
||||
End: Infinity,
|
||||
};
|
||||
const delta = moves[event.key];
|
||||
if (delta !== undefined) {
|
||||
event.preventDefault();
|
||||
find.move(Number.isFinite(delta) ? delta : delta > 0 ? find.rows.length : -find.rows.length);
|
||||
} else if (event.key === "Enter") {
|
||||
const row = find.rows[find.selectedIndex];
|
||||
if (row) {
|
||||
event.preventDefault();
|
||||
openRow(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Focuses and selects the query field. */
|
||||
async function focusQuery(): Promise<void> {
|
||||
await nextTick();
|
||||
queryInput.value?.focus();
|
||||
queryInput.value?.select();
|
||||
}
|
||||
|
||||
watch(() => find.focusRequest, focusQuery);
|
||||
|
||||
watch(
|
||||
() => find.selectedIndex,
|
||||
async (index) => {
|
||||
await nextTick();
|
||||
const element = index < 0 ? null : document.getElementById(optionId(index));
|
||||
if (element && typeof element.scrollIntoView === "function") {
|
||||
element.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
void focusQuery();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="find"
|
||||
data-test="find"
|
||||
>
|
||||
<form
|
||||
class="find__form"
|
||||
@submit.prevent="submit"
|
||||
>
|
||||
<div class="find__line">
|
||||
<span class="find__field find__field--query">
|
||||
<Search
|
||||
:size="14"
|
||||
class="find__icon"
|
||||
/>
|
||||
<input
|
||||
ref="queryInput"
|
||||
v-model="find.query"
|
||||
class="find__input"
|
||||
type="text"
|
||||
spellcheck="false"
|
||||
:aria-label="t('find.query.label')"
|
||||
:placeholder="t('find.query.placeholder')"
|
||||
:aria-invalid="find.error !== null"
|
||||
data-test="find-query"
|
||||
@keydown="onFieldKey"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="find__toggle"
|
||||
:aria-pressed="find.caseSensitive"
|
||||
:title="t('find.option.caseSensitive')"
|
||||
:aria-label="t('find.option.caseSensitive')"
|
||||
data-test="find-case"
|
||||
@click="toggle('caseSensitive')"
|
||||
>
|
||||
<CaseSensitive :size="16" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="find__toggle"
|
||||
:aria-pressed="find.wholeWord"
|
||||
:title="t('find.option.wholeWord')"
|
||||
:aria-label="t('find.option.wholeWord')"
|
||||
data-test="find-word"
|
||||
@click="toggle('wholeWord')"
|
||||
>
|
||||
<WholeWord :size="16" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="find__toggle"
|
||||
:aria-pressed="find.regex"
|
||||
:title="t('find.option.regex')"
|
||||
:aria-label="t('find.option.regex')"
|
||||
data-test="find-regex"
|
||||
@click="toggle('regex')"
|
||||
>
|
||||
<Regex :size="16" />
|
||||
</button>
|
||||
</span>
|
||||
<button
|
||||
v-if="find.running"
|
||||
type="button"
|
||||
class="find__action"
|
||||
data-test="find-cancel"
|
||||
@click="find.cancel()"
|
||||
>
|
||||
<CircleStop :size="14" />
|
||||
{{ t("common.cancel") }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="submit"
|
||||
class="find__action"
|
||||
data-test="find-submit"
|
||||
>
|
||||
{{ t("find.action.search") }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="find__line">
|
||||
<span class="find__field">
|
||||
<input
|
||||
v-model="find.include"
|
||||
class="find__input"
|
||||
type="text"
|
||||
spellcheck="false"
|
||||
:aria-label="t('find.include.label')"
|
||||
:placeholder="t('find.include.placeholder')"
|
||||
data-test="find-include"
|
||||
@keydown="onFieldKey"
|
||||
>
|
||||
</span>
|
||||
<span class="find__field">
|
||||
<input
|
||||
v-model="find.exclude"
|
||||
class="find__input"
|
||||
type="text"
|
||||
spellcheck="false"
|
||||
:aria-label="t('find.exclude.label')"
|
||||
:placeholder="t('find.exclude.placeholder')"
|
||||
data-test="find-exclude"
|
||||
@keydown="onFieldKey"
|
||||
>
|
||||
</span>
|
||||
</div>
|
||||
</form>
|
||||
<div
|
||||
class="find__status"
|
||||
role="status"
|
||||
data-test="find-status"
|
||||
>
|
||||
<span>{{ status }}</span>
|
||||
<span
|
||||
v-if="find.summary?.truncated"
|
||||
class="find__truncated"
|
||||
data-test="find-truncated"
|
||||
>{{ t("find.status.truncated", { matches: String(find.summary.matches) }) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="find.error"
|
||||
class="find__error"
|
||||
role="alert"
|
||||
data-test="find-error"
|
||||
>
|
||||
{{ find.error }}
|
||||
</div>
|
||||
<div
|
||||
ref="list"
|
||||
class="find__results"
|
||||
role="listbox"
|
||||
tabindex="0"
|
||||
:aria-label="t('find.results.label')"
|
||||
:aria-activedescendant="find.selectedIndex >= 0 ? optionId(find.selectedIndex) : undefined"
|
||||
data-test="find-results"
|
||||
@keydown="onListKey"
|
||||
>
|
||||
<div
|
||||
v-for="group in groups"
|
||||
:key="group.path"
|
||||
role="group"
|
||||
:aria-label="group.path"
|
||||
class="find__file"
|
||||
>
|
||||
<div
|
||||
class="find__file-header"
|
||||
data-test="find-file"
|
||||
>
|
||||
<span class="find__file-name">{{ baseName(group.path) }}</span>
|
||||
<span class="find__file-dir">{{ dirName(group.path) }}</span>
|
||||
<span class="find__file-count">{{ group.rows.length }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-for="{ row, index } in group.rows"
|
||||
:id="optionId(index)"
|
||||
:key="row.key"
|
||||
role="option"
|
||||
class="find__row"
|
||||
:class="{ 'find__row--selected': find.selectedKey === row.key }"
|
||||
:aria-selected="find.selectedKey === row.key"
|
||||
data-test="find-row"
|
||||
@click="openRow(row)"
|
||||
>
|
||||
<span class="find__line-number">{{ row.match.line + 1 }}</span>
|
||||
<span class="find__preview">{{ parts(row.match).before }}<mark
|
||||
class="find__hit"
|
||||
data-test="find-hit"
|
||||
>{{ parts(row.match).hit }}</mark>{{ parts(row.match).after }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.find {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.find__form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--lt-space-s, 4px);
|
||||
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
|
||||
}
|
||||
|
||||
.find__line {
|
||||
display: flex;
|
||||
gap: var(--lt-space-s, 4px);
|
||||
}
|
||||
|
||||
.find__field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
padding: 0 var(--lt-space-xs, 2px) 0 var(--lt-space-s, 4px);
|
||||
background: var(--lt-editor-bg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
}
|
||||
|
||||
.find__field:focus-within {
|
||||
border-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.find__icon {
|
||||
flex: none;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.find__input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: var(--lt-space-xs, 2px);
|
||||
font: inherit;
|
||||
color: var(--lt-fg);
|
||||
background: transparent;
|
||||
border: none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.find__input::placeholder {
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.find__toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--lt-space-xs, 2px);
|
||||
color: var(--lt-fg-muted);
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.find__toggle:hover {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.find__toggle[aria-pressed="true"] {
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-editor-match-bg);
|
||||
border-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.find__toggle:focus-visible,
|
||||
.find__action:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
}
|
||||
|
||||
.find__action {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
padding: 0 var(--lt-space-m, 8px);
|
||||
font: inherit;
|
||||
color: var(--lt-fg);
|
||||
background: transparent;
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.find__status {
|
||||
display: flex;
|
||||
gap: var(--lt-space-m, 8px);
|
||||
padding: 0 var(--lt-space-m, 8px) var(--lt-space-s, 4px);
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.find__truncated {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.find__error {
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
|
||||
color: var(--lt-fg);
|
||||
background: color-mix(in srgb, var(--lt-error) 15%, var(--lt-bg));
|
||||
}
|
||||
|
||||
.find__results {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--lt-border);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.find__results:focus-visible {
|
||||
box-shadow: inset 0 0 0 1px var(--lt-accent);
|
||||
}
|
||||
|
||||
.find__file-header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--lt-space-m, 8px);
|
||||
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.find__file-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.find__file-dir {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.find__file-count {
|
||||
margin-left: auto;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.find__row {
|
||||
display: flex;
|
||||
gap: var(--lt-space-m, 8px);
|
||||
padding: 0 var(--lt-space-m, 8px) 0 var(--lt-space-l, 24px);
|
||||
font-family: var(--lt-font-mono);
|
||||
white-space: pre;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.find__row:hover {
|
||||
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
|
||||
}
|
||||
|
||||
.find__row--selected,
|
||||
.find__row--selected:hover {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.find__line-number {
|
||||
flex: none;
|
||||
min-width: 4ch;
|
||||
text-align: right;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.find__row--selected .find__line-number {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.find__preview {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.find__hit {
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-editor-match-bg);
|
||||
border-radius: 2px;
|
||||
}
|
||||
</style>
|
||||
239
ui/src/components/layout/BottomPanel.vue
Normal file
239
ui/src/components/layout/BottomPanel.vue
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The bottom panel of the main window: a tool window docked under the
|
||||
* editor (Find since M2.4; later Problems, Terminal and others). A header
|
||||
* with the title, a collapse/expand button and a close button, the content
|
||||
* slot, and a splitter on the top edge to resize it.
|
||||
*
|
||||
* The splitter is dragged with the pointer or moved with Up/Down (Shift for
|
||||
* larger steps) when focused. Collapsed, only the header shows. Height and
|
||||
* expansion are view state, emitted through `v-model:height` and
|
||||
* `v-model:open`; the close button emits `close`, and the owner decides
|
||||
* what closing means.
|
||||
*/
|
||||
import { ChevronDown, ChevronUp, X } from "@lucide/vue";
|
||||
import { computed } from "vue";
|
||||
import { t } from "../../i18n";
|
||||
|
||||
/** Props of the bottom panel. */
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** Title shown in the header and as the accessible name. */
|
||||
title: string;
|
||||
/** Height of the content in CSS pixels, header excluded. */
|
||||
height?: number;
|
||||
/** Smallest height the splitter allows. */
|
||||
minHeight?: number;
|
||||
/** Largest height the splitter allows. */
|
||||
maxHeight?: number;
|
||||
/** Whether the panel is expanded (true) or collapsed to its header. */
|
||||
open?: boolean;
|
||||
}>(),
|
||||
{ height: 240, minHeight: 80, maxHeight: 900, open: true },
|
||||
);
|
||||
|
||||
/** Events of the bottom panel. */
|
||||
const emit = defineEmits<{
|
||||
/** New height after a resize. */
|
||||
"update:height": [height: number];
|
||||
/** New expansion after collapse or expand. */
|
||||
"update:open": [open: boolean];
|
||||
/** The close button was pressed. */
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
/** Inline style carrying the current height. */
|
||||
const bodyStyle = computed(() => ({ height: `${String(props.height)}px` }));
|
||||
|
||||
/**
|
||||
* Emits a height clamped to the allowed range.
|
||||
*
|
||||
* @param height - the wanted height.
|
||||
*/
|
||||
function setHeight(height: number): void {
|
||||
emit("update:height", Math.round(Math.min(props.maxHeight, Math.max(props.minHeight, height))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a pointer drag on the splitter; dragging up makes the panel taller.
|
||||
*
|
||||
* @param event - the pointer-down event.
|
||||
*/
|
||||
function onSplitterDown(event: PointerEvent): void {
|
||||
const target = event.currentTarget;
|
||||
if (!(target instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const startY = event.clientY;
|
||||
const startHeight = props.height;
|
||||
target.setPointerCapture(event.pointerId);
|
||||
const move = (e: PointerEvent): void => {
|
||||
setHeight(startHeight - (e.clientY - startY));
|
||||
};
|
||||
const up = (e: PointerEvent): void => {
|
||||
target.releasePointerCapture(e.pointerId);
|
||||
target.removeEventListener("pointermove", move);
|
||||
target.removeEventListener("pointerup", up);
|
||||
};
|
||||
target.addEventListener("pointermove", move);
|
||||
target.addEventListener("pointerup", up);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes with the keyboard when the splitter has focus.
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function onSplitterKey(event: KeyboardEvent): void {
|
||||
const step = event.shiftKey ? 48 : 12;
|
||||
if (event.key === "ArrowUp") {
|
||||
setHeight(props.height + step);
|
||||
} else if (event.key === "ArrowDown") {
|
||||
setHeight(props.height - step);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="bottom-panel"
|
||||
:aria-label="title"
|
||||
data-test="bottom-panel"
|
||||
>
|
||||
<div
|
||||
v-if="open"
|
||||
class="bottom-panel__splitter"
|
||||
role="separator"
|
||||
aria-orientation="horizontal"
|
||||
tabindex="0"
|
||||
:aria-valuenow="height"
|
||||
:aria-valuemin="minHeight"
|
||||
:aria-valuemax="maxHeight"
|
||||
:aria-label="t('common.toolWindow.resize', { title })"
|
||||
data-test="bottom-panel-splitter"
|
||||
@pointerdown="onSplitterDown"
|
||||
@keydown="onSplitterKey"
|
||||
/>
|
||||
<header class="bottom-panel__header">
|
||||
<span class="bottom-panel__title">{{ title }}</span>
|
||||
<span class="bottom-panel__actions">
|
||||
<button
|
||||
type="button"
|
||||
class="bottom-panel__button"
|
||||
:title="open ? t('common.toolWindow.collapse', { title }) : t('common.toolWindow.expand', { title })"
|
||||
:aria-label="open ? t('common.toolWindow.collapse', { title }) : t('common.toolWindow.expand', { title })"
|
||||
:aria-expanded="open"
|
||||
data-test="bottom-panel-toggle"
|
||||
@click="emit('update:open', !open)"
|
||||
>
|
||||
<ChevronDown
|
||||
v-if="open"
|
||||
:size="16"
|
||||
/>
|
||||
<ChevronUp
|
||||
v-else
|
||||
:size="16"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="bottom-panel__button"
|
||||
:title="t('common.toolWindow.hide', { title })"
|
||||
:aria-label="t('common.toolWindow.hide', { title })"
|
||||
data-test="bottom-panel-close"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X :size="16" />
|
||||
</button>
|
||||
</span>
|
||||
</header>
|
||||
<div
|
||||
v-if="open"
|
||||
class="bottom-panel__body"
|
||||
:style="bodyStyle"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.bottom-panel {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: none;
|
||||
max-height: 75%;
|
||||
background: var(--lt-bg);
|
||||
border-top: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.bottom-panel__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex: none;
|
||||
height: var(--lt-header-height, 28px);
|
||||
padding: 0 var(--lt-space-s, 4px) 0 var(--lt-space-m, 8px);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.bottom-panel__title {
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bottom-panel__actions {
|
||||
display: inline-flex;
|
||||
gap: var(--lt-space-xs, 2px);
|
||||
}
|
||||
|
||||
.bottom-panel__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
flex-shrink: 1;
|
||||
}
|
||||
|
||||
.bottom-panel__button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--lt-space-xs, 2px);
|
||||
color: var(--lt-fg-muted);
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bottom-panel__button:hover {
|
||||
color: var(--lt-fg);
|
||||
background: color-mix(in srgb, var(--lt-fg) 8%, transparent);
|
||||
}
|
||||
|
||||
.bottom-panel__button:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
}
|
||||
|
||||
.bottom-panel__splitter {
|
||||
position: absolute;
|
||||
top: -3px;
|
||||
right: 0;
|
||||
left: 0;
|
||||
height: 6px;
|
||||
cursor: row-resize;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.bottom-panel__splitter:hover,
|
||||
.bottom-panel__splitter:focus-visible {
|
||||
outline: none;
|
||||
background: color-mix(in srgb, var(--lt-accent) 50%, transparent);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,41 +1,60 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* Layout of the main window: the Project tool window on the left, the
|
||||
* editor area in the middle and the status bar along the bottom.
|
||||
* editor area in the middle, the bottom panel under both (M2.4) and the
|
||||
* status bar along the bottom.
|
||||
*
|
||||
* The editor area is a slot so the editor (M1.6) can replace the
|
||||
* placeholder without touching the layout. The layout supplies the UI
|
||||
* command `view.toggleProjectTree` (`Mod+1`), which shows or hides the
|
||||
* Project tool window.
|
||||
*
|
||||
* The bottom panel ({@link BottomPanel}) holds the Find tool window. It
|
||||
* appears with the UI command `find.open` (`Mod+Alt+F`, supplied here so it
|
||||
* works before the panel exists), collapses to its header and closes from
|
||||
* its header; the Find store keeps the results while it is closed.
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { useFindStore } from "../../stores/find";
|
||||
import FindToolWindow from "../find/FindToolWindow.vue";
|
||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||
import StatusBar from "../StatusBar.vue";
|
||||
import BottomPanel from "./BottomPanel.vue";
|
||||
import ToolWindow from "./ToolWindow.vue";
|
||||
|
||||
/** Width of the left tool window in CSS pixels. */
|
||||
const leftWidth = ref(260);
|
||||
/** Whether the left tool window is shown. */
|
||||
const leftOpen = ref(true);
|
||||
/** Height of the bottom panel's content in CSS pixels. */
|
||||
const bottomHeight = ref(240);
|
||||
|
||||
const commands = useCommandsStore();
|
||||
const find = useFindStore();
|
||||
|
||||
/** Withdraws the command handler; set while mounted. */
|
||||
let withdraw: (() => void) | null = null;
|
||||
/** Withdraws the command handlers; filled while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
onMounted(() => {
|
||||
withdraw = commands.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
leftOpen.value = !leftOpen.value;
|
||||
},
|
||||
});
|
||||
find.start();
|
||||
withdraw = [
|
||||
commands.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
leftOpen.value = !leftOpen.value;
|
||||
},
|
||||
}),
|
||||
commands.provide("find.open", { run: (params) => find.open(params) }),
|
||||
];
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
withdraw?.();
|
||||
withdraw = null;
|
||||
for (const fn of withdraw) {
|
||||
fn();
|
||||
}
|
||||
withdraw = [];
|
||||
find.stop();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
|
@ -56,6 +75,15 @@ onBeforeUnmount(() => {
|
|||
<slot />
|
||||
</main>
|
||||
</div>
|
||||
<BottomPanel
|
||||
v-if="find.visible"
|
||||
v-model:height="bottomHeight"
|
||||
v-model:open="find.expanded"
|
||||
:title="t('find.toolWindow.title')"
|
||||
@close="find.hide()"
|
||||
>
|
||||
<FindToolWindow />
|
||||
</BottomPanel>
|
||||
<StatusBar />
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
{
|
||||
"app.statusBar.version": "{name} {version}",
|
||||
"command.editor.reveal": "Reveal Cursor in Editor",
|
||||
"command.find.open": "Find in Files…",
|
||||
"command.key.alt": "Alt",
|
||||
"command.key.cmd": "Cmd",
|
||||
"command.key.ctrl": "Ctrl",
|
||||
|
|
@ -16,6 +17,8 @@
|
|||
"common.dontSave": "Don't Save",
|
||||
"common.error.unexpectedResult": "unexpected result of {command}",
|
||||
"common.save": "Save",
|
||||
"common.toolWindow.collapse": "Collapse {title}",
|
||||
"common.toolWindow.expand": "Expand {title}",
|
||||
"common.toolWindow.hide": "Hide {title}",
|
||||
"common.toolWindow.resize": "Resize {title}",
|
||||
"common.toolWindow.show": "Show {title}",
|
||||
|
|
@ -28,6 +31,24 @@
|
|||
"editor.tabs.close": "Close {name}",
|
||||
"editor.tabs.label": "Editor tabs",
|
||||
"editor.tabs.unsaved": "unsaved changes",
|
||||
"find.action.search": "Search",
|
||||
"find.exclude.label": "Exclude files",
|
||||
"find.exclude.placeholder": "Exclude, e.g. *.min.js, var/**",
|
||||
"find.include.label": "Include files",
|
||||
"find.include.placeholder": "Include, e.g. *.php, src/**",
|
||||
"find.option.caseSensitive": "Match case",
|
||||
"find.option.regex": "Regular expression",
|
||||
"find.option.wholeWord": "Whole words",
|
||||
"find.query.label": "Text to find",
|
||||
"find.query.placeholder": "Find in files",
|
||||
"find.results.label": "Search results",
|
||||
"find.status.cancelled": "Cancelled · {matches} matches in {files} files",
|
||||
"find.status.done": "{matches} matches in {files} files · {ms} ms",
|
||||
"find.status.idle": "Type a text and press Enter",
|
||||
"find.status.none": "No matches",
|
||||
"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",
|
||||
"notification.close": "Close notification",
|
||||
"notification.command.failed": "{command} failed: {message}",
|
||||
"notification.project.notLocal": "The chosen folder is not on this computer: {reason}",
|
||||
|
|
|
|||
|
|
@ -61,6 +61,30 @@ export type EngineEventPayload =
|
|||
kind: "recoveryResolved";
|
||||
/** Paths restored or discarded; unchecked, it comes from the engine. */
|
||||
paths: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "searchResults";
|
||||
/** The search, as `search.find` returned it; unchecked. */
|
||||
searchId: unknown;
|
||||
/** Project-relative path of the file; unchecked. */
|
||||
path: unknown;
|
||||
/** `[{line, column, length, preview, previewColumn}]`; unchecked. */
|
||||
matches: unknown;
|
||||
}
|
||||
| {
|
||||
kind: "searchDone";
|
||||
/** The search; unchecked, it comes from the engine. */
|
||||
searchId: unknown;
|
||||
/** Files with reported matches; unchecked. */
|
||||
files: unknown;
|
||||
/** Matches reported; unchecked. */
|
||||
matches: unknown;
|
||||
/** Whether the match cap left matches out; unchecked. */
|
||||
truncated: unknown;
|
||||
/** Whether the search was cancelled; unchecked. */
|
||||
cancelled: unknown;
|
||||
/** Wall time in milliseconds; unchecked. */
|
||||
elapsedMs: unknown;
|
||||
};
|
||||
|
||||
/** Callback receiving engine events. */
|
||||
|
|
|
|||
469
ui/src/stores/find.ts
Normal file
469
ui/src/stores/find.ts
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
/**
|
||||
* The Find tool window's state (M2.4): the query and its options, the
|
||||
* running search and its results, grouped by file.
|
||||
*
|
||||
* - **Searching:** {@link useFindStore}'s `search` runs `search.find` and
|
||||
* keeps the returned `searchId`. Results arrive as `searchResults` events
|
||||
* (one per file, in no fixed order; the store keeps files sorted by path)
|
||||
* and end with `searchDone`. Events of other searches are ignored. Events
|
||||
* that arrive while `search.find` has not answered yet are held and
|
||||
* replayed once the id is known, because events and command results
|
||||
* travel on different channels.
|
||||
* - **One search at a time:** a new search cancels the running one
|
||||
* (`search.cancel`); the engine does not do that by itself.
|
||||
* - **Errors:** a refused search (`invalid_params` for a bad regex or glob)
|
||||
* shows its message in the window, not as a toast.
|
||||
* - **Opening:** `open` shows the panel, takes the query from the params
|
||||
* (an agent's `find.open {query}` searches at once) or from the editor
|
||||
* (selection or word at the cursor) and asks the window to focus its field.
|
||||
* - **Untrusted input:** event fields are checked; malformed matches are
|
||||
* dropped.
|
||||
*/
|
||||
import type { EditorState } from "@codemirror/state";
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import { t } from "../i18n";
|
||||
import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../ipc";
|
||||
import { useEditorStore } from "./editor";
|
||||
|
||||
/** One match as the window shows it. */
|
||||
export interface FindMatch {
|
||||
/** 0-based line. */
|
||||
line: number;
|
||||
/** 0-based column in UTF-16 code units. */
|
||||
column: number;
|
||||
/** Length of the match in UTF-16 code units, at least 1. */
|
||||
length: number;
|
||||
/** The line, or a window of it around the match. */
|
||||
preview: string;
|
||||
/** Start of the match inside {@link FindMatch.preview}. */
|
||||
previewColumn: number;
|
||||
}
|
||||
|
||||
/** The matches of one file. */
|
||||
export interface FindFile {
|
||||
/** Project-relative path. */
|
||||
path: string;
|
||||
/** Matches in line order. */
|
||||
matches: FindMatch[];
|
||||
}
|
||||
|
||||
/** Totals of a finished search, from `searchDone`. */
|
||||
export interface FindSummary {
|
||||
/** Files with matches. */
|
||||
files: number;
|
||||
/** Matches. */
|
||||
matches: number;
|
||||
/** Whether the match cap left matches out. */
|
||||
truncated: boolean;
|
||||
/** Whether the search was cancelled. */
|
||||
cancelled: boolean;
|
||||
/** Wall time in milliseconds. */
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
/** A match in the flat result order, for keyboard navigation. */
|
||||
export interface FindRow {
|
||||
/** Stable key: path and match index. */
|
||||
key: string;
|
||||
/** Path of the file. */
|
||||
path: string;
|
||||
/** The match. */
|
||||
match: FindMatch;
|
||||
}
|
||||
|
||||
/** Longest query taken from the editor selection, in UTF-16 code units. */
|
||||
export const MAX_PREFILL = 1000;
|
||||
|
||||
/** Most events held while `search.find` has not answered. */
|
||||
const MAX_EARLY_EVENTS = 5000;
|
||||
|
||||
/**
|
||||
* The query `find.open` takes from an editor: the main selection if it is
|
||||
* not empty and has no line break, else the word at the cursor.
|
||||
*
|
||||
* @param state - the active editor state, if any.
|
||||
* @returns the text, or null when there is nothing to take.
|
||||
*/
|
||||
export function prefillFrom(state: EditorState | undefined): string | null {
|
||||
if (!state) {
|
||||
return null;
|
||||
}
|
||||
const { from, to, head } = state.selection.main;
|
||||
if (from !== to && to - from <= MAX_PREFILL) {
|
||||
const text = state.sliceDoc(from, to);
|
||||
if (!/[\r\n]/.test(text) && text.trim() !== "") {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
const word = state.wordAt(head);
|
||||
return word ? state.sliceDoc(word.from, word.to) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a comma-separated list of globs.
|
||||
*
|
||||
* @param text - what the user typed, for example `*.php, src/**`.
|
||||
*/
|
||||
export function splitGlobs(text: string): string[] {
|
||||
return text
|
||||
.split(",")
|
||||
.map((glob) => glob.trim())
|
||||
.filter((glob) => glob !== "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a non-negative integer field.
|
||||
*
|
||||
* @param value - an untrusted field.
|
||||
*/
|
||||
function count(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the matches of a `searchResults` event, dropping malformed ones and
|
||||
* clamping the highlight into the preview.
|
||||
*
|
||||
* @param raw - the untrusted `matches` field.
|
||||
*/
|
||||
export function toMatches(raw: unknown): FindMatch[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
const out: FindMatch[] = [];
|
||||
for (const item of raw as unknown[]) {
|
||||
if (typeof item !== "object" || item === null) {
|
||||
continue;
|
||||
}
|
||||
const m = item as Record<string, unknown>;
|
||||
const line = count(m.line);
|
||||
const column = count(m.column);
|
||||
const length = count(m.length);
|
||||
const previewColumn = count(m.previewColumn);
|
||||
if (line === null || column === null || length === null || previewColumn === null || typeof m.preview !== "string") {
|
||||
continue;
|
||||
}
|
||||
const start = Math.min(previewColumn, m.preview.length);
|
||||
out.push({ line, column, length: Math.max(1, length), preview: m.preview, previewColumn: start });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index at which a path belongs in a list sorted by path.
|
||||
*
|
||||
* @param files - files sorted by path.
|
||||
* @param path - the path to place.
|
||||
*/
|
||||
function insertionIndex(files: readonly FindFile[], path: string): number {
|
||||
let low = 0;
|
||||
let high = files.length;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
const other = files[mid]?.path ?? "";
|
||||
if (other < path) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/** Store of the Find tool window. */
|
||||
export const useFindStore = defineStore("find", () => {
|
||||
const editor = useEditorStore();
|
||||
/** Whether the panel exists in the layout (after the first `find.open`). */
|
||||
const visible = ref(false);
|
||||
/** Whether the panel is expanded (false: collapsed to its header). */
|
||||
const expanded = ref(true);
|
||||
/** The query text. */
|
||||
const query = ref("");
|
||||
/** Whether the query is a regular expression. */
|
||||
const regex = ref(false);
|
||||
/** Whether case matters. */
|
||||
const caseSensitive = ref(false);
|
||||
/** Whether only whole words match. */
|
||||
const wholeWord = ref(false);
|
||||
/** Include globs, comma-separated. */
|
||||
const include = ref("");
|
||||
/** Exclude globs, comma-separated. */
|
||||
const exclude = ref("");
|
||||
/** Id of the current search, null before the engine answered. */
|
||||
const searchId = ref<number | null>(null);
|
||||
/** Whether a search is running. */
|
||||
const running = ref(false);
|
||||
/** Files with matches, sorted by path; replaced on every change. */
|
||||
const files = shallowRef<FindFile[]>([]);
|
||||
/** Totals once the search ended. */
|
||||
const summary = ref<FindSummary | null>(null);
|
||||
/** Message of a refused search or cancel, shown in the window. */
|
||||
const error = ref<string | null>(null);
|
||||
/** Key of the selected row, see {@link FindRow}. */
|
||||
const selectedKey = ref<string | null>(null);
|
||||
/** Bumped when the window should focus and select its query field. */
|
||||
const focusRequest = ref(0);
|
||||
/** Counter of searches started, so a late answer of an older one is dropped. */
|
||||
let generation = 0;
|
||||
/** Whether `search.find` was sent and has not answered. */
|
||||
let awaitingId = false;
|
||||
/** Search events that arrived while {@link awaitingId}. */
|
||||
let early: EngineEventPayload[] = [];
|
||||
/** Ends the event subscription; set while started. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** Every match in display order. */
|
||||
const rows = computed<FindRow[]>(() =>
|
||||
files.value.flatMap((file) =>
|
||||
file.matches.map((match, i) => ({ key: `${file.path}\u0000${String(i)}`, path: file.path, match })),
|
||||
),
|
||||
);
|
||||
|
||||
/** Matches received so far. */
|
||||
const matchCount = computed(() => rows.value.length);
|
||||
|
||||
/** Index of the selected row in {@link rows}, -1 if none. */
|
||||
const selectedIndex = computed(() => rows.value.findIndex((row) => row.key === selectedKey.value));
|
||||
|
||||
/** Drops the results of the previous search. */
|
||||
function clearResults(): void {
|
||||
files.value = [];
|
||||
summary.value = null;
|
||||
selectedKey.value = null;
|
||||
error.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one file's matches.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @param matches - its matches.
|
||||
*/
|
||||
function addFile(path: string, matches: FindMatch[]): void {
|
||||
if (matches.length === 0) {
|
||||
return;
|
||||
}
|
||||
const next = [...files.value];
|
||||
const at = insertionIndex(next, path);
|
||||
const same = next[at];
|
||||
if (same?.path === path) {
|
||||
next[at] = { path, matches: [...same.matches, ...matches] };
|
||||
} else {
|
||||
next.splice(at, 0, { path, matches });
|
||||
}
|
||||
files.value = next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a search event of the current search.
|
||||
*
|
||||
* @param event - a `searchResults` or `searchDone` event.
|
||||
*/
|
||||
function apply(event: EngineEventPayload): void {
|
||||
if (event.kind === "searchResults") {
|
||||
if (typeof event.path === "string" && event.path !== "") {
|
||||
addFile(event.path, toMatches(event.matches));
|
||||
}
|
||||
} else if (event.kind === "searchDone") {
|
||||
running.value = false;
|
||||
summary.value = {
|
||||
files: count(event.files) ?? files.value.length,
|
||||
matches: count(event.matches) ?? matchCount.value,
|
||||
truncated: event.truncated === true,
|
||||
cancelled: event.cancelled === true,
|
||||
elapsedMs: count(event.elapsedMs) ?? 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an engine event.
|
||||
*
|
||||
* @param event - the engine event.
|
||||
*/
|
||||
function onEvent(event: EngineEventPayload): void {
|
||||
if (event.kind === "searchResults" || event.kind === "searchDone") {
|
||||
if (searchId.value !== null && event.searchId === searchId.value) {
|
||||
apply(event);
|
||||
} else if (awaitingId && early.length < MAX_EARLY_EVENTS) {
|
||||
early.push(event);
|
||||
}
|
||||
} else if (event.kind === "projectClosed" || event.kind === "projectOpened") {
|
||||
generation += 1;
|
||||
awaitingId = false;
|
||||
early = [];
|
||||
searchId.value = null;
|
||||
running.value = false;
|
||||
clearResults();
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks the engine to stop the running search; its `searchDone` follows. */
|
||||
async function cancel(): Promise<void> {
|
||||
const id = searchId.value;
|
||||
if (!running.value || id === null) {
|
||||
return;
|
||||
}
|
||||
const result = await run("search.cancel", { searchId: id });
|
||||
if (!result.ok) {
|
||||
error.value = result.error.message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a search for the current query and options, cancelling the
|
||||
* running one. An empty query only clears the results.
|
||||
*/
|
||||
async function search(): Promise<void> {
|
||||
void cancel();
|
||||
generation += 1;
|
||||
const mine = generation;
|
||||
clearResults();
|
||||
searchId.value = null;
|
||||
running.value = false;
|
||||
early = [];
|
||||
if (query.value === "") {
|
||||
awaitingId = false;
|
||||
return;
|
||||
}
|
||||
running.value = true;
|
||||
awaitingId = true;
|
||||
const params: JsonValue = {
|
||||
query: query.value,
|
||||
regex: regex.value,
|
||||
caseSensitive: caseSensitive.value,
|
||||
wholeWord: wholeWord.value,
|
||||
include: splitGlobs(include.value),
|
||||
exclude: splitGlobs(exclude.value),
|
||||
};
|
||||
const result = await run<unknown>("search.find", params);
|
||||
const answer = result.ok && typeof result.value === "object" && result.value !== null ? (result.value as Record<string, unknown>) : null;
|
||||
const id = answer ? count(answer.searchId) : null;
|
||||
if (mine !== generation) {
|
||||
if (id !== null) {
|
||||
void run("search.cancel", { searchId: id });
|
||||
}
|
||||
return;
|
||||
}
|
||||
awaitingId = false;
|
||||
const held = early;
|
||||
early = [];
|
||||
if (!result.ok) {
|
||||
running.value = false;
|
||||
error.value = result.error.message;
|
||||
return;
|
||||
}
|
||||
if (id === null) {
|
||||
running.value = false;
|
||||
error.value = t("common.error.unexpectedResult", { command: "search.find" });
|
||||
return;
|
||||
}
|
||||
searchId.value = id;
|
||||
for (const event of held) {
|
||||
if ("searchId" in event && event.searchId === id) {
|
||||
apply(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the panel and focuses its query field: the UI command
|
||||
* `find.open`. With a string `query` param (agents) it takes that query
|
||||
* and searches at once; otherwise it takes the editor's selection or the
|
||||
* word at the cursor, if any, and waits for Enter.
|
||||
*
|
||||
* @param params - the command params; untrusted.
|
||||
*/
|
||||
async function open(params: unknown = {}): Promise<void> {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
visible.value = true;
|
||||
expanded.value = true;
|
||||
focusRequest.value += 1;
|
||||
if (typeof p.query === "string") {
|
||||
query.value = p.query;
|
||||
if (typeof p.regex === "boolean") regex.value = p.regex;
|
||||
if (typeof p.caseSensitive === "boolean") caseSensitive.value = p.caseSensitive;
|
||||
if (typeof p.wholeWord === "boolean") wholeWord.value = p.wholeWord;
|
||||
if (typeof p.include === "string") include.value = p.include;
|
||||
if (typeof p.exclude === "string") exclude.value = p.exclude;
|
||||
await search();
|
||||
return;
|
||||
}
|
||||
const id = editor.activeId;
|
||||
const prefill = prefillFrom(id === null ? undefined : editor.syncOf(id)?.state);
|
||||
if (prefill !== null && prefill !== query.value) {
|
||||
query.value = prefill;
|
||||
error.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hides the panel; the results stay for the next `find.open`. */
|
||||
function hide(): void {
|
||||
visible.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the selection through the rows.
|
||||
*
|
||||
* @param delta - rows to move; clamped at both ends.
|
||||
*/
|
||||
function move(delta: number): void {
|
||||
const list = rows.value;
|
||||
if (list.length === 0) {
|
||||
return;
|
||||
}
|
||||
const from = selectedIndex.value;
|
||||
const to = from < 0 ? (delta > 0 ? 0 : list.length - 1) : Math.min(list.length - 1, Math.max(0, from + delta));
|
||||
selectedKey.value = list[to]?.key ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a row.
|
||||
*
|
||||
* @param key - its key, see {@link FindRow}.
|
||||
*/
|
||||
function select(key: string): void {
|
||||
selectedKey.value = key;
|
||||
}
|
||||
|
||||
/** Starts listening to search events. Starting twice is a no-op. */
|
||||
function start(): void {
|
||||
unsubscribe ??= onEngineEvent(onEvent);
|
||||
}
|
||||
|
||||
/** Stops listening. */
|
||||
function stop(): void {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}
|
||||
|
||||
return {
|
||||
visible,
|
||||
expanded,
|
||||
query,
|
||||
regex,
|
||||
caseSensitive,
|
||||
wholeWord,
|
||||
include,
|
||||
exclude,
|
||||
searchId,
|
||||
running,
|
||||
files,
|
||||
summary,
|
||||
error,
|
||||
selectedKey,
|
||||
focusRequest,
|
||||
rows,
|
||||
matchCount,
|
||||
selectedIndex,
|
||||
search,
|
||||
cancel,
|
||||
open,
|
||||
hide,
|
||||
move,
|
||||
select,
|
||||
start,
|
||||
stop,
|
||||
};
|
||||
});
|
||||
530
ui/tests/find/FindToolWindow.test.ts
Normal file
530
ui/tests/find/FindToolWindow.test.ts
Normal file
|
|
@ -0,0 +1,530 @@
|
|||
/**
|
||||
* Tests of the Find tool window (M2.4): the Find store (search params,
|
||||
* results sorted by file, events of other searches ignored, events before
|
||||
* the `searchId` answer replayed, a new search cancelling the old one,
|
||||
* refused queries, malformed matches, project close), the prefill from the
|
||||
* editor, the window (status and counts, truncated hint, highlight, toggles
|
||||
* repeating the search, cancel, keyboard navigation and opening a match
|
||||
* through `editor.reveal`), the bottom panel, and `find.open` through the
|
||||
* main layout and `uiCommand`. The engine is a fake behind the mocked Tauri
|
||||
* `invoke` and `listen`.
|
||||
*/
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
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";
|
||||
|
||||
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 { useCommandsStore } from "../../src/commands/store";
|
||||
import FindToolWindow from "../../src/components/find/FindToolWindow.vue";
|
||||
import BottomPanel from "../../src/components/layout/BottomPanel.vue";
|
||||
import MainLayout from "../../src/components/layout/MainLayout.vue";
|
||||
import { prefillFrom, splitGlobs, toMatches, useFindStore } from "../../src/stores/find";
|
||||
|
||||
/** Every `engine_execute` call, in order. */
|
||||
let calls: { command: string; params: Record<string, unknown> }[];
|
||||
/** Engine event callbacks of every subscription. */
|
||||
let listeners: ((event: { payload: unknown }) => void)[];
|
||||
/** Next `searchId` the fake returns. */
|
||||
let nextSearchId: number;
|
||||
/** Error the next `search.find` fails with, if any. */
|
||||
let findError: { code: string; message: string } | null;
|
||||
/** Events the fake emits before `search.find` answers. */
|
||||
let beforeAnswer: unknown[];
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components, unmounted after each test. */
|
||||
let mounted: VueWrapper[];
|
||||
|
||||
/**
|
||||
* Sends an engine event to every subscription.
|
||||
*
|
||||
* @param payload - the event.
|
||||
*/
|
||||
async function emit(payload: unknown): Promise<void> {
|
||||
for (const listener of [...listeners]) {
|
||||
listener({ payload });
|
||||
}
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/**
|
||||
* A `searchResults` event.
|
||||
*
|
||||
* @param searchId - the search.
|
||||
* @param path - the file.
|
||||
* @param lines - one match per entry: line number and preview with the
|
||||
* match marked by `[` and `]`.
|
||||
*/
|
||||
function results(searchId: number, path: string, lines: [number, string][]): unknown {
|
||||
return {
|
||||
kind: "searchResults",
|
||||
searchId,
|
||||
path,
|
||||
matches: lines.map(([line, marked]) => {
|
||||
const start = marked.indexOf("[");
|
||||
const end = marked.indexOf("]") - 1;
|
||||
const preview = marked.replace("[", "").replace("]", "");
|
||||
return { line, column: start + 2, length: end - start, preview, previewColumn: start };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A `searchDone` event.
|
||||
*
|
||||
* @param searchId - the search.
|
||||
* @param extra - fields to override.
|
||||
*/
|
||||
function done(searchId: number, extra: Record<string, unknown> = {}): unknown {
|
||||
return { kind: "searchDone", searchId, files: 2, matches: 3, truncated: false, cancelled: false, elapsedMs: 12, ...extra };
|
||||
}
|
||||
|
||||
/** The params of every call of a command. */
|
||||
function paramsOf(command: string): Record<string, unknown>[] {
|
||||
return calls.filter((c) => c.command === command).map((c) => c.params);
|
||||
}
|
||||
|
||||
/** Mounts the Find window with a started store and an `editor.reveal` spy. */
|
||||
async function mountFind(): Promise<{ wrapper: VueWrapper; reveals: unknown[] }> {
|
||||
const reveals: unknown[] = [];
|
||||
useCommandsStore(pinia).provide("editor.reveal", { run: (params) => void reveals.push(params) });
|
||||
useFindStore(pinia).start();
|
||||
const wrapper = mount(FindToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await flushPromises();
|
||||
return { wrapper, reveals };
|
||||
}
|
||||
|
||||
/**
|
||||
* Types a query and presses Enter.
|
||||
*
|
||||
* @param wrapper - the Find window.
|
||||
* @param text - the query.
|
||||
*/
|
||||
async function searchFor(wrapper: VueWrapper, text: string): Promise<void> {
|
||||
await wrapper.get("[data-test=find-query]").setValue(text);
|
||||
await wrapper.get("form").trigger("submit");
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
calls = [];
|
||||
listeners = [];
|
||||
nextSearchId = 7;
|
||||
findError = null;
|
||||
beforeAnswer = [];
|
||||
mounted = [];
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||
listeners.push(callback);
|
||||
return Promise.resolve(() => {
|
||||
listeners = listeners.filter((l) => l !== callback);
|
||||
});
|
||||
});
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (cmd === "engine_list_commands") {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
if (cmd !== "engine_execute" || !args) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
calls.push({ command: args.command, params: args.params });
|
||||
if (args.command === "search.find") {
|
||||
if (findError) {
|
||||
return Promise.reject(Object.assign(new Error(findError.code), findError));
|
||||
}
|
||||
const searchId = nextSearchId;
|
||||
nextSearchId += 1;
|
||||
for (const event of beforeAnswer) {
|
||||
for (const listener of [...listeners]) {
|
||||
listener({ payload: event });
|
||||
}
|
||||
}
|
||||
return Promise.resolve({ searchId });
|
||||
}
|
||||
if (args.command === "search.cancel") {
|
||||
return Promise.resolve({ cancelled: true });
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
useFindStore(pinia).stop();
|
||||
useCommandsStore(pinia).stop();
|
||||
});
|
||||
|
||||
describe("find store", () => {
|
||||
it("sends the query, options and split globs", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
find.query = "foo";
|
||||
find.caseSensitive = true;
|
||||
find.regex = true;
|
||||
find.include = " *.php, src/** ,";
|
||||
find.exclude = "vendor/**";
|
||||
await find.search();
|
||||
expect(paramsOf("search.find")).toEqual([
|
||||
{ query: "foo", regex: true, caseSensitive: true, wholeWord: false, include: ["*.php", "src/**"], exclude: ["vendor/**"] },
|
||||
]);
|
||||
expect(find.searchId).toBe(7);
|
||||
expect(find.running).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps files sorted, ignores other searches and ends with the summary", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
find.query = "foo";
|
||||
await find.search();
|
||||
await emit(results(7, "src/b.php", [[3, " $[foo] = 1;"]]));
|
||||
await emit(results(99, "src/x.php", [[0, "[foo]"]]));
|
||||
await emit(results(7, "a.php", [[0, "[foo]"], [4, "x [foo]"]]));
|
||||
expect(find.files.map((f) => f.path)).toEqual(["a.php", "src/b.php"]);
|
||||
expect(find.matchCount).toBe(3);
|
||||
await emit(done(99));
|
||||
expect(find.running).toBe(true);
|
||||
await emit(done(7, { truncated: true }));
|
||||
expect(find.running).toBe(false);
|
||||
expect(find.summary).toEqual({ files: 2, matches: 3, truncated: true, cancelled: false, elapsedMs: 12 });
|
||||
});
|
||||
|
||||
it("replays events that arrive before search.find answers", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
beforeAnswer = [results(7, "a.php", [[0, "[foo]"]]), results(3, "old.php", [[0, "[foo]"]]), done(7, { files: 1, matches: 1 })];
|
||||
find.query = "foo";
|
||||
await find.search();
|
||||
expect(find.files.map((f) => f.path)).toEqual(["a.php"]);
|
||||
expect(find.summary?.matches).toBe(1);
|
||||
expect(find.running).toBe(false);
|
||||
});
|
||||
|
||||
it("cancels the running search when a new one starts", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
find.query = "foo";
|
||||
await find.search();
|
||||
await emit(results(7, "a.php", [[0, "[foo]"]]));
|
||||
find.query = "bar";
|
||||
await find.search();
|
||||
expect(paramsOf("search.cancel")).toEqual([{ searchId: 7 }]);
|
||||
expect(find.searchId).toBe(8);
|
||||
expect(find.files).toEqual([]);
|
||||
await emit(results(7, "late.php", [[0, "[foo]"]]));
|
||||
expect(find.files).toEqual([]);
|
||||
});
|
||||
|
||||
it("drops the answer of a search overtaken by a newer one and cancels it", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
find.query = "foo";
|
||||
const first = find.search();
|
||||
find.query = "bar";
|
||||
const second = find.search();
|
||||
await Promise.all([first, second]);
|
||||
expect(find.searchId).toBe(8);
|
||||
expect(paramsOf("search.cancel")).toEqual([{ searchId: 7 }]);
|
||||
});
|
||||
|
||||
it("shows a refused query in place", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
findError = { code: "invalid_params", message: "search.find: regex parse error" };
|
||||
find.query = "(";
|
||||
find.regex = true;
|
||||
await find.search();
|
||||
expect(find.error).toBe("search.find: regex parse error");
|
||||
expect(find.running).toBe(false);
|
||||
});
|
||||
|
||||
it("does not search for an empty query", async () => {
|
||||
const find = useFindStore();
|
||||
await find.search();
|
||||
expect(paramsOf("search.find")).toEqual([]);
|
||||
});
|
||||
|
||||
it("cancels through search.cancel", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
find.query = "foo";
|
||||
await find.search();
|
||||
await find.cancel();
|
||||
expect(paramsOf("search.cancel")).toEqual([{ searchId: 7 }]);
|
||||
await emit(done(7, { cancelled: true }));
|
||||
expect(find.summary?.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
it("clears the results when the project closes", async () => {
|
||||
const find = useFindStore();
|
||||
find.start();
|
||||
await flushPromises();
|
||||
find.query = "foo";
|
||||
await find.search();
|
||||
await emit(results(7, "a.php", [[0, "[foo]"]]));
|
||||
await emit({ kind: "projectClosed" });
|
||||
expect(find.files).toEqual([]);
|
||||
expect(find.running).toBe(false);
|
||||
await emit(results(7, "b.php", [[0, "[foo]"]]));
|
||||
expect(find.files).toEqual([]);
|
||||
});
|
||||
|
||||
it("drops malformed matches and clamps the highlight", () => {
|
||||
expect(
|
||||
toMatches([
|
||||
{ line: 1, column: 2, length: 3, preview: "abc", previewColumn: 9 },
|
||||
{ line: -1, column: 0, length: 1, preview: "x", previewColumn: 0 },
|
||||
{ line: 0, column: 0, length: 1, preview: 5, previewColumn: 0 },
|
||||
null,
|
||||
"x",
|
||||
]),
|
||||
).toEqual([{ line: 1, column: 2, length: 3, preview: "abc", previewColumn: 3 }]);
|
||||
expect(toMatches("nope")).toEqual([]);
|
||||
});
|
||||
|
||||
it("splits globs", () => {
|
||||
expect(splitGlobs("")).toEqual([]);
|
||||
expect(splitGlobs("*.php,, *.twig ")).toEqual(["*.php", "*.twig"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("prefill", () => {
|
||||
/**
|
||||
* An editor state with a selection.
|
||||
*
|
||||
* @param doc - the text.
|
||||
* @param anchor - selection anchor.
|
||||
* @param head - selection head.
|
||||
*/
|
||||
function stateOf(doc: string, anchor: number, head = anchor): EditorState {
|
||||
return EditorState.create({ doc, selection: EditorSelection.single(anchor, head) });
|
||||
}
|
||||
|
||||
it("takes the selection", () => {
|
||||
expect(prefillFrom(stateOf("echo $foo->bar();", 5, 14))).toBe("$foo->bar");
|
||||
});
|
||||
|
||||
it("takes the word at the cursor without a selection", () => {
|
||||
expect(prefillFrom(stateOf("echo productName;", 8))).toBe("productName");
|
||||
});
|
||||
|
||||
it("ignores a multi-line selection and falls back to the word", () => {
|
||||
expect(prefillFrom(stateOf("alpha\nbeta", 0, 8))).toBe("beta");
|
||||
});
|
||||
|
||||
it("gives nothing without an editor or a word", () => {
|
||||
expect(prefillFrom(undefined)).toBeNull();
|
||||
expect(prefillFrom(stateOf("a ; b", 3))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("find.open prefill", () => {
|
||||
it("replaces the query from the editor and drops a stale error", async () => {
|
||||
const find = useFindStore();
|
||||
const editor = (await import("../../src/stores/editor")).useEditorStore();
|
||||
const state = EditorState.create({ doc: "echo productName;", selection: EditorSelection.single(8) });
|
||||
editor.activeId = 1;
|
||||
vi.spyOn(editor, "syncOf").mockReturnValue({ state } as unknown as ReturnType<typeof editor.syncOf>);
|
||||
find.query = "(";
|
||||
find.error = "bad regex";
|
||||
await find.open({});
|
||||
expect(find.query).toBe("productName");
|
||||
expect(find.error).toBeNull();
|
||||
expect(find.visible).toBe(true);
|
||||
expect(paramsOf("search.find")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Find tool window", () => {
|
||||
it("searches on Enter and shows counts, files and highlighted matches", async () => {
|
||||
const { wrapper } = await mountFind();
|
||||
expect(wrapper.get("[data-test=find-status]").text()).toBe("Type a text and press Enter");
|
||||
await searchFor(wrapper, "foo");
|
||||
expect(paramsOf("search.find")[0]?.query).toBe("foo");
|
||||
expect(wrapper.find("[data-test=find-cancel]").exists()).toBe(true);
|
||||
await emit(results(7, "src/b.php", [[3, " $[foo] = 1;"]]));
|
||||
await emit(results(7, "a.php", [[0, "[foo]"], [4, "x [foo] y"]]));
|
||||
expect(wrapper.get("[data-test=find-status]").text()).toBe("Searching… 3 matches in 2 files");
|
||||
const files = wrapper.findAll("[data-test=find-file]").map((f) => f.text());
|
||||
expect(files).toEqual(["a.php2", "b.phpsrc1"]);
|
||||
const rows = wrapper.findAll("[data-test=find-row]");
|
||||
expect(rows.map((r) => r.text())).toEqual(["1foo", "5x foo y", "4$foo = 1;"]);
|
||||
expect(wrapper.findAll("[data-test=find-hit]").map((h) => h.text())).toEqual(["foo", "foo", "foo"]);
|
||||
await emit(done(7, { truncated: true, matches: 3, files: 2 }));
|
||||
expect(wrapper.get("[data-test=find-status]").text()).toContain("3 matches in 2 files · 12 ms");
|
||||
expect(wrapper.find("[data-test=find-truncated]").exists()).toBe(true);
|
||||
expect(wrapper.find("[data-test=find-submit]").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("says when nothing matched or the search was cancelled", async () => {
|
||||
const { wrapper } = await mountFind();
|
||||
await searchFor(wrapper, "zzz");
|
||||
await emit(done(7, { files: 0, matches: 0 }));
|
||||
expect(wrapper.get("[data-test=find-status]").text()).toBe("No matches");
|
||||
await searchFor(wrapper, "foo");
|
||||
await wrapper.get("[data-test=find-cancel]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(paramsOf("search.cancel")).toEqual([{ searchId: 8 }]);
|
||||
await emit(done(8, { cancelled: true, files: 0, matches: 0 }));
|
||||
expect(wrapper.get("[data-test=find-status]").text()).toContain("Cancelled");
|
||||
});
|
||||
|
||||
it("shows a refused regex as an alert", async () => {
|
||||
const { wrapper } = await mountFind();
|
||||
findError = { code: "invalid_params", message: "bad regex" };
|
||||
await searchFor(wrapper, "(");
|
||||
expect(wrapper.get("[data-test=find-error]").text()).toBe("bad regex");
|
||||
expect(wrapper.get("[data-test=find-query]").attributes("aria-invalid")).toBe("true");
|
||||
expect(wrapper.get("[data-test=find-status]").text()).toBe("");
|
||||
});
|
||||
|
||||
it("repeats the search when an option is toggled", async () => {
|
||||
const { wrapper } = await mountFind();
|
||||
await wrapper.get("[data-test=find-word]").trigger("click");
|
||||
expect(paramsOf("search.find")).toEqual([]);
|
||||
await searchFor(wrapper, "foo");
|
||||
await wrapper.get("[data-test=find-case]").trigger("click");
|
||||
await flushPromises();
|
||||
await wrapper.get("[data-test=find-regex]").trigger("click");
|
||||
await flushPromises();
|
||||
const sent = paramsOf("search.find");
|
||||
expect(sent.map((p) => [p.wholeWord, p.caseSensitive, p.regex])).toEqual([
|
||||
[true, false, false],
|
||||
[true, true, false],
|
||||
[true, true, true],
|
||||
]);
|
||||
expect(wrapper.get("[data-test=find-regex]").attributes("aria-pressed")).toBe("true");
|
||||
});
|
||||
|
||||
it("walks the results with the keyboard and opens them through editor.reveal", async () => {
|
||||
const { wrapper, reveals } = await mountFind();
|
||||
await searchFor(wrapper, "foo");
|
||||
await emit(results(7, "a.php", [[0, "[foo]"], [4, "x [foo]"]]));
|
||||
await emit(results(7, "b.php", [[2, "[foo]"]]));
|
||||
await wrapper.get("[data-test=find-query]").trigger("keydown", { key: "ArrowDown" });
|
||||
const list = wrapper.get("[data-test=find-results]");
|
||||
expect(document.activeElement).toBe(list.element);
|
||||
expect(list.attributes("aria-activedescendant")).toBe("find-row-0");
|
||||
await list.trigger("keydown", { key: "ArrowDown" });
|
||||
await list.trigger("keydown", { key: "ArrowDown" });
|
||||
await list.trigger("keydown", { key: "ArrowDown" });
|
||||
expect(list.attributes("aria-activedescendant")).toBe("find-row-2");
|
||||
await list.trigger("keydown", { key: "Home" });
|
||||
expect(list.attributes("aria-activedescendant")).toBe("find-row-0");
|
||||
await list.trigger("keydown", { key: "ArrowDown" });
|
||||
await list.trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(reveals).toEqual([{ path: "a.php", line: 4, column: 4 }]);
|
||||
await list.trigger("keydown", { key: "End" });
|
||||
expect(wrapper.findAll("[data-test=find-row]")[2]?.attributes("aria-selected")).toBe("true");
|
||||
await wrapper.findAll("[data-test=find-row]")[0]?.trigger("click");
|
||||
await flushPromises();
|
||||
expect(reveals).toEqual([
|
||||
{ path: "a.php", line: 4, column: 4 },
|
||||
{ path: "a.php", line: 0, column: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("focuses and selects the query field when find.open runs again", async () => {
|
||||
const { wrapper } = await mountFind();
|
||||
const input = wrapper.get("[data-test=find-query]").element as HTMLInputElement;
|
||||
document.body.focus();
|
||||
await useFindStore(pinia).open({});
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(input);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bottom panel", () => {
|
||||
it("collapses to its header, expands, closes and resizes with the keyboard", async () => {
|
||||
const closes: number[] = [];
|
||||
const wrapper = mount(BottomPanel, {
|
||||
props: {
|
||||
title: "Find",
|
||||
open: true,
|
||||
height: 200,
|
||||
minHeight: 100,
|
||||
maxHeight: 230,
|
||||
"onUpdate:open": (open: boolean) => wrapper.setProps({ open }),
|
||||
"onUpdate:height": (height: number) => wrapper.setProps({ height }),
|
||||
onClose: () => closes.push(1),
|
||||
},
|
||||
slots: { default: "<p data-test='content'>results</p>" },
|
||||
});
|
||||
const splitter = wrapper.get("[data-test=bottom-panel-splitter]");
|
||||
await splitter.trigger("keydown", { key: "ArrowUp" });
|
||||
expect(wrapper.get(".bottom-panel__body").attributes("style")).toContain("height: 212px");
|
||||
await splitter.trigger("keydown", { key: "ArrowUp", shiftKey: true });
|
||||
expect(wrapper.get(".bottom-panel__body").attributes("style")).toContain("height: 230px");
|
||||
await splitter.trigger("keydown", { key: "ArrowDown", shiftKey: true });
|
||||
await splitter.trigger("keydown", { key: "ArrowDown", shiftKey: true });
|
||||
await splitter.trigger("keydown", { key: "ArrowDown", shiftKey: true });
|
||||
expect(wrapper.get(".bottom-panel__body").attributes("style")).toContain("height: 100px");
|
||||
await wrapper.get("[data-test=bottom-panel-toggle]").trigger("click");
|
||||
expect(wrapper.find("[data-test=content]").exists()).toBe(false);
|
||||
expect(wrapper.find("[data-test=bottom-panel-splitter]").exists()).toBe(false);
|
||||
await wrapper.get("[data-test=bottom-panel-toggle]").trigger("click");
|
||||
expect(wrapper.find("[data-test=content]").exists()).toBe(true);
|
||||
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
|
||||
expect(closes).toEqual([1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("find.open", () => {
|
||||
/** Mounts the main layout with the commands store started. */
|
||||
async function mountLayout(): Promise<VueWrapper> {
|
||||
const wrapper = mount(MainLayout, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } },
|
||||
});
|
||||
mounted.push(wrapper);
|
||||
await useCommandsStore(pinia).start();
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
it("is registered with its own shortcut", async () => {
|
||||
await mountLayout();
|
||||
const registered = paramsOf("ui.registerCommands")[0]?.commands as { id: string; defaultShortcut?: string }[];
|
||||
expect(registered.find((c) => c.id === "find.open")?.defaultShortcut).toBe("Mod+Alt+F");
|
||||
});
|
||||
|
||||
it("opens the panel from the shortcut, then hides and keeps the results", async () => {
|
||||
const wrapper = await mountLayout();
|
||||
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false);
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "f", code: "KeyF", ctrlKey: true, altKey: true, bubbles: true }));
|
||||
await flushPromises();
|
||||
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(true);
|
||||
expect(document.activeElement).toBe(wrapper.get("[data-test=find-query]").element);
|
||||
await wrapper.get("[data-test=bottom-panel-close]").trigger("click");
|
||||
expect(wrapper.find("[data-test=bottom-panel]").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("searches at once for an agent's uiCommand with a query", async () => {
|
||||
const wrapper = await mountLayout();
|
||||
await emit({ kind: "uiCommand", id: "find.open", params: { query: "needle", wholeWord: true, include: "*.php" } });
|
||||
expect(paramsOf("search.find")).toEqual([
|
||||
{ query: "needle", regex: false, caseSensitive: false, wholeWord: true, include: ["*.php"], exclude: [] },
|
||||
]);
|
||||
await emit(results(7, "a.php", [[0, "[needle]"]]));
|
||||
expect(wrapper.findAll("[data-test=find-row]")).toHaveLength(1);
|
||||
expect((wrapper.get("[data-test=find-query]").element as HTMLInputElement).value).toBe("needle");
|
||||
});
|
||||
});
|
||||
|
|
@ -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)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
);
|
||||
expect(typeof value).toBe("string");
|
||||
expect(value.trim()).not.toBe("");
|
||||
|
|
|
|||
|
|
@ -260,6 +260,7 @@ describe("CommandPalette", () => {
|
|||
expect(rows(wrapper)).toEqual([
|
||||
"project.close",
|
||||
"palette.open",
|
||||
"find.open",
|
||||
"project.openDialog",
|
||||
"app.quit",
|
||||
"editor.reveal",
|
||||
|
|
@ -281,7 +282,7 @@ describe("CommandPalette", () => {
|
|||
const wrapper = await mountPalette();
|
||||
await press(PALETTE_KEY);
|
||||
await type(wrapper, "o");
|
||||
expect(rows(wrapper).slice(0, 2)).toEqual(["project.openDialog", "palette.open"]);
|
||||
expect(rows(wrapper).slice(0, 3)).toEqual(["project.openDialog", "find.open", "palette.open"]);
|
||||
await type(wrapper, "open f");
|
||||
expect(rows(wrapper)[0]).toBe("project.openDialog");
|
||||
await press({ key: "ArrowDown" });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue