From 003b7970e65c361a6c9f44dac086b15726accda7 Mon Sep 17 00:00:00 2001 From: danny Date: Wed, 14 Oct 2026 19:24:23 +0200 Subject: [PATCH] M1.5: main window layout and project tree against mocked engine events Left Project tool window (hide/show stripe, pointer and keyboard resize), editor area placeholder and status bar. Project tree with lazy project.children listings, WAI-ARIA keyboard navigation, Lucide icons, dimmed ignored/excluded entries and refresh on TreeChanged. Empty state runs project.openDialog. Pinia store fed only by engine events and command results; events come through a local onEngineEvent adapter until the desktop bridge (M1.4) lands. Lucide via @lucide/vue (the renamed lucide-vue-next, ISC). Co-Authored-By: Claude Opus 5.5 --- NOTICE | 2 +- docs/gaps.md | 3 +- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 5 +- ui/package.json | 1 + ui/pnpm-lock.yaml | 12 + ui/src/App.vue | 36 +- ui/src/components/layout/MainLayout.vue | 62 +++ ui/src/components/layout/ToolWindow.vue | 231 +++++++++++ .../components/project/ProjectToolWindow.vue | 105 +++++ ui/src/components/project/ProjectTree.vue | 367 ++++++++++++++++++ ui/src/components/project/engineEvents.ts | 79 ++++ ui/src/stores/project.ts | 340 ++++++++++++++++ ui/tests/layout/ToolWindow.test.ts | 46 +++ ui/tests/project/ProjectTree.test.ts | 230 +++++++++++ ui/tests/project/store.test.ts | 51 +++ 16 files changed, 1541 insertions(+), 32 deletions(-) create mode 100644 ui/src/components/layout/MainLayout.vue create mode 100644 ui/src/components/layout/ToolWindow.vue create mode 100644 ui/src/components/project/ProjectToolWindow.vue create mode 100644 ui/src/components/project/ProjectTree.vue create mode 100644 ui/src/components/project/engineEvents.ts create mode 100644 ui/src/stores/project.ts create mode 100644 ui/tests/layout/ToolWindow.test.ts create mode 100644 ui/tests/project/ProjectTree.test.ts create mode 100644 ui/tests/project/store.test.ts diff --git a/NOTICE b/NOTICE index 38625d4..804f848 100644 --- a/NOTICE +++ b/NOTICE @@ -12,7 +12,7 @@ are compiled or bundled into release builds are summarised below and must be kept up to date when one is added or removed. Bundled components (planned; update when added): - * Lucide icons (lucide-vue-next) — ISC License, https://lucide.dev + * Lucide icons (@lucide/vue, formerly lucide-vue-next) — ISC License, https://lucide.dev * Inter typeface (@fontsource/inter) — SIL Open Font License 1.1 * JetBrains Mono typeface (@fontsource/jetbrains-mono) — SIL Open Font License 1.1 * CodeMirror 6 — MIT License diff --git a/docs/gaps.md b/docs/gaps.md index ac33914..9be6137 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -8,7 +8,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t |---|---|---|---| | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | | G2 | Editor core: buffers, undo, multi-caret, save, recovery journal | M1 | ~30 h | -| G3 | Project model: VFS, file watching, project tree, tabs; command palette, settings, theme switching | M1 | ~30 h | +| G3 | Project model: VFS, file watching, project tree, tabs; command palette, settings, theme switching. Project tree UI and main window layout exist against a mocked engine (M1.5); wiring follows M1.4 | M1 | ~30 h | | G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h | @@ -33,5 +33,6 @@ Known smaller items from M0: | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | G3 note: project tree UI (M1.5) | | 2026-10-14 | minor | G1 closed; estimates for G2–G16; M0 follow-ups | | 2026-10-13 | major | Initial gap list | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e83b7dc..adca3ae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -13,7 +13,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Area | Weight | Score | Missing | Hours (one agent) | Evidence | |---|---:|---:|---|---:|---| | Editor core | 12 | 0% | everything | ~120 (est.) | — | -| Project view, VFS | 6 | 0% | everything | ~40 (est.) | — | +| Project view, VFS | 6 | 0% | everything reachable in the app | ~40 (est.) | M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine; not reachable in the app until M1.3/M1.4 | | Navigation | 10 | 0% | everything | ~120 (est.) | — | | Search and replace | 6 | 0% | everything | ~80 (est.) | — | | Code completion | 10 | 0% | everything | ~250 (est.) | — | @@ -52,5 +52,6 @@ No PHP feature. The foundation, verified on Windows 11: | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | Project view evidence: project tree UI (M1.5), score unchanged | | 2026-10-14 | minor | Hours per area, weights reviewed, M0 evidence | | 2026-10-13 | major | Baseline | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bb9c6bc..afa1996 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,9 +1,11 @@ # UI parity checklist -> **Status:** baseline · **Last updated:** 2026-10-13 +> **Status:** main window layout and project tree against a mocked engine (M1.5) · **Last updated:** 2026-10-14 - [ ] Main window: tool window stripes, editor area, status bar, navigation bar + - M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4). - [ ] Project tool window (tree, scroll from source, file operations) + - M1.5 (2026-10-14): tree of the open folder with lazy `project.children` listings, folders and PHP files with Lucide icons, ignored/excluded entries dimmed, keyboard navigation (WAI-ARIA tree: arrows, Home/End, Enter), double-click opens, refresh on `TreeChanged`, listing errors shown in the tree, empty state with Open Folder…. Vitest only, against a mocked engine. Missing: scroll from source (Select Opened File), expand/collapse all, views list, sort options, speed search, file colours, file operations. Behaviour notes: `plan/phpstorm/02-project-view.md`. - [ ] Editor tabs (pin, split, reorder, close others) - [ ] Command palette / search everywhere - [ ] Settings dialog with search @@ -20,4 +22,5 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | Notes on main window and project tool window (M1.5) | | 2026-10-13 | major | Baseline | diff --git a/ui/package.json b/ui/package.json index 2e4c50d..fd6a8f0 100644 --- a/ui/package.json +++ b/ui/package.json @@ -16,6 +16,7 @@ "test": "vitest run" }, "dependencies": { + "@lucide/vue": "^1.57.0", "@tauri-apps/api": "^2.12.3", "pinia": "^4.0.3", "vue": "^3.5.44" diff --git a/ui/pnpm-lock.yaml b/ui/pnpm-lock.yaml index 8898fdc..a98512f 100644 --- a/ui/pnpm-lock.yaml +++ b/ui/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + '@lucide/vue': + specifier: ^1.57.0 + version: 1.57.0(vue@3.5.44(typescript@6.0.3)) '@tauri-apps/api': specifier: ^2.12.3 version: 2.12.3 @@ -221,6 +224,11 @@ packages: '@keyv/serialize@1.1.1': resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + '@lucide/vue@1.57.0': + resolution: {integrity: sha512-l/D9mr+8Wb8uHl2vzHfcGVRkunJnq0NDmv8HFwXAL3UiYYxuNpDSd1uaCVqeR8+I1XY70dWA+R5W/pSpXWilMw==} + peerDependencies: + vue: '>=3.0.1' + '@one-ini/wasm@0.2.1': resolution: {integrity: sha512-TUqERXGNTifZ9y2g3wPxQrw3HpHv/02DsW3D90T9x0hhonrL1ZqpSmNrU2XkoIq0fP1N6gZfVQzy2Fw1ZvGBNg==} @@ -1375,6 +1383,10 @@ snapshots: '@keyv/serialize@1.1.1': {} + '@lucide/vue@1.57.0(vue@3.5.44(typescript@6.0.3))': + dependencies: + vue: 3.5.44(typescript@6.0.3) + '@one-ini/wasm@0.2.1': {} '@oxc-project/types@0.153.0': {} diff --git a/ui/src/App.vue b/ui/src/App.vue index ffda0ad..4f7c1f3 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -1,10 +1,10 @@ diff --git a/ui/src/components/layout/ToolWindow.vue b/ui/src/components/layout/ToolWindow.vue new file mode 100644 index 0000000..628dc0d --- /dev/null +++ b/ui/src/components/layout/ToolWindow.vue @@ -0,0 +1,231 @@ + + + + + diff --git a/ui/src/components/project/ProjectToolWindow.vue b/ui/src/components/project/ProjectToolWindow.vue new file mode 100644 index 0000000..bfaf7a1 --- /dev/null +++ b/ui/src/components/project/ProjectToolWindow.vue @@ -0,0 +1,105 @@ + + + + + diff --git a/ui/src/components/project/ProjectTree.vue b/ui/src/components/project/ProjectTree.vue new file mode 100644 index 0000000..52495ba --- /dev/null +++ b/ui/src/components/project/ProjectTree.vue @@ -0,0 +1,367 @@ + + + + + diff --git a/ui/src/components/project/engineEvents.ts b/ui/src/components/project/engineEvents.ts new file mode 100644 index 0000000..d16a84f --- /dev/null +++ b/ui/src/components/project/engineEvents.ts @@ -0,0 +1,79 @@ +/** + * Thin adapter between the project UI and the engine event stream. + * + * The desktop bridge (M1.4) will add a typed `onEngineEvent(handler) => + * unsubscribe` to `ui/src/ipc.ts`, fed by the Tauri event `engine://event`. + * Until it lands, this module provides the same signature backed by a local + * dispatcher so the store and its tests can be written against it. Wiring the + * real stream is a one-line change: replace the local {@link onEngineEvent} + * with `export { onEngineEvent } from "../../ipc";`. + * + * The event and payload shapes below follow the planned engine `Event` enum + * (M1.3) and are the frontend's assumption until that lands. + */ + +/** Kind of a project tree entry as reported by `project.children`. */ +export type TreeEntryKind = "dir" | "file"; + +/** One entry of a directory listing, as returned by `project.children`. */ +export interface TreeEntry { + /** File or directory name, without any path. */ + name: string; + /** Project-relative path with `/` separators; the root is `""`. */ + path: string; + /** Whether the entry is a directory or a file. */ + kind: TreeEntryKind; + /** Matched by an ignore rule (`.gitignore`, `.ignore`, global excludes). */ + ignored: boolean; + /** Excluded from the project model (for example `node_modules/`). */ + excluded?: boolean; +} + +/** The project root, as carried by the `ProjectOpened` event. */ +export interface ProjectRoot { + /** Absolute, canonical path of the root folder. */ + path: string; + /** Display name, usually the folder name. */ + name: string; +} + +/** + * Engine events the project UI reacts to. The engine sends more kinds + * (buffer events); consumers ignore any `type` they do not handle. + */ +export type EngineEvent = + | { type: "ProjectOpened"; root: ProjectRoot } + | { type: "ProjectClosed" } + | { type: "TreeChanged"; dir: string }; + +/** Callback receiving engine events. */ +export type EngineEventHandler = (event: EngineEvent) => void; + +/** Handlers subscribed through the local dispatcher. */ +const handlers = new Set(); + +/** + * Subscribes to engine events. + * + * @param handler - called for every event, in order of arrival. + * @returns a function that removes the subscription. + */ +export function onEngineEvent(handler: EngineEventHandler): () => void { + handlers.add(handler); + return () => { + handlers.delete(handler); + }; +} + +/** + * Delivers an event to every subscriber of the local dispatcher. Used by + * tests and as the mock engine until the desktop bridge exists; removed when + * {@link onEngineEvent} is wired to `ui/src/ipc.ts`. + * + * @param event - the event to deliver. + */ +export function emitEngineEvent(event: EngineEvent): void { + for (const handler of [...handlers]) { + handler(event); + } +} diff --git a/ui/src/stores/project.ts b/ui/src/stores/project.ts new file mode 100644 index 0000000..5f4f1f7 --- /dev/null +++ b/ui/src/stores/project.ts @@ -0,0 +1,340 @@ +/** + * State of the open project and its tree, for the project tool window. + * + * Fed only by engine events (`ProjectOpened`, `ProjectClosed`, + * `TreeChanged`) and by results of engine commands (`project.children`). + * Directory listings load lazily when a folder is first expanded. Selection + * and expansion are view state kept here so the tree survives remounts. + * Command failures are stored and shown, never thrown. + */ +import { defineStore } from "pinia"; +import { computed, ref } from "vue"; +import { run, type EngineError } from "../ipc"; +import { + onEngineEvent, + type EngineEvent, + type ProjectRoot, + type TreeEntry, +} from "../components/project/engineEvents"; + +/** Engine command ids used by the project tool window. */ +export const PROJECT_COMMANDS = { + /** Lists one directory: params `{ dir }`, result `TreeEntry[]`. */ + children: "project.children", + /** Shows the folder picker and opens the chosen folder. */ + openDialog: "project.openDialog", + /** Opens a file in an editor buffer: params `{ path }`. */ + openFile: "file.open", +} as const; + +/** Loading state of one directory listing. */ +export interface DirState { + /** Entries in engine order, or null while not loaded yet. */ + entries: TreeEntry[] | null; + /** Whether a `project.children` call is in flight. */ + loading: boolean; + /** Error of the last `project.children` call, null if it succeeded. */ + error: EngineError | null; +} + +/** A visible line of the flattened tree. */ +export type TreeRow = + | { + /** An entry. */ + kind: "entry"; + /** The entry. */ + entry: TreeEntry; + /** Nesting depth, 0 for children of the root. */ + depth: number; + /** Whether the entry is an expanded directory. */ + expanded: boolean; + } + | { + /** Placeholder while a directory loads. */ + kind: "loading"; + /** Directory being loaded. */ + dir: string; + /** Nesting depth of the placeholder. */ + depth: number; + } + | { + /** A failed listing. */ + kind: "error"; + /** Directory whose listing failed. */ + dir: string; + /** Nesting depth of the message. */ + depth: number; + /** The error to show. */ + error: EngineError; + }; + +/** + * Returns the parent of a project-relative path. + * + * @param path - a path such as `src/App.php`. + * @returns the parent (`src`), or `""` for top-level entries. + */ +export function parentOf(path: string): string { + const slash = path.lastIndexOf("/"); + return slash < 0 ? "" : path.slice(0, slash); +} + +/** + * Whether `path` is `dir` itself or lies inside it. + * + * @param path - the path to test. + * @param dir - a directory path; `""` is the root and contains everything. + */ +function isWithin(path: string, dir: string): boolean { + return dir === "" || path === dir || path.startsWith(`${dir}/`); +} + +/** Store of the open project, its lazily loaded tree and the tree view state. */ +export const useProjectStore = defineStore("project", () => { + /** The open project, null when no folder is open. */ + const root = ref(null); + /** Listings by directory path (`""` is the root). */ + const dirs = ref>({}); + /** Expanded directories. */ + const expanded = ref>(new Set()); + /** Path of the selected entry, null if none. */ + const selected = ref(null); + /** Error of the last open-folder or open-file command, null if none. */ + const lastError = ref(null); + /** Latest request number per directory, to drop stale listings. */ + const requests = new Map(); + /** Counter for {@link requests}. */ + let nextRequest = 0; + /** Unsubscribe function of the event subscription, null if not started. */ + let unsubscribe: (() => void) | null = null; + + /** Clears everything that belongs to an open project. */ + function reset(): void { + dirs.value = {}; + expanded.value = new Set(); + selected.value = null; + requests.clear(); + } + + /** + * Entries cached for a directory. + * + * @param dir - the directory path. + * @returns its last loaded entries, or null if never loaded. + */ + function cachedEntries(dir: string): TreeEntry[] | null { + return dirs.value[dir]?.entries ?? null; + } + + /** + * Loads (or reloads) one directory listing through `project.children`. + * A failure is stored on the directory; earlier entries are kept so a + * failed refresh does not empty the tree. + * + * @param dir - project-relative directory, `""` for the root. + */ + async function loadChildren(dir: string): Promise { + const request = ++nextRequest; + requests.set(dir, request); + dirs.value[dir] = { entries: cachedEntries(dir), loading: true, error: null }; + const result = await run(PROJECT_COMMANDS.children, { dir }); + if (requests.get(dir) !== request) { + return; + } + if (result.ok) { + const entries = result.value; + dirs.value[dir] = { entries, loading: false, error: null }; + prune(dir, entries); + } else { + dirs.value[dir] = { entries: cachedEntries(dir), loading: false, error: result.error }; + } + } + + /** + * Drops cached listings, expansion and selection below `dir` for entries + * that disappeared from its new listing. + * + * @param dir - the reloaded directory. + * @param entries - its new entries. + */ + function prune(dir: string, entries: TreeEntry[]): void { + const alive = new Set(entries.map((entry) => entry.path)); + const gone = (path: string): boolean => { + if (path === dir || !isWithin(path, dir)) { + return false; + } + const rest = dir === "" ? path : path.slice(dir.length + 1); + const first = rest.split("/")[0] ?? rest; + return !alive.has(dir === "" ? first : `${dir}/${first}`); + }; + for (const path of Object.keys(dirs.value)) { + if (gone(path)) { + Reflect.deleteProperty(dirs.value, path); + requests.delete(path); + } + } + const keep = [...expanded.value].filter((path) => !gone(path)); + if (keep.length !== expanded.value.size) { + expanded.value = new Set(keep); + } + if (selected.value !== null && gone(selected.value)) { + selected.value = null; + } + } + + /** + * Expands a directory, loading its listing on first expansion. + * + * @param dir - the directory path. + */ + async function expand(dir: string): Promise { + expanded.value.add(dir); + const state = dirs.value[dir]; + if (!state || (state.entries === null && !state.loading)) { + await loadChildren(dir); + } + } + + /** + * Collapses a directory; its listing stays cached. + * + * @param dir - the directory path. + */ + function collapse(dir: string): void { + expanded.value.delete(dir); + } + + /** + * Expands a collapsed directory or collapses an expanded one. + * + * @param dir - the directory path. + */ + async function toggle(dir: string): Promise { + if (expanded.value.has(dir)) { + collapse(dir); + } else { + await expand(dir); + } + } + + /** + * Selects an entry. + * + * @param path - the entry path, or null to clear the selection. + */ + function select(path: string | null): void { + selected.value = path; + } + + /** + * Runs the open-folder command. The engine reports the opened project + * with a `ProjectOpened` event; cancelling the picker is not an error. + */ + async function openFolder(): Promise { + const result = await run(PROJECT_COMMANDS.openDialog); + lastError.value = result.ok ? null : result.error; + } + + /** + * Asks the engine to open a file in an editor buffer. The editor learns + * about the buffer from engine events. + * + * @param path - project-relative path of the file. + */ + async function openFile(path: string): Promise { + const result = await run(PROJECT_COMMANDS.openFile, { path }); + lastError.value = result.ok ? null : result.error; + } + + /** + * Applies one engine event to the store. + * + * @param event - the event; kinds the project view does not use are ignored. + */ + function handleEvent(event: EngineEvent): void { + switch (event.type) { + case "ProjectOpened": + reset(); + root.value = event.root; + lastError.value = null; + void loadChildren(""); + break; + case "ProjectClosed": + reset(); + root.value = null; + break; + case "TreeChanged": + if (root.value !== null && dirs.value[event.dir]?.entries) { + void loadChildren(event.dir); + } + break; + default: + break; + } + } + + /** Subscribes to engine events; calling it again has no effect. */ + function start(): void { + unsubscribe ??= onEngineEvent(handleEvent); + } + + /** Ends the event subscription. */ + function stop(): void { + unsubscribe?.(); + unsubscribe = null; + } + + /** + * The tree flattened into visible rows: entries of the root and of every + * expanded directory, with a loading or error row where a listing is + * pending or failed. + */ + const rows = computed(() => { + const out: TreeRow[] = []; + const visit = (dir: string, depth: number): void => { + const state = dirs.value[dir]; + if (!state) { + return; + } + if (state.error) { + out.push({ kind: "error", dir, depth, error: state.error }); + } + if (state.entries === null) { + if (state.loading) { + out.push({ kind: "loading", dir, depth }); + } + return; + } + for (const entry of state.entries) { + const open = entry.kind === "dir" && expanded.value.has(entry.path); + out.push({ kind: "entry", entry, depth, expanded: open }); + if (open) { + visit(entry.path, depth + 1); + } + } + }; + if (root.value !== null) { + visit("", 0); + } + return out; + }); + + return { + root, + dirs, + expanded, + selected, + lastError, + rows, + loadChildren, + expand, + collapse, + toggle, + select, + openFolder, + openFile, + handleEvent, + start, + stop, + }; +}); diff --git a/ui/tests/layout/ToolWindow.test.ts b/ui/tests/layout/ToolWindow.test.ts new file mode 100644 index 0000000..f78f574 --- /dev/null +++ b/ui/tests/layout/ToolWindow.test.ts @@ -0,0 +1,46 @@ +/** + * Tests for the left tool window: hide and show, and keyboard resizing + * clamped to the allowed range. + */ +import { mount } from "@vue/test-utils"; +import { describe, expect, it } from "vitest"; +import ToolWindow from "../../src/components/layout/ToolWindow.vue"; + +describe("ToolWindow", () => { + it("hides to a stripe and shows again", async () => { + const wrapper = mount(ToolWindow, { + props: { + title: "Project", + open: true, + "onUpdate:open": (open: boolean) => wrapper.setProps({ open }), + }, + slots: { default: "

