# Tree View

> Nested rows you open and close, such as files and folders. Children can load when opened.

Page: https://uicontext.com/docs/components/tree-view

Group: Navigation.

## When to use

Nested rows you open and close, such as files and folders. Children can load when opened. Use [Page Tree](https://uicontext.com/docs/components/page-tree.md) instead when the tree holds pages to drag, rename and add to.

## Usage

```ts
import { TreeView } from "./ui/uicontext/components/TreeView.ts"

const Message = UiSchema.TaggedEnum({
	ChangedExpanded: { expanded: Schema.Array(Schema.String) },
	Selected: { id: Schema.String },
})

const nodes = [
	{ id: "docs", parent: null, label: "docs" },
	{ id: "docs/setup.md", parent: "docs", label: "setup.md" },
	{ id: "README.md", parent: null, label: "README.md" },
]

export const Files = (h: Html.H<typeof Message.Type>, expanded: ReadonlyArray<string>, selected: string | null) =>
	TreeView(h, {
		props: { label: "Files", nodes, expanded, selected },
		onEmit: {
			RequestedExpanded: ({ expanded }) => Message.ChangedExpanded({ expanded }),
			RequestedSelect: ({ id }) => Message.Selected({ id }),
		},
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Files in a repository

The example the page opens with: Tree View in “Files in a repository”.

```ts title="src/demo.ts" source="www/src/examples/tree-view/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { type TreeNode, TreeView } from "./ui/uicontext/components/TreeView.ts"
import { color, corner, font, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	wrap: { display: "grid", gap: space.md, inlineSize: "min(100%, 22rem)" },
	panel: { padding: space.xs, borderWidth: stroke.hairline, borderStyle: "solid", borderColor: color.line, borderRadius: corner.card, backgroundColor: color.panel },
	open: { margin: 0, fontSize: font.sm, color: color.muted, overflowWrap: "anywhere" },
})

// a repository's files, as a code review or an editor's sidebar shows them
const files: ReadonlyArray<TreeNode> = [
	{ id: "src", parent: null, label: "src" },
	{ id: "src/app", parent: "src", label: "app" },
	{ id: "src/app/routes.ts", parent: "src/app", label: "routes.ts", meta: "4 KB" },
	{ id: "src/app/session.ts", parent: "src/app", label: "session.ts", meta: "11 KB" },
	{ id: "src/billing", parent: "src", label: "billing" },
	{ id: "src/billing/invoice.ts", parent: "src/billing", label: "invoice.ts", meta: "7 KB" },
	{ id: "src/billing/proration.ts", parent: "src/billing", label: "proration.ts", meta: "3 KB" },
	{ id: "src/billing/tax-rates-by-jurisdiction.generated.ts", parent: "src/billing", label: "tax-rates-by-jurisdiction.generated.ts", meta: "1.2 MB" },
	{ id: "src/main.ts", parent: "src", label: "main.ts", meta: "1 KB" },
	{ id: "test", parent: null, label: "test" },
	{ id: "test/invoice.test.ts", parent: "test", label: "invoice.test.ts", meta: "5 KB" },
	{ id: "package.json", parent: null, label: "package.json", meta: "2 KB" },
	{ id: "README.md", parent: null, label: "README.md", meta: "6 KB" },
]

const Message = UiSchema.TaggedEnum({
	ChangedExpanded: { expanded: Schema.Array(Schema.String) },
	Selected: { id: Schema.String },
})

export const RepositoryFiles = Html.component({
	name: "RepositoryFiles",
	model: Schema.Struct({ expanded: Schema.Array(Schema.String), selected: Schema.NullOr(Schema.String) }),
	message: Message,
}).make({
	init: () => ({ expanded: ["src", "src/billing"], selected: "src/billing/invoice.ts" }),
	update: {
		ChangedExpanded: ($, { expanded }) => $.evolve({ expanded }),
		Selected: ($, { id }) => $.evolve({ selected: id }),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			h.div.attrs(sx(styles.panel)).children(
				TreeView(h, {
					props: { label: "Files", nodes: files, expanded: model.expanded, selected: model.selected },
					onEmit: {
						RequestedExpanded: ({ expanded }) => Message.ChangedExpanded({ expanded }),
						RequestedSelect: ({ id }) => Message.Selected({ id }),
					},
				}),
			),
			h.p.attrs(sx(styles.open)).children(model.selected === null ? "No file open" : model.selected),
		),
})
```

### Children that load when opened

`hasChildren` draws a folder before its children arrive; opening it shows Loading… until they do.

```ts title="src/lazy.ts" source="www/src/examples/tree-view/lazy.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { TreeNode, TreeView } from "./ui/uicontext/components/TreeView.ts"
import { color, corner, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	panel: { inlineSize: "min(100%, 22rem)", padding: space.xs, borderWidth: stroke.hairline, borderStyle: "solid", borderColor: color.line, borderRadius: corner.card, backgroundColor: color.panel },
})

