/** * The Problems tool window's state (M3.3): the language server's * diagnostics of the project, grouped by file, and the server's state. * * - **Source:** `diagnosticsChanged {path, items}` replaces one file's * list (empty items remove the file); `diagnostics.list` loads every * file on start and when a project opens, and `lsp.status` the server's * state, which then follows `lspStatus`. A project close clears both. * - **Progress (H3):** the server's newest work-done progress task * (`progress` of `lsp.status`, then `lspProgress`), shown by * `LspProgressItem` in the status bar. It clears when the server stops, * restarts or fails, and on project close. * - **Editor:** every change is handed to the editor's lint extension * ({@link publishDiagnostics}), which draws the underlines and gutter * markers. * - **Rows:** files sorted by path; inside a file errors first, then * warnings, information and hints, each by position. One flat row list * drives keyboard navigation; Enter or a click reveals the position * (`editor.reveal`). * - **Untrusted input:** event fields come from the engine and, through * it, from Phpactor; malformed items are dropped and the counts capped * ({@link MAX_ITEMS_PER_FILE}, {@link MAX_FILES}). */ import { defineStore } from "pinia"; import { computed, ref, shallowRef } from "vue"; import { onEngineEvent, run, type EngineEventPayload } from "../../ipc"; import { clearDiagnostics, publishDiagnostics, type DiagnosticItem, type DiagnosticPosition, type DiagnosticSeverity, } from "../editor/lint"; /** Most diagnostics kept per file. */ export const MAX_ITEMS_PER_FILE = 10_000; /** Most files kept. */ export const MAX_FILES = 10_000; /** States of the language server, as `lspStatus` names them. */ export const LSP_STATES = ["starting", "ready", "restarting", "failed", "stopped"] as const; /** State of the language server. */ export type LspState = (typeof LSP_STATES)[number]; /** The language server's state and why it is in it. */ export interface LspStatus { /** The state. */ state: LspState; /** Why it restarts or failed. */ message: string | null; } /** The language server's newest running work-done progress task. */ export interface LspProgress { /** Its title, such as `Indexing workspace`. */ title: string; /** Its latest message, if any. */ message: string | null; /** 0–100, if the server gives one. */ percentage: number | null; } /** The diagnostics of one file. */ export interface ProblemFile { /** Project-relative path with `/`. */ path: string; /** Its diagnostics in display order. */ items: DiagnosticItem[]; } /** A diagnostic in the flat display order. */ export interface ProblemRow { /** Stable key: path and index. */ key: string; /** Path of the file. */ path: string; /** The diagnostic. */ item: DiagnosticItem; } /** Severities in display order. */ const SEVERITY_ORDER: Record = { error: 0, warning: 1, info: 2, hint: 3 }; /** * Reads a position. * * @param raw - an untrusted `{line, column}`. */ function toPosition(raw: unknown): DiagnosticPosition | null { if (typeof raw !== "object" || raw === null) { return null; } const { line, column } = raw as Record; const ok = (n: unknown): n is number => typeof n === "number" && Number.isInteger(n) && n >= 0; return ok(line) && ok(column) ? { line, column } : null; } /** * Reads one diagnostic; null if malformed. * * @param raw - an untrusted item of `diagnosticsChanged`. */ export function toItem(raw: unknown): DiagnosticItem | null { if (typeof raw !== "object" || raw === null) { return null; } const i = raw as Record; const range = typeof i.range === "object" && i.range !== null ? (i.range as Record) : null; const start = toPosition(range?.start); const end = toPosition(range?.end); const severity = i.severity; if ( !start || !end || typeof i.message !== "string" || (severity !== "error" && severity !== "warning" && severity !== "info" && severity !== "hint") ) { return null; } const item: DiagnosticItem = { range: { start, end }, severity, message: i.message }; if (typeof i.source === "string" && i.source !== "") { item.source = i.source; } if (typeof i.code === "string" && i.code !== "") { item.code = i.code; } return item; } /** * Reads and orders a file's diagnostics: errors first, then by position. * * @param raw - the untrusted `items` field. */ export function toItems(raw: unknown): DiagnosticItem[] { if (!Array.isArray(raw)) { return []; } const items: DiagnosticItem[] = []; for (const entry of raw as unknown[]) { if (items.length >= MAX_ITEMS_PER_FILE) { break; } const item = toItem(entry); if (item) { items.push(item); } } return items.sort( (a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || a.range.start.line - b.range.start.line || a.range.start.column - b.range.start.column, ); } /** * Reads the payload of `lspStatus` or the result of `lsp.status`. * * @param raw - untrusted. * @returns the status, or null if the state is unknown. */ export function toStatus(raw: unknown): LspStatus | null { if (typeof raw !== "object" || raw === null) { return null; } const { state, message } = raw as Record; const known = LSP_STATES.find((s) => s === state); if (!known) { return null; } return { state: known, message: typeof message === "string" ? message : null }; } /** * Reads the payload of `lspProgress` or the `progress` of `lsp.status`. * * @param raw - untrusted. * @returns the running task, or null when none runs or it is malformed. */ export function toProgress(raw: unknown): LspProgress | null { if (typeof raw !== "object" || raw === null) { return null; } const { active, title, message, percentage } = raw as Record; if (active !== true) { return null; } return { title: typeof title === "string" ? title.slice(0, 200) : "", message: typeof message === "string" ? message.slice(0, 500) : null, percentage: typeof percentage === "number" && Number.isFinite(percentage) ? Math.round(Math.min(100, Math.max(0, percentage))) : null, }; } /** The Problems store. */ export const useProblemsStore = defineStore("problems", () => { /** Whether the tool window is shown in the bottom panel. */ const visible = ref(false); /** Whether the panel is expanded while Problems is shown. */ const expanded = ref(true); /** Files with diagnostics, sorted by path. */ const files = shallowRef([]); /** The language server's state; null before the first report. */ const lsp = ref(null); /** The server's running work-done progress task; null when none. */ const progress = ref(null); /** Key of the selected row. */ const selectedKey = ref(null); /** Bumped when the window should take the keyboard focus. */ const focusRequest = ref(0); /** Whether a focus request waits for the window (it may mount later). */ const focusPending = ref(false); /** Every diagnostic in display order. */ const rows = computed(() => files.value.flatMap((file) => file.items.map((item, index) => ({ key: `${file.path}#${String(index)}`, path: file.path, item })), ), ); /** Index of the selected row, -1 if none. */ const selectedIndex = computed(() => rows.value.findIndex((row) => row.key === selectedKey.value)); /** Counts by severity over all files. */ const counts = computed(() => { const out: Record = { error: 0, warning: 0, info: 0, hint: 0 }; for (const file of files.value) { for (const item of file.items) { out[item.severity] += 1; } } return out; }); /** * Replaces one file's diagnostics. * * @param path - project-relative path. * @param items - its diagnostics, already read; empty removes the file. */ function setFile(path: string, items: DiagnosticItem[]): void { const rest = files.value.filter((file) => file.path !== path); if (items.length > 0 && (rest.length < files.value.length || rest.length < MAX_FILES)) { rest.push({ path, items }); rest.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); } files.value = rest; publishDiagnostics(path, items); } /** Drops every file's diagnostics. */ function clear(): void { files.value = []; selectedKey.value = null; clearDiagnostics(); } /** Loads every file's diagnostics and the server's state from the engine. */ async function load(): Promise { const [list, status] = await Promise.all([run("diagnostics.list"), run("lsp.status")]); if (status.ok) { lsp.value = toStatus(status.value) ?? lsp.value; const value = status.value; const raw = typeof value === "object" && value !== null && !Array.isArray(value) ? value.progress : null; progress.value = toProgress(raw); } if (!list.ok) { return; } const value = list.value; const raw = typeof value === "object" && value !== null && !Array.isArray(value) ? value.files : null; if (!Array.isArray(raw)) { return; } clear(); for (const entry of raw) { if (typeof entry === "object" && entry !== null && !Array.isArray(entry) && typeof entry.path === "string") { setFile(entry.path, toItems(entry.items)); } } } /** * Applies one engine event. * * @param event - the event. */ function onEvent(event: EngineEventPayload): void { if (event.kind === "diagnosticsChanged") { if (typeof event.path === "string" && event.path !== "") { setFile(event.path, toItems(event.items)); } } else if (event.kind === "lspStatus") { lsp.value = toStatus(event) ?? lsp.value; if (lsp.value && lsp.value.state !== "ready" && lsp.value.state !== "starting") { progress.value = null; } } else if (event.kind === "lspProgress") { progress.value = toProgress(event); } else if (event.kind === "projectClosed") { clear(); lsp.value = null; progress.value = null; } else if (event.kind === "projectOpened") { void load(); } } /** Ends the event subscription; set while started. */ let unsubscribe: (() => void) | null = null; /** Subscribes to engine events and loads the current state. */ function start(): void { if (unsubscribe) { return; } unsubscribe = onEngineEvent(onEvent); void load(); } /** Ends the subscription. */ function stop(): void { unsubscribe?.(); unsubscribe = null; } /** Shows the tool window and asks it to take the focus: `problems.open`. */ function open(): void { visible.value = true; expanded.value = true; focusPending.value = true; focusRequest.value += 1; } /** Hides the tool window; the diagnostics stay. */ function hide(): void { visible.value = false; } /** * Selects a row. * * @param key - the row key, or null for none. */ function select(key: string | null): void { selectedKey.value = key; } /** * Moves the selection by `delta` rows, clamped to the list. * * @param delta - rows to move; positive is down. */ function move(delta: number): void { const list = rows.value; if (list.length === 0) { return; } const from = selectedIndex.value < 0 ? (delta > 0 ? -1 : list.length) : selectedIndex.value; const index = Math.min(list.length - 1, Math.max(0, from + delta)); selectedKey.value = list[index]?.key ?? null; } return { visible, expanded, files, lsp, progress, rows, counts, selectedKey, selectedIndex, focusRequest, focusPending, onEvent, load, start, stop, open, hide, select, move, }; });