M2.7: Structure tool window and syntax.outline

Engine: every open PHP buffer keeps a tree-sitter tree, reparsed
incrementally on a worker thread off the engine lock (200 ms debounce,
edit batches recorded by buffer.edit, full parse when the chain breaks).
syntax.outline {id} returns {items, truncated, version}; outlineChanged
{id} at most every 200 ms per buffer. Replaced trees and outlines are
freed on the worker.

UI: left stripe with Project | Structure in MainLayout, the Structure
tool window (WAI-ARIA tree, Lucide kind icons, signatures, jumps via
editor.reveal), view.toggleStructure on Mod+2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-17 13:31:37 +02:00
parent 73819df926
commit c68932c39c
27 changed files with 2596 additions and 28 deletions

View file

@ -26,4 +26,5 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "palette.open", labelKey: "command.palette.open", defaultShortcut: "Mod+Shift+P" },
{ id: "settings.open", labelKey: "command.settings.open", defaultShortcut: "Mod+," },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", defaultShortcut: "Mod+1" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", defaultShortcut: "Mod+2" },
];

View file

@ -1,26 +1,34 @@
<script setup lang="ts">
/**
* Layout of the main window: the Project tool window on the left, the
* editor area in the middle, the bottom panel under both (M2.4) and the
* status bar along the bottom.
* Layout of the main window: the left tool-window stripe, the left tool
* window, the editor area in the middle, the bottom panel under both
* (M2.4) 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. The layout supplies the UI
* command `view.toggleProjectTree` (`Mod+1`), which shows or hides the
* Project tool window.
* placeholder without touching the layout.
*
* The left stripe (M2.7) is a vertical tab list with Project and
* Structure. The left tool window shows one of them; clicking the shown
* one's tab hides the window, clicking the other switches to it. Both stay
* mounted while the window is open, so switching keeps their state. The
* layout supplies the UI commands `view.toggleProjectTree` (`Mod+1`) and
* `view.toggleStructure` (`Mod+2`): each shows its tool window, or hides
* the left window when that tool window is already shown.
*
* The bottom panel ({@link BottomPanel}) holds the Find tool window. It
* appears with the UI command `find.open` (`Mod+Alt+F`, supplied here so it
* works before the panel exists), collapses to its header and closes from
* its header; the Find store keeps the results while it is closed.
*/
import { onBeforeUnmount, onMounted, ref } from "vue";
import { FolderTree, ListTree } from "@lucide/vue";
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useFindStore } from "../../stores/find";
import FindToolWindow from "../find/FindToolWindow.vue";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue";
import BottomPanel from "./BottomPanel.vue";
import ToolWindow from "./ToolWindow.vue";
@ -31,6 +39,33 @@ const leftOpen = ref(true);
/** Height of the bottom panel's content in CSS pixels. */
const bottomHeight = ref(240);
/** Tool windows of the left side. */
type LeftTool = "project" | "structure";
/** The left tool window shown while {@link leftOpen} is set. */
const leftTool = ref<LeftTool>("project");
/** Stripe tabs in display order: id, title and icon. */
const leftTools = computed(() => [
{ id: "project" as const, title: t("project.toolWindow.title"), icon: FolderTree },
{ id: "structure" as const, title: t("structure.toolWindow.title"), icon: ListTree },
]);
/** Title of the shown left tool window. */
const leftTitle = computed(() => leftTools.value.find((tool) => tool.id === leftTool.value)?.title ?? "");
/**
* Shows a left tool window, or hides the left window when it is already
* shown.
*
* @param tool - the tool window.
*/
function toggleLeft(tool: LeftTool): void {
if (leftOpen.value && leftTool.value === tool) {
leftOpen.value = false;
return;
}
leftTool.value = tool;
leftOpen.value = true;
}
const commands = useCommandsStore();
const find = useFindStore();
@ -42,10 +77,15 @@ onMounted(() => {
withdraw = [
commands.provide("view.toggleProjectTree", {
run: () => {
leftOpen.value = !leftOpen.value;
toggleLeft("project");
},
}),
commands.provide("find.open", { run: (params) => find.open(params) }),
commands.provide("view.toggleStructure", {
run: () => {
toggleLeft("structure");
},
}),
];
});
@ -61,12 +101,40 @@ onBeforeUnmount(() => {
<template>
<div class="main-layout">
<div class="main-layout__row">
<nav
class="main-layout__stripe"
role="tablist"
aria-orientation="vertical"
:aria-label="t('common.toolWindow.stripe')"
data-test="left-stripe"
>
<button
v-for="tool in leftTools"
:key="tool.id"
type="button"
role="tab"
class="main-layout__stripe-button"
:class="{ 'main-layout__stripe-button--active': leftOpen && leftTool === tool.id }"
:aria-selected="leftOpen && leftTool === tool.id"
:title="tool.title"
:aria-label="tool.title"
:data-test="`stripe-${tool.id}`"
@click="toggleLeft(tool.id)"
>
<component
:is="tool.icon"
:size="18"
/>
</button>
</nav>
<ToolWindow
v-if="leftOpen"
v-model:width="leftWidth"
v-model:open="leftOpen"
:title="t('project.toolWindow.title')"
:title="leftTitle"
>
<ProjectToolWindow />
<ProjectToolWindow v-show="leftTool === 'project'" />
<StructureToolWindow v-show="leftTool === 'structure'" />
</ToolWindow>
<main
class="main-layout__editor"
@ -101,6 +169,43 @@ onBeforeUnmount(() => {
min-height: 0;
}
.main-layout__stripe {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--lt-space-xs, 2px);
flex: none;
padding: var(--lt-space-s, 4px) var(--lt-space-xs, 2px);
background: var(--lt-bg);
border-right: 1px solid var(--lt-border);
}
.main-layout__stripe-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;
}
.main-layout__stripe-button:hover {
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-fg) 8%, transparent);
}
.main-layout__stripe-button--active {
color: var(--lt-accent);
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
}
.main-layout__stripe-button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.main-layout__editor {
flex: 1;
min-width: 0;

View file

@ -0,0 +1,434 @@
<script setup lang="ts">
/**
* The Structure tool window (M2.7): the declarations of the active editor
* tab as a keyboard-navigable tree (WAI-ARIA tree view), with a kind icon,
* the name and the short signature.
*
* Keys: Up/Down move the selection, Home/End jump to the first/last row,
* Right expands a node or moves into it, Left collapses a node or moves to
* its parent, Enter jumps to the declaration. A click selects a row and
* jumps too; the chevron only expands or collapses. Jumps run the UI
* command `editor.reveal {path, line, column}` at the start of the name.
* Without a tab, for a file without declarations and for a file too large
* to parse the window says so. State lives in {@link useStructureStore},
* which follows the active tab and `outlineChanged` while the window is
* mounted.
*/
import {
Box,
ChevronDown,
ChevronRight,
CircleDot,
Component,
Layers,
ListOrdered,
Package,
Parentheses,
SquareFunction,
SquarePi,
Variable,
} from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, type Component as VueComponent } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { parentKey, useStructureStore, type OutlineKind, type StructureRow } from "./structure";
const structure = useStructureStore();
const editor = useEditorStore();
const commands = useCommandsStore();
/** The tree element, for keeping the selected row in view. */
const treeEl = ref<HTMLElement | null>(null);
/** Lucide icon per kind. */
const ICONS: Record<OutlineKind, VueComponent> = {
namespace: Package,
class: Box,
interface: Component,
trait: Layers,
enum: ListOrdered,
function: SquareFunction,
method: Parentheses,
property: Variable,
constant: SquarePi,
enumCase: CircleDot,
};
/** Accessible name per kind. */
const KIND_LABELS: Record<OutlineKind, () => string> = {
namespace: () => t("structure.kind.namespace"),
class: () => t("structure.kind.class"),
interface: () => t("structure.kind.interface"),
trait: () => t("structure.kind.trait"),
enum: () => t("structure.kind.enum"),
function: () => t("structure.kind.function"),
method: () => t("structure.kind.method"),
property: () => t("structure.kind.property"),
constant: () => t("structure.kind.constant"),
enumCase: () => t("structure.kind.enumCase"),
};
/** Index of the selected row, -1 if none. */
const selectedIndex = computed(() => structure.rows.findIndex((row) => row.key === structure.selected));
/**
* DOM id of a row, for `aria-activedescendant`.
*
* @param key - the row key.
*/
function rowId(key: string): string {
return `lt-structure-${encodeURIComponent(key)}`;
}
/** Id of the selected row, or undefined. */
const activeId = computed(() =>
structure.selected !== null && selectedIndex.value >= 0 ? rowId(structure.selected) : undefined,
);
/** Text shown instead of the tree, or null when the tree shows. */
const emptyText = computed(() => {
if (editor.activeId === null) {
return t("structure.empty.noFile");
}
if (structure.error) {
return null;
}
if (structure.truncated) {
return t("structure.empty.tooLarge");
}
if (structure.items.length === 0) {
return structure.pending ? t("structure.empty.parsing") : t("structure.empty.none");
}
return null;
});
/** 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 row at an index, clamped to the list.
*
* @param index - the wanted index.
*/
function selectIndex(index: number): void {
const rows = structure.rows;
const row = rows[Math.max(0, Math.min(index, rows.length - 1))];
if (row) {
structure.select(row.key);
void revealSelected();
}
}
/**
* Jumps to a row's declaration in the editor.
*
* @param row - the row.
*/
function jump(row: StructureRow): void {
const path = structure.path;
if (path === null) {
return;
}
void commands.execute("editor.reveal", { path, line: row.node.start.line, column: row.node.start.column });
}
/**
* Handles a click on a row: selects it and jumps there.
*
* @param row - the clicked row.
*/
function onRowClick(row: StructureRow): void {
structure.select(row.key);
jump(row);
}
/**
* Handles a click on a chevron: selects the row and toggles it.
*
* @param row - the row.
*/
function onChevronClick(row: StructureRow): void {
structure.select(row.key);
if (row.parent) {
structure.setExpanded(row.key, !row.expanded);
}
}
/**
* Moves right: expands a collapsed node, or enters an expanded one.
*
* @param row - the selected row.
*/
function moveRight(row: StructureRow): void {
if (!row.parent) {
return;
}
if (!row.expanded) {
structure.setExpanded(row.key, true);
return;
}
selectIndex(selectedIndex.value + 1);
}
/**
* Moves left: collapses an expanded node, or selects the parent.
*
* @param row - the selected row.
*/
function moveLeft(row: StructureRow): void {
if (row.expanded) {
structure.setExpanded(row.key, false);
return;
}
const parent = parentKey(row.key);
if (parent !== null) {
structure.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 ? structure.rows[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(structure.rows.length - 1);
break;
case "ArrowRight":
if (row) {
moveRight(row);
}
break;
case "ArrowLeft":
if (row) {
moveLeft(row);
}
break;
case "Enter":
if (row) {
jump(row);
}
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);
}
}
onMounted(() => {
structure.start();
});
onBeforeUnmount(() => {
structure.stop();
});
</script>
<template>
<div class="structure-view">
<p
v-if="structure.error"
class="structure-view__note structure-view__note--error"
role="alert"
data-test="structure-error"
>
{{ structure.error.message }}
</p>
<p
v-if="emptyText !== null"
class="structure-view__note"
data-test="structure-empty"
>
{{ emptyText }}
</p>
<div
v-else-if="structure.rows.length > 0"
ref="treeEl"
class="structure-tree"
role="tree"
tabindex="0"
:aria-label="t('structure.tree.label')"
:aria-activedescendant="activeId"
data-test="structure-tree"
@keydown="onKeydown"
@focus="onFocus"
>
<div
v-for="row in structure.rows"
:id="rowId(row.key)"
:key="row.key"
class="structure-tree__row"
:class="{ 'structure-tree__row--selected': row.key === structure.selected }"
role="treeitem"
:aria-level="row.depth + 1"
:aria-selected="row.key === structure.selected"
:aria-expanded="row.parent ? row.expanded : undefined"
:style="{ '--tree-depth': row.depth }"
data-test="structure-row"
:data-kind="row.node.kind"
@click="onRowClick(row)"
>
<span
class="structure-tree__chevron"
data-test="structure-chevron"
@click.stop="onChevronClick(row)"
>
<template v-if="row.parent">
<ChevronDown
v-if="row.expanded"
:size="14"
/>
<ChevronRight
v-else
:size="14"
/>
</template>
</span>
<span
class="structure-tree__icon"
:class="`structure-tree__icon--${row.node.kind}`"
:title="KIND_LABELS[row.node.kind]()"
>
<component
:is="ICONS[row.node.kind]"
:size="16"
:aria-label="KIND_LABELS[row.node.kind]()"
/>
</span>
<span class="structure-tree__name">{{ row.node.name }}</span>
<span
v-if="row.node.detail !== null"
class="structure-tree__detail"
>{{ row.node.detail }}</span>
</div>
</div>
</div>
</template>
<style scoped>
.structure-view {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.structure-view__note {
margin: 0;
padding: var(--lt-space-m, 8px);
color: var(--lt-fg-muted);
}
.structure-view__note--error {
color: var(--lt-error);
}
.structure-tree {
flex: 1;
overflow: auto;
padding: var(--lt-space-xs, 2px) 0;
outline: none;
}
.structure-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;
}
.structure-tree__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.structure-tree__row--selected {
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
}
.structure-tree:focus-visible .structure-tree__row--selected {
background: color-mix(in srgb, var(--lt-accent) 32%, transparent);
}
.structure-tree__chevron {
display: inline-flex;
width: 14px;
flex: none;
color: var(--lt-fg-muted);
}
.structure-tree__icon {
display: inline-flex;
flex: none;
color: var(--lt-fg-muted);
}
.structure-tree__icon--namespace,
.structure-tree__icon--class,
.structure-tree__icon--interface,
.structure-tree__icon--trait,
.structure-tree__icon--enum {
color: var(--lt-syntax-type);
}
.structure-tree__icon--function,
.structure-tree__icon--method {
color: var(--lt-syntax-function);
}
.structure-tree__icon--property {
color: var(--lt-syntax-variable);
}
.structure-tree__icon--constant,
.structure-tree__icon--enumCase {
color: var(--lt-syntax-constant);
}
.structure-tree__name {
flex: none;
}
.structure-tree__detail {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
margin-left: var(--lt-space-s, 4px);
color: var(--lt-fg-muted);
}
</style>

