M1.15: one modal at a time, restore dialog follows outside restores

- Modal rule (ui/src/commands/modals.ts): palette, settings dialog and the
  close question are exclusive; opening one closes the other. Running any
  command but palette.open (keyboard, palette, uiCommand) closes the
  palette. The restore dialog is queued: hidden while another modal is
  open, back with its list intact afterwards.
- recovery.restore / recovery.discard emit recoveryResolved {paths}; the
  restore dialog drops the settled paths and closes when none are left.
  Rust was needed: discard gave the UI no signal, and a restored entry
  stays in the journal as the buffer's own entry.
- Dimmed restored text (C2 screenshot 09) was the dialog overlay, not an
  editor style; no editor change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 21:49:38 +02:00
parent d12a517009
commit 1a38e68480
13 changed files with 442 additions and 12 deletions

View file

@ -47,6 +47,15 @@ pub fn infos(state: &mut State) -> Vec<EntryInfo> {
entries.iter().map(|e| journal::info(state, e)).collect()
}
/// Emits [`Event::RecoveryResolved`] for `paths`, unless there are none.
fn emit_resolved(state: &mut State, mut paths: Vec<String>) {
if paths.is_empty() {
return;
}
paths.sort();
state.emit(Event::RecoveryResolved { paths });
}
/// `recovery.list`: the unsaved texts the journal holds.
pub struct List;
@ -123,7 +132,7 @@ impl Command for Restore {
label: "Restore Unsaved Changes",
menu_path: None,
default_shortcut: None,
params: "{ paths?: [string] (all entries if missing) }; opens each file as a dirty buffer with the journal text, line ending and BOM; returns { restored: [{ path, id }], failed: [{ path, message }] }",
params: "{ paths?: [string] (all entries if missing) }; opens each file as a dirty buffer with the journal text, line ending and BOM; returns { restored: [{ path, id }], failed: [{ path, message }] }; emits recoveryResolved with the restored paths",
}
}
@ -139,13 +148,18 @@ impl Command for Restore {
.into_iter()
.map(|path| json!({ "path": path, "message": "no recovery entry" }))
.collect();
let mut resolved = Vec::new();
for entry in entries {
let path = entry.path.clone();
match restore(state, entry) {
Ok(id) => restored.push(json!({ "path": path, "id": id })),
Ok(id) => {
restored.push(json!({ "path": path, "id": id }));
resolved.push(path);
}
Err(e) => failed.push(json!({ "path": path, "message": e.to_string() })),
}
}
emit_resolved(state, resolved);
Ok(Outcome::value(
json!({ "restored": restored, "failed": failed }),
))
@ -162,7 +176,7 @@ impl Command for Discard {
label: "Discard Unsaved Changes",
menu_path: None,
default_shortcut: None,
params: "{ paths?: [string] (all entries if missing) }; deletes the journal entries; an open buffer with unsaved changes is journaled again; returns { discarded: [path] }",
params: "{ paths?: [string] (all entries if missing) }; deletes the journal entries; an open buffer with unsaved changes is journaled again; returns { discarded: [path] }; emits recoveryResolved with the discarded paths",
}
}
@ -186,6 +200,7 @@ impl Command for Discard {
discarded.push(entry.path);
}
}
emit_resolved(state, discarded.clone());
Ok(Outcome::value(json!({ "discarded": discarded })))
}
}

View file

@ -137,6 +137,13 @@ pub enum Event {
/// The params the command was run with, as given.
params: Value,
},
/// `recovery.restore` or `recovery.discard` settled journal entries:
/// they were restored into buffers or discarded, so a restore dialog
/// that still lists them drops them (M1.15).
RecoveryResolved {
/// Project-relative paths with `/`, sorted.
paths: Vec<String>,
},
}
/// Severity of an [`Event::Notification`].
@ -228,4 +235,15 @@ mod tests {
json!({"kind": "uiCommand", "id": "palette.open", "params": {}})
);
}
#[test]
fn recovery_resolved_shape() {
let e = Event::RecoveryResolved {
paths: vec!["src/a.php".into()],
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "recoveryResolved", "paths": ["src/a.php"]})
);
}
}

