# Sidebar

> A navigation tree of workspaces, teams and pages.

Page: https://uicontext.com/docs/components/sidebar

Group: Navigation.

## When to use

A navigation tree of workspaces, teams and pages. Use [Page Tree](https://uicontext.com/docs/components/page-tree.md) instead when the sidebar lists a workspace's documents.

## Usage

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

const Message = UiSchema.TaggedEnum({ RequestedOpenPage: { id: Schema.String } })

export const Sidebar = (h: Html.H<typeof Message.Type>, current: string) =>
	Nav(h, {
		props: {
			label: "Workspace",
			current,
			sections: [
				{
					id: "teams",
					title: "Your teams",
					items: [
						{ id: "engineering", label: "Engineering", href: "/engineering" },
						{ id: "issues", label: "Issues", href: "/engineering/issues", parent: "engineering", count: 12 },
					],
				},
			],
		},
		onEmit: {
			RequestedOpen: ({ id }) => Message.RequestedOpenPage({ id }),
			RequestedAction: () => undefined,
			RequestedMove: () => undefined,
			RequestedAdd: () => undefined,
			RequestedExpand: () => undefined,
			RequestedCollapse: () => undefined,
		},
	})
```

## Examples

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

### A workspace sidebar

The example the page opens with: Sidebar in “A workspace sidebar”.

```ts title="src/demo.ts" source="www/src/examples/sidebar/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { Nav, type NavItem, type NavSection } from "./ui/uicontext/components/Nav.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { choice, color, corner, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	stack: { display: "grid", gap: space.md, justifyItems: "start" },
	// a sidebar's width, on the app's background
	sidebar: {
		inlineSize: "min(100%, 260px)",
		paddingBlock: space.md,
		borderRadius: corner.card,
		backgroundColor: color.app,
		boxShadow: `inset 0 0 0 1px ${color.line}`,
	},
	note: { margin: 0, minBlockSize: "1.4em", fontSize: font.sm, color: color.muted },
})

const team = (id: string, label: string, hue: string, extra: Partial<NavItem> = {}): NavItem => ({
	id,
	label,
	href: `#${id}`,
	glyph: { _tag: "Swatch", color: hue },
	...extra,
})

// pages nest as deep as people make them: Handbook › Engineering › On-call › Runbooks › Database failover
const pages: ReadonlyArray<NavItem> = [
	{ id: "handbook", label: "Handbook", href: "#handbook", movable: true, accepts: true },
	{ id: "eng", label: "Engineering", href: "#eng", parent: "handbook", movable: true, accepts: true },
	{ id: "oncall", label: "On-call", href: "#oncall", parent: "eng", movable: true, accepts: true },
	{ id: "runbooks", label: "Runbooks", href: "#runbooks", parent: "oncall", movable: true, accepts: true },
	{ id: "failover", label: "Database failover", href: "#failover", parent: "runbooks", movable: true, accepts: true },
	{ id: "rotation", label: "Rotation schedule", href: "#rotation", parent: "oncall", movable: true, accepts: true },
	{ id: "notes", label: "Meeting notes", href: "#notes", movable: true, accepts: true },
	{ id: "roadmap", label: "Roadmap 2027", href: "#roadmap", movable: true, accepts: true },
]

const Message = UiSchema.TaggedEnum({
	RequestedOpenItem: { id: Schema.String },
	RequestedMoveItem: { id: Schema.String, into: Schema.NullOr(Schema.String), before: Schema.optional(Schema.NullOr(Schema.String)) },
	RequestedItemAction: { id: Schema.String, action: Schema.String },
	RequestedAddPage: {},
})

const Placement = Schema.Struct({ id: Schema.String, parent: Schema.NullOr(Schema.String) })