View file

@ -0,0 +1,314 @@
/**
* The Structure tool window's state (M2.7): the outline of the active
* editor tab as a tree, which nodes are collapsed and which row is
* selected.
*
* - **Source:** `syntax.outline {id}` for the active tab's buffer. It is
* fetched again when the active tab changes and on `outlineChanged {id}`
* for that buffer (the engine sends it after the first parse and after
* edits, debounced). An answer that arrives after a newer request is
* dropped.
* - **Tree:** every node starts expanded; collapsed nodes are remembered
* per buffer by their path of names, so they stay collapsed across
* refreshes and tab switches.
* - **Untrusted input:** the outline comes from the engine; malformed items
* are dropped, nesting is capped at {@link MAX_DEPTH} and the item count
* at {@link MAX_ITEMS}.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef, watch, type WatchStopHandle } from "vue";
import { onEngineEvent, run, type EngineError, type EngineEventPayload } from "../../ipc";
import { useEditorStore } from "../../stores/editor";
/** Engine command that returns the outline. */
export const OUTLINE_COMMAND = "syntax.outline";
/** Deepest nesting kept from the engine's outline. */
export const MAX_DEPTH = 64;
/** Most items kept from one outline. */
export const MAX_ITEMS = 50_000;
/** The kinds of outline items, as the engine names them. */
export const OUTLINE_KINDS = [
"namespace",
"class",
"interface",
"trait",
"enum",
"function",
"method",
"property",
"constant",
"enumCase",
] as const;
/** Kind of an outline item. */
export type OutlineKind = (typeof OUTLINE_KINDS)[number];
/** A 0-based position; the column counts UTF-16 code units. */
export interface OutlinePosition {
/** Line. */
line: number;
/** Column. */
column: number;
}
/** One declaration of the outline. */
export interface OutlineNode {
/** What it declares. */
kind: OutlineKind;
/** Name as written (`$id` for a property). */
name: string;
/** Short signature, e.g. `(int $id): ?Product`; null if none. */
detail: string | null;
/** Start of the name, where a jump lands. */
start: OutlinePosition;
/** Nested declarations in source order. */
children: OutlineNode[];
}
/** A visible row of the tree. */
export interface StructureRow {
/** Stable key: the path of kinds and names from the root. */
key: string;
/** Nesting depth, 0 at the top. */
depth: number;
/** The item. */
node: OutlineNode;
/** Whether the item has children. */
parent: boolean;
/** Whether its children are shown. */
expanded: boolean;
}
/**
* Reads a position, or null if malformed.
*
* @param raw - an untrusted `{line, column}`.
*/
function toPosition(raw: unknown): OutlinePosition | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const p = raw as Record<string, unknown>;
const ok = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v) && v >= 0;
return ok(p.line) && ok(p.column) ? { line: p.line, column: p.column } : null;
}
/**
* Reads the outline items of a `syntax.outline` result.
*
* @param raw - the untrusted `items` field.
* @returns the well-formed items; malformed ones are dropped with their
* children.
*/
export function toOutline(raw: unknown): OutlineNode[] {
let budget = MAX_ITEMS;
const read = (items: unknown, depth: number): OutlineNode[] => {
if (!Array.isArray(items) || depth >= MAX_DEPTH) {
return [];
}
const out: OutlineNode[] = [];
for (const item of items as unknown[]) {
if (budget <= 0) {
break;
}
if (typeof item !== "object" || item === null) {
continue;
}
const i = item as Record<string, unknown>;
const kind = OUTLINE_KINDS.find((k) => k === i.kind);
const selection = typeof i.selectionRange === "object" && i.selectionRange !== null
? toPosition((i.selectionRange as Record<string, unknown>).start)
: null;
if (kind === undefined || typeof i.name !== "string" || selection === null) {
continue;
}
budget -= 1;
out.push({
kind,
name: i.name,
detail: typeof i.detail === "string" && i.detail !== "" ? i.detail : null,
start: selection,
children: read(i.children, depth + 1),
});
}
return out;
};
return read(raw, 0);
}
/**
* The visible rows of an outline.
*
* @param nodes - the outline.
* @param collapsed - keys of collapsed nodes.
*/
export function flatten(nodes: OutlineNode[], collapsed: ReadonlySet<string>): StructureRow[] {
const rows: StructureRow[] = [];
const walk = (list: OutlineNode[], depth: number, prefix: string): void => {
const seen = new Map<string, number>();
for (const node of list) {
const base = `${prefix}/${node.kind}:${node.name}`;
const n = seen.get(base) ?? 0;
seen.set(base, n + 1);
const key = n === 0 ? base : `${base}#${String(n)}`;
const parent = node.children.length > 0;
const expanded = parent && !collapsed.has(key);
rows.push({ key, depth, node, parent, expanded });
if (expanded) {
walk(node.children, depth + 1, key);
}
}
};
walk(nodes, 0, "");
return rows;
}
/** The key of a row's parent, or null at the top. */
export function parentKey(key: string): string | null {
const slash = key.lastIndexOf("/");
return slash > 0 ? key.slice(0, slash) : null;
}
/** Store of the Structure tool window. */
export const useStructureStore = defineStore("structure", () => {
const editor = useEditorStore();
/** Buffer whose outline is shown, null without an active tab. */
const bufferId = ref<number | null>(null);
/** The outline. */
const items = shallowRef<OutlineNode[]>([]);
/** The file was too large to parse. */
const truncated = ref(false);
/** No parse of the buffer has finished yet. */
const pending = ref(false);
/** The last failed `syntax.outline`, null if none. */
const error = ref<EngineError | null>(null);
/** Collapsed node keys per buffer. */
const collapsedBy = ref(new Map<number, Set<string>>());
/** Key of the selected row, null if none. */
const selected = ref<string | null>(null);
/** Number of the newest request; older answers are dropped. */
let sequence = 0;
/** How many components started the store. */
let users = 0;
/** Ends the event subscription and the tab watch. */
let stops: (() => void)[] = [];
/** Collapsed keys of the shown buffer. */
const collapsed = computed<ReadonlySet<string>>(() =>
bufferId.value === null ? new Set() : (collapsedBy.value.get(bufferId.value) ?? new Set()),
);
/** The visible rows. */
const rows = computed(() => flatten(items.value, collapsed.value));
/** Path of the shown buffer, for `editor.reveal`. */
const path = computed(() => editor.tabs.find((tab) => tab.id === bufferId.value)?.path ?? null);
/**
* Fetches the outline of a buffer.
*
* @param id - buffer id, or null to clear the window.
*/
async function load(id: number | null): Promise<void> {
sequence += 1;
const mine = sequence;
if (id !== bufferId.value) {
selected.value = null;
}
bufferId.value = id;
if (id === null) {
items.value = [];
truncated.value = false;
pending.value = false;
error.value = null;
return;
}
const result = await run<{ items?: unknown; truncated?: unknown; version?: unknown }>(OUTLINE_COMMAND, { id });
if (mine !== sequence) {
return;
}
if (!result.ok) {
error.value = result.error;
items.value = [];
return;
}
error.value = null;
items.value = toOutline(result.value.items);
truncated.value = result.value.truncated === true;
pending.value = result.value.version === null;
}
/**
* Handles an engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "outlineChanged" && event.id === bufferId.value) {
void load(bufferId.value);
}
}
/** Starts following the active tab and engine events; counted per user. */
function start(): void {
users += 1;
if (users > 1) {
return;
}
const unwatch: WatchStopHandle = watch(
() => editor.activeId,
(id) => void load(id),
{ immediate: true },
);
stops = [onEngineEvent(onEvent), unwatch];
}
/** Stops following once the last user stopped. */
function stop(): void {
users = Math.max(0, users - 1);
if (users > 0) {
return;
}
for (const fn of stops) {
fn();
}
stops = [];
}
/**
* Expands or collapses a node.
*
* @param key - the row key.
* @param expand - true to expand, false to collapse.
*/
function setExpanded(key: string, expand: boolean): void {
const id = bufferId.value;
if (id === null) {
return;
}
const open = new Set(editor.tabs.map((tab) => tab.id));
const next = new Map([...collapsedBy.value].filter(([buffer]) => open.has(buffer)));
const keys = new Set(next.get(id) ?? []);
if (expand) {
keys.delete(key);
} else {
keys.add(key);
}
next.set(id, keys);
collapsedBy.value = next;
}
/**
* Selects a row.
*
* @param key - the row key, or null.
*/
function select(key: string | null): void {
selected.value = key;
}
return { bufferId, items, truncated, pending, error, selected, rows, path, collapsed, load, start, stop, setExpanded, select };
});

