A local-first multi-agent app development platform, built on PenguinHarness
refactor(web): draw the plugin library's file browser with the Workspace tree (#685)
Yaowei Zheng012f20e926f4
diff --git a/.agents/skills/penguin-harness-frontend/SKILL.md b/.agents/skills/penguin-harness-frontend/SKILL.mdindex 78b2eb69..ec26cfbd 100644--- a/.agents/skills/penguin-harness-frontend/SKILL.md+++ b/.agents/skills/penguin-harness-frontend/SKILL.md@@ -134,9 +134,11 @@ the caret, the close cross or the collapse chevron.## Every user-facing string is bilingualTwo dictionaries: `src/lib/strings.ts` is zh (and defines the `Strings` type), `src/lib/strings-en.ts`-is en and is typed `const en: Strings`. Adding a key to one and not the other is a **type error**,-not a runtime surprise — and `test/placeholders-parity.test.ts` checks that both sides interpolate-the same placeholders. Add both, in the same shape, in the same PR.+is en and is typed `const en: Strings`. That type is the whole guard: a key added to one and not+the other, or a signature that changed on one side, is a **type error** rather than a runtime+surprise. What it cannot see is whether a function-valued string uses the parameter it is handed —+`(n: number) => "items"` typechecks while the other side interpolates `n`. Add both, in the same+shape, in the same PR.`S` is a live binding swapped on locale change, so read it at render time; never hoist `S.x.y` intoa module-level constant.diff --git a/changelog/unreleased/2026-09-11-shared-file-tree.md b/changelog/unreleased/2026-09-11-shared-file-tree.mdnew file mode 100644index 00000000..ed87f3ee--- /dev/null+++ b/changelog/unreleased/2026-09-11-shared-file-tree.md@@ -0,0 +1,32 @@+# The plugin library's file browser draws the Workspace's tree++- **Date:** 2026-09-11+- **Type:** refactor+- **Scope:** `web`+- **PR:** [#685](https://github.com/Prism-Shadow/penguin-harness/pull/685)++[中文版](2026-09-11-shared-file-tree.zh.md)++The Workspace panel's directory tree moved into `components/ui/file-tree.tsx`, and the plugin+detail Modal's file browser was put on it. That browser's rows had been plain buttons — a text+triangle per group, a middot per file, a border between every row, and a nested file carrying+its whole relative path in its name; they are now the rows the Files panel draws, with a+chevron, a folder or page glyph, indentation per level and the height animation on opening and+closing a directory. A skill's `reference/` became a directory row of its own instead of a+slash inside nine file names.++## Details++- The row markup, the indentation scale, the glyphs, the selected, hover and focus treatment,+ the WAI-ARIA `tree` semantics (`role`, `aria-level`, `aria-posinset`, `aria-setsize`,+ `aria-expanded`), the roving tab stop, the arrow-key walk and the `data-tree-path` /+ `data-tree-kind` attributes a caller resolves a pointer event through all went into+ `FileTree`. Data loading stayed with the callers: the Workspace panel lists one directory+ per level as it is opened, the plugin browser groups the single listing it already holds.+- The row shape, `subtreeEnd` and `treeKeyStep` moved from `lib/workspace-tree.ts` to+ `lib/file-tree.ts`, with their test cases. Stepping out of a row now takes the parent from+ the row above it rather than from its path, so a tree whose top-level rows are whole paths+ (`skills/<name>`) steps onto a row that exists.+- `WorkspaceTreeView` kept what only the Workspace has: the size and modified time in a row's+ tooltip and after its name, the upload directory standing in for a selection while no file is+ open, and the three things an empty row list can mean.diff --git a/changelog/unreleased/2026-09-11-shared-file-tree.zh.md b/changelog/unreleased/2026-09-11-shared-file-tree.zh.mdnew file mode 100644index 00000000..fad46518--- /dev/null+++ b/changelog/unreleased/2026-09-11-shared-file-tree.zh.md@@ -0,0 +1,26 @@+# 插件库的文件浏览器改用 Workspace 的目录树++- **Date:** 2026-09-11+- **Type:** refactor+- **Scope:** `web`+- **PR:** [#685](https://github.com/Prism-Shadow/penguin-harness/pull/685)++[English](2026-09-11-shared-file-tree.md)++Workspace 面板的目录树移入 `components/ui/file-tree.tsx`,插件详情 Modal 的文件浏览器改由它绘制。+该浏览器此前的行是朴素按钮——每个分组一个文本三角、每个文件一个间隔点、行与行之间一条分隔线,嵌套+文件还把整段相对路径写进名字里;现在它们就是文件面板画的那种行:折叠箭头、文件夹或文件图形、按层级+缩进,展开与收起目录时带高度过渡。Skill 的 `reference/` 成为一个独立的目录行,不再是九个文件名里的+一条斜杠。++## 细节++- 行的标记、缩进刻度、图形、选中与 hover、focus 的表现,WAI-ARIA `tree` 语义(`role`、`aria-level`、+ `aria-posinset`、`aria-setsize`、`aria-expanded`)、轮转式 tab 落点与方向键行走,以及调用方用来在指针+ 事件中定位行的 `data-tree-path` / `data-tree-kind` 属性,一并移入了 `FileTree`。取数仍归调用方:+ Workspace 面板每展开一层就列一次目录,插件浏览器则对已经拿到的那份清单做分组。+- 行的形状、`subtreeEnd` 与 `treeKeyStep` 从 `lib/workspace-tree.ts` 移入 `lib/file-tree.ts`,其用例+ 一并迁移。从一行向上退出时,父行改为取上方最近的更浅一层的行,而不再从路径推得,因此顶层行本身就是+ 整段路径(`skills/<名称>`)的树也能落到真实存在的行上。+- `WorkspaceTreeView` 保留只属于 Workspace 的部分:行提示与名称之后的大小与修改时间、未打开任何文件+ 时以上传目录代替选中项,以及行列表为空时的三种含义。diff --git a/packages/web/src/components/ui/file-tree.tsx b/packages/web/src/components/ui/file-tree.tsxnew file mode 100644index 00000000..af348538--- /dev/null+++ b/packages/web/src/components/ui/file-tree.tsx@@ -0,0 +1,341 @@+/**+ * The app's file tree: one row per entry on screen, indented by depth, a chevron and a folder+ * glyph on directories, a page glyph on files. Clicking a directory opens or closes it,+ * clicking a file hands it to the caller.+ *+ * The caller brings the rows (`lib/file-tree.ts` states their shape) and nothing else about how+ * they were produced: the Workspace panel lists one directory per level as it is opened, the+ * plugin browser groups a listing it already holds. What this owns is the drawing and the+ * interaction — indentation, glyphs, the selected and hover treatment, the ARIA tree semantics+ * and the keyboard walk.+ *+ * Keyboard: the WAI-ARIA tree pattern with a roving tab stop — one row is in the tab order+ * (the focused one, else the selected one, else the first), arrows move between rows and+ * open/close directories (treeKeyStep), Enter and Space act like a click.+ *+ * Rows carry `data-tree-path` / `data-tree-kind`, which is how a caller that handles a pointer+ * event over the whole tree (the Workspace panel's drag-and-drop, its context menu) resolves+ * the row under the pointer.+ *+ * The rows stay one flat list; what nests is the drawing. An open directory's descendants go+ * in a `role="group"` box whose height is animated, so a subtree grows out of its directory's+ * row and shrinks back into it. Only the directory the caller says was just toggled animates,+ * so a re-render, a filter or an unrelated commit animates nothing. Closing is the awkward+ * half: the rows are gone from `rows` by the time the view hears about it, so the view keeps+ * the last committed rows and re-renders the closed directory's own descendants, inert, for+ * as long as the shrink lasts.+ */+import { useEffect, useRef, useState } from "react";+import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";+import { subtreeEnd, treeKeyStep } from "../../lib/file-tree";+import type { FileTreeRow } from "../../lib/file-tree";+import { Chevron } from "./chevron";+import { GlyphIcon } from "./glyph-icon";+import { FOLDER_ICON, FOLDER_OPEN_ICON } from "./group-list";+import { FILE_ICON } from "./icons";+import { ICON_SIZE } from "../../lib/icon-scale";++/** Left padding of a depth-0 row, in px; deeper rows add `TREE_INDENT_PX` per level. */+const TREE_PAD_PX = 6;++/** Indent per nesting level, in px. */+const TREE_INDENT_PX = 14;++/** Width of the chevron column, in px — `w-3.5`, mirrored so an empty directory's line can clear it. */+const CHEVRON_COL_PX = 14;++/**+ * How long a closing subtree is kept on screen when its animation never reports back. Under+ * `prefers-reduced-motion` the keyframes are off, so no `animationend` ever arrives and this+ * timer is the only thing that drops the retained rows. Comfortably past the 200ms shrink.+ */+const CLOSE_FALLBACK_MS = 260;++/** The directory whose open or close the tree should animate. `serial` makes toggling the same directory again a new event. */+export interface TreeToggle {+ dir: string;+ open: boolean;+ serial: number;+}++export function FileTree<Row extends FileTreeRow>({+ rows,+ label,+ selectedPath,+ loadingDirs,+ dropTargetDir = null,+ scrollTo = null,+ toggled = null,+ rowTitle,+ rowTrailing,+ emptyLabel,+ className = "",+ children,+ onToggleDir,+ onOpenFile,+}: {+ rows: readonly Row[];+ /** The tree's accessible name. */+ label: string;+ /** The row drawn as selected, and the tab stop's fallback. */+ selectedPath: string | null;+ /** Directories whose listing is in flight: the row dims and reports `aria-busy`. */+ loadingDirs?: ReadonlySet<string>;+ /** The folder a hovering drag would drop into, ringed while it is; null while nothing is dragged. */+ dropTargetDir?: string | null;+ /** A row to bring into view; a new object scrolls again even for the same path. */+ scrollTo?: { path: string } | null;+ /** The directory last opened or closed, whose subtree animates. Null: nothing to animate. */+ toggled?: TreeToggle | null;+ /** A row's `title` tooltip; the path by default. */+ rowTitle?: (row: Row) => string;+ /** Trailing content on a row, after its name — the Workspace's file sizes. */+ rowTrailing?: (row: Row) => ReactNode;+ /** What an open directory holding nothing says in place of its children; omitted, it says nothing. */+ emptyLabel?: string;+ /** Extra classes on the tree container — its own layout and scrolling belong to the caller. */+ className?: string;+ /** Shown in place of the rows when there are none: the caller's empty or no-match state. */+ children?: ReactNode;+ onToggleDir: (dir: string) => void;+ onOpenFile: (path: string) => void;+}) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const [focused, setFocused] = useState<string | null>(null);++ // The descendants of directories that have just closed, by directory path. They are no+ // longer in `rows` — the caller closed the directory in the same commit that reported the+ // toggle — so they are captured from the previous commit's rows and drawn until the shrink+ // is over. They are never in `rows`, and so never in treeKeyStep, the tab stop or onScreen.+ const [closing, setClosing] = useState<ReadonlyMap<string, readonly Row[]>>(() => new Map());+ // The serial of the toggle already acted on. The serial, not the object: a filter hands the+ // prop null and then hands the very same toggle back when it is cleared, and replaying that+ // close would shrink a ghost subtree out of a directory the user never touched.+ const [seenSerial, setSeenSerial] = useState<number>(toggled?.serial ?? 0);+ const prevRowsRef = useRef<readonly Row[]>(rows);++ if (toggled === null) {+ // A filter redraws the tree from a different row set; nothing left over belongs to it.+ if (closing.size > 0) setClosing(new Map());+ } else if (toggled.serial !== seenSerial) {+ // Adjusting state during render rather than in an effect: the retained rows have to be in+ // the same paint that dropped them, or the subtree blinks out and then shrinks from nothing.+ setSeenSerial(toggled.serial);+ if (toggled.open) {+ // Re-opened while shrinking: the live group takes over, animating open from where it is.+ if (closing.has(toggled.dir)) {+ const next = new Map(closing);+ next.delete(toggled.dir);+ setClosing(next);+ }+ } else {+ const prev = prevRowsRef.current;+ const at = prev.findIndex((r) => r.path === toggled.dir);+ const kept = at < 0 ? [] : prev.slice(at + 1, subtreeEnd(prev, at));+ if (kept.length > 0) setClosing(new Map(closing).set(toggled.dir, kept));+ }+ }++ useEffect(() => {+ prevRowsRef.current = rows;+ }, [rows]);++ const dropClosing = (dir: string): void => {+ setClosing((prev) => {+ if (!prev.has(dir)) return prev;+ const next = new Map(prev);+ next.delete(dir);+ return next;+ });+ };++ useEffect(() => {+ if (closing.size === 0) return;+ const timers = [...closing.keys()].map((dir) =>+ setTimeout(() => dropClosing(dir), CLOSE_FALLBACK_MS),+ );+ return () => {+ for (const timer of timers) clearTimeout(timer);+ };+ }, [closing]);++ const rowElement = (path: string): HTMLElement | null =>+ containerRef.current?.querySelector<HTMLElement>(`[data-tree-path="${CSS.escape(path)}"]`) ??+ null;++ useEffect(() => {+ if (scrollTo === null) return;+ if (scrollTo.path === "") containerRef.current?.scrollTo({ top: 0 });+ else rowElement(scrollTo.path)?.scrollIntoView({ block: "nearest" });+ }, [scrollTo]);++ const activate = (row: Row): void => {+ setFocused(row.path);+ if (row.kind === "dir") onToggleDir(row.path);+ else onOpenFile(row.path);+ };++ const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>): void => {+ if (e.key === "Enter" || e.key === " ") {+ const row = rows.find((r) => r.path === focused);+ if (row === undefined) return;+ e.preventDefault();+ activate(row);+ return;+ }+ const step = treeKeyStep(rows, focused, e.key);+ if (step === null) return;+ e.preventDefault();+ if (step.focus !== undefined) {+ setFocused(step.focus);+ rowElement(step.focus)?.focus();+ }+ if (step.expand !== undefined) onToggleDir(step.expand);+ if (step.collapse !== undefined) onToggleDir(step.collapse);+ };++ // The one row in the tab order. A focused row that scrolled out of the rows (its+ // directory closed) hands the stop back to the selection or the first row.+ const onScreen = (path: string | null): boolean =>+ path !== null && rows.some((r) => r.path === path);+ const tabStop = onScreen(focused)+ ? focused+ : onScreen(selectedPath)+ ? selectedPath+ : (rows[0]?.path ?? null);++ /** One row. A retained row is a leftover of a closing subtree: it draws, and does nothing else. */+ const renderRow = (row: Row, retained: boolean): ReactNode => {+ const selected = !retained && row.path === selectedPath;+ const dropHere = !retained && row.kind === "dir" && row.path === dropTargetDir;+ const loading = row.kind === "dir" && loadingDirs !== undefined && loadingDirs.has(row.path);+ return (+ <div+ key={row.path}+ role="treeitem"+ tabIndex={retained || row.path !== tabStop ? -1 : 0}+ aria-level={row.depth + 1}+ aria-posinset={row.posInSet}+ aria-setsize={row.setSize}+ aria-selected={selected}+ {...(row.kind === "dir" ? { "aria-expanded": row.expanded } : {})}+ aria-busy={loading || undefined}+ // A retained row carries no path: rowElement() and a caller's pointer hit test both+ // resolve a row by this attribute, and neither may land on one that is on its way out.+ {...(retained ? {} : { "data-tree-path": row.path, "data-tree-kind": row.kind })}+ title={rowTitle?.(row) ?? row.path}+ {...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}+ style={{ paddingLeft: TREE_PAD_PX + row.depth * TREE_INDENT_PX }}+ className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${+ dropHere+ ? "bg-sky-50 ring-2 ring-inset ring-sky-500/60 dark:bg-sky-950/40"+ : selected+ ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/50"+ } ${loading ? "opacity-60" : ""}`}+ >+ <span className="flex w-3.5 shrink-0 justify-center text-gray-400" aria-hidden>+ {row.kind === "dir" && <Chevron open={row.expanded} size={ICON_SIZE.chevronDense} />}+ </span>+ <GlyphIcon+ d={row.kind === "dir" ? (row.expanded ? FOLDER_OPEN_ICON : FOLDER_ICON) : FILE_ICON}+ size={ICON_SIZE.rowLead}+ className="text-gray-400"+ />+ <span className="min-w-0 flex-1 truncate">{row.name}</span>+ {rowTrailing?.(row)}+ </div>+ );+ };++ /** An open directory with nothing in it says so, in place of the children it lacks. */+ const renderEmptyLine = (row: Row): ReactNode => (+ <p+ key={`empty:${row.path}`}+ className="py-1 pr-2 text-xs text-gray-400"+ style={{ paddingLeft: TREE_PAD_PX + (row.depth + 1) * TREE_INDENT_PX + CHEVRON_COL_PX }}+ >+ {emptyLabel}+ </p>+ );++ /**+ * The rows of `list` in `[start, end)`, with each open directory's descendants nested in a+ * group below it. `retained` marks a closing subtree, which draws its own nested groups but+ * animates nothing and takes no part in interaction.+ */+ const renderRange = (+ list: readonly Row[],+ start: number,+ end: number,+ retained: boolean,+ ): ReactNode[] => {+ const out: ReactNode[] = [];+ let i = start;+ while (i < end) {+ const row = list[i]!;+ out.push(renderRow(row, retained));+ if (row.kind !== "dir") {+ i += 1;+ continue;+ }+ const childrenEnd = subtreeEnd(list, i);+ if (row.expanded && row.loaded) {+ // The group mounts only once the listing is there, so a first open of an unloaded+ // directory animates when its rows arrive rather than around an empty box.+ const opening = !retained && toggled !== null && toggled.open && toggled.dir === row.path;+ out.push(+ <div+ key={`group:${row.path}`}+ role="group"+ aria-label={row.name}+ className={`tree-group ${opening ? "tree-group-open" : ""}`}+ >+ <div>+ {!row.empty+ ? renderRange(list, i + 1, childrenEnd, retained)+ : emptyLabel === undefined+ ? null+ : renderEmptyLine(row)}+ </div>+ </div>,+ );+ } else if (!retained && closing.has(row.path)) {+ const kept = closing.get(row.path)!;+ out.push(+ <div+ key={`closing:${row.path}`}+ role="group"+ aria-hidden+ inert+ className="tree-group tree-group-close"+ onAnimationEnd={(e) => {+ if (e.target === e.currentTarget) dropClosing(row.path);+ }}+ >+ <div>{renderRange(kept, 0, kept.length, true)}</div>+ </div>,+ );+ }+ i = childrenEnd;+ }+ return out;+ };++ return (+ <div+ ref={containerRef}+ role="tree"+ aria-label={label}+ onKeyDown={onKeyDown}+ className={`py-1 ${className}`}+ >+ {rows.length === 0+ ? children+ : // `role="group"` is the tree pattern's own container for one level, so the rows inside+ // one are still `treeitem`s of this tree and keep stating their own aria-level,+ // aria-posinset and aria-setsize.+ renderRange(rows, 0, rows.length, false)}+ </div>+ );+}diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex 01d0fcc6..d3b47dd2 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -104,7 +104,7 @@ import { CodeBlock } from "./code-block";import { languageForExtension } from "./code-languages";import { WorkspaceFileEditor } from "./workspace-editor";import { WorkspaceTreeView } from "./workspace-tree-view";-import type { TreeToggle } from "./workspace-tree-view";+import type { TreeToggle } from "../../components/ui/file-tree";/** Source highlighting cap: tokenizing the full preview cap's worth of content in one go would block the main thread, so beyond this it falls back to unhighlighted. */const HIGHLIGHT_LIMIT = 64 * 1024;diff --git a/packages/web/src/features/chat/workspace-tree-view.tsx b/packages/web/src/features/chat/workspace-tree-view.tsxindex 294008e4..484ca88a 100644--- a/packages/web/src/features/chat/workspace-tree-view.tsx+++ b/packages/web/src/features/chat/workspace-tree-view.tsx@@ -1,53 +1,15 @@/**- * The Files panel's directory tree: one row per entry on screen (lib/workspace-tree.ts- * flattens the listings), indented by depth, a chevron and a folder glyph on directories,- * a page glyph and the size on files. Clicking a directory opens or closes it, clicking a- * file opens it in the preview.- *- * Keyboard: the WAI-ARIA tree pattern with a roving tab stop — one row is in the tab order- * (the focused one, else the selected one, else the first), arrows move between rows and- * open/close directories (treeKeyStep), Enter and Space act like a click.- *- * While OS files are dragged over the panel, the folder row that would receive them is- * highlighted; the rows carry `data-tree-path` / `data-tree-kind` so the panel's drop- * handling can resolve the row under the pointer.- *- * The rows stay one flat list; what nests is the drawing. An open directory's descendants go- * in a `role="group"` box whose height is animated, so a subtree grows out of its directory's- * row and shrinks back into it. Only the directory the panel says was just toggled animates,- * so a re-render, a filter or an unrelated commit animates nothing. Closing is the awkward- * half: the rows are gone from `rows` by the time the view hears about it, so the view keeps- * the last committed rows and re-renders the closed directory's own descendants, inert, for- * as long as the shrink lasts.+ * The Files panel's directory tree: the shared `FileTree` over the rows lib/workspace-tree.ts+ * flattens out of the lazily fetched listings. What this file adds is what only the Workspace+ * has — the size and modified time in a row's tooltip and after its name, the directory+ * uploads land in standing in for a selection while no file is open, and the three things an+ * empty row list can mean.*/-import { useEffect, useRef, useState } from "react";-import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";import { S } from "../../lib/strings";import { formatBytes, formatDateTime } from "../../lib/format";-import { subtreeEnd, treeKeyStep } from "../../lib/workspace-tree";import type { TreeRow } from "../../lib/workspace-tree";-import { Chevron } from "../../components/ui/chevron";-import { GlyphIcon } from "../../components/ui/glyph-icon";-import { FOLDER_ICON, FOLDER_OPEN_ICON } from "../../components/ui/group-list";-import { ICON_SIZE } from "../../lib/icon-scale";-import { FILE_ICON } from "../../components/ui/icons";--/** Indent per nesting level, in px. */-const INDENT_PX = 14;--/**- * How long a closing subtree is kept on screen when its animation never reports back. Under- * `prefers-reduced-motion` the keyframes are off, so no `animationend` ever arrives and this- * timer is the only thing that drops the retained rows. Comfortably past the 200ms shrink.- */-const CLOSE_FALLBACK_MS = 260;--/** The directory whose open or close the tree should animate. `serial` makes toggling the same directory again a new event. */-export interface TreeToggle {- dir: string;- open: boolean;- serial: number;-}+import { FileTree } from "../../components/ui/file-tree";+import type { TreeToggle } from "../../components/ui/file-tree";export function WorkspaceTreeView({rows,@@ -81,255 +43,39 @@ export function WorkspaceTreeView({onToggleDir: (dir: string) => void;onOpenFile: (path: string) => void;}) {- const containerRef = useRef<HTMLDivElement | null>(null);- const [focused, setFocused] = useState<string | null>(null);-- // The descendants of directories that have just closed, by directory path. They are no- // longer in `rows` — the panel closed the directory in the same commit that reported the- // toggle — so they are captured from the previous commit's rows and drawn until the shrink- // is over. They are never in `rows`, and so never in treeKeyStep, the tab stop or onScreen.- const [closing, setClosing] = useState<ReadonlyMap<string, readonly TreeRow[]>>(() => new Map());- // The serial of the toggle already acted on. The serial, not the object: a filter hands the- // prop null and then hands the very same toggle back when it is cleared, and replaying that- // close would shrink a ghost subtree out of a directory the user never touched.- const [seenSerial, setSeenSerial] = useState<number>(toggled?.serial ?? 0);- const prevRowsRef = useRef<readonly TreeRow[]>(rows);-- if (toggled === null) {- // A filter redraws the tree from a different row set; nothing left over belongs to it.- if (closing.size > 0) setClosing(new Map());- } else if (toggled.serial !== seenSerial) {- // Adjusting state during render rather than in an effect: the retained rows have to be in- // the same paint that dropped them, or the subtree blinks out and then shrinks from nothing.- setSeenSerial(toggled.serial);- if (toggled.open) {- // Re-opened while shrinking: the live group takes over, animating open from where it is.- if (closing.has(toggled.dir)) {- const next = new Map(closing);- next.delete(toggled.dir);- setClosing(next);+ return (+ <FileTree+ rows={rows}+ label={S.files.treeLabel}+ // With nothing open in the preview the highlight falls to the directory an upload would+ // land in, so the panel always shows where it is pointed.+ selectedPath={selectedPath ?? (currentDir === "" ? null : currentDir)}+ loadingDirs={loadingDirs}+ dropTargetDir={dropTargetDir}+ scrollTo={scrollTo}+ toggled={toggled}+ rowTitle={(row) =>+ row.kind === "file"+ ? `${row.path} · ${formatBytes(row.sizeBytes)} · ${formatDateTime(row.mtime)}`+ : row.path}- } else {- const prev = prevRowsRef.current;- const at = prev.findIndex((r) => r.path === toggled.dir);- const kept = at < 0 ? [] : prev.slice(at + 1, subtreeEnd(prev, at));- if (kept.length > 0) setClosing(new Map(closing).set(toggled.dir, kept));- }- }-- useEffect(() => {- prevRowsRef.current = rows;- }, [rows]);-- const dropClosing = (dir: string): void => {- setClosing((prev) => {- if (!prev.has(dir)) return prev;- const next = new Map(prev);- next.delete(dir);- return next;- });- };-- useEffect(() => {- if (closing.size === 0) return;- const timers = [...closing.keys()].map((dir) =>- setTimeout(() => dropClosing(dir), CLOSE_FALLBACK_MS),- );- return () => {- for (const timer of timers) clearTimeout(timer);- };- }, [closing]);-- const rowElement = (path: string): HTMLElement | null =>- containerRef.current?.querySelector<HTMLElement>(`[data-tree-path="${CSS.escape(path)}"]`) ??- null;-- useEffect(() => {- if (scrollTo === null) return;- if (scrollTo.path === "") containerRef.current?.scrollTo({ top: 0 });- else rowElement(scrollTo.path)?.scrollIntoView({ block: "nearest" });- }, [scrollTo]);-- const activate = (row: TreeRow): void => {- setFocused(row.path);- if (row.kind === "dir") onToggleDir(row.path);- else onOpenFile(row.path);- };-- const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>): void => {- if (e.key === "Enter" || e.key === " ") {- const row = rows.find((r) => r.path === focused);- if (row === undefined) return;- e.preventDefault();- activate(row);- return;- }- const step = treeKeyStep(rows, focused, e.key);- if (step === null) return;- e.preventDefault();- if (step.focus !== undefined) {- setFocused(step.focus);- rowElement(step.focus)?.focus();- }- if (step.expand !== undefined) onToggleDir(step.expand);- if (step.collapse !== undefined) onToggleDir(step.collapse);- };-- // The one row in the tab order. A focused row that scrolled out of the rows (its- // directory closed) hands the stop back to the selection or the first row.- const onScreen = (path: string | null): boolean =>- path !== null && rows.some((r) => r.path === path);- const tabStop = onScreen(focused)- ? focused- : onScreen(selectedPath)- ? selectedPath- : (rows[0]?.path ?? null);-- /** One row. A retained row is a leftover of a closing subtree: it draws, and does nothing else. */- const renderRow = (row: TreeRow, retained: boolean): ReactNode => {- const selected =- !retained &&- (row.path === selectedPath ||- (selectedPath === null && row.kind === "dir" && row.path === currentDir));- const dropHere = !retained && row.kind === "dir" && row.path === dropTargetDir;- const loading = row.kind === "dir" && loadingDirs.has(row.path);- const detail =- row.kind === "file"- ? `${row.path} · ${formatBytes(row.sizeBytes)} · ${formatDateTime(row.mtime)}`- : row.path;- return (- <div- key={row.path}- role="treeitem"- tabIndex={retained || row.path !== tabStop ? -1 : 0}- aria-level={row.depth + 1}- aria-posinset={row.posInSet}- aria-setsize={row.setSize}- aria-selected={selected}- {...(row.kind === "dir" ? { "aria-expanded": row.expanded } : {})}- aria-busy={loading || undefined}- // A retained row carries no path: rowElement() and the drop hit test both resolve a- // row by this attribute, and neither may land on one that is on its way out.- {...(retained ? {} : { "data-tree-path": row.path, "data-tree-kind": row.kind })}- title={detail}- {...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}- style={{ paddingLeft: 6 + row.depth * INDENT_PX }}- className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${- dropHere- ? "bg-sky-50 ring-2 ring-inset ring-sky-500/60 dark:bg-sky-950/40"- : selected- ? "bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100"- : "text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/50"- } ${loading ? "opacity-60" : ""}`}- >- <span className="flex w-3.5 shrink-0 justify-center text-gray-400" aria-hidden>- {row.kind === "dir" && <Chevron open={row.expanded} size={ICON_SIZE.chevronDense} />}- </span>- <GlyphIcon- d={row.kind === "dir" ? (row.expanded ? FOLDER_OPEN_ICON : FOLDER_ICON) : FILE_ICON}- size={ICON_SIZE.rowLead}- className="text-gray-400"- />- <span className="min-w-0 flex-1 truncate">{row.name}</span>- {row.kind === "file" && (+ rowTrailing={(row) =>+ row.kind === "file" && (<span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">{formatBytes(row.sizeBytes)}</span>- )}- </div>- );- };-- /** An open directory with nothing in it says so, in place of the children it lacks. */- const renderEmptyLine = (row: TreeRow): ReactNode => (- <p- key={`empty:${row.path}`}- className="py-1 pr-2 text-xs text-gray-400"- style={{ paddingLeft: 6 + (row.depth + 1) * INDENT_PX + 14 }}- >- {S.files.empty}- </p>- );-- /**- * The rows of `list` in `[start, end)`, with each open directory's descendants nested in a- * group below it. `retained` marks a closing subtree, which draws its own nested groups but- * animates nothing and takes no part in interaction.- */- const renderRange = (- list: readonly TreeRow[],- start: number,- end: number,- retained: boolean,- ): ReactNode[] => {- const out: ReactNode[] = [];- let i = start;- while (i < end) {- const row = list[i]!;- out.push(renderRow(row, retained));- if (row.kind !== "dir") {- i += 1;- continue;+ )}- const childrenEnd = subtreeEnd(list, i);- if (row.expanded && row.loaded) {- // The group mounts only once the listing is there, so a first open of an unloaded- // directory animates when its rows arrive rather than around an empty box.- const opening = !retained && toggled !== null && toggled.open && toggled.dir === row.path;- out.push(- <div- key={`group:${row.path}`}- role="group"- aria-label={row.name}- className={`tree-group ${opening ? "tree-group-open" : ""}`}- >- <div>- {row.empty ? renderEmptyLine(row) : renderRange(list, i + 1, childrenEnd, retained)}- </div>- </div>,- );- } else if (!retained && closing.has(row.path)) {- const kept = closing.get(row.path)!;- out.push(- <div- key={`closing:${row.path}`}- role="group"- aria-hidden- inert- className="tree-group tree-group-close"- onAnimationEnd={(e) => {- if (e.target === e.currentTarget) dropClosing(row.path);- }}- >- <div>{renderRange(kept, 0, kept.length, true)}</div>- </div>,- );- }- i = childrenEnd;- }- return out;- };-- return (- <div- ref={containerRef}- role="tree"- aria-label={S.files.treeLabel}- onKeyDown={onKeyDown}- className="min-h-0 flex-1 overflow-auto py-1"+ emptyLabel={S.files.empty}+ className="min-h-0 flex-1 overflow-auto"+ onToggleDir={onToggleDir}+ onOpenFile={onOpenFile}>- {rows.length === 0 ? (- filtering ? (- <p className="px-3 py-2 text-sm text-gray-400">{S.files.searchNoMatch}</p>- ) : rootEmpty ? (- <p className="px-3 py-2 text-sm text-gray-400">{S.files.empty}</p>- ) : null- ) : (- // `role="group"` is the tree pattern's own container for one level, so the rows inside- // one are still `treeitem`s of this tree and keep stating their own aria-level,- // aria-posinset and aria-setsize.- renderRange(rows, 0, rows.length, false)- )}- </div>+ {filtering ? (+ <p className="px-3 py-2 text-sm text-gray-400">{S.files.searchNoMatch}</p>+ ) : rootEmpty ? (+ <p className="px-3 py-2 text-sm text-gray-400">{S.files.empty}</p>+ ) : null}+ </FileTree>);}diff --git a/packages/web/src/features/plugins/plugin-detail.tsx b/packages/web/src/features/plugins/plugin-detail.tsxindex 7fcdc07d..4a1297d6 100644--- a/packages/web/src/features/plugins/plugin-detail.tsx+++ b/packages/web/src/features/plugins/plugin-detail.tsx@@ -1,17 +1,20 @@/*** Plugin detail Modal — opened by clicking a library card (the model library's card-detail* pattern): the plugin's icon, full description, metadata line and hook points, then a file- * browser over everything it ships, in the benchmark case browser's shape — a tree on the left- * (one collapsible group per skill and one for the hook package, any number open at once) and- * a preview on the right. The header and the tree never leave: opening a file fills the- * preview pane instead of replacing the view, so the summary and the other files stay in sight- * while reading. The files arrive in one request (GET /api/plugins/:plugin/files) when the- * Modal opens; a markdown file renders through the chat markdown component with its- * frontmatter stripped, anything else as a code block.+ * browser over everything it ships — the shared `FileTree` on the left (one directory per+ * skill and one for the hook package, any number open at once) and a preview on the right.+ * The header and the tree never leave: opening a file fills the preview pane instead of+ * replacing the view, so the summary and the other files stay in sight while reading. The+ * files arrive in one request (GET /api/plugins/:plugin/files) when the Modal opens; a+ * markdown file renders through the chat markdown component with its frontmatter stripped,+ * anything else as a code block.*/import { useEffect, useState } from "react";import { Modal } from "../../components/ui/modal";import { Badge } from "../../components/ui/badge";+import { FileTree } from "../../components/ui/file-tree";+import type { TreeToggle } from "../../components/ui/file-tree";+import type { FileTreeRow } from "../../lib/file-tree";import { PLUGIN_ICON } from "../../components/ui/icons";import { SkeletonList } from "../../components/ui/skeleton";import { S } from "../../lib/strings";@@ -97,6 +100,68 @@ export function groupPluginFiles(return groups;}+/** A directory of the tree while it is being built: the files directly in it, and what nests under it. */+interface TreeNode {+ path: string;+ name: string;+ kind: "dir" | "file";+ children: TreeNode[];+}++/**+ * The tree's rows for `groups`: each group is a directory row holding its own files, and a+ * file's remaining path segments nest under it — a skill's `reference/` is a directory of its+ * own rather than a slash inside a name. Order is the group's (SKILL.md leads, the rest by+ * path), with a directory appearing where its first file does. A collapsed directory+ * contributes its row and no children.+ */+export function pluginTreeRows(+ groups: readonly FileGroup[],+ collapsed: ReadonlySet<string>,+): FileTreeRow[] {+ const roots: TreeNode[] = [];+ for (const group of groups) {+ const root: TreeNode = { path: group.id, name: group.label, kind: "dir", children: [] };+ roots.push(root);+ for (const path of group.paths) {+ const segments = path.slice(group.id.length + 1).split("/");+ let node = root;+ for (const [index, segment] of segments.entries()) {+ const childPath = `${node.path}/${segment}`;+ const leaf = index === segments.length - 1;+ let child = node.children.find((c) => c.path === childPath);+ if (child === undefined) {+ child = { path: childPath, name: segment, kind: leaf ? "file" : "dir", children: [] };+ node.children.push(child);+ }+ node = child;+ }+ }+ }++ const rows: FileTreeRow[] = [];+ const walk = (nodes: readonly TreeNode[], depth: number): void => {+ for (const [index, node] of nodes.entries()) {+ const expanded = node.kind === "dir" && !collapsed.has(node.path);+ rows.push({+ path: node.path,+ name: node.name,+ kind: node.kind,+ depth,+ posInSet: index + 1,+ setSize: nodes.length,+ expanded,+ // Nothing here is fetched per directory: the whole listing arrived in one response.+ loaded: true,+ empty: node.kind === "dir" && node.children.length === 0,+ });+ if (expanded) walk(node.children, depth + 1);+ }+ };+ walk(roots, 0);+ return rows;+}+export function PluginDetailModal({plugin,meta,@@ -110,9 +175,11 @@ export function PluginDetailModal({const { locale } = useLocale();const [files, setFiles] = useState<Record<string, string> | null>(null);const [error, setError] = useState<string | null>(null);- /** Collapsed groups: every group starts open, so the whole plugin is in view at once. */- const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ /** Collapsed directories: every one starts open, so the whole plugin is in view at once. */+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());const [selected, setSelected] = useState<string | null>(null);+ /** The directory whose subtree the tree should animate — the one just clicked. */+ const [toggled, setToggled] = useState<TreeToggle | null>(null);useEffect(() => {let cancelled = false;@@ -137,18 +204,23 @@ export function PluginDetailModal({plugin.skills.map((s) => s.name),S.plugins.detailHooks,);+ const rows = pluginTreeRows(groups, collapsed);// The first file of the first group opens on arrival (the benchmark browser's readme// auto-preview), so the pane is never empty while there is something to read.const current = selected ?? groups[0]?.paths[0] ?? null;const text = current !== null && files !== null ? files[current] : undefined;- const toggleGroup = (id: string) =>+ const toggleDir = (dir: string): void => {+ const open = collapsed.has(dir);+ // The serial makes toggling the same directory again a new event for the tree to animate.+ setToggled((last) => ({ dir, open, serial: (last?.serial ?? 0) + 1 }));setCollapsed((prev) => {const next = new Set(prev);- if (next.has(id)) next.delete(id);- else next.add(id);+ if (open) next.delete(dir);+ else next.add(dir);return next;});+ };return (<Modal open title={plugin.name} onClose={onClose} widthClass="sm:max-w-4xl">@@ -184,50 +256,19 @@ export function PluginDetailModal({<div className="max-h-40 overflow-y-auto md:max-h-[50vh]">{error && <p className="px-3 py-2 text-xs text-red-500">{error}</p>}{files === null && !error && <SkeletonList rows={3} />}- {groups.map((group) => {- const open = !collapsed.has(group.id);- return (- <div- key={group.id}- className="border-b border-gray-200 last:border-b-0 dark:border-gray-800"- >- <button- type="button"- aria-expanded={open}- onClick={() => toggleGroup(group.id)}- className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-800/60"- >- <span className="text-xs text-gray-400">{open ? "▾" : "▸"}</span>- <span className="min-w-0 flex-1 truncate font-mono text-xs font-semibold">- {group.label}- </span>- </button>- {open &&- group.paths.map((path) => {- const active = path === current;- return (- <button- key={path}- type="button"- aria-current={active ? "true" : undefined}- onClick={() => setSelected(path)}- className={`flex w-full items-center gap-2 border-t border-gray-100 px-6 py-1.5 text-left text-xs hover:bg-gray-100 dark:border-gray-800/70 dark:hover:bg-gray-800/60 ${- active- ? "bg-gray-100 font-medium text-gray-900 dark:bg-gray-800/60 dark:text-gray-100"- : "text-gray-600 dark:text-gray-400"- }`}- >- <span className="text-gray-400">·</span>- {/* The path inside its group: SKILL.md, reference/x.md, stop.mjs. */}- <span className="min-w-0 flex-1 truncate">- {path.slice(group.id.length + 1)}- </span>- </button>- );- })}- </div>- );- })}+ {/* A `tree` with no `treeitem` in it is not one: while the listing is in flight, or+ when it failed or held nothing, the aside carries the skeleton or the error and+ no tree at all. */}+ {rows.length > 0 && (+ <FileTree+ rows={rows}+ label={S.files.treeLabel}+ selectedPath={current}+ toggled={toggled}+ onToggleDir={toggleDir}+ onOpenFile={setSelected}+ />+ )}</div></aside>diff --git a/packages/web/src/lib/file-tree.ts b/packages/web/src/lib/file-tree.tsnew file mode 100644index 00000000..57ac9ad0--- /dev/null+++ b/packages/web/src/lib/file-tree.ts@@ -0,0 +1,97 @@+/**+ * The file tree's DOM-free logic, shared by every browser that draws one row per entry: the+ * shape of a row, where a row's subtree ends in the flat row list, and the keyboard step of+ * the WAI-ARIA tree pattern.+ *+ * How the rows are produced is the caller's business and deliberately not modelled here — the+ * Workspace panel lists one directory per level as it is opened, the plugin browser groups a+ * flat listing it already holds — so a row states everything the tree needs to draw it.+ */++/** One rendered tree row: an entry, where it sits, and a directory's open/loaded state. */+export interface FileTreeRow {+ path: string;+ name: string;+ kind: "dir" | "file";+ /** Nesting depth; a root-level entry is 0. */+ depth: number;+ /** 1-based position among its own directory's entries, and how many there are: the row list+ * is flat, so each row has to state its own set rather than infer it from its container. */+ posInSet: number;+ setSize: number;+ /** Directory rows: whether it is open. */+ expanded: boolean;+ /** Directory rows: whether its children are on hand (a lazily listed directory is not, while it loads). */+ loaded: boolean;+ /** Directory rows: loaded and holding nothing. */+ empty: boolean;+}++/**+ * Where the row at `i` stops owning what follows it: the index of the first later row at its+ * own depth or shallower, or the end of the list. The rows in `(i, end)` are its descendants,+ * which is what lets the flat row list be drawn as nested containers.+ */+export function subtreeEnd(rows: readonly FileTreeRow[], i: number): number {+ const depth = rows[i]?.depth;+ if (depth === undefined) return rows.length;+ for (let j = i + 1; j < rows.length; j += 1) if (rows[j]!.depth <= depth) return j;+ return rows.length;+}++/** What one navigation key does to the tree: move focus, open a directory, or close one. */+export interface TreeKeyAction {+ focus?: string;+ expand?: string;+ collapse?: string;+}++/**+ * The keyboard step for `key` with `focused` as the current row (null: none yet), or null+ * when the key is not a tree key or has nothing to do.+ * - ArrowDown / ArrowUp move within the rows on screen (clamped at the ends); with no+ * focused row either lands on the first row.+ * - ArrowRight opens a closed directory, steps into the first child of an open one.+ * - ArrowLeft closes an open directory, otherwise steps out to the parent row.+ * - Home / End jump to the first / last row.+ */+export function treeKeyStep(+ rows: readonly FileTreeRow[],+ focused: string | null,+ key: string,+): TreeKeyAction | null {+ if (rows.length === 0) return null;+ const first = rows[0]!;+ const index = focused === null ? -1 : rows.findIndex((r) => r.path === focused);+ const row = index >= 0 ? rows[index]! : null;+ switch (key) {+ case "ArrowDown":+ return { focus: rows[Math.min(rows.length - 1, index + 1)]!.path };+ case "ArrowUp":+ return { focus: rows[Math.max(0, index - 1)]!.path };+ case "Home":+ return { focus: first.path };+ case "End":+ return { focus: rows[rows.length - 1]!.path };+ case "ArrowRight": {+ if (row === null) return { focus: first.path };+ if (row.kind !== "dir") return null;+ if (!row.expanded) return { expand: row.path };+ const next = rows[index + 1];+ return next !== undefined && next.depth > row.depth ? { focus: next.path } : null;+ }+ case "ArrowLeft": {+ if (row === null) return null;+ if (row.kind === "dir" && row.expanded) return { collapse: row.path };+ // The parent is the nearest earlier row above this one's depth. Derived from the rows+ // rather than from the path, because a row's path need not name a row: the plugin+ // browser's top-level rows are `skills/<name>`, and there is no `skills` row to step to.+ for (let i = index - 1; i >= 0; i -= 1) {+ if (rows[i]!.depth < row.depth) return { focus: rows[i]!.path };+ }+ return null;+ }+ default:+ return null;+ }+}diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.tsindex e7bda4dc..1cff6da4 100644--- a/packages/web/src/lib/workspace-tree.ts+++ b/packages/web/src/lib/workspace-tree.ts@@ -2,9 +2,8 @@* Workspace files panel logic, kept DOM-free so it can be unit-tested:* - the directory tree's shape — listings fetched lazily per directory and keyed by its* Workspace-relative path ("" is the root), the set of open directories, and the flat- * row list the tree renders from the two;- * - the keyboard step over those rows (the WAI-ARIA tree pattern: up/down move, right- * opens a directory or steps into it, left closes it or steps out to its parent);+ * row list the tree renders from the two (the row's own shape and the keyboard step over+ * it are shared with the app's other file trees, in lib/file-tree.ts);* - the search box's filter over the rows that are loaded;* - which directory a dropped batch lands in;* - when the panel is too narrow for a tree beside a preview, and how wide the tree pane@@ -17,6 +16,7 @@*/import type { WorkspaceFileEntry } from "@prismshadow/penguin-server/api";import { joinWorkspacePath } from "./file-path";+import type { FileTreeRow } from "./file-tree";// ------------------------------------------------------------------------------- layout@@ -143,23 +143,8 @@ export function withExpanded(return next;}-/** One rendered tree row: an entry plus where it sits and, for a directory, its open/loaded state. */-export interface TreeRow {- path: string;- name: string;- kind: "dir" | "file";- /** Nesting depth; a root-level entry is 0. */- depth: number;- /** 1-based position among its own directory's entries, and how many there are: the row list- * is flat, so each row has to state its own set rather than infer it from its container. */- posInSet: number;- setSize: number;- /** Directory rows: whether it is open. */- expanded: boolean;- /** Directory rows: whether its listing has arrived (an open, unloaded directory is being fetched). */- loaded: boolean;- /** Directory rows: loaded and holding nothing. */- empty: boolean;+/** One rendered tree row: a shared tree row plus what the Workspace shows beside a file's name. */+export interface TreeRow extends FileTreeRow {sizeBytes: number;mtime: string;}@@ -198,18 +183,6 @@ export function flattenTree(listings: Listings, expanded: ReadonlySet<string>):return rows;}-/**- * Where the row at `i` stops owning what follows it: the index of the first later row at its- * own depth or shallower, or the end of the list. The rows in `(i, end)` are its descendants,- * which is what lets the flat row list be drawn as nested containers.- */-export function subtreeEnd(rows: readonly TreeRow[], i: number): number {- const depth = rows[i]?.depth;- if (depth === undefined) return rows.length;- for (let j = i + 1; j < rows.length; j += 1) if (rows[j]!.depth <= depth) return j;- return rows.length;-}-/*** The rows left by the search box, or all of them for an empty query. Matching is a* case-insensitive substring of the entry's own name; the panel hands in rows walked with@@ -237,57 +210,6 @@ export function filterTreeRows(rows: readonly TreeRow[], query: string): TreeRow);}-/** What one navigation key does to the tree: move focus, open a directory, or close one. */-export interface TreeKeyAction {- focus?: string;- expand?: string;- collapse?: string;-}--/**- * The keyboard step for `key` with `focused` as the current row (null: none yet), or null- * when the key is not a tree key or has nothing to do.- * - ArrowDown / ArrowUp move within the rows on screen (clamped at the ends); with no- * focused row either lands on the first row.- * - ArrowRight opens a closed directory, steps into the first child of an open one.- * - ArrowLeft closes an open directory, otherwise steps out to the parent row.- * - Home / End jump to the first / last row.- */-export function treeKeyStep(- rows: readonly TreeRow[],- focused: string | null,- key: string,-): TreeKeyAction | null {- if (rows.length === 0) return null;- const first = rows[0]!;- const index = focused === null ? -1 : rows.findIndex((r) => r.path === focused);- const row = index >= 0 ? rows[index]! : null;- switch (key) {- case "ArrowDown":- return { focus: rows[Math.min(rows.length - 1, index + 1)]!.path };- case "ArrowUp":- return { focus: rows[Math.max(0, index - 1)]!.path };- case "Home":- return { focus: first.path };- case "End":- return { focus: rows[rows.length - 1]!.path };- case "ArrowRight": {- if (row === null) return { focus: first.path };- if (row.kind !== "dir") return null;- if (!row.expanded) return { expand: row.path };- const next = rows[index + 1];- return next !== undefined && next.depth > row.depth ? { focus: next.path } : null;- }- case "ArrowLeft": {- if (row === null) return null;- if (row.kind === "dir" && row.expanded) return { collapse: row.path };- return row.path.includes("/") ? { focus: parentDir(row.path) } : null;- }- default:- return null;- }-}-// -------------------------------------------------------------------------- breadcrumbs/** The single item a run of dropped leading segments collapses into. */diff --git a/packages/web/test/file-tree.test.ts b/packages/web/test/file-tree.test.tsnew file mode 100644index 00000000..98ad1447--- /dev/null+++ b/packages/web/test/file-tree.test.ts@@ -0,0 +1,120 @@+/**+ * The shared file tree's DOM-free logic (lib/file-tree.ts): where a row's subtree ends in the+ * flat row list, and the keyboard step over those rows — the WAI-ARIA tree pattern's up/down+ * move, right to open a directory or step into it, left to close it or step out to its parent.+ */+import { describe, expect, it } from "vitest";+import { subtreeEnd, treeKeyStep } from "../src/lib/file-tree";+import type { FileTreeRow } from "../src/lib/file-tree";++const baseName = (path: string): string => path.slice(path.lastIndexOf("/") + 1);++const dirRow = (+ path: string,+ depth: number,+ posInSet: number,+ setSize: number,+ over: Partial<FileTreeRow> = {},+): FileTreeRow => ({+ path,+ name: baseName(path),+ kind: "dir",+ depth,+ posInSet,+ setSize,+ expanded: true,+ loaded: true,+ empty: false,+ ...over,+});++const fileRow = (path: string, depth: number, posInSet: number, setSize: number): FileTreeRow => ({+ path,+ name: baseName(path),+ kind: "file",+ depth,+ posInSet,+ setSize,+ expanded: false,+ loaded: true,+ empty: false,+});++/** root: a/ (b/ empty, y.md), x.txt — with both directories open. */+const ROWS: FileTreeRow[] = [+ dirRow("a", 0, 1, 2),+ dirRow("a/b", 1, 1, 2, { empty: true }),+ fileRow("a/y.md", 1, 2, 2),+ fileRow("x.txt", 0, 2, 2),+];++/** The same tree with nothing open: an unopened directory has no listing yet. */+const CLOSED: FileTreeRow[] = [+ dirRow("a", 0, 1, 2, { expanded: false, loaded: false }),+ fileRow("x.txt", 0, 2, 2),+];++describe("subtreeEnd", () => {+ it("ends a row's subtree at the next row no deeper than it", () => {+ // "a" owns rows 1..2, the nested "a/b" owns nothing, and "x.txt" after them is where both stop.+ expect(subtreeEnd(ROWS, 0)).toBe(3);+ expect(subtreeEnd(ROWS, 1)).toBe(2);+ expect(subtreeEnd(ROWS, 3)).toBe(4);+ });+});++describe("treeKeyStep", () => {+ it("moves down and up within the rows on screen, clamped at the ends", () => {+ expect(treeKeyStep(ROWS, null, "ArrowDown")).toEqual({ focus: "a" });+ expect(treeKeyStep(ROWS, "a", "ArrowDown")).toEqual({ focus: "a/b" });+ expect(treeKeyStep(ROWS, "x.txt", "ArrowDown")).toEqual({ focus: "x.txt" });+ expect(treeKeyStep(ROWS, "a/b", "ArrowUp")).toEqual({ focus: "a" });+ expect(treeKeyStep(ROWS, "a", "ArrowUp")).toEqual({ focus: "a" });+ expect(treeKeyStep(ROWS, "a/b", "Home")).toEqual({ focus: "a" });+ expect(treeKeyStep(ROWS, "a", "End")).toEqual({ focus: "x.txt" });+ });++ it("ArrowRight opens a closed directory, steps into an open one, and does nothing on a file or an empty directory", () => {+ expect(treeKeyStep(CLOSED, "a", "ArrowRight")).toEqual({ expand: "a" });+ expect(treeKeyStep(ROWS, "a", "ArrowRight")).toEqual({ focus: "a/b" });+ expect(treeKeyStep(ROWS, "a/b", "ArrowRight")).toBeNull();+ expect(treeKeyStep(ROWS, "a/y.md", "ArrowRight")).toBeNull();+ expect(treeKeyStep(ROWS, null, "ArrowRight")).toEqual({ focus: "a" });+ });++ it("ArrowLeft closes an open directory, otherwise steps out to the parent row", () => {+ expect(treeKeyStep(ROWS, "a/b", "ArrowLeft")).toEqual({ collapse: "a/b" });+ expect(treeKeyStep(ROWS, "a/y.md", "ArrowLeft")).toEqual({ focus: "a" });+ // A root-level file has no parent row to step out to.+ expect(treeKeyStep(ROWS, "x.txt", "ArrowLeft")).toBeNull();+ expect(treeKeyStep(ROWS, null, "ArrowLeft")).toBeNull();+ });++ it("ArrowLeft steps to the row above, never to a path that is not a row", () => {+ // The plugin browser's top-level rows are whole paths ("skills/<name>"): there is no+ // "skills" row to step out to, so a parent taken from the path would focus nothing.+ const rows = [+ dirRow("skills/humanizer", 0, 1, 1),+ fileRow("skills/humanizer/SKILL.md", 1, 1, 2),+ dirRow("skills/humanizer/reference", 1, 2, 2, { expanded: false }),+ ];+ expect(treeKeyStep(rows, "skills/humanizer/SKILL.md", "ArrowLeft")).toEqual({+ focus: "skills/humanizer",+ });+ expect(treeKeyStep(rows, "skills/humanizer", "ArrowLeft")).toEqual({+ collapse: "skills/humanizer",+ });+ expect(+ treeKeyStep(+ [dirRow("skills/humanizer", 0, 1, 1, { expanded: false })],+ "skills/humanizer",+ "ArrowLeft",+ ),+ ).toBeNull();+ });++ it("ignores keys that are not tree keys, and does nothing with no rows", () => {+ expect(treeKeyStep(ROWS, "a", "Enter")).toBeNull();+ expect(treeKeyStep([], null, "ArrowDown")).toBeNull();+ });+});diff --git a/packages/web/test/plugin-files.test.ts b/packages/web/test/plugin-files.test.tsindex d3e50127..50ccf5b1 100644--- a/packages/web/test/plugin-files.test.ts+++ b/packages/web/test/plugin-files.test.ts@@ -2,10 +2,10 @@* The plugin detail browser's tree, derived from the files endpoint's keys: one group per* skill in the plugin's own order with SKILL.md leading, hook scripts in one trailing group,* and a skill the listing did not name (a stale listing against a newer library) still gets a- * group rather than vanishing.+ * group rather than vanishing; then the rows the shared file tree draws from those groups.*/import { describe, expect, it } from "vitest";-import { groupPluginFiles } from "../src/features/plugins/plugin-detail";+import { groupPluginFiles, pluginTreeRows } from "../src/features/plugins/plugin-detail";describe("groupPluginFiles", () => {it("groups skills in plugin order, SKILL.md first, then the hook scripts", () => {@@ -44,3 +44,48 @@ describe("groupPluginFiles", () => {expect(groups.map((g) => g.id)).toEqual(["skills/known", "skills/extra"]);});});++describe("pluginTreeRows", () => {+ it("nests a file's own path segments under its group and skips a collapsed directory's children", () => {+ const groups = groupPluginFiles(+ ["skills/humanizer/SKILL.md", "skills/humanizer/reference/tells.md", "hooks/stop.mjs"],+ ["humanizer"],+ "Hooks",+ );+ expect(+ pluginTreeRows(groups, new Set()).map((r) => [r.path, r.kind, r.depth, r.expanded]),+ ).toEqual([+ ["skills/humanizer", "dir", 0, true],+ ["skills/humanizer/SKILL.md", "file", 1, false],+ ["skills/humanizer/reference", "dir", 1, true],+ ["skills/humanizer/reference/tells.md", "file", 2, false],+ ["hooks", "dir", 0, true],+ ["hooks/stop.mjs", "file", 1, false],+ ]);+ expect(+ pluginTreeRows(groups, new Set(["skills/humanizer/reference"])).map((r) => r.path),+ ).toEqual([+ "skills/humanizer",+ "skills/humanizer/SKILL.md",+ "skills/humanizer/reference",+ "hooks",+ "hooks/stop.mjs",+ ]);+ });++ it("states each row's own position among its siblings, for the flat list to announce", () => {+ const groups = groupPluginFiles(+ ["skills/a/SKILL.md", "skills/b/SKILL.md", "hooks/stop.mjs"],+ ["a", "b"],+ "Hooks",+ );+ expect(pluginTreeRows(groups, new Set()).map((r) => `${r.posInSet}/${r.setSize}`)).toEqual([+ "1/3",+ "1/1",+ "2/3",+ "1/1",+ "3/3",+ "1/1",+ ]);+ });+});diff --git a/packages/web/test/workspace-tree.test.ts b/packages/web/test/workspace-tree.test.tsindex c947ee9d..85de87d0 100644--- a/packages/web/test/workspace-tree.test.ts+++ b/packages/web/test/workspace-tree.test.ts@@ -1,7 +1,7 @@/*** Files panel logic (lib/workspace-tree.ts): the tree's rows from lazily loaded listings,- * the search box's filter over them, the keyboard step over those rows, where a drop lands,- * the narrow-layout decision and the tree pane's width bounds, how much of a path the+ * the search box's filter over them, where a drop lands, the narrow-layout+ * decision and the tree pane's width bounds, how much of a path the* toolbar can show, which files count as text (by name, or by their bytes when the name says* nothing), the preferences' tolerant parses, and when leaving the editor has to ask.*/@@ -33,8 +33,6 @@ import {readTreeVisible,readTreeWidth,sortEntries,- subtreeEnd,- treeKeyStep,upsertEntry,utf8Complete,visibleCrumbSegments,@@ -143,54 +141,6 @@ describe("flattenTree", () => {});});-describe("subtreeEnd", () => {- it("ends a row's subtree at the next row no deeper than it", () => {- // root: a/ (b/ empty, y.md), x.txt — "a" owns rows 1..2, the nested "a/b" owns nothing,- // and "x.txt" after them is where both stop.- const rows = flattenTree(LISTINGS, new Set(["a", "a/b"]));- expect(rows.map((r) => r.path)).toEqual(["a", "a/b", "a/y.md", "x.txt"]);- expect(subtreeEnd(rows, 0)).toBe(3);- expect(subtreeEnd(rows, 1)).toBe(2);- expect(subtreeEnd(rows, 3)).toBe(4);- });-});--describe("treeKeyStep", () => {- const rows = flattenTree(LISTINGS, new Set(["a", "a/b"]));-- it("moves down and up within the rows on screen, clamped at the ends", () => {- expect(treeKeyStep(rows, null, "ArrowDown")).toEqual({ focus: "a" });- expect(treeKeyStep(rows, "a", "ArrowDown")).toEqual({ focus: "a/b" });- expect(treeKeyStep(rows, "x.txt", "ArrowDown")).toEqual({ focus: "x.txt" });- expect(treeKeyStep(rows, "a/b", "ArrowUp")).toEqual({ focus: "a" });- expect(treeKeyStep(rows, "a", "ArrowUp")).toEqual({ focus: "a" });- expect(treeKeyStep(rows, "a/b", "Home")).toEqual({ focus: "a" });- expect(treeKeyStep(rows, "a", "End")).toEqual({ focus: "x.txt" });- });-- it("ArrowRight opens a closed directory, steps into an open one, and does nothing on a file or an empty directory", () => {- const closed = flattenTree(LISTINGS, new Set());- expect(treeKeyStep(closed, "a", "ArrowRight")).toEqual({ expand: "a" });- expect(treeKeyStep(rows, "a", "ArrowRight")).toEqual({ focus: "a/b" });- expect(treeKeyStep(rows, "a/b", "ArrowRight")).toBeNull();- expect(treeKeyStep(rows, "a/y.md", "ArrowRight")).toBeNull();- expect(treeKeyStep(rows, null, "ArrowRight")).toEqual({ focus: "a" });- });-- it("ArrowLeft closes an open directory, otherwise steps out to the parent row", () => {- expect(treeKeyStep(rows, "a/b", "ArrowLeft")).toEqual({ collapse: "a/b" });- expect(treeKeyStep(rows, "a/y.md", "ArrowLeft")).toEqual({ focus: "a" });- // A root-level file has no parent row to step out to.- expect(treeKeyStep(rows, "x.txt", "ArrowLeft")).toBeNull();- expect(treeKeyStep(rows, null, "ArrowLeft")).toBeNull();- });-- it("ignores keys that are not tree keys, and does nothing with no rows", () => {- expect(treeKeyStep(rows, "a", "Enter")).toBeNull();- expect(treeKeyStep([], null, "ArrowDown")).toBeNull();- });-});-describe("dropTargetDir", () => {it("lands on a folder row, in a file row's directory, or in the current directory", () => {expect(dropTargetDir({ kind: "dir", path: "docs/api" }, "src")).toBe("docs/api");