references/api-core.md
# 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. |
references/api-react.md
# 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. |
references/api-ssr.md
# 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`.
references/api-web-components.md
# 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. |
references/recipe-interactions.md
# 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 `/`.
references/recipe-react.md
# 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.
references/recipe-ssr.md
# 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.
references/recipe-theme.md
# 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.
references/recipe-vanilla.md
# 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.
SKILL.md
---
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) |