View file

@ -11,6 +11,7 @@
"command.settings.open": "Settings…",
"command.unavailable": "{command} cannot run right now",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
"common.close": "Close",
"common.dismiss": "Dismiss",
@ -22,6 +23,7 @@
"common.toolWindow.hide": "Hide {title}",
"common.toolWindow.resize": "Resize {title}",
"common.toolWindow.show": "Show {title}",
"common.toolWindow.stripe": "Tool windows",
"editor.closePrompt.question": "Save changes to {name} before closing?",
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
@ -101,6 +103,22 @@
"settings.ui.language.description": "Language of the interface. More languages follow.",
"settings.ui.language.label": "Language",
"settings.ui.language.value.en": "English",
"structure.empty.noFile": "Open a file to see its structure",
"structure.empty.none": "No declarations in this file",
"structure.empty.parsing": "Reading the file…",
"structure.empty.tooLarge": "This file is too large to show its structure",
"structure.kind.class": "Class",
"structure.kind.constant": "Constant",
"structure.kind.enum": "Enum",
"structure.kind.enumCase": "Enum case",
"structure.kind.function": "Function",
"structure.kind.interface": "Interface",
"structure.kind.method": "Method",
"structure.kind.namespace": "Namespace",
"structure.kind.property": "Property",
"structure.kind.trait": "Trait",
"structure.toolWindow.title": "Structure",
"structure.tree.label": "Declarations of the file",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light"
}

