M1.4: desktop bridge: engine events to the window, folder picker, live project tree
The desktop host publishes every engine event, from commands and from a
pump thread that calls Engine::pump_vfs every 100 ms, to control channel
subscribers and to the window as the Tauri event engine://event, in engine
order. ui/src/ipc.ts gets a typed onEngineEvent; its first subscription
calls engine_ready, and the host replays the current project and buffers,
so a project opened from the command line (lutra-desktop --control PORT
PATH) reaches the UI. project.openDialog returns Effect::PickFolder; the
host shows the native folder picker (tauri-plugin-dialog, licence checked)
and opens the choice, one picker at a time, cancel is not an error.
Capabilities shrink to event listen/unlisten.
Contract fix: the M1.5 project UI assumed shapes the engine does not use.
engineEvents.ts now translates engine events ({kind: projectOpened, ...})
and project.children results ({dir, entries, truncated}) into the UI types,
keeping role and truncated; the store maps listings through
toTreeEntries() and the project tests use the real engine shapes.
Verified in the running app on Windows 11: tree of a project given on the
command line, expanding src, a file created on disk appearing live, the
folder picker opening one dialog and opening the chosen folder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
69130d1efb
commit
dd98636de4
23 changed files with 751 additions and 99 deletions
|
|
@ -1,32 +1,49 @@
|
|||
/**
|
||||
* Thin adapter between the project UI and the engine event stream.
|
||||
* Thin adapter between the project UI and the engine.
|
||||
*
|
||||
* 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";`.
|
||||
* Translates the engine's contract into the types the project store and tree
|
||||
* use: engine events (`ui/src/ipc.ts` › `onEngineEvent`, tagged by `kind`)
|
||||
* become {@link EngineEvent}s, and `project.children` results become
|
||||
* {@link TreeListing}s through {@link toTreeEntries}. Keeping the
|
||||
* translation here lets the store stay independent of the wire format.
|
||||
*
|
||||
* The event and payload shapes below follow the planned engine `Event` enum
|
||||
* (M1.3) and are the frontend's assumption until that lands.
|
||||
* Subscriptions go through a local dispatcher: the first handler opens one
|
||||
* subscription to the real event stream, the last one closes it. Tests feed
|
||||
* the dispatcher with {@link emitEngineEvent} using engine payloads, so the
|
||||
* translation is tested too.
|
||||
*/
|
||||
import { onEngineEvent as onIpcEngineEvent, type EngineEventPayload } from "../../ipc";
|
||||
|
||||
/** Kind of a project tree entry as reported by `project.children`. */
|
||||
/** Kind of a project tree entry. Engine kinds `file` and `other` are both leaves. */
|
||||
export type TreeEntryKind = "dir" | "file";
|
||||
|
||||
/** One entry of a directory listing, as returned by `project.children`. */
|
||||
/** Lutra's role for an entry: third-party `library` code or `excluded` from the project model. */
|
||||
export type EntryRole = "normal" | "library" | "excluded";
|
||||
|
||||
/** One entry of a directory listing. */
|
||||
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. */
|
||||
/** Whether the entry is a directory or a leaf. */
|
||||
kind: TreeEntryKind;
|
||||
/** Matched by an ignore rule (`.gitignore`, `.ignore`, global excludes). */
|
||||
ignored: boolean;
|
||||
/** Excluded from the project model (for example `node_modules/`). */
|
||||
/** Lutra's role for the entry; `normal` when the engine did not send one. */
|
||||
role?: EntryRole;
|
||||
/** Excluded from the project model (for example `node_modules/`); same as `role === "excluded"`. */
|
||||
excluded?: boolean;
|
||||
/** Neither a file nor a directory (a broken link, a socket). */
|
||||
special?: boolean;
|
||||
}
|
||||
|
||||
/** A translated `project.children` result. */
|
||||
export interface TreeListing {
|
||||
/** The entries, in engine order. */
|
||||
entries: TreeEntry[];
|
||||
/** The directory had more entries than the engine lists. */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/** The project root, as carried by the `ProjectOpened` event. */
|
||||
|
|
@ -38,42 +55,134 @@ export interface ProjectRoot {
|
|||
}
|
||||
|
||||
/**
|
||||
* Engine events the project UI reacts to. The engine sends more kinds
|
||||
* (buffer events); consumers ignore any `type` they do not handle.
|
||||
* Engine events the project UI reacts to. Other engine events are not
|
||||
* translated and never reach project handlers.
|
||||
*/
|
||||
export type EngineEvent =
|
||||
| { type: "ProjectOpened"; root: ProjectRoot }
|
||||
| { type: "ProjectClosed" }
|
||||
| { type: "TreeChanged"; dir: string };
|
||||
|
||||
/** Callback receiving engine events. */
|
||||
/** Callback receiving project events. */
|
||||
export type EngineEventHandler = (event: EngineEvent) => void;
|
||||
|
||||
/**
|
||||
* Translates an engine event into a project event.
|
||||
*
|
||||
* @param payload - the engine event.
|
||||
* @returns the project event, or null for kinds the project UI ignores.
|
||||
*/
|
||||
export function toProjectEvent(payload: EngineEventPayload): EngineEvent | null {
|
||||
switch (payload.kind) {
|
||||
case "projectOpened":
|
||||
return { type: "ProjectOpened", root: { path: payload.root, name: payload.name } };
|
||||
case "projectClosed":
|
||||
return { type: "ProjectClosed" };
|
||||
case "treeChanged":
|
||||
return { type: "TreeChanged", dir: payload.dir };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a string field of an unknown object. */
|
||||
function stringField(value: Record<string, unknown>, key: string): string | null {
|
||||
const field = value[key];
|
||||
return typeof field === "string" ? field : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates one engine entry.
|
||||
*
|
||||
* @param raw - an entry of the engine's `entries` array.
|
||||
* @returns the tree entry, or null if the entry is malformed.
|
||||
*/
|
||||
function toTreeEntry(raw: unknown): TreeEntry | null {
|
||||
if (typeof raw !== "object" || raw === null) {
|
||||
return null;
|
||||
}
|
||||
const value = raw as Record<string, unknown>;
|
||||
const name = stringField(value, "name");
|
||||
const path = stringField(value, "path");
|
||||
const kind = stringField(value, "kind");
|
||||
if (name === null || path === null || kind === null) {
|
||||
return null;
|
||||
}
|
||||
const roleField = stringField(value, "role");
|
||||
const role: EntryRole = roleField === "library" || roleField === "excluded" ? roleField : "normal";
|
||||
return {
|
||||
name,
|
||||
path,
|
||||
kind: kind === "directory" ? "dir" : "file",
|
||||
ignored: value.ignored === true,
|
||||
role,
|
||||
excluded: role === "excluded",
|
||||
special: kind === "other",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates a `project.children` result
|
||||
* (`{ dir, entries: [{ name, path, kind, ignored, role }], truncated }`).
|
||||
* Malformed entries are skipped.
|
||||
*
|
||||
* @param value - the command result.
|
||||
* @returns the listing, or null if the result has no `entries` array.
|
||||
*/
|
||||
export function toTreeEntries(value: unknown): TreeListing | null {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return null;
|
||||
}
|
||||
const result = value as Record<string, unknown>;
|
||||
if (!Array.isArray(result.entries)) {
|
||||
return null;
|
||||
}
|
||||
const entries: TreeEntry[] = [];
|
||||
for (const raw of result.entries as unknown[]) {
|
||||
const entry = toTreeEntry(raw);
|
||||
if (entry) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
return { entries, truncated: result.truncated === true };
|
||||
}
|
||||
|
||||
/** Handlers subscribed through the local dispatcher. */
|
||||
const handlers = new Set<EngineEventHandler>();
|
||||
|
||||
/** Ends the subscription to the real event stream, null while closed. */
|
||||
let stopIpc: (() => void) | null = null;
|
||||
|
||||
/**
|
||||
* Subscribes to engine events.
|
||||
* Delivers an engine event to every project handler, translated. Used by
|
||||
* the real event stream and by tests.
|
||||
*
|
||||
* @param payload - the engine event.
|
||||
*/
|
||||
export function emitEngineEvent(payload: EngineEventPayload): void {
|
||||
const event = toProjectEvent(payload);
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
for (const handler of [...handlers]) {
|
||||
handler(event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to project 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);
|
||||
stopIpc ??= onIpcEngineEvent(emitEngineEvent);
|
||||
return () => {
|
||||
handlers.delete(handler);
|
||||
if (handlers.size === 0) {
|
||||
stopIpc?.();
|
||||
stopIpc = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,71 @@
|
|||
*
|
||||
* Every user-visible action runs as an engine command through {@link run}.
|
||||
* Calls never reject: failures come back as `{ ok: false, error }` so that
|
||||
* every caller has to handle them.
|
||||
* every caller has to handle them. State changes arrive as engine events
|
||||
* through {@link onEngineEvent}.
|
||||
*/
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
|
||||
/** Name of the Tauri event that carries engine events. */
|
||||
export const ENGINE_EVENT = "engine://event";
|
||||
|
||||
/**
|
||||
* An engine event as the desktop shell emits it: the engine's `Event`,
|
||||
* tagged by `kind`. Paths are project-relative with `/`; the root is `""`.
|
||||
*/
|
||||
export type EngineEventPayload =
|
||||
| { kind: "projectOpened"; root: string; name: string }
|
||||
| { kind: "projectClosed" }
|
||||
| { kind: "treeChanged"; dir: string }
|
||||
| { kind: "bufferOpened"; id: number; path: string }
|
||||
| { kind: "bufferChanged"; id: number; version: number }
|
||||
| { kind: "dirtyChanged"; id: number; dirty: boolean }
|
||||
| { kind: "bufferClosed"; id: number }
|
||||
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
|
||||
| { kind: "watchFailed"; message: string };
|
||||
|
||||
/** Callback receiving engine events. */
|
||||
export type EngineEventHandler = (event: EngineEventPayload) => void;
|
||||
|
||||
/** Whether the shell was told that the frontend listens (`engine_ready`). */
|
||||
let announced = false;
|
||||
|
||||
/**
|
||||
* Subscribes to engine events. The first successful subscription tells the
|
||||
* shell that the frontend listens, so it replays the current project state
|
||||
* the page may have missed while loading. Outside the Tauri shell (tests,
|
||||
* a plain browser) subscribing fails quietly and no events arrive.
|
||||
*
|
||||
* @param handler - called for every event, in order of arrival.
|
||||
* @returns a function that ends the subscription.
|
||||
*/
|
||||
export function onEngineEvent(handler: EngineEventHandler): () => void {
|
||||
let unlisten: UnlistenFn | null = null;
|
||||
let cancelled = false;
|
||||
listen<EngineEventPayload>(ENGINE_EVENT, (event) => {
|
||||
handler(event.payload);
|
||||
})
|
||||
.then((fn) => {
|
||||
if (cancelled) {
|
||||
fn();
|
||||
return;
|
||||
}
|
||||
unlisten = fn;
|
||||
if (!announced) {
|
||||
announced = true;
|
||||
invoke("engine_ready").catch(() => {
|
||||
announced = false;
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unlisten?.();
|
||||
unlisten = null;
|
||||
};
|
||||
}
|
||||
|
||||
/** A JSON value as exchanged with the engine. */
|
||||
export type JsonValue =
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { computed, ref } from "vue";
|
|||
import { run, type EngineError } from "../ipc";
|
||||
import {
|
||||
onEngineEvent,
|
||||
toTreeEntries,
|
||||
type EngineEvent,
|
||||
type ProjectRoot,
|
||||
type TreeEntry,
|
||||
|
|
@ -19,7 +20,7 @@ import {
|
|||
|
||||
/** Engine command ids used by the project tool window. */
|
||||
export const PROJECT_COMMANDS = {
|
||||
/** Lists one directory: params `{ dir }`, result `TreeEntry[]`. */
|
||||
/** Lists one directory: params `{ dir }`, result `{ dir, entries, truncated }` (see `toTreeEntries`). */
|
||||
children: "project.children",
|
||||
/** Shows the folder picker and opens the chosen folder. */
|
||||
openDialog: "project.openDialog",
|
||||
|
|
@ -35,6 +36,8 @@ export interface DirState {
|
|||
loading: boolean;
|
||||
/** Error of the last `project.children` call, null if it succeeded. */
|
||||
error: EngineError | null;
|
||||
/** The engine listed only part of the directory. */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/** A visible line of the flattened tree. */
|
||||
|
|
@ -136,17 +139,26 @@ export const useProjectStore = defineStore("project", () => {
|
|||
async function loadChildren(dir: string): Promise<void> {
|
||||
const request = ++nextRequest;
|
||||
requests.set(dir, request);
|
||||
dirs.value[dir] = { entries: cachedEntries(dir), loading: true, error: null };
|
||||
const result = await run<TreeEntry[]>(PROJECT_COMMANDS.children, { dir });
|
||||
const truncated = dirs.value[dir]?.truncated ?? false;
|
||||
dirs.value[dir] = { entries: cachedEntries(dir), loading: true, error: null, truncated };
|
||||
const result = await run<unknown>(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);
|
||||
const listing = result.ok ? toTreeEntries(result.value) : null;
|
||||
if (listing) {
|
||||
dirs.value[dir] = {
|
||||
entries: listing.entries,
|
||||
loading: false,
|
||||
error: null,
|
||||
truncated: listing.truncated,
|
||||
};
|
||||
prune(dir, listing.entries);
|
||||
} else {
|
||||
dirs.value[dir] = { entries: cachedEntries(dir), loading: false, error: result.error };
|
||||
const error = result.ok
|
||||
? { code: "ipc", message: `unexpected result of ${PROJECT_COMMANDS.children}` }
|
||||
: result.error;
|
||||
dirs.value[dir] = { entries: cachedEntries(dir), loading: false, error, truncated };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
62
ui/tests/ipcEvents.test.ts
Normal file
62
ui/tests/ipcEvents.test.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
/**
|
||||
* Tests for the engine event subscription in `ipc.ts`: payloads reach the
|
||||
* handler, the shell is told once that the frontend listens, and a failed
|
||||
* subscription never rejects.
|
||||
*/
|
||||
import { flushPromises } from "@vue/test-utils";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
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 }));
|
||||
|
||||
describe("onEngineEvent", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
invoke.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
it("forwards payloads, announces readiness once and unlistens", async () => {
|
||||
const unlisten = vi.fn();
|
||||
const callbacks: ((event: { payload: unknown }) => void)[] = [];
|
||||
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||
callbacks.push(callback);
|
||||
return Promise.resolve(unlisten);
|
||||
});
|
||||
const { onEngineEvent, ENGINE_EVENT } = await import("../src/ipc");
|
||||
const seen: unknown[] = [];
|
||||
const stop = onEngineEvent((event) => seen.push(event));
|
||||
const stop2 = onEngineEvent(() => undefined);
|
||||
await flushPromises();
|
||||
expect(listen).toHaveBeenCalledWith(ENGINE_EVENT, expect.any(Function));
|
||||
expect(invoke).toHaveBeenCalledTimes(1);
|
||||
expect(invoke).toHaveBeenCalledWith("engine_ready");
|
||||
callbacks[0]?.({ payload: { kind: "treeChanged", dir: "src" } });
|
||||
expect(seen).toEqual([{ kind: "treeChanged", dir: "src" }]);
|
||||
stop();
|
||||
stop2();
|
||||
expect(unlisten).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("unlistens a subscription that was cancelled before it started", async () => {
|
||||
const unlisten = vi.fn();
|
||||
listen.mockResolvedValue(unlisten);
|
||||
const { onEngineEvent } = await import("../src/ipc");
|
||||
const stop = onEngineEvent(() => undefined);
|
||||
stop();
|
||||
await flushPromises();
|
||||
expect(unlisten).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("swallows a failing subscription outside the shell", async () => {
|
||||
listen.mockRejectedValue(new Error("no Tauri"));
|
||||
const { onEngineEvent } = await import("../src/ipc");
|
||||
const stop = onEngineEvent(() => undefined);
|
||||
await flushPromises();
|
||||
stop();
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
@ -11,12 +11,26 @@ 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 { emitEngineEvent } from "../../src/components/project/engineEvents";
|
||||
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
|
||||
import { useProjectStore } from "../../src/stores/project";
|
||||
|
||||
/** An entry as the engine's `project.children` returns it. */
|
||||
interface EngineEntry {
|
||||
/** Display name. */
|
||||
name: string;
|
||||
/** Project-relative path. */
|
||||
path: string;
|
||||
/** Engine kind. */
|
||||
kind: "directory" | "file" | "other";
|
||||
/** Matched by an ignore rule. */
|
||||
ignored: boolean;
|
||||
/** Lutra's role for the entry. */
|
||||
role: "normal" | "library" | "excluded";
|
||||
}
|
||||
|
||||
/** In-memory folder listings by directory, as `project.children` returns them. */
|
||||
let folder: Record<string, TreeEntry[]>;
|
||||
let folder: Record<string, EngineEntry[]>;
|
||||
|
||||
/**
|
||||
* Builds an entry.
|
||||
|
|
@ -25,8 +39,10 @@ let folder: Record<string, TreeEntry[]>;
|
|||
* @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 };
|
||||
function entry(path: string, kind: "dir" | "file", ignored = false): EngineEntry {
|
||||
const engineKind = kind === "dir" ? "directory" : "file";
|
||||
const role = path === "node_modules" ? "excluded" : path === "vendor" ? "library" : "normal";
|
||||
return { name: path.split("/").pop() ?? path, path, kind: engineKind, ignored, role };
|
||||
}
|
||||
|
||||
/** Mock engine: answers `project.children`, accepts other commands. */
|
||||
|
|
@ -38,7 +54,7 @@ function engine(command: string, args: { command: string; params: { dir?: string
|
|||
const dir = args.params.dir ?? "";
|
||||
const entries = folder[dir];
|
||||
return entries
|
||||
? Promise.resolve(entries)
|
||||
? Promise.resolve({ dir, entries, truncated: false })
|
||||
: Promise.reject(Object.assign(new Error(`cannot list ${dir}`), { code: "not_found" }));
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
|
|
@ -47,7 +63,7 @@ function engine(command: string, args: { command: string; params: { dir?: string
|
|||
/** Mounts the tool window and opens the mock project through an event. */
|
||||
async function mountOpen(): Promise<VueWrapper> {
|
||||
const wrapper = mount(ProjectToolWindow, { attachTo: document.body });
|
||||
emitEngineEvent({ type: "ProjectOpened", root: { path: "/tmp/demo", name: "demo" } });
|
||||
emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
|
@ -183,7 +199,7 @@ describe("ProjectToolWindow", () => {
|
|||
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" });
|
||||
emitEngineEvent({ kind: "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();
|
||||
|
|
@ -194,7 +210,7 @@ describe("ProjectToolWindow", () => {
|
|||
|
||||
it("ignores TreeChanged for directories never loaded", async () => {
|
||||
wrapper = await mountOpen();
|
||||
emitEngineEvent({ type: "TreeChanged", dir: "vendor" });
|
||||
emitEngineEvent({ kind: "treeChanged", dir: "vendor" });
|
||||
await flushPromises();
|
||||
expect(childrenCalls()).toEqual([""]);
|
||||
});
|
||||
|
|
@ -211,7 +227,7 @@ describe("ProjectToolWindow", () => {
|
|||
it("keeps old entries when a refresh fails", async () => {
|
||||
wrapper = await mountOpen();
|
||||
Reflect.deleteProperty(folder, "");
|
||||
emitEngineEvent({ type: "TreeChanged", dir: "" });
|
||||
emitEngineEvent({ kind: "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"]);
|
||||
|
|
@ -219,12 +235,12 @@ describe("ProjectToolWindow", () => {
|
|||
|
||||
it("returns to the empty state on ProjectClosed and unsubscribes on unmount", async () => {
|
||||
wrapper = await mountOpen();
|
||||
emitEngineEvent({ type: "ProjectClosed" });
|
||||
emitEngineEvent({ kind: "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" } });
|
||||
emitEngineEvent({ kind: "projectOpened", root: "/tmp/other", name: "other" });
|
||||
expect(useProjectStore().root).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
105
ui/tests/project/engineEvents.test.ts
Normal file
105
ui/tests/project/engineEvents.test.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
/**
|
||||
* Tests for the adapter between the engine contract and the project UI:
|
||||
* `project.children` results and engine events are translated without
|
||||
* losing kind, ignore flag, role or truncation.
|
||||
*/
|
||||
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 {
|
||||
emitEngineEvent,
|
||||
onEngineEvent,
|
||||
toProjectEvent,
|
||||
toTreeEntries,
|
||||
type EngineEvent,
|
||||
} from "../../src/components/project/engineEvents";
|
||||
import { useProjectStore } from "../../src/stores/project";
|
||||
|
||||
describe("toTreeEntries", () => {
|
||||
it("maps kinds, ignore flags and roles", () => {
|
||||
const listing = toTreeEntries({
|
||||
dir: "",
|
||||
entries: [
|
||||
{ name: "src", path: "src", kind: "directory", ignored: false, role: "normal" },
|
||||
{ name: "vendor", path: "vendor", kind: "directory", ignored: false, role: "library" },
|
||||
{ name: "node_modules", path: "node_modules", kind: "directory", ignored: false, role: "excluded" },
|
||||
{ name: "a.log", path: "a.log", kind: "file", ignored: true, role: "normal" },
|
||||
{ name: "dangling", path: "dangling", kind: "other", ignored: false, role: "normal" },
|
||||
],
|
||||
truncated: true,
|
||||
});
|
||||
expect(listing).toEqual({
|
||||
truncated: true,
|
||||
entries: [
|
||||
{ name: "src", path: "src", kind: "dir", ignored: false, role: "normal", excluded: false, special: false },
|
||||
{ name: "vendor", path: "vendor", kind: "dir", ignored: false, role: "library", excluded: false, special: false },
|
||||
{ name: "node_modules", path: "node_modules", kind: "dir", ignored: false, role: "excluded", excluded: true, special: false },
|
||||
{ name: "a.log", path: "a.log", kind: "file", ignored: true, role: "normal", excluded: false, special: false },
|
||||
{ name: "dangling", path: "dangling", kind: "file", ignored: false, role: "normal", excluded: false, special: true },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("skips malformed entries and rejects results without entries", () => {
|
||||
expect(toTreeEntries({ entries: [{ name: "x" }, 3, null, { name: "a", path: "a", kind: "file" }] })).toEqual({
|
||||
truncated: false,
|
||||
entries: [{ name: "a", path: "a", kind: "file", ignored: false, role: "normal", excluded: false, special: false }],
|
||||
});
|
||||
expect(toTreeEntries([])).toBeNull();
|
||||
expect(toTreeEntries(null)).toBeNull();
|
||||
expect(toTreeEntries({ entries: "no" })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("toProjectEvent", () => {
|
||||
it("translates project events and ignores the rest", () => {
|
||||
expect(toProjectEvent({ kind: "projectOpened", root: "/p/demo", name: "demo" })).toEqual({
|
||||
type: "ProjectOpened",
|
||||
root: { path: "/p/demo", name: "demo" },
|
||||
});
|
||||
expect(toProjectEvent({ kind: "projectClosed" })).toEqual({ type: "ProjectClosed" });
|
||||
expect(toProjectEvent({ kind: "treeChanged", dir: "src" })).toEqual({ type: "TreeChanged", dir: "src" });
|
||||
expect(toProjectEvent({ kind: "bufferOpened", id: 1, path: "a.php" })).toBeNull();
|
||||
});
|
||||
|
||||
it("delivers only translated events to project handlers", () => {
|
||||
const seen: EngineEvent[] = [];
|
||||
const stop = onEngineEvent((event) => seen.push(event));
|
||||
emitEngineEvent({ kind: "dirtyChanged", id: 1, dirty: true });
|
||||
emitEngineEvent({ kind: "treeChanged", dir: "" });
|
||||
stop();
|
||||
emitEngineEvent({ kind: "treeChanged", dir: "late" });
|
||||
expect(seen).toEqual([{ type: "TreeChanged", dir: "" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("project store with the engine result", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
invoke.mockReset();
|
||||
});
|
||||
|
||||
it("keeps truncation and role from project.children", async () => {
|
||||
invoke.mockResolvedValue({
|
||||
dir: "",
|
||||
entries: [{ name: "vendor", path: "vendor", kind: "directory", ignored: false, role: "library" }],
|
||||
truncated: true,
|
||||
});
|
||||
const store = useProjectStore();
|
||||
store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } });
|
||||
await store.loadChildren("");
|
||||
expect(store.dirs[""]?.truncated).toBe(true);
|
||||
expect(store.dirs[""]?.entries?.[0]?.role).toBe("library");
|
||||
});
|
||||
|
||||
it("reports an unexpected result as an error instead of throwing", async () => {
|
||||
invoke.mockResolvedValue(["old", "shape"]);
|
||||
const store = useProjectStore();
|
||||
store.handleEvent({ type: "ProjectOpened", root: { path: "/p", name: "p" } });
|
||||
await store.loadChildren("");
|
||||
expect(store.dirs[""]?.error?.code).toBe("ipc");
|
||||
});
|
||||
});
|
||||
|
|
@ -23,9 +23,9 @@ describe("project store", () => {
|
|||
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 }]);
|
||||
resolvers[1]?.({ dir: "", entries: [{ name: "new.php", path: "new.php", kind: "file", ignored: false, role: "normal" }], truncated: false });
|
||||
await second;
|
||||
resolvers[0]?.([{ name: "old.php", path: "old.php", kind: "file", ignored: false }]);
|
||||
resolvers[0]?.({ dir: "", entries: [{ name: "old.php", path: "old.php", kind: "file", ignored: false, role: "normal" }], truncated: false });
|
||||
await Promise.resolve();
|
||||
expect(store.rows.map((row) => (row.kind === "entry" ? row.entry.path : row.kind))).toEqual(["new.php"]);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue