feat: use pierre trees for file explorer

This commit is contained in:
Yujong Lee 2026-09-10 15:04:40 -07:00
parent e9227d0f8c
commit de0834b590
16 changed files with 570 additions and 98 deletions

View file

@ -0,0 +1,39 @@
---
name: trees
description:
Use when an app uses @pierre/trees to render or control a file tree, including
React, vanilla JavaScript, SSR, web components, selection, search, rename,
drag and drop, icons, git status, and themes.
---
# `@pierre/trees`
Use `@pierre/trees` for an interactive file tree. Public state and callbacks use
path strings.
## Install
```bash
pnpm add @pierre/trees
```
Install `react` and `react-dom` when the app uses the React entry.
## Select an API reference
| Entry | Reference |
| ------------------------------ | ------------------------------------------------------ |
| `@pierre/trees` | [Core API](references/api-core.md) |
| `@pierre/trees/react` | [React API](references/api-react.md) |
| `@pierre/trees/ssr` | [SSR API](references/api-ssr.md) |
| `@pierre/trees/web-components` | [Web components API](references/api-web-components.md) |
## Select a recipe
| Task | Recipe |
| ------------------------------------------------------- | ------------------------------------------------------ |
| Render and update a tree in React | [Use React](references/recipe-react.md) |
| Render and update a tree without React | [Use vanilla JavaScript](references/recipe-vanilla.md) |
| Preload a tree on the server | [Use SSR](references/recipe-ssr.md) |
| Apply a resolved Shiki or VS Code theme | [Apply a theme](references/recipe-theme.md) |
| Configure search, rename, drag and drop, and git status | [Add interactions](references/recipe-interactions.md) |

View file

@ -0,0 +1,173 @@
# Core API
This reference lists every export from `@pierre/trees` and every public
`FileTree` member.
## Contents
- [Runtime values](#runtime-values)
- [`FileTree` members](#filetree-members)
- [Configuration and state types](#configuration-and-state-types)
- [Mutation types](#mutation-types)
- [Interaction types](#interaction-types)
- [Presentation types](#presentation-types)
- [Constants](#constants)
## Runtime values
| Export | Kind | Purpose |
| ------------------------------- | -------- | ----------------------------------------------------------------- |
| `FileTree` | Class | Owns the tree model, renders it, and exposes path-based controls. |
| `prepareFileTreeInput` | Function | Prepares and optionally sorts a path list for reuse. |
| `preparePresortedFileTreeInput` | Function | Prepares a path list that already has final order. |
| `preloadFileTree` | Function | Creates server-rendered tree markup and hydration data. |
| `serializeFileTreeSsrPayload` | Function | Joins an SSR payload into one host markup string. |
| `themeToTreeStyles` | Function | Maps a resolved theme to tree host CSS properties. |
| `getBuiltInSpriteSheet` | Function | Gets the SVG sprite for a built-in icon set. |
| `createFileTreeIconResolver` | Function | Creates an icon resolver from an icon configuration. |
## `FileTree` members
| Member | Purpose |
| -------------------------------- | ----------------------------------------------------------- |
| `new FileTree(options)` | Creates a model from paths or prepared input. |
| `FileTree.LoadedCustomComponent` | Reports whether the file-tree custom element module loaded. |
| `render(props)` | Mounts the tree into a wrapper or host element. |
| `hydrate(props)` | Attaches the model to preloaded host markup. |
| `unmount()` | Removes the mounted view and keeps the model. |
| `cleanUp()` | Removes the view and destroys model resources. |
| `getFileTreeContainer()` | Gets the mounted host element. |
| `getItem(path)` | Gets a path handle or `null`. |
| `getFocusedItem()` | Gets the focused item handle or `null`. |
| `getFocusedPath()` | Gets the focused path or `null`. |
| `getSelectedPaths()` | Gets the selected paths. |
| `getComposition()` | Gets the current header and context-menu configuration. |
| `getItemHeight()` | Gets the resolved row height. |
| `getDensityFactor()` | Gets the resolved density factor. |
| `subscribe(listener)` | Subscribes to model changes. |
| `focusPath(path)` | Focuses a path. |
| `focusNearestPath(path)` | Focuses and returns the nearest available path. |
| `scrollToPath(path, options?)` | Scrolls a path into view. |
| `add(path)` | Adds one path. |
| `remove(path, options?)` | Removes one path. |
| `move(from, to, options?)` | Moves one path. |
| `batch(operations)` | Applies several path mutations together. |
| `resetPaths(paths, options?)` | Replaces the full path set. |
| `onMutation(type, handler)` | Subscribes to mutation events. |
| `setSearch(value)` | Sets or clears the search query. |
| `openSearch(initialValue?)` | Opens the search session. |
| `closeSearch()` | Closes the search session. |
| `isSearchOpen()` | Tests whether search is open. |
| `getSearchValue()` | Gets the search query. |
| `getSearchMatchingPaths()` | Gets paths that match the query. |
| `focusNextSearchMatch()` | Focuses the next search match. |
| `focusPreviousSearchMatch()` | Focuses the previous search match. |
| `startRenaming(path?, options?)` | Starts inline rename and reports whether it started. |
| `setGitStatus(status?)` | Replaces all git status entries. |
| `applyGitStatusPatch(patch)` | Applies a partial git status update. |
| `setIcons(icons?)` | Replaces the icon configuration. |
| `setComposition(composition?)` | Replaces header and context-menu configuration. |
## Configuration and state types
| Export | Purpose |
| -------------------------- | --------------------------------------------------------------- |
| `FileTreeOptions` | Defines input, behavior, rendering, and presentation options. |
| `FileTreePreparedInput` | Holds a reusable prepared path list. |
| `FileTreeInitialExpansion` | Selects closed, open, or depth-based initial expansion. |
| `FileTreeSortComparator` | Compares two path entries. |
| `FileTreeSortEntry` | Describes one path for a sort comparator. |
| `FileTreeRenderOptions` | Configures row height, row count, overscan, and sticky folders. |
| `FileTreeRenderProps` | Selects the wrapper or existing host for `render`. |
| `FileTreeHydrationProps` | Selects the host for `hydrate`. |
| `FileTreeVisibleRow` | Describes one visible tree row. |
| `FileTreeItemHandle` | Represents a file or directory item. |
| `FileTreeFileHandle` | Controls one file item. |
| `FileTreeDirectoryHandle` | Controls one directory item and its expansion. |
| `FileTreeListener` | Defines a model subscription callback. |
| `FileTreeSsrPayload` | Holds the host and shadow markup for server output. |
## Mutation types
| Export | Purpose |
| ----------------------------------- | -------------------------------------------------------------- |
| `FileTreeMutationHandle` | Defines the public path mutation methods. |
| `FileTreeBatchOperation` | Describes one add, remove, or move in a batch. |
| `FileTreeCollisionStrategy` | Selects error, replace, or skip behavior for a move collision. |
| `FileTreeMoveOptions` | Configures move collision behavior. |
| `FileTreeRemoveOptions` | Configures recursive removal. |
| `FileTreeResetOptions` | Configures a path reset and optional prepared input. |
| `FileTreeResetPreparedOptions` | Configures a reset that uses prepared input. |
| `FileTreeMutationEvent` | Represents any mutation event. |
| `FileTreeMutationSemanticEvent` | Represents an add, remove, move, or reset event. |
| `FileTreeMutationEventType` | Names a mutation operation. |
| `FileTreeMutationEventForType` | Selects the event shape for an operation name. |
| `FileTreeMutationEventInvalidation` | Describes the state invalidation from a mutation. |
| `FileTreeAddEvent` | Describes one add result. |
| `FileTreeRemoveEvent` | Describes one remove result. |
| `FileTreeMoveEvent` | Describes one move result. |
| `FileTreeResetEvent` | Describes one reset result. |
| `FileTreeBatchEvent` | Describes one batch result. |
## Interaction types
| Export | Purpose |
| --------------------------------- | -------------------------------------------------- |
| `FileTreeSelectionChangeListener` | Receives the selected path list. |
| `FileTreeSearchChangeListener` | Receives the current search query. |
| `FileTreeSearchSessionHandle` | Defines search session methods. |
| `FileTreeSearchMode` | Selects how nonmatching rows appear. |
| `FileTreeSearchBlurBehavior` | Selects search behavior after focus leaves. |
| `FileTreeScrollOffset` | Selects top, center, or nearest scroll alignment. |
| `FileTreeScrollToPathOptions` | Configures focus and alignment for `scrollToPath`. |
| `FileTreeDragAndDropConfig` | Configures drag rules and completion callbacks. |
| `FileTreeDropTarget` | Describes the current drop target. |
| `FileTreeDropContext` | Describes dragged paths and their target. |
| `FileTreeDropResult` | Describes the completed move or batch operation. |
| `FileTreeRenamingConfig` | Configures rename rules and callbacks. |
| `FileTreeRenamingItem` | Describes the item offered to a rename rule. |
| `FileTreeRenameEvent` | Describes a completed rename. |
## Presentation types
| Export | Purpose |
| ---------------------------------- | ----------------------------------------------------------- |
| `FileTreeCompositionOptions` | Configures header and context-menu composition. |
| `FileTreeHeaderCompositionOptions` | Supplies header HTML or a header renderer. |
| `ContextMenuItem` | Describes the file or directory for a context menu. |
| `ContextMenuOpenContext` | Supplies menu position, close, and focus controls. |
| `ContextMenuAnchorRect` | Describes the menu anchor rectangle. |
| `ContextMenuTriggerMode` | Selects right-click, button, or both triggers. |
| `ContextMenuButtonVisibility` | Selects when the row menu button appears. |
| `FileTreeRowDecoration` | Describes text or icon content in the decoration lane. |
| `FileTreeRowDecorationContext` | Supplies the item and visible row to a decoration renderer. |
| `FileTreeRowDecorationRenderer` | Produces one row decoration. |
| `GitStatus` | Names a supported git status. |
| `GitStatusEntry` | Assigns a git status to one path. |
| `FileTreeGitStatusPatch` | Adds, changes, or removes git status entries. |
| `FileTreeBuiltInIconSet` | Names a built-in icon set. |
| `FileTreeIconConfig` | Configures built-in and custom icon rules. |
| `FileTreeIcons` | Accepts an icon set name or icon configuration. |
| `RemappedIcon` | Names or defines a replacement SVG symbol. |
| `FileTreeDensity` | Accepts a density keyword or numeric factor. |
| `FileTreeDensityKeyword` | Names compact, default, or relaxed density. |
| `FileTreeDensityPreset` | Holds a density factor and row height. |
| `TreeThemeInput` | Defines the resolved theme accepted by `themeToTreeStyles`. |
| `TreeThemeStyles` | Maps tree CSS property names to values. |
## Constants
| Export | Purpose |
| ---------------------------------------------- | --------------------------------------------------------------- |
| `FILE_TREE_TAG_NAME` | Provides the `file-tree-container` element name. |
| `FILE_TREE_STYLE_ATTRIBUTE` | Provides the core style marker attribute. |
| `FILE_TREE_UNSAFE_CSS_ATTRIBUTE` | Provides the custom style marker attribute. |
| `FILE_TREE_SCROLLBAR_MEASURE_ATTRIBUTE` | Provides the scrollbar measurement attribute. |
| `FILE_TREE_SCROLLBAR_GUTTER_STYLE_ATTRIBUTE` | Provides the measured scrollbar style attribute. |
| `FILE_TREE_SCROLLBAR_GUTTER_MEASURED_PROPERTY` | Provides the measured scrollbar CSS property. |
| `FILE_TREE_DEFAULT_ITEM_HEIGHT` | Provides the default row height. |
| `FILE_TREE_DENSITY_PRESETS` | Maps each density keyword to its preset. |
| `FLATTENED_PREFIX` | Provides the identifier prefix for a flattened directory chain. |
| `HEADER_SLOT_NAME` | Provides the header slot name. |
| `CONTEXT_MENU_SLOT_NAME` | Provides the context-menu slot name. |
| `CONTEXT_MENU_TRIGGER_TYPE` | Provides the context-menu trigger type. |

View file

@ -0,0 +1,27 @@
# React API
This reference lists every export from `@pierre/trees/react`.
| Export | Kind | Purpose |
| -------------------------- | --------- | ---------------------------------------------------------------------- |
| `FileTree` | Component | Mounts a `FileTree` model in a React host element. |
| `FileTreeProps` | Type | Defines the model, header, context menu, preload data, and host props. |
| `FileTreePreloadedData` | Type | Selects the `id` and `shadowHtml` fields for hydration. |
| `useFileTree` | Hook | Creates one stable `FileTree` model. |
| `UseFileTreeResult` | Type | Holds the model returned by `useFileTree`. |
| `useFileTreeSelection` | Hook | Returns the selected path list and updates with the model. |
| `useFileTreeSearch` | Hook | Returns search state and search actions. |
| `FileTreeSearchState` | Type | Defines the search snapshot and actions. |
| `useFileTreeSelector` | Hook | Subscribes to a selected part of model state. |
| `FileTreeSelector` | Type | Selects a value from a model. |
| `FileTreeSelectorEquality` | Type | Compares two selected values. |
`FileTreeProps` extends React host attributes except `children`. Its specific
fields are:
| Field | Purpose |
| ------------------- | --------------------------------------------------- |
| `model` | Supplies the required `FileTree` model. |
| `header` | Supplies React content for the header slot. |
| `renderContextMenu` | Produces React content for the active context menu. |
| `preloadedData` | Supplies server markup for hydration. |

View file

@ -0,0 +1,12 @@
# SSR API
This reference lists every export from `@pierre/trees/ssr`.
| Export | Kind | Purpose |
| ----------------------------- | -------- | --------------------------------------------------------------- |
| `preloadFileTree` | Function | Renders a tree to a `FileTreeSsrPayload`. |
| `serializeFileTreeSsrPayload` | Function | Creates declarative or DOM-inserted host markup from a payload. |
| `FileTreeSsrPayload` | Type | Holds the host start, shadow HTML, host end, and stable ID. |
`preloadFileTree` and `serializeFileTreeSsrPayload` are also available from
`@pierre/trees`.

View file

@ -0,0 +1,11 @@
# Web components API
Import `@pierre/trees/web-components` to register the `file-tree-container`
custom element. The entry exports these APIs:
| Export | Kind | Purpose |
| --------------------------- | -------- | ------------------------------------------------------------------------- |
| `FileTreeContainerLoaded` | Value | Confirms that the registration module ran. |
| `adoptDeclarativeShadowDom` | Function | Copies a declarative template into an empty shadow root. |
| `ensureFileTreeStyles` | Function | Installs the core tree stylesheet in a shadow root. |
| `prepareFileTreeShadowRoot` | Function | Adopts server markup, installs styles, and measures the scrollbar gutter. |

View file

@ -0,0 +1,30 @@
# Recipe: add file tree interactions
Enable only the interactions that the product exposes:
```ts
const tree = new FileTree({
paths,
search: true,
renaming: {
onRename(event) {
renamePath(event.sourcePath, event.destinationPath);
},
},
dragAndDrop: {
canDrop({ target }) {
return target.kind === 'directory';
},
onDropComplete(event) {
saveMove(event);
},
},
gitStatus,
});
```
Use `openSearch()` to open search from an application command. Use
`startRenaming(path)` to start rename from a menu. Use `setGitStatus()` or
`applyGitStatusPatch()` after repository state changes.
Directory input paths end with `/`. File input paths do not end with `/`.

View file

@ -0,0 +1,22 @@
# Recipe: use a file tree in React
Create the model once and pass it to the component:
```tsx
'use client';
import { FileTree, useFileTree } from '@pierre/trees/react';
export function ProjectFiles({ paths }: { paths: readonly string[] }) {
const { model } = useFileTree({
paths,
initialExpansion: 'open',
search: true,
});
return <FileTree model={model} style={{ height: 320 }} />;
}
```
Call model methods for updates after model creation. For example, call
`model.resetPaths(paths)` after the source path list changes.

View file

@ -0,0 +1,31 @@
# Recipe: preload a file tree on the server
Create one payload and pass it to the React tree:
```tsx
import { preloadFileTree } from '@pierre/trees/ssr';
import { FileTree, useFileTree } from '@pierre/trees/react';
const options = {
id: 'project-files',
paths: ['README.md', 'src/', 'src/index.ts'],
initialExpansion: 'open' as const,
initialVisibleRowCount: 8,
};
const preloadedData = preloadFileTree(options);
export function ProjectFiles() {
const { model } = useFileTree(options);
return (
<FileTree
model={model}
preloadedData={preloadedData}
style={{ height: 240 }}
/>
);
}
```
For a direct HTML response, call `serializeFileTreeSsrPayload(payload)`. Pass
`dom` as the second argument when a DOM API inserts the complete markup string.

View file

@ -0,0 +1,18 @@
# Recipe: apply a resolved theme
Convert one resolved Shiki or VS Code theme to host styles:
```tsx
import { themeToTreeStyles } from '@pierre/trees';
import { FileTree } from '@pierre/trees/react';
const treeStyle = {
height: 320,
...themeToTreeStyles(resolvedTheme),
};
<FileTree model={model} style={treeStyle} />;
```
Recalculate the styles when the resolved theme changes. Set tree override CSS
properties on the same host style when the product needs a local color choice.

View file

@ -0,0 +1,23 @@
# Recipe: use a file tree in vanilla JavaScript
Create the model and mount it in an element with a height:
```ts
import { FileTree } from '@pierre/trees';
const mount = document.querySelector<HTMLElement>('#files');
if (mount == null) throw new Error('Missing file tree mount');
mount.style.height = '320px';
const tree = new FileTree({
paths: ['README.md', 'src/', 'src/index.ts'],
initialExpansion: 'open',
search: true,
});
tree.render({ containerWrapper: mount });
```
Use `add`, `remove`, `move`, or `resetPaths` to update paths. Call `cleanUp()`
when the host removes the tree.

View file

@ -40,7 +40,7 @@
<aside class="file-tree" aria-label="Project files">
<p class="tree-title">EXAMPLES</p>
<nav id="example-nav" class="example-nav" aria-label="Examples"></nav>
<p class="tree-title files-title">FILES</p>
<p id="file-tree-title" class="tree-title files-title">FILES</p>
<nav id="file-nav" class="file-nav"></nav>
</aside>
</div>

View file

@ -11,6 +11,7 @@
"@codemirror/lsp-client": "^6.2.5",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.11",
"@pierre/trees": "^1.0.0-beta.6",
"codemirror": "^6.0.2",
"vite": "^7.1.5",
"ws": "^8.18.3"
@ -717,6 +718,51 @@
"node": "^22.20 || ^24.12 || >=25"
}
},
"node_modules/@pierre/theming": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@pierre/theming/-/theming-1.0.0.tgz",
"integrity": "sha512-WsdrnhKfjeyXGDikZmN9pkpeZ5S/cl6EE72feiSc0tlynT1tMYqXqouhuv/foK+PY9OEnebOAVRQn3+rAstR8g==",
"license": "apache-2.0",
"peerDependencies": {
"@pierre/theme": "^1.1.0",
"@shikijs/themes": "^3.0.0 || ^4.0.0",
"react": "^18.3.1 || ^19.0.0",
"react-dom": "^18.3.1 || ^19.0.0",
"shiki": "^3.0.0 || ^4.0.0"
},
"peerDependenciesMeta": {
"@pierre/theme": {
"optional": true
},
"@shikijs/themes": {
"optional": true
},
"react": {
"optional": true
},
"react-dom": {
"optional": true
},
"shiki": {
"optional": true
}
}
},
"node_modules/@pierre/trees": {
"version": "1.0.0-beta.6",
"resolved": "https://registry.npmjs.org/@pierre/trees/-/trees-1.0.0-beta.6.tgz",
"integrity": "sha512-zxeuSFM9TveM7b5XofweJALCtm/tGYV9HZzdbf7Uf+kBxIlUyz24/EHaGRjB0dsmmfDQl2ETz7AWwJ15lhSnpw==",
"license": "apache-2.0",
"dependencies": {
"@pierre/theming": "1.0.0",
"preact": "11.0.0-beta.0",
"preact-render-to-string": "6.6.5"
},
"peerDependencies": {
"react": "^18.3.1 || ^19.0.0",
"react-dom": "^18.3.1 || ^19.0.0"
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.63.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz",
@ -1256,6 +1302,48 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/preact": {
"version": "11.0.0-beta.0",
"resolved": "https://registry.npmjs.org/preact/-/preact-11.0.0-beta.0.tgz",
"integrity": "sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
}
},
"node_modules/preact-render-to-string": {
"version": "6.6.5",
"resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.6.5.tgz",
"integrity": "sha512-O6MHzYNIKYaiSX3bOw0gGZfEbOmlIDtDfWwN1JJdc/T3ihzRT6tGGSEWE088dWrEDGa1u7101q+6fzQnO9XCPA==",
"license": "MIT",
"peerDependencies": {
"preact": ">=10 || >= 11.0.0-0"
}
},
"node_modules/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
"integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
"integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.28.0"
},
"peerDependencies": {
"react": "^19.3.0"
}
},
"node_modules/rollup": {
"version": "4.63.1",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz",
@ -1301,6 +1389,13 @@
"fsevents": "~2.3.2"
}
},
"node_modules/scheduler": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
"integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
"license": "MIT",
"peer": true
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",

View file

@ -12,6 +12,7 @@
"@codemirror/lsp-client": "^6.2.5",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.11",
"@pierre/trees": "^1.0.0-beta.6",
"codemirror": "^6.0.2",
"vite": "^7.1.5",
"ws": "^8.18.3"

View file

@ -0,0 +1,11 @@
{
"version": 1,
"skills": {
"trees": {
"source": "pierrecomputer/pierre",
"sourceType": "github",
"skillPath": "skills/trees/SKILL.md",
"computedHash": "7132a04dc1cb869f53db7fc01f34805d7c78a1089608d9df9b4839647e34b13a"
}
}
}

View file

@ -11,6 +11,7 @@ import {
} from '@codemirror/lsp-client';
import { oneDark } from '@codemirror/theme-one-dark';
import { Decoration, MatchDecorator, ViewPlugin } from '@codemirror/view';
import { FileTree } from '@pierre/trees';
import { EditorView, basicSetup } from 'codemirror';
import './style.css';
@ -128,6 +129,7 @@ const editorsParent = requireElement<HTMLDivElement>('editors');
const markdownEditorParent = requireElement<HTMLDivElement>('markdown-editor');
const exampleNav = requireElement<HTMLElement>('example-nav');
const fileNav = requireElement<HTMLElement>('file-nav');
const fileTreeTitle = requireElement<HTMLParagraphElement>('file-tree-title');
const activePath = requireElement<HTMLSpanElement>('active-path');
const guidePath = requireElement<HTMLSpanElement>('guide-path');
@ -264,43 +266,46 @@ const main = async () => {
const views = new Map<string, EditorView>();
const containers = new Map<string, HTMLDivElement>();
const exampleButtons = new Map<string, HTMLButtonElement>();
const fileButtons = new Map<string, HTMLButtonElement>();
let fileTree: FileTree | null = null;
let syncingTreeSelection = false;
let activeExampleId = initialExample.id;
let activeUri = '';
const renderFileTree = (example: PlaygroundExample) => {
fileTree?.cleanUp();
fileNav.replaceChildren();
fileButtons.clear();
fileTreeTitle.textContent = `FILES · ${example.id}://`;
fileNav.setAttribute('aria-label', `${example.title} files`);
const root = document.createElement('div');
root.className = 'tree-folder tree-root';
root.textContent = `${example.id}://`;
fileNav.append(root);
const directories = new Set<string>();
example.files.forEach(file => {
const segments = file.path.split('/');
for (let index = 1; index < segments.length; index += 1) {
directories.add(`${segments.slice(0, index).join('/')}/`);
}
});
const rootFiles = example.files.filter(file => !file.path.includes('/'));
const sourceFiles = example.files.filter(file => file.path.startsWith('src/'));
const addFileButton = (file: PlaygroundFile, depth: 'root' | 'child') => {
const button = document.createElement('button');
button.className = 'file-tree-item';
button.dataset.active = String(file.uri === activeUri);
button.dataset.depth = depth;
button.dataset.kind = file.languageId === 'rust' ? 'rs' : 'toml';
button.type = 'button';
button.textContent = depth === 'child' ? file.path.replace('src/', '') : file.path;
button.addEventListener('click', () => showFile(file.uri));
fileNav.append(button);
fileButtons.set(file.uri, button);
};
rootFiles.forEach(file => addFileButton(file, 'root'));
if (sourceFiles.length > 0) {
const sourceFolder = document.createElement('div');
sourceFolder.className = 'tree-folder tree-child-folder';
sourceFolder.textContent = 'src';
fileNav.append(sourceFolder);
sourceFiles.forEach(file => addFileButton(file, 'child'));
}
const activeFile = fileByUri.get(activeUri);
const activePathInExample = activeFile?.example.id === example.id ? activeFile.file.path : undefined;
fileTree = new FileTree({
paths: [...directories, ...example.files.map(file => file.path)],
initialExpansion: 'open',
initialSelectedPaths: activePathInExample ? [activePathInExample] : [],
icons: { set: 'complete', colored: true },
density: 'compact',
stickyFolders: true,
onSelectionChange(selectedPaths) {
if (syncingTreeSelection) {
return;
}
const selectedPath = selectedPaths.at(-1);
const selectedFile = example.files.find(file => file.path === selectedPath);
if (selectedFile) {
showFile(selectedFile.uri);
}
},
});
fileTree.render({ containerWrapper: fileNav });
};
const selectExample = (exampleId: string, selectDefaultFile = true) => {
@ -323,7 +328,7 @@ const main = async () => {
return true;
};
const showFile = (uri: string) => {
function showFile(uri: string) {
const entry = fileByUri.get(uri);
const view = views.get(uri);
if (!entry || !view) {
@ -336,13 +341,19 @@ const main = async () => {
containers.forEach((container, candidate) => {
container.hidden = candidate !== uri;
});
fileButtons.forEach((button, candidate) => {
button.dataset.active = String(candidate === uri);
syncingTreeSelection = true;
fileTree?.getSelectedPaths().forEach(path => {
if (path !== entry.file.path) {
fileTree?.getItem(path)?.deselect();
}
});
fileTree?.getItem(entry.file.path)?.select();
fileTree?.scrollToPath(entry.file.path, { focus: false, offset: 'nearest' });
syncingTreeSelection = false;
activePath.textContent = `${entry.example.id}://${entry.file.path}`;
view.focus();
return view;
};
}
const openFileTarget = (target: string) => {
const match = /^([a-z][a-z0-9+.-]*):\/\/(.+?)(?:#L(\d+))?$/i.exec(target);

View file

@ -212,8 +212,11 @@ h1 {
}
.file-tree {
display: flex;
flex-direction: column;
min-width: 0;
overflow: auto;
min-height: 0;
overflow: hidden;
border-left: 1px solid #292e36;
background: #0f1216;
color: #aeb4bd;
@ -241,6 +244,33 @@ h1 {
flex-direction: column;
}
.example-nav {
flex: 0 0 auto;
}
.file-nav {
flex: 1 1 auto;
min-height: 0;
height: 100%;
--trees-accent-override: #bd5b2f;
--trees-bg-override: #0f1216;
--trees-bg-muted-override: #191d23;
--trees-border-color-override: #292e36;
--trees-fg-override: #aeb4bd;
--trees-fg-muted-override: #777f8b;
--trees-focus-ring-color-override: #d06a3a;
--trees-font-family-override: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--trees-font-size-override: 0.78rem;
--trees-selected-bg-override: #252029;
--trees-selected-fg-override: #eef0f3;
--trees-selected-focused-border-color-override: #bd5b2f;
}
.file-nav > file-tree-container {
display: block;
height: 100%;
}
.example-item {
width: 100%;
padding: 0.48rem 0.75rem;
@ -263,68 +293,6 @@ h1 {
border-left-color: #bd5b2f;
}
.tree-folder {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.35rem 0.75rem;
color: #d3d7dd;
font-weight: 650;
}
.tree-root {
color: #eef0f3;
}
.tree-child-folder {
padding-left: 1.25rem;
}
.tree-folder::before {
color: #777f8b;
content: '\25BE';
font-size: 0.65rem;
}
.file-tree-item {
position: relative;
width: 100%;
padding: 0.42rem 0.55rem 0.42rem 2.05rem;
border: 0;
border-left: 2px solid transparent;
color: #858c97;
background: transparent;
cursor: pointer;
font-family: inherit;
text-align: left;
}
.file-tree-item::before {
position: absolute;
left: 0.85rem;
color: #c96f43;
content: attr(data-kind);
font-size: 0.62rem;
}
.file-tree-item[data-depth='child'] {
padding-left: 2.55rem;
}
.file-tree-item[data-depth='child']::before {
left: 1.35rem;
}
.file-tree-item:hover,
.file-tree-item[data-active='true'] {
color: #eef0f3;
background: #191d23;
}
.file-tree-item[data-active='true'] {
border-left-color: #bd5b2f;
}
.cm-editor {
font-size: 0.95rem;
}