View file

@ -273,6 +273,50 @@ fn restore_reports_missing_entries_and_newer_unsaved_buffers() {
);
}
fn resolved_paths(events: &[Event]) -> Vec<Vec<String>> {
events
.iter()
.filter_map(|e| match e {
Event::RecoveryResolved { paths } => Some(paths.clone()),
_ => None,
})
.collect()
}
#[test]
fn restore_and_discard_emit_the_resolved_paths() {
let setup = Setup::new(&[("a.php", b"a"), ("b.php", b"b"), ("c.php", b"c")]);
let (mut engine, _) = setup.engine();
for path in ["a.php", "b.php", "c.php"] {
let id = open(&mut engine, path);
edit(&mut engine, id, 1, 1, "!");
}
engine.flush_journal().unwrap();
drop(engine);
let (mut engine, _) = setup.engine();
let c = open(&mut engine, "c.php");
edit(&mut engine, c, 0, 0, "newer");
let out = engine
.execute(
"recovery.restore",
json!({"paths": ["c.php", "a.php", "nope.php"]}),
)
.unwrap();
assert_eq!(resolved_paths(&out.events), vec![vec!["a.php".to_string()]]);
let out = engine
.execute("recovery.discard", json!({"paths": ["b.php"]}))
.unwrap();
assert_eq!(resolved_paths(&out.events), vec![vec!["b.php".to_string()]]);
let out = engine
.execute("recovery.discard", json!({"paths": ["nope.php"]}))
.unwrap();
assert!(
resolved_paths(&out.events).is_empty(),
"nothing settled, no event"
);
}
#[test]
fn disk_changes_after_the_entry_are_flagged() {
let setup = Setup::new(&[("a.php", b"a"), ("gone.php", b"g")]);

View file

@ -79,7 +79,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
### Events
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
@ -147,9 +147,9 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Storage:** `<data_dir>/recovery/<project-id>/<entry-id>.json`. The project id is the FNV-1a 64-bit hash of the canonical project root, the entry id the same hash of the project-relative path, each as 16 hex digits (FNV instead of `std`'s hasher, whose output may change between Rust versions). One file per dirty buffer: `{path, text, lineEnding, bom, savedAt}`; `text` is the buffer text as held in memory (mixed line breaks included), `lineEnding` the ending it saves with, `savedAt` milliseconds since the Unix epoch. Engines without a config (`Engine::new`) keep no journal. Code: `crates/engine/src/journal.rs`, commands in `cmd/recovery.rs`.
- **Writing:** `buffer.edit` only records the edit time. `Engine::pump_vfs` (the desktop's pump thread, every 100 ms) writes a buffer once it has been idle for 1 s, or 2 s after its first unwritten edit while typing continues, so an entry is on disk at most ~1.1 s after the last edit and never per keystroke. Writes use `lutra_vfs::write_atomic`. `Engine::flush_journal()` writes everything now (tests, hosts about to stop). Cost for a 1 MiB buffer (measured on Windows 11, `journal_write_cost_for_a_one_megabyte_buffer`): median 8.5 ms in a release build, 67 ms in a debug build, under the engine lock; a keystroke arriving meanwhile waits that long. Moving the write to a background thread is a follow-up if large files make it noticeable.
- **Removal:** `file.save`/`file.saveAll`, `buffer.close` (also `force`), `project.close`/`project.open` with `force` and `recovery.discard` remove entries. Save and close remove only entries this session wrote or restored; entries left by a crashed session stay until restored or discarded. Editing such a file without restoring it overwrites its entry.
- **Commands and event:** after `project.open`, `recoveryAvailable {entries: [{path, savedAt, diskChanged}]}` when the journal is not empty. `recovery.list` → `{entries}`; `recovery.restore {paths?}` → `{restored: [{path, id}], failed: [{path, message}]}` opens each file as a dirty buffer (version 1, saved version 0) with the journal text, line ending and BOM, or puts the text into a clean open buffer; a buffer with unsaved changes is newer than the journal and is left alone (`failed`); a file gone from disk is restored too and saving recreates it. `recovery.discard {paths?}` → `{discarded}`; a discarded entry of an open dirty buffer is written again on the next tick. `diskChanged` is true when the file's modification time is after `savedAt` or the file is gone.
- **Commands and event:** after `project.open`, `recoveryAvailable {entries: [{path, savedAt, diskChanged}]}` when the journal is not empty. `recovery.list` → `{entries}`; `recovery.restore {paths?}` → `{restored: [{path, id}], failed: [{path, message}]}` opens each file as a dirty buffer (version 1, saved version 0) with the journal text, line ending and BOM, or puts the text into a clean open buffer; a buffer with unsaved changes is newer than the journal and is left alone (`failed`); a file gone from disk is restored too and saving recreates it. `recovery.discard {paths?}` → `{discarded}`; a discarded entry of an open dirty buffer is written again on the next tick. Both emit `recoveryResolved {paths}` (sorted, only when not empty) with the restored or discarded paths (M1.15): a restored entry stays in the journal as the dirty buffer's own entry, so "journal empty" is not the signal; the settled paths are. `diskChanged` is true when the file's modification time is after `savedAt` or the file is gone.
- **Untrusted input:** entries are read with a 512 MiB cap, at most 1,000 per project. An entry that is not valid JSON of that shape, whose path escapes the project or does not match its file name is renamed to `<entry>.bad`, skipped, and reported once as `notification {level: warning, messageKey: "notification.recovery.corrupt", params: {file, reason}}`. A failed write is reported once until a write succeeds (`notification.recovery.writeFailed {path, reason}`); an unreadable journal directory gives `notification.recovery.unavailable {reason}`. Neither stops editing or opening.
- **UI:** `ui/src/components/recovery/` (store `recovery.ts`, `RecoveryDialog.vue`, mounted in `App.vue`). The list comes from `recoveryAvailable` and, because that event is not replayed after a page reload, from `recovery.list` on `projectOpened`. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open.
- **UI:** `ui/src/components/recovery/` (store `recovery.ts`, `RecoveryDialog.vue`, mounted in `App.vue`). The list comes from `recoveryAvailable` and, because that event is not replayed after a page reload, from `recovery.list` on `projectOpened`. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open. `recoveryResolved` drops the settled paths from the list, so a restore or discard over the control channel closes the dialog when nothing is left (M1.15). The dialog is queued behind the other modals (see UI commands › Modal rule).
- **Limits:** two Lutra instances on the same project share one journal directory; `diskChanged` misses a disk change that happened before the last journal write.
### UI commands, palette and keymap (M1.8)
@ -172,6 +172,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- the editor area provides `file.save`, `file.saveAll` and `buffer.close` with the active buffer as context (they replace the editor-only keymap of M1.6).
- A UI command without a handler is disabled. The settings dialog provides `settings.open` (M1.9b).
- An engine command without a handler runs through `run(id, {})`.
- **Modal rule (M1.15, `ui/src/commands/modals.ts`):** at most one modal is open. The palette, the settings dialog and the close question are exclusive: each reports `opened(id, close)` / `closed(id)` to the Pinia `modals` store, and opening one closes the open one (the close question closes as Cancel; the store follows `editor.closePrompt`, so the editor has no code for it). Running any command but `palette.open` through `execute` (keyboard, palette, `uiCommand`) closes the palette first. The restore dialog is queued instead: hidden while an exclusive modal is open, shown again with its list intact when it closes. Reason: its offer must survive a palette or settings dialog opened by an agent, and closing it would only hide the journal until the next open.
- **Enabled state:** a handler's `enabled` decides, else the engine's. The list is refreshed on `projectOpened`/`projectClosed` and whenever the palette opens.
- **Keyboard:** one window `keydown` listener in the capture phase (works while CodeMirror or an input has focus). A matching shortcut is always swallowed; a disabled command does nothing. A failure raises `notification.command.failed`.
- **Palette** (`ui/src/components/palette/CommandPalette.vue`, mounted in `App.vue`):
@ -211,6 +212,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.15: modal rule (one modal at a time, restore dialog queued), `recoveryResolved` event |
| 2026-10-16 | minor | M1.9b: settings dialog (store, search, controls by type, reset, live updates, font-size token override) |
| 2026-10-16 | minor | M1.14: app icon from the owner's master, multi-size ICO, placeholder as fallback |
| 2026-10-16 | minor | M1.8: UI commands (`ui.registerCommands`, `uiCommand`, `ui` in listCommands), global keymap, command palette |

View file

@ -10,9 +10,9 @@
- [ ] 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`.
- [ ] Restore dialog for unsaved changes after a crash
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. Behaviour notes: `plan/phpstorm/04-recovery.md`.
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. M1.15: a restore or discard from elsewhere (control channel) removes the settled files and closes the dialog when none are left; the dialog waits behind the palette and the settings dialog. Behaviour notes: `plan/phpstorm/04-recovery.md`.
- [ ] Command palette / search everywhere
- M1.8 (2026-10-16): command palette (`Mod+Shift+P`) over every user-facing command, engine and UI (commands with a menu path or default shortcut, plus UI commands): fuzzy ranking on the label and the id (prefix, word prefix, word starts, substring, in-order characters), recently run commands first, shortcuts shown, disabled commands dimmed and not runnable, arrow keys, Enter, Escape, focus returned on close; a failing command raises an error toast. One global keymap (`ui/src/commands/`) matches every command's default shortcut by key code; UI commands `palette.open`, `settings.open` (`Mod+,`, opens the settings dialog since M1.9b) and `view.toggleProjectTree` (`Mod+1`). Vitest (keymap, ranking, store, palette, App); live check pending (gaming mode). Missing: files, classes, symbols and text tabs (search everywhere), settings in the results, synonyms and abbreviations, inline toggles, assigning a shortcut from the palette, recent commands across restarts. Behaviour notes: `plan/phpstorm/05-palette.md`.
- M1.8 (2026-10-16): command palette (`Mod+Shift+P`) over every user-facing command, engine and UI (commands with a menu path or default shortcut, plus UI commands): fuzzy ranking on the label and the id (prefix, word prefix, word starts, substring, in-order characters), recently run commands first, shortcuts shown, disabled commands dimmed and not runnable, arrow keys, Enter, Escape, focus returned on close; a failing command raises an error toast. One global keymap (`ui/src/commands/`) matches every command's default shortcut by key code; UI commands `palette.open`, `settings.open` (`Mod+,`, opens the settings dialog since M1.9b) and `view.toggleProjectTree` (`Mod+1`). Vitest (keymap, ranking, store, palette, App); live check pending (gaming mode). Missing: files, classes, symbols and text tabs (search everywhere), settings in the results, synonyms and abbreviations, inline toggles, assigning a shortcut from the palette, recent commands across restarts. M1.15: one modal at a time; running any command (also as a `uiCommand`) closes the palette, opening the palette closes the settings dialog and the close question. Behaviour notes: `plan/phpstorm/05-palette.md`.
- [ ] Settings dialog with search
- M1.9b (2026-10-16): dialog (`Mod+,`, palette, control channel) built from `settings.list`: sections on the left, controls by type (select, number with min/max, switch), labels and descriptions from the catalog, search over label, description, key and section with matches grouped by section, Reset to default per setting, changes applied at once with inline errors, live updates on `settingsChanged`, theme picker (`appearance.theme`, switches at once), editor font size applied to the editor; Escape closes, focus trapped, every control reachable by Tab. Vitest (14 tests); live check pending (gaming mode). Missing: a tree of nested categories, project-level settings and their marker, modified markers, highlighting matches, export/import, more settings (keymap, code style, inspections). Behaviour notes: `plan/phpstorm/06-settings.md`.
- [ ] Keymap editor (Lutra's own default keymap; no copied keymaps)
@ -31,6 +31,7 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | patch | Palette and restore dialog: modal rule, restore dialog follows outside restores (M1.15) |
| 2026-10-16 | minor | Settings dialog partial; theme picker and editor font size (M1.9b) |
| 2026-10-16 | minor | Command palette and global keymap partial (M1.8) |
| 2026-10-16 | minor | Notifications partial (M1.12) |

89
ui/src/commands/modals.ts Normal file
View file

@ -0,0 +1,89 @@
/**
* The modal rule (M1.15): at most one modal is open at a time.
*
* - **Exclusive modals:** the command palette, the settings dialog and the
* close question of a dirty tab. Opening one closes the one that is open
* (the close question closes as Cancel). Each reports itself with
* {@link useModalsStore}'s `opened` and `closed`; the close question is
* followed from the editor store, so the editor needs no code for it.
* - **The restore dialog is queued:** it never closes another modal and is
* never closed by one. While an exclusive modal is open it is hidden, and
* it shows again, with its list intact, when that modal closes. Its
* offer stays until the user decides, so it must not be lost to a
* palette opened by an agent.
* - **The palette is a launcher:** running any command other than
* `palette.open` closes it first (see `store.ts` › `execute`), so a
* `uiCommand` from the control channel never leaves it open behind
* what the command shows.
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { useEditorStore } from "../stores/editor";
/** The exclusive modals. */
export type ModalId = "palette" | "settings" | "closePrompt";
/** Store of the open exclusive modal. */
export const useModalsStore = defineStore("modals", () => {
const editor = useEditorStore();
/** The exclusive modal that is open, or null. */
const current = ref<ModalId | null>(null);
/** Closes {@link current}; set while one is open. */
let closeCurrent: (() => void) | null = null;
/**
* Forgets `id` as the open modal; the modal closed itself.
*
* @param id - the modal.
*/
function closed(id: ModalId): void {
if (current.value === id) {
current.value = null;
closeCurrent = null;
}
}
/**
* Closes `id` if it is the open modal.
*
* @param id - the modal.
*/
function dismiss(id: ModalId): void {
if (current.value !== id) {
return;
}
const close = closeCurrent;
closed(id);
close?.();
}
/**
* Records `id` as the open modal and closes the one open before.
* Call it before the modal takes the focus, so the closed modal gives
* the focus back first.
*
* @param id - the modal that opens.
* @param close - closes it when another modal opens.
*/
function opened(id: ModalId, close: () => void): void {
if (current.value !== null && current.value !== id) {
dismiss(current.value);
}
current.value = id;
closeCurrent = close;
}
watch(
() => editor.closePrompt !== null,
(asking) => {
if (asking) {
opened("closePrompt", () => void editor.resolveClose("cancel"));
} else {
closed("closePrompt");
}
},
{ immediate: true },
);
return { current, opened, closed, dismiss };
});

View file

@ -14,12 +14,15 @@
* buffer) with {@link useCommandsStore}'s `provide`. Other engine
* commands run with empty params.
* - **Errors:** a failed command raises an error toast (M1.12).
* - **Palette:** running any command but `palette.open` closes the palette
* first (the modal rule, `modals.ts`).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowReactive } from "vue";
import { hasMessage, t } from "../i18n";
import { listCommands, onEngineEvent, run, type CommandInfo, type EngineEventPayload, type JsonValue } from "../ipc";
import { useNotificationsStore } from "../stores/notifications";
import { useModalsStore } from "./modals";
import { buildKeymap, commandFor, formatShortcut, isMac } from "./keymap";
import { UI_COMMANDS } from "./uiCommands";
@ -84,6 +87,7 @@ function labelOf(info: CommandInfo): string {
/** Store of the commands, the keymap and the recently run commands. */
export const useCommandsStore = defineStore("commands", () => {
const notifications = useNotificationsStore();
const modals = useModalsStore();
/** Commands as the engine lists them; empty until loaded. */
const infos = ref<CommandInfo[]>([]);
/** Handlers supplied by components, by command id. */
@ -179,7 +183,8 @@ export const useCommandsStore = defineStore("commands", () => {
/**
* Runs a command the user chose (keyboard or palette): through its
* handler if a component supplied one, else through the engine. A
* disabled command does nothing. A failure raises an error toast.
* disabled command does nothing. A failure raises an error toast. Any
* command but `palette.open` closes the palette before it runs.
*
* @param id - the command id.
* @param params - the params.
@ -189,6 +194,9 @@ export const useCommandsStore = defineStore("commands", () => {
return;
}
remember(id);
if (id !== "palette.open") {
modals.dismiss("palette");
}
const handler = handlers.get(id);
if (handler) {
try {

View file

@ -9,13 +9,18 @@
* Arrow keys move the selection, Enter runs it, Escape or a click outside
* closes. The command runs after the palette closed and gave the focus
* back, so a command that asks something (closing a dirty tab) gets it.
* Only one modal is open at a time (see `commands/modals.ts`): opening the
* palette closes the settings dialog or the close question, and running
* any other command, also through a `uiCommand`, closes the palette.
*/
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { rank } from "../../commands/rank";
import { useModalsStore } from "../../commands/modals";
import { useCommandsStore, type PaletteEntry } from "../../commands/store";
import { t } from "../../i18n";
const commands = useCommandsStore();
const modals = useModalsStore();
/** Whether the palette is shown. */
const open = ref(false);
@ -44,6 +49,7 @@ watch(query, () => {
/** Opens the palette with an empty query and refreshes the enabled states. */
async function show(): Promise<void> {
modals.opened("palette", close);
if (!open.value) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
@ -62,6 +68,7 @@ function close(): void {
return;
}
open.value = false;
modals.closed("palette");
returnFocus?.focus();
returnFocus = null;
}

View file

@ -7,9 +7,16 @@
* not replayed after a page reload, `projectOpened` also asks the engine with
* `recovery.list`. Every action names its paths explicitly, so entries of
* files restored earlier in the dialog are never discarded by accident.
*
* `recoveryResolved` (M1.15) drops the paths that `recovery.restore` or
* `recovery.discard` settled from elsewhere (the control channel, an
* agent), so the dialog closes when nothing is left to decide. The dialog
* is queued behind the other modals (`commands/modals.ts`): hidden while
* the palette, the settings dialog or the close question is open.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useModalsStore } from "../../commands/modals";
import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../../ipc";
/** One unsaved text the journal holds. */
@ -78,6 +85,7 @@ function toFailures(raw: unknown): RecoveryFailure[] {
/** Store behind the restore dialog. */
export const useRecoveryStore = defineStore("recovery", () => {
const modals = useModalsStore();
/** Entries still waiting for a decision; the dialog shows while non-empty. */
const entries = ref<RecoveryEntry[]>([]);
/** Paths ticked for "Restore selected". */
@ -88,8 +96,10 @@ export const useRecoveryStore = defineStore("recovery", () => {
const error = ref<string | null>(null);
/** A restore or discard is running. */
const busy = ref(false);
/** Whether the dialog is shown. */
const open = computed(() => entries.value.length > 0 || failures.value.length > 0);
/** Whether there is something to show: entries or failures. */
const pending = computed(() => entries.value.length > 0 || failures.value.length > 0);
/** Whether the dialog is shown: pending and no other modal open. */
const open = computed(() => pending.value && modals.current === null);
/** Ends the event subscription; null while not subscribed. */
let unsubscribe: (() => void) | null = null;
@ -111,6 +121,20 @@ export const useRecoveryStore = defineStore("recovery", () => {
show([]);
}
/**
* Drops paths settled elsewhere from the list and the ticks.
*
* @param raw - the `paths` of `recoveryResolved`, untrusted.
*/
function resolve(raw: unknown): void {
if (!Array.isArray(raw)) {
return;
}
const done = new Set(raw.filter((p): p is string => typeof p === "string"));
entries.value = entries.value.filter((e) => !done.has(e.path));
selected.value = new Set([...selected.value].filter((p) => !done.has(p)));
}
/** Asks the engine for the entries, after a project opened. */
async function refresh(): Promise<void> {
const result = await run<{ entries?: unknown }>("recovery.list");
@ -129,6 +153,9 @@ export const useRecoveryStore = defineStore("recovery", () => {
case "recoveryAvailable":
show(toRecoveryEntries((event as { entries?: unknown }).entries));
break;
case "recoveryResolved":
resolve((event as { paths?: unknown }).paths);
break;
case "projectOpened":
void refresh();
break;
@ -223,6 +250,7 @@ export const useRecoveryStore = defineStore("recovery", () => {
failures,
error,
busy,
pending,
open,
handleEvent,
start,

View file

@ -16,9 +16,12 @@
* so a change over the control channel shows while the dialog is open.
* - **Keyboard:** Escape closes, Tab and Shift+Tab stay inside the dialog,
* and the focus returns to where it was.
* - **One modal:** opening the dialog closes the palette or the close
* question (see `commands/modals.ts`).
*/
import { X } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { useModalsStore } from "../../commands/modals";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import {
@ -34,6 +37,7 @@ import {
const commands = useCommandsStore();
const settings = useSettingsStore();
const modals = useModalsStore();
/** Whether the dialog is shown. */
const open = ref(false);
@ -200,6 +204,7 @@ function choose(id: string): void {
/** Opens the dialog (or focuses its search field) and reloads the settings. */
async function show(): Promise<void> {
modals.opened("settings", close);
if (!open.value) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
@ -217,6 +222,7 @@ function close(): void {
return;
}
open.value = false;
modals.closed("settings");
for (const key of Object.keys(drafts)) {
Reflect.deleteProperty(drafts, key);
}

View file

@ -56,6 +56,11 @@ export type EngineEventPayload =
id: unknown;
/** The params it was run with, as given; unchecked. */
params?: unknown;
}
| {
kind: "recoveryResolved";
/** Paths restored or discarded; unchecked, it comes from the engine. */
paths: unknown;
};
/** Callback receiving engine events. */

View file

@ -0,0 +1,186 @@
/**
* Tests of the modal rule (M1.15, `commands/modals.ts`): the palette, the
* settings dialog and the close question never stack, running a command
* closes the palette also when it comes as a `uiCommand`, and the restore
* dialog waits behind the other modals with its list intact. The engine is
* a fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, h } from "vue";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useModalsStore } from "../../src/commands/modals";
import { useCommandsStore } from "../../src/commands/store";
import CommandPalette from "../../src/components/palette/CommandPalette.vue";
import RecoveryDialog from "../../src/components/recovery/RecoveryDialog.vue";
import { useRecoveryStore } from "../../src/components/recovery/recovery";
import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
import { useEditorStore } from "../../src/stores/editor";
/** The engine event callbacks, one per subscription. */
let listeners: ((payload: unknown) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscriber.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of listeners) {
listener(payload);
}
await flushPromises();
}
/**
* Runs a UI command the way the control channel does.
*
* @param id - the command id.
*/
async function uiCommand(id: string): Promise<void> {
await emit({ kind: "uiCommand", id, params: {} });
}
/** A focusable button standing in for the editor. */
const Host = defineComponent({
setup: () => () => h("button", { id: "host-button" }, "host"),
});
/** Mounts the editor stand-in and the modals the app mounts, and starts the commands. */
async function mountApp(): Promise<VueWrapper> {
const host = mount(Host, { attachTo: document.body });
const recovery = mount(RecoveryDialog, { attachTo: document.body, global: { plugins: [pinia] } });
const palette = mount(CommandPalette, { attachTo: document.body, global: { plugins: [pinia] } });
const settings = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(host, recovery, palette, settings);
await useCommandsStore(pinia).start();
await flushPromises();
document.getElementById("host-button")?.focus();
return host;
}
/** Whether the palette is shown. */
function paletteShown(): boolean {
return document.querySelector("[data-test=palette]") !== null;
}
/** Whether the settings dialog is shown. */
function settingsShown(): boolean {
return document.querySelector("[data-test=settings]") !== null;
}
/** Whether the restore dialog is shown. */
function recoveryShown(): boolean {
return document.querySelector("[data-test=recovery-dialog]") !== null;
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
listeners = [];
mounted = [];
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push((payload) => {
callback({ payload });
});
return Promise.resolve(() => undefined);
});
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd === "engine_execute" && args?.command === "settings.list") {
return Promise.resolve([]);
}
if (cmd === "engine_execute" && args?.command === "settings.get") {
return Promise.resolve({ values: {} });
}
return Promise.resolve(null);
});
});
afterEach(() => {
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
});
describe("one modal at a time", () => {
it("settings.open from the control channel closes the open palette", async () => {
await mountApp();
await uiCommand("palette.open");
expect(paletteShown()).toBe(true);
await uiCommand("settings.open");
expect(paletteShown()).toBe(false);
expect(settingsShown()).toBe(true);
expect(useModalsStore(pinia).current).toBe("settings");
});
it("any command run while the palette is open closes it first", async () => {
await mountApp();
const toggled = vi.fn();
useCommandsStore(pinia).provide("view.toggleProjectTree", { run: toggled });
await uiCommand("palette.open");
await uiCommand("view.toggleProjectTree");
expect(toggled).toHaveBeenCalledOnce();
expect(paletteShown()).toBe(false);
expect(useModalsStore(pinia).current).toBeNull();
expect(document.activeElement?.id).toBe("host-button");
});
it("opening the palette closes the settings dialog", async () => {
await mountApp();
await uiCommand("settings.open");
await uiCommand("palette.open");
expect(settingsShown()).toBe(false);
expect(paletteShown()).toBe(true);
expect(useModalsStore(pinia).current).toBe("palette");
await uiCommand("palette.open");
expect(paletteShown()).toBe(true);
});
it("the close question closes the palette, and the palette cancels the question", async () => {
await mountApp();
const editor = useEditorStore(pinia);
await uiCommand("palette.open");
editor.closePrompt = { id: 1, name: "a.php" };
await flushPromises();
expect(paletteShown()).toBe(false);
expect(useModalsStore(pinia).current).toBe("closePrompt");
await uiCommand("palette.open");
expect(editor.closePrompt).toBeNull();
expect(paletteShown()).toBe(true);
});
it("the restore dialog waits behind the other modals with its list intact", async () => {
await mountApp();
const entry = { path: "src/a.php", savedAt: 1, diskChanged: false };
await uiCommand("palette.open");
await emit({ kind: "recoveryAvailable", entries: [entry] });
expect(recoveryShown()).toBe(false);
expect(paletteShown()).toBe(true);
await uiCommand("settings.open");
expect(recoveryShown()).toBe(false);
document.querySelector<HTMLElement>("[data-test=settings-dialog]")?.dispatchEvent(
new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),
);
await flushPromises();
expect(settingsShown()).toBe(false);
expect(recoveryShown()).toBe(true);
expect(useRecoveryStore(pinia).entries).toEqual([entry]);
expect(document.activeElement).toBe(document.querySelector("[data-test=recovery-restore-all]"));
});
});

View file

@ -2,7 +2,8 @@
* Tests for the restore dialog and its store: the list from
* `recoveryAvailable` and from `recovery.list` after `projectOpened`, the
* "changed on disk" hint, Restore all / Restore selected / Discard with
* explicit paths, failures, errors, Escape, and checking untrusted entries.
* explicit paths, failures, errors, Escape, entries settled elsewhere
* (`recoveryResolved`), and checking untrusted entries.
* The engine is a fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
@ -217,6 +218,26 @@ describe("RecoveryDialog", () => {
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
expect(calls).toEqual([]);
});
it("drops entries restored or discarded elsewhere and closes when none are left", async () => {
const wrapper = mountDialog();
await offer();
await wrapper.get("[data-test='recovery-select-c.php']").setValue(true);
const store = useRecoveryStore();
store.handleEvent({ kind: "recoveryResolved", paths: ["src/a.php", "c.php", 7, "gone.php"] });
await flushPromises();
expect(wrapper.findAll("[data-test=recovery-entry]").map((r) => r.find(".recovery__path").text())).toEqual([
"src/b.php",
]);
expect([...store.selected]).toEqual([]);
store.handleEvent({ kind: "recoveryResolved", paths: "nope" });
await flushPromises();
expect(wrapper.findAll("[data-test=recovery-entry]")).toHaveLength(1);
store.handleEvent({ kind: "recoveryResolved", paths: ["src/b.php"] });
await flushPromises();
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
expect(calls).toEqual([]);
});
});
describe("toRecoveryEntries", () => {