Compare commits

...

2 commits

Author SHA1 Message Date
danny
b3642e53ea PM: merge M4.3 diff viewer
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:45:34 +01:00
danny
8360ffc2e2 M4.3: side-by-side diff viewer with next/previous change
vcs.showDiff {path?, staged?} (Mod+Alt+Shift+D) opens a "Diff: <name>"
tab in the editor area: @codemirror/merge (MIT, loaded lazily, 27 kB /
9.7 kB gzip), with the index (or HEAD for the staged view) read-only on
the left, line breaks normalised to LF, and the working copy on the right,
editable through its normal engine buffer. vcs.nextChange (Alt+Shift+])
and vcs.previousChange (Alt+Shift+[) move between chunks. Binary, too
large, failed and deleted files show a notice. Entry points: the Changes
window, a new project tree context menu (Open, Show Diff; right click or
Shift+F10) and the palette/menu. Colours come from the --lt-vcs-* tokens.
21 Vitest tests; parity docs updated (Git 6% -> 8%, est.).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:44:56 +01:00
23 changed files with 1836 additions and 24 deletions

View file

@ -64,7 +64,7 @@ claude mcp add lutra -- lutra mcp
## Status
**Pre-alpha (2026-10-22): M3 done, the MVP is feature-complete.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 added find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); M3 added an integrated terminal (`Mod+Shift+T`) and PHP language features from Phpactor: errors underlined as you type (Problems tab `Mod+Alt+P`), code completion, documentation on hover and parameter info, go to definition (`F12` or Ctrl+click), find references (`Shift+F12`) and rename (`F2`), plus the `lutra` CLI, an MCP server (`lutra mcp`), an app menu and autosave. Git (M4) has started: a Changes tab (`Mod+Alt+Shift+G`) stages files and commits them, on the way to alpha. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
**Pre-alpha (2026-10-22): M3 done, the MVP is feature-complete.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 added find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); M3 added an integrated terminal (`Mod+Shift+T`) and PHP language features from Phpactor: errors underlined as you type (Problems tab `Mod+Alt+P`), code completion, documentation on hover and parameter info, go to definition (`F12` or Ctrl+click), find references (`Shift+F12`) and rename (`F2`), plus the `lutra` CLI, an MCP server (`lutra mcp`), an app menu and autosave. Git (M4) has started: a Changes tab (`Mod+Alt+Shift+G`) stages files and commits them, the gutter marks changed lines, and a side-by-side diff (`Mod+Alt+Shift+D`) shows each change, on the way to alpha. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,

View file

@ -2,7 +2,7 @@
**Stage: pre-alpha (M3 done: MVP feature-complete)** · next: hardening and Git (M4); 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-22 · **Last updated:** 2026-10-25 · **Change:** minor (M4.4: gutter markers and status colours, Git 6%) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-26 · **Change:** minor (M4.3: diff viewer, Git 8%) · **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) | **~21%** (32 of 155 feature units of the public PhpStorm help have at least partial support) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~5.6%** (Editor core 11% × weight 12, Navigation 13% × weight 10, Code completion 5% × weight 10, Inspections 5% × weight 8, Refactoring 3% × weight 7, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Git 6% × weight 8, Settings 8% × weight 1, of 101 = 570/101) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~5.8%** (Editor core 11% × weight 12, Navigation 13% × weight 10, Code completion 5% × weight 10, Inspections 5% × weight 8, Refactoring 3% × weight 7, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Git 8% × weight 8, Settings 8% × weight 1, of 101 = 586/101) | estimated |
| **MVP (M1–M3)** | **done** in ~26 h of agent time (M1 ~5.6 h, M2 ~6.1 h, M3 ~14 h, measured); was ~190 h before calibration | measured (factor per cycle: C1 0.07, C2 0.10, C3 0.14, C4 0.17) |
| **To full parity** | **~520 h** at the current factor of ~0.18 (range 300–3,300 h; the factor has risen each cycle, and deep areas such as type inference and inspections have no data yet) | estimated |
@ -49,7 +49,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a
| Inspections and quick-fixes | 4% (est.) | ~290 |
| Refactoring | 3% (est.) | ~244 |
| Code style and formatting | 0% | ~120 |
| Version control (Git) | 6% (est.) | ~136 |
| Version control (Git) | 8% (est.) | ~128 |
| Terminal | 15% (est.) | ~26 |
| Run configurations | 0% | ~50 |
| Debugger (Xdebug) | 0% | ~120 |
@ -75,6 +75,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | What landed |
|---|---|
| 2026-10-26 | M4.3: see what you changed side by side. Double-click a file in the Changes tab, right-click it in the project tree, or press `Mod+Alt+Shift+D`, and a "Diff: <name>" tab shows the staged version (or the last commit) on the left and your file on the right, where you can keep editing. `Alt+Shift+]` and `Alt+Shift+[` jump between changes; binary and very large files get a short notice instead. |
| 2026-10-25 | M4.4: Lutra shows what you changed. A coloured bar in the gutter marks lines you added or edited since the staged version, and a small notch marks deleted lines; it follows your typing. File names in the project tree and the tabs are coloured by their Git status: new, modified, deleted, untracked, conflicted and ignored. |
| 2026-10-25 | M4.2: a Changes tab for Git (`Mod+Alt+Shift+G`, menu Git › Changes) lists staged, changed and untracked files. Tick a file or a whole group to stage it, untick to unstage, write a message and press Commit (or Ctrl+Enter); Amend rewrites the last commit. Lutra saves your open files first, and the toast shows the new commit's short hash. Double-click opens the file (the diff viewer follows). |
| 2026-10-22 | M3.4: PHP code completes as you type. After `->`, `::`, `$` or a few letters Lutra shows Phpactor's suggestions with an icon per kind, and accepting one also adds its import. Resting the mouse on a class or method shows its documentation (`Mod+I` at the cursor), and typing `(` or `,` shows the parameters with the current one highlighted. A suggestion takes about 60–110 ms on Windows. |
@ -103,6 +104,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | M4.3: diff viewer; Git 6% → 8% (est.), hours ~136 → ~128, feature depth ~5.6% → ~5.8%, progress log |
| 2026-10-25 | minor | M4.4: gutter change markers and status colours; Git 4% → 6% (est.), hours ~138 → ~136, feature depth ~5.4% → ~5.6%, progress log |
| 2026-10-25 | minor | M4.2: Changes tool window; Git 0% → 4% (est.), feature depth ~5.1% → ~5.4%, progress log |
| 2026-10-22 | minor | C4 review: M3 done (MVP feature-complete, ~14 h measured), breadth recounted 28 → 32 units (~21%), factor 0.17, full parity ~520 h at ×0.18 |

View file

@ -1,6 +1,6 @@
# Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4) · **Last updated:** 2026-10-25
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3) · **Last updated:** 2026-10-26
## Overview
@ -609,6 +609,19 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Measured** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7944, a temp repository with the owner's global `core.autocrlf`; each number includes the control round trip and the pending wait): the first `git.lineChanges` 332 ms (git detection, opening the repository, reading the blob), then 0.4–1.4 ms with the index text cached; after `git.stage` (158 ms) the next call reads the blob again and returns no ranges. Screenshots read in both themes: a modified bar, a deleted notch and an added bar where expected, no markers after staging, tabs in the modified and untracked colours, no markers for the untracked file. No keys were sent (owner at the PC).
- **Tests:** `cmd::git_lines` unit and property tests (line splitting, kinds, line endings, empty files, cache caps and generation, ranges in order and inside the buffer); `crates/engine/tests/git_lines.rs` (4 tests against real temp repositories: added/modified/deleted, a CRLF buffer against an autocrlf LF blob, staging drops the cache, an untracked file and no repository, bad params); Vitest `ui/tests/editor/gitGutter.test.ts` (12: reading, building, query on show, debounce, stale answers, failures, refresh, mapping), `ui/tests/vcs/vcsStatus.test.ts` (colours, reading, coalescing, events, tabs) and one tree test in `ui/tests/project/ProjectTree.test.ts`.
### Diff viewer (M4.3)
- **Where:** `ui/src/components/vcs/diff/`: `diff.ts` is the Pinia store of the diff tabs, `DiffView.vue` the view (loaded with `defineAsyncComponent`, so `@codemirror/merge` sits in its own 27 kB chunk, 9.7 kB gzip, not in the start bundle), `navigation.ts` the bridge to the next/previous change commands, `commands.ts` the handlers, supplied by the editor area. The project tree's context menu is `ui/src/components/project/TreeContextMenu.vue`.
- **Dependency:** `@codemirror/merge` 6.12 (MIT, Marijn Haverbeke; depends only on CodeMirror packages, `@lezer/highlight` and `style-mod`).
- **Commands** (UI commands, menu group Git): `vcs.showDiff {path?, staged?}` `Mod+Alt+Shift+D` opens the diff of a file (without a path: the active diff's or editor tab's file; enabled while a project is open); `vcs.nextChange` `Alt+Shift+]` and `vcs.previousChange` `Alt+Shift+[` move the cursor of the focused side (else the working copy) to the next or previous changed chunk, wrapping, and are enabled while a diff with changes shows. The shortcuts are Lutra's own: checked against the public default keymaps (Windows, macOS; the target uses other keys for show diff and next/previous difference), Lutra's registered shortcuts and CodeMirror's `basicSetup` keys.
- **Entry points:** double-click or Enter in the Changes window (`staged` true for a Staged row), the project tree's context menu (right click on a file, or Shift+F10 / the context-menu key on the selected file: Open, Show Diff), the palette and the menu.
- **Tabs:** diff tabs live in the diff store, not in the editor store: one per path and side (`staged:` / `work:` key), shown after the file tabs and titled "Diff: <name>" ("Diff: <name> (staged)" for the staged view). A diff covers the editor tab that was active when it was activated (the anchor; a synchronous watch on `editor.activeId` re-anchors while the diff opens its file and hides the diff when any other editor tab becomes active). Clicking a file tab hides it; closing the working copy's buffer, a project open or a project close closes diff tabs.
- **Left side:** `git.show {path, ref}` through `runWaiting`: `staged: true` compares with HEAD, otherwise with the index (equal to HEAD without staged changes, so a partly staged file shows only what is left to stage). A path missing at the ref is an empty side (a new file). Line breaks are normalised to `
` (git returns the blob as stored, LF under `core.autocrlf`; CodeMirror compares lines, so a CRLF working copy lines up). Re-read on `gitChanged`; a changed text replaces the left document in place. Binary or too large (`git.show`'s flags) shows a notice and opens nothing; a failed `git.show` shows git's message.
- **Right side:** the working copy is opened as an ordinary engine buffer through the editor store (it also gets its own file tab, hidden while the diff shows), so edits, saves, autosave, the journal and diagnostics work as in any tab. The right editor starts from the buffer's `BufferSync` state with the normal editor extensions; an update listener hands each local change to the sync (`sync.dispatch`, the diff of the documents if they ever differ), which sends `buffer.edit` as usual. Engine changes of the buffer (reload, an agent's edit) arrive as `bufferChanged`; once the sync has taken them over (`idle()`), the difference is applied to the right editor outside its undo history. A file missing from the working copy (deleted) shows an empty read-only side and a notice; the editor's error line is not raised for it.
- **Look:** both sides use the Lutra editor theme and the file's language; changed lines are tinted with `color-mix` of `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right) into `--lt-editor-bg`, changed words more strongly, a change bar in each gutter, unchanged stretches over 8 lines collapse to a row (3 lines of context). No colour outside the tokens.
- **Tests:** `ui/tests/vcs/DiffView.test.ts` (21 Vitest tests against a fake engine: params and `git.show` parsing, EOL normalisation, index and HEAD sides, one tab per side, the palette without a path, bad params and no file as toasts, disabled without a project, edits on the right reaching `buffer.edit`, engine changes reaching the right side, the left side refresh on `gitChanged`, closing with the buffer, binary / too large / git error / deleted / new file, switching between diff and file tabs, next/previous change with wrap-around, the tree context menu by right click and by Shift+F10 with Escape).
## Decisions (M0)
| Question | Decision | Why |
@ -626,6 +639,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | M4.3: diff viewer (`vcs.showDiff`, `vcs.nextChange`, `vcs.previousChange`, `@codemirror/merge` loaded lazily, the project tree's context menu) |
| 2026-10-25 | minor | M4.4: `git.lineChanges` (index cache, `similar` line diff off the lock), gutter change markers, Git status colours in the tree and tabs |
| 2026-10-25 | minor | M4.2: Changes tool window (`vcs.openChanges`, `vcs.commit`, `vcs.refresh`, staging, commit after `flushDirty`) |
| 2026-10-25 | minor | M4.1: Git backend (`lutra-vcs`, `git.*` commands, `gitChanged`, `git.executable`) |

View file

@ -1,6 +1,6 @@
# Gaps
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4); G14 English UI catalog in place · **Last updated:** 2026-10-25
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3); G14 English UI catalog in place · **Last updated:** 2026-10-26
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.
@ -13,7 +13,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h |
| G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), diff viewer, branch popup, log, blame, conflicts, stash, remotes | M4 | ~136 h |
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), branch popup, log, blame, conflicts, stash, remotes | M4 | ~128 h |
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
| G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h |
@ -52,6 +52,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | G8 shrunk: diff viewer (M4.3) |
| 2026-10-25 | minor | G8 shrunk: gutter markers and status colours (M4.4) |
| 2026-10-25 | minor | G8 shrunk: Changes window (M4.2) |
| 2026-10-25 | minor | G8 shrunk: Git backend (M4.1) |