// a store's catalog: the top categories come with the page, the rest load when a category opens
const top: ReadonlyArray<TreeNode> = [
	{ id: "kitchen", parent: null, label: "Kitchen", meta: "1,204", hasChildren: true },
	{ id: "outdoor", parent: null, label: "Outdoor", meta: "873", hasChildren: true },
	{ id: "lighting", parent: null, label: "Lighting", meta: "412", hasChildren: true },
	{ id: "gift-cards", parent: null, label: "Gift cards", meta: "6" },
]

const below: Readonly<Record<string, ReadonlyArray<readonly [string, string]>>> = {
	kitchen: [["Cookware", "318"], ["Knives", "96"], ["Small appliances", "441"], ["Tableware", "349"]],
	outdoor: [["Grills", "122"], ["Garden furniture", "507"], ["Planters", "244"]],
	lighting: [["Pendants", "131"], ["Floor lamps", "88"], ["Bulbs", "193"]],
}

const Message = UiSchema.TaggedEnum({
	ChangedExpanded: { expanded: Schema.Array(Schema.String) },
	Selected: { id: Schema.String },
	Loaded: { parent: Schema.String, nodes: Schema.Array(TreeNode) },
})

// stands in for the API: answers after a moment
const LoadCategory = Command.make("Example.LoadCategory", { args: { parent: Schema.String } }, ({ parent }) =>
	Effect.sleep(700).pipe(
		Effect.as(
			Message.Loaded({
				parent,
				nodes: (below[parent] ?? []).map(([label, count]) => ({ id: `${parent}/${label.toLowerCase().replaceAll(" ", "-")}`, parent, label, meta: count })),
			}),
		),
	),
)

export const CatalogCategories = Html.component({
	name: "CatalogCategories",
	model: Schema.Struct({ nodes: Schema.Array(TreeNode), expanded: Schema.Array(Schema.String), selected: Schema.NullOr(Schema.String) }),
	message: Message,
}).make({
	init: () => ({ nodes: top, expanded: [], selected: null }),
	update: {
		ChangedExpanded: ($, { expanded }) => {
			const opened = expanded.filter((id) => !$.model.expanded.includes(id))
			const missing = opened.filter((id) => !$.model.nodes.some((n) => n.parent === id))
			const step = $.evolve({ expanded })
			return missing.reduce((s, parent) => s.run(LoadCategory.make({ parent })), step)
		},
		Selected: ($, { id }) => $.evolve({ selected: id }),
		Loaded: ($, { parent, nodes }) =>
			$.model.nodes.some((n) => n.parent === parent) ? $.model : $.evolve({ nodes: (list) => [...list, ...nodes] }),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.panel)).children(
			TreeView(h, {
				props: { label: "Categories", nodes: model.nodes, expanded: model.expanded, selected: model.selected, plain: true },
				onEmit: {
					RequestedExpanded: ({ expanded }) => Message.ChangedExpanded({ expanded }),
					RequestedSelect: ({ id }) => Message.Selected({ id }),
				},
			}),
		),
})
```

## API reference

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | What the tree holds, for screen readers: "Files", "Categories". |
| `nodes` (required) | `TreeNode[]` | Every row, flat, in order among its siblings. |
| `expanded` (required) | `string[]` | The open folders. The caller keeps them and stores what `RequestedExpanded` asks for. |
| `selected` (required) | `string \| null` | The selected row, or null. The caller keeps it. |
| `plain` | `boolean` | Draw no folder and page marks: a tree of plain words. |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedExpanded` | `{ expanded: string[] }` | The open folders asked for: store them and pass them back as `expanded`. |
| `RequestedSelect` | `{ id: string }` | A row was picked with a click, Enter or Space. |

## Keyboard and accessibility

### Keys

| Keys | Does |
| --- | --- |
| Down arrow, Up arrow | Move between rows |
| Right arrow | Open a folder, or move into it |
| Left arrow | Close it, or move to its folder |
| Home, End | Go to the first or the last row |
| Enter, Space | Select the row |
| * | Open every folder beside this one |
| A–Z | Jump to the next row that starts with what’s typed |

On a Mac, Control is Command and Alt is Option. Left and Right trade places in right-to-left text.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/tree-view
```

With npm: `npx shadcn@latest add checkfu/uicontext/tree-view`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/tree-view`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/tree-view`.

It writes these files:

- `src/ui/uicontext/components/Direction.ts`
- `src/ui/uicontext/components/Glyph.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/TreeView.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Glyph.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/TreeView.ts](https://github.com/checkfu/uicontext/blob/main/src/TreeView.ts)

## Related

- [App Shell](https://uicontext.com/docs/components/app-shell.md) (`app-shell`): The frame of an app: a sidebar, the page and an optional side panel, on any screen size.
- [Tab Strip](https://uicontext.com/docs/components/tab-strip.md) (`tab-strip`): Document tabs over the page to open, close and drag to reorder.
- [Sidebar](https://uicontext.com/docs/components/sidebar.md) (`sidebar`): A navigation tree of workspaces, teams and pages.
- [Page Header](https://uicontext.com/docs/components/page-header.md) (`page-header`): A page's title, description, breadcrumb and actions.
- [Tabs](https://uicontext.com/docs/components/tabs.md) (`tabs`): Switch between panels, or between views of the same data.
- [Route Tabs](https://uicontext.com/docs/components/route-tabs.md) (`route-tabs`): A row of links between the pages of one section.
