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

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", () => {