View file

@ -85,6 +85,11 @@ export type EngineEventPayload =
cancelled: unknown;
/** Wall time in milliseconds; unchecked. */
elapsedMs: unknown;
}
| {
kind: "outlineChanged";
/** Buffer whose outline changed; unchecked, it comes from the engine. */
id: unknown;
};
/** Callback receiving engine events. */

View file

@ -55,7 +55,7 @@ describe("App", () => {
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(true);
await press({ key: "1", code: "Digit1", ctrlKey: true });
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(false);
expect(wrapper.find("[data-test=tool-window-stripe]").exists()).toBe(true);
expect(wrapper.find("[data-test=left-stripe]").exists()).toBe(true);
await press({ key: "1", code: "Digit1", ctrlKey: true });
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(true);
await press({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true });

View file

@ -122,7 +122,7 @@ describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) {
expect(key).toMatch(
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|structure)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");

View file

@ -266,6 +266,7 @@ describe("CommandPalette", () => {
"editor.reveal",
"settings.open",
"view.toggleProjectTree",
"view.toggleStructure",
]);
const quit = wrapper.find("[data-command='app.quit']");
expect(quit.find("[data-test=palette-shortcut]").text()).toBe("Ctrl+Q");
@ -297,7 +298,7 @@ describe("CommandPalette", () => {
const wrapper = await mountPalette();
await press(PALETTE_KEY);
await press({ key: "ArrowUp" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("view.toggleProjectTree");
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("view.toggleStructure");
await press({ key: "ArrowDown" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.close");
});

View file

@ -0,0 +1,436 @@
/**
* Tests of the Structure tool window (M2.7): reading the engine's outline
* (malformed items dropped, depth cap), the visible rows and collapsed
* nodes, the store following the active tab and `outlineChanged` (and
* dropping stale answers), the window (empty states, icons and signatures,
* keyboard navigation, jumps through `editor.reveal`), and the left stripe
* with `view.toggleStructure` in the main layout. The engine is a fake
* behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, 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 }));
import { useCommandsStore } from "../../src/commands/store";
import MainLayout from "../../src/components/layout/MainLayout.vue";
import StructureToolWindow from "../../src/components/structure/StructureToolWindow.vue";
import { MAX_DEPTH, flatten, parentKey, toOutline, useStructureStore } from "../../src/components/structure/structure";
import { useEditorStore } from "../../src/stores/editor";
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Engine event callbacks of every subscription. */
let listeners: ((event: { payload: unknown }) => void)[];
/** The outline the fake returns per buffer id. */
let outlines: Map<number, unknown>;
/** Answers of `syntax.outline` held back until released, if set. */
let held: (() => void)[] | null;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscription.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/**
* An outline item as the engine sends it.
*
* @param kind - the kind.
* @param name - the name.
* @param line - line of the name.
* @param children - nested items.
* @param detail - signature, if any.
*/
function item(kind: string, name: string, line: number, children: unknown[] = [], detail?: string): unknown {
const at = { line, column: 4 };
return {
kind,
name,
...(detail === undefined ? {} : { detail }),
range: { start: at, end: at },
selectionRange: { start: at, end: { line, column: 4 + name.length } },
children,
};
}
/** The outline of a small class file. */
const SHOP = [
item("namespace", "App", 1, [
item("class", "Shop", 3, [
item("property", "$items", 5, [], "array"),
item("method", "find", 7, [], "(int $id): ?Product"),
item("method", "save", 9),
], "extends Base"),
]),
];
/**
* Opens a fake tab in the editor store.
*
* @param id - buffer id.
* @param path - file path.
*/
function openTab(id: number, path: string): void {
const editor = useEditorStore(pinia);
editor.tabs.push({ id, path, name: path, dirty: false, notice: null });
editor.activeId = id;
}
/** The `syntax.outline` ids requested, in order. */
function outlineRequests(): unknown[] {
return calls.filter((c) => c.command === "syntax.outline").map((c) => c.params.id);
}
/** Names of the visible rows. */
function rowNames(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=structure-row]").map((r) => r.get(".structure-tree__name").text());
}
/** Mounts the window with an `editor.reveal` spy. */
async function mountStructure(): Promise<{ wrapper: VueWrapper; reveals: unknown[] }> {
const reveals: unknown[] = [];
useCommandsStore(pinia).provide("editor.reveal", { run: (params) => void reveals.push(params) });
const wrapper = mount(StructureToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return { wrapper, reveals };
}
/**
* Presses a key on the tree.
*
* @param wrapper - the window.
* @param key - the key.
*/
async function key(wrapper: VueWrapper, key: string): Promise<void> {
await wrapper.get("[data-test=structure-tree]").trigger("keydown", { key });
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
listeners = [];
outlines = new Map();
held = null;
mounted = [];
Element.prototype.scrollIntoView = () => undefined;
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd !== "engine_execute" || !args) {
return Promise.resolve(null);
}
calls.push({ command: args.command, params: args.params });
if (args.command === "syntax.outline") {
const id = args.params.id as number;
const answer = (): unknown => {
const items = outlines.get(id);
if (items === "fail") {
return Promise.reject(Object.assign(new Error("failed"), { code: "failed", message: "no buffer" }));
}
return { items: items ?? [], truncated: id === 99, version: items === undefined ? null : 1 };
};
if (held) {
const queue = held;
return new Promise((resolve) => {
queue.push(() => {
resolve(answer());
});
});
}
return Promise.resolve(answer());
}
return Promise.resolve(null);
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
});
describe("outline parsing", () => {
it("keeps well-formed items and drops malformed ones", () => {
const nodes = toOutline([
item("class", "A", 0, [item("method", "m", 1, [], "(): void"), { kind: "method", name: 3 }]),
item("lambda", "x", 2),
{ kind: "function", name: "f", selectionRange: { start: { line: -1, column: 0 } } },
null,
"class",
]);
expect(nodes).toEqual([
{
kind: "class",
name: "A",
detail: null,
start: { line: 0, column: 4 },
children: [{ kind: "method", name: "m", detail: "(): void", start: { line: 1, column: 4 }, children: [] }],
},
]);
expect(toOutline({ items: [] })).toEqual([]);
});
it("caps the nesting depth", () => {
let deep: unknown = item("function", "leaf", 0);
for (let i = 0; i < MAX_DEPTH + 10; i += 1) {
deep = item("class", `C${String(i)}`, 0, [deep]);
}
let depth = 0;
let nodes = toOutline([deep]);
while (nodes[0]) {
depth += 1;
nodes = nodes[0].children;
}
expect(depth).toBe(MAX_DEPTH);
});
it("flattens with collapsed nodes and unique keys", () => {
const nodes = toOutline([item("class", "A", 0, [item("method", "m", 1), item("method", "m", 2)]), item("class", "B", 3)]);
const rows = flatten(nodes, new Set());
expect(rows.map((r) => [r.key, r.depth, r.parent, r.expanded])).toEqual([
["/class:A", 0, true, true],
["/class:A/method:m", 1, false, false],
["/class:A/method:m#1", 1, false, false],
["/class:B", 0, false, false],
]);
expect(flatten(nodes, new Set(["/class:A"])).map((r) => r.key)).toEqual(["/class:A", "/class:B"]);
expect(parentKey("/class:A/method:m")).toBe("/class:A");
expect(parentKey("/class:A")).toBeNull();
});
});
describe("structure store", () => {
it("follows the active tab and outlineChanged of that buffer only", async () => {
outlines.set(3, SHOP);
outlines.set(4, [item("function", "helper", 0)]);
const store = useStructureStore(pinia);
store.start();
await flushPromises();
expect(outlineRequests()).toEqual([]);
openTab(3, "src/Shop.php");
await flushPromises();
expect(store.items.map((n) => n.name)).toEqual(["App"]);
openTab(4, "src/helpers.php");
await flushPromises();
expect(store.items.map((n) => n.name)).toEqual(["helper"]);
await emit({ kind: "outlineChanged", id: 3 });
expect(outlineRequests()).toEqual([3, 4]);
outlines.set(4, [item("function", "helper2", 0)]);
await emit({ kind: "outlineChanged", id: 4 });
expect(outlineRequests()).toEqual([3, 4, 4]);
expect(store.items.map((n) => n.name)).toEqual(["helper2"]);
store.stop();
await emit({ kind: "outlineChanged", id: 4 });
expect(outlineRequests()).toEqual([3, 4, 4]);
});
it("drops an answer overtaken by a newer request", async () => {
outlines.set(3, SHOP);
outlines.set(4, [item("function", "helper", 0)]);
const store = useStructureStore(pinia);
store.start();
held = [];
const queue = held;
openTab(3, "a.php");
await flushPromises();
openTab(4, "b.php");
await flushPromises();
const [first, second] = queue;
second?.();
await flushPromises();
first?.();
await flushPromises();
expect(store.items.map((n) => n.name)).toEqual(["helper"]);
store.stop();
});
it("keeps collapsed nodes per buffer across refreshes", async () => {
outlines.set(3, SHOP);
outlines.set(4, SHOP);
const store = useStructureStore(pinia);
store.start();
openTab(3, "a.php");
await flushPromises();
store.setExpanded("/namespace:App/class:Shop", false);
expect(store.rows.map((r) => r.node.name)).toEqual(["App", "Shop"]);
await emit({ kind: "outlineChanged", id: 3 });
expect(store.rows.map((r) => r.node.name)).toEqual(["App", "Shop"]);
openTab(4, "b.php");
await flushPromises();
expect(store.rows).toHaveLength(5);
useEditorStore(pinia).activeId = 3;
await flushPromises();
expect(store.rows).toHaveLength(2);
store.stop();
});
});
describe("Structure tool window", () => {
it("says when no file is open, a file has no declarations, is being read or is too large", async () => {
const { wrapper } = await mountStructure();
expect(wrapper.get("[data-test=structure-empty]").text()).toBe("Open a file to see its structure");
openTab(5, "pending.php");
await flushPromises();
expect(wrapper.get("[data-test=structure-empty]").text()).toBe("Reading the file…");
outlines.set(6, []);
openTab(6, "empty.php");
await flushPromises();
expect(wrapper.get("[data-test=structure-empty]").text()).toBe("No declarations in this file");
openTab(99, "huge.php");
await flushPromises();
expect(wrapper.get("[data-test=structure-empty]").text()).toBe("This file is too large to show its structure");
outlines.set(7, "fail");
openTab(7, "gone.php");
await flushPromises();
expect(wrapper.get("[data-test=structure-error]").text()).toBe("no buffer");
});
it("shows the tree with kind icons and signatures, and updates on outlineChanged", async () => {
outlines.set(3, SHOP);
openTab(3, "src/Shop.php");
const { wrapper } = await mountStructure();
expect(rowNames(wrapper)).toEqual(["App", "Shop", "$items", "find", "save"]);
const rows = wrapper.findAll("[data-test=structure-row]");
expect(rows.map((r) => r.attributes("data-kind"))).toEqual(["namespace", "class", "property", "method", "method"]);
expect(rows.map((r) => r.attributes("aria-level"))).toEqual(["1", "2", "3", "3", "3"]);
expect(rows[3]?.get(".structure-tree__detail").text()).toBe("(int $id): ?Product");
expect(rows[3]?.get(".structure-tree__icon").attributes("title")).toBe("Method");
expect(rows[3]?.find("svg").exists()).toBe(true);
expect(rows[1]?.attributes("aria-expanded")).toBe("true");
expect(rows[2]?.attributes("aria-expanded")).toBeUndefined();
outlines.set(3, [item("class", "Shop", 3, [item("method", "find", 7)])]);
await emit({ kind: "outlineChanged", id: 3 });
expect(rowNames(wrapper)).toEqual(["Shop", "find"]);
});
it("jumps to a declaration on click, the chevron only folds", async () => {
outlines.set(3, SHOP);
openTab(3, "src/Shop.php");
const { wrapper, reveals } = await mountStructure();
await wrapper.findAll("[data-test=structure-row]")[3]?.trigger("click");
await flushPromises();
expect(reveals).toEqual([{ path: "src/Shop.php", line: 7, column: 4 }]);
expect(wrapper.findAll("[data-test=structure-row]")[3]?.attributes("aria-selected")).toBe("true");
await wrapper.findAll("[data-test=structure-chevron]")[1]?.trigger("click");
await flushPromises();
expect(rowNames(wrapper)).toEqual(["App", "Shop"]);
expect(reveals).toHaveLength(1);
});
it("walks, folds and jumps with the keyboard", async () => {
outlines.set(3, SHOP);
openTab(3, "src/Shop.php");
const { wrapper, reveals } = await mountStructure();
const tree = wrapper.get("[data-test=structure-tree]");
await tree.trigger("focus");
const selected = (): string | undefined =>
wrapper.find("[data-test=structure-row][aria-selected=true] .structure-tree__name").text();
expect(selected()).toBe("App");
expect(tree.attributes("aria-activedescendant")).toBe(wrapper.findAll("[data-test=structure-row]")[0]?.attributes("id"));
await key(wrapper, "ArrowRight");
expect(selected()).toBe("Shop");
await key(wrapper, "ArrowLeft");
expect(rowNames(wrapper)).toEqual(["App", "Shop"]);
await key(wrapper, "ArrowRight");
expect(rowNames(wrapper)).toHaveLength(5);
await key(wrapper, "End");
expect(selected()).toBe("save");
await key(wrapper, "ArrowUp");
await key(wrapper, "Enter");
await flushPromises();
expect(reveals).toEqual([{ path: "src/Shop.php", line: 7, column: 4 }]);
await key(wrapper, "ArrowLeft");
expect(selected()).toBe("Shop");
await key(wrapper, "Home");
expect(selected()).toBe("App");
await key(wrapper, "ArrowDown");
expect(selected()).toBe("Shop");
});
});
describe("left stripe and view.toggleStructure", () => {
/** Mounts the main layout with the commands store started. */
async function mountLayout(): Promise<VueWrapper> {
const wrapper = mount(MainLayout, {
attachTo: document.body,
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } },
});
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
/** The title of the left tool window, or null when it is hidden. */
function leftTitle(wrapper: VueWrapper): string | null {
const window = wrapper.find("[data-test=tool-window]");
return window.exists() ? window.get(".tool-window__title").text() : null;
}
it("is registered with its own shortcut", async () => {
await mountLayout();
const registered = calls.find((c) => c.command === "ui.registerCommands")?.params.commands as {
id: string;
defaultShortcut?: string;
}[];
expect(registered.find((c) => c.id === "view.toggleStructure")?.defaultShortcut).toBe("Mod+2");
});
it("switches between Project and Structure from the stripe and hides the shown one", async () => {
const wrapper = await mountLayout();
const tabs = wrapper.findAll("[role=tab]");
expect(tabs.map((tab) => tab.attributes("aria-label"))).toEqual(["Project", "Structure"]);
expect(tabs.map((tab) => tab.attributes("aria-selected"))).toEqual(["true", "false"]);
expect(leftTitle(wrapper)).toBe("Project");
await wrapper.get("[data-test=stripe-structure]").trigger("click");
expect(leftTitle(wrapper)).toBe("Structure");
expect(wrapper.get("[data-test=structure-empty]").isVisible()).toBe(true);
await wrapper.get("[data-test=stripe-structure]").trigger("click");
expect(leftTitle(wrapper)).toBeNull();
expect(wrapper.findAll("[role=tab]").map((tab) => tab.attributes("aria-selected"))).toEqual(["false", "false"]);
await wrapper.get("[data-test=stripe-project]").trigger("click");
expect(leftTitle(wrapper)).toBe("Project");
});
it("toggles Structure from the shortcut and from an agent's uiCommand", async () => {
outlines.set(3, SHOP);
openTab(3, "src/Shop.php");
const wrapper = await mountLayout();
window.dispatchEvent(new KeyboardEvent("keydown", { key: "2", code: "Digit2", ctrlKey: true, bubbles: true }));
await flushPromises();
expect(leftTitle(wrapper)).toBe("Structure");
expect(rowNames(wrapper)).toEqual(["App", "Shop", "$items", "find", "save"]);
await emit({ kind: "uiCommand", id: "view.toggleStructure", params: {} });
expect(leftTitle(wrapper)).toBeNull();
await emit({ kind: "uiCommand", id: "view.toggleStructure", params: {} });
expect(leftTitle(wrapper)).toBe("Structure");
await emit({ kind: "uiCommand", id: "view.toggleProjectTree", params: {} });
expect(leftTitle(wrapper)).toBe("Project");
});
});