/** * The modal rule (M1.15): at most one modal is open at a time. * * - **Exclusive modals:** the command palette, the go-to popup (M2.6), the * app menu (M3.9), 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. The go-to popup is a launcher too: any command * but the go-to open commands closes it. So is the app menu (M3.9): any * command but `menu.open` closes it. */ import { defineStore } from "pinia"; import { ref, watch } from "vue"; import { useEditorStore } from "../stores/editor"; /** The exclusive modals. */ export type ModalId = "palette" | "goto" | "menu" | "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(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 }; });