From 0fb7e33fc7884757438c82cad3119ceab19fde0e Mon Sep 17 00:00:00 2001 From: danny Date: Thu, 15 Oct 2026 18:26:32 +0200 Subject: [PATCH 1/2] M1.6: buffer.close default shortcut Mod+W Spec field only, so the editor's close-tab shortcut comes from the engine like Mod+S and Mod+Alt+S. Registry test checks the three. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/buffer.rs | 2 +- crates/engine/src/engine.rs | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/buffer.rs b/crates/engine/src/cmd/buffer.rs index 79a5804..1fbe799 100644 --- a/crates/engine/src/cmd/buffer.rs +++ b/crates/engine/src/cmd/buffer.rs @@ -193,7 +193,7 @@ impl Command for Close { id: "buffer.close", label: "Close Buffer", menu_path: None, - default_shortcut: None, + default_shortcut: Some("Mod+W"), params: "{ id: number, force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if the buffer is dirty and force is not set", } } diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index 3dcbf17..44fd043 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -249,6 +249,13 @@ mod tests { let quit = by_id("app.quit"); assert_eq!(quit.default_shortcut.as_deref(), Some("Mod+Q")); assert!(quit.enabled); + for (id, shortcut) in [ + ("file.save", "Mod+S"), + ("file.saveAll", "Mod+Alt+S"), + ("buffer.close", "Mod+W"), + ] { + assert_eq!(by_id(id).default_shortcut.as_deref(), Some(shortcut)); + } assert!(!by_id("test.disabled").enabled); assert!(by_id("project.open").enabled); assert!(!by_id("file.open").enabled, "needs a project"); From 9fa6028335bbe5ad07140eb3af70c903afb392ec Mon Sep 17 00:00:00 2001 From: danny Date: Thu, 15 Oct 2026 18:26:32 +0200 Subject: [PATCH 2/2] M1.6: tabs and CodeMirror editor - Editor area with tab bar, CodeMirror 6 view, close question and notices (ui/src/components/editor/, ui/src/stores/editor.ts), mounted in App.vue; the project tree opens files through the editor store. - BufferSync: local edits to buffer.edit against the confirmed version, one call in flight, resync on stale_version or newer bufferChanged with rebase of unsent changes; EngineText maps CodeMirror positions to engine UTF-16 offsets for CRLF text. - Save, save all and close from engine default shortcuts via listCommands. - Dirty marker, Save / Don't Save / Cancel, non-blocking notice when a dirty file changes or disappears on disk. - Vitest: keystroke bursts with stale versions and remote edits (LF and CRLF), mapping, store and component tests against a fake engine. - Progress docs: Editor core 8% (est.), depth ~1.4%, G2, ui-parity tabs, M1 row, architecture, README status. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- ROADMAP.md | 10 +- docs/architecture.md | 12 +- docs/gaps.md | 9 +- docs/roadmap.md | 3 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- ui/package.json | 3 + ui/pnpm-lock.yaml | 134 ++++++ ui/src/App.vue | 14 +- ui/src/components/editor/ClosePrompt.vue | 135 ++++++ ui/src/components/editor/CodeEditor.vue | 96 ++++ ui/src/components/editor/EditorArea.vue | 158 +++++++ ui/src/components/editor/EditorTabs.vue | 154 +++++++ ui/src/components/editor/bufferSync.ts | 386 ++++++++++++++++ ui/src/components/editor/engineEvents.ts | 100 +++++ ui/src/components/editor/engineText.ts | 214 +++++++++ ui/src/components/editor/extensions.ts | 97 +++++ ui/src/components/editor/shortcuts.ts | 155 +++++++ ui/src/components/project/ProjectTree.vue | 4 +- ui/src/stores/editor.ts | 507 ++++++++++++++++++++++ ui/tests/App.test.ts | 8 +- ui/tests/editor/EditorArea.test.ts | 430 ++++++++++++++++++ ui/tests/editor/bufferSync.test.ts | 280 ++++++++++++ ui/tests/editor/engineText.test.ts | 58 +++ 25 files changed, 2958 insertions(+), 22 deletions(-) create mode 100644 ui/src/components/editor/ClosePrompt.vue create mode 100644 ui/src/components/editor/CodeEditor.vue create mode 100644 ui/src/components/editor/EditorArea.vue create mode 100644 ui/src/components/editor/EditorTabs.vue create mode 100644 ui/src/components/editor/bufferSync.ts create mode 100644 ui/src/components/editor/engineEvents.ts create mode 100644 ui/src/components/editor/engineText.ts create mode 100644 ui/src/components/editor/extensions.ts create mode 100644 ui/src/components/editor/shortcuts.ts create mode 100644 ui/src/stores/editor.ts create mode 100644 ui/tests/editor/EditorArea.test.ts create mode 100644 ui/tests/editor/bufferSync.test.ts create mode 100644 ui/tests/editor/engineText.test.ts diff --git a/README.md b/README.md index eb3e68e..3d55274 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ claude mcp add lutra -- lutra mcp ## Status -**Pre-alpha (2026-10-15): M1 in progress.** You can open a folder and browse it in the project tree, with live updates from disk; editing in the UI and PHP features come next. The MVP (M1–M3) is estimated at about 190 agent hours. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, +**Pre-alpha (2026-10-15): M1 in progress.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now); syntax highlighting and PHP features come next. The MVP (M1–M3) is estimated at about 190 agent hours. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, [`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list. **First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files, diff --git a/ROADMAP.md b/ROADMAP.md index 7f9e832..77b5f57 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha (foundation done)** · next: M1 editor and project; 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-14 · **Last updated:** 2026-10-15 · **Change:** minor (project tree works against the engine) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-15 · **Change:** minor (tabs and editor in the app) · **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) | **0%** | measured | -| **Feature depth** (weighted by use, scored by behaviour) | **~0.5%** (Project view 8% × weight 6) | estimated | +| **Feature depth** (weighted by use, scored by behaviour) | **~1.4%** (Editor core 8% × weight 12, Project view 8% × weight 6, of 101) | estimated | | **To MVP (M3)** | **~190 h** (M1 ~60 h, M2 ~50 h, M3 ~80 h) | estimated | | **To full parity** | **~3,300 h** (range 2,000–5,000 h) | estimated | @@ -25,7 +25,7 @@ Dimension hours overlap: language, framework and tooling hours are part of the f | Dimension | % | One agent (h) | Doc | |---|---:|---:|---| -| Features (depth) | ~0.5% | ~2,930 | [target-app-parity.md](docs/target-app-parity.md) | +| Features (depth) | ~1.4% | ~2,920 | [target-app-parity.md](docs/target-app-parity.md) | | UI/UX fidelity | 0% | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) | | PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) | | Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) | @@ -41,7 +41,7 @@ Stability 5%: no-panic lints, the engine guard and a fuzzed control protocol exi | Area | % | One agent (h) | |---|---:|---:| -| Editor core (buffers, undo, multi-caret, folding, soft wrap) | 0% | ~120 | +| Editor core (buffers, undo, multi-caret, folding, soft wrap) | 8% (est.) | ~110 | | Project view, VFS, file watching | 8% (est.) | ~40 | | Navigation (go to class/file/symbol, recent files, structure) | 0% | ~120 | | Search and replace (in file, in project, structural) | 0% | ~80 | @@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | What landed | |---|---| +| 2026-10-15 | M1.6: files open in tabs with a CodeMirror editor synced to the engine; save, save all, close with a Save / Don't Save / Cancel question, a notice when a file with unsaved changes changes on disk; a 1 MB file opens in about 90 ms. | | 2026-10-15 | M1 so far: text buffer, VFS with native watching, engine workspace (files, buffers, edit protocol, events), desktop bridge: open a folder by picker or command line, browse it in the project tree with live updates from disk. | | 2026-10-14 | M0 foundation: Cargo workspace with layered crates, no-panic lints with a self-test, `cargo xtask ci` (fmt, clippy, tests, layers, assets, clean-room, licences, frontend lint/typecheck/tests), Vue frontend, command registry with panic guard (`app.about`, `app.quit`), JSON control channel, Tauri window themed from Rust tokens, CI workflow. First estimates. | | 2026-10-13 | Project started: name, conventions, agent rules and progress docs. | @@ -85,6 +86,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Feature depth ~1.4%: tabs and editor (M1.6) | | 2026-10-15 | minor | Feature depth above 0%: project tree runs against the engine (M1.4) | | 2026-10-14 | minor | M0 done; MVP and parity estimates; stability and agent automation scored | | 2026-10-13 | major | Initial roadmap | diff --git a/docs/architecture.md b/docs/architecture.md index 6db1a53..c2490f5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Status:** M0 decisions recorded, M1 workspace and desktop bridge documented · **Last updated:** 2026-10-15 +> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor documented · **Last updated:** 2026-10-15 ## Overview @@ -92,6 +92,15 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - Capabilities: the main window may only listen to and unlisten from events (`core:event:allow-listen`, `core:event:allow-unlisten`). Engine commands are app commands and need no permission; the dialog plugin is used from Rust only, so the frontend gets no dialog permission. - Contract fix: the project UI from M1.5 was written against assumed shapes. `ui/src/components/project/engineEvents.ts` is now the adapter between the engine contract and the UI types: `toProjectEvent` translates `{kind: "projectOpened", root, name}` and friends into the store's events, and `toTreeEntries` translates `project.children`'s `{dir, entries: [{name, path, kind: file|directory|other, ignored, role}], truncated}` into tree entries (`kind: dir|file`, `role`, `excluded`, `special` for `other`) plus `truncated`. Malformed entries are skipped; a result without `entries` becomes an `ipc` error on the directory. +### Tabs and editor (M1.6) + +- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it. `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them. +- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text. +- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table. +- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context. Saving and closing wait until the sync has no pending edits. +- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Lutra saves only on request for now (no autosave). +- Theme: the editor reads colours only from `--lt-*` tokens. Tokens the theme does not have yet are read as `var(--lt-new-token, )` so they take effect once added in Rust. + ## Decisions (M0) | Question | Decision | Why | @@ -109,6 +118,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | M1.6: tabs and editor (buffer sync, CRLF offsets, shortcuts from command specs) | | 2026-10-15 | minor | M1.4: desktop bridge (engine://event, engine_ready replay, folder picker, capabilities), UI contract fix | | 2026-10-14 | minor | M1.3: workspace commands, edit protocol, events, events.subscribe, watched-directory limits | | 2026-10-14 | minor | Screenshot method, placeholder app identifier | diff --git a/docs/gaps.md b/docs/gaps.md index a375069..cfea08b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,14 +1,14 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers); G3 project tree works in the app · **Last updated:** 2026-10-15 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app); G3 project tree works in the app · **Last updated:** 2026-10-15 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. | # | Gap | Milestone | Estimate (one agent) | |---|---|---|---| | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | -| G2 | Editor core: ~~engine buffers, save~~ (M1.3), editor UI, undo, multi-caret, recovery journal | M1 | ~25 h | -| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, showing truncated listings, error notifications for the folder picker, tabs; command palette, settings, theme switching | M1 | ~24 h | +| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), recovery journal, tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~18 h | +| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, showing truncated listings, error notifications for the folder picker, ~~tabs~~ (M1.6); command palette, settings, theme switching | M1 | ~24 h | | G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h | @@ -23,7 +23,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G15 | Database tools, HTTP client, Docker and remote | later | ~430 h | | G16 | Plug-ins and ecosystem | later | ~120 h | -G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. Still open: the editor UI, undo, multi-caret and the recovery journal; estimate lowered to ~25 h. +G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. Still open: the recovery journal, tab management beyond open/close, a conflict UI (compare and merge with the disk version), autosave, editor settings (font size, soft wrap); estimate lowered to ~18 h. Known smaller items from M0: @@ -35,6 +35,7 @@ Known smaller items from M0: | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | G2 shrunk: tabs and editor (M1.6) | | 2026-10-15 | minor | G3 shrunk: project tree wired to the engine (M1.4) | | 2026-10-14 | minor | G2 shrunk, G3 note: engine workspace (M1.3) | | 2026-10-14 | minor | G3 note: project tree UI (M1.5) | diff --git a/docs/roadmap.md b/docs/roadmap.md index 06aa8b5..552c8c7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -7,7 +7,7 @@ Hours are agent wall-clock hours for one agent; M0 is measured, the rest estimat | Milestone | Goal | State | Hours | |---|---|---|---:| | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: no remote) | ~2 (measured) | -| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge) | ~60 | +| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor) | ~60 | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~50 | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~80 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | @@ -31,6 +31,7 @@ By the estimates above the alpha gate needs M1–M4 plus cross-platform verifica | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | M1.6 tabs and editor | | 2026-10-15 | minor | M1.4 desktop bridge | | 2026-10-14 | minor | M1 in progress | | 2026-10-14 | minor | M0 done; hours per milestone | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4e9ea16..1e06d1f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity -> **Status:** M1 in progress (text buffer, VFS, engine workspace, project tree in the app), no PHP feature ships · **Last updated:** 2026-10-15 · **Target:** PhpStorm 2026.x +> **Status:** M1 in progress (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor in the app), no PHP feature ships · **Last updated:** 2026-10-15 · **Target:** PhpStorm 2026.x ## How this is measured @@ -12,7 +12,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Area | Weight | Score | Missing | Hours (one agent) | Evidence | |---|---:|---:|---|---:|---| -| Editor core | 12 | 0% | everything user-visible: no editor in the UI yet; engine buffers, file commands and events exist | ~120 (est.) | `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) | +| Editor core | 12 | 8% (est.) | crash-recovery journal, syntax highlighting (M2), code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs | ~110 (est.) | M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) | | Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations, showing truncated listings | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not | | Navigation | 10 | 0% | everything | ~120 (est.) | — | | Search and replace | 6 | 0% | everything | ~80 (est.) | — | @@ -35,7 +35,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Plug-ins | 0.5 | 0% | everything | ~120 (est.) | — | | AI features | 0.5 | 0% | everything | ~60 (est.) | — | -Sum: about 2,930 h. Adding UI fidelity (~150 h), localization (~40 h), performance (~100 h) and stability hardening (~100 h) gives the ROADMAP's ~3,300 h to full parity. The range is wide (2,000–5,000 h): completion, inspections, refactoring and frameworks depend on an own type-inference engine whose size is hard to judge before M6. +Sum: about 2,920 h. Adding UI fidelity (~150 h), localization (~40 h), performance (~100 h) and stability hardening (~100 h) gives the ROADMAP's ~3,300 h to full parity. The range is wide (2,000–5,000 h): completion, inspections, refactoring and frameworks depend on an own type-inference engine whose size is hard to judge before M6. Weights were reviewed at the end of M0 and kept: nothing built so far gives a reason to change them. @@ -61,6 +61,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated); | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Editor core 0% → 8% (estimated): tabs and editor in the app (M1.6) | | 2026-10-15 | minor | Project view 0% → 8% (estimated): tree runs against the engine in the app (M1.4) | | 2026-10-14 | minor | Project view evidence: project tree UI (M1.5), score unchanged | | 2026-10-14 | minor | M1.3 engine workspace evidence (Editor core, Project view; scores unchanged) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0b9a5ca..ec2ed0b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity checklist -> **Status:** main window layout (M1.5) and project tree running against the engine in the app (M1.4) · **Last updated:** 2026-10-15 +> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6) · **Last updated:** 2026-10-15 - [ ] Main window: tool window stripes, editor area, status bar, navigation bar - M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4). @@ -8,6 +8,7 @@ - M1.5 (2026-10-14): tree of the open folder with lazy `project.children` listings, folders and PHP files with Lucide icons, ignored/excluded entries dimmed, keyboard navigation (WAI-ARIA tree: arrows, Home/End, Enter), double-click opens, refresh on `TreeChanged`, listing errors shown in the tree, empty state with Open Folder…. Vitest only, against a mocked engine. - M1.4 (2026-10-15): runs against the real engine in the app: projects open from the folder picker or the command line, the tree updates live when files change on disk; checked with `ui.screenshot` on Windows 11. Missing: scroll from source (Select Opened File), expand/collapse all, views list, sort options, speed search, file colours, file operations. Behaviour notes: `plan/phpstorm/02-project-view.md`. - [ ] Editor tabs (pin, split, reorder, close others) + - M1.6 (2026-10-15): tab bar above a CodeMirror 6 editor; files open from the project tree (Enter, double click) next to the active tab, or from engine events (control channel, page reload); click and Left/Right activate, the close button, a middle click and `Mod+W` close; a dot marks unsaved changes; closing a dirty tab asks Save / Don't Save / Cancel; `Mod+S` saves, `Mod+Alt+S` saves all (shortcuts read from the engine's command specs); a non-blocking notice when a dirty file changes or disappears on disk. Checked with `ui.screenshot` on Windows 11 and Vitest. Missing: preview tab, pin, split, reorder by drag, close others/all, reopen closed tab, tab limit, tab context menu, recent-files switcher, duplicate-name disambiguation. Behaviour notes: `plan/phpstorm/03-editor-tabs.md`. - [ ] Command palette / search everywhere - [ ] Settings dialog with search - [ ] Keymap editor (Lutra's own default keymap; no copied keymaps) @@ -23,6 +24,7 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Editor tabs partial (M1.6) | | 2026-10-15 | minor | Project tool window runs against the engine (M1.4) | | 2026-10-14 | minor | Notes on main window and project tool window (M1.5) | | 2026-10-13 | major | Baseline | diff --git a/ui/package.json b/ui/package.json index fd6a8f0..b59ff2f 100644 --- a/ui/package.json +++ b/ui/package.json @@ -16,8 +16,11 @@ "test": "vitest run" }, "dependencies": { + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.14", "@lucide/vue": "^1.57.0", "@tauri-apps/api": "^2.12.3", + "codemirror": "^6.0.2", "pinia": "^4.0.3", "vue": "^3.5.44" }, diff --git a/ui/pnpm-lock.yaml b/ui/pnpm-lock.yaml index a98512f..f6a548b 100644 --- a/ui/pnpm-lock.yaml +++ b/ui/pnpm-lock.yaml @@ -8,12 +8,21 @@ importers: .: dependencies: + '@codemirror/state': + specifier: ^6.7.6 + version: 6.7.6 + '@codemirror/view': + specifier: ^6.43.14 + version: 6.43.14 '@lucide/vue': specifier: ^1.57.0 version: 1.57.0(vue@3.5.44(typescript@6.0.3)) '@tauri-apps/api': specifier: ^2.12.3 version: 2.12.3 + codemirror: + specifier: ^6.0.2 + version: 6.0.2 pinia: specifier: ^4.0.3 version: 4.0.3(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.44(typescript@6.0.3)) @@ -101,6 +110,30 @@ packages: '@cacheable/utils@2.5.0': resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + '@codemirror/autocomplete@6.20.3': + resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==} + + '@codemirror/commands@6.11.1': + resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==} + + '@codemirror/language@6.13.1': + resolution: {integrity: sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==} + + '@codemirror/lint@6.9.7': + resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==} + + '@codemirror/search@6.7.2': + resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==} + + '@codemirror/state@6.7.6': + resolution: {integrity: sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==} + + '@codemirror/streamparser@6.0.0': + resolution: {integrity: sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==} + + '@codemirror/view@6.43.14': + resolution: {integrity: sha512-hC45YnmJNR1rz42OF57BLoQNFMV12/13drnvibDsR2quNDmldcb4WvYVV81hFQg56i9lcqQMEDqilhX2QDcGQQ==} + '@csstools/color-helpers@6.1.2': resolution: {integrity: sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==} engines: {node: '>=20.19.0'} @@ -224,11 +257,23 @@ packages: '@keyv/serialize@1.1.1': resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + '@lezer/common@1.5.3': + resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==} + + '@lezer/highlight@1.2.5': + resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==} + + '@lezer/lr@1.4.11': + resolution: {integrity: sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==} + '@lucide/vue@1.57.0': resolution: {integrity: sha512-l/D9mr+8Wb8uHl2vzHfcGVRkunJnq0NDmv8HFwXAL3UiYYxuNpDSd1uaCVqeR8+I1XY70dWA+R5W/pSpXWilMw==} peerDependencies: vue: '>=3.0.1' + '@marijn/find-cluster-break@1.0.4': + resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==} + '@one-ini/wasm@0.2.1': resolution: {integrity: sha512-TUqERXGNTifZ9y2g3wPxQrw3HpHv/02DsW3D90T9x0hhonrL1ZqpSmNrU2XkoIq0fP1N6gZfVQzy2Fw1ZvGBNg==} @@ -541,6 +586,9 @@ packages: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} + codemirror@6.0.2: + resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==} + commander@14.0.3: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} @@ -548,6 +596,9 @@ packages: config-chain@1.1.13: resolution: {integrity: sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==} + crelt@1.0.7: + resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==} + cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -1031,6 +1082,9 @@ packages: std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + style-mod@4.1.4: + resolution: {integrity: sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==} + tinybench@6.2.2: resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==} engines: {node: '>=20.0.0'} @@ -1203,6 +1257,9 @@ packages: typescript: optional: true + w3c-keyname@2.2.8: + resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + w3c-xmlserializer@6.0.0: resolution: {integrity: sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} @@ -1290,6 +1347,55 @@ snapshots: hashery: 1.5.1 keyv: 5.6.0 + '@codemirror/autocomplete@6.20.3': + dependencies: + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.14 + '@lezer/common': 1.5.3 + + '@codemirror/commands@6.11.1': + dependencies: + '@codemirror/language': 6.13.1 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.14 + '@lezer/common': 1.5.3 + + '@codemirror/language@6.13.1': + dependencies: + '@codemirror/state': 6.7.6 + '@codemirror/streamparser': 6.0.0 + '@codemirror/view': 6.43.14 + '@lezer/common': 1.5.3 + '@lezer/highlight': 1.2.5 + '@lezer/lr': 1.4.11 + style-mod: 4.1.4 + + '@codemirror/lint@6.9.7': + dependencies: + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.14 + crelt: 1.0.7 + + '@codemirror/search@6.7.2': + dependencies: + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.14 + crelt: 1.0.7 + + '@codemirror/state@6.7.6': + dependencies: + '@marijn/find-cluster-break': 1.0.4 + + '@codemirror/streamparser@6.0.0': {} + + '@codemirror/view@6.43.14': + dependencies: + '@codemirror/state': 6.7.6 + crelt: 1.0.7 + style-mod: 4.1.4 + w3c-keyname: 2.2.8 + '@csstools/color-helpers@6.1.2': {} '@csstools/css-calc@3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': @@ -1383,10 +1489,22 @@ snapshots: '@keyv/serialize@1.1.1': {} + '@lezer/common@1.5.3': {} + + '@lezer/highlight@1.2.5': + dependencies: + '@lezer/common': 1.5.3 + + '@lezer/lr@1.4.11': + dependencies: + '@lezer/common': 1.5.3 + '@lucide/vue@1.57.0(vue@3.5.44(typescript@6.0.3))': dependencies: vue: 3.5.44(typescript@6.0.3) + '@marijn/find-cluster-break@1.0.4': {} + '@one-ini/wasm@0.2.1': {} '@oxc-project/types@0.153.0': {} @@ -1706,6 +1824,16 @@ snapshots: chai@6.3.0: {} + codemirror@6.0.2: + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/commands': 6.11.1 + '@codemirror/language': 6.13.1 + '@codemirror/lint': 6.9.7 + '@codemirror/search': 6.7.2 + '@codemirror/state': 6.7.6 + '@codemirror/view': 6.43.14 + commander@14.0.3: {} config-chain@1.1.13: @@ -1713,6 +1841,8 @@ snapshots: ini: 1.3.8 proto-list: 1.2.4 + crelt@1.0.7: {} + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -2166,6 +2296,8 @@ snapshots: std-env@4.3.0: {} + style-mod@4.1.4: {} + tinybench@6.2.2: {} tinyexec@1.3.1: {} @@ -2285,6 +2417,8 @@ snapshots: optionalDependencies: typescript: 6.0.3 + w3c-keyname@2.2.8: {} + w3c-xmlserializer@6.0.0: dependencies: xml-name-validator: 5.0.0 diff --git a/ui/src/App.vue b/ui/src/App.vue index 4f7c1f3..d68fa5a 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -1,9 +1,11 @@ + + + + diff --git a/ui/src/components/editor/CodeEditor.vue b/ui/src/components/editor/CodeEditor.vue new file mode 100644 index 0000000..5ac391a --- /dev/null +++ b/ui/src/components/editor/CodeEditor.vue @@ -0,0 +1,96 @@ + + + + + diff --git a/ui/src/components/editor/EditorArea.vue b/ui/src/components/editor/EditorArea.vue new file mode 100644 index 0000000..c8b96ae --- /dev/null +++ b/ui/src/components/editor/EditorArea.vue @@ -0,0 +1,158 @@ + + + + + diff --git a/ui/src/components/editor/EditorTabs.vue b/ui/src/components/editor/EditorTabs.vue new file mode 100644 index 0000000..5a41176 --- /dev/null +++ b/ui/src/components/editor/EditorTabs.vue @@ -0,0 +1,154 @@ + + + + + diff --git a/ui/src/components/editor/bufferSync.ts b/ui/src/components/editor/bufferSync.ts new file mode 100644 index 0000000..9cc0915 --- /dev/null +++ b/ui/src/components/editor/bufferSync.ts @@ -0,0 +1,386 @@ +/** + * Keeps one CodeMirror editor state in step with one engine buffer. + * + * The engine is the source of truth. Local changes are sent with + * `buffer.edit {id, baseVersion, edits}`, at most one call at a time; changes + * typed while a call is in flight are composed and sent together next. The + * invariant is: local document = unsent(inflight(confirmed)), where + * `confirmed` is the engine text at `version`. + * + * Resync: when the engine rejects an edit with `stale_version`, or reports a + * newer version than ours through `bufferChanged` (a reload from disk, an + * edit from the control channel), the sync fetches the text with + * `buffer.get`, computes the remote change against `confirmed`, rebases the + * unsent local changes over it and applies the remote change to the editor. + * No local keystroke is lost; the rebased changes are then sent against the + * new version. Idea from https://codemirror.net/examples/collab/. + */ +import { + Annotation, + ChangeSet, + EditorState, + Transaction, + type Extension, + type TransactionSpec, +} from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { run, type EngineError, type RunResult } from "../../ipc"; +import { diffDocs, EngineText, separatorOf, type EngineEdit } from "./engineText"; + +/** A buffer as `file.open` and `buffer.get` describe it. */ +export interface BufferInfo { + /** Buffer id. */ + id: number; + /** Project-relative path. */ + path: string; + /** Full text as the engine holds it. */ + text: string; + /** Current version. */ + version: number; + /** Whether the buffer has unsaved changes. */ + dirty: boolean; + /** Line ending the buffer saves with. */ + lineEnding: string; +} + +/** Result of `buffer.edit`. */ +export interface EditResult { + /** Buffer id. */ + id: number; + /** Version after the edit. */ + version: number; + /** Whether the buffer is dirty now. */ + dirty: boolean; +} + +/** Params of `buffer.edit`. */ +export interface EditParams { + /** Buffer id. */ + id: number; + /** Version the edits refer to. */ + baseVersion: number; + /** The edits, in engine UTF-16 offsets of the text at `baseVersion`. */ + edits: EngineEdit[]; +} + +/** How the sync reaches the engine; replaced by a fake in tests. */ +export interface SyncTransport { + /** Runs `buffer.edit`. */ + edit(params: EditParams): Promise>; + /** Runs `buffer.get`. */ + get(id: number): Promise>; +} + +/** Transport through the engine IPC. */ +export const engineTransport: SyncTransport = { + edit: (params) => + run("buffer.edit", { + id: params.id, + baseVersion: params.baseVersion, + edits: params.edits.map((e) => ({ from: e.from, to: e.to, insert: e.insert })), + }), + get: (id) => run("buffer.get", { id }), +}; + +/** Marks transactions that carry engine changes, so they are not sent back. */ +export const remoteChange = Annotation.define(); + +/** + * Checks that a value looks like a {@link BufferInfo}. + * + * @param value - an untrusted command result. + */ +export function isBufferInfo(value: unknown): value is BufferInfo { + if (typeof value !== "object" || value === null) { + return false; + } + const v = value as Record; + return ( + typeof v.id === "number" && + typeof v.path === "string" && + typeof v.text === "string" && + typeof v.version === "number" && + typeof v.dirty === "boolean" + ); +} + +/** Synchronises one buffer; see the module documentation. */ +export class BufferSync { + /** Engine buffer id. */ + readonly id: number; + /** The local editor state, always current. */ + private current: EditorState; + /** The view showing this buffer, null while another tab is active. */ + private view: EditorView | null = null; + /** Engine text at {@link version}. */ + private confirmed: EngineText; + /** Engine version of {@link confirmed}. */ + private version: number; + /** Highest version the engine reported for this buffer. */ + private latestKnown: number; + /** Changes sent and not yet answered, relative to {@link confirmed}. */ + private inflight: ChangeSet | null = null; + /** Local changes not sent yet, relative to `inflight(confirmed)`. */ + private unsent: ChangeSet | null = null; + /** Whether a `buffer.get` for a resync is running. */ + private resyncing = false; + /** Line break used for inserted text. */ + private separator: string; + /** Set once the buffer is closed; nothing is sent afterwards. */ + private disposed = false; + /** Callbacks waiting for {@link idle}. */ + private waiters: (() => void)[] = []; + /** Engine transport. */ + private readonly transport: SyncTransport; + /** Receives errors that are not handled by a resync. */ + private readonly onError: (error: EngineError) => void; + + /** + * @param info - the buffer as the engine described it. + * @param extensions - editor extensions for the state. + * @param transport - how to reach the engine. + * @param onError - receives failures (shown by the editor store). + */ + constructor( + info: BufferInfo, + extensions: Extension, + transport: SyncTransport = engineTransport, + onError: (error: EngineError) => void = () => undefined, + ) { + this.id = info.id; + this.confirmed = EngineText.fromEngine(info.text); + this.version = info.version; + this.latestKnown = info.version; + this.separator = separatorOf(info.lineEnding); + this.transport = transport; + this.onError = onError; + this.current = EditorState.create({ doc: this.confirmed.doc, extensions }); + } + + /** The current local editor state. */ + get state(): EditorState { + return this.current; + } + + /** Engine version the local document is based on. */ + get baseVersion(): number { + return this.version; + } + + /** Whether local changes have not reached the engine yet. */ + get pending(): boolean { + return this.inflight !== null || this.unsent !== null || this.resyncing; + } + + /** + * Shows this buffer in a view: the view takes over the local state and + * receives remote changes from now on. + * + * @param view - the editor view. + */ + attach(view: EditorView): void { + this.view = view; + view.setState(this.current); + } + + /** Stops updating the view (another tab became active). */ + detach(): void { + this.view = null; + } + + /** Stops syncing; the buffer was closed. */ + dispose(): void { + this.disposed = true; + this.view = null; + this.inflight = null; + this.unsent = null; + this.settle(); + } + + /** + * Creates and applies a transaction on the local state, as typing would. + * + * @param spec - the transaction. + */ + dispatch(spec: TransactionSpec): void { + this.applyTransactions([this.current.update(spec)]); + } + + /** + * Applies transactions created from the current state (by the view or by + * {@link dispatch}). Local document changes are queued for the engine. + * + * @param transactions - the transactions, in order. + */ + applyTransactions(transactions: readonly Transaction[]): void { + const last = transactions[transactions.length - 1]; + if (!last) { + return; + } + this.current = last.state; + for (const tr of transactions) { + if (tr.docChanged && tr.annotation(remoteChange) !== true) { + this.unsent = this.unsent ? this.unsent.compose(tr.changes) : tr.changes; + } + } + this.view?.update([...transactions]); + this.flush(); + } + + /** + * Notes a version reported by the engine (`bufferChanged`). A version + * newer than the local base starts a resync once nothing is in flight. + * + * @param version - the reported version. + */ + notifyVersion(version: number): void { + this.latestKnown = Math.max(this.latestKnown, version); + if (this.latestKnown > this.version && this.inflight === null) { + this.resync(); + } + } + + /** Resolves once every local change has reached the engine. */ + idle(): Promise { + if (!this.pending || this.disposed) { + return Promise.resolve(); + } + return new Promise((resolve) => this.waiters.push(resolve)); + } + + /** + * Wakes {@link idle} callers when nothing is pending. + * + * @param force - wake them even with pending changes (the engine could not + * be reached, so waiting longer would hang the caller). + */ + private settle(force = false): void { + if (!force && this.pending && !this.disposed) { + return; + } + const waiters = this.waiters; + this.waiters = []; + for (const wake of waiters) { + wake(); + } + } + + /** Sends the unsent changes, unless a call or a resync is running. */ + private flush(): void { + if (this.disposed || this.inflight !== null || this.resyncing || this.unsent === null) { + this.settle(); + return; + } + const changes = this.unsent; + this.inflight = changes; + this.unsent = null; + const params: EditParams = { + id: this.id, + baseVersion: this.version, + edits: this.confirmed.edits(changes, this.separator), + }; + void this.transport.edit(params).then((result) => { + this.onEditResult(changes, result); + }); + } + + /** + * Handles the answer to a `buffer.edit`. + * + * @param changes - the changes that were sent. + * @param result - the engine's answer. + */ + private onEditResult(changes: ChangeSet, result: RunResult): void { + if (this.disposed || this.inflight !== changes) { + return; + } + this.inflight = null; + if (result.ok) { + this.confirmed = this.confirmed.apply(changes, this.separator); + this.version = result.value.version; + this.latestKnown = Math.max(this.latestKnown, this.version); + if (this.latestKnown > this.version) { + this.resync(); + } else { + this.flush(); + } + return; + } + this.unsent = this.unsent ? changes.compose(this.unsent) : changes; + if (result.error.code === "stale_version") { + this.resync(); + } else { + this.onError(result.error); + this.resync(true); + } + } + + /** + * Fetches the engine text and rebases local changes onto it. + * + * @param dropLocal - discard unsent local changes instead of rebasing them + * (after the engine refused them for a reason other than a stale base). + */ + private resync(dropLocal = false): void { + if (this.disposed || this.resyncing || this.inflight !== null) { + return; + } + this.resyncing = true; + void this.transport.get(this.id).then((result) => { + this.resyncing = false; + if (this.disposed) { + return; + } + if (!result.ok || !isBufferInfo(result.value)) { + this.onError( + result.ok ? { code: "ipc", message: "unexpected result of buffer.get" } : result.error, + ); + this.settle(true); + return; + } + this.rebase(result.value, dropLocal); + }); + } + + /** + * Moves the local document onto fresh engine text. + * + * @param info - the engine's current buffer. + * @param dropLocal - see {@link resync}. + */ + private rebase(info: BufferInfo, dropLocal: boolean): void { + const fresh = EngineText.fromEngine(info.text); + const remote = diffDocs(this.confirmed.doc, fresh.doc); + const local = this.unsent; + let toLocal: ChangeSet; + if (local === null) { + toLocal = remote; + } else if (dropLocal) { + toLocal = local.invert(this.confirmed.doc).compose(remote); + this.unsent = null; + } else { + toLocal = remote.map(local, true); + this.unsent = local.map(remote); + if (this.unsent.empty) { + this.unsent = null; + } + } + this.confirmed = fresh; + this.version = info.version; + this.latestKnown = Math.max(this.latestKnown, info.version); + this.separator = separatorOf(info.lineEnding); + if (!toLocal.empty) { + this.applyTransactions([ + this.current.update({ + changes: toLocal, + annotations: [remoteChange.of(true), Transaction.addToHistory.of(false)], + }), + ]); + } + if (this.latestKnown > this.version) { + this.resync(); + } else { + this.flush(); + } + } +} diff --git a/ui/src/components/editor/engineEvents.ts b/ui/src/components/editor/engineEvents.ts new file mode 100644 index 0000000..ed0d7ae --- /dev/null +++ b/ui/src/components/editor/engineEvents.ts @@ -0,0 +1,100 @@ +/** + * Adapter between engine events and the editor store. + * + * Picks the events the editor needs from the engine's `engine://event` + * stream (see `docs/architecture.md` › Events), checks their fields (they + * cross the IPC boundary) and hands them to subscribers. One IPC + * subscription serves every subscriber. {@link emitEditorEvent} injects an + * event directly, which the tests use instead of the Tauri shell. + */ +import { onEngineEvent as onIpcEngineEvent, type EngineEventPayload } from "../../ipc"; + +/** An engine event as the editor store consumes it. */ +export type EditorEvent = + | { kind: "projectOpened" } + | { kind: "projectClosed" } + | { kind: "bufferOpened"; id: number; path: string } + | { kind: "bufferChanged"; id: number; version: number } + | { kind: "dirtyChanged"; id: number; dirty: boolean } + | { kind: "bufferClosed"; id: number } + | { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }; + +/** Callback receiving editor events. */ +export type EditorEventHandler = (event: EditorEvent) => void; + +/** + * Picks and checks an editor event from an engine event. + * + * @param payload - the engine event, untrusted. + * @returns the editor event, or null for other kinds and malformed events. + */ +export function toEditorEvent(payload: EngineEventPayload): EditorEvent | null { + const raw = payload as unknown as Record; + const num = (key: string): number | null => + typeof raw[key] === "number" && Number.isFinite(raw[key]) ? raw[key] : null; + const id = num("id"); + switch (payload.kind) { + case "projectOpened": + case "projectClosed": + return { kind: payload.kind }; + case "bufferOpened": + return id !== null && typeof raw.path === "string" + ? { kind: "bufferOpened", id, path: raw.path } + : null; + case "bufferChanged": { + const version = num("version"); + return id !== null && version !== null ? { kind: "bufferChanged", id, version } : null; + } + case "dirtyChanged": + return id !== null && typeof raw.dirty === "boolean" + ? { kind: "dirtyChanged", id, dirty: raw.dirty } + : null; + case "bufferClosed": + return id !== null ? { kind: "bufferClosed", id } : null; + case "fileChangedOnDisk": + return id !== null && typeof raw.path === "string" && typeof raw.removed === "boolean" + ? { kind: "fileChangedOnDisk", id, path: raw.path, removed: raw.removed } + : null; + default: + return null; + } +} + +/** Current subscribers. */ +const handlers = new Set(); + +/** Ends the IPC subscription; null while nobody listens. */ +let stopIpc: (() => void) | null = null; + +/** + * Delivers an engine event to every subscriber, if it is an editor event. + * + * @param payload - the engine event. + */ +export function emitEditorEvent(payload: EngineEventPayload): void { + const event = toEditorEvent(payload); + if (!event) { + return; + } + for (const handler of [...handlers]) { + handler(event); + } +} + +/** + * Subscribes to editor events. + * + * @param handler - called for every editor event, in engine order. + * @returns a function that ends the subscription. + */ +export function onEditorEvent(handler: EditorEventHandler): () => void { + handlers.add(handler); + stopIpc ??= onIpcEngineEvent(emitEditorEvent); + return () => { + handlers.delete(handler); + if (handlers.size === 0) { + stopIpc?.(); + stopIpc = null; + } + }; +} diff --git a/ui/src/components/editor/engineText.ts b/ui/src/components/editor/engineText.ts new file mode 100644 index 0000000..f97627f --- /dev/null +++ b/ui/src/components/editor/engineText.ts @@ -0,0 +1,214 @@ +/** + * Mapping between engine buffer text and CodeMirror documents. + * + * The engine keeps a file's text as it is on disk, line breaks included, and + * counts offsets in UTF-16 code units of that text. CodeMirror splits the + * text into lines and counts every line break as one position. Positions + * therefore differ by one for every `\r\n` before them. {@link EngineText} + * remembers which breaks are `\r\n` and converts positions and change sets + * into engine edits. Text without `\r\n` needs no bookkeeping. + */ +import { ChangeSet, Text } from "@codemirror/state"; + +/** Line ending of a buffer as the engine names it. */ +export type LineEndingName = "lf" | "crlf" | "cr"; + +/** One change of a `buffer.edit` call, in engine UTF-16 offsets. */ +export interface EngineEdit { + /** Start offset in the text at the base version. */ + from: number; + /** End offset (exclusive) in the text at the base version. */ + to: number; + /** Inserted text, with the buffer's line ending. */ + insert: string; +} + +/** Line breaks the engine and CodeMirror both recognise. */ +const LINE_BREAK = /\r\n|\r|\n/g; + +/** + * The line break string for a line ending name. + * + * @param name - the engine's name; anything unknown counts as `lf`. + */ +export function separatorOf(name: string): string { + return name === "crlf" ? "\r\n" : name === "cr" ? "\r" : "\n"; +} + +/** + * A CodeMirror document together with the kind of each of its line breaks + * in the engine text. + */ +export class EngineText { + /** The document as CodeMirror sees it. */ + readonly doc: Text; + /** + * For each line break (index `i` follows line `i`, 0-based) whether it is + * `\r\n` in the engine text; null when there is none. + */ + private readonly crlf: readonly boolean[] | null; + /** Number of `\r\n` breaks before each line; built on first use. */ + private prefix: Uint32Array | null = null; + + /** + * @param doc - the CodeMirror document. + * @param crlf - break kinds, see {@link EngineText.crlf}. + */ + private constructor(doc: Text, crlf: readonly boolean[] | null) { + this.doc = doc; + this.crlf = crlf; + } + + /** + * Builds the mapping for text received from the engine. + * + * @param text - the engine's buffer text. + */ + static fromEngine(text: string): EngineText { + const lines: string[] = []; + const crlf: boolean[] = []; + let any = false; + let start = 0; + LINE_BREAK.lastIndex = 0; + for (let m = LINE_BREAK.exec(text); m !== null; m = LINE_BREAK.exec(text)) { + lines.push(text.slice(start, m.index)); + const isCrlf = m[0] === "\r\n"; + crlf.push(isCrlf); + any ||= isCrlf; + start = m.index + m[0].length; + } + lines.push(text.slice(start)); + return new EngineText(Text.of(lines), any ? crlf : null); + } + + /** + * The engine text this mapping stands for, for checks and tests. Only + * `\r\n` breaks are remembered, so a lone `\r` comes back as `\n` (both + * are one UTF-16 unit, so offsets are unaffected). + */ + engineString(): string { + if (this.crlf === null) { + return this.doc.sliceString(0); + } + const parts: string[] = []; + let line = 0; + for (const text of this.doc.iterLines()) { + parts.push(text); + if (line < this.crlf.length) { + parts.push(this.crlf[line] === true ? "\r\n" : "\n"); + } + line += 1; + } + return parts.join(""); + } + + /** + * Converts a CodeMirror position into an engine offset. + * + * @param pos - a position in {@link doc}, clamped to its length. + * @returns the UTF-16 offset in the engine text. + */ + toEngine(pos: number): number { + const clamped = Math.max(0, Math.min(pos, this.doc.length)); + if (this.crlf === null) { + return clamped; + } + const line = this.doc.lineAt(clamped).number - 1; + return clamped + (this.prefixTable()[line] ?? 0); + } + + /** The table of `\r\n` counts before each line. */ + private prefixTable(): Uint32Array { + if (this.prefix === null) { + const crlf = this.crlf ?? []; + const table = new Uint32Array(crlf.length + 1); + for (let i = 0; i < crlf.length; i += 1) { + table[i + 1] = (table[i] ?? 0) + (crlf[i] === true ? 1 : 0); + } + this.prefix = table; + } + return this.prefix; + } + + /** + * Translates a change set on {@link doc} into engine edits. + * + * @param changes - changes whose start document is {@link doc}. + * @param separator - line break for inserted text (the buffer's ending). + */ + edits(changes: ChangeSet, separator: string): EngineEdit[] { + const out: EngineEdit[] = []; + changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => { + out.push({ + from: this.toEngine(fromA), + to: this.toEngine(toA), + insert: inserted.sliceString(0, inserted.length, separator), + }); + }); + return out; + } + + /** + * The mapping after a change set, assuming the engine applied the same + * changes with inserted line breaks written as `separator`. + * + * @param changes - changes whose start document is {@link doc}. + * @param separator - line break used for inserted text. + */ + apply(changes: ChangeSet, separator: string): EngineText { + const doc = changes.apply(this.doc); + const newCrlf = separator === "\r\n"; + if (this.crlf === null && !newCrlf) { + return new EngineText(doc, null); + } + const old = this.crlf; + const out: boolean[] = []; + let cursor = 0; + changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => { + const fromLine = this.doc.lineAt(fromA).number - 1; + const toLine = this.doc.lineAt(toA).number - 1; + for (let i = cursor; i < fromLine; i += 1) { + out.push(old?.[i] === true); + } + for (let i = 1; i < inserted.lines; i += 1) { + out.push(newCrlf); + } + cursor = Math.max(cursor, toLine); + }); + for (let i = cursor; i < this.doc.lines - 1; i += 1) { + out.push(old?.[i] === true); + } + return new EngineText(doc, out.includes(true) ? out : null); + } +} + +/** + * A minimal change set turning `from` into `to`: one replacement between + * their common prefix and suffix. + * + * @param from - the old document. + * @param to - the new document. + */ +export function diffDocs(from: Text, to: Text): ChangeSet { + const a = from.sliceString(0); + const b = to.sliceString(0); + if (a === b) { + return ChangeSet.empty(a.length); + } + const max = Math.min(a.length, b.length); + let prefix = 0; + while (prefix < max && a.charCodeAt(prefix) === b.charCodeAt(prefix)) { + prefix += 1; + } + let suffix = 0; + while ( + suffix < max - prefix && + a.charCodeAt(a.length - 1 - suffix) === b.charCodeAt(b.length - 1 - suffix) + ) { + suffix += 1; + } + return ChangeSet.of( + [{ from: prefix, to: a.length - suffix, insert: b.slice(prefix, b.length - suffix) }], + a.length, + ); +} diff --git a/ui/src/components/editor/extensions.ts b/ui/src/components/editor/extensions.ts new file mode 100644 index 0000000..e98b3e6 --- /dev/null +++ b/ui/src/components/editor/extensions.ts @@ -0,0 +1,97 @@ +/** + * CodeMirror extensions of the Lutra editor: the basic setup (line numbers, + * history, selection, brackets, search) without a language (PHP comes in + * M2), and a theme that takes every colour from `--lt-*` tokens. + * + * Tokens the theme does not define yet are read with a fallback derived from + * existing tokens (`var(--lt-editor-selection-bg, color-mix(…))`), so that a + * token added to the Rust theme later takes effect without code changes. + * Requested from design: `--lt-editor-selection-bg`, + * `--lt-editor-active-line-bg`, `--lt-editor-cursor`, `--lt-editor-gutter-bg`, + * `--lt-editor-gutter-fg`, `--lt-editor-match-bg`, `--lt-font-size-editor`. + */ +import { EditorView } from "@codemirror/view"; +import type { Extension } from "@codemirror/state"; +import { basicSetup } from "codemirror"; + +/** Editor theme built from theme tokens only. */ +export const lutraEditorTheme: Extension = EditorView.theme({ + "&": { + height: "100%", + color: "var(--lt-fg)", + backgroundColor: "var(--lt-editor-bg)", + fontSize: "var(--lt-font-size-editor, var(--lt-font-size-ui))", + }, + "&.cm-focused": { + outline: "none", + }, + ".cm-scroller": { + fontFamily: "var(--lt-font-mono)", + lineHeight: "1.5", + }, + ".cm-content": { + caretColor: "var(--lt-editor-cursor, var(--lt-accent))", + }, + ".cm-cursor, .cm-dropCursor": { + borderLeftColor: "var(--lt-editor-cursor, var(--lt-accent))", + }, + "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": + { + backgroundColor: + "var(--lt-editor-selection-bg, color-mix(in srgb, var(--lt-accent) 30%, transparent))", + }, + ".cm-activeLine": { + backgroundColor: + "var(--lt-editor-active-line-bg, color-mix(in srgb, var(--lt-fg) 5%, transparent))", + }, + ".cm-selectionMatch, .cm-searchMatch": { + backgroundColor: + "var(--lt-editor-match-bg, color-mix(in srgb, var(--lt-accent) 18%, transparent))", + }, + "&.cm-focused .cm-matchingBracket": { + backgroundColor: + "var(--lt-editor-match-bg, color-mix(in srgb, var(--lt-accent) 18%, transparent))", + outline: "1px solid var(--lt-border)", + }, + ".cm-gutters": { + backgroundColor: "var(--lt-editor-gutter-bg, var(--lt-editor-bg))", + color: "var(--lt-editor-gutter-fg, var(--lt-fg-muted))", + borderRight: "1px solid var(--lt-border)", + }, + ".cm-activeLineGutter": { + backgroundColor: + "var(--lt-editor-active-line-bg, color-mix(in srgb, var(--lt-fg) 5%, transparent))", + color: "var(--lt-fg)", + }, + ".cm-panels": { + backgroundColor: "var(--lt-bg)", + color: "var(--lt-fg)", + }, + ".cm-panels-top": { + borderBottom: "1px solid var(--lt-border)", + }, + ".cm-panels-bottom": { + borderTop: "1px solid var(--lt-border)", + }, + ".cm-textfield": { + backgroundColor: "var(--lt-editor-bg)", + color: "var(--lt-fg)", + border: "1px solid var(--lt-border)", + }, + ".cm-button": { + backgroundImage: "none", + backgroundColor: "var(--lt-bg)", + color: "var(--lt-fg)", + border: "1px solid var(--lt-border)", + }, + ".cm-tooltip": { + backgroundColor: "var(--lt-bg)", + color: "var(--lt-fg)", + border: "1px solid var(--lt-border)", + }, +}); + +/** Every extension of an editor state. */ +export function editorExtensions(): Extension { + return [basicSetup, lutraEditorTheme]; +} diff --git a/ui/src/components/editor/shortcuts.ts b/ui/src/components/editor/shortcuts.ts new file mode 100644 index 0000000..1d43354 --- /dev/null +++ b/ui/src/components/editor/shortcuts.ts @@ -0,0 +1,155 @@ +/** + * Editor shortcuts, taken from the engine's command specs. + * + * The engine defines default shortcuts in Lutra notation (`Mod+Alt+S`, + * `Mod` = Cmd on macOS, Ctrl elsewhere). The editor area loads them with + * `listCommands` and maps key presses to the editor commands it handles + * with context (the active buffer): saving, saving all and closing a tab. + * Nothing here hard-codes a key. + */ +import { listCommands, type CommandInfo, type RunResult } from "../../ipc"; + +/** Engine commands the editor area runs with the active buffer as context. */ +export const EDITOR_SHORTCUT_COMMANDS = ["file.save", "file.saveAll", "buffer.close"] as const; + +/** One of {@link EDITOR_SHORTCUT_COMMANDS}. */ +export type EditorShortcutCommand = (typeof EDITOR_SHORTCUT_COMMANDS)[number]; + +/** A parsed shortcut. */ +export interface Shortcut { + /** Ctrl must be held. */ + ctrl: boolean; + /** Meta (Cmd) must be held. */ + meta: boolean; + /** Alt (Option) must be held. */ + alt: boolean; + /** Shift must be held. */ + shift: boolean; + /** The key, lower case (`s`, `f4`, `enter`). */ + key: string; +} + +/** Whether the frontend runs on macOS, where `Mod` means Cmd. */ +export function isMac(): boolean { + return typeof navigator !== "undefined" && /Mac OS X|Macintosh|iPhone|iPad/.test(navigator.userAgent); +} + +/** + * Parses a shortcut in Lutra notation. + * + * @param text - for example `Mod+Alt+S`. + * @param mac - whether `Mod` means Cmd. + * @returns the shortcut, or null when the text has no key or an unknown modifier. + */ +export function parseShortcut(text: string, mac: boolean): Shortcut | null { + const parts = text.split("+").map((part) => part.trim().toLowerCase()); + const key = parts.pop(); + if (key === undefined || key === "") { + return null; + } + const shortcut: Shortcut = { ctrl: false, meta: false, alt: false, shift: false, key }; + for (const part of parts) { + switch (part) { + case "mod": + if (mac) { + shortcut.meta = true; + } else { + shortcut.ctrl = true; + } + break; + case "ctrl": + shortcut.ctrl = true; + break; + case "cmd": + case "meta": + shortcut.meta = true; + break; + case "alt": + shortcut.alt = true; + break; + case "shift": + shortcut.shift = true; + break; + default: + return null; + } + } + return shortcut; +} + +/** + * The key of an event, independent of keyboard layout effects of Alt and + * Shift for letters and digits (`Alt+S` on macOS types `ß`). + * + * @param event - the key event. + */ +function eventKey(event: KeyboardEvent): string { + const code = event.code; + if (/^Key[A-Z]$/.test(code)) { + return code.slice(3).toLowerCase(); + } + if (/^Digit[0-9]$/.test(code)) { + return code.slice(5); + } + return event.key.toLowerCase(); +} + +/** + * Whether a key event matches a shortcut exactly. + * + * @param event - the key event. + * @param shortcut - the shortcut. + */ +export function matches(event: KeyboardEvent, shortcut: Shortcut): boolean { + return ( + event.ctrlKey === shortcut.ctrl && + event.metaKey === shortcut.meta && + event.altKey === shortcut.alt && + event.shiftKey === shortcut.shift && + eventKey(event) === shortcut.key + ); +} + +/** Shortcuts of the editor commands, by command. */ +export type EditorKeymap = { command: EditorShortcutCommand; shortcut: Shortcut }[]; + +/** + * Loads the default shortcuts of the editor commands from the engine. + * + * @param mac - whether `Mod` means Cmd. + * @returns the keymap, or the error of `listCommands`. + */ +export async function loadEditorKeymap(mac = isMac()): Promise> { + const result = await listCommands(); + if (!result.ok) { + return result; + } + const list: unknown = result.value; + if (!Array.isArray(list)) { + return { ok: false, error: { code: "ipc", message: "unexpected result of listCommands" } }; + } + const commands = (list as unknown[]).filter( + (c): c is CommandInfo => typeof c === "object" && c !== null && "id" in c, + ); + const keymap: EditorKeymap = []; + for (const command of EDITOR_SHORTCUT_COMMANDS) { + const info = commands.find((c) => c.id === command); + const raw: unknown = info?.defaultShortcut; + const shortcut = typeof raw === "string" ? parseShortcut(raw, mac) : null; + if (shortcut) { + keymap.push({ command, shortcut }); + } + } + return { ok: true, value: keymap }; +} + +/** + * The editor command a key event triggers. + * + * @param keymap - the loaded keymap. + * @param event - the key event. + * @returns the command, or null. + */ +export function commandFor(keymap: EditorKeymap, event: KeyboardEvent): EditorShortcutCommand | null { + return keymap.find((entry) => matches(event, entry.shortcut))?.command ?? null; +} diff --git a/ui/src/components/project/ProjectTree.vue b/ui/src/components/project/ProjectTree.vue index 52495ba..c72d0c5 100644 --- a/ui/src/components/project/ProjectTree.vue +++ b/ui/src/components/project/ProjectTree.vue @@ -11,9 +11,11 @@ import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue"; import { computed, nextTick, ref } from "vue"; import { parentOf, useProjectStore, type TreeRow } from "../../stores/project"; +import { useEditorStore } from "../../stores/editor"; import type { TreeEntry } from "./engineEvents"; const project = useProjectStore(); +const editor = useEditorStore(); /** The tree element, for keeping the selected row in view. */ const treeEl = ref(null); @@ -108,7 +110,7 @@ function activate(entry: TreeEntry): void { if (entry.kind === "dir") { void project.toggle(entry.path); } else { - void project.openFile(entry.path); + void editor.openFile(entry.path); } } diff --git a/ui/src/stores/editor.ts b/ui/src/stores/editor.ts new file mode 100644 index 0000000..762d0e7 --- /dev/null +++ b/ui/src/stores/editor.ts @@ -0,0 +1,507 @@ +/** + * Editor tabs: which engine buffers are open, which one is active, their + * dirty state, notices, and the Save / Don't save / Cancel question when a + * dirty tab closes. + * + * Fed by engine events (`bufferOpened`, `bufferChanged`, `dirtyChanged`, + * `bufferClosed`, `fileChangedOnDisk`, project open/close) and by command + * results. Text lives in the engine and in one {@link BufferSync} per tab, + * kept outside reactive state. Command failures are stored and shown, never + * thrown. + */ +import { defineStore } from "pinia"; +import { computed, ref, shallowRef } from "vue"; +import { run, type EngineError, type RunResult } from "../ipc"; +import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync"; +import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents"; +import { editorExtensions } from "../components/editor/extensions"; +import type { Extension } from "@codemirror/state"; + +/** Engine command ids used by the editor. */ +export const EDITOR_COMMANDS = { + /** Opens a file: params `{ path }`, result {@link BufferInfo}. */ + open: "file.open", + /** Describes a buffer: params `{ id }`, result {@link BufferInfo}. */ + get: "buffer.get", + /** Saves a buffer: params `{ id }`. */ + save: "file.save", + /** Saves every dirty buffer: result `{ saved, failed: [{ id, message }] }`. */ + saveAll: "file.saveAll", + /** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */ + close: "buffer.close", +} as const; + +/** A notice shown above a tab's editor; it never blocks editing. */ +export interface EditorNotice { + /** What happened. */ + kind: "changedOnDisk" | "removedOnDisk" | "error"; + /** Text for the user. */ + message: string; +} + +/** One editor tab. */ +export interface EditorTab { + /** Engine buffer id. */ + id: number; + /** Project-relative path. */ + path: string; + /** File name shown on the tab. */ + name: string; + /** Unsaved changes in the engine buffer. */ + dirty: boolean; + /** Notice for this tab, null if none. */ + notice: EditorNotice | null; +} + +/** The pending question for closing a dirty tab. */ +export interface ClosePrompt { + /** Buffer id of the tab. */ + id: number; + /** File name, for the question. */ + name: string; +} + +/** Answer to a {@link ClosePrompt}. */ +export type CloseChoice = "save" | "discard" | "cancel"; + +/** Timing of the last file open, for the performance budget. */ +export interface OpenTiming { + /** Path of the opened file. */ + path: string; + /** Size of the text in UTF-16 code units. */ + length: number; + /** Milliseconds from the request until the editor state existed. */ + stateMs: number; + /** Milliseconds until the editor showed it, null until the view reports. */ + shownMs: number | null; +} + +/** + * The file name of a project-relative path. + * + * @param path - for example `src/App.php`. + */ +export function baseName(path: string): string { + const slash = path.lastIndexOf("/"); + return slash < 0 ? path : path.slice(slash + 1); +} + +/** Store of editor tabs. */ +export const useEditorStore = defineStore("editor", () => { + /** Open tabs in display order. */ + const tabs = ref([]); + /** Buffer id of the active tab, null when no tab is open. */ + const activeId = ref(null); + /** Pending close question, null if none. */ + const closePrompt = ref(null); + /** Last failed editor command, null if none. */ + const lastError = ref(null); + /** Timing of the last open, see {@link OpenTiming}. */ + const lastOpen = shallowRef(null); + /** Syncs by buffer id; not reactive (they hold large editor states). */ + const syncs = new Map(); + /** Start time of open requests by path, for {@link lastOpen}. */ + const openStarted = new Map(); + /** Start time of the open measured in {@link lastOpen}. */ + let timedStart = 0; + /** Engine transport for syncs, replaceable in tests. */ + let transport: SyncTransport = engineTransport; + /** Extensions of new editor states, replaceable in tests. */ + let extensions: () => Extension = editorExtensions; + /** Counter of tab adoptions, so only the newest open activates its tab. */ + let openSequence = 0; + /** Unsubscribe function of the event subscription. */ + let unsubscribe: (() => void) | null = null; + + /** The active tab, or null. */ + const activeTab = computed(() => tabs.value.find((t) => t.id === activeId.value) ?? null); + + /** + * The tab of a buffer. + * + * @param id - buffer id. + */ + function tabOf(id: number): EditorTab | undefined { + return tabs.value.find((t) => t.id === id); + } + + /** + * The sync of a buffer, for the editor view. + * + * @param id - buffer id. + */ + function syncOf(id: number): BufferSync | undefined { + return syncs.get(id); + } + + /** + * Replaces the engine transport and editor extensions (tests). + * + * @param next - transport for new syncs. + * @param nextExtensions - extensions for new editor states. + */ + function configure(next: SyncTransport, nextExtensions?: () => Extension): void { + transport = next; + if (nextExtensions) { + extensions = nextExtensions; + } + } + + /** + * Adds a tab for a buffer the engine described, unless it exists, and + * activates it. + * + * @param info - the buffer. + * @param activate - whether the tab becomes active. + */ + function adopt(info: BufferInfo, activate = true): void { + if (!syncs.has(info.id)) { + const started = openStarted.get(info.path); + syncs.set( + info.id, + new BufferSync(info, extensions(), transport, (error) => { + const tab = tabOf(info.id); + if (tab) { + tab.notice = { kind: "error", message: error.message }; + } + }), + ); + if (started !== undefined) { + openStarted.delete(info.path); + timedStart = started; + lastOpen.value = { + path: info.path, + length: info.text.length, + stateMs: performance.now() - started, + shownMs: null, + }; + } + } + if (!tabOf(info.id)) { + const index = tabs.value.findIndex((t) => t.id === activeId.value); + const tab: EditorTab = { + id: info.id, + path: info.path, + name: baseName(info.path), + dirty: info.dirty, + notice: null, + }; + tabs.value.splice(index < 0 ? tabs.value.length : index + 1, 0, tab); + } + if (activate || activeId.value === null) { + activeId.value = info.id; + } + } + + /** + * Records that the view showed the buffer whose open is being timed. + * + * @param id - buffer id that became visible. + */ + function markShown(id: number): void { + const timing = lastOpen.value; + if (!timing || timing.shownMs !== null || tabOf(id)?.path !== timing.path) { + return; + } + lastOpen.value = { ...timing, shownMs: performance.now() - timedStart }; + } + + /** + * Opens a file in a tab (or activates its tab). + * + * @param path - project-relative path. + */ + async function openFile(path: string): Promise { + openStarted.set(path, performance.now()); + const result = await run(EDITOR_COMMANDS.open, { path }); + if (!result.ok) { + openStarted.delete(path); + lastError.value = result.error; + return; + } + if (!isBufferInfo(result.value)) { + lastError.value = { code: "ipc", message: `unexpected result of ${EDITOR_COMMANDS.open}` }; + return; + } + lastError.value = null; + openSequence += 1; + adopt(result.value); + } + + /** + * Activates a tab. + * + * @param id - buffer id. + */ + function activate(id: number): void { + if (tabOf(id)) { + activeId.value = id; + } + } + + /** + * Removes a tab and its sync; the neighbour becomes active. + * + * @param id - buffer id. + */ + function removeTab(id: number): void { + syncs.get(id)?.dispose(); + syncs.delete(id); + const index = tabs.value.findIndex((t) => t.id === id); + if (index < 0) { + return; + } + tabs.value.splice(index, 1); + if (activeId.value === id) { + const next = tabs.value[Math.min(index, tabs.value.length - 1)]; + activeId.value = next ? next.id : null; + } + if (closePrompt.value?.id === id) { + closePrompt.value = null; + } + } + + /** + * Waits until local edits of a buffer reached the engine. + * + * @param id - buffer id. + */ + async function settled(id: number): Promise { + await syncs.get(id)?.idle(); + } + + /** + * Runs `buffer.close`. + * + * @param id - buffer id. + * @param force - discard unsaved changes. + * @returns the command result. + */ + async function closeBuffer(id: number, force: boolean): Promise> { + const result = await run(EDITOR_COMMANDS.close, { id, force }); + if (result.ok) { + removeTab(id); + } + return result; + } + + /** + * Closes a tab; a dirty one asks Save / Don't save / Cancel first. + * + * @param id - buffer id; the active tab when omitted. + */ + async function requestClose(id: number | null = activeId.value): Promise { + if (id === null) { + return; + } + const tab = tabOf(id); + if (!tab) { + return; + } + await settled(id); + if (tab.dirty) { + closePrompt.value = { id, name: tab.name }; + return; + } + const result = await closeBuffer(id, false); + if (result.ok) { + lastError.value = null; + } else if (result.error.code === "unsaved_changes") { + tab.dirty = true; + closePrompt.value = { id, name: tab.name }; + } else { + lastError.value = result.error; + } + } + + /** + * Answers the pending close question. + * + * @param choice - save and close, close without saving, or keep the tab. + */ + async function resolveClose(choice: CloseChoice): Promise { + const prompt = closePrompt.value; + closePrompt.value = null; + if (!prompt || choice === "cancel") { + return; + } + if (choice === "save" && !(await save(prompt.id))) { + return; + } + const result = await closeBuffer(prompt.id, choice === "discard"); + lastError.value = result.ok ? null : result.error; + } + + /** + * Saves a buffer after its local edits reached the engine. + * + * @param id - buffer id; the active tab when omitted. + * @returns whether the save succeeded. + */ + async function save(id: number | null = activeId.value): Promise { + if (id === null || !tabOf(id)) { + return false; + } + await settled(id); + const result = await run(EDITOR_COMMANDS.save, { id }); + lastError.value = result.ok ? null : result.error; + if (result.ok) { + const tab = tabOf(id); + if (tab) { + tab.dirty = false; + if (tab.notice?.kind === "changedOnDisk") { + tab.notice = null; + } + } + } + return result.ok; + } + + /** Saves every buffer after all local edits reached the engine. */ + async function saveAll(): Promise { + await Promise.all(tabs.value.map((t) => settled(t.id))); + const result = await run<{ failed?: { id?: unknown; message?: unknown }[] }>( + EDITOR_COMMANDS.saveAll, + ); + if (!result.ok) { + lastError.value = result.error; + return; + } + const failed = Array.isArray(result.value.failed) ? result.value.failed : []; + lastError.value = + failed.length > 0 + ? { + code: "save_failed", + message: failed + .map((f) => (typeof f.message === "string" ? f.message : "save failed")) + .join("; "), + } + : null; + } + + /** + * Hides a tab's notice. + * + * @param id - buffer id. + */ + function dismissNotice(id: number): void { + const tab = tabOf(id); + if (tab) { + tab.notice = null; + } + } + + /** Drops every tab (the project closed or changed). */ + function clear(): void { + for (const sync of syncs.values()) { + sync.dispose(); + } + syncs.clear(); + tabs.value = []; + activeId.value = null; + closePrompt.value = null; + } + + /** + * Adds a tab for a buffer opened elsewhere (control channel, replay after + * a reload), fetching its text first. When several open at once, the + * last one opened becomes active, whatever order the fetches finish in. + * + * @param id - buffer id. + */ + async function adoptOpened(id: number): Promise { + if (syncs.has(id)) { + return; + } + const sequence = ++openSequence; + const result = await run(EDITOR_COMMANDS.get, { id }); + if (!result.ok) { + lastError.value = result.error; + return; + } + if (isBufferInfo(result.value) && !syncs.has(id)) { + adopt(result.value, sequence === openSequence); + } + } + + /** + * Applies one editor event. + * + * @param event - the event. + */ + function handleEvent(event: EditorEvent): void { + switch (event.kind) { + case "projectOpened": + case "projectClosed": + clear(); + break; + case "bufferOpened": + void adoptOpened(event.id); + break; + case "bufferChanged": + syncs.get(event.id)?.notifyVersion(event.version); + break; + case "dirtyChanged": { + const tab = tabOf(event.id); + if (tab) { + tab.dirty = event.dirty; + } + break; + } + case "bufferClosed": + removeTab(event.id); + break; + case "fileChangedOnDisk": { + const tab = tabOf(event.id); + if (!tab) { + break; + } + if (event.removed) { + tab.notice = { + kind: "removedOnDisk", + message: `${tab.name} was deleted on disk. Your text is kept; saving writes it again.`, + }; + } else { + tab.notice = { + kind: "changedOnDisk", + message: `${tab.name} changed on disk. Your unsaved changes are kept; saving overwrites the file.`, + }; + } + break; + } + } + } + + /** Subscribes to engine events; calling it again has no effect. */ + function start(): void { + unsubscribe ??= onEditorEvent(handleEvent); + } + + /** Ends the event subscription. */ + function stop(): void { + unsubscribe?.(); + unsubscribe = null; + } + + return { + tabs, + activeId, + activeTab, + closePrompt, + lastError, + lastOpen, + syncOf, + configure, + openFile, + activate, + requestClose, + resolveClose, + save, + saveAll, + dismissNotice, + markShown, + handleEvent, + start, + stop, + }; +}); diff --git a/ui/tests/App.test.ts b/ui/tests/App.test.ts index b391795..9b7519f 100644 --- a/ui/tests/App.test.ts +++ b/ui/tests/App.test.ts @@ -18,7 +18,13 @@ describe("App", () => { }); it("shows name and version in the status bar", async () => { - invoke.mockResolvedValue({ name: "Lutra", version: "0.0.0", slogan: "An otterly perfect IDE" }); + invoke.mockImplementation((command: string) => + Promise.resolve( + command === "engine_list_commands" + ? [] + : { name: "Lutra", version: "0.0.0", slogan: "An otterly perfect IDE" }, + ), + ); const wrapper = mount(App); await flushPromises(); expect(wrapper.get("[data-test=status-bar]").text()).toBe("Lutra 0.0.0"); diff --git a/ui/tests/editor/EditorArea.test.ts b/ui/tests/editor/EditorArea.test.ts new file mode 100644 index 0000000..0e6d3a0 --- /dev/null +++ b/ui/tests/editor/EditorArea.test.ts @@ -0,0 +1,430 @@ +/** + * Tests for the editor area and the editor store: opening tabs (from the + * tree and from engine events), editing through CodeMirror into + * `buffer.edit`, the dirty marker, closing (middle click, shortcut, the + * Save / Don't Save / Cancel question), saving through shortcuts loaded + * from the engine's command list, and the notice for files changed on disk. + * The engine is a fake behind the mocked Tauri `invoke`. + */ +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()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import EditorArea from "../../src/components/editor/EditorArea.vue"; +import { emitEditorEvent } from "../../src/components/editor/engineEvents"; +import { emitEngineEvent } from "../../src/components/project/engineEvents"; +import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue"; +import { useEditorStore } from "../../src/stores/editor"; + +/** A buffer of the fake engine. */ +interface FakeBuffer { + path: string; + text: string; + version: number; + saved: number; +} + +/** Fake engine state. */ +let buffers: Map; +/** Files on the fake disk. */ +let disk: Record; +/** Next buffer id. */ +let nextId: number; +/** Every `engine_execute` call, in order. */ +let calls: { command: string; params: Record }[]; + +/** + * 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: "lf" } + : null; +} + +/** + * Rejects like the shell does with an engine error. + * + * @param code - error code. + */ +function fail(code: string): Promise { + return Promise.reject(Object.assign(new Error(code), { code, message: code })); +} + +/** + * The fake engine's command handler. + * + * @param command - command id. + * @param p - params. + */ +function execute(command: string, p: Record): Promise { + const id = typeof p.id === "number" ? p.id : -1; + const b = buffers.get(id); + switch (command) { + 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("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; + } + const wasDirty = b.version !== b.saved; + b.text = out + b.text.slice(pos); + b.version += 1; + emitEditorEvent({ kind: "bufferChanged", id, version: b.version }); + if (!wasDirty) { + emitEditorEvent({ kind: "dirtyChanged", id, dirty: true }); + } + return Promise.resolve({ id, version: b.version, dirty: true }); + } + case "file.save": + if (!b) { + return fail("failed"); + } + disk[b.path] = b.text; + b.saved = b.version; + emitEditorEvent({ kind: "dirtyChanged", id, dirty: false }); + return Promise.resolve({ id, version: b.version }); + case "file.saveAll": { + const saved: number[] = []; + for (const [bid, buffer] of buffers) { + if (buffer.version !== buffer.saved) { + disk[buffer.path] = buffer.text; + buffer.saved = buffer.version; + saved.push(bid); + } + } + return Promise.resolve({ saved, failed: [] }); + } + case "buffer.close": + if (!b) { + return fail("failed"); + } + if (b.version !== b.saved && p.force !== true) { + return fail("unsaved_changes"); + } + buffers.delete(id); + emitEditorEvent({ kind: "bufferClosed", id }); + return Promise.resolve(null); + case "project.children": + return Promise.resolve({ + dir: "", + entries: Object.keys(disk).map((path) => ({ + name: path, + path, + kind: "file", + ignored: false, + role: "normal", + })), + truncated: false, + }); + default: + return Promise.resolve(null); + } +} + +/** Pinia of the current test, installed in every mounted component. */ +let pinia: Pinia; + +/** Mounted components to unmount after each test. */ +let mounted: VueWrapper[] = []; + +/** Mounts the editor area. */ +async function mountArea(): Promise { + const wrapper = mount(EditorArea, { + attachTo: document.body, + slots: { default: "empty" }, + global: { plugins: [pinia] }, + }); + mounted.push(wrapper); + await flushPromises(); + return wrapper; +} + +/** The CodeMirror view inside a wrapper. */ +function viewOf(wrapper: VueWrapper): EditorView { + const el = wrapper.find(".cm-editor").element; + const view = EditorView.findFromDOM(el as HTMLElement); + if (!view) { + throw new Error("no editor view"); + } + return view; +} + +/** + * Presses a key on the window. + * + * @param init - key event properties. + */ +async function press(init: KeyboardEventInit): Promise { + window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init })); + await flushPromises(); +} + +/** Commands sent to the engine, without project and listing calls. */ +function commands(): string[] { + return calls.map((c) => c.command).filter((c) => !c.startsWith("project.")); +} + +/** + * jsdom has no layout; CodeMirror measures text ranges, so give ranges + * empty rectangles. + */ +function stubRangeGeometry(): void { + const empty = (): DOMRectList => { + const list: DOMRect[] = []; + return Object.assign(list, { item: () => null }); + }; + Range.prototype.getClientRects = empty; + Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0); +} + +beforeEach(() => { + stubRangeGeometry(); + pinia = createPinia(); + setActivePinia(pinia); + buffers = new Map(); + disk = { "a.php": " }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([ + { id: "file.save", label: "Save", menuPath: null, defaultShortcut: "Mod+S", params: "", enabled: true }, + { id: "file.saveAll", label: "Save All", menuPath: null, defaultShortcut: "Mod+Alt+S", params: "", enabled: true }, + { id: "buffer.close", label: "Close", menuPath: null, defaultShortcut: "Mod+W", params: "", enabled: true }, + ]); + } + if (cmd === "engine_execute" && args) { + calls.push({ command: args.command, params: args.params }); + return execute(args.command, args.params); + } + return Promise.reject(new Error(`unexpected ${cmd}`)); + }); +}); + +afterEach(async () => { + await flushPromises(); + for (const wrapper of mounted) { + wrapper.unmount(); + } + mounted = []; +}); + +describe("EditorArea", () => { + it("shows the slot without tabs and opens a file from the project tree", async () => { + const area = await mountArea(); + expect(area.text()).toContain("empty"); + const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(tree); + emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); + await flushPromises(); + await tree.find("[data-path='a.php']").trigger("dblclick"); + await flushPromises(); + const tabs = area.findAll("[data-test=editor-tab]"); + expect(tabs.map((t) => t.text())).toEqual(["a.php"]); + expect(viewOf(area).state.doc.toString()).toBe(" { + const area = await mountArea(); + const editor = useEditorStore(pinia); + await editor.openFile("a.php"); + await flushPromises(); + const view = viewOf(area); + view.dispatch({ changes: { from: 5, insert: " // hi" } }); + view.dispatch({ changes: { from: 0, insert: "#" } }); + await flushPromises(); + expect(buffers.get(1)?.text).toBe("# { + const area = await mountArea(); + await useEditorStore(pinia).openFile("b.txt"); + await flushPromises(); + const b = buffers.get(1); + if (!b) { + throw new Error("no buffer"); + } + b.text = "honey bee\n"; + b.version = 2; + emitEditorEvent({ kind: "bufferChanged", id: 1, version: 2 }); + await flushPromises(); + expect(viewOf(area).state.doc.toString()).toBe("honey bee\n"); + }); + + it("switches tabs and closes a clean tab with a middle click", async () => { + const area = await mountArea(); + const editor = useEditorStore(pinia); + await editor.openFile("a.php"); + await editor.openFile("b.txt"); + await flushPromises(); + expect(editor.activeId).toBe(2); + await area.findAll("[data-test=editor-tab]")[0]?.trigger("click"); + expect(viewOf(area).state.doc.toString()).toContain(" t.text())).toEqual(["a.php"]); + expect(commands()).toContain("buffer.close"); + }); + + it("asks before closing a dirty tab: cancel, don't save, save", async () => { + const area = await mountArea(); + const editor = useEditorStore(pinia); + await editor.openFile("a.php"); + await flushPromises(); + viewOf(area).dispatch({ changes: { from: 0, insert: "x" } }); + await flushPromises(); + + await press({ key: "w", code: "KeyW", ctrlKey: true }); + expect(area.find("[data-test=close-prompt]").exists()).toBe(true); + await area.find("[data-test=close-cancel]").trigger("click"); + await flushPromises(); + expect(area.find("[data-test=close-prompt]").exists()).toBe(false); + expect(editor.tabs).toHaveLength(1); + + await area.find("[data-test=tab-close]").trigger("click"); + await flushPromises(); + await area.find("[data-test=close-save]").trigger("click"); + await flushPromises(); + expect(disk["a.php"]).toBe("x { + const area = await mountArea(); + const editor = useEditorStore(pinia); + await editor.openFile("a.php"); + await editor.openFile("b.txt"); + await flushPromises(); + viewOf(area).dispatch({ changes: { from: 0, insert: "B" } }); + await press({ key: "s", code: "KeyS", ctrlKey: true }); + expect(disk["b.txt"]).toBe("Bbee\n"); + expect(calls.at(-1)).toEqual({ command: "file.save", params: { id: 2 } }); + expect(area.find("[data-test=tab-dirty]").exists()).toBe(false); + + await area.findAll("[data-test=editor-tab]")[0]?.trigger("click"); + viewOf(area).dispatch({ changes: { from: 0, insert: "A" } }); + await press({ key: "ß", code: "KeyS", ctrlKey: true, altKey: true }); + expect(disk["a.php"]).toBe("A { + const area = await mountArea(); + await execute("file.open", { path: "b.txt" }); + emitEditorEvent({ kind: "bufferOpened", id: 1, path: "b.txt" }); + await flushPromises(); + expect(area.findAll("[data-test=editor-tab]").map((t) => t.text())).toEqual(["b.txt"]); + emitEditorEvent({ kind: "bufferClosed", id: 1 }); + await flushPromises(); + expect(area.findAll("[data-test=editor-tab]")).toHaveLength(0); + }); + + it("activates the last opened buffer even when its fetch finishes first", async () => { + const area = await mountArea(); + await execute("file.open", { path: "a.php" }); + await execute("file.open", { path: "b.txt" }); + let releaseFirst: () => void = () => undefined; + const fallback = invoke.getMockImplementation(); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (args?.command === "buffer.get" && args.params.id === 1) { + return new Promise((resolve) => { + releaseFirst = () => { + resolve(describeBuffer(1)); + }; + }); + } + return fallback?.(cmd, args) as Promise; + }); + emitEditorEvent({ kind: "bufferOpened", id: 1, path: "a.php" }); + emitEditorEvent({ kind: "bufferOpened", id: 2, path: "b.txt" }); + await flushPromises(); + releaseFirst(); + await flushPromises(); + const editor = useEditorStore(pinia); + expect(editor.tabs.map((t) => t.path).sort()).toEqual(["a.php", "b.txt"]); + expect(editor.activeId).toBe(2); + expect(area.find("[aria-selected=true]").text()).toBe("b.txt"); + }); + + it("shows a notice when a dirty file changes on disk, and an open error", async () => { + const area = await mountArea(); + const editor = useEditorStore(pinia); + await editor.openFile("a.php"); + await flushPromises(); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false }); + await flushPromises(); + expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk"); + await area.find("[data-test=notice-dismiss]").trigger("click"); + expect(area.find("[data-test=editor-notice]").exists()).toBe(false); + + await editor.openFile("missing.php"); + await flushPromises(); + expect(area.find("[data-test=editor-error]").text()).toContain("not_found"); + }); + + it("opens a 1 MB file and records the time", async () => { + const line = " number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** A fake engine buffer with the engine's edit protocol. */ +class FakeEngine implements SyncTransport { + text: string; + version = 1; + readonly lineEnding: string; + /** Answers waiting to be delivered. */ + private queue: (() => void)[] = []; + /** Versions to report through `bufferChanged`. */ + events: number[] = []; + editCalls = 0; + staleRejections = 0; + + constructor(text: string, lineEnding = "lf", private random: () => number = Math.random) { + this.text = text; + this.lineEnding = lineEnding; + } + + info(): BufferInfo { + return { + id: 1, + path: "a.txt", + text: this.text, + version: this.version, + dirty: this.version !== 1, + lineEnding: this.lineEnding, + }; + } + + edit(params: EditParams): Promise> { + this.editCalls += 1; + return this.later(() => { + if (params.baseVersion !== this.version) { + this.staleRejections += 1; + return { ok: false, error: { code: "stale_version", message: "stale" } }; + } + let out = ""; + let pos = 0; + for (const e of params.edits) { + expect(e.from).toBeGreaterThanOrEqual(pos); + expect(e.to).toBeLessThanOrEqual(this.text.length); + out += this.text.slice(pos, e.from) + e.insert; + pos = e.to; + } + this.text = out + this.text.slice(pos); + this.version += 1; + this.events.push(this.version); + return { ok: true, value: { id: 1, version: this.version, dirty: true } }; + }); + } + + get(): Promise> { + return this.later(() => ({ ok: true, value: this.info() })); + } + + /** + * An edit made outside the editor: inserts `text` at a line start. + * + * @param text - inserted text. + * @param line - 0-based line; random when omitted. + */ + external(text: string, line?: number): void { + const starts = [0]; + for (let i = 0; i < this.text.length; i += 1) { + if (this.text[i] === "\n") { + starts.push(i + 1); + } + } + const at = starts[line ?? Math.floor(this.random() * starts.length)] ?? 0; + this.text = this.text.slice(0, at) + text + this.text.slice(at); + this.version += 1; + this.events.push(this.version); + } + + /** Queues an answer; {@link step} delivers queued answers in random order. */ + private later(answer: () => T): Promise { + return new Promise((resolve) => { + this.queue.push(() => { + resolve(answer()); + }); + }); + } + + /** Delivers one queued answer, if any. */ + step(): boolean { + if (this.queue.length === 0) { + return false; + } + const index = Math.floor(this.random() * this.queue.length); + const [answer] = this.queue.splice(index, 1); + answer?.(); + return true; + } +} + +/** Lets promise callbacks run. */ +async function tick(): Promise { + for (let i = 0; i < 5; i += 1) { + await Promise.resolve(); + } +} + +/** + * Delivers every pending answer and event until the sync is idle. + * + * @param engine - the fake engine. + * @param sync - the sync under test. + */ +async function drain(engine: FakeEngine, sync: BufferSync): Promise { + for (let i = 0; i < 10_000; i += 1) { + const events = engine.events.splice(0); + for (const v of events) { + sync.notifyVersion(v); + } + const stepped = engine.step(); + await tick(); + if (!stepped && events.length === 0 && !sync.pending) { + return; + } + } + throw new Error("sync did not settle"); +} + +/** + * The engine text with CodeMirror's line breaks, for comparison. + * + * @param text - engine text. + */ +function normalised(text: string): string { + return text.replace(/\r\n?/g, "\n"); +} + +describe("BufferSync", () => { + it("sends local edits with the base version and tracks versions", async () => { + const engine = new FakeEngine("hello\n"); + const sync = new BufferSync(engine.info(), [], engine); + sync.dispatch({ changes: { from: 5, insert: " world" } }); + expect(sync.pending).toBe(true); + await drain(engine, sync); + expect(engine.text).toBe("hello world\n"); + expect(sync.baseVersion).toBe(2); + expect(sync.pending).toBe(false); + }); + + it("applies a change made in the engine", async () => { + const engine = new FakeEngine("one\ntwo\n"); + const sync = new BufferSync(engine.info(), [], engine); + engine.external("zero\n", 0); + await drain(engine, sync); + expect(sync.state.doc.toString()).toBe("zero\none\ntwo\n"); + expect(sync.baseVersion).toBe(engine.version); + }); + + it("keeps the local cursor when a remote change lands before it", async () => { + const engine = new FakeEngine("abc\n"); + const sync = new BufferSync(engine.info(), [], engine); + sync.dispatch({ selection: { anchor: 2 } }); + engine.external("x\n", 0); + await drain(engine, sync); + expect(sync.state.selection.main.head).toBe(4); + }); + + it("loses no keystroke in a burst with stale versions and remote edits", async () => { + const random = rng(42); + const engine = new FakeEngine(" { + const random = rng(7); + const engine = new FakeEngine("a\r\nbb\r\nccc\r\n", "crlf", random); + const sync = new BufferSync(engine.info(), [], engine); + for (let i = 0; i < 300; i += 1) { + const len = sync.state.doc.length; + const from = Math.floor(random() * (len + 1)); + const to = Math.min(len, from + Math.floor(random() * 3)); + const insert = random() < 0.3 ? "\n" : random() < 0.5 ? "é😀" : ""; + sync.dispatch({ changes: { from, to, insert } }); + if (random() < 0.1) { + engine.external(`r${String(i)}\r\n`); + } + if (random() < 0.6) { + engine.step(); + } + if (random() < 0.3) { + for (const v of engine.events.splice(0)) { + sync.notifyVersion(v); + } + } + await tick(); + } + await drain(engine, sync); + expect(sync.state.doc.toString()).toBe(normalised(engine.text)); + expect(engine.text.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/); + }); + + it("drops local changes and reports when the engine refuses them", async () => { + const engine = new FakeEngine("keep\n"); + const errors: string[] = []; + const refusing: SyncTransport = { + edit: () => + Promise.resolve({ ok: false, error: { code: "invalid_params", message: "bad" } }), + get: () => engine.get(), + }; + const sync = new BufferSync(engine.info(), [], refusing, (e) => errors.push(e.code)); + sync.dispatch({ changes: { from: 0, insert: "lost " } }); + await drain(engine, sync); + expect(errors).toEqual(["invalid_params"]); + expect(sync.state.doc.toString()).toBe("keep\n"); + }); + + it("idle resolves after the engine confirmed every change", async () => { + const engine = new FakeEngine(""); + const sync = new BufferSync(engine.info(), [], engine); + sync.dispatch({ changes: { from: 0, insert: "x" } }); + let done = false; + void sync.idle().then(() => { + done = true; + }); + await tick(); + expect(done).toBe(false); + await drain(engine, sync); + await tick(); + expect(done).toBe(true); + }); +}); diff --git a/ui/tests/editor/engineText.test.ts b/ui/tests/editor/engineText.test.ts new file mode 100644 index 0000000..103e8fe --- /dev/null +++ b/ui/tests/editor/engineText.test.ts @@ -0,0 +1,58 @@ +/** + * Tests for the mapping between engine text (line breaks as on disk) and + * CodeMirror documents (one position per line break). + */ +import { ChangeSet, Text } from "@codemirror/state"; +import { describe, expect, it } from "vitest"; +import { diffDocs, EngineText, separatorOf } from "../../src/components/editor/engineText"; + +describe("EngineText", () => { + it("maps positions past CRLF breaks and keeps mixed endings", () => { + const text = EngineText.fromEngine("a\r\nb\nc\rd\r\n"); + expect(text.doc.toString()).toBe("a\nb\nc\nd\n"); + expect(text.toEngine(0)).toBe(0); + expect(text.toEngine(2)).toBe(3); + expect(text.toEngine(4)).toBe(5); + expect(text.toEngine(8)).toBe(10); + expect(text.toEngine(99)).toBe(10); + expect(text.engineString()).toBe("a\r\nb\nc\nd\r\n"); + }); + + it("is the identity for text without CRLF", () => { + const text = EngineText.fromEngine("x😀\ny"); + expect(text.toEngine(4)).toBe(4); + }); + + it("turns changes into engine edits with the buffer's line ending", () => { + const text = EngineText.fromEngine("ab\r\ncd\r\n"); + const changes = ChangeSet.of( + [ + { from: 1, insert: "\n" }, + { from: 3, to: 5, insert: "X" }, + ], + text.doc.length, + ); + expect(text.edits(changes, "\r\n")).toEqual([ + { from: 1, to: 1, insert: "\r\n" }, + { from: 4, to: 6, insert: "X" }, + ]); + const after = text.apply(changes, "\r\n"); + expect(after.doc.toString()).toBe("a\nb\nX\n"); + expect(after.engineString()).toBe("a\r\nb\r\nX\r\n"); + }); + + it("diffs documents into one replacement", () => { + const a = Text.of(["hello", "world"]); + const b = Text.of(["hello", "brave", "world"]); + const diff = diffDocs(a, b); + expect(diff.apply(a).toString()).toBe(b.toString()); + expect(diffDocs(a, a).empty).toBe(true); + }); + + it("names separators", () => { + expect(separatorOf("crlf")).toBe("\r\n"); + expect(separatorOf("cr")).toBe("\r"); + expect(separatorOf("lf")).toBe("\n"); + expect(separatorOf("?")).toBe("\n"); + }); +});