/** * Editor tabs: which engine buffers are open, which one is active, their * dirty state, notices, and the Save / Don't save / Cancel question when a * dirty tab closes. * * Fed by engine events (`bufferOpened`, `bufferChanged`, `dirtyChanged`, * `bufferClosed`, `fileChangedOnDisk`, project open/close) and by command * results. Text lives in the engine and in one {@link BufferSync} per tab, * kept outside reactive state. Command failures are stored and shown, never * thrown. */ import { defineStore } from "pinia"; import { computed, ref, shallowRef } from "vue"; import { run, type EngineError, type RunResult } from "../ipc"; import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync"; import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents"; import { editorExtensions } from "../components/editor/extensions"; import type { Extension } from "@codemirror/state"; /** Engine command ids used by the editor. */ export const EDITOR_COMMANDS = { /** Opens a file: params `{ path }`, result {@link BufferInfo}. */ open: "file.open", /** Describes a buffer: params `{ id }`, result {@link BufferInfo}. */ get: "buffer.get", /** Saves a buffer: params `{ id }`. */ save: "file.save", /** Saves every dirty buffer: result `{ saved, failed: [{ id, message }] }`. */ saveAll: "file.saveAll", /** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */ close: "buffer.close", } as const; /** A notice shown above a tab's editor; it never blocks editing. */ export interface EditorNotice { /** What happened. */ kind: "changedOnDisk" | "removedOnDisk" | "error"; /** Text for the user. */ message: string; } /** One editor tab. */ export interface EditorTab { /** Engine buffer id. */ id: number; /** Project-relative path. */ path: string; /** File name shown on the tab. */ name: string; /** Unsaved changes in the engine buffer. */ dirty: boolean; /** Notice for this tab, null if none. */ notice: EditorNotice | null; } /** The pending question for closing a dirty tab. */ export interface ClosePrompt { /** Buffer id of the tab. */ id: number; /** File name, for the question. */ name: string; } /** Answer to a {@link ClosePrompt}. */ export type CloseChoice = "save" | "discard" | "cancel"; /** Timing of the last file open, for the performance budget. */ export interface OpenTiming { /** Path of the opened file. */ path: string; /** Size of the text in UTF-16 code units. */ length: number; /** Milliseconds from the request until the editor state existed. */ stateMs: number; /** Milliseconds until the editor showed it, null until the view reports. */ shownMs: number | null; } /** * The file name of a project-relative path. * * @param path - for example `src/App.php`. */ export function baseName(path: string): string { const slash = path.lastIndexOf("/"); return slash < 0 ? path : path.slice(slash + 1); } /** Store of editor tabs. */ export const useEditorStore = defineStore("editor", () => { /** Open tabs in display order. */ const tabs = ref([]); /** Buffer id of the active tab, null when no tab is open. */ const activeId = ref(null); /** Pending close question, null if none. */ const closePrompt = ref(null); /** Last failed editor command, null if none. */ const lastError = ref(null); /** Timing of the last open, see {@link OpenTiming}. */ const lastOpen = shallowRef(null); /** Syncs by buffer id; not reactive (they hold large editor states). */ const syncs = new Map(); /** Start time of open requests by path, for {@link lastOpen}. */ const openStarted = new Map(); /** Start time of the open measured in {@link lastOpen}. */ let timedStart = 0; /** Engine transport for syncs, replaceable in tests. */ let transport: SyncTransport = engineTransport; /** Extensions of new editor states, replaceable in tests. */ let extensions: () => Extension = editorExtensions; /** Counter of tab adoptions, so only the newest open activates its tab. */ let openSequence = 0; /** Unsubscribe function of the event subscription. */ let unsubscribe: (() => void) | null = null; /** The active tab, or null. */ const activeTab = computed(() => tabs.value.find((t) => t.id === activeId.value) ?? null); /** * The tab of a buffer. * * @param id - buffer id. */ function tabOf(id: number): EditorTab | undefined { return tabs.value.find((t) => t.id === id); } /** * The sync of a buffer, for the editor view. * * @param id - buffer id. */ function syncOf(id: number): BufferSync | undefined { return syncs.get(id); } /** * Replaces the engine transport and editor extensions (tests). * * @param next - transport for new syncs. * @param nextExtensions - extensions for new editor states. */ function configure(next: SyncTransport, nextExtensions?: () => Extension): void { transport = next; if (nextExtensions) { extensions = nextExtensions; } } /** * Adds a tab for a buffer the engine described, unless it exists, and * activates it. * * @param info - the buffer. * @param activate - whether the tab becomes active. */ function adopt(info: BufferInfo, activate = true): void { if (!syncs.has(info.id)) { const started = openStarted.get(info.path); syncs.set( info.id, new BufferSync(info, extensions(), transport, (error) => { const tab = tabOf(info.id); if (tab) { tab.notice = { kind: "error", message: error.message }; } }), ); if (started !== undefined) { openStarted.delete(info.path); timedStart = started; lastOpen.value = { path: info.path, length: info.text.length, stateMs: performance.now() - started, shownMs: null, }; } } if (!tabOf(info.id)) { const index = tabs.value.findIndex((t) => t.id === activeId.value); const tab: EditorTab = { id: info.id, path: info.path, name: baseName(info.path), dirty: info.dirty, notice: null, }; tabs.value.splice(index < 0 ? tabs.value.length : index + 1, 0, tab); } if (activate || activeId.value === null) { activeId.value = info.id; } } /** * Records that the view showed the buffer whose open is being timed. * * @param id - buffer id that became visible. */ function markShown(id: number): void { const timing = lastOpen.value; if (!timing || timing.shownMs !== null || tabOf(id)?.path !== timing.path) { return; } lastOpen.value = { ...timing, shownMs: performance.now() - timedStart }; } /** * Opens a file in a tab (or activates its tab). * * @param path - project-relative path. */ async function openFile(path: string): Promise { openStarted.set(path, performance.now()); const result = await run(EDITOR_COMMANDS.open, { path }); if (!result.ok) { openStarted.delete(path); lastError.value = result.error; return; } if (!isBufferInfo(result.value)) { lastError.value = { code: "ipc", message: `unexpected result of ${EDITOR_COMMANDS.open}` }; return; } lastError.value = null; openSequence += 1; adopt(result.value); } /** * Activates a tab. * * @param id - buffer id. */ function activate(id: number): void { if (tabOf(id)) { activeId.value = id; } } /** * Removes a tab and its sync; the neighbour becomes active. * * @param id - buffer id. */ function removeTab(id: number): void { syncs.get(id)?.dispose(); syncs.delete(id); const index = tabs.value.findIndex((t) => t.id === id); if (index < 0) { return; } tabs.value.splice(index, 1); if (activeId.value === id) { const next = tabs.value[Math.min(index, tabs.value.length - 1)]; activeId.value = next ? next.id : null; } if (closePrompt.value?.id === id) { closePrompt.value = null; } } /** * Waits until local edits of a buffer reached the engine. * * @param id - buffer id. */ async function settled(id: number): Promise { await syncs.get(id)?.idle(); } /** * Runs `buffer.close`. * * @param id - buffer id. * @param force - discard unsaved changes. * @returns the command result. */ async function closeBuffer(id: number, force: boolean): Promise> { const result = await run(EDITOR_COMMANDS.close, { id, force }); if (result.ok) { removeTab(id); } return result; } /** * Closes a tab; a dirty one asks Save / Don't save / Cancel first. * * @param id - buffer id; the active tab when omitted. */ async function requestClose(id: number | null = activeId.value): Promise { if (id === null) { return; } const tab = tabOf(id); if (!tab) { return; } await settled(id); if (tab.dirty) { closePrompt.value = { id, name: tab.name }; return; } const result = await closeBuffer(id, false); if (result.ok) { lastError.value = null; } else if (result.error.code === "unsaved_changes") { tab.dirty = true; closePrompt.value = { id, name: tab.name }; } else { lastError.value = result.error; } } /** * Answers the pending close question. * * @param choice - save and close, close without saving, or keep the tab. */ async function resolveClose(choice: CloseChoice): Promise { const prompt = closePrompt.value; closePrompt.value = null; if (!prompt || choice === "cancel") { return; } if (choice === "save" && !(await save(prompt.id))) { return; } const result = await closeBuffer(prompt.id, choice === "discard"); lastError.value = result.ok ? null : result.error; } /** * Saves a buffer after its local edits reached the engine. * * @param id - buffer id; the active tab when omitted. * @returns whether the save succeeded. */ async function save(id: number | null = activeId.value): Promise { if (id === null || !tabOf(id)) { return false; } await settled(id); const result = await run(EDITOR_COMMANDS.save, { id }); lastError.value = result.ok ? null : result.error; if (result.ok) { const tab = tabOf(id); if (tab) { tab.dirty = false; if (tab.notice?.kind === "changedOnDisk") { tab.notice = null; } } } return result.ok; } /** Saves every buffer after all local edits reached the engine. */ async function saveAll(): Promise { await Promise.all(tabs.value.map((t) => settled(t.id))); const result = await run<{ failed?: { id?: unknown; message?: unknown }[] }>( EDITOR_COMMANDS.saveAll, ); if (!result.ok) { lastError.value = result.error; return; } const failed = Array.isArray(result.value.failed) ? result.value.failed : []; lastError.value = failed.length > 0 ? { code: "save_failed", message: failed .map((f) => (typeof f.message === "string" ? f.message : "save failed")) .join("; "), } : null; } /** * Hides a tab's notice. * * @param id - buffer id. */ function dismissNotice(id: number): void { const tab = tabOf(id); if (tab) { tab.notice = null; } } /** Drops every tab (the project closed or changed). */ function clear(): void { for (const sync of syncs.values()) { sync.dispose(); } syncs.clear(); tabs.value = []; activeId.value = null; closePrompt.value = null; } /** * Adds a tab for a buffer opened elsewhere (control channel, replay after * a reload), fetching its text first. When several open at once, the * last one opened becomes active, whatever order the fetches finish in. * * @param id - buffer id. */ async function adoptOpened(id: number): Promise { if (syncs.has(id)) { return; } const sequence = ++openSequence; const result = await run(EDITOR_COMMANDS.get, { id }); if (!result.ok) { lastError.value = result.error; return; } if (isBufferInfo(result.value) && !syncs.has(id)) { adopt(result.value, sequence === openSequence); } } /** * Applies one editor event. * * @param event - the event. */ function handleEvent(event: EditorEvent): void { switch (event.kind) { case "projectOpened": case "projectClosed": clear(); break; case "bufferOpened": void adoptOpened(event.id); break; case "bufferChanged": syncs.get(event.id)?.notifyVersion(event.version); break; case "dirtyChanged": { const tab = tabOf(event.id); if (tab) { tab.dirty = event.dirty; } break; } case "bufferClosed": removeTab(event.id); break; case "fileChangedOnDisk": { const tab = tabOf(event.id); if (!tab) { break; } if (event.removed) { tab.notice = { kind: "removedOnDisk", message: `${tab.name} was deleted on disk. Your text is kept; saving writes it again.`, }; } else { tab.notice = { kind: "changedOnDisk", message: `${tab.name} changed on disk. Your unsaved changes are kept; saving overwrites the file.`, }; } break; } } } /** Subscribes to engine events; calling it again has no effect. */ function start(): void { unsubscribe ??= onEditorEvent(handleEvent); } /** Ends the event subscription. */ function stop(): void { unsubscribe?.(); unsubscribe = null; } return { tabs, activeId, activeTab, closePrompt, lastError, lastOpen, syncOf, configure, openFile, activate, requestClose, resolveClose, save, saveAll, dismissNotice, markShown, handleEvent, start, stop, }; });