diff --git a/docs/architecture.md b/docs/architecture.md index 0469b99..94f8965 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -140,6 +140,16 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Since M3.10 changes are also saved automatically (see Autosave). - Theme: the editor reads colours only from `--lt-*` tokens, including the editor tokens from M1.10 (selection, active line, cursor, gutter, match, editor font size); no fallbacks remain. +### Tab management (C10 A1) + +- **Model:** `ui/src/components/editor/tabs/model.ts`, pure functions on a `TabLayout` (one or two groups, each with its tab placements `{id, pinned, preview}` and active buffer; the focused group; the orientation `right|down`). Rules: one preview per group, replaced in place by the next preview (the replaced buffer is closed unless the other group shows it); pinned tabs first and left out of bulk closes; an emptied group goes away while another is left; at most two groups. +- **Store:** `ui/src/stores/editor.ts` keeps one record and one `BufferSync` per buffer and the layout; `tabs` lists every open buffer once, `activeId` is the focused group's active buffer, `groups` feeds the panes. A buffer in both groups has one sync, which now updates every attached view (`BufferSync.attach/detach(view)`), so both groups share text, selection and undo history. Closing a tab the other group still shows only removes the tab; bulk closes ask once (`closePrompt.items`) with Save All / Don't Save / Cancel. "Reopen Closed Tab" keeps the last 30 non-preview closes per window with group, index, pin, selection and the position at the top of the view. +- **Public API for other areas:** `tabOfPath(path)`, `tabOf(id)`, `reloadBuffer(id)` (the sync takes the engine's text over and drops unsent edits, after the engine reloaded a file), `openFile(path, {preview?, group?, activate?, pinned?, index?})`. Banners about a group's active tab go into `EditorPane.vue`. +- **Opening:** the project tree's single click, Find results and Go-to choices open previews (`editor.reveal` takes `preview: true`); double click, Enter and every other caller open permanent tabs. Setting `editor.tabs.preview` (bool, default true) turns previews off. +- **Commands:** UI commands `tabs.closeOthers|closeAll|closeLeft|closeRight|closeUnmodified|reopenClosed|togglePin|keepOpen|splitRight|splitDown|moveToOtherGroup|focusOtherGroup|unsplit` (`tabs/commands.ts`, `COMMAND_IDS`, spread into `UI_COMMANDS`), params `{id?, group?}`, menu group Window; no default shortcuts. The tab context menu (`tabs/TabContextMenu.vue`) runs them. +- **Persistence:** `layout.get` → `{layout: object|null}` and `layout.set {layout}` (engine, `cmd/layout.rs`) keep the layout of the open project in `/layout/.json` (project id as in the recovery journal; written with `write_atomic`; 256 KiB cap both ways; a missing or broken file reads as null). The store writes 300 ms after a change, restores on `projectOpened` (files that are gone are skipped) and never writes while a project closes. Never in webview storage (ESLint rule). +- **Not yet:** drag to reorder or between groups, diff tabs outside the first group, separate selections per group for the same file. + ### Highlighting and editor.reveal (M2.2) - **Languages:** `ui/src/components/editor/language.ts` picks a language once per tab from the file extension (`languageOf`): PHP (`php`, `phtml`, `inc`, `php3`–`php8`, `phps`) through `@codemirror/lang-php`, whose Lezer grammar also parses the HTML, CSS and JavaScript around `` blocks; HTML, CSS, JavaScript/TypeScript (with JSX), JSON, YAML and Markdown through their `@codemirror/lang-*` packages (all MIT). Other files stay plain text. The editor store passes the tab's path to `editorExtensions(path)` when it creates the tab's state. @@ -170,7 +180,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - `/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap. - A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten. -- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10), the assist keys `editor.completion.autoPopup` (bool, default true), `editor.completion.delayMs` (int 0–2000, default 0) and `editor.hover.delayMs` (int 100–3000, default 350; H4). Defined in `lutra_engine::settings::DEFS`. +- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10), the assist keys `editor.completion.autoPopup` (bool, default true), `editor.completion.delayMs` (int 0–2000, default 0) and `editor.hover.delayMs` (int 100–3000, default 350; H4), `editor.tabs.preview` (bool, default true; C10 A1). Defined in `lutra_engine::settings::DEFS`. - Commands: `settings.list` → `[{key, type: enum|int|bool|string, default, enumValues?, min?, max?, path?, labelKey, descriptionKey, section}]` (`path: true` marks a file path setting, `Kind::Path`) (catalog keys `settings..label` / `.description`; `section` is an id shown with `settings.section.`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing. - Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…). @@ -789,6 +799,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | C10 A1: tab management, editor groups, `layout.get/set` | | 2026-11-06 | minor | C9 D2: remote browser, compare and sync; save before upload | | 2026-11-06 | minor | C9 D1: `crates/deploy` (L3), `deploy.*` commands, deployment events and UI | | 2026-11-02 | minor | C9 F1: `Kind::Path` and `check_path` (one validator for `settings.set` and the dialog, `path` in `settings.list`), `lutra_proc::spawn_detached` for the CLI's desktop start | diff --git a/docs/gaps.md b/docs/gaps.md index 136563b..0e8c9c8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -7,7 +7,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | # | 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 with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~14 h | +| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), ~~tab management (preview, pin, split, close others, reopen)~~ (C10 A1), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~10 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~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b; C9 T1: six built-in themes, picker with live preview, theme file import, editor font family and line height), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar: A1 adds the system menus (Lutra, Edit, Window; ⌘W and ⌘Q stay Lutra's), mirroring Lutra's own menus natively and display modes open) | M1 | ~24 h | | G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | @@ -28,7 +28,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h | | G21 | Feature breadth: the full PhpStorm help inventory has 155 feature units; ~23 have at least partial support (2026-10-18, estimated). The list lives in `plan/phpstorm/00-feature-inventory.md` with public URLs | ongoing | — | -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. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. Still open: tab management beyond open/close, a conflict UI (compare and merge with the disk version), local history, editor settings (soft wrap); estimate lowered to ~14 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. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. C10 A1 added tab management: preview tabs (and their setting), pinning, close others/all/left/right/unmodified with one question for every unsaved file, reopen closed tab with selection and scroll, a second editor group (split right/down, move, focus, unsplit) sharing one engine buffer and undo history, a tab context menu, `tabs.*` commands and the tab layout per project in Lutra's own state file. Left from tab management: drag to reorder or between groups, more than two groups, a tab limit, a recent-files switcher. Still open: a conflict UI (compare and merge with the disk version), local history, editor settings (soft wrap); estimate lowered to ~10 h. G4 progress: M2.1 added the structural half in `crates/syntax`: tree-sitter PHP parse and incremental reparse, outline (namespaces, class-likes, functions, members, promoted properties, enum cases; anonymous classes marked) and folding ranges, an 8 MiB parse cap, proptests and snapshots. M2.2 made highlighting visible. M2.7 added the Structure tool window: each open PHP buffer keeps a tree-sitter tree, reparsed incrementally on a worker thread off the engine lock (200 ms debounce), `syntax.outline` and `outlineChanged`, and the outline as a tree in the left tool window with jumps through `editor.reveal`. Open in G4: semantic highlighting, folding in the editor, Structure speed search, sorting and filters. Finding: a full parse of 1 MB takes 364–553 ms on the dev machine (target 50 ms; reparse 7–11 ms), so parsing must stay off the engine lock and the index must parse in parallel. @@ -55,6 +55,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | G2 shrunk: tab management (C10 A1) | | 2026-11-06 | patch | G17: deployment v2 (C9 D2): remote browser, compare, sync | | 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 | | 2026-11-06 | minor | G3: more themes, theme import, editor font settings (C9 T1) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8c41a87..2f97c63 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -11,7 +11,8 @@ - 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. M1.13 (2026-10-16): a partly listed folder ends with a "Listing truncated" note; opening a file that is already open (tree, control channel) switches to its tab (Vitest; live check pending (gaming mode)). 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`. + - 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 (then): 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`. + - C10 A1 (2026-11-08): **preview tabs**: a single click in the project tree, a Find result or a Go-to choice opens a preview tab (italic title) that the next preview in its group replaces; editing it, opening it for good (double click in the tree), a double click on the tab or "Keep Tab Open" makes it permanent; setting `editor.tabs.preview` turns previews off. **Pinning** (Lucide `pin` icon): pinned tabs sit left and survive every bulk close. **Close actions**: close, close other tabs, close all, close to the left / right, close unmodified; the unsaved files of one action are asked about once with a list (Save All / Don't Save / Cancel). **Reopen Closed Tab**: a stack of the last 30 closed tabs per window, reopened at their place with selection and scroll position. **Split**: Split Right / Split Down add a second editor group (at most two) showing the active tab; Move Tab to Other Group, Focus Other Group, Unsplit; the same file in both groups is one engine buffer with one text, selection and undo history; the focused group is marked. A **tab context menu** (right click) runs all of these. Commands `tabs.*` in the registry (palette, a new Window menu group, agents); no default shortcuts. The layout of each project (groups, tabs, pins, previews, active tabs) is stored in Lutra's own state file (`layout.get` / `layout.set`, `/layout/`) and restored when the project opens. Vitest (model and area tests); live check over `--control` on Windows 11. Missing: reorder by drag, dragging tabs between groups, more than two groups, a tab limit, a recent-files switcher, duplicate-name disambiguation, diff tabs in the second group, per-group scroll for the same file (both groups share one selection). - [ ] Editor syntax highlighting (Lutra's own colours, no copied scheme) - M2.2 (2026-10-16): the language is picked from the file extension when a tab opens: PHP (with the HTML, CSS and JavaScript around ` { return info !== undefined && info.ui !== true && info.enabled; } + /** + * Whether a command exists: the engine lists it, it is a UI command, or a + * component supplies a handler. Menus hide items of commands another + * area adds later. + * + * @param id - the command id. + */ + function isKnown(id: string): boolean { + return handlers.has(id) || all.value.some((c) => c.id === id); + } + /** * The commands the palette offers: UI commands and engine commands that * are user actions (they have a menu path or a default shortcut), not @@ -330,5 +341,5 @@ export const useCommandsStore = defineStore("commands", () => { unsubscribe = null; } - return { infos, recent, keymap, entries, isEnabled, provide, execute, dispatch, refresh, start, stop }; + return { infos, recent, keymap, entries, isEnabled, isKnown, provide, execute, dispatch, refresh, start, stop }; }); diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index 758c172..2ec51f7 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -7,6 +7,8 @@ * is disabled. */ +import { TAB_UI_COMMANDS } from "../components/editor/tabs/commands"; + /** A UI command as registered with the engine. */ export interface UiCommandSpec { /** Command id, `area.action` in camelCase. */ @@ -71,4 +73,5 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [ { id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" }, { id: "view.selectTheme", labelKey: "command.view.selectTheme", menuPath: "View/Select Theme…" }, { id: "view.importTheme", labelKey: "command.view.importTheme", menuPath: "View/Import Theme…" }, + ...TAB_UI_COMMANDS, ]; diff --git a/ui/src/components/editor/ClosePrompt.vue b/ui/src/components/editor/ClosePrompt.vue index be403dd..0ef75ba 100644 --- a/ui/src/components/editor/ClosePrompt.vue +++ b/ui/src/components/editor/ClosePrompt.vue @@ -1,7 +1,8 @@ + + + + diff --git a/ui/src/components/editor/EditorTabs.vue b/ui/src/components/editor/EditorTabs.vue index 89b26a6..9dfb6c0 100644 --- a/ui/src/components/editor/EditorTabs.vue +++ b/ui/src/components/editor/EditorTabs.vue @@ -1,32 +1,54 @@ @@ -102,24 +138,36 @@ function onKeydown(event: KeyboardEvent): void { class="tabs" role="tablist" :aria-label="t('editor.tabs.label')" + :data-group="group" data-test="editor-tabs" @keydown="onKeydown" > - + {{ diffTitle(tab) }} + + + + @@ -196,6 +255,15 @@ function onKeydown(event: KeyboardEvent): void { white-space: nowrap; } +.tabs__tab--preview .tabs__name { + font-style: italic; +} + +.tabs__pin { + flex-shrink: 0; + color: var(--lt-fg-muted); +} + .tabs__tab:hover { color: var(--lt-fg); } diff --git a/ui/src/components/editor/bufferSync.ts b/ui/src/components/editor/bufferSync.ts index e594a77..b933998 100644 --- a/ui/src/components/editor/bufferSync.ts +++ b/ui/src/components/editor/bufferSync.ts @@ -111,8 +111,12 @@ export class BufferSync { 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; + /** + * The views showing this buffer: none while another tab is active, two + * when both editor groups show it (they share this one state, so text, + * selection and undo history are the same in both). + */ + private readonly views = new Set(); /** Engine text at {@link version}. */ private confirmed: EngineText; /** Engine version of {@link confirmed}. */ @@ -181,24 +185,40 @@ export class BufferSync { /** * Shows this buffer in a view: the view takes over the local state and - * receives remote changes from now on. + * receives every change from now on. * * @param view - the editor view. */ attach(view: EditorView): void { - this.view = view; + this.views.add(view); view.setState(this.current); } - /** Stops updating the view (another tab became active). */ - detach(): void { - this.view = null; + /** + * Stops updating a view (another tab became active there). + * + * @param view - the view; every view when omitted. + */ + detach(view?: EditorView): void { + if (view) { + this.views.delete(view); + } else { + this.views.clear(); + } + } + + /** + * Takes the engine's text over and drops local changes not sent yet, for + * a buffer the engine just reloaded from disk (C10 A2's "Reload"). + */ + reload(): void { + this.resync(true); } /** Stops syncing; the buffer was closed. */ dispose(): void { this.disposed = true; - this.view = null; + this.views.clear(); this.inflight = null; this.unsent = null; this.settle(); @@ -230,7 +250,9 @@ export class BufferSync { this.unsent = this.unsent ? this.unsent.compose(tr.changes) : tr.changes; } } - this.view?.update([...transactions]); + for (const view of this.views) { + view.update([...transactions]); + } this.flush(); } diff --git a/ui/src/components/editor/reveal.ts b/ui/src/components/editor/reveal.ts index b6ef182..bf725f2 100644 --- a/ui/src/components/editor/reveal.ts +++ b/ui/src/components/editor/reveal.ts @@ -8,7 +8,8 @@ * {@link positionOf} (CRLF-safe). Out-of-range values are clamped. Without * a `path` it centres the cursor of the active tab, which is what running * it from the palette does. The Find, Go-to and Structure windows and - * agents (`uiCommand`) call it. + * agents (`uiCommand`) call it. With `preview: true` (the Find and Go-to + * windows) a file not open yet opens in a preview tab (C10 A1). */ import { EditorView } from "@codemirror/view"; import { nextTick } from "vue"; @@ -27,6 +28,8 @@ export interface RevealTarget { line: number | null; /** 0-based column in UTF-16 code units. */ column: number; + /** Open a file that has no tab yet as a preview tab. */ + preview: boolean; } /** The editor store as reveal uses it. */ @@ -45,10 +48,11 @@ export function parseReveal(params: unknown): RevealTarget | null { const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined; const line = number(p.line); const column = number(p.column); - if (path === undefined || line === undefined || column === undefined) { + const preview = p.preview === undefined || p.preview === null ? false : typeof p.preview === "boolean" ? p.preview : undefined; + if (path === undefined || line === undefined || column === undefined || preview === undefined) { return null; } - return { path, line, column: column ?? 0 }; + return { path, line, column: column ?? 0, preview }; } /** @@ -67,11 +71,10 @@ export async function reveal(editor: EditorStore, params: unknown): Promise tab.path === path)?.id ?? (await editor.openFile(path)); + id = await editor.openFile(path, { preview: target.preview }); if (id === null) { throw new Error(editor.lastError?.message ?? t("editor.reveal.openFailed", { path })); } - editor.activate(id); await nextTick(); } const sync = id === null ? undefined : editor.syncOf(id); diff --git a/ui/src/components/editor/tabs/TabContextMenu.vue b/ui/src/components/editor/tabs/TabContextMenu.vue new file mode 100644 index 0000000..3287558 --- /dev/null +++ b/ui/src/components/editor/tabs/TabContextMenu.vue @@ -0,0 +1,265 @@ + + + + + diff --git a/ui/src/components/editor/tabs/commands.ts b/ui/src/components/editor/tabs/commands.ts new file mode 100644 index 0000000..6daebac --- /dev/null +++ b/ui/src/components/editor/tabs/commands.ts @@ -0,0 +1,137 @@ +/** + * The tab management UI commands (C10 A1). They are listed in the registry + * through {@link TAB_UI_COMMANDS} (spread into `UI_COMMANDS`), so the + * palette, the Window menu, the keymap editor, agents and the control + * channel reach them. The tab context menu runs the same commands. + * + * Every command takes optional params `{ id?: buffer id, group?: group + * index }`; without them it acts on the active tab of the focused group. + * None has a default shortcut: the obvious keys are taken by Lutra's + * own keymap or by CodeMirror's basicSetup, so users bind them in the + * keymap editor. + */ +import type { CommandHandler, useCommandsStore } from "../../../commands/store"; +import type { UiCommandSpec } from "../../../commands/uiCommands"; +import type { JsonValue } from "../../../ipc"; +import type { useEditorStore } from "../../../stores/editor"; +import type { CloseAction } from "./model"; + +/** Command ids of this module. */ +export const COMMAND_IDS = { + closeOthers: "tabs.closeOthers", + closeAll: "tabs.closeAll", + closeLeft: "tabs.closeLeft", + closeRight: "tabs.closeRight", + closeUnmodified: "tabs.closeUnmodified", + reopenClosed: "tabs.reopenClosed", + togglePin: "tabs.togglePin", + keepOpen: "tabs.keepOpen", + splitRight: "tabs.splitRight", + splitDown: "tabs.splitDown", + moveToOtherGroup: "tabs.moveToOtherGroup", + focusOtherGroup: "tabs.focusOtherGroup", + unsplit: "tabs.unsplit", +} as const; + +/** Menu path prefix of the tab commands. */ +const MENU = "Window/Editor Tabs/"; + +/** The registry entries of the tab commands. */ +export const TAB_UI_COMMANDS: readonly UiCommandSpec[] = [ + { id: COMMAND_IDS.closeOthers, labelKey: "command.tabs.closeOthers", menuPath: `${MENU}Close Other Tabs` }, + { id: COMMAND_IDS.closeAll, labelKey: "command.tabs.closeAll", menuPath: `${MENU}Close All Tabs` }, + { id: COMMAND_IDS.closeLeft, labelKey: "command.tabs.closeLeft", menuPath: `${MENU}Close Tabs to the Left` }, + { id: COMMAND_IDS.closeRight, labelKey: "command.tabs.closeRight", menuPath: `${MENU}Close Tabs to the Right` }, + { id: COMMAND_IDS.closeUnmodified, labelKey: "command.tabs.closeUnmodified", menuPath: `${MENU}Close Unmodified Tabs` }, + { id: COMMAND_IDS.reopenClosed, labelKey: "command.tabs.reopenClosed", menuPath: `${MENU}Reopen Closed Tab` }, + { id: COMMAND_IDS.togglePin, labelKey: "command.tabs.togglePin", menuPath: `${MENU}Pin or Unpin Tab` }, + { id: COMMAND_IDS.keepOpen, labelKey: "command.tabs.keepOpen", menuPath: `${MENU}Keep Tab Open` }, + { id: COMMAND_IDS.splitRight, labelKey: "command.tabs.splitRight", menuPath: "Window/Split Right" }, + { id: COMMAND_IDS.splitDown, labelKey: "command.tabs.splitDown", menuPath: "Window/Split Down" }, + { id: COMMAND_IDS.moveToOtherGroup, labelKey: "command.tabs.moveToOtherGroup", menuPath: "Window/Move Tab to Other Group" }, + { id: COMMAND_IDS.focusOtherGroup, labelKey: "command.tabs.focusOtherGroup", menuPath: "Window/Focus Other Group" }, + { id: COMMAND_IDS.unsplit, labelKey: "command.tabs.unsplit", menuPath: "Window/Unsplit" }, +]; + +/** The tab a command acts on. */ +export interface TabTarget { + /** Buffer id; the group's active tab when undefined. */ + id?: number | undefined; + /** Group index; the focused group when undefined. */ + group?: number | undefined; +} + +/** + * Reads `{ id?, group? }` from untrusted params; fields of the wrong type + * are ignored. + * + * @param params - the command params. + */ +export function parseTarget(params: JsonValue): TabTarget { + const p = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {}; + const int = (value: JsonValue | undefined): number | undefined => + typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined; + return { id: int(p.id), group: int(p.group) }; +} + +/** + * Supplies the behaviour of the tab commands. + * + * @param commands - the command store. + * @param editor - the editor store. + * @returns functions that withdraw the handlers. + */ +export function provideTabCommands(commands: ReturnType, editor: ReturnType): (() => void)[] { + const hasTab = (): boolean => editor.activeId !== null; + const split = (): boolean => editor.groups.length > 1; + const close = (action: CloseAction): CommandHandler => ({ + run: async (params) => { + const target = parseTarget(params); + await editor.closeAction(action, target.id, target.group); + }, + enabled: hasTab, + }); + const handlers: [string, CommandHandler][] = [ + [COMMAND_IDS.closeOthers, close("others")], + [COMMAND_IDS.closeAll, close("all")], + [COMMAND_IDS.closeLeft, close("left")], + [COMMAND_IDS.closeRight, close("right")], + [COMMAND_IDS.closeUnmodified, close("unmodified")], + [COMMAND_IDS.reopenClosed, { run: async () => { await editor.reopenClosed(); }, enabled: () => editor.canReopen }], + [ + COMMAND_IDS.togglePin, + { + run: (params) => { + const target = parseTarget(params); + editor.setPinned(target.id, target.group); + }, + enabled: hasTab, + }, + ], + [ + COMMAND_IDS.keepOpen, + { + run: (params) => { + const target = parseTarget(params); + editor.keepOpen(target.id, target.group); + }, + enabled: hasTab, + }, + ], + [COMMAND_IDS.splitRight, { run: () => { editor.split("right"); }, enabled: hasTab }], + [COMMAND_IDS.splitDown, { run: () => { editor.split("down"); }, enabled: hasTab }], + [ + COMMAND_IDS.moveToOtherGroup, + { + run: (params) => { + const target = parseTarget(params); + editor.moveToOtherGroup(target.id, target.group); + }, + enabled: () => hasTab() && (split() || editor.tabs.length > 1), + }, + ], + [COMMAND_IDS.focusOtherGroup, { run: () => { editor.focusOtherGroup(); }, enabled: split }], + [COMMAND_IDS.unsplit, { run: () => { editor.unsplit(); }, enabled: split }], + ]; + return handlers.map(([id, handler]) => commands.provide(id, handler)); +} diff --git a/ui/src/components/editor/tabs/model.ts b/ui/src/components/editor/tabs/model.ts new file mode 100644 index 0000000..c995725 --- /dev/null +++ b/ui/src/components/editor/tabs/model.ts @@ -0,0 +1,587 @@ +/** + * The tab layout of the editor area as pure functions (C10 A1): one or two + * editor groups, each with its own row of tabs and active tab. + * + * A tab places an engine buffer in a group. The same buffer may sit in both + * groups; it is still one engine buffer with one undo history (the editor + * store keeps one {@link BufferSync} per buffer). Every function here + * returns a new layout and leaves its input alone, so the store can replace + * its state in one step and tests can check each rule on plain data. + * + * Rules: + * - **Preview:** a group holds at most one preview tab. Opening another + * preview replaces it in place; editing it, opening the same file for + * good or "Keep open" makes it permanent. + * - **Pinned** tabs sit left of the unpinned ones; bulk closes leave them. + * - **Groups:** at most {@link MAX_GROUPS}. A group whose last tab closes + * goes away while another group is left. + */ + +/** Most editor groups (v1: one split). */ +export const MAX_GROUPS = 2; + +/** How two groups sit next to each other. */ +export type SplitOrientation = "right" | "down"; + +/** One tab: a buffer placed in a group. */ +export interface TabPlacement { + /** Engine buffer id. */ + id: number; + /** Pinned tabs sit left and survive bulk closes. */ + pinned: boolean; + /** A preview tab is replaced by the next preview in its group. */ + preview: boolean; +} + +/** One editor group. */ +export interface TabGroup { + /** Tabs in display order, pinned ones first. */ + tabs: TabPlacement[]; + /** Buffer id of the group's active tab, null when the group is empty. */ + activeId: number | null; +} + +/** The whole layout of the editor area. */ +export interface TabLayout { + /** One or two groups; never empty. */ + groups: TabGroup[]; + /** Index of the group that has the focus. */ + focused: number; + /** Where the second group sits. */ + orientation: SplitOrientation; +} + +/** How a tab is placed by {@link placeTab}. */ +export interface PlaceOptions { + /** Open as a preview tab. */ + preview: boolean; + /** Make it the group's active tab and focus the group. */ + activate: boolean; + /** Pin it. */ + pinned?: boolean | undefined; + /** Index to insert at (clamped to the pinned or unpinned block). */ + index?: number | undefined; +} + +/** Result of {@link placeTab}. */ +export interface PlaceResult { + /** The new layout. */ + layout: TabLayout; + /** Buffer id of the preview tab that was replaced, null if none. */ + replaced: number | null; +} + +/** Bulk close actions of a tab's context menu. */ +export type CloseAction = "others" | "all" | "left" | "right" | "unmodified"; + +/** An empty layout: one group without tabs. */ +export function emptyLayout(): TabLayout { + return { groups: [{ tabs: [], activeId: null }], focused: 0, orientation: "right" }; +} + +/** + * A copy of a layout whose groups and tab rows can be changed freely. + * + * @param layout - the layout to copy. + */ +function copy(layout: TabLayout): TabLayout { + return { + groups: layout.groups.map((g) => ({ activeId: g.activeId, tabs: g.tabs.map((t) => ({ ...t })) })), + focused: layout.focused, + orientation: layout.orientation, + }; +} + +/** + * The number of pinned tabs at the start of a group. + * + * @param group - the group. + */ +export function pinnedCount(group: TabGroup): number { + return group.tabs.filter((t) => t.pinned).length; +} + +/** + * Indexes of the groups that show a buffer. + * + * @param layout - the layout. + * @param id - buffer id. + */ +export function groupsOf(layout: TabLayout, id: number): number[] { + return layout.groups.flatMap((g, index) => (g.tabs.some((t) => t.id === id) ? [index] : [])); +} + +/** + * Every buffer id in the layout, once, in group then tab order. + * + * @param layout - the layout. + */ +export function bufferIds(layout: TabLayout): number[] { + return [...new Set(layout.groups.flatMap((g) => g.tabs.map((t) => t.id)))]; +} + +/** + * The active buffer of the focused group, null if it is empty. + * + * @param layout - the layout. + */ +export function activeBuffer(layout: TabLayout): number | null { + return layout.groups[layout.focused]?.activeId ?? null; +} + +/** + * A group index clamped to the layout; the focused group when omitted. + * + * @param layout - the layout. + * @param group - wanted index. + */ +export function groupIndex(layout: TabLayout, group?: number | null): number { + if (group === undefined || group === null || !Number.isInteger(group)) { + return layout.focused; + } + return Math.min(Math.max(group, 0), layout.groups.length - 1); +} + +/** + * Places a buffer in a group: activates its tab when the group has it, + * replaces the group's preview tab when a preview opens, else inserts a new + * tab after the active one (inside the pinned or unpinned block). + * + * @param layout - the layout. + * @param group - group index (clamped). + * @param id - buffer id. + * @param options - see {@link PlaceOptions}. + * @returns the new layout and the replaced preview's buffer id. + */ +export function placeTab(layout: TabLayout, group: number, id: number, options: PlaceOptions): PlaceResult { + const next = copy(layout); + const index = groupIndex(next, group); + const target = next.groups[index]; + if (!target) { + return { layout: next, replaced: null }; + } + let replaced: number | null = null; + const existing = target.tabs.find((t) => t.id === id); + if (existing) { + if (!options.preview) { + existing.preview = false; + } + } else { + const pinned = options.pinned === true; + const tab: TabPlacement = { id, pinned, preview: options.preview && !pinned }; + const previewAt = tab.preview ? target.tabs.findIndex((t) => t.preview) : -1; + const old = target.tabs[previewAt]; + if (old) { + replaced = old.id; + target.tabs.splice(previewAt, 1, tab); + if (target.activeId === old.id) { + target.activeId = id; + } + } else { + const pins = pinnedCount(target); + const activeAt = target.tabs.findIndex((t) => t.id === target.activeId); + const wanted = options.index ?? (activeAt < 0 ? target.tabs.length : activeAt + 1); + const [low, high] = pinned ? [0, pins] : [pins, target.tabs.length]; + target.tabs.splice(Math.min(Math.max(wanted, low), high), 0, tab); + } + } + if (options.activate || target.activeId === null) { + target.activeId = id; + } + if (options.activate) { + next.focused = index; + } + return { layout: next, replaced }; +} + +/** + * Activates a tab and focuses its group. + * + * @param layout - the layout. + * @param group - group index. + * @param id - buffer id; nothing changes when the group lacks it. + */ +export function activateTab(layout: TabLayout, group: number, id: number): TabLayout { + const target = layout.groups[group]; + if (!target?.tabs.some((t) => t.id === id)) { + return layout; + } + const next = copy(layout); + const nextGroup = next.groups[group]; + if (nextGroup) { + nextGroup.activeId = id; + } + next.focused = group; + return next; +} + +/** + * Focuses a group. + * + * @param layout - the layout. + * @param group - group index (clamped). + */ +export function focusGroup(layout: TabLayout, group: number): TabLayout { + const index = groupIndex(layout, group); + return index === layout.focused ? layout : { ...copy(layout), focused: index }; +} + +/** + * Drops empty groups while more than one is left and keeps + * {@link TabLayout.focused} valid. + * + * @param layout - a layout this module owns (changed in place). + */ +function collapse(layout: TabLayout): TabLayout { + const focusedGroup = layout.groups[layout.focused]; + if (layout.groups.length > 1) { + layout.groups = layout.groups.filter((g) => g.tabs.length > 0); + if (layout.groups.length === 0) { + layout.groups = [{ tabs: [], activeId: null }]; + } + } + const kept = focusedGroup ? layout.groups.indexOf(focusedGroup) : -1; + layout.focused = kept >= 0 ? kept : Math.min(layout.focused, layout.groups.length - 1); + return layout; +} + +/** + * Removes a tab from one group; its right (else left) neighbour becomes the + * group's active tab. An emptied group goes away while another is left. + * + * @param layout - the layout. + * @param group - group index. + * @param id - buffer id. + */ +export function removeTab(layout: TabLayout, group: number, id: number): TabLayout { + const next = copy(layout); + const target = next.groups[group]; + const at = target ? target.tabs.findIndex((t) => t.id === id) : -1; + if (!target || at < 0) { + return layout; + } + target.tabs.splice(at, 1); + if (target.activeId === id) { + target.activeId = target.tabs[Math.min(at, target.tabs.length - 1)]?.id ?? null; + } + return collapse(next); +} + +/** + * Removes a buffer from every group (the engine closed it). + * + * @param layout - the layout. + * @param id - buffer id. + */ +export function removeBuffer(layout: TabLayout, id: number): TabLayout { + let next = layout; + for (const group of groupsOf(layout, id).reverse()) { + next = removeTab(next, group, id); + } + return next; +} + +/** + * Makes every tab of a buffer permanent (it was edited or opened for good). + * + * @param layout - the layout. + * @param id - buffer id. + * @param group - only this group; every group when omitted. + */ +export function keepOpen(layout: TabLayout, id: number, group?: number): TabLayout { + const has = layout.groups.some((g, index) => (group === undefined || index === group) && g.tabs.some((t) => t.id === id && t.preview)); + if (!has) { + return layout; + } + const next = copy(layout); + next.groups.forEach((g, index) => { + if (group === undefined || index === group) { + for (const tab of g.tabs) { + if (tab.id === id) { + tab.preview = false; + } + } + } + }); + return next; +} + +/** + * Pins or unpins a tab. A pinned tab moves to the end of the pinned block, + * an unpinned one to the start of the unpinned block; pinning also keeps a + * preview open. + * + * @param layout - the layout. + * @param group - group index. + * @param id - buffer id. + * @param pinned - the new state. + */ +export function setPinned(layout: TabLayout, group: number, id: number, pinned: boolean): TabLayout { + const next = copy(layout); + const target = next.groups[group]; + const at = target ? target.tabs.findIndex((t) => t.id === id) : -1; + const tab = target?.tabs[at]; + if (!target || !tab || tab.pinned === pinned) { + return layout; + } + target.tabs.splice(at, 1); + tab.pinned = pinned; + tab.preview = false; + target.tabs.splice(pinnedCount(target), 0, tab); + return next; +} + +/** + * The buffers a bulk close removes from a group. Pinned tabs always stay. + * + * @param group - the group. + * @param id - buffer id of the tab the action starts from (ignored by + * `all` and `unmodified`). + * @param action - which tabs to close. + * @param dirty - whether a buffer has unsaved changes (for `unmodified`). + * @returns buffer ids in tab order. + */ +export function closeTargets(group: TabGroup, id: number | null, action: CloseAction, dirty: (id: number) => boolean): number[] { + const at = group.tabs.findIndex((t) => t.id === id); + return group.tabs + .filter((tab, index) => { + if (tab.pinned) { + return false; + } + switch (action) { + case "others": + return tab.id !== id; + case "all": + return true; + case "left": + return at >= 0 && index < at; + case "right": + return at >= 0 && index > at; + case "unmodified": + return !dirty(tab.id); + } + return false; + }) + .map((tab) => tab.id); +} + +/** + * Splits the editor area: the active tab of the focused group opens in the + * other group too (a new group when there is one), which gets the focus. + * With two groups already, it sets the orientation and shows the tab there. + * + * @param layout - the layout. + * @param orientation - where the other group sits. + */ +export function split(layout: TabLayout, orientation: SplitOrientation): TabLayout { + const id = activeBuffer(layout); + const next = copy(layout); + next.orientation = orientation; + if (next.groups.length < MAX_GROUPS) { + next.groups.push({ tabs: [], activeId: null }); + } + const other = otherGroup(next); + if (id === null || other === null) { + return next; + } + return placeTab(next, other, id, { preview: false, activate: true }).layout; +} + +/** + * The index of the group that does not have the focus, null with one group. + * + * @param layout - the layout. + */ +export function otherGroup(layout: TabLayout): number | null { + return layout.groups.length < 2 ? null : layout.focused === 0 ? 1 : 0; +} + +/** + * Moves a tab to the other group (splitting to the right when there is + * only one group) and focuses it there. A buffer already shown there is + * only activated. + * + * @param layout - the layout. + * @param group - group index of the tab. + * @param id - buffer id. + */ +export function moveToOtherGroup(layout: TabLayout, group: number, id: number): TabLayout { + const source = layout.groups[group]; + const tab = source?.tabs.find((t) => t.id === id); + if (!tab) { + return layout; + } + if (layout.groups.length === 1 && source && source.tabs.length === 1) { + return layout; + } + let next = copy(layout); + if (next.groups.length < MAX_GROUPS) { + next.groups.push({ tabs: [], activeId: null }); + } + const target = group === 0 ? 1 : 0; + next = placeTab(next, target, id, { preview: tab.preview, activate: true, pinned: tab.pinned }).layout; + const sourceGroup = next.groups[group]; + const at = sourceGroup ? sourceGroup.tabs.findIndex((t) => t.id === id) : -1; + if (sourceGroup && at >= 0) { + sourceGroup.tabs.splice(at, 1); + if (sourceGroup.activeId === id) { + sourceGroup.activeId = sourceGroup.tabs[Math.min(at, sourceGroup.tabs.length - 1)]?.id ?? null; + } + } + return collapse(next); +} + +/** + * Joins both groups into one: tabs of the other group that the focused one + * lacks are added at its end. + * + * @param layout - the layout. + */ +export function unsplit(layout: TabLayout): TabLayout { + const other = otherGroup(layout); + if (other === null) { + return layout; + } + const next = copy(layout); + const kept = next.groups[next.focused]; + const dropped = next.groups[other]; + if (!kept || !dropped) { + return layout; + } + for (const tab of dropped.tabs) { + if (!kept.tabs.some((t) => t.id === tab.id)) { + kept.tabs.splice(tab.pinned ? pinnedCount(kept) : kept.tabs.length, 0, { ...tab, preview: false }); + } + } + kept.activeId ??= dropped.activeId; + return { groups: [kept], focused: 0, orientation: next.orientation }; +} + +/** A tab as the layout file stores it (paths instead of buffer ids). */ +export type StoredTab = { + /** Project-relative path. */ + path: string; + /** Pinned. */ + pinned: boolean; + /** Preview. */ + preview: boolean; +}; + +/** A group as the layout file stores it. */ +export type StoredGroup = { + /** Tabs in order. */ + tabs: StoredTab[]; + /** Path of the active tab, null if none. */ + active: string | null; +}; + +/** The layout of a project as Lutra's state file stores it. */ +export type StoredLayout = { + /** Format version, {@link STORED_VERSION}. */ + version: number; + /** One or two groups. */ + groups: StoredGroup[]; + /** Focused group. */ + focused: number; + /** Where the second group sits. */ + orientation: SplitOrientation; +}; + +/** Version of {@link StoredLayout}. */ +export const STORED_VERSION = 1; + +/** Most tabs one stored group may hold; more are dropped when reading. */ +export const MAX_STORED_TABS = 200; + +/** + * Converts a layout for storing. + * + * @param layout - the layout. + * @param pathOf - project-relative path of a buffer, undefined if unknown. + */ +export function toStored(layout: TabLayout, pathOf: (id: number) => string | undefined): StoredLayout { + const groups = layout.groups.map((g) => ({ + tabs: g.tabs.flatMap((t) => { + const path = pathOf(t.id); + return path === undefined ? [] : [{ path, pinned: t.pinned, preview: t.preview }]; + }), + active: g.activeId === null ? null : (pathOf(g.activeId) ?? null), + })); + return { version: STORED_VERSION, groups, focused: layout.focused, orientation: layout.orientation }; +} + +/** + * Reads a stored layout from untrusted JSON. Unknown or malformed parts are + * dropped; a value that is not a layout at all gives null. + * + * @param value - what the state file held. + */ +export function parseStored(value: unknown): StoredLayout | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return null; + } + const v = value as Record; + if (v.version !== STORED_VERSION || !Array.isArray(v.groups)) { + return null; + } + const groups: StoredGroup[] = []; + for (const raw of v.groups.slice(0, MAX_GROUPS)) { + if (typeof raw !== "object" || raw === null) { + continue; + } + const g = raw as Record; + const tabs: StoredTab[] = []; + const seen = new Set(); + for (const rawTab of Array.isArray(g.tabs) ? g.tabs.slice(0, MAX_STORED_TABS) : []) { + if (typeof rawTab !== "object" || rawTab === null) { + continue; + } + const tab = rawTab as Record; + if (typeof tab.path !== "string" || tab.path === "" || seen.has(tab.path)) { + continue; + } + seen.add(tab.path); + tabs.push({ path: tab.path, pinned: tab.pinned === true, preview: tab.preview === true && tab.pinned !== true }); + } + tabs.sort((a, b) => Number(b.pinned) - Number(a.pinned)); + const active = typeof g.active === "string" && seen.has(g.active) ? g.active : (tabs[0]?.path ?? null); + if (tabs.length > 0) { + groups.push({ tabs, active }); + } + } + const focused = typeof v.focused === "number" && Number.isInteger(v.focused) ? Math.min(Math.max(v.focused, 0), Math.max(groups.length - 1, 0)) : 0; + const orientation: SplitOrientation = v.orientation === "down" ? "down" : "right"; + return { version: STORED_VERSION, groups, focused, orientation }; +} + +/** A closed tab, for "Reopen Closed Tab". */ +export interface ClosedTab { + /** Project-relative path. */ + path: string; + /** Group it sat in. */ + group: number; + /** Index in that group. */ + index: number; + /** Whether it was pinned. */ + pinned: boolean; + /** Selection anchor, as a CodeMirror position. */ + anchor: number; + /** Selection head. */ + head: number; + /** Position at the top of the view, null when unknown. */ + top: number | null; +} + +/** Most entries of the reopen stack. */ +export const MAX_CLOSED = 30; + +/** + * Pushes a closed tab on the reopen stack; an older entry of the same path + * goes away and the stack keeps at most {@link MAX_CLOSED} entries. + * + * @param stack - the stack, newest last. + * @param entry - the closed tab. + */ +export function pushClosed(stack: readonly ClosedTab[], entry: ClosedTab): ClosedTab[] { + return [...stack.filter((e) => e.path !== entry.path), entry].slice(-MAX_CLOSED); +} diff --git a/ui/src/components/find/FindToolWindow.vue b/ui/src/components/find/FindToolWindow.vue index 99b41c0..7a5d324 100644 --- a/ui/src/components/find/FindToolWindow.vue +++ b/ui/src/components/find/FindToolWindow.vue @@ -128,7 +128,7 @@ function dirName(path: string): string { */ function openRow(row: FindRow): void { find.select(row.key); - void commands.execute("editor.reveal", { path: row.path, line: row.match.line, column: row.match.column }); + void commands.execute("editor.reveal", { path: row.path, line: row.match.line, column: row.match.column, preview: true }); } /** Starts a search for the fields' current values. */ diff --git a/ui/src/components/goto/GotoPopup.vue b/ui/src/components/goto/GotoPopup.vue index bfcc38b..0828969 100644 --- a/ui/src/components/goto/GotoPopup.vue +++ b/ui/src/components/goto/GotoPopup.vue @@ -197,7 +197,9 @@ function choose(item: GotoItem | undefined): void { } close(); const params: JsonValue = - item.line === null ? { path: item.path } : { path: item.path, line: item.line, column: item.column ?? 0 }; + item.line === null + ? { path: item.path, preview: true } + : { path: item.path, line: item.line, column: item.column ?? 0, preview: true }; void commands.execute("editor.reveal", params); } diff --git a/ui/src/components/menu/menu.ts b/ui/src/components/menu/menu.ts index 152c30b..9789a4e 100644 --- a/ui/src/components/menu/menu.ts +++ b/ui/src/components/menu/menu.ts @@ -2,8 +2,9 @@ * The app menu's model (M3.9): the commands that have a menu path, grouped * by the path's first segment. * - * - **Groups** come in Lutra's order (File, Edit, View, Go, Help); a group - * Lutra does not know goes before Help, sorted by name. Empty groups are + * - **Groups** come in Lutra's order (File, Edit, View, Go, then Window and + * Help last); a group Lutra does not know goes before Window, sorted by + * name. Empty groups are * left out. Known group names come from the catalog. * - **Items** in a group follow {@link ITEM_ORDER}; others come after it, * sorted by label. @@ -38,7 +39,7 @@ export interface MenuGroup { } /** Known groups in display order. */ -const GROUP_ORDER = ["File", "Edit", "View", "Go", "Help"]; +const GROUP_ORDER = ["File", "Edit", "View", "Go", "Window", "Help"]; /** Order of known commands inside their group. */ const ITEM_ORDER = [ @@ -58,6 +59,19 @@ const ITEM_ORDER = [ "goto.fileOpen", "goto.classOpen", "goto.symbolOpen", + "tabs.splitRight", + "tabs.splitDown", + "tabs.moveToOtherGroup", + "tabs.focusOtherGroup", + "tabs.unsplit", + "tabs.closeOthers", + "tabs.closeAll", + "tabs.closeLeft", + "tabs.closeRight", + "tabs.closeUnmodified", + "tabs.reopenClosed", + "tabs.togglePin", + "tabs.keepOpen", "app.about", ]; @@ -76,6 +90,8 @@ function groupLabel(key: string): string { return t("menu.group.view"); case "Go": return t("menu.group.go"); + case "Window": + return t("menu.group.window"); case "Help": return t("menu.group.help"); default: @@ -91,7 +107,7 @@ function groupLabel(key: string): string { function groupRank(key: string): number { const index = GROUP_ORDER.indexOf(key); if (index >= 0) { - return key === "Help" ? 1000 : index; + return key === "Help" ? 1000 : key === "Window" ? 900 : index; } return 500; } diff --git a/ui/src/components/project/ProjectTree.vue b/ui/src/components/project/ProjectTree.vue index 169a55b..66caf6e 100644 --- a/ui/src/components/project/ProjectTree.vue +++ b/ui/src/components/project/ProjectTree.vue @@ -5,8 +5,9 @@ * * Keys: Up/Down move the selection, Home/End jump to the first/last row, * Right expands a folder or moves into it, Left collapses a folder or moves - * to the parent, Enter opens a file or toggles a folder. Double-click does - * the same as Enter. Ignored and excluded entries are dimmed. A directory + * to the parent, Enter opens a file or toggles a folder. A single click on + * a file opens it in a preview tab (C10 A1); double-click does the same as + * Enter and keeps the tab open. Ignored and excluded entries are dimmed. A directory * the engine listed only partly ends with a "listing truncated" note. * File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside * a repository, ignored entries take the ignored colour. @@ -177,6 +178,8 @@ function onRowClick(entry: TreeEntry, onChevron: boolean): void { project.select(entry.path); if (onChevron && entry.kind === "dir") { void project.toggle(entry.path); + } else if (entry.kind !== "dir") { + void editor.openFile(entry.path, { preview: true }); } } diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 370ab5e..3cc7051 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -26,6 +26,19 @@ "command.palette.open": "Command Palette", "command.problems.open": "Problems", "command.settings.open": "Settings…", + "command.tabs.closeAll": "Close All Tabs", + "command.tabs.closeLeft": "Close Tabs to the Left", + "command.tabs.closeOthers": "Close Other Tabs", + "command.tabs.closeRight": "Close Tabs to the Right", + "command.tabs.closeUnmodified": "Close Unmodified Tabs", + "command.tabs.focusOtherGroup": "Focus Other Group", + "command.tabs.keepOpen": "Keep Tab Open", + "command.tabs.moveToOtherGroup": "Move Tab to Other Group", + "command.tabs.reopenClosed": "Reopen Closed Tab", + "command.tabs.splitDown": "Split Down", + "command.tabs.splitRight": "Split Right", + "command.tabs.togglePin": "Pin or Unpin Tab", + "command.tabs.unsplit": "Unsplit", "command.terminal.open": "Terminal", "command.unavailable": "{command} cannot run right now", "command.vcs.abortMerge": "Abort Merge…", @@ -62,6 +75,7 @@ "common.dontSave": "Don't Save", "common.error.unexpectedResult": "unexpected result of {command}", "common.save": "Save", + "common.saveAll": "Save All", "common.toolWindow.bottomTabs": "Bottom tool windows", "common.toolWindow.collapse": "Collapse {title}", "common.toolWindow.expand": "Expand {title}", @@ -212,6 +226,7 @@ "editor.chunk.unstage": "Unstage", "editor.chunk.unstaged": "Not staged", "editor.closePrompt.question": "Save changes to {name} before closing?", + "editor.closePrompt.questionMany": "Save changes to these {count} files before closing?", "editor.gitGutter.added": "Added since the staged version", "editor.gitGutter.deleted": "Lines deleted here since the staged version", "editor.gitGutter.modified": "Changed since the staged version", @@ -222,7 +237,14 @@ "editor.reveal.openFailed": "could not open {path}", "editor.saveFailed": "save failed", "editor.tabs.close": "Close {name}", + "editor.tabs.group": "Editor group {n}", "editor.tabs.label": "Editor tabs", + "editor.tabs.menu.close": "Close", + "editor.tabs.menu.label": "Actions for {name}", + "editor.tabs.menu.pin": "Pin Tab", + "editor.tabs.menu.showHistory": "Show Local History", + "editor.tabs.menu.unpin": "Unpin Tab", + "editor.tabs.pinned": "pinned", "editor.tabs.unsaved": "unsaved changes", "find.action.search": "Search", "find.count.files.one": "1 file", @@ -266,6 +288,7 @@ "menu.group.go": "Go", "menu.group.help": "Help", "menu.group.view": "View", + "menu.group.window": "Window", "menu.label": "Main menu", "nav.definition.none": "No definition found for {name}", "nav.picker.line": "line {line}", @@ -432,6 +455,8 @@ "settings.editor.hover.delayMs.label": "Documentation tooltip delay (ms)", "settings.editor.lineHeight.description": "Height of each editor line relative to the font size. 150 means one and a half times the font size.", "settings.editor.lineHeight.label": "Editor line height (%)", + "settings.editor.tabs.preview.description": "A single click in the project tree, search results or Go to opens a preview tab that the next one replaces. Editing it or a double click keeps it open.", + "settings.editor.tabs.preview.label": "Preview tabs", "settings.error.browseFailed": "The file picker could not open: {message}", "settings.error.int": "Enter a whole number", "settings.error.intRange": "Enter a whole number from {min} to {max}", diff --git a/ui/src/stores/editor.ts b/ui/src/stores/editor.ts index f578ddc..e300a12 100644 --- a/ui/src/stores/editor.ts +++ b/ui/src/stores/editor.ts @@ -1,23 +1,39 @@ /** - * 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. + * Editor tabs: which engine buffers are open, how their tabs sit in one or + * two editor groups (C10 A1, rules in `components/editor/tabs/model.ts`), + * their dirty state, notices, the reopen stack and the Save / Don't save / + * Cancel question when tabs with unsaved changes close. * * Fed by engine events (`bufferOpened`, `bufferFocused`, `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. + * results. Text lives in the engine and in one {@link BufferSync} per + * buffer, kept outside reactive state; a buffer shown in both groups has + * one sync, so both share the text and the undo history. Command failures + * are stored and shown, never thrown. + * + * The tab layout of a project is stored through the engine (`layout.set`, + * Lutra's own state file) and restored when the project opens. + * + * **Public API for other areas** (C10 A2's conflict banner and others): + * {@link tabOfPath} finds the tab of a path, {@link tabOf} the tab of a + * buffer id, {@link reloadBuffer} makes the editor take the engine's text + * over after a reload from disk, {@link openFile} opens or shows a file. + * Read {@link tabs} (one entry per open buffer), {@link activeId} and + * {@link groups}; change tabs only through the store's functions. */ import { defineStore } from "pinia"; -import { computed, ref, shallowRef } from "vue"; +import { computed, ref, shallowRef, watch } from "vue"; +import { EditorView } from "@codemirror/view"; import { t } from "../i18n"; 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 { AssistBuffer } from "../components/editor/assist"; +import * as model from "../components/editor/tabs/model"; +import type { CloseAction, ClosedTab, SplitOrientation, TabLayout } from "../components/editor/tabs/model"; import type { Extension } from "@codemirror/state"; +import { useSettingsStore } from "./settings"; /** Engine command ids used by the editor. */ export const EDITOR_COMMANDS = { @@ -34,8 +50,18 @@ export const EDITOR_COMMANDS = { saveAll: "file.saveAll", /** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */ close: "buffer.close", + /** Reads the stored tab layout: result `{ layout: object | null }`. */ + layoutGet: "layout.get", + /** Stores the tab layout: params `{ layout }`. */ + layoutSet: "layout.set", } as const; +/** Setting that turns preview tabs on (default) or off. */ +export const PREVIEW_SETTING = "editor.tabs.preview"; + +/** Milliseconds a layout change waits before it is stored. */ +const PERSIST_DELAY_MS = 300; + /** A notice shown above a tab's editor; it never blocks editing. */ export interface EditorNotice { /** What happened. */ @@ -44,7 +70,7 @@ export interface EditorNotice { message: string; } -/** One editor tab. */ +/** One open buffer, as its tabs show it. */ export interface EditorTab { /** Engine buffer id. */ id: number; @@ -58,17 +84,57 @@ export interface EditorTab { notice: EditorNotice | null; } -/** The pending question for closing a dirty tab. */ -export interface ClosePrompt { - /** Buffer id of the tab. */ +/** One tab of a group as the tab strip shows it. */ +export interface GroupTab { + /** The buffer. */ + tab: EditorTab; + /** Pinned. */ + pinned: boolean; + /** Preview (italic title). */ + preview: boolean; +} + +/** One editor group as the editor area shows it. */ +export interface EditorGroup { + /** Group index. */ + index: number; + /** Tabs in display order. */ + tabs: GroupTab[]; + /** Buffer id of the group's active tab, null if empty. */ + activeId: number | null; +} + +/** One buffer a close question asks about. */ +export interface ClosingBuffer { + /** Buffer id. */ id: number; - /** File name, for the question. */ + /** File name. */ name: string; } -/** Answer to a {@link ClosePrompt}. */ +/** The pending question for closing tabs with unsaved changes. */ +export interface ClosePrompt { + /** The dirty buffers, in tab order; one or more. */ + items: ClosingBuffer[]; +} + +/** Answer to a {@link ClosePrompt}: save all, discard all, or keep them. */ export type CloseChoice = "save" | "discard" | "cancel"; +/** How {@link openFile} shows a file. */ +export interface OpenOptions { + /** Open as a preview tab (ignored when the setting is off). */ + preview?: boolean; + /** Group to open in; the focused group when omitted. */ + group?: number; + /** Make the tab active and focus its group (default true). */ + activate?: boolean; + /** Pin the new tab. */ + pinned?: boolean; + /** Index in the group for a new tab. */ + index?: number; +} + /** Timing of the last file open, for the performance budget. */ export interface OpenTiming { /** Path of the opened file. */ @@ -93,10 +159,12 @@ export function baseName(path: string): string { /** 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); + /** Open buffers, once each, in no particular order. */ + const records = ref([]); + /** The tab layout of the groups. */ + const layout = shallowRef(model.emptyLayout()); + /** Closed tabs for "Reopen Closed Tab", newest last. */ + const closed = shallowRef([]); /** Pending close question, null if none. */ const closePrompt = ref(null); /** Last failed editor command, null if none. */ @@ -105,6 +173,8 @@ export const useEditorStore = defineStore("editor", () => { const lastOpen = shallowRef(null); /** Syncs by buffer id; not reactive (they hold large editor states). */ const syncs = new Map(); + /** Editor views by group index, registered by the editor panes. */ + const views = 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}. */ @@ -117,9 +187,70 @@ export const useEditorStore = defineStore("editor", () => { let openSequence = 0; /** Unsubscribe function of the event subscription. */ let unsubscribe: (() => void) | null = null; + /** Buffers of the pending {@link closePrompt} and the clean ones closing with them. */ + let pendingClose: number[] = []; + /** Whether layout changes are stored (a project is open and restored). */ + let persisting = false; + /** Timer of the next layout store, null if none. */ + let persistTimer: ReturnType | null = null; + + /** Every open buffer once, in group then tab order. */ + const tabs = computed({ + get: () => { + const byId = new Map(records.value.map((r) => [r.id, r])); + const ordered = model.bufferIds(layout.value).flatMap((id) => { + const record = byId.get(id); + return record ? [record] : []; + }); + const placed = new Set(ordered.map((r) => r.id)); + return [...ordered, ...records.value.filter((r) => !placed.has(r.id))]; + }, + set: (next) => { + records.value = next; + let nextLayout = model.emptyLayout(); + for (const tab of next) { + nextLayout = model.placeTab(nextLayout, 0, tab.id, { preview: false, activate: false }).layout; + } + layout.value = nextLayout; + }, + }); + + /** The active buffer of the focused group; setting it activates its tab. */ + const activeId = computed({ + get: () => model.activeBuffer(layout.value), + set: (id) => { + if (id === null) { + return; + } + ensurePlaced(id); + activate(id); + }, + }); /** The active tab, or null. */ - const activeTab = computed(() => tabs.value.find((t) => t.id === activeId.value) ?? null); + const activeTab = computed(() => records.value.find((t) => t.id === activeId.value) ?? null); + + /** The groups as the editor area shows them. */ + const groups = computed(() => { + const byId = new Map(records.value.map((r) => [r.id, r])); + return layout.value.groups.map((group, index) => ({ + index, + activeId: group.activeId, + tabs: group.tabs.flatMap((p) => { + const tab = byId.get(p.id); + return tab ? [{ tab, pinned: p.pinned, preview: p.preview }] : []; + }), + })); + }); + + /** Index of the focused group. */ + const focusedGroup = computed(() => layout.value.focused); + + /** Where the second group sits. */ + const orientation = computed(() => layout.value.orientation); + + /** Whether "Reopen Closed Tab" has something to reopen. */ + const canReopen = computed(() => closed.value.length > 0); /** * The tab of a buffer. @@ -127,7 +258,16 @@ export const useEditorStore = defineStore("editor", () => { * @param id - buffer id. */ function tabOf(id: number): EditorTab | undefined { - return tabs.value.find((t) => t.id === id); + return records.value.find((t) => t.id === id); + } + + /** + * The tab of a file (public API, see the module documentation). + * + * @param path - project-relative path as `file.open` reports it. + */ + function tabOfPath(path: string): EditorTab | undefined { + return records.value.find((t) => t.path === path); } /** @@ -139,6 +279,20 @@ export const useEditorStore = defineStore("editor", () => { return syncs.get(id); } + /** + * Makes the editor take the engine's current text of a buffer over and + * drop local edits not sent yet (public API: after the engine reloaded the + * file from disk, for example from a conflict banner's "Reload"). + * + * @param id - buffer id. + * @returns whether the buffer is open. + */ + function reloadBuffer(id: number): boolean { + const sync = syncs.get(id); + sync?.reload(); + return sync !== undefined; + } + /** * Replaces the engine transport and editor extensions (tests). * @@ -153,13 +307,33 @@ export const useEditorStore = defineStore("editor", () => { } /** - * Adds a tab for a buffer the engine described, unless it exists, and - * activates it. + * Registers the view of an editor group, so closing a tab can remember + * its scroll position. + * + * @param group - group index. + * @param view - the view, or null when the pane goes away. + */ + function registerView(group: number, view: EditorView | null): void { + if (view) { + views.set(group, view); + } else { + views.delete(group); + } + } + + /** Whether preview tabs are on. */ + function previewEnabled(): boolean { + const value = useSettingsStore().values[PREVIEW_SETTING]; + return typeof value === "boolean" ? value : true; + } + + /** + * Creates the sync and record of a buffer the engine described, unless + * they exist. * * @param info - the buffer. - * @param activate - whether the tab becomes active. */ - function adopt(info: BufferInfo, activate = true): void { + function track(info: BufferInfo): void { if (!syncs.has(info.id)) { const started = openStarted.get(info.path); syncs.set( @@ -183,18 +357,82 @@ export const useEditorStore = defineStore("editor", () => { } } if (!tabOf(info.id)) { - const index = tabs.value.findIndex((t) => t.id === activeId.value); - const tab: EditorTab = { + records.value.push({ 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; + } + + /** + * Drops the sync and record of a buffer no group shows any more. + * + * @param id - buffer id. + */ + function untrack(id: number): void { + syncs.get(id)?.dispose(); + syncs.delete(id); + records.value = records.value.filter((r) => r.id !== id); + if (closePrompt.value?.items.some((item) => item.id === id)) { + const items = closePrompt.value.items.filter((item) => item.id !== id); + closePrompt.value = items.length > 0 ? { items } : null; + } + } + + /** Places a tracked buffer that no group shows into the focused group. */ + function ensurePlaced(id: number): void { + if (tabOf(id) && model.groupsOf(layout.value, id).length === 0) { + layout.value = model.placeTab(layout.value, layout.value.focused, id, { preview: false, activate: false }).layout; + } + } + + /** + * Places a buffer in a group. A preview that replaces the group's old + * preview closes the old buffer unless another group shows it. + * + * @param id - buffer id. + * @param options - see {@link OpenOptions}. + */ + function place(id: number, options: OpenOptions): void { + const group = model.groupIndex(layout.value, options.group); + const preview = options.preview === true && options.pinned !== true && previewEnabled(); + const oldPreview = layout.value.groups[group]?.tabs.find((tab) => tab.preview); + if (preview && oldPreview && oldPreview.id !== id && tabOf(oldPreview.id)?.dirty === true) { + layout.value = model.keepOpen(layout.value, oldPreview.id, group); + } + const result = model.placeTab(layout.value, group, id, { + preview, + activate: options.activate !== false, + pinned: options.pinned, + index: options.index, + }); + layout.value = result.layout; + const replaced = result.replaced; + if (replaced !== null && replaced !== id && model.groupsOf(layout.value, replaced).length === 0) { + void closeBuffer(replaced, false).then((closeResult) => { + if (!closeResult.ok) { + layout.value = model.placeTab(layout.value, group, replaced, { preview: false, activate: false }).layout; + } + }); + } + } + + /** + * Adds a tab for a buffer the engine described, unless one exists, in + * the focused group (tests and buffers opened elsewhere). + * + * @param info - the buffer. + * @param activate - whether the tab becomes active. + */ + function adopt(info: BufferInfo, activate = true): void { + track(info); + if (model.groupsOf(layout.value, info.id).length === 0) { + place(info.id, { activate: activate || activeId.value === null }); + } else if (activate) { + activateAnywhere(info.id); } } @@ -212,13 +450,30 @@ export const useEditorStore = defineStore("editor", () => { } /** - * Opens a file in a tab (or activates its tab). + * Opens a file in a tab, or shows its tab: the focused group's tab when + * it has one, else the other group's, else a new tab in the target group. + * A permanent open makes an existing preview tab permanent. * * @param path - project-relative path. + * @param options - preview, group and placement, see {@link OpenOptions}. * @returns the buffer id of the tab, or null if the open failed * ({@link lastError} says why). */ - async function openFile(path: string): Promise { + async function openFile(path: string, options: OpenOptions = {}): Promise { + const existing = tabOfPath(path); + if (existing && options.group === undefined) { + const where = model.groupsOf(layout.value, existing.id); + const group = where.includes(layout.value.focused) ? layout.value.focused : where[0]; + if (group !== undefined) { + if (options.preview !== true) { + layout.value = model.keepOpen(layout.value, existing.id, group); + } + if (options.activate !== false) { + layout.value = model.activateTab(layout.value, group, existing.id); + } + return existing.id; + } + } openStarted.set(path, performance.now()); const result = await run(EDITOR_COMMANDS.open, { path }); if (!result.ok) { @@ -232,41 +487,96 @@ export const useEditorStore = defineStore("editor", () => { } lastError.value = null; openSequence += 1; - adopt(result.value); + track(result.value); + place(result.value.id, options); return result.value.id; } /** - * Activates a tab. + * Activates a tab in a group and focuses that group. + * + * @param id - buffer id. + * @param group - group index; the focused group, else the first group + * that shows the buffer, when omitted. + */ + function activate(id: number, group?: number): void { + if (group !== undefined) { + layout.value = model.activateTab(layout.value, group, id); + return; + } + activateAnywhere(id); + } + + /** + * Activates a buffer in the focused group if it shows it, else in the + * first group that does. * * @param id - buffer id. */ - function activate(id: number): void { - if (tabOf(id)) { - activeId.value = id; + function activateAnywhere(id: number): void { + const where = model.groupsOf(layout.value, id); + const group = where.includes(layout.value.focused) ? layout.value.focused : where[0]; + if (group !== undefined) { + layout.value = model.activateTab(layout.value, group, id); } } /** - * Removes a tab and its sync; the neighbour becomes active. + * Focuses a group. + * + * @param group - group index. + */ + function focusGroup(group: number): void { + layout.value = model.focusGroup(layout.value, group); + } + + /** + * Remembers a tab for "Reopen Closed Tab": its place, selection and the + * position at the top of its view when a group shows it. + * + * @param id - buffer id. + */ + function remember(id: number): void { + const record = tabOf(id); + const where = model.groupsOf(layout.value, id); + const group = where[0]; + if (!record || group === undefined) { + return; + } + const placement = layout.value.groups[group]?.tabs; + const index = placement ? placement.findIndex((p) => p.id === id) : -1; + const tab = placement?.[index]; + if (!tab || tab.preview) { + return; + } + const sync = syncs.get(id); + const selection = sync?.state.selection.main; + let top: number | null = null; + for (const [viewGroup, view] of views) { + if (layout.value.groups[viewGroup]?.activeId === id && view.state === sync?.state) { + top = view.lineBlockAtHeight(view.scrollDOM.scrollTop).from; + } + } + closed.value = model.pushClosed(closed.value, { + path: record.path, + group, + index, + pinned: tab.pinned, + anchor: selection?.anchor ?? 0, + head: selection?.head ?? 0, + top, + }); + } + + /** + * Removes a buffer from every group and drops it (the engine closed it). * * @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; - } + remember(id); + layout.value = model.removeBuffer(layout.value, id); + untrack(id); } /** @@ -288,7 +598,7 @@ export const useEditorStore = defineStore("editor", () => { /** Whether any tab has unsaved changes or edits still on the way. */ function hasUnsaved(): boolean { - return tabs.value.some((t) => t.dirty) || [...syncs.values()].some((sync) => sync.pending); + return records.value.some((t) => t.dirty) || [...syncs.values()].some((sync) => sync.pending); } /** @@ -307,50 +617,136 @@ export const useEditorStore = defineStore("editor", () => { } /** - * Closes a tab; a dirty one asks Save / Don't save / Cancel first. + * Closes buffers, asking once about those with unsaved changes. Buffers + * the other group still shows only lose their tab in `group`. + * + * @param group - group index of the tabs. + * @param ids - buffer ids, in tab order. + */ + async function closeTabs(group: number, ids: readonly number[]): Promise { + if (closePrompt.value) { + return; + } + const last: number[] = []; + for (const id of ids) { + if (model.groupsOf(layout.value, id).some((g) => g !== group)) { + layout.value = model.removeTab(layout.value, group, id); + } else if (tabOf(id)) { + last.push(id); + } + } + await Promise.all(last.map((id) => settled(id))); + const dirty = last.filter((id) => tabOf(id)?.dirty === true); + if (dirty.length > 0) { + pendingClose = last; + closePrompt.value = { items: dirty.map((id) => ({ id, name: tabOf(id)?.name ?? "" })) }; + return; + } + await finishClose(last, false); + } + + /** + * Closes buffers through the engine; one that turns out to have unsaved + * changes leads to the close question for it. + * + * @param ids - buffer ids. + * @param force - discard unsaved changes. + */ + async function finishClose(ids: readonly number[], force: boolean): Promise { + const refused: number[] = []; + let error: EngineError | null = null; + for (const id of ids) { + const result = await closeBuffer(id, force); + if (!result.ok) { + if (result.error.code === "unsaved_changes") { + const tab = tabOf(id); + if (tab) { + tab.dirty = true; + refused.push(id); + } + } else { + error = result.error; + } + } + } + lastError.value = error; + if (refused.length > 0) { + pendingClose = refused; + closePrompt.value = { items: refused.map((id) => ({ id, name: tabOf(id)?.name ?? "" })) }; + } + } + + /** + * Closes one tab; a buffer with unsaved changes asks first, unless the + * other group still shows it. * * @param id - buffer id; the active tab when omitted. + * @param group - group index; the focused group if it shows the buffer, + * else the first that does. */ - async function requestClose(id: number | null = activeId.value): Promise { - if (id === null) { + async function requestClose(id: number | null = activeId.value, group?: number): Promise { + if (id === null || !tabOf(id)) { return; } - const tab = tabOf(id); - if (!tab) { + const where = model.groupsOf(layout.value, id); + const target = group ?? (where.includes(layout.value.focused) ? layout.value.focused : where[0]); + if (target === undefined) { + await closeTabs(layout.value.focused, [id]); return; } - await settled(id); - if (tab.dirty) { - closePrompt.value = { id, name: tab.name }; + await closeTabs(target, [id]); + } + + /** + * Runs a bulk close from a tab's context menu or the Window menu. + * + * @param action - which tabs. + * @param id - the tab the action starts from; the group's active tab + * when omitted. + * @param group - group index; the focused group when omitted. + */ + async function closeAction(action: CloseAction, id?: number | null, group?: number): Promise { + const index = model.groupIndex(layout.value, group); + const target = layout.value.groups[index]; + if (!target) { 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; - } + const from = id ?? target.activeId; + const ids = model.closeTargets(target, from, action, (buffer) => tabOf(buffer)?.dirty === true || syncs.get(buffer)?.pending === true); + await closeTabs(index, ids); } /** * Answers the pending close question. * - * @param choice - save and close, close without saving, or keep the tab. + * @param choice - save and close, close without saving, or keep the tabs. */ async function resolveClose(choice: CloseChoice): Promise { const prompt = closePrompt.value; + const ids = pendingClose; closePrompt.value = null; + pendingClose = []; if (!prompt || choice === "cancel") { return; } - if (choice === "save" && !(await save(prompt.id))) { + if (choice === "save") { + const failed = new Set(); + for (const item of prompt.items) { + if (!(await save(item.id))) { + failed.add(item.id); + } + } + const error = lastError.value; + await finishClose( + ids.filter((id) => !failed.has(id)), + false, + ); + if (failed.size > 0) { + lastError.value = error; + } return; } - const result = await closeBuffer(prompt.id, choice === "discard"); - lastError.value = result.ok ? null : result.error; + await finishClose(ids, true); } /** @@ -380,7 +776,7 @@ export const useEditorStore = defineStore("editor", () => { /** Saves every buffer after all local edits reached the engine. */ async function saveAll(): Promise { - await Promise.all(tabs.value.map((t) => settled(t.id))); + await Promise.all(records.value.map((t) => settled(t.id))); const result = await run<{ failed?: { id?: unknown; message?: unknown }[] }>( EDITOR_COMMANDS.saveAll, ); @@ -400,6 +796,127 @@ export const useEditorStore = defineStore("editor", () => { : null; } + /** + * Pins or unpins a tab. + * + * @param id - buffer id; the active tab when omitted. + * @param group - group index; the focused group when omitted. + * @param pinned - the new state; toggles when omitted. + */ + function setPinned(id?: number | null, group?: number, pinned?: boolean): void { + const index = model.groupIndex(layout.value, group); + const buffer = id ?? layout.value.groups[index]?.activeId ?? null; + const tab = layout.value.groups[index]?.tabs.find((p) => p.id === buffer); + if (buffer === null || !tab) { + return; + } + layout.value = model.setPinned(layout.value, index, buffer, pinned ?? !tab.pinned); + } + + /** + * Whether a tab is pinned. + * + * @param id - buffer id; the active tab when omitted. + * @param group - group index; the focused group when omitted. + */ + function isPinned(id?: number | null, group?: number): boolean { + const index = model.groupIndex(layout.value, group); + const buffer = id ?? layout.value.groups[index]?.activeId ?? null; + return layout.value.groups[index]?.tabs.find((p) => p.id === buffer)?.pinned === true; + } + + /** + * Whether a tab is a preview tab. + * + * @param id - buffer id; the active tab when omitted. + * @param group - group index; the focused group when omitted. + */ + function isPreview(id?: number | null, group?: number): boolean { + const index = model.groupIndex(layout.value, group); + const buffer = id ?? layout.value.groups[index]?.activeId ?? null; + return layout.value.groups[index]?.tabs.find((p) => p.id === buffer)?.preview === true; + } + + /** + * Makes a preview tab permanent ("Keep open", a double click). + * + * @param id - buffer id; the active tab when omitted. + * @param group - group index; the focused group when omitted. + */ + function keepOpen(id?: number | null, group?: number): void { + const index = model.groupIndex(layout.value, group); + const buffer = id ?? layout.value.groups[index]?.activeId ?? null; + if (buffer !== null) { + layout.value = model.keepOpen(layout.value, buffer, index); + } + } + + /** + * Splits the editor area; the active tab opens in the other group too. + * + * @param direction - where the other group sits. + */ + function split(direction: SplitOrientation): void { + layout.value = model.split(layout.value, direction); + } + + /** + * Moves a tab to the other group (splitting first when there is one). + * + * @param id - buffer id; the active tab when omitted. + * @param group - group index; the focused group when omitted. + */ + function moveToOtherGroup(id?: number | null, group?: number): void { + const index = model.groupIndex(layout.value, group); + const buffer = id ?? layout.value.groups[index]?.activeId ?? null; + if (buffer !== null) { + layout.value = model.moveToOtherGroup(layout.value, index, buffer); + } + } + + /** Focuses the other group, if there is one. */ + function focusOtherGroup(): void { + const other = model.otherGroup(layout.value); + if (other !== null) { + focusGroup(other); + views.get(other)?.focus(); + } + } + + /** Joins both groups into the focused one. */ + function unsplit(): void { + layout.value = model.unsplit(layout.value); + } + + /** + * Reopens the most recently closed tab where it was, with its selection + * and scroll position. + * + * @returns the buffer id, or null when nothing was reopened. + */ + async function reopenClosed(): Promise { + const entry = closed.value[closed.value.length - 1]; + if (!entry) { + return null; + } + closed.value = closed.value.slice(0, -1); + const group = Math.min(entry.group, layout.value.groups.length - 1); + const id = await openFile(entry.path, { group, index: entry.index, pinned: entry.pinned }); + const sync = id === null ? undefined : syncs.get(id); + if (!sync) { + return id; + } + const length = sync.state.doc.length; + const clamp = (pos: number): number => Math.min(Math.max(pos, 0), length); + const top = entry.top === null ? null : clamp(entry.top); + sync.dispatch({ + selection: { anchor: clamp(entry.anchor), head: clamp(entry.head) }, + effects: EditorView.scrollIntoView(top ?? clamp(entry.head), { y: top === null ? "center" : "start" }), + userEvent: "select.reopen", + }); + return id; + } + /** * Hides a tab's notice. * @@ -414,13 +931,84 @@ export const useEditorStore = defineStore("editor", () => { /** Drops every tab (the project closed or changed). */ function clear(): void { + persisting = false; + if (persistTimer !== null) { + clearTimeout(persistTimer); + persistTimer = null; + } for (const sync of syncs.values()) { sync.dispose(); } syncs.clear(); - tabs.value = []; - activeId.value = null; + records.value = []; + layout.value = model.emptyLayout(); + closed.value = []; closePrompt.value = null; + pendingClose = []; + } + + /** Stores the layout of the open project now. */ + async function persistNow(): Promise { + persistTimer = null; + if (!persisting) { + return; + } + const stored = model.toStored(layout.value, (id) => tabOf(id)?.path); + const result = await run(EDITOR_COMMANDS.layoutSet, { layout: stored }); + if (!result.ok && result.error.code !== "disabled") { + lastError.value = result.error; + } + } + + /** Stores the layout soon, once changes stopped for a moment. */ + function schedulePersist(): void { + if (!persisting) { + return; + } + if (persistTimer !== null) { + clearTimeout(persistTimer); + } + persistTimer = setTimeout(() => { + void persistNow(); + }, PERSIST_DELAY_MS); + } + + watch(layout, schedulePersist); + + /** + * Restores the stored layout of a project that just opened: reopens its + * files group by group, skipping files that are gone, then stores + * changes again. Tabs of buffers that opened meanwhile (crash recovery) + * stay. + */ + async function restoreLayout(): Promise { + const result = await run<{ layout?: unknown }>(EDITOR_COMMANDS.layoutGet); + const stored = result.ok ? model.parseStored(result.value.layout) : null; + if (stored && stored.groups.length > 0) { + const base = layout.value; + const groupsNeeded = Math.max(stored.groups.length, base.groups.length); + const extra = Array.from({ length: groupsNeeded - base.groups.length }, () => ({ tabs: [], activeId: null })); + layout.value = { ...base, groups: [...base.groups, ...extra], orientation: stored.orientation }; + for (const [group, storedGroup] of stored.groups.entries()) { + for (const tab of storedGroup.tabs) { + await openFile(tab.path, { group, activate: false, pinned: tab.pinned, preview: tab.preview }); + lastError.value = null; + } + const active = storedGroup.active === null ? undefined : tabOfPath(storedGroup.active); + if (active) { + layout.value = model.activateTab(layout.value, group, active.id); + } + } + const focusedActive = layout.value.groups[stored.focused]?.activeId; + if (focusedActive !== undefined && focusedActive !== null) { + layout.value = model.activateTab(layout.value, stored.focused, focusedActive); + } + const emptied = layout.value.groups.findIndex((g) => g.tabs.length === 0); + if (emptied >= 0 && layout.value.groups.length > 1) { + layout.value = model.unsplit(model.focusGroup(layout.value, emptied === 0 ? 1 : 0)); + } + } + persisting = true; } /** Adoptions of `bufferOpened` buffers still fetching their state. */ @@ -466,7 +1054,8 @@ export const useEditorStore = defineStore("editor", () => { */ function focusOpened(id: number): void { ++openSequence; - activate(id); + ensurePlaced(id); + activateAnywhere(id); } /** @@ -477,6 +1066,9 @@ export const useEditorStore = defineStore("editor", () => { function handleEvent(event: EditorEvent): void { switch (event.kind) { case "projectOpened": + clear(); + void restoreLayout(); + break; case "projectClosed": clear(); break; @@ -496,11 +1088,16 @@ export const useEditorStore = defineStore("editor", () => { const tab = tabOf(event.id); if (tab) { tab.dirty = event.dirty; + if (event.dirty) { + layout.value = model.keepOpen(layout.value, event.id); + } } break; } case "bufferClosed": - removeTab(event.id); + if (tabOf(event.id)) { + removeTab(event.id); + } break; case "fileChangedOnDisk": { const tab = tabOf(event.id); @@ -536,22 +1133,42 @@ export const useEditorStore = defineStore("editor", () => { return { tabs, + groups, + focusedGroup, + orientation, + canReopen, activeId, activeTab, adopted, closePrompt, lastError, lastOpen, + tabOf, + tabOfPath, syncOf, + reloadBuffer, configure, + registerView, + adopt, openFile, activate, + focusGroup, requestClose, + closeAction, resolveClose, save, saveAll, settleAll, hasUnsaved, + setPinned, + isPinned, + isPreview, + keepOpen, + split, + moveToOtherGroup, + focusOtherGroup, + unsplit, + reopenClosed, dismissNotice, markShown, handleEvent, diff --git a/ui/tests/commands/modals.test.ts b/ui/tests/commands/modals.test.ts index a08b66c..1083620 100644 --- a/ui/tests/commands/modals.test.ts +++ b/ui/tests/commands/modals.test.ts @@ -180,7 +180,7 @@ describe("one modal at a time", () => { await mountApp(); const editor = useEditorStore(pinia); await uiCommand("palette.open"); - editor.closePrompt = { id: 1, name: "a.php" }; + editor.closePrompt = { items: [{ id: 1, name: "a.php" }] }; await flushPromises(); expect(paletteShown()).toBe(false); expect(useModalsStore(pinia).current).toBe("closePrompt"); diff --git a/ui/tests/editor/tabModel.test.ts b/ui/tests/editor/tabModel.test.ts new file mode 100644 index 0000000..751fb49 --- /dev/null +++ b/ui/tests/editor/tabModel.test.ts @@ -0,0 +1,262 @@ +/** + * Tests for the pure tab layout (C10 A1, `components/editor/tabs/model.ts`): + * preview replacement, pinning, bulk close targets, splitting, moving and + * joining groups, the stored layout and the reopen stack. + */ +import { describe, expect, it } from "vitest"; +import { + activeBuffer, + closeTargets, + emptyLayout, + groupsOf, + keepOpen, + MAX_CLOSED, + moveToOtherGroup, + parseStored, + placeTab, + pushClosed, + removeBuffer, + removeTab, + setPinned, + split, + toStored, + unsplit, + type ClosedTab, + type TabLayout, +} from "../../src/components/editor/tabs/model"; + +/** + * A one-group layout with permanent tabs for the ids, the last one active. + * + * @param ids - buffer ids in order. + */ +function withTabs(...ids: number[]): TabLayout { + let layout = emptyLayout(); + for (const id of ids) { + layout = placeTab(layout, 0, id, { preview: false, activate: true }).layout; + } + return layout; +} + +/** + * The buffer ids of a group in order. + * + * @param layout - the layout. + * @param group - group index. + */ +function ids(layout: TabLayout, group = 0): number[] { + return layout.groups[group]?.tabs.map((t) => t.id) ?? []; +} + +describe("placing tabs", () => { + it("inserts after the active tab and activates", () => { + let layout = withTabs(1, 2, 3); + layout = placeTab(layout, 0, 1, { preview: false, activate: true }).layout; + layout = placeTab(layout, 0, 4, { preview: false, activate: true }).layout; + expect(ids(layout)).toEqual([1, 4, 2, 3]); + expect(activeBuffer(layout)).toBe(4); + }); + + it("replaces the one preview tab in place and reports it", () => { + let layout = withTabs(1, 2); + layout = placeTab(layout, 0, 1, { preview: false, activate: true }).layout; + let result = placeTab(layout, 0, 5, { preview: true, activate: true }); + expect(result.replaced).toBeNull(); + layout = placeTab(result.layout, 0, 2, { preview: false, activate: true }).layout; + result = placeTab(layout, 0, 6, { preview: true, activate: true }); + expect(result.replaced).toBe(5); + expect(ids(result.layout)).toEqual([1, 6, 2]); + expect(result.layout.groups[0]?.tabs.filter((t) => t.preview).map((t) => t.id)).toEqual([6]); + }); + + it("opening a preview for good, or keeping it open, makes it permanent", () => { + let layout = placeTab(emptyLayout(), 0, 1, { preview: true, activate: true }).layout; + expect(placeTab(layout, 0, 1, { preview: true, activate: true }).layout.groups[0]?.tabs[0]?.preview).toBe(true); + expect(placeTab(layout, 0, 1, { preview: false, activate: true }).layout.groups[0]?.tabs[0]?.preview).toBe(false); + layout = keepOpen(layout, 1); + expect(placeTab(layout, 0, 2, { preview: true, activate: true }).replaced).toBeNull(); + }); + + it("never puts an unpinned tab before a pinned one", () => { + let layout = withTabs(1, 2); + layout = setPinned(layout, 0, 2, true); + expect(ids(layout)).toEqual([2, 1]); + layout = placeTab(layout, 0, 3, { preview: false, activate: true, index: 0 }).layout; + expect(ids(layout)).toEqual([2, 3, 1]); + }); + + it("leaves the input layout alone", () => { + const layout = withTabs(1); + placeTab(layout, 0, 2, { preview: false, activate: true }); + expect(ids(layout)).toEqual([1]); + }); +}); + +describe("pinning", () => { + it("moves a pinned tab to the end of the pinned block and back", () => { + let layout = withTabs(1, 2, 3); + layout = setPinned(layout, 0, 3, true); + layout = setPinned(layout, 0, 2, true); + expect(ids(layout)).toEqual([3, 2, 1]); + layout = setPinned(layout, 0, 3, false); + expect(ids(layout)).toEqual([2, 3, 1]); + }); + + it("keeps a pinned preview open", () => { + const layout = setPinned(placeTab(emptyLayout(), 0, 1, { preview: true, activate: true }).layout, 0, 1, true); + expect(layout.groups[0]?.tabs[0]).toEqual({ id: 1, pinned: true, preview: false }); + }); +}); + +describe("close targets", () => { + const layout = setPinned(withTabs(1, 2, 3, 4, 5), 0, 1, true); + const group = layout.groups[0]; + const dirty = (id: number): boolean => id === 4; + + it("leave pinned tabs out of every bulk close", () => { + expect(group && closeTargets(group, 3, "others", dirty)).toEqual([2, 4, 5]); + expect(group && closeTargets(group, 3, "all", dirty)).toEqual([2, 3, 4, 5]); + expect(group && closeTargets(group, 3, "left", dirty)).toEqual([2]); + expect(group && closeTargets(group, 3, "right", dirty)).toEqual([4, 5]); + expect(group && closeTargets(group, null, "unmodified", dirty)).toEqual([2, 3, 5]); + }); + + it("close nothing left or right of a tab the group lacks", () => { + expect(group && closeTargets(group, 99, "left", dirty)).toEqual([]); + expect(group && closeTargets(group, 99, "right", dirty)).toEqual([]); + }); +}); + +describe("removing tabs", () => { + it("activates the right neighbour, else the left one", () => { + let layout = withTabs(1, 2, 3); + layout = placeTab(layout, 0, 2, { preview: false, activate: true }).layout; + layout = removeTab(layout, 0, 2); + expect(activeBuffer(layout)).toBe(3); + layout = removeTab(layout, 0, 3); + expect(activeBuffer(layout)).toBe(1); + layout = removeTab(layout, 0, 1); + expect(activeBuffer(layout)).toBeNull(); + expect(layout.groups).toHaveLength(1); + }); +}); + +describe("groups", () => { + it("split shows the active tab in a new focused group, at most two groups", () => { + let layout = split(withTabs(1, 2), "right"); + expect(layout.groups).toHaveLength(2); + expect(layout.focused).toBe(1); + expect(ids(layout, 1)).toEqual([2]); + expect(groupsOf(layout, 2)).toEqual([0, 1]); + layout = placeTab(layout, 1, 3, { preview: false, activate: true }).layout; + layout = split(layout, "down"); + expect(layout.groups).toHaveLength(2); + expect(layout.orientation).toBe("down"); + expect(layout.focused).toBe(0); + expect(ids(layout, 0)).toEqual([1, 2, 3]); + }); + + it("an emptied group goes away and the focus stays valid", () => { + let layout = split(withTabs(1, 2), "right"); + layout = removeTab(layout, 1, 2); + expect(layout.groups).toHaveLength(1); + expect(layout.focused).toBe(0); + expect(ids(layout)).toEqual([1, 2]); + }); + + it("closing a buffer removes it from both groups", () => { + const layout = removeBuffer(split(withTabs(1, 2), "right"), 2); + expect(layout.groups).toHaveLength(1); + expect(ids(layout)).toEqual([1]); + }); + + it("moving a tab splits when needed and takes it out of its group", () => { + let layout = moveToOtherGroup(withTabs(1, 2), 0, 2); + expect(ids(layout, 0)).toEqual([1]); + expect(ids(layout, 1)).toEqual([2]); + expect(layout.focused).toBe(1); + layout = moveToOtherGroup(layout, 1, 2); + expect(layout.groups).toHaveLength(1); + expect(ids(layout)).toEqual([1, 2]); + expect(moveToOtherGroup(withTabs(1), 0, 1)).toEqual(withTabs(1)); + }); + + it("unsplit joins the other group's tabs into the focused one", () => { + let layout = split(withTabs(1, 2), "right"); + layout = placeTab(layout, 1, 3, { preview: true, activate: true }).layout; + layout = unsplit(layout); + expect(layout.groups).toHaveLength(1); + expect(ids(layout)).toEqual([2, 3, 1]); + expect(layout.groups[0]?.tabs.map((t) => t.preview)).toEqual([false, true, false]); + }); +}); + +describe("stored layout", () => { + it("round-trips groups, pins, previews and the active tabs by path", () => { + let layout = split(setPinned(withTabs(1, 2), 0, 2, true), "down"); + layout = placeTab(layout, 1, 3, { preview: true, activate: true }).layout; + const paths: Record = { 1: "a.php", 2: "b.php", 3: "c.php" }; + const stored = toStored(layout, (id) => paths[id]); + expect(stored).toEqual({ + version: 1, + focused: 1, + orientation: "down", + groups: [ + { tabs: [{ path: "b.php", pinned: true, preview: false }, { path: "a.php", pinned: false, preview: false }], active: "b.php" }, + { tabs: [{ path: "b.php", pinned: false, preview: false }, { path: "c.php", pinned: false, preview: true }], active: "c.php" }, + ], + }); + expect(parseStored(JSON.parse(JSON.stringify(stored)))).toEqual(stored); + }); + + it("reads untrusted values defensively", () => { + for (const bad of [null, 1, "x", [], {}, { version: 2, groups: [] }, { version: 1, groups: "x" }]) { + expect(parseStored(bad)).toBeNull(); + } + const parsed = parseStored({ + version: 1, + focused: 7, + orientation: "diagonal", + groups: [ + { tabs: [{ path: "a" }, { path: "a" }, { path: "" }, 3, null, { path: "p", pinned: true, preview: true }], active: "nope" }, + null, + { tabs: [] }, + { tabs: [{ path: "c" }] }, + ], + }); + expect(parsed).toEqual({ + version: 1, + focused: 0, + orientation: "right", + groups: [{ tabs: [{ path: "p", pinned: true, preview: false }, { path: "a", pinned: false, preview: false }], active: "p" }], + }); + }); + + it("caps the number of stored tabs", () => { + const tabs = Array.from({ length: 500 }, (_, i) => ({ path: `f${String(i)}.php` })); + expect(parseStored({ version: 1, groups: [{ tabs }] })?.groups[0]?.tabs).toHaveLength(200); + }); +}); + +describe("reopen stack", () => { + /** + * A closed tab entry. + * + * @param path - its path. + */ + function entry(path: string): ClosedTab { + return { path, group: 0, index: 0, pinned: false, anchor: 0, head: 0, top: null }; + } + + it("keeps one entry per path, newest last, and caps its size", () => { + let stack = pushClosed([], entry("a")); + stack = pushClosed(stack, entry("b")); + stack = pushClosed(stack, entry("a")); + expect(stack.map((e) => e.path)).toEqual(["b", "a"]); + for (let i = 0; i < 50; i++) { + stack = pushClosed(stack, entry(String(i))); + } + expect(stack).toHaveLength(MAX_CLOSED); + expect(stack[stack.length - 1]?.path).toBe("49"); + }); +}); diff --git a/ui/tests/editor/tabs.test.ts b/ui/tests/editor/tabs.test.ts new file mode 100644 index 0000000..54ed32b --- /dev/null +++ b/ui/tests/editor/tabs.test.ts @@ -0,0 +1,573 @@ +/** + * Tests for tab management in the editor area (C10 A1): preview tabs from + * the project tree and their setting, pinning, bulk closes with one + * question for every unsaved file, the context menu, reopening a closed + * tab with its selection, splitting with one shared buffer, the stored + * layout per project and the public API for other areas. The engine is a + * fake behind the mocked Tauri `invoke`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { EditorView, runScopeHandlers } from "@codemirror/view"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { useCommandsStore } from "../../src/commands/store"; +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 { COMMAND_IDS } from "../../src/components/editor/tabs/commands"; +import { PREVIEW_SETTING, useEditorStore } from "../../src/stores/editor"; +import { useSettingsStore } from "../../src/stores/settings"; + +/** 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 }[]; +/** What `layout.get` returns. */ +let storedLayout: unknown; +/** Pinia of the current test. */ +let pinia: Pinia; +/** Mounted components to unmount after each test. */ +let mounted: VueWrapper[] = []; + +/** + * 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"); + } + 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; + 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 "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 "layout.get": + return Promise.resolve({ layout: storedLayout }); + case "layout.set": + return Promise.resolve({ stored: true }); + 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); + } +} + +/** + * jsdom has no layout; CodeMirror measures text ranges, so give ranges + * empty rectangles. + */ +function stubRangeGeometry(): void { + const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null }); + Range.prototype.getClientRects = empty; + Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0); +} + +/** Fresh Pinia and a fake engine with four files on its disk. */ +function resetFakeEngine(): void { + stubRangeGeometry(); + pinia = createPinia(); + setActivePinia(pinia); + buffers = new Map(); + disk = { "a.php": " }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([]); + } + 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}`)); + }); +} + +beforeEach(resetFakeEngine); + +afterEach(async () => { + await flushPromises(); + useCommandsStore(pinia).stop(); + for (const wrapper of mounted) { + wrapper.unmount(); + } + mounted = []; + vi.useRealTimers(); +}); + +/** Mounts the editor area and starts the command store. */ +async function mountArea(): Promise { + await useCommandsStore(pinia).start(); + const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await flushPromises(); + return wrapper; +} + +/** Mounts the project tree with the fake project open. */ +async function mountTree(): Promise { + const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(tree); + emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); + await flushPromises(); + return tree; +} + +/** + * Names on the tab bar of a group, `*` marking previews and `^` pins. + * + * @param area - the mounted area. + * @param group - group index. + */ +function tabNames(area: VueWrapper, group = 0): string[] { + return area.findAll(`[data-test=editor-tabs][data-group='${String(group)}'] [data-test=editor-tab]`).map((tab) => { + const name = tab.find(".tabs__name").text(); + return `${tab.attributes("data-pinned") ? "^" : ""}${name}${tab.attributes("data-preview") ? "*" : ""}`; + }); +} + +/** + * The CodeMirror view of a group. + * + * @param area - the mounted area. + * @param group - group index. + */ +function viewOf(area: VueWrapper, group = 0): EditorView { + const el = area.find(`[data-test=code-editor][data-group='${String(group)}'] .cm-editor`).element; + const view = EditorView.findFromDOM(el as HTMLElement); + if (!view) { + throw new Error("no editor view"); + } + return view; +} + +/** + * Opens files permanently, in order. + * + * @param paths - project-relative paths. + */ +async function openAll(...paths: string[]): Promise { + const editor = useEditorStore(pinia); + for (const path of paths) { + await editor.openFile(path); + } + await flushPromises(); +} + +/** + * Makes a buffer dirty through its view. + * + * @param area - the mounted area. + * @param path - file to edit (activated first). + */ +async function makeDirty(area: VueWrapper, path: string): Promise { + const editor = useEditorStore(pinia); + await editor.openFile(path); + await flushPromises(); + viewOf(area).dispatch({ changes: { from: 0, insert: "x" } }); + await flushPromises(); +} + +/** + * Mounts the area and the tree once and opens a file, so the cold start of + * the first CodeMirror view and the first render (seconds under load) is + * not paid inside the first test's time budget (see `EditorArea.test.ts`). + */ +beforeAll(async () => { + resetFakeEngine(); + const area = await mountArea(); + const tree = await mountTree(); + await tree.find("[data-path='a.php']").trigger("dblclick"); + await flushPromises(); + expect(area.find(".cm-editor").exists()).toBe(true); + useCommandsStore(pinia).stop(); + for (const wrapper of mounted) { + wrapper.unmount(); + } + mounted = []; +}, 30_000); + +describe("preview tabs", () => { + it("a single click opens a preview that the next one replaces; a double click keeps it", async () => { + const area = await mountArea(); + const tree = await mountTree(); + await tree.find("[data-path='a.php']").trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php*"]); + expect(area.find("[data-test=editor-tab] .tabs__name").element.closest(".tabs__tab--preview")).not.toBeNull(); + await tree.find("[data-path='b.php']").trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual(["b.php*"]); + expect(calls.filter((c) => c.command === "buffer.close").map((c) => c.params)).toEqual([{ id: 1, force: false }]); + await tree.find("[data-path='b.php']").trigger("dblclick"); + await flushPromises(); + await tree.find("[data-path='c.php']").trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual(["b.php", "c.php*"]); + await area.findAll("[data-test=editor-tab]")[1]?.trigger("dblclick"); + expect(tabNames(area)).toEqual(["b.php", "c.php"]); + }); + + it("editing a preview keeps it open", async () => { + const area = await mountArea(); + const editor = useEditorStore(pinia); + await editor.openFile("a.php", { preview: true }); + await flushPromises(); + viewOf(area).dispatch({ changes: { from: 0, insert: "x" } }); + await flushPromises(); + await editor.openFile("b.php", { preview: true }); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php", "b.php*"]); + }); + + it("the setting turns previews off", async () => { + const area = await mountArea(); + useSettingsStore(pinia).values[PREVIEW_SETTING] = false; + const editor = useEditorStore(pinia); + await editor.openFile("a.php", { preview: true }); + await editor.openFile("b.php", { preview: true }); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php", "b.php"]); + }); +}); + +describe("pinning and closing", () => { + it("pinned tabs sit left with a pin and survive close others and close all", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php", "c.php"); + const commands = useCommandsStore(pinia); + await commands.execute(COMMAND_IDS.togglePin, { id: 3 }); + await flushPromises(); + expect(tabNames(area)).toEqual(["^c.php", "a.php", "b.php"]); + expect(area.findAll("[data-test=tab-pin]")).toHaveLength(1); + await commands.execute(COMMAND_IDS.closeOthers, { id: 1 }); + await flushPromises(); + expect(tabNames(area)).toEqual(["^c.php", "a.php"]); + await commands.execute(COMMAND_IDS.closeAll); + await flushPromises(); + expect(tabNames(area)).toEqual(["^c.php"]); + }); + + it("closes to the left, to the right and the unmodified tabs", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php", "c.php", "d.php"); + const editor = useEditorStore(pinia); + await editor.closeAction("right", 3); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]); + await editor.closeAction("left", 2); + await flushPromises(); + expect(tabNames(area)).toEqual(["b.php", "c.php"]); + await makeDirty(area, "c.php"); + await editor.closeAction("unmodified"); + await flushPromises(); + expect(tabNames(area)).toEqual(["c.php"]); + }); + + it("asks once for every unsaved file and saves them all", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php", "c.php"); + await makeDirty(area, "a.php"); + await makeDirty(area, "b.php"); + const editor = useEditorStore(pinia); + await editor.closeAction("all"); + await flushPromises(); + expect(editor.closePrompt?.items.map((i) => i.name)).toEqual(["a.php", "b.php"]); + expect(area.findAll("[data-test=close-list] li").map((li) => li.text())).toEqual(["a.php", "b.php"]); + expect(area.get("[data-test=close-save]").text()).toBe("Save All"); + await area.get("[data-test=close-cancel]").trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]); + await editor.closeAction("all"); + await flushPromises(); + await area.get("[data-test=close-save]").trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual([]); + expect(disk["a.php"]?.startsWith("x")).toBe(true); + expect(disk["b.php"]?.startsWith("x")).toBe(true); + }); + + it("discards every unsaved file with Don't Save", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php"); + await makeDirty(area, "a.php"); + const editor = useEditorStore(pinia); + await editor.closeAction("all"); + await flushPromises(); + expect(area.find("[data-test=close-list]").exists()).toBe(false); + await area.get("[data-test=close-discard]").trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual([]); + expect(disk["a.php"]).toBe(" c.command === "buffer.close").map((c) => c.params.force)).toEqual([true, true]); + }); + + it("the context menu runs the tab commands for its tab", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php", "c.php"); + await area.findAll("[data-test=editor-tab]")[1]?.trigger("contextmenu", { clientX: 10, clientY: 10 }); + const items = area.findAll("[data-test=tab-menu-item]").map((i) => i.attributes("data-item")); + expect(items).toEqual([ + "close", + COMMAND_IDS.closeOthers, + COMMAND_IDS.closeAll, + COMMAND_IDS.closeLeft, + COMMAND_IDS.closeRight, + COMMAND_IDS.closeUnmodified, + COMMAND_IDS.reopenClosed, + "pin", + COMMAND_IDS.splitRight, + COMMAND_IDS.splitDown, + COMMAND_IDS.moveToOtherGroup, + ]); + await area.get(`[data-item='${COMMAND_IDS.closeOthers}']`).trigger("click"); + await flushPromises(); + expect(tabNames(area)).toEqual(["b.php"]); + expect(area.find("[data-test=tab-menu]").exists()).toBe(false); + }); +}); + +describe("tab context menu and local history", () => { + it("shows Show Local History only while history.show exists and runs it with the path", async () => { + const area = await mountArea(); + await openAll("a.php"); + await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 }); + expect(area.find("[data-item='history.show']").exists()).toBe(false); + await area.get("[data-test=tab-menu]").trigger("keydown", { key: "Escape" }); + const shown: unknown[] = []; + useCommandsStore(pinia).provide("history.show", { run: (params) => void shown.push(params) }); + await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 }); + await area.get("[data-item='history.show']").trigger("click"); + await flushPromises(); + expect(shown).toEqual([{ path: "a.php" }]); + }); +}); + +describe("reopen closed tab", () => { + it("reopens the last closed tab at its place with its selection", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php", "c.php"); + const editor = useEditorStore(pinia); + editor.activate(2); + await flushPromises(); + viewOf(area).dispatch({ selection: { anchor: 3, head: 7 } }); + expect(editor.canReopen).toBe(false); + await editor.requestClose(2); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php", "c.php"]); + await useCommandsStore(pinia).execute(COMMAND_IDS.reopenClosed); + await flushPromises(); + expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]); + const selection = viewOf(area).state.selection.main; + expect([selection.anchor, selection.head]).toEqual([3, 7]); + expect(editor.canReopen).toBe(false); + }); +}); + +describe("split", () => { + it("shows the same buffer in two groups with one text and one undo history", async () => { + const area = await mountArea(); + await openAll("a.php", "b.php"); + const editor = useEditorStore(pinia); + await useCommandsStore(pinia).execute(COMMAND_IDS.splitRight); + await flushPromises(); + expect(area.findAll("[data-test=editor-pane]")).toHaveLength(2); + expect(tabNames(area, 0)).toEqual(["a.php", "b.php"]); + expect(tabNames(area, 1)).toEqual(["b.php"]); + expect(editor.focusedGroup).toBe(1); + viewOf(area, 1).dispatch({ changes: { from: 0, insert: "// " } }); + await flushPromises(); + expect(viewOf(area, 0).state.doc.toString()).toBe("// { + const area = await mountArea(); + await openAll("a.php", "b.php", "c.php"); + const editor = useEditorStore(pinia); + const commands = useCommandsStore(pinia); + await commands.execute(COMMAND_IDS.moveToOtherGroup, { id: 1 }); + await flushPromises(); + expect(tabNames(area, 0)).toEqual(["b.php", "c.php"]); + expect(tabNames(area, 1)).toEqual(["a.php"]); + await commands.execute(COMMAND_IDS.focusOtherGroup); + expect(editor.focusedGroup).toBe(0); + await commands.execute(COMMAND_IDS.splitDown); + await flushPromises(); + expect(area.find(".editor-area__groups--down").exists()).toBe(true); + await commands.execute(COMMAND_IDS.unsplit); + await flushPromises(); + expect(area.findAll("[data-test=editor-pane]")).toHaveLength(1); + }); + + it("closing a tab the other group still shows keeps the buffer", async () => { + const area = await mountArea(); + await openAll("a.php"); + const editor = useEditorStore(pinia); + editor.split("right"); + await flushPromises(); + await makeDirty(area, "a.php"); + await editor.requestClose(1, 1); + await flushPromises(); + expect(editor.closePrompt).toBeNull(); + expect(calls.some((c) => c.command === "buffer.close")).toBe(false); + expect(area.findAll("[data-test=editor-pane]")).toHaveLength(1); + }); +}); + +describe("stored layout", () => { + it("stores changes through layout.set and restores the layout when the project opens", async () => { + storedLayout = { + version: 1, + focused: 1, + orientation: "down", + groups: [ + { tabs: [{ path: "b.php", pinned: true }, { path: "gone.php" }, { path: "a.php" }], active: "a.php" }, + { tabs: [{ path: "c.php", preview: true }], active: "c.php" }, + ], + }; + const area = await mountArea(); + emitEditorEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); + await flushPromises(); + await flushPromises(); + expect(tabNames(area, 0)).toEqual(["^b.php", "a.php"]); + expect(tabNames(area, 1)).toEqual(["c.php*"]); + expect(area.find(".editor-area__groups--down").exists()).toBe(true); + const editor = useEditorStore(pinia); + expect(editor.focusedGroup).toBe(1); + expect(editor.groups[0]?.activeId).toBe(editor.tabOfPath("a.php")?.id); + expect(calls.some((c) => c.command === "layout.set")).toBe(false); + vi.useFakeTimers(); + editor.unsplit(); + await vi.advanceTimersByTimeAsync(400); + const set = calls.filter((c) => c.command === "layout.set"); + expect(set).toHaveLength(1); + expect((set[0]?.params.layout as { groups: unknown[] }).groups).toHaveLength(1); + }); + + it("does not store the empty layout of a closing project", async () => { + await mountArea(); + emitEditorEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); + await flushPromises(); + await openAll("a.php"); + vi.useFakeTimers(); + emitEditorEvent({ kind: "projectClosed" }); + await vi.advanceTimersByTimeAsync(400); + expect(calls.filter((c) => c.command === "layout.set")).toHaveLength(0); + }); +}); + +describe("public API", () => { + it("finds the tab of a path and reloads a buffer from the engine", async () => { + const area = await mountArea(); + await openAll("a.php"); + const editor = useEditorStore(pinia); + expect(editor.tabOfPath("a.php")?.id).toBe(1); + expect(editor.tabOfPath("nope.php")).toBeUndefined(); + const buffer = buffers.get(1); + if (buffer) { + buffer.text = "reloaded\n"; + buffer.version += 1; + } + expect(editor.reloadBuffer(1)).toBe(true); + await flushPromises(); + expect(viewOf(area).state.doc.toString()).toBe("reloaded\n"); + expect(editor.reloadBuffer(99)).toBe(false); + }); +}); diff --git a/ui/tests/find/FindToolWindow.test.ts b/ui/tests/find/FindToolWindow.test.ts index b8157dd..5dc48a7 100644 --- a/ui/tests/find/FindToolWindow.test.ts +++ b/ui/tests/find/FindToolWindow.test.ts @@ -340,6 +340,7 @@ describe("find.open prefill", () => { const find = useFindStore(); const editor = (await import("../../src/stores/editor")).useEditorStore(); const state = EditorState.create({ doc: "echo productName;", selection: EditorSelection.single(8) }); + editor.tabs = [{ id: 1, path: "a.php", name: "a.php", dirty: false, notice: null }]; editor.activeId = 1; vi.spyOn(editor, "syncOf").mockReturnValue({ state } as unknown as ReturnType); find.query = "("; @@ -440,14 +441,14 @@ describe("Find tool window", () => { await list.trigger("keydown", { key: "ArrowDown" }); await list.trigger("keydown", { key: "Enter" }); await flushPromises(); - expect(reveals).toEqual([{ path: "a.php", line: 4, column: 4 }]); + expect(reveals).toEqual([{ path: "a.php", line: 4, column: 4, preview: true }]); await list.trigger("keydown", { key: "End" }); expect(wrapper.findAll("[data-test=find-row]")[2]?.attributes("aria-selected")).toBe("true"); await wrapper.findAll("[data-test=find-row]")[0]?.trigger("click"); await flushPromises(); expect(reveals).toEqual([ - { path: "a.php", line: 4, column: 4 }, - { path: "a.php", line: 0, column: 2 }, + { path: "a.php", line: 4, column: 4, preview: true }, + { path: "a.php", line: 0, column: 2, preview: true }, ]); }); diff --git a/ui/tests/goto/GotoPopup.test.ts b/ui/tests/goto/GotoPopup.test.ts index 4a3e3c2..3cca500 100644 --- a/ui/tests/goto/GotoPopup.test.ts +++ b/ui/tests/goto/GotoPopup.test.ts @@ -329,7 +329,7 @@ describe("keyboard and opening", () => { await press({ key: "ArrowDown" }); await press({ key: "Enter" }); expect(wrapper.find("[data-test=goto]").exists()).toBe(false); - expect(revealed).toEqual([{ path: "vendor/acme/User.php" }]); + expect(revealed).toEqual([{ path: "vendor/acme/User.php", preview: true }]); expect(document.activeElement?.id).toBe("host-button"); expect(useModalsStore(pinia).current).toBe(null); }); @@ -346,7 +346,7 @@ describe("keyboard and opening", () => { expect(rows(wrapper)).toEqual(["find | App\\User"]); expect(wrapper.findAll("mark").map((m) => m.text())).toEqual(["fi"]); await wrapper.find("[data-test=goto-row]").trigger("click"); - expect(revealed).toEqual([{ path: "src/User.php", line: 7, column: 20 }]); + expect(revealed).toEqual([{ path: "src/User.php", line: 7, column: 20, preview: true }]); }); it("switches modes with Tab and keeps the text", async () => { diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index 6d8ed65..73bb32b 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -254,7 +254,7 @@ describe("AppMenu", () => { expect(menuShown()).toBe(true); expect(menu.find("[data-test=menu-button]").attributes("aria-expanded")).toBe("true"); const headings = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => g.querySelector(".app-menu__heading")?.textContent.trim()); - expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Tools", "Help"]); + expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Tools", "Window", "Help"]); const listed = listing() as { id: string; menuPath: string | null }[]; const withPath = listed.filter((c) => c.menuPath !== null); expect([...itemIds()].sort()).toEqual(withPath.map((c) => c.id).sort()); diff --git a/ui/tests/structure/StructureToolWindow.test.ts b/ui/tests/structure/StructureToolWindow.test.ts index cfc8601..eea90b8 100644 --- a/ui/tests/structure/StructureToolWindow.test.ts +++ b/ui/tests/structure/StructureToolWindow.test.ts @@ -87,7 +87,7 @@ const SHOP = [ */ function openTab(id: number, path: string): void { const editor = useEditorStore(pinia); - editor.tabs.push({ id, path, name: path, dirty: false, notice: null }); + editor.tabs = [...editor.tabs, { id, path, name: path, dirty: false, notice: null }]; editor.activeId = id; }