View file

@ -1,6 +1,6 @@
# Milestones
> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours) · **Last updated:** 2026-10-25
> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer) · **Last updated:** 2026-10-26
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 were scaled ×0.1 to ×0.15 (measured factors: C1 0.07, C2 0.10, C3 0.14, C4 0.17; next cycle ×0.18); M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value).
@ -10,7 +10,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
| 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 | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | done 2026-10-22 (C4: M3.1 PHP detection and Phpactor download, M3.2 LSP client, M3.3 engine wiring and diagnostics, M3.4 completion, hover and signature help, M3.5 definition, references and rename, M3.6 integrated terminal, M3.7 CLI and single instance, M3.8 MCP server, M3.9 app menu, M3.10 autosave; live check with real key presses pending) | ~14 (measured) |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours done) | ~136 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer done) | ~128 |
| M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 |
| M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 |
| M7 | Workbench and tools: Deployment (FTP/SFTP/local mappings, upload/download, compare with server, save before deploy, optional upload on save per server), Local History, diff tool (files/folders), scratch files, macros, keymap editor, user themes, plug-in system, Database tools and SQL, HTTP Client, SSH/Docker/Vagrant/WSL, File Watchers, external tools, TODO view, tasks and contexts | not started | ~900 |
@ -34,6 +34,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | M4.3 diff viewer |
| 2026-10-25 | minor | M4.4 gutter markers and status colours |
| 2026-10-25 | minor | M4.2 Changes tool window |
| 2026-10-24 | minor | M4.1 Git backend; M4 in progress |

View file

@ -1,6 +1,6 @@
# Target-app parity
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2) · **Last updated:** 2026-10-25 · **Target:** PhpStorm 2026.x
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2), diff viewer (M4.3) · **Last updated:** 2026-10-26 · **Target:** PhpStorm 2026.x
## How this is measured
@ -22,7 +22,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
| Inspections and quick-fixes | 8 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own |
| Refactoring | 7 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. |
| Code style and formatting | 4 | 0% | everything | ~120 (est.) | — |
| Git | 8 | 6% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer, branch widget (C5 wave 3); log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~136 (est.) | M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing and staging work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, branches, log, blame and remotes do not yet. |
| Git | 8 | 8% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branch widget (C5 wave 3); log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~128 (est.) | M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: <name>" tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing and staging work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, branches, log, blame and remotes do not yet. |
| Terminal | 3 | 15% (est.) | renaming and splitting tabs, sessions kept across restarts, search in the output, clickable paths and links, drag and drop, command completion, terminal settings (shell path, start directory, environment, font, cursor shape, bell, copy on selection, middle-click paste), a key back to the editor, the PHP interpreter in `PATH`, a terminal in a file's directory, confirmation before killing a running process, moving a terminal into the editor | ~26 (est.) | M3.6: `crates/terminal` runs the shell in a pseudo terminal (`portable-pty`: ConPTY on Windows, Unix pty elsewhere) on its own reader, writer and waiter threads: UTF-8 split across reads joined, invalid bytes U+FFFD, a 1 MiB output buffer per session with backpressure (the shell waits, nothing is dropped while it runs), a non-blocking input queue, resize, kill, exit codes. Engine `terminal.create {cwd?, shell?, cols, rows}` / `terminal.input` / `terminal.resize` / `terminal.close`, events `terminalOutput` (≤ 64 KiB per terminal and 256 KiB per pump, round-robin) and `terminalExited {code}`; terminals close with the project and on `app.quit`. UI: a Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, several terminals as sub-tabs (Local, Local (2)…) with close and new buttons, output replayed after collapsing the panel, copy (`Mod+Shift+C`, `Ctrl+C` with a selection) and paste (`Mod+Shift+V`, `Ctrl+V`), a focus rule that leaves plain Ctrl keys to the shell, Lutra's own ANSI colours (`--lt-terminal-*`, all text colours ≥ 4.5:1), `terminal.open` `Mod+Shift+T`. Tests: 8 session tests with real `cmd.exe` (echo, exit code, input, 6,000 multibyte characters without U+FFFD, 30,000 lines through a full buffer without losing a line, resize, kill, spawn errors) and UTF-8 proptests (`crates/terminal`), 3 engine tests (`crates/engine/tests/terminal.rs`), a TCP control test create → output → input → exit (`crates/control/tests/terminal.rs`), 20 Vitest tests with a mocked xterm (`ui/tests/terminal/`). Live check (Windows 11, debug build with bundled UI, control port 7936, temp project): `terminal.open` showed a pwsh prompt in the project root, first `terminalOutput` 0.2–0.5 s after the command; `php -v` printed PHP 8.4.24 within 0.5–1.5 s; `dir` listed the project; resizing the window changed the shell's width 144 → 190 → 105 → 142 columns (pwsh `WindowSize`); a second terminal as sub-tab "Local (2)"; Find and Terminal as bottom tabs; dark and light screenshots read; `exit 3` gave `terminalExited {code: 3}`; `app.quit` ended the app and its shells (measured). The live check found two bugs, fixed before the commit: xterm's own black viewport background showed as a bar under the last row, and programs printing ANSI white (PSReadLine) were unreadable on the light theme, so xterm now enforces a 4.5:1 minimum contrast. Typing, clicking and copy/paste were not driven in the app (the control channel has no input method); Vitest covers them. Graded against `plan/phpstorm/10-terminal.md` |
| Run configurations | 2 | 0% | everything | ~50 (est.) | — |
| Debugger | 5 | 0% | everything | ~120 (est.) | — |
@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | M4.3: Git 6% → 8% (est.), diff viewer; hours 136 → 128 |
| 2026-10-25 | minor | M4.4: Git 4% → 6% (est.), gutter change markers and status colours; hours 138 → 136 |
| 2026-10-25 | minor | H3: Inspections and quick-fixes 4% → 5% (est.), `php -l` on Windows; Code completion evidence (indexing ~3× faster), score unchanged; hours 290 → 287 and 240 → 238 |
| 2026-10-25 | minor | M4.2: Git 1% → 4% (est.), Changes tool window; hours 148 → 138 |

View file

@ -1,11 +1,12 @@
# Tooling checklist
> **Status:** integrated terminal partial (M3.6), Git backend and Changes window partial (M4.1, M4.2) · **Last updated:** 2026-10-25
> **Status:** integrated terminal partial (M3.6), Git backend, Changes window and diff viewer partial (M4.1, M4.2, M4.3) · **Last updated:** 2026-10-26
- [ ] Integrated terminal with tabs
- M3.6 (2026-10-18): PTY sessions (pwsh → powershell → cmd on Windows, `$SHELL` or `/bin/sh` on Unix; cwd = project root) in the bottom panel's Terminal tab, several terminals as sub-tabs, xterm.js rendering with Lutra's colours, copy/paste, resize, exit codes; closed with the project. Missing: settings, persistence across restarts, split tabs, search, links, the PHP interpreter in `PATH`.
- [ ] Git: status, diff, commit, push/pull, branches, log, blame, conflict resolution
- M4.2 (2026-10-25): status, stage/unstage and commit (with amend) from the Changes tab, saving open files first. Missing: diff, gutter markers, branches UI, push/pull, log, blame, conflicts, stash.
- M4.3 (2026-10-26): a side-by-side diff of the working copy against the staged version or the last commit, editable on the right, with next/previous change. Missing: comparing with other revisions or branches, a unified view, three-way merge for conflicts.
- [ ] Composer: install, update, require, scripts
- [ ] PHP interpreters: local, Docker
- [ ] Xdebug via DAP: breakpoints, stepping, variables, watches
@ -19,6 +20,7 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | Git: diff viewer (M4.3) |
| 2026-10-25 | minor | Git: status, staging and commit from the Changes tab (M4.2) |
| 2026-10-18 | minor | Integrated terminal partial (M3.6) |
| 2026-10-13 | major | Baseline |