tree

" }, + }); + expect(wrapper.find("[data-test=content]").exists()).toBe(true); + await wrapper.get("[data-test=tool-window-hide]").trigger("click"); + expect(wrapper.find("[data-test=content]").exists()).toBe(false); + expect(wrapper.find("[data-test=tool-window-stripe]").exists()).toBe(true); + await wrapper.get("[data-test=tool-window-show]").trigger("click"); + expect(wrapper.find("[data-test=content]").exists()).toBe(true); + }); + + it("resizes with the keyboard within the limits", async () => { + const wrapper = mount(ToolWindow, { + props: { + title: "Project", + width: 200, + minWidth: 150, + maxWidth: 230, + "onUpdate:width": (width: number) => wrapper.setProps({ width }), + }, + }); + const splitter = wrapper.get("[data-test=tool-window-splitter]"); + await splitter.trigger("keydown", { key: "ArrowRight" }); + expect(wrapper.get("[data-test=tool-window]").attributes("style")).toContain("width: 212px"); + await splitter.trigger("keydown", { key: "ArrowRight", shiftKey: true }); + expect(wrapper.get("[data-test=tool-window]").attributes("style")).toContain("width: 230px"); + await splitter.trigger("keydown", { key: "ArrowLeft", shiftKey: true }); + await splitter.trigger("keydown", { key: "ArrowLeft", shiftKey: true }); + expect(wrapper.get("[data-test=tool-window]").attributes("style")).toContain("width: 150px"); + }); +}); diff --git a/ui/tests/project/ProjectTree.test.ts b/ui/tests/project/ProjectTree.test.ts new file mode 100644 index 0000000..16468ce --- /dev/null +++ b/ui/tests/project/ProjectTree.test.ts @@ -0,0 +1,230 @@ +/** + * Tests for the Project tool window: empty state, lazy expansion, keyboard + * navigation, refresh on `TreeChanged` and error display. The engine is + * mocked: `invoke` answers `project.children` from an in-memory folder and + * events go through the local dispatcher in `engineEvents.ts`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { emitEngineEvent, type TreeEntry } from "../../src/components/project/engineEvents"; +import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue"; +import { useProjectStore } from "../../src/stores/project"; + +/** In-memory folder listings by directory, as `project.children` returns them. */ +let folder: Record; + +/** + * Builds an entry. + * + * @param path - project-relative path. + * @param kind - entry kind. + * @param ignored - ignore flag. + */ +function entry(path: string, kind: "dir" | "file", ignored = false): TreeEntry { + return { name: path.split("/").pop() ?? path, path, kind, ignored }; +} + +/** Mock engine: answers `project.children`, accepts other commands. */ +function engine(command: string, args: { command: string; params: { dir?: string } }): unknown { + if (command !== "engine_execute") { + return Promise.reject(new Error(`unexpected ${command}`)); + } + if (args.command === "project.children") { + const dir = args.params.dir ?? ""; + const entries = folder[dir]; + return entries + ? Promise.resolve(entries) + : Promise.reject(Object.assign(new Error(`cannot list ${dir}`), { code: "not_found" })); + } + return Promise.resolve(null); +} + +/** Mounts the tool window and opens the mock project through an event. */ +async function mountOpen(): Promise { + const wrapper = mount(ProjectToolWindow, { attachTo: document.body }); + emitEngineEvent({ type: "ProjectOpened", root: { path: "/tmp/demo", name: "demo" } }); + await flushPromises(); + return wrapper; +} + +/** Visible entry paths, in order. */ +function paths(wrapper: VueWrapper): string[] { + return wrapper.findAll("[data-test=tree-row]").map((row) => row.attributes("data-path") ?? ""); +} + +/** + * Presses a key on the tree and waits for the engine. + * + * @param wrapper - the mounted tool window. + * @param key - the key name. + */ +async function press(wrapper: VueWrapper, key: string): Promise { + await wrapper.get("[data-test=project-tree]").trigger("keydown", { key }); + await flushPromises(); +} + +/** Path of the selected row, or null. */ +function selectedPath(wrapper: VueWrapper): string | null { + const row = wrapper.find("[data-test=tree-row][aria-selected=true]"); + return row.exists() ? (row.attributes("data-path") ?? null) : null; +} + +/** Calls of `project.children`, as the `dir` params. */ +function childrenCalls(): string[] { + return invoke.mock.calls + .filter((call) => (call[1] as { command: string }).command === "project.children") + .map((call) => (call[1] as { params: { dir: string } }).params.dir); +} + +describe("ProjectToolWindow", () => { + let wrapper: VueWrapper | null = null; + + beforeEach(() => { + setActivePinia(createPinia()); + invoke.mockReset(); + invoke.mockImplementation(engine); + folder = { + "": [entry("src", "dir"), entry("vendor", "dir"), entry("node_modules", "dir", true), entry("index.php", "file")], + src: [entry("src/Controller", "dir"), entry("src/App.php", "file")], + "src/Controller": [entry("src/Controller/Home.php", "file")], + }; + }); + + afterEach(() => { + wrapper?.unmount(); + wrapper = null; + }); + + it("shows the empty state and runs the open-folder command", async () => { + wrapper = mount(ProjectToolWindow); + expect(wrapper.find("[data-test=project-empty]").exists()).toBe(true); + await wrapper.get("[data-test=open-folder]").trigger("click"); + await flushPromises(); + expect(invoke).toHaveBeenCalledWith("engine_execute", { command: "project.openDialog", params: {} }); + }); + + it("shows an open-folder failure", async () => { + invoke.mockRejectedValue({ code: "internal", message: "no dialog" }); + wrapper = mount(ProjectToolWindow); + await wrapper.get("[data-test=open-folder]").trigger("click"); + await flushPromises(); + expect(wrapper.get("[data-test=project-error]").text()).toBe("no dialog"); + }); + + it("lists the root after ProjectOpened and dims ignored entries", async () => { + wrapper = await mountOpen(); + expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]); + expect(childrenCalls()).toEqual([""]); + const rows = wrapper.findAll("[data-test=tree-row]"); + expect(rows[2]?.classes()).toContain("tree__row--dimmed"); + expect(rows[0]?.classes()).not.toContain("tree__row--dimmed"); + }); + + it("expands lazily on chevron click and collapses again", async () => { + wrapper = await mountOpen(); + await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click"); + await flushPromises(); + expect(paths(wrapper)).toEqual(["src", "src/Controller", "src/App.php", "vendor", "node_modules", "index.php"]); + expect(childrenCalls()).toEqual(["", "src"]); + await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click"); + await flushPromises(); + expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]); + await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click"); + await flushPromises(); + expect(childrenCalls()).toEqual(["", "src"]); + }); + + it("navigates with the keyboard", async () => { + wrapper = await mountOpen(); + await wrapper.get("[data-test=project-tree]").trigger("focus"); + expect(selectedPath(wrapper)).toBe("src"); + await press(wrapper, "ArrowRight"); + expect(paths(wrapper)).toContain("src/App.php"); + expect(selectedPath(wrapper)).toBe("src"); + await press(wrapper, "ArrowRight"); + expect(selectedPath(wrapper)).toBe("src/Controller"); + await press(wrapper, "Enter"); + expect(paths(wrapper)).toContain("src/Controller/Home.php"); + await press(wrapper, "ArrowDown"); + expect(selectedPath(wrapper)).toBe("src/Controller/Home.php"); + await press(wrapper, "Enter"); + expect(invoke).toHaveBeenCalledWith("engine_execute", { + command: "file.open", + params: { path: "src/Controller/Home.php" }, + }); + await press(wrapper, "ArrowLeft"); + expect(selectedPath(wrapper)).toBe("src/Controller"); + await press(wrapper, "ArrowLeft"); + expect(paths(wrapper)).not.toContain("src/Controller/Home.php"); + await press(wrapper, "ArrowUp"); + expect(selectedPath(wrapper)).toBe("src"); + await press(wrapper, "ArrowUp"); + expect(selectedPath(wrapper)).toBe("src"); + await press(wrapper, "End"); + expect(selectedPath(wrapper)).toBe("index.php"); + await press(wrapper, "ArrowDown"); + expect(selectedPath(wrapper)).toBe("index.php"); + await press(wrapper, "Home"); + expect(selectedPath(wrapper)).toBe("src"); + const tree = wrapper.get("[data-test=project-tree]"); + expect(tree.attributes("aria-activedescendant")).toBe(wrapper.get("[aria-selected=true]").attributes("id")); + }); + + it("reloads a loaded directory on TreeChanged and drops removed entries", async () => { + wrapper = await mountOpen(); + await wrapper.get("[data-test=project-tree]").trigger("focus"); + await press(wrapper, "ArrowRight"); + await press(wrapper, "ArrowRight"); + await press(wrapper, "ArrowRight"); + expect(selectedPath(wrapper)).toBe("src/Controller"); + folder.src = [entry("src/App.php", "file"), entry("src/Kernel.php", "file")]; + emitEngineEvent({ type: "TreeChanged", dir: "src" }); + await flushPromises(); + expect(paths(wrapper)).toEqual(["src", "src/App.php", "src/Kernel.php", "vendor", "node_modules", "index.php"]); + expect(selectedPath(wrapper)).toBeNull(); + const store = useProjectStore(); + expect(store.expanded.has("src/Controller")).toBe(false); + expect(store.dirs["src/Controller"]).toBeUndefined(); + }); + + it("ignores TreeChanged for directories never loaded", async () => { + wrapper = await mountOpen(); + emitEngineEvent({ type: "TreeChanged", dir: "vendor" }); + await flushPromises(); + expect(childrenCalls()).toEqual([""]); + }); + + it("shows a project.children error in the tree instead of throwing", async () => { + wrapper = await mountOpen(); + await wrapper.findAll("[data-test=tree-chevron]")[1]?.trigger("click"); + await flushPromises(); + const error = wrapper.get("[data-test=tree-error]"); + expect(error.text()).toBe("cannot list vendor"); + expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]); + }); + + it("keeps old entries when a refresh fails", async () => { + wrapper = await mountOpen(); + Reflect.deleteProperty(folder, ""); + emitEngineEvent({ type: "TreeChanged", dir: "" }); + await flushPromises(); + expect(wrapper.get("[data-test=tree-error]").text()).toBe("cannot list"); + expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]); + }); + + it("returns to the empty state on ProjectClosed and unsubscribes on unmount", async () => { + wrapper = await mountOpen(); + emitEngineEvent({ type: "ProjectClosed" }); + await flushPromises(); + expect(wrapper.find("[data-test=project-empty]").exists()).toBe(true); + wrapper.unmount(); + wrapper = null; + emitEngineEvent({ type: "ProjectOpened", root: { path: "/tmp/other", name: "other" } }); + expect(useProjectStore().root).toBeNull(); + }); +}); diff --git a/ui/tests/project/store.test.ts b/ui/tests/project/store.test.ts new file mode 100644 index 0000000..01ce404 --- /dev/null +++ b/ui/tests/project/store.test.ts @@ -0,0 +1,51 @@ +/** + * Tests for the project store on its own: stale listings are dropped and + * events of unknown kinds are ignored. + */ +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import type { EngineEvent } from "../../src/components/project/engineEvents"; +import { parentOf, useProjectStore } from "../../src/stores/project"; + +describe("project store", () => { + beforeEach(() => { + setActivePinia(createPinia()); + invoke.mockReset(); + }); + + it("drops a listing that was superseded by a newer request", async () => { + const resolvers: ((value: unknown) => void)[] = []; + invoke.mockImplementation(() => new Promise((resolve) => resolvers.push(resolve))); + const store = useProjectStore(); + store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } }); + const second = store.loadChildren(""); + resolvers[1]?.([{ name: "new.php", path: "new.php", kind: "file", ignored: false }]); + await second; + resolvers[0]?.([{ name: "old.php", path: "old.php", kind: "file", ignored: false }]); + await Promise.resolve(); + expect(store.rows.map((row) => (row.kind === "entry" ? row.entry.path : row.kind))).toEqual(["new.php"]); + }); + + it("shows a loading row while the root lists", () => { + invoke.mockImplementation(() => new Promise(() => undefined)); + const store = useProjectStore(); + store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } }); + expect(store.rows).toEqual([{ kind: "loading", dir: "", depth: 0 }]); + }); + + it("ignores events it does not handle", () => { + const store = useProjectStore(); + store.handleEvent({ type: "BufferOpened" } as unknown as EngineEvent); + expect(store.root).toBeNull(); + expect(invoke).not.toHaveBeenCalled(); + }); + + it("computes parents", () => { + expect(parentOf("a/b/c.php")).toBe("a/b"); + expect(parentOf("c.php")).toBe(""); + }); +});