export const WorkspaceSidebar = Html.component({
	name: "WorkspaceSidebar",
	// where each page sits, in order: the app's data, which the tree shows and moves ask to change
	model: Schema.Struct({ current: Schema.String, pages: Schema.Array(Placement), note: Schema.String }),
	message: Message,
}).make({
	init: () => ({
		current: "issues",
		pages: pages.map((p) => ({ id: p.id, parent: p.parent ?? null })),
		note: "Alt+arrows move a page; drag one onto another to nest it.",
	}),
	update: {
		RequestedOpenItem: ($, { id }) => $.evolve({ current: id }),
		RequestedMoveItem: ($, { id, into, before }) => {
			const moved = { id, parent: into }
			const rest = $.model.pages.filter((p) => p.id !== id)
			// no `before`: it keeps its place in the order and only changes parent
			const at = before === null ? -1 : rest.findIndex((p) => p.id === before)
			const next = before === undefined
				? $.model.pages.map((p) => (p.id === id ? moved : p))
				: at === -1 ? [...rest, moved] : [...rest.slice(0, at), moved, ...rest.slice(at)]
			const name = pages.find((p) => p.id === id)?.label ?? id
			const label = (page: string) => pages.find((p) => p.id === page)?.label ?? page
			const where = before === undefined
				? into === null ? "to the top level" : `into ${label(into)}`
				: before === null ? "to the end" : `before ${label(before)}`
			return $.evolve({ pages: next, note: `Moved ${name} ${where}.` })
		},
		RequestedItemAction: ($, { id, action }) =>
			$.evolve({ note: `${action === "rename" ? "Rename" : "Move to trash"}: ${pages.find((p) => p.id === id)?.label ?? id}` }),
		RequestedAddPage: ($) => $.evolve({ note: "The app would create a page here." }),
	},
	view: (h, model) => {
		const byId = new Map(pages.map((p) => [p.id, p]))
		const pageItems = model.pages.flatMap((placement) => {
			const page = byId.get(placement.id)
			if (page === undefined) return []
			const { parent: _, ...rest } = page
			return [{
				...rest,
				...(placement.parent === null ? {} : { parent: placement.parent }),
				actions: [
					{ id: "rename", label: "Rename" },
					{ id: "trash", label: "Move to trash", consequential: true },
				],
			}]
		})
		const sections: ReadonlyArray<NavSection> = [
			{
				id: "top",
				items: [
					{ id: "inbox", label: "Inbox", href: "#inbox", count: 4, countLabel: "unread", attention: true },
					{ id: "my-issues", label: "My issues", href: "#my-issues" },
				],
			},
			{
				id: "teams",
				title: "Your teams",
				items: [
					team("engineering", "Engineering", choice.indigo),
					{ id: "issues", label: "Issues", href: "#issues", parent: "engineering", count: 12 },
					{ id: "cycles", label: "Cycles", href: "#cycles", parent: "engineering" },
					team("design", "Design", choice.orange, { badge: "Private" }),
					team("operations", "Operations", choice.gray, { badge: "Archived", muted: true }),
				],
			},
			{ id: "pages", title: "Pages", reorderable: true, accepts: true, add: "New page", items: pageItems },
		]
		return h.div.attrs(sx(styles.stack)).children(
			h.div.attrs(sx(styles.sidebar)).children(
				Nav(h, {
					props: { label: "Workspace", sections, current: model.current, expanded: ["handbook", "eng", "oncall", "runbooks"], agentId: "nav-demo" },
					onEmit: {
						RequestedOpen: ({ id }) => Message.RequestedOpenItem({ id }),
						RequestedAction: ({ id, action }) => Message.RequestedItemAction({ id, action }),
						RequestedMove: ({ id, into, before }) => Message.RequestedMoveItem({ id, into, before }),
						RequestedAdd: () => Message.RequestedAddPage(),
						RequestedExpand: () => undefined,
						RequestedCollapse: () => undefined,
					},
				}),
			),
			h.p.attrs({ role: "status", ...sx(styles.note) }).children(model.note),
		)
	},
})
```

## API reference

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | The navigation's accessible name: "Workspace" |
| `sections` (required) | `NavSection[]` | The sidebar's sections, each a titled tree of items |
| `current` | `string \| null` | The item for the page shown now |
| `expanded` | `string[]` | Items open at first (the current item's parents always are) |
| `closed` | `string[]` | Sections closed at first |
| `agentId` | `string` | This navigation's id for agents, unique on the page |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedOpen` | `{ id: string; link: string }` | An item without a link was activated, or an agent opened one |
| `RequestedAction` | `{ id: string; action: string; link: string }` | An action from an item's menu was chosen: the app does it |
| `RequestedAdd` | `{ section: string }` | A section's add button was pressed: the app creates an item there |
| `RequestedMove` | `{ id: string; link: string; into: string \| null; section: string; before?: string \| null }` | `into` an item (or null: the section's top level). `before` is set only in a reorderable section: the sibling (an item id) it goes before, or null for last. Without it, the app picks the place. |
| `RequestedExpand` | `{ id: string; link: string }` | Opened: load its children (for `link`) if they aren't there yet |
| `RequestedCollapse` | `{ id: string; link: string }` | An item was closed |

**Agent actions**

| Action | Description |
| --- | --- |
| `ActivatedItem` | Open an item by its id (see page_query for every item) |
| `ToggledItem` | Open or close an item's children |
| `ClickedSection` | Open or close a section |
| `ClickedSectionAdd` | Add to a section (its add button) |
| `ClickedItemAction` | Run one of an item's actions, by item id and action id |
| `MovedItem` | Move an item into another (into: its id) or to its section's top level (into: null). In a reorderable section, before: the sibling it goes before there, or null for last |

## Keyboard and accessibility

### Keys

| Keys | Does |
| --- | --- |
| Down arrow, Up arrow | Move between links |
| Right arrow | Open a section, or move into it |
| Left arrow | Close it, or move to the parent |
| Home, End | Go to the first or the last link |
| Enter | Follow the link |

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

- A `nav` landmark whose sections are each a WAI-ARIA tree and one Tab stop: Up and Down move, Right opens or moves in, Left closes or moves out, Home and End jump, and typing jumps to an item.
- Enter follows the link, and the current page is `aria-current="page"`. Shift+F10 opens an item's actions; Alt with the arrow keys moves a movable item.
- Counts and attention dots are read as words. Agents read the visible items and open one by id.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/sidebar
```

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

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/InlineNotice.ts`
- `src/ui/uicontext/components/Motion.ts`
- `src/ui/uicontext/components/Nav.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/agent/Agent.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Glyph.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/touch.stylex.ts`

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

## Source

- [src/Nav.ts](https://github.com/checkfu/uicontext/blob/main/src/Nav.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.
- [Tree View](https://uicontext.com/docs/components/tree-view.md) (`tree-view`): Nested rows you open and close, such as files and folders. Children can load when opened.
- [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.
