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 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-14 19:24:23 +02:00
parent faadb05eb3
commit 003b7970e6
16 changed files with 1541 additions and 32 deletions

View file

@ -1,10 +1,10 @@
<script setup lang="ts">
/**
* Root component: the empty workbench of milestone M0, a main area and the
* status bar. Loads product information from the engine on mount.
* Root component: mounts the main window layout with the editor area
* placeholder. Loads product information from the engine on mount.
*/
import { onMounted } from "vue";
import StatusBar from "./components/StatusBar.vue";
import MainLayout from "./components/layout/MainLayout.vue";
import { useAppStore } from "./stores/app";
const app = useAppStore();
@ -15,34 +15,14 @@ onMounted(() => {
</script>
<template>
<div class="workbench">
<main
class="workbench__main"
data-test="main"
>
<p class="workbench__hint">
{{ app.about?.slogan ?? "" }}
</p>
</main>
<StatusBar />
</div>
<MainLayout>
<p class="workbench__hint">
{{ app.about?.slogan ?? "" }}
</p>
</MainLayout>
</template>
<style scoped>
.workbench {
display: flex;
flex-direction: column;
height: 100%;
}
.workbench__main {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: var(--lt-editor-bg);
}
.workbench__hint {
color: var(--lt-fg-muted);
}

View file

@ -0,0 +1,62 @@
<script setup lang="ts">
/**
* Layout of the main window: the Project tool window on the left, the
* editor area in the middle and the status bar along the bottom.
*
* The editor area is a slot so the editor (M1.6) can replace the
* placeholder without touching the layout.
*/
import { ref } from "vue";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import ToolWindow from "./ToolWindow.vue";
/** Width of the left tool window in CSS pixels. */
const leftWidth = ref(260);
/** Whether the left tool window is shown. */
const leftOpen = ref(true);
</script>
<template>
<div class="main-layout">
<div class="main-layout__row">
<ToolWindow
v-model:width="leftWidth"
v-model:open="leftOpen"
title="Project"
>
<ProjectToolWindow />
</ToolWindow>
<main
class="main-layout__editor"
data-test="main"
>
<slot />
</main>
</div>
<StatusBar />
</div>
</template>
<style scoped>
.main-layout {
display: flex;
flex-direction: column;
height: 100%;
}
.main-layout__row {
display: flex;
flex: 1;
min-height: 0;
}
.main-layout__editor {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
background: var(--lt-editor-bg);
}
</style>

View file

@ -0,0 +1,231 @@
<script setup lang="ts">
/**
* A tool window docked on the left side of the main window: a header with
* the title and a hide button, the content slot, and a splitter on the right
* edge to resize it. When hidden, a narrow stripe with a button brings it
* back.
*
* The splitter is dragged with the pointer or moved with Left/Right (Shift
* for larger steps) when focused. Width and visibility are view state of this
* component, emitted through `v-model:width` and `v-model:open`.
*/
import { PanelLeftClose, PanelLeftOpen } from "@lucide/vue";
import { computed } from "vue";
/** Props of the tool window. */
const props = withDefaults(
defineProps<{
/** Title shown in the header and as the accessible name. */
title: string;
/** Width in CSS pixels. */
width?: number;
/** Smallest width the splitter allows. */
minWidth?: number;
/** Largest width the splitter allows. */
maxWidth?: number;
/** Whether the window is shown (true) or collapsed to its stripe. */
open?: boolean;
}>(),
{ width: 260, minWidth: 140, maxWidth: 640, open: true },
);
/** Events of the tool window. */
const emit = defineEmits<{
/** New width after a resize. */
"update:width": [width: number];
/** New visibility after hide or show. */
"update:open": [open: boolean];
}>();
/** Inline style carrying the current width. */
const style = computed(() => ({ width: `${String(props.width)}px` }));
/**
* Emits a width clamped to the allowed range.
*
* @param width - the wanted width.
*/
function setWidth(width: number): void {
emit("update:width", Math.round(Math.min(props.maxWidth, Math.max(props.minWidth, width))));
}
/**
* Starts a pointer drag on the splitter.
*
* @param event - the pointer-down event.
*/
function onSplitterDown(event: PointerEvent): void {
const target = event.currentTarget;
if (!(target instanceof HTMLElement)) {
return;
}
const startX = event.clientX;
const startWidth = props.width;
target.setPointerCapture(event.pointerId);
const move = (e: PointerEvent): void => {
setWidth(startWidth + e.clientX - startX);
};
const up = (e: PointerEvent): void => {
target.releasePointerCapture(e.pointerId);
target.removeEventListener("pointermove", move);
target.removeEventListener("pointerup", up);
};
target.addEventListener("pointermove", move);
target.addEventListener("pointerup", up);
}
/**
* Resizes with the keyboard when the splitter has focus.
*
* @param event - the key event.
*/
function onSplitterKey(event: KeyboardEvent): void {
const step = event.shiftKey ? 48 : 12;
if (event.key === "ArrowLeft") {
setWidth(props.width - step);
} else if (event.key === "ArrowRight") {
setWidth(props.width + step);
} else {
return;
}
event.preventDefault();
}
</script>
<template>
<aside
v-if="open"
class="tool-window"
:style="style"
:aria-label="title"
data-test="tool-window"
>
<header class="tool-window__header">
<span class="tool-window__title">{{ title }}</span>
<button
type="button"
class="tool-window__button"
:title="`Hide ${title}`"
:aria-label="`Hide ${title}`"
data-test="tool-window-hide"
@click="emit('update:open', false)"
>
<PanelLeftClose :size="16" />
</button>
</header>
<div class="tool-window__body">
<slot />
</div>
<div
class="tool-window__splitter"
role="separator"
aria-orientation="vertical"
tabindex="0"
:aria-valuenow="width"
:aria-valuemin="minWidth"
:aria-valuemax="maxWidth"
:aria-label="`Resize ${title}`"
data-test="tool-window-splitter"
@pointerdown="onSplitterDown"
@keydown="onSplitterKey"
/>
</aside>
<div
v-else
class="tool-window-stripe"
data-test="tool-window-stripe"
>
<button
type="button"
class="tool-window__button"
:title="`Show ${title}`"
:aria-label="`Show ${title}`"
data-test="tool-window-show"
@click="emit('update:open', true)"
>
<PanelLeftOpen :size="16" />
</button>
</div>
</template>
<style scoped>
.tool-window {
position: relative;
display: flex;
flex-direction: column;
flex: none;
min-height: 0;
background: var(--lt-bg);
border-right: 1px solid var(--lt-border);
}
.tool-window__header {
display: flex;
align-items: center;
justify-content: space-between;
height: var(--lt-header-height, 28px);
padding: 0 var(--lt-space-s, 4px) 0 var(--lt-space-m, 8px);
border-bottom: 1px solid var(--lt-border);
}
.tool-window__title {
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tool-window__body {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.tool-window__button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.tool-window__button:hover {
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-fg) 8%, transparent);
}
.tool-window__button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.tool-window__splitter {
position: absolute;
top: 0;
right: -3px;
bottom: 0;
width: 6px;
cursor: col-resize;
z-index: 1;
}
.tool-window__splitter:hover,
.tool-window__splitter:focus-visible {
outline: none;
background: color-mix(in srgb, var(--lt-accent) 50%, transparent);
}
.tool-window-stripe {
display: flex;
flex-direction: column;
align-items: center;
flex: none;
padding: var(--lt-space-s, 4px) var(--lt-space-xs, 2px);
background: var(--lt-bg);
border-right: 1px solid var(--lt-border);
}
</style>

View file

@ -0,0 +1,105 @@
<script setup lang="ts">
/**
* Content of the Project tool window: the project tree when a folder is
* open, otherwise an empty state with an "Open Folder…" button that runs the
* engine's open-folder command. Subscribes the project store to engine
* events while mounted. Command errors are shown below the content.
*/
import { FolderOpen } from "@lucide/vue";
import { onBeforeUnmount, onMounted } from "vue";
import { useProjectStore } from "../../stores/project";
import ProjectTree from "./ProjectTree.vue";
const project = useProjectStore();
onMounted(() => {
project.start();
});
onBeforeUnmount(() => {
project.stop();
});
</script>
<template>
<div class="project-view">
<ProjectTree v-if="project.root" />
<div
v-else
class="project-view__empty"
data-test="project-empty"
>
<p class="project-view__hint">
No folder is open.
</p>
<button
type="button"
class="project-view__open"
data-test="open-folder"
@click="project.openFolder()"
>
<FolderOpen :size="16" />
<span>Open Folder…</span>
</button>
</div>
<p
v-if="project.lastError"
class="project-view__error"
role="alert"
data-test="project-error"
>
{{ project.lastError.message }}
</p>
</div>
</template>
<style scoped>
.project-view {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.project-view__empty {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--lt-space-m, 8px);
padding: var(--lt-space-l, 16px) var(--lt-space-m, 8px);
}
.project-view__hint {
margin: 0;
color: var(--lt-fg-muted);
}
.project-view__open {
display: inline-flex;
align-items: center;
gap: var(--lt-space-s, 4px);
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
font: inherit;
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
border: 1px solid var(--lt-accent);
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.project-view__open:hover {
background: color-mix(in srgb, var(--lt-accent) 30%, transparent);
}
.project-view__open:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
.project-view__error {
margin: 0;
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
color: var(--lt-error);
border-top: 1px solid var(--lt-border);
}
</style>

View file

@ -0,0 +1,367 @@
<script setup lang="ts">
/**
* The project tree: a keyboard-navigable tree of the open folder, following
* the WAI-ARIA tree view pattern. Folders load lazily on first expansion.
*
* Keys: Up/Down move the selection, Home/End jump to the first/last row,
* Right expands a folder or moves into it, Left collapses a folder or moves
* to the parent, Enter opens a file or toggles a folder. Double-click does
* the same as Enter. Ignored and excluded entries are dimmed.
*/
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
import type { TreeEntry } from "./engineEvents";
const project = useProjectStore();
/** The tree element, for keeping the selected row in view. */
const treeEl = ref<HTMLElement | null>(null);
/** Rows that are entries, in display order, for keyboard navigation. */
const entryRows = computed(() =>
project.rows.filter((row): row is Extract<TreeRow, { kind: "entry" }> => row.kind === "entry"),
);
/** Index of the selected entry within {@link entryRows}, -1 if none. */
const selectedIndex = computed(() =>
entryRows.value.findIndex((row) => row.entry.path === project.selected),
);
/**
* DOM id of a row, used for `aria-activedescendant`.
*
* @param path - the entry path.
*/
function rowId(path: string): string {
return `lt-tree-${encodeURIComponent(path)}`;
}
/** Id of the selected row, or undefined when nothing is selected. */
const activeId = computed(() =>
project.selected !== null && selectedIndex.value >= 0 ? rowId(project.selected) : undefined,
);
/**
* Key used by `v-for` for a row.
*
* @param row - the row.
*/
function rowKey(row: TreeRow): string {
return row.kind === "entry" ? `e:${row.entry.path}` : `${row.kind}:${row.dir}`;
}
/**
* Whether an entry is shown dimmed.
*
* @param entry - the entry.
*/
function isDimmed(entry: TreeEntry): boolean {
return entry.ignored || entry.excluded === true;
}
/**
* Whether a file name looks like PHP source, for the code icon.
*
* @param name - the file name.
*/
function isPhp(name: string): boolean {
return /\.(php|phtml|inc)$/i.test(name);
}
/** Scrolls the selected row into view after the DOM updated. */
async function revealSelected(): Promise<void> {
await nextTick();
const id = activeId.value;
if (id === undefined || !treeEl.value) {
return;
}
const el = treeEl.value.querySelector(`#${CSS.escape(id)}`);
if (el instanceof HTMLElement && typeof el.scrollIntoView === "function") {
el.scrollIntoView({ block: "nearest" });
}
}
/**
* Selects the entry at an index of {@link entryRows}, clamped to the list.
*
* @param index - the wanted index.
*/
function selectIndex(index: number): void {
const rows = entryRows.value;
if (rows.length === 0) {
return;
}
const row = rows[Math.max(0, Math.min(index, rows.length - 1))];
if (row) {
project.select(row.entry.path);
void revealSelected();
}
}
/**
* Opens a file or toggles a folder.
*
* @param entry - the entry to activate.
*/
function activate(entry: TreeEntry): void {
if (entry.kind === "dir") {
void project.toggle(entry.path);
} else {
void project.openFile(entry.path);
}
}
/**
* Handles a click on a row: selects it; a click on the chevron toggles.
*
* @param entry - the clicked entry.
* @param onChevron - whether the click hit the expand chevron.
*/
function onRowClick(entry: TreeEntry, onChevron: boolean): void {
project.select(entry.path);
if (onChevron && entry.kind === "dir") {
void project.toggle(entry.path);
}
}
/** Moves right: expands a collapsed folder, or enters an expanded one. */
function moveRight(row: Extract<TreeRow, { kind: "entry" }>): void {
if (row.entry.kind !== "dir") {
return;
}
if (!row.expanded) {
void project.expand(row.entry.path);
return;
}
const next = entryRows.value[selectedIndex.value + 1];
if (next && parentOf(next.entry.path) === row.entry.path) {
selectIndex(selectedIndex.value + 1);
}
}
/** Moves left: collapses an expanded folder, or selects the parent. */
function moveLeft(row: Extract<TreeRow, { kind: "entry" }>): void {
if (row.entry.kind === "dir" && row.expanded) {
project.collapse(row.entry.path);
return;
}
const parent = parentOf(row.entry.path);
if (parent !== "") {
project.select(parent);
void revealSelected();
}
}
/**
* Keyboard navigation of the tree.
*
* @param event - the key event on the tree element.
*/
function onKeydown(event: KeyboardEvent): void {
const index = selectedIndex.value;
const row = index >= 0 ? entryRows.value[index] : undefined;
switch (event.key) {
case "ArrowDown":
selectIndex(row ? index + 1 : 0);
break;
case "ArrowUp":
selectIndex(row ? index - 1 : 0);
break;
case "Home":
selectIndex(0);
break;
case "End":
selectIndex(entryRows.value.length - 1);
break;
case "ArrowRight":
if (row) {
moveRight(row);
}
break;
case "ArrowLeft":
if (row) {
moveLeft(row);
}
break;
case "Enter":
if (row) {
activate(row.entry);
}
break;
default:
return;
}
event.preventDefault();
}
/** Selects the first row when the tree gains focus without a selection. */
function onFocus(): void {
if (selectedIndex.value < 0) {
selectIndex(0);
}
}
</script>
<template>
<div
ref="treeEl"
class="tree"
role="tree"
tabindex="0"
:aria-label="project.root?.name ?? ''"
:aria-activedescendant="activeId"
data-test="project-tree"
@keydown="onKeydown"
@focus="onFocus"
>
<template
v-for="row in project.rows"
:key="rowKey(row)"
>
<div
v-if="row.kind === 'entry'"
:id="rowId(row.entry.path)"
class="tree__row"
:class="{
'tree__row--selected': row.entry.path === project.selected,
'tree__row--dimmed': isDimmed(row.entry),
}"
role="treeitem"
:aria-level="row.depth + 1"
:aria-selected="row.entry.path === project.selected"
:aria-expanded="row.entry.kind === 'dir' ? row.expanded : undefined"
:style="{ '--tree-depth': row.depth }"
:data-path="row.entry.path"
data-test="tree-row"
@click="onRowClick(row.entry, false)"
@dblclick="activate(row.entry)"
>
<span
class="tree__chevron"
data-test="tree-chevron"
@click.stop="onRowClick(row.entry, true)"
>
<template v-if="row.entry.kind === 'dir'">
<ChevronDown
v-if="row.expanded"
:size="14"
/>
<ChevronRight
v-else
:size="14"
/>
</template>
</span>
<span class="tree__icon">
<template v-if="row.entry.kind === 'dir'">
<FolderOpen
v-if="row.expanded"
:size="16"
/>
<Folder
v-else
:size="16"
/>
</template>
<FileCode
v-else-if="isPhp(row.entry.name)"
:size="16"
/>
<File
v-else
:size="16"
/>
</span>
<span class="tree__name">{{ row.entry.name }}</span>
</div>
<div
v-else-if="row.kind === 'loading'"
class="tree__row tree__row--note"
:style="{ '--tree-depth': row.depth }"
data-test="tree-loading"
>
Loading…
</div>
<div
v-else
class="tree__row tree__row--note tree__row--error"
role="alert"
:style="{ '--tree-depth': row.depth }"
data-test="tree-error"
>
{{ row.error.message }}
</div>
</template>
</div>
</template>
<style scoped>
.tree {
flex: 1;
overflow: auto;
padding: var(--lt-space-xs, 2px) 0;
outline: none;
}
.tree__row {
display: flex;
align-items: center;
gap: var(--lt-space-xs, 2px);
height: var(--lt-row-height, 22px);
padding-left: calc(var(--lt-space-s, 4px) + var(--tree-depth) * var(--lt-tree-indent, 16px));
padding-right: var(--lt-space-m, 8px);
white-space: nowrap;
cursor: default;
}
.tree__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.tree__row--selected {
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
}
.tree:focus-visible .tree__row--selected {
background: color-mix(in srgb, var(--lt-accent) 32%, transparent);
}
.tree__row--dimmed {
color: var(--lt-fg-muted);
}
.tree__row--note {
color: var(--lt-fg-muted);
padding-left: calc(var(--lt-space-s, 4px) + (var(--tree-depth) + 1) * var(--lt-tree-indent, 16px));
}
.tree__row--error {
color: var(--lt-error);
white-space: normal;
height: auto;
min-height: var(--lt-row-height, 22px);
}
.tree__chevron {
display: inline-flex;
width: 14px;
flex: none;
color: var(--lt-fg-muted);
}
.tree__icon {
display: inline-flex;
flex: none;
color: var(--lt-fg-muted);
}
.tree__row--selected .tree__icon {
color: var(--lt-accent);
}
.tree__name {
overflow: hidden;
text-overflow: ellipsis;
}
</style>

View file

@ -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<EngineEventHandler>();
/**
* 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);
}
}

340
ui/src/stores/project.ts Normal file
View file

@ -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<ProjectRoot | null>(null);
/** Listings by directory path (`""` is the root). */
const dirs = ref<Record<string, DirState>>({});
/** Expanded directories. */
const expanded = ref<Set<string>>(new Set());
/** Path of the selected entry, null if none. */
const selected = ref<string | null>(null);
/** Error of the last open-folder or open-file command, null if none. */
const lastError = ref<EngineError | null>(null);
/** Latest request number per directory, to drop stale listings. */
const requests = new Map<string, number>();
/** 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<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 });
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<void> {
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<void> {
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<void> {
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<void> {
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<TreeRow[]>(() => {
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,
};
});