View file

@ -1,6 +1,6 @@
# UI parity checklist
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4) · **Last updated:** 2026-10-25
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3) · **Last updated:** 2026-10-26
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
@ -43,11 +43,13 @@
- [ ] Git tool window
- M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). Missing: a tree view and grouping by directory or module, changelists, chunk staging, a context menu (rollback, delete, add to .gitignore), recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`.
- M4.4 (2026-10-25): the editor gutter shows a bar beside lines added or changed since the staged version and a notch where lines were deleted (tooltips from the catalog), updated 150 ms after typing and whenever Git changes; file names in the project tree and the tabs take the Git status colour (added, modified, deleted, untracked, conflicted; ignored entries inside a repository). Vitest. Missing: clicking a marker to see the old text, revert or stage the chunk, next/previous change, markers against HEAD, coloured directories.
- M4.3 (2026-10-26): "Diff: <name>" tabs in the editor area after the file tabs (`vcs.showDiff` `Mod+Alt+Shift+D`, menu Git › Show Diff; double-click or Enter in Changes; right click or Shift+F10 on a file in the project tree → Show Diff): the staged version or the last commit on the left, read-only, and the working copy on the right, editable like its own tab; a caption says what is compared; changed lines and words tinted with the VCS tokens, a change bar in each gutter, unchanged stretches collapsed to a clickable row; next/previous change `Alt+Shift+]` / `Alt+Shift+[` (wrapping); notices for binary, too large and deleted files and for git's errors. The project tree got its first context menu (Open, Show Diff; WAI-ARIA menu, keyboard). Vitest. Missing: unified view, revert/stage arrows between the sides, synchronised horizontal scrolling, whitespace and highlighting options, comparing with any revision, a diff window of its own, more tree context menu items.
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-26 | minor | Diff viewer and the project tree's context menu (M4.3) |
| 2026-10-25 | minor | Git change markers in the gutter, status colours in the tree and tabs (M4.4) |
| 2026-10-25 | minor | Changes tool window (M4.2) |
| 2026-10-25 | minor | Themes: banner-aligned palettes, diagnostic and VCS colours, completion icon colours (H5) |

View file

@ -26,6 +26,7 @@
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.13.1",
"@codemirror/lint": "^6.9.7",
"@codemirror/merge": "^6.12.3",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.14",
"@lezer/highlight": "^1.2.5",

14
ui/pnpm-lock.yaml generated
View file

@ -38,6 +38,9 @@ importers:
'@codemirror/lint':
specifier: ^6.9.7
version: 6.9.7
'@codemirror/merge':
specifier: ^6.12.3
version: 6.12.3
'@codemirror/state':
specifier: ^6.7.6
version: 6.7.6
@ -182,6 +185,9 @@ packages:
'@codemirror/lint@6.9.7':
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
'@codemirror/merge@6.12.3':
resolution: {integrity: sha512-Wq9wXrp41cW/nIpi1CQPyNwD+36kg8KIX676ym0Hyfn3Dpr+XQHNAIsZYVNlaivuVB4SAASbreG3V0VXinbqZA==}
'@codemirror/search@6.7.2':
resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==}
@ -1527,6 +1533,14 @@ snapshots:
'@codemirror/view': 6.43.14
crelt: 1.0.7
'@codemirror/merge@6.12.3':
dependencies:
'@codemirror/language': 6.13.1
'@codemirror/state': 6.7.6
'@codemirror/view': 6.43.14
'@lezer/highlight': 1.2.5
style-mod: 4.1.4
'@codemirror/search@6.7.2':
dependencies:
'@codemirror/state': 6.7.6

View file

@ -38,5 +38,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+Alt+Shift+M" },
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" },
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
];

View file

@ -7,9 +7,11 @@
* palette (`commands/store.ts`): the area supplies their behaviour with the
* active buffer as context and says when they can run. It also supplies the
* UI commands `editor.reveal` (`reveal.ts`) and the assist commands
* (`assist/commands.ts`).
* (`assist/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the tab bar;
* while one is active the diff view replaces the editor, and the area
* supplies the diff commands.
*/
import { onBeforeUnmount, onMounted } from "vue";
import { defineAsyncComponent, onBeforeUnmount, onMounted } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
@ -18,9 +20,15 @@ import CodeEditor from "./CodeEditor.vue";
import EditorTabs from "./EditorTabs.vue";
import { reveal, REVEAL_COMMAND } from "./reveal";
import * as assist from "./assist/commands";
import { provideDiffCommands } from "../vcs/diff/commands";
import { useDiffStore } from "../vcs/diff/diff";
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
const DiffView = defineAsyncComponent(() => import("../vcs/diff/DiffView.vue"));
const editor = useEditorStore();
const commands = useCommandsStore();
const diff = useDiffStore();
/** Withdraws the command handlers; filled while mounted. */
let withdraw: (() => void)[] = [];
@ -36,6 +44,7 @@ onMounted(() => {
commands.provide(assist.COMPLETE_COMMAND, { run: assist.completeAtCursor, enabled: assist.assistEnabled }),
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
...provideDiffCommands(commands),
];
});
@ -53,10 +62,10 @@ onBeforeUnmount(() => {
class="editor-area"
data-test="editor-area"
>
<template v-if="editor.tabs.length > 0">
<template v-if="editor.tabs.length > 0 || diff.tabs.length > 0">
<EditorTabs />
<div
v-if="editor.activeTab?.notice"
v-if="!diff.visible && editor.activeTab?.notice"
class="editor-area__notice"
:class="{ 'editor-area__notice--error': editor.activeTab.notice.kind === 'error' }"
role="status"
@ -72,7 +81,8 @@ onBeforeUnmount(() => {
{{ t("common.dismiss") }}
</button>
</div>
<CodeEditor />
<DiffView v-if="diff.visible" />
<CodeEditor v-else-if="editor.activeTab" />
</template>
<div
v-else

View file

@ -5,15 +5,51 @@
* A click activates a tab, a middle click or the close button closes it,
* Left/Right move between tabs. A dot marks unsaved changes. Closing a
* dirty tab asks first (see the editor store). Names are coloured by their
* Git status (`--lt-vcs-*`, M4.4).
* Git status (`--lt-vcs-*`, M4.4). Diff tabs (M4.3, `vcs/diff/diff.ts`)
* follow the editor tabs; while one is active, no editor tab is marked
* active.
*/
import { X } from "@lucide/vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore } from "../../stores/vcsStatus";
import { useDiffStore } from "../vcs/diff/diff";
const editor = useEditorStore();
const vcs = useVcsStatusStore();
const diff = useDiffStore();
/**
* Whether an editor tab is the active one.
*
* @param id - buffer id of the tab.
*/
function isActive(id: number): boolean {
return id === editor.activeId && !diff.visible;
}
/**
* Shows an editor tab (and hides an active diff).
*
* @param id - buffer id of the tab.
*/
function activateTab(id: number): void {
diff.deactivate();
editor.activate(id);
}
/**
* Closes a diff tab on a middle click.
*
* @param event - the auxiliary click.
* @param key - key of the diff tab.
*/
function onDiffAuxClick(event: MouseEvent, key: string): void {
if (event.button === 1) {
event.preventDefault();
diff.close(key);
}
}
/**
* Closes a tab on a middle click.
@ -42,7 +78,7 @@ function onKeydown(event: KeyboardEvent): void {
event.preventDefault();
const next = editor.tabs[(index + step + editor.tabs.length) % editor.tabs.length];
if (next) {
editor.activate(next.id);
activateTab(next.id);
}
}
</script>
@ -59,14 +95,14 @@ function onKeydown(event: KeyboardEvent): void {
v-for="tab in editor.tabs"
:key="tab.id"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.id === editor.activeId }"
:class="{ 'tabs__tab--active': isActive(tab.id) }"
role="tab"
:tabindex="tab.id === editor.activeId ? 0 : -1"
:aria-selected="tab.id === editor.activeId"
:tabindex="isActive(tab.id) ? 0 : -1"
:aria-selected="isActive(tab.id)"
:title="tab.path"
:data-id="tab.id"
data-test="editor-tab"
@click="editor.activate(tab.id)"
@click="activateTab(tab.id)"
@mousedown.middle.prevent
@auxclick="onAuxClick($event, tab.id)"
>
@ -92,6 +128,33 @@ function onKeydown(event: KeyboardEvent): void {
<X :size="12" />
</button>
</div>
<div
v-for="tab in diff.tabs"
:key="tab.key"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.key === diff.activeKey }"
role="tab"
:tabindex="tab.key === diff.activeKey ? 0 : -1"
:aria-selected="tab.key === diff.activeKey"
:title="tab.path"
:data-key="tab.key"
data-test="diff-tab"
@click="diff.activate(tab.key)"
@mousedown.middle.prevent
@auxclick="onDiffAuxClick($event, tab.key)"
>
<span class="tabs__name">{{ tab.staged ? t("vcs.diff.tabTitleStaged", { name: tab.name }) : t("vcs.diff.tabTitle", { name: tab.name }) }}</span>
<button
class="tabs__close"
type="button"
tabindex="-1"
:aria-label="t('vcs.diff.closeTab', { name: tab.name })"
data-test="diff-tab-close"
@click.stop="diff.close(tab.key)"
>
<X :size="12" />
</button>
</div>
</div>
</template>

View file

@ -10,6 +10,8 @@
* the engine listed only partly ends with a "listing truncated" note.
* File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside
* a repository, ignored entries take the ignored colour.
* A right click on a file, or Shift+F10 / the context-menu key on the
* selected file, opens its context menu (`TreeContextMenu.vue`, M4.3).
*/
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
@ -18,6 +20,7 @@ import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore, type VcsColour } from "../../stores/vcsStatus";
import type { TreeEntry } from "./engineEvents";
import TreeContextMenu from "./TreeContextMenu.vue";
const project = useProjectStore();
const editor = useEditorStore();
@ -89,6 +92,40 @@ function isPhp(name: string): boolean {
return /\.(php|phtml|inc)$/i.test(name);
}
/** The open context menu: the file and where it shows; null when closed. */
const menu = ref<{ path: string; name: string; x: number; y: number } | null>(null);
/**
* Opens the context menu of a file; folders have none yet.
*
* @param entry - the entry.
* @param x - window x of the menu.
* @param y - window y of the menu.
*/
function openMenu(entry: TreeEntry, x: number, y: number): void {
if (entry.kind !== "file") {
return;
}
project.select(entry.path);
menu.value = { path: entry.path, name: entry.name, x, y };
}
/**
* Opens the context menu of the selected file from the keyboard, below its row.
*
* @param entry - the selected entry.
*/
function openMenuAtRow(entry: TreeEntry): void {
const rect = document.getElementById(rowId(entry.path))?.getBoundingClientRect();
openMenu(entry, rect ? rect.left + 24 : 0, rect ? rect.bottom : 0);
}
/** Closes the context menu and gives the focus back to the tree. */
function closeMenu(): void {
menu.value = null;
treeEl.value?.focus();
}
/** Scrolls the selected row into view after the DOM updated. */
async function revealSelected(): Promise<void> {
await nextTick();
@ -209,6 +246,13 @@ function onKeydown(event: KeyboardEvent): void {
activate(row.entry);
}
break;
case "ContextMenu":
case "F10":
if (!row || (event.key === "F10" && !event.shiftKey)) {
return;
}
openMenuAtRow(row.entry);
break;
default:
return;
}
@ -256,6 +300,7 @@ function onFocus(): void {
data-test="tree-row"
@click="onRowClick(row.entry, false)"
@dblclick="activate(row.entry)"
@contextmenu.prevent="openMenu(row.entry, $event.clientX, $event.clientY)"
>
<span
class="tree__chevron"
@ -325,6 +370,16 @@ function onFocus(): void {
{{ row.error.message }}
</div>
</template>
<Teleport to="body">
<TreeContextMenu
v-if="menu"
:path="menu.path"
:name="menu.name"
:x="menu.x"
:y="menu.y"
@close="closeMenu"
/>
</Teleport>
</div>
</template>

View file

@ -0,0 +1,201 @@
<script setup lang="ts">
/**
* The project tree's context menu for a file (M4.3): Open and Show Diff
* (`vcs.showDiff {path}`, dimmed while the command is disabled).
*
* Follows the WAI-ARIA menu pattern: it takes the focus when it opens,
* Up/Down move between items (wrapping), Enter or Space runs one, Escape,
* Tab or a press outside closes it. The position is clamped into the
* window.
*/
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff";
const props = defineProps<{
/** Project-relative path of the file. */
path: string;
/** File name, for the accessible label. */
name: string;
/** Window x of the pointer (or the row) in pixels. */
x: number;
/** Window y of the pointer (or the row) in pixels. */
y: number;
}>();
const emit = defineEmits<{
/** The menu should close (an item ran or the user dismissed it). */
close: [];
}>();
const editor = useEditorStore();
const commands = useCommandsStore();
/** The menu element. */
const menuEl = ref<HTMLElement | null>(null);
/** Index of the focused item. */
const focused = ref(0);
/** One item of the menu. */
interface MenuItem {
/** Stable id, also used by tests. */
id: string;
/** Text shown. */
label: string;
/** Whether it can run now. */
enabled: boolean;
/** Runs it. */
run: () => Promise<void>;
}
/** The items, in order. */
const items = computed<MenuItem[]>(() => [
{
id: "open",
label: t("project.tree.menu.open"),
enabled: true,
run: async () => {
await editor.openFile(props.path);
},
},
{
id: "showDiff",
label: t("project.tree.menu.showDiff"),
enabled: commands.isEnabled(SHOW_DIFF_COMMAND),
run: () => commands.execute(SHOW_DIFF_COMMAND, { path: props.path }),
},
]);
/** The menu's position, kept inside the window. */
const position = computed(() => ({
left: `${String(Math.max(0, Math.min(props.x, window.innerWidth - 200)))}px`,
top: `${String(Math.max(0, Math.min(props.y, window.innerHeight - 80)))}px`,
}));
/**
* Runs an item and closes the menu.
*
* @param item - the item.
*/
async function choose(item: MenuItem): Promise<void> {
if (!item.enabled) {
return;
}
emit("close");
await item.run();
}
/**
* Keyboard handling of the menu.
*
* @param event - the key event.
*/
function onKeydown(event: KeyboardEvent): void {
const count = items.value.length;
switch (event.key) {
case "ArrowDown":
focused.value = (focused.value + 1) % count;
break;
case "ArrowUp":
focused.value = (focused.value - 1 + count) % count;
break;
case "Enter":
case " ": {
const item = items.value[focused.value];
if (item) {
void choose(item);
}
break;
}
case "Escape":
case "Tab":
emit("close");
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
}
/**
* Closes the menu on a press outside it.
*
* @param event - the pointer event on the window.
*/
function onPointerDown(event: PointerEvent): void {
if (menuEl.value && event.target instanceof Node && !menuEl.value.contains(event.target)) {
emit("close");
}
}
onMounted(() => {
window.addEventListener("pointerdown", onPointerDown, true);
void nextTick(() => menuEl.value?.focus());
});
onBeforeUnmount(() => {
window.removeEventListener("pointerdown", onPointerDown, true);
});
</script>
<template>
<div
ref="menuEl"
class="tree-menu"
role="menu"
tabindex="-1"
:aria-label="t('project.tree.menu.label', { name })"
:aria-activedescendant="`lt-tree-menu-${items[focused]?.id ?? ''}`"
:style="position"
data-test="tree-menu"
@keydown="onKeydown"
@contextmenu.prevent
>
<div
v-for="(item, index) in items"
:id="`lt-tree-menu-${item.id}`"
:key="item.id"
class="tree-menu__item"
:class="{ 'tree-menu__item--focused': index === focused, 'tree-menu__item--disabled': !item.enabled }"
role="menuitem"
:aria-disabled="!item.enabled"
:data-item="item.id"
data-test="tree-menu-item"
@mouseenter="focused = index"
@click="choose(item)"
>
{{ item.label }}
</div>
</div>
</template>
<style scoped>
.tree-menu {
position: fixed;
z-index: 50;
min-width: 160px;
padding: 4px 0;
color: var(--lt-fg);
background: var(--lt-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
outline: none;
}
.tree-menu__item {
padding: 4px 16px;
cursor: default;
white-space: nowrap;
}
.tree-menu__item--focused {
background: var(--lt-editor-selection-bg);
}
.tree-menu__item--disabled {
color: var(--lt-fg-muted);
}
</style>

View file

@ -0,0 +1,338 @@
<script setup lang="ts">
/**
* The active diff tab (M4.3): a side-by-side `@codemirror/merge` view of
* the ref (left, read-only) and the working copy (right, editable), or a
* notice for binary, too large and failed diffs.
*
* - **Right side and the buffer:** the right editor starts from the
* working copy's {@link BufferSync} state. Every local change of it is
* handed to the sync, which sends it to the engine like typing in the
* file's own tab (the file's tab is hidden while the diff shows, so the
* sync has no view of its own). Engine changes to the buffer (a reload
* from disk, an agent's edit) come back through `bufferChanged`: once the
* sync has taken them over, the difference is applied to the right
* editor outside its undo history.
* - **Left side:** replaced in place when the store re-reads it
* (`gitChanged` after staging).
* - **Colours:** only `--lt-*` tokens; changed lines are tinted with
* `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right).
* - **Navigation:** a navigator over the merge view is registered for
* `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused
* side, else the working copy, moves to the next or previous chunk.
*/
import { getChunks, goToNextChunk, goToPreviousChunk, MergeView } from "@codemirror/merge";
import { Annotation, EditorState, Transaction, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { basicSetup } from "codemirror";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { t } from "../../../i18n";
import { onEngineEvent } from "../../../ipc";
import { useEditorStore } from "../../../stores/editor";
import type { BufferSync } from "../../editor/bufferSync";
import { diffDocs } from "../../editor/engineText";
import { editorExtensions, lutraEditorTheme } from "../../editor/extensions";
import { languageExtensions } from "../../editor/language";
import { refFor, useDiffStore } from "./diff";
import { setNavigator } from "./navigation";
const diff = useDiffStore();
const editor = useEditorStore();
/** Element the merge view is mounted in. */
const host = ref<HTMLElement | null>(null);
/** The merge view, null while none is built. */
let merge: MergeView | null = null;
/** The sync of the right side, null when the working copy is missing. */
let sync: BufferSync | null = null;
/** What the current merge view was built for, to rebuild only on a change. */
let builtFor = "";
/** Ends the engine event subscription. */
let unsubscribe: (() => void) | null = null;
/** Marks right-side transactions that carry the buffer's changes, so they are not sent back. */
const fromBuffer = Annotation.define<boolean>();
/** Colours of the diff, from tokens only. */
const diffTheme: Extension = EditorView.theme({
"&.cm-merge-a .cm-changedLine, .cm-deletedChunk": {
backgroundColor: "color-mix(in srgb, var(--lt-vcs-deleted) 14%, var(--lt-editor-bg))",
},
"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine": {
backgroundColor: "color-mix(in srgb, var(--lt-vcs-added) 14%, var(--lt-editor-bg))",
},
"&.cm-merge-a .cm-changedText, .cm-deletedChunk .cm-deletedText": {
background: "color-mix(in srgb, var(--lt-vcs-deleted) 35%, transparent)",
},
"&.cm-merge-b .cm-changedText": {
background: "color-mix(in srgb, var(--lt-vcs-added) 35%, transparent)",
},
"&.cm-merge-b .cm-deletedText": {
background: "color-mix(in srgb, var(--lt-vcs-deleted) 35%, transparent)",
},
".cm-collapsedLines": {
color: "var(--lt-fg-muted)",
background: "var(--lt-bg)",
borderTop: "1px solid var(--lt-border)",
borderBottom: "1px solid var(--lt-border)",
},
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": {
background: "var(--lt-vcs-deleted)",
},
"&.cm-merge-b .cm-changedLineGutter": {
background: "var(--lt-vcs-added)",
},
});
/** The header line: what is compared with what. */
const caption = computed(() => {
const tab = diff.activeTab;
if (!tab) {
return "";
}
return refFor(tab.staged) === "HEAD"
? t("vcs.diff.captionHead", { path: tab.path })
: t("vcs.diff.captionIndex", { path: tab.path });
});
/** The notice shown instead of, or above, the diff; null if none. */
const notice = computed(() => {
const content = diff.activeContent;
switch (content?.phase) {
case "binary":
return t("vcs.diff.binary");
case "tooLarge":
return t("vcs.diff.tooLarge");
case "error":
return t("vcs.diff.failed", { reason: content.message ?? "" });
case "ready":
return content.message;
default:
return null;
}
});
/**
* Hands local changes of the right editor to the buffer's sync.
*
* @param transactions - transactions the right editor applied.
*/
function forward(transactions: readonly Transaction[]): void {
if (!sync) {
return;
}
for (const tr of transactions) {
if (!tr.docChanged || tr.annotation(fromBuffer) === true) {
continue;
}
const changes = sync.state.doc.eq(tr.startState.doc) ? tr.changes : diffDocs(sync.state.doc, tr.state.doc);
const userEvent = tr.annotation(Transaction.userEvent);
sync.dispatch(userEvent === undefined ? { changes } : { changes, userEvent });
}
}
/** Brings the right editor up to the buffer's text, outside its undo history. */
function pullFromBuffer(): void {
if (!merge || !sync) {
return;
}
const from = merge.b.state.doc;
const to = sync.state.doc;
if (from.eq(to)) {
return;
}
merge.b.dispatch({
changes: diffDocs(from, to),
annotations: [fromBuffer.of(true), Transaction.addToHistory.of(false)],
});
}
/** Destroys the merge view. */
function destroy(): void {
setNavigator(null);
merge?.destroy();
merge = null;
sync = null;
builtFor = "";
}
/** Builds the merge view for the active tab, or rebuilds it when its inputs changed. */
function build(): void {
const tab = diff.activeTab;
const content = diff.activeContent;
const key = tab && content?.phase === "ready" ? `${tab.key}#${String(content.bufferId ?? "none")}` : "";
if (key === builtFor && merge) {
return;
}
destroy();
if (!tab || !content || content.phase !== "ready" || !host.value) {
return;
}
const bufferId = content.bufferId;
sync = bufferId === null ? null : (editor.syncOf(bufferId) ?? null);
const readOnly = [EditorState.readOnly.of(true), EditorView.editable.of(false)];
const right: Extension = sync
? [
editorExtensions(tab.path, { id: sync.id, idle: () => sync?.idle() ?? Promise.resolve() }),
diffTheme,
EditorView.updateListener.of((update) => {
forward(update.transactions);
}),
]
: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly];
merge = new MergeView({
a: { doc: content.left, extensions: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly] },
b: sync ? { doc: sync.state.doc, selection: sync.state.selection, extensions: right } : { doc: "", extensions: right },
parent: host.value,
gutter: true,
highlightChanges: true,
collapseUnchanged: { margin: 3, minSize: 8 },
});
builtFor = key;
const view = merge;
const side = (): EditorView => (view.a.hasFocus ? view.a : view.b);
setNavigator({
view,
hasChanges: () => (getChunks(side().state)?.chunks.length ?? 0) > 0,
go: (direction) => {
const target = side();
const moved = (direction > 0 ? goToNextChunk : goToPreviousChunk)(target);
target.focus();
return moved;
},
});
}
/** Replaces the left document with the store's text after a re-read. */
function updateLeft(): void {
const content = diff.activeContent;
if (!merge || content?.phase !== "ready") {
return;
}
const doc = merge.a.state.doc;
if (doc.toString() !== content.left) {
merge.a.dispatch({ changes: { from: 0, to: doc.length, insert: content.left } });
}
}
watch(
() => [diff.activeKey, diff.activeContent] as const,
() => {
build();
},
);
watch(
() => diff.leftRevision,
() => {
updateLeft();
},
);
onMounted(() => {
build();
unsubscribe = onEngineEvent((event) => {
if (event.kind !== "bufferChanged" || !sync || event.id !== sync.id) {
return;
}
const target = sync;
void Promise.resolve()
.then(() => target.idle())
.then(() => {
if (sync === target) {
pullFromBuffer();
}
});
});
});
onBeforeUnmount(() => {
unsubscribe?.();
unsubscribe = null;
destroy();
});
</script>
<template>
<div
class="diff-view"
data-test="diff-view"
:data-path="diff.activeTab?.path"
>
<div
class="diff-view__caption"
data-test="diff-caption"
>
{{ caption }}
</div>
<div
v-if="notice"
class="diff-view__notice"
role="status"
data-test="diff-notice"
>
{{ notice }}
</div>
<div
v-if="diff.activeContent?.phase === 'loading'"
class="diff-view__loading"
data-test="diff-loading"
>
{{ t("vcs.diff.loading") }}
</div>
<div
v-show="diff.activeContent?.phase === 'ready'"
ref="host"
class="diff-view__merge"
data-test="diff-merge"
/>
</div>
</template>
<style scoped>
.diff-view {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
background: var(--lt-editor-bg);
}
.diff-view__caption {
flex-shrink: 0;
padding: 3px 12px;
color: var(--lt-fg-muted);
background: var(--lt-bg);
border-bottom: 1px solid var(--lt-border);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.diff-view__notice {
flex-shrink: 0;
padding: 4px 12px;
color: var(--lt-fg);
background: var(--lt-notice-bg);
border-bottom: 1px solid var(--lt-border);
}
.diff-view__loading {
padding: 12px;
color: var(--lt-fg-muted);
}
.diff-view__merge {
flex: 1;
min-height: 0;
overflow: auto;
user-select: text;
}
.diff-view__merge :deep(.cm-mergeView) {
min-height: 100%;
}
.diff-view__merge :deep(.cm-mergeViewEditor + .cm-mergeViewEditor) {
border-left: 1px solid var(--lt-border);
}
</style>

View file

@ -0,0 +1,43 @@
/**
* The diff viewer's UI commands, supplied by the editor area:
*
* - `vcs.showDiff {path?, staged?}`: opens the diff of a file; without a
* path, of the active diff or editor tab (the palette). Enabled while a
* project is open.
* - `vcs.nextChange` / `vcs.previousChange`: move to the next or previous
* change of the visible diff. Enabled while a diff with changes shows.
*/
import type { useCommandsStore } from "../../../commands/store";
import { useProjectStore } from "../../../stores/project";
import { NEXT_CHANGE_COMMAND, PREVIOUS_CHANGE_COMMAND, SHOW_DIFF_COMMAND, useDiffStore } from "./diff";
import { goToChange, hasChanges } from "./navigation";
/**
* Supplies the diff commands and starts the diff store.
*
* @param commands - the command store.
* @returns functions that withdraw the handlers and stop the store.
*/
export function provideDiffCommands(commands: ReturnType<typeof useCommandsStore>): (() => void)[] {
const diff = useDiffStore();
const project = useProjectStore();
diff.start();
return [
commands.provide(SHOW_DIFF_COMMAND, { run: (params) => diff.showDiff(params), enabled: () => project.root !== null }),
commands.provide(NEXT_CHANGE_COMMAND, {
run: () => {
goToChange(1);
},
enabled: () => diff.activeContent?.phase === "ready" && hasChanges(),
}),
commands.provide(PREVIOUS_CHANGE_COMMAND, {
run: () => {
goToChange(-1);
},
enabled: () => diff.activeContent?.phase === "ready" && hasChanges(),
}),
() => {
diff.stop();
},
];
}

View file

@ -0,0 +1,475 @@
/**
* The diff viewer's state (M4.3): the "Diff: <name>" tabs of the editor
* area and what each one compares.
*
* - **Opening:** the UI command `vcs.showDiff {path, staged?}` (Changes
* window, the project tree's context menu, the palette). One tab per path
* and side; opening it again activates and reloads it.
* - **Left side:** `git.show {path, ref}` (a pending outcome, so through
* `runWaiting`). `staged: true` compares with HEAD; otherwise with the
* index, which equals HEAD for a file without staged changes, so a
* partly staged file shows only what is not staged yet. A path missing at
* that ref (a new or untracked file) gives an empty left side. Git
* returns the blob as stored (LF when autocrlf normalised it), so line
* breaks are normalised to `\n` ({@link normaliseEol}); CodeMirror keeps
* lines, not break characters, so a CRLF working copy lines up.
* - **Right side:** the working copy as an ordinary engine buffer, opened
* through the editor store, so its edits, saves, autosave and the
* recovery journal work as in any tab (the buffer also gets its normal
* tab). A file missing from the working copy (deleted) shows an empty,
* read-only right side and a notice.
* - **Notices instead of a diff:** binary files and files over git's cap
* (`binary` / `tooLarge` of `git.show`).
* - **Active tab:** a diff tab is shown over the editor tab that was
* active when it was activated (the anchor). Any other editor tab
* becoming active hides the diff again; the editor tabs bar deactivates
* it on a click.
* - **Refresh:** `gitChanged` re-reads the left side of every text tab
* (staging changes the index). A project open or close drops every tab;
* closing the working copy's buffer closes its diff tabs.
* - **Untrusted input:** `git.show` results are checked field by field.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef, watch } from "vue";
import { t } from "../../../i18n";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { baseName, useEditorStore } from "../../../stores/editor";
/** Command id that opens a diff. */
export const SHOW_DIFF_COMMAND = "vcs.showDiff";
/** Command id that moves to the next change of the active diff. */
export const NEXT_CHANGE_COMMAND = "vcs.nextChange";
/** Command id that moves to the previous change of the active diff. */
export const PREVIOUS_CHANGE_COMMAND = "vcs.previousChange";
/** The ref a diff compares the working copy with. */
export type DiffRef = "HEAD" | "index";
/** Params of `vcs.showDiff`, checked. */
export interface ShowDiffParams {
/** Project-relative path; null for the active editor tab's file. */
path: string | null;
/** Whether to compare with HEAD (the staged view). */
staged: boolean;
}
/** One diff tab. */
export interface DiffTab {
/** Stable key: side and path. */
key: string;
/** Project-relative path with `/`. */
path: string;
/** Whether it compares with HEAD instead of the index. */
staged: boolean;
/** File name shown on the tab. */
name: string;
}
/** What a diff tab shows. */
export type DiffPhase = "loading" | "ready" | "binary" | "tooLarge" | "error";
/** The loaded contents of a diff tab. */
export interface DiffContent {
/** What the tab shows. */
phase: DiffPhase;
/** The left text with `\n` breaks; empty when missing at the ref. */
left: string;
/** Whether the path does not exist at the ref (a new file). */
leftMissing: boolean;
/** Engine buffer of the working copy, null when it could not be opened. */
bufferId: number | null;
/** Error text, or why the working copy is missing; null if none. */
message: string | null;
}
/** A `git.show` result, checked. */
export interface ShowResult {
/** The text, null when the path does not exist at the ref. */
text: string | null;
/** Whether git sees the file as binary. */
binary: boolean;
/** Whether the file is over git's size cap. */
tooLarge: boolean;
}
/**
* Turns every line break into `\n`.
*
* @param text - text with any mix of `\r\n`, `\r` and `\n`.
*/
export function normaliseEol(text: string): string {
return text.replace(/\r\n?/g, "\n");
}
/**
* The ref to compare with.
*
* @param staged - whether the staged view (HEAD) is asked for.
*/
export function refFor(staged: boolean): DiffRef {
return staged ? "HEAD" : "index";
}
/**
* The key of a diff tab.
*
* @param path - project-relative path.
* @param staged - the side.
*/
export function diffKey(path: string, staged: boolean): string {
return `${staged ? "staged" : "work"}:${path}`;
}
/**
* Reads the params of `vcs.showDiff`; null when malformed.
*
* @param params - untrusted (`{}` from the palette and the keyboard).
*/
export function parseShowDiff(params: unknown): ShowDiffParams | null {
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined;
const staged = p.staged === undefined || p.staged === null ? false : typeof p.staged === "boolean" ? p.staged : undefined;
if (path === undefined || staged === undefined) {
return null;
}
return { path, staged };
}
/**
* Reads a `git.show` result; null when malformed.
*
* @param raw - untrusted.
*/
export function toShowResult(raw: unknown): ShowResult | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const r = raw as Record<string, unknown>;
if (r.text !== null && typeof r.text !== "string") {
return null;
}
return { text: r.text, binary: r.binary === true, tooLarge: r.tooLarge === true };
}
/** A tab's content while it loads. */
const LOADING: DiffContent = { phase: "loading", left: "", leftMissing: false, bufferId: null, message: null };
/** The diff store. */
export const useDiffStore = defineStore("diff", () => {
const editor = useEditorStore();
/** Open diff tabs in display order. */
const tabs = ref<DiffTab[]>([]);
/** Key of the active diff tab, null when an editor tab is shown. */
const activeKey = ref<string | null>(null);
/** Contents by tab key; replaced as a whole on every change. */
const contents = shallowRef<Record<string, DiffContent>>({});
/** Bumped whenever a tab's left text is re-read with a different result. */
const leftRevision = ref(0);
/** The editor tab shown under the active diff (see the module docs). */
let anchor: number | null = null;
/** Loads opening the working copy now; the editor tab they activate becomes the anchor. */
let anchoring = 0;
/** Load generation by tab key, so only the newest load of a tab lands. */
const generations = new Map<string, number>();
/** The active diff tab, null when none is shown. */
const activeTab = computed(() => tabs.value.find((tab) => tab.key === activeKey.value) ?? null);
/** Whether a diff tab covers the editor now. */
const visible = computed(() => activeTab.value !== null);
/** The content of the active tab, null when none is shown. */
const activeContent = computed(() => (activeTab.value ? (contents.value[activeTab.value.key] ?? LOADING) : null));
watch(
() => editor.activeId,
(id) => {
if (anchoring > 0) {
anchor = id;
} else if (id !== anchor) {
activeKey.value = null;
}
},
{ flush: "sync" },
);
watch(
() => editor.tabs.map((tab) => tab.id),
(ids) => {
for (const tab of [...tabs.value]) {
const bufferId = contents.value[tab.key]?.bufferId;
if (bufferId !== undefined && bufferId !== null && !ids.includes(bufferId)) {
close(tab.key);
}
}
},
);
/**
* Stores the content of a tab.
*
* @param key - the tab key.
* @param content - its content.
*/
function setContent(key: string, content: DiffContent): void {
contents.value = { ...contents.value, [key]: content };
}
/**
* The content of a tab.
*
* @param key - the tab key.
*/
function contentOf(key: string): DiffContent | null {
return contents.value[key] ?? null;
}
/**
* Shows a diff tab over the active editor tab.
*
* @param key - the tab key.
*/
function activate(key: string): void {
if (tabs.value.some((tab) => tab.key === key)) {
anchor = editor.activeId;
activeKey.value = key;
}
}
/** Shows the editor tab again. */
function deactivate(): void {
activeKey.value = null;
}
/**
* Reads the left side of a diff.
*
* @param tab - the tab.
* @returns the checked result, or the error text.
*/
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
const result = await runWaiting("git.show", { path: tab.path, ref: refFor(tab.staged) });
if (!result.ok) {
return result.error.message;
}
return toShowResult(result.value) ?? t("common.error.unexpectedResult", { command: "git.show" });
}
/**
* Opens the working copy of a tab as an engine buffer.
*
* @param tab - the tab.
* @returns the buffer id, or the reason it could not be opened.
*/
async function openRight(tab: DiffTab): Promise<number | string> {
const existing = editor.tabs.find((editorTab) => editorTab.path === tab.path);
if (existing && editor.syncOf(existing.id)) {
return existing.id;
}
const before = editor.lastError;
const wasActive = activeKey.value === tab.key;
if (wasActive) {
anchoring += 1;
}
try {
const id = await editor.openFile(tab.path);
if (id !== null) {
return id;
}
const reason = editor.lastError?.message ?? "";
editor.lastError = before;
return reason;
} finally {
if (wasActive) {
anchoring -= 1;
if (activeKey.value === tab.key) {
anchor = editor.activeId;
}
}
}
}
/**
* Loads both sides of a tab.
*
* @param tab - the tab.
*/
async function load(tab: DiffTab): Promise<void> {
const generation = (generations.get(tab.key) ?? 0) + 1;
generations.set(tab.key, generation);
const current = (): boolean => generations.get(tab.key) === generation && tabs.value.some((t) => t.key === tab.key);
setContent(tab.key, LOADING);
const left = await readLeft(tab);
if (!current()) {
return;
}
if (typeof left === "string") {
setContent(tab.key, { ...LOADING, phase: "error", message: left });
return;
}
if (left.binary || left.tooLarge) {
setContent(tab.key, { ...LOADING, phase: left.binary ? "binary" : "tooLarge" });
return;
}
const right = await openRight(tab);
if (!current()) {
return;
}
setContent(tab.key, {
phase: "ready",
left: normaliseEol(left.text ?? ""),
leftMissing: left.text === null,
bufferId: typeof right === "number" ? right : null,
message: typeof right === "number" ? null : t("vcs.diff.workingCopyMissing", { reason: right }),
});
}
/**
* Opens (or activates and reloads) the diff of a file.
*
* @param path - project-relative path.
* @param staged - compare with HEAD instead of the index.
*/
async function open(path: string, staged: boolean): Promise<void> {
const key = diffKey(path, staged);
let tab = tabs.value.find((t) => t.key === key);
if (!tab) {
tab = { key, path, staged, name: baseName(path) };
tabs.value.push(tab);
}
activate(key);
await load(tab);
}
/**
* Re-reads the left side of every loaded text tab; a changed text
* replaces the left document (`gitChanged`).
*/
async function refreshLeft(): Promise<void> {
await Promise.all(
tabs.value.map(async (tab) => {
const before = contents.value[tab.key];
if (before?.phase !== "ready") {
return;
}
const generation = generations.get(tab.key);
const left = await readLeft(tab);
const now = contents.value[tab.key];
if (generations.get(tab.key) !== generation || now?.phase !== "ready" || typeof left === "string") {
return;
}
if (left.binary || left.tooLarge) {
setContent(tab.key, { ...LOADING, phase: left.binary ? "binary" : "tooLarge" });
return;
}
const text = normaliseEol(left.text ?? "");
if (text !== now.left || (left.text === null) !== now.leftMissing) {
setContent(tab.key, { ...now, left: text, leftMissing: left.text === null });
leftRevision.value += 1;
}
}),
);
}
/**
* Closes a diff tab; the working copy's buffer stays open.
*
* @param key - the tab key.
*/
function close(key: string): void {
const index = tabs.value.findIndex((tab) => tab.key === key);
if (index < 0) {
return;
}
tabs.value.splice(index, 1);
generations.delete(key);
contents.value = Object.fromEntries(Object.entries(contents.value).filter(([k]) => k !== key));
if (activeKey.value === key) {
activeKey.value = null;
const next = tabs.value[Math.min(index, tabs.value.length - 1)];
if (next && editor.tabs.length === 0) {
activate(next.key);
}
}
}
/** Drops every tab (project opened or closed). */
function clear(): void {
tabs.value = [];
activeKey.value = null;
contents.value = {};
generations.clear();
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "projectOpened" || event.kind === "projectClosed") {
clear();
} else if (event.kind === "gitChanged") {
void refreshLeft();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events; calling it again has no effect. */
function start(): void {
unsubscribe ??= onEngineEvent(onEvent);
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/**
* Runs `vcs.showDiff`: the given file, else the active diff's or editor
* tab's file.
*
* @param params - untrusted params.
* @throws Error with a catalog message when the params are malformed or
* there is no file to compare.
*/
async function showDiff(params: JsonValue): Promise<void> {
const parsed = parseShowDiff(params);
if (!parsed) {
throw new Error(t("vcs.diff.invalidParams"));
}
const path = parsed.path ?? activeTab.value?.path ?? editor.activeTab?.path ?? null;
if (path === null) {
throw new Error(t("vcs.diff.noFile"));
}
const staged = parsed.path === null && activeTab.value ? activeTab.value.staged : parsed.staged;
await open(path, staged);
}
return {
tabs,
activeKey,
activeTab,
activeContent,
visible,
contents,
leftRevision,
contentOf,
activate,
deactivate,
open,
showDiff,
refreshLeft,
close,
clear,
onEvent,
start,
stop,
};
});

View file

@ -0,0 +1,58 @@
/**
* Next/previous change in the diff shown now (`vcs.nextChange`,
* `vcs.previousChange`). The diff view registers a navigator here while it
* shows a merge view; the commands move the cursor of the side that has
* the focus (the working copy otherwise) to the next or previous changed
* chunk, wrapping around, and scroll it into view.
*
* This module does not import `@codemirror/merge`, so the package stays in
* the lazily loaded diff view's chunk.
*/
import type { MergeView } from "@codemirror/merge";
/** What the diff view offers the commands. */
export interface DiffNavigator {
/** The merge view (tests read it). */
view: MergeView;
/** Whether the diff has at least one change. */
hasChanges(): boolean;
/**
* Moves to the next or previous change.
*
* @param direction - 1 for the next change, -1 for the previous one.
* @returns whether the cursor moved.
*/
go(direction: 1 | -1): boolean;
}
/** The navigator of the diff shown now, null when none is visible. */
let current: DiffNavigator | null = null;
/**
* Registers the navigator of the diff shown now.
*
* @param navigator - the navigator, or null when the merge view goes away.
*/
export function setNavigator(navigator: DiffNavigator | null): void {
current = navigator;
}
/** The merge view shown now, null when none. */
export function currentMerge(): MergeView | null {
return current?.view ?? null;
}
/** Whether the visible diff has at least one change. */
export function hasChanges(): boolean {
return current?.hasChanges() ?? false;
}
/**
* Moves to the next or previous change of the visible diff.
*
* @param direction - 1 for the next change, -1 for the previous one.
* @returns whether the cursor moved.
*/
export function goToChange(direction: 1 | -1): boolean {
return current?.go(direction) ?? false;
}

View file

@ -20,8 +20,11 @@
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
"command.vcs.commit": "Commit…",
"command.vcs.nextChange": "Next Change",
"command.vcs.openChanges": "Changes",
"command.vcs.previousChange": "Previous Change",
"command.vcs.refresh": "Refresh Changes",
"command.vcs.showDiff": "Show Diff",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
@ -177,6 +180,9 @@
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",
"project.tree.loading": "Loading…",
"project.tree.menu.label": "Actions for {name}",
"project.tree.menu.open": "Open",
"project.tree.menu.showDiff": "Show Diff",
"project.tree.truncated": "Listing truncated: more entries than can be shown",
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
"recovery.dialog.discard": "Discard",
@ -292,6 +298,18 @@
"vcs.commit.hint": "Commit the staged changes ({keys})",
"vcs.commit.messageLabel": "Commit message",
"vcs.commit.placeholder": "Commit message",
"vcs.diff.binary": "Binary file: no text diff to show.",
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
"vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)",
"vcs.diff.closeTab": "Close the diff of {name}",
"vcs.diff.failed": "The diff cannot be shown: {reason}",
"vcs.diff.invalidParams": "vcs.showDiff takes {path?: string, staged?: boolean}",
"vcs.diff.loading": "Reading the file from Git…",
"vcs.diff.noFile": "Open a file or pass a path to show its diff",
"vcs.diff.tabTitle": "Diff: {name}",
"vcs.diff.tabTitleStaged": "Diff: {name} (staged)",
"vcs.diff.tooLarge": "The file is too large to compare.",
"vcs.diff.workingCopyMissing": "The working copy cannot be opened ({reason}); it may have been deleted.",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",

View file

@ -277,7 +277,10 @@ describe("AppMenu", () => {
"goto.symbolOpen",
"vcs.openChanges",
"vcs.commit",
"vcs.nextChange",
"vcs.previousChange",
"vcs.refresh",
"vcs.showDiff",
"app.about",
]);
const close = document.querySelector("[data-command='buffer.close']");

View file

@ -267,15 +267,18 @@ describe("CommandPalette", () => {
"goto.classOpen",
"goto.fileOpen",
"goto.symbolOpen",
"vcs.nextChange",
"project.openDialog",
"menu.open",
"editor.parameterInfo",
"vcs.previousChange",
"problems.open",
"editor.quickDocumentation",
"app.quit",
"vcs.refresh",
"editor.reveal",
"settings.open",
"vcs.showDiff",
"view.toggleProjectTree",
"view.toggleStructure",
"terminal.open",

View file

@ -0,0 +1,504 @@
/**
* Tests of the diff viewer (M4.3): reading the untrusted params and
* `git.show` results, line-break normalisation, `vcs.showDiff` opening a
* "Diff: <name>" tab with the index (or HEAD for the staged view) on the
* left and the working copy's buffer on the right, edits on the right
* reaching the engine through the buffer, engine changes reaching the right
* side, left side refresh on `gitChanged`, notices for binary, too large,
* failed and deleted files, switching between diff and editor tabs, the
* next/previous change commands and the project tree's context menu. The
* engine is a fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { EditorView } from "@codemirror/view";
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 EditorArea from "../../src/components/editor/EditorArea.vue";
import { emitEngineEvent } from "../../src/components/project/engineEvents";
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
import {
diffKey,
normaliseEol,
parseShowDiff,
refFor,
toShowResult,
useDiffStore,
} from "../../src/components/vcs/diff/diff";
import { currentMerge } from "../../src/components/vcs/diff/navigation";
import { useEditorStore } from "../../src/stores/editor";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useProjectStore } from "../../src/stores/project";
/** A buffer of the fake engine. */
interface FakeBuffer {
path: string;
text: string;
version: number;
saved: number;
}
/** Fake engine buffers by id. */
let buffers: Map<number, FakeBuffer>;
/** Files in the working copy. */
let disk: Record<string, string>;
/** What `git.show` answers, by `ref:path`; missing entries mean "not at that ref". */
let blobs: Record<string, unknown>;
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** Next buffer id. */
let nextId: number;
/** Every engine call, in order. */
let calls: { via: string; command: string; params: Record<string, unknown> }[];
/** Engine event callbacks of every subscription. */
let listeners: ((event: { payload: unknown }) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
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();
}
/**
* Describes a buffer as `file.open` and `buffer.get` do.
*
* @param id - buffer id.
*/
function describeBuffer(id: number): unknown {
const b = buffers.get(id);
return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.version !== b.saved, lineEnding: b.text.includes("\r\n") ? "crlf" : "lf" } : null;
}
/**
* Rejects like the shell does with an engine error.
*
* @param code - error code.
* @param message - error text.
*/
function fail(code: string, message = code): Promise<never> {
return Promise.reject(Object.assign(new Error(message), { code, message }));
}
/**
* The fake engine.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const failure = failures[command];
if (failure) {
return fail(failure.code, failure.message);
}
const id = typeof p.id === "number" ? p.id : -1;
const b = buffers.get(id);
switch (command) {
case "git.show": {
const blob = blobs[`${String(p.ref)}:${String(p.path)}`];
return Promise.resolve(blob === undefined ? { text: null, binary: false, tooLarge: false } : blob);
}
case "file.open": {
const path = String(p.path);
for (const [existing, buffer] of buffers) {
if (buffer.path === path) {
return Promise.resolve(describeBuffer(existing));
}
}
const text = disk[path];
if (text === undefined) {
return fail("failed", `${path}: file not found`);
}
const newId = nextId++;
buffers.set(newId, { path, text, version: 1, saved: 1 });
return Promise.resolve(describeBuffer(newId));
}
case "buffer.get":
return b ? Promise.resolve(describeBuffer(id)) : fail("failed");
case "buffer.edit": {
if (!b) {
return fail("failed");
}
if (p.baseVersion !== b.version) {
return fail("stale_version");
}
let out = "";
let pos = 0;
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
out += b.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
b.text = out + b.text.slice(pos);
b.version += 1;
return Promise.resolve({ id, version: b.version, dirty: true });
}
case "project.children":
return Promise.resolve({
dir: "",
entries: Object.keys(disk).map((path) => ({ name: path, path, kind: "file", ignored: false, role: null })),
truncated: false,
});
default:
return Promise.resolve({});
}
}
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): { via: string; command: string; params: Record<string, unknown> }[] {
return calls.filter((c) => c.command === command);
}
/** jsdom has no layout; CodeMirror measures text ranges, so give ranges empty rectangles. */
function stubRangeGeometry(): void {
const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getClientRects = empty;
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
}
/** Mounts the editor area with the keymap and an open project. */
async function mountArea(): Promise<VueWrapper> {
await useCommandsStore(pinia).start();
useProjectStore(pinia).root = { path: "/p", name: "p" };
const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
/**
* Runs a command through the command store and waits for it.
*
* @param id - command id.
* @param params - its params.
*/
async function runCommand(id: string, params: Record<string, unknown> = {}): Promise<void> {
await useCommandsStore(pinia).execute(id, params as never);
await vi.dynamicImportSettled();
await flushPromises();
}
/** Both sides of the merge view. */
function sides(): { a: EditorView; b: EditorView } {
const merge = currentMerge();
if (!merge) {
throw new Error("no merge view");
}
return { a: merge.a, b: merge.b };
}
beforeEach(() => {
stubRangeGeometry();
Element.prototype.scrollIntoView = () => undefined;
pinia = createPinia();
setActivePinia(pinia);
buffers = new Map();
disk = { "a.php": "<?php\necho 2;\nnew();\n", "b.txt": "bee\n" };
blobs = {
"index:a.php": { text: "<?php\r\necho 1;\r\n", binary: false, tooLarge: false },
"HEAD:a.php": { text: "<?php\necho 0;\n", binary: false, tooLarge: false },
};
failures = {};
nextId = 1;
calls = [];
listeners = [];
mounted = [];
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" || cmd === "engine_execute_waiting") && args) {
calls.push({ via: cmd, command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.resolve(null);
});
});
afterEach(async () => {
await flushPromises();
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
document.body.innerHTML = "";
});
describe("helpers", () => {
it("normalises every line break to LF", () => {
expect(normaliseEol("a\r\nb\rc\nd")).toBe("a\nb\nc\nd");
expect(normaliseEol("")).toBe("");
});
it("reads the params of vcs.showDiff", () => {
expect(parseShowDiff({})).toEqual({ path: null, staged: false });
expect(parseShowDiff({ path: "a.php", staged: true })).toEqual({ path: "a.php", staged: true });
expect(parseShowDiff(null)).toEqual({ path: null, staged: false });
expect(parseShowDiff({ path: 3 })).toBeNull();
expect(parseShowDiff({ path: "" })).toBeNull();
expect(parseShowDiff({ path: "a", staged: "yes" })).toBeNull();
});
it("reads git.show results and picks the ref", () => {
expect(toShowResult({ text: "x", binary: false, tooLarge: false })).toEqual({ text: "x", binary: false, tooLarge: false });
expect(toShowResult({ text: null, binary: true })).toEqual({ text: null, binary: true, tooLarge: false });
expect(toShowResult({ text: 5 })).toBeNull();
expect(toShowResult([])).toBeNull();
expect(toShowResult("x")).toBeNull();
expect(refFor(true)).toBe("HEAD");
expect(refFor(false)).toBe("index");
expect(diffKey("a", true)).not.toBe(diffKey("a", false));
});
});
describe("vcs.showDiff", () => {
it("opens a diff tab: index on the left (CRLF normalised), the working copy's buffer on the right", async () => {
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "a.php", staged: false });
expect(callsOf("git.show")).toEqual([{ via: "engine_execute_waiting", command: "git.show", params: { path: "a.php", ref: "index" } }]);
expect(area.findAll("[data-test=diff-tab]").map((t) => t.text())).toEqual(["Diff: a.php"]);
expect(area.find("[data-test=diff-tab]").attributes("aria-selected")).toBe("true");
expect(area.find("[data-test=editor-tab]").attributes("aria-selected")).toBe("false");
expect(area.find("[data-test=code-editor]").exists()).toBe(false);
expect(area.find("[data-test=diff-caption]").text()).toContain("staged version");
const { a, b } = sides();
expect(a.state.doc.toString()).toBe("<?php\necho 1;\n");
expect(a.state.readOnly).toBe(true);
expect(b.state.doc.toString()).toBe("<?php\necho 2;\nnew();\n");
expect(b.state.readOnly).toBe(false);
expect(currentMerge()?.chunks.length).toBeGreaterThan(0);
});
it("compares with HEAD for the staged view and reuses one tab per path and side", async () => {
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "a.php", staged: true });
expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "HEAD" });
expect(sides().a.state.doc.toString()).toBe("<?php\necho 0;\n");
expect(area.find("[data-test=diff-caption]").text()).toContain("last commit");
expect(area.find("[data-test=diff-tab]").text()).toBe("Diff: a.php (staged)");
await runCommand("vcs.showDiff", { path: "a.php", staged: true });
expect(area.findAll("[data-test=diff-tab]")).toHaveLength(1);
expect(callsOf("file.open")).toHaveLength(1);
});
it("without a path, diffs the active editor tab's file", async () => {
await mountArea();
await useEditorStore(pinia).openFile("a.php");
await runCommand("vcs.showDiff");
expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "index" });
expect(useDiffStore(pinia).activeTab?.path).toBe("a.php");
});
it("refuses bad params and a missing file with an error toast", async () => {
await mountArea();
await runCommand("vcs.showDiff", { path: 7 });
await runCommand("vcs.showDiff");
const texts = useNotificationsStore(pinia).toasts.map((toast) => toast.text);
expect(texts.some((text) => text.includes("{path?: string"))).toBe(true);
expect(texts.some((text) => text.includes("Open a file"))).toBe(true);
expect(callsOf("git.show")).toHaveLength(0);
});
it("is disabled without a project", async () => {
await mountArea();
useProjectStore(pinia).root = null;
expect(useCommandsStore(pinia).isEnabled("vcs.showDiff")).toBe(false);
});
});
describe("editing and refreshing", () => {
it("sends edits on the right through the buffer", async () => {
await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
const { b } = sides();
b.dispatch({ changes: { from: 0, insert: "// x\n" }, userEvent: "input.type" });
await flushPromises();
const edits = callsOf("buffer.edit");
expect(edits).toHaveLength(1);
expect(edits[0]?.params.edits).toEqual([{ from: 0, to: 0, insert: "// x\n" }]);
expect(buffers.get(1)?.text).toBe("// x\n<?php\necho 2;\nnew();\n");
expect(useEditorStore(pinia).syncOf(1)?.state.doc.toString()).toBe("// x\n<?php\necho 2;\nnew();\n");
});
it("shows engine changes of the buffer on the right", async () => {
await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
const buffer = buffers.get(1);
if (!buffer) {
throw new Error("no buffer");
}
buffer.text = "<?php\necho 3;\n";
buffer.version = 5;
await emit({ kind: "bufferChanged", id: 1, version: 5 });
await flushPromises();
expect(sides().b.state.doc.toString()).toBe("<?php\necho 3;\n");
expect(callsOf("buffer.edit")).toHaveLength(0);
});
it("re-reads the left side on gitChanged", async () => {
await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
blobs["index:a.php"] = { text: "<?php\necho 2;\nnew();\n", binary: false, tooLarge: false };
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
await flushPromises();
expect(sides().a.state.doc.toString()).toBe("<?php\necho 2;\nnew();\n");
expect(currentMerge()?.chunks).toHaveLength(0);
});
it("closes the diff when the working copy's buffer closes", async () => {
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
await emit({ kind: "bufferClosed", id: 1 });
await flushPromises();
expect(area.findAll("[data-test=diff-tab]")).toHaveLength(0);
});
});
describe("notices", () => {
it("shows a notice for binary and too large files without opening the file", async () => {
blobs["index:img.png"] = { text: null, binary: true, tooLarge: false };
blobs["index:big.sql"] = { text: null, binary: false, tooLarge: true };
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "img.png" });
expect(area.find("[data-test=diff-notice]").text()).toContain("Binary file");
await runCommand("vcs.showDiff", { path: "big.sql" });
expect(area.find("[data-test=diff-notice]").text()).toContain("too large");
expect(callsOf("file.open")).toHaveLength(0);
expect(currentMerge()).toBeNull();
});
it("shows git's error", async () => {
failures["git.show"] = { code: "failed", message: "fatal: bad object" };
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
expect(area.find("[data-test=diff-notice]").text()).toContain("fatal: bad object");
});
it("shows a deleted working copy as an empty read-only side with a notice", async () => {
blobs["index:gone.php"] = { text: "<?php\n", binary: false, tooLarge: false };
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "gone.php" });
expect(area.find("[data-test=diff-notice]").text()).toContain("may have been deleted");
expect(area.find("[data-test=editor-error]").exists()).toBe(false);
const { a, b } = sides();
expect(a.state.doc.toString()).toBe("<?php\n");
expect(b.state.doc.toString()).toBe("");
expect(b.state.readOnly).toBe(true);
});
it("shows a new file against an empty left side", async () => {
await mountArea();
await runCommand("vcs.showDiff", { path: "b.txt" });
const { a, b } = sides();
expect(a.state.doc.toString()).toBe("");
expect(b.state.doc.toString()).toBe("bee\n");
});
});
describe("tabs and navigation", () => {
it("switches between the diff and the editor tab, and closes the diff tab", async () => {
const area = await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
await area.find("[data-test=editor-tab]").trigger("click");
expect(area.find("[data-test=diff-view]").exists()).toBe(false);
expect(area.find("[data-test=code-editor]").exists()).toBe(true);
await area.find("[data-test=diff-tab]").trigger("click");
await flushPromises();
expect(area.find("[data-test=diff-view]").exists()).toBe(true);
await area.find("[data-test=diff-tab-close]").trigger("click");
await flushPromises();
expect(area.findAll("[data-test=diff-tab]")).toHaveLength(0);
expect(area.find("[data-test=code-editor]").exists()).toBe(true);
expect(area.findAll("[data-test=editor-tab]")).toHaveLength(1);
});
it("moves to the next and previous change, wrapping around", async () => {
blobs["index:a.php"] = { text: "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n", binary: false, tooLarge: false };
disk["a.php"] = "1\nX\n3\n4\n5\n6\n7\n8\n9\n10\nY\n12\n";
await mountArea();
await runCommand("vcs.showDiff", { path: "a.php" });
const { b } = sides();
expect(currentMerge()?.chunks).toHaveLength(2);
const lineOfCursor = (): number => b.state.doc.lineAt(b.state.selection.main.head).number;
expect(useCommandsStore(pinia).isEnabled("vcs.nextChange")).toBe(true);
await runCommand("vcs.nextChange");
expect(lineOfCursor()).toBe(2);
await runCommand("vcs.nextChange");
expect(lineOfCursor()).toBe(11);
await runCommand("vcs.nextChange");
expect(lineOfCursor()).toBe(2);
await runCommand("vcs.previousChange");
expect(lineOfCursor()).toBe(11);
});
it("disables next/previous change without a visible diff", async () => {
await mountArea();
expect(useCommandsStore(pinia).isEnabled("vcs.nextChange")).toBe(false);
expect(useCommandsStore(pinia).isEnabled("vcs.previousChange")).toBe(false);
});
});
describe("project tree context menu", () => {
it("opens on a right click and runs Show Diff for the file", async () => {
const area = await mountArea();
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(tree);
emitEngineEvent({ kind: "projectOpened", root: "/p", name: "p" });
await flushPromises();
useProjectStore(pinia).root = { path: "/p", name: "p" };
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
const menu = document.querySelector("[data-test=tree-menu]");
expect(menu).not.toBeNull();
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff"]);
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
await flushPromises();
await flushPromises();
expect(document.querySelector("[data-test=tree-menu]")).toBeNull();
expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "index" });
expect(area.findAll("[data-test=diff-tab]").map((t) => t.text())).toEqual(["Diff: a.php"]);
});
it("opens from the keyboard with Shift+F10 and closes with Escape", async () => {
await mountArea();
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(tree);
emitEngineEvent({ kind: "projectOpened", root: "/p", name: "p" });
await flushPromises();
useProjectStore(pinia).select("a.php");
await tree.find("[data-test=project-tree]").trigger("keydown", { key: "F10", shiftKey: true });
await flushPromises();
const menu = document.querySelector<HTMLElement>("[data-test=tree-menu]");
expect(menu).not.toBeNull();
expect(document.activeElement).toBe(menu);
menu?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
await flushPromises();
expect(document.querySelector("[data-test=tree-menu]")).toBeNull();
expect(callsOf("git.show")).toHaveLength(0);
});
});