# Sidebar

> The navigation down the side of an app. It holds groups of pages, each page with an icon and an optional count or badge. Groups can fold away, there is room for a header and an account line, and its edge can be dragged to make it wider or narrower.

- **Best for:** App navigation down the side: grouped pages with icons and counts.
- **Not for:** A site header with a few links: use Navbar.
- Organism. Source: `src/components/organisms/sidebar/Sidebar.tsx`
- Rendered docs page: `/components/sidebar`

## Import

```tsx
import { SIDEBAR_WIDTH, Sidebar } from 'src/components/organisms/sidebar/Sidebar'
```

Paths are from the Division DS repository root. Installed with shadcn they start `src/division-ds/` instead of `src/` (`src/division-ds/components/...`); import them relative to your file. An install has no index barrels: import each component from its own file, never from `components/molecules`.

## Props

| Prop | Type | Default | Description |
|---|---|---|---|
| `label` | `string` |  | Required. The name screen readers give the navigation region. |
| `groups` | `SidebarGroup[]` |  | Required. Each group has title, icon, items, collapsible and defaultOpen, and optionally action (a small icon button at the right end of the title row, beside the fold toggle, never inside it) footer (under the items, lined up with them, hidden while the group is folded), count (a short right-aligned readout in the data font, such as "2/2", read as part of the toggle’s name) onOpenChange (called with the new state when the reader folds or unfolds it) and open (controls the fold from outside, paired with onOpenChange, for a page that opens one group and folds the rest). Each item can carry count (a number in the data font), badge ({ text, tone, label? }: a solid Badge in a status tone after the label and before the count, never cut short, heard after a comma as label, or text when there is no label), bar (a 2px MeterBar under the item), children (pages under it, indented one level behind a fold toggle named "<label> items"; one level only), defaultOpen (whether those children start shown, false by default, always true when one of them is current) and action (a small icon button at the right of the row, shown on hover and on focus). Labels truncate in a narrow column instead of pushing the count out. |
| `header` | `ReactNode` |  | Sits above the groups: a product name, a workspace switcher. |
| `footer` | `ReactNode` |  | Pinned below the groups when the Sidebar has a height (h-full in a column layout): the signed-in account, a help link. |
| `renderLink` | `(props: LinkRenderProps) => ReactNode` | `a plain anchor` | Pass your router's link component here. Map href to its own prop, and pass className, aria-current and onClick through. |
| `width` | `number` |  | The width in pixels. With onWidthChange, the width the handle starts from: store what onWidthChange reports and pass it back here. Alone, a fixed width. Clamped to minWidth and maxWidth. Leave it out and the Sidebar fills its column, or takes the width a className gives it. |
| `onWidthChange` | `(width: number) => void` |  | Turns on the resize handle, and is called with each new width from a drag or a key. Store the value (in localStorage, say) so the Sidebar opens at the same width next time. Without it there is no handle. SIDEBAR_WIDTH, exported beside the component, holds the bounds, the 256px starting width used when width is left out, and the 16px keyboard step. |
| `minWidth` | `number` | `200` | The narrowest the handle can make it. |
| `maxWidth` | `number` | `400` | The widest the handle can make it. |
| `resizeLabel` | `string` | `'Resize sidebar'` | The resize handle's accessible name. |
| `className` | `string` |  | Added to the root classes. Where two Tailwind utility classes clash, the later one wins. className="border-e-0" turns off the inline-end border, where nothing sits beside the Sidebar (in a Sheet, or when your layout draws the line itself). With a resize handle, keep at least 8px of end padding (the Sidebar sets pe-2 itself; more is fine) so the handle never covers an action, and scroll a tall Sidebar from a parent, not with overflow on the Sidebar itself: the handle would scroll away with the items. |
| `id` | `string` |  | The nav's id, which the resize handle's aria-controls names. One is generated when you give none. |
| `ref` | `Ref<HTMLElement>` |  | The nav element. |

## Types and helpers

Exported beside the component, from the same file. Import a type with `import type { ... }`.

```ts
export type SidebarItem = {
  label: string
  href: string
  /** An icon, drawn aria-hidden; the label carries the meaning. */
  icon?: ReactNode
  current?: boolean
  /** A number shown at the end of the item and read as part of its name ("Orders 12"). */
  count?: number
  /** A solid Badge after the label and before the count: "2" in the warning tone for two tasks
   *  waiting in review. It never truncates; the label does. Its words join the link's name after a
   *  comma: `label` when given ("Spring restock, 2 in review"), else `text` ("Spring restock, 2"). */
  badge?: SidebarItemBadge
  /** A 2px bar under the item (the MeterRow bar), inset to the item's padding. */
  bar?: Omit<MeterBarProps, 'className'>
  /** Pages under this one (a project's tasks), indented one level and folded by a chevron button
   *  beside the link, named "<label> items", with aria-expanded. One level only: a child's
   *  own children are not drawn. */
  children?: SidebarItem[]
  /** Whether the children start shown. Ignored when a child is current: the item then starts open,
   *  and opens again if the current page moves into it later. @default false */
  defaultOpen?: boolean
  /** A small icon button at the right of the row (a ghost size="sm" IconButton: "New task in
   *  Spring restock"). It is a sibling of the link, never inside it, and shows on hover and while
   *  anything in the row has focus; it stays in the tab order the whole time. A sibling row without
   *  one keeps that width free, so the counts line up: keep it to one sm icon button. */
  action?: ReactNode
}
```

```ts
export type SidebarItemBadge = {
  /** What the badge shows: a short number or word. */
  text: string
  /** A status tone, as Badge's: 'warning' for something waiting on the reader. */
  tone: NonNullable<BadgeProps['tone']>
  /** How a screen reader says it, when the text alone would not make sense: "2 in review" for "2". */
  label?: string
}
```

```ts
export type SidebarGroup = {
  /** Also the React key for this group; unique within a Sidebar. */
  title: string
  /** Drawn before the title, aria-hidden; the title alone names the group. */
  icon?: ReactNode
  items: SidebarItem[]
  /** @default true */
  collapsible?: boolean
  /** Ignored when the group holds the current item, which always starts open. @default true */
  defaultOpen?: boolean
  /** Drawn at the far right of the title row: a small icon button, e.g. a ghost size="sm" Button
   *  with a Plus icon and aria-label="New project". It sits beside the fold toggle, never inside it,
   *  so pressing it does not open or close the group. The title truncates before it is pushed out. */
  action?: ReactNode
  /** Drawn under the items, inside the group, lined up with the items' left edge and padding: an
   *  "Add project" button. Hidden (and unreachable by Tab) while the group is folded. */
  footer?: ReactNode
  /** Right-aligned data before the chevron ("2/2"). Read as part of the toggle's name. */
  count?: string
  /** Called when the reader folds or unfolds the group. */
  onOpenChange?: (open: boolean) => void
  /** Controls the fold from outside, for a page that opens one group and folds the rest (for
   *  example to reveal an item picked elsewhere). Pair it with onOpenChange. Unset, the group keeps
   *  its own state. */
  open?: boolean
}
```

```ts
/** The resize bounds, the width a resizable Sidebar starts at when none is given, and the arrow
 *  key step (Shift moves four steps). */
export const SIDEBAR_WIDTH = { default: 256, min: 200, max: 400, step: 16 } as const
```

## Examples

Each is compiled and rendered on the docs page. Imports are omitted; see above.

### Dashboard navigation

```tsx
const GROUPS: SidebarGroup[] = [
  {
    title: 'Operations',
    icon: <Warehouse />,
    items: [
      { label: 'Overview', href: '#overview', icon: <LayoutDashboard /> },
      { label: 'Orders', href: '#orders', icon: <Package />, current: true, count: 12 },
      { label: 'Shipments', href: '#shipments', icon: <Truck /> },
      { label: 'Returns', href: '#returns', icon: <Inbox />, count: 3 },
    ],
  },
  {
    title: 'Catalogue',
    icon: <Boxes />,
    defaultOpen: false,
    items: [
      { label: 'Products', href: '#products', icon: <Box /> },
      { label: 'Inventory', href: '#inventory', icon: <Map /> },
    ],
  },
  {
    title: 'Account',
    icon: <UserCog />,
    collapsible: false,
    items: [
      { label: 'Settings', href: '#settings', icon: <Settings /> },
      { label: 'Team', href: '#team', icon: <Users /> },
    ],
  },
]

const HEADER = <p className="font-display font-semibold">Hexline ops</p>

const FOOTER = <p className="text-xs text-[var(--color-text-secondary)]">Signed in as Ana Pop</p>

<div className="max-w-64">
  <Sidebar label="Dashboard navigation" groups={GROUPS} header={HEADER} footer={FOOTER} />
</div>
```

### A Projects group with an action in its title row and a footer under its items

```tsx
const PROJECT_GROUPS: SidebarGroup[] = [
  {
    title: 'Projects',
    icon: <FolderKanban />,
    action: (
      <IconButton label="New project" variant="ghost" size="sm">
        <Plus aria-hidden="true" />
      </IconButton>
    ),
    items: [
      { label: 'Spring restock', href: '#spring-restock', icon: <Folder /> },
      { label: 'Warehouse move', href: '#warehouse-move', icon: <Folder /> },
    ],
    footer: (
      <Button variant="ghost" size="sm">
        <Plus aria-hidden="true" />
        New project
      </Button>
    ),
  },
]

<div className="max-w-64">
  <Sidebar label="Projects navigation" groups={PROJECT_GROUPS} />
</div>
```

### Projects that fold open to their tasks, with a New task action on hover and focus, and counts in one column

```tsx
const newTask = (project: string) => (
  <IconButton label={`New task in ${project}`} variant="ghost" size="sm">
    <Plus aria-hidden="true" />
  </IconButton>
)

const NESTED_GROUPS: SidebarGroup[] = [
  {
    title: 'Projects',
    icon: <FolderKanban />,
    items: [
      {
        label: 'Spring restock',
        href: '#spring-restock',
        icon: <Folder />,
        count: 2,
        action: newTask('Spring restock'),
        children: [
          { label: 'Count bay 4', href: '#count-bay-4', icon: <Circle />, current: true },
          { label: 'Order shelf labels', href: '#order-labels', icon: <CircleCheck /> },
        ],
      },
      {
        label: 'Warehouse move',
        href: '#warehouse-move',
        icon: <Folder />,
        action: newTask('Warehouse move'),
        children: [
          { label: 'Book the trucks', href: '#book-trucks', icon: <Circle /> },
          { label: 'Label the racks', href: '#label-racks', icon: <Circle /> },
        ],
      },
      { label: 'Returns audit', href: '#returns-audit', icon: <Folder />, count: 14 },
    ],
  },
]

<div className="max-w-64">
  <Sidebar label="Project tasks" groups={NESTED_GROUPS} />
</div>
```

### Group counts, item bars and a narrow column: labels truncate, counts stay

```tsx
const METER_GROUPS: SidebarGroup[] = [
  {
    title: 'Warehouses',
    icon: <Warehouse />,
    count: '3/4',
    items: [
      { label: 'North depot and loading bay', href: '#north', icon: <Box />, count: 412, bar: { value: 412, max: 600, color: 'teal' } },
      { label: 'Harbour store', href: '#harbour', icon: <Box />, count: 268, bar: { value: 268, max: 600, color: 'teal' } },
      { label: 'East yard', href: '#east', icon: <Box />, count: 74, bar: { value: 74, max: 600, color: 'teal' } },
    ],
  },
]

<div className="max-w-48">
  <Sidebar label="Warehouse navigation" groups={METER_GROUPS} />
</div>
```

### Resizable: drag the edge, or focus it and use the arrow keys, between 200 and 400px

```tsx
const GROUPS: SidebarGroup[] = [
  {
    title: 'Operations',
    icon: <Warehouse />,
    items: [
      { label: 'Overview', href: '#overview', icon: <LayoutDashboard /> },
      { label: 'Orders', href: '#orders', icon: <Package />, current: true, count: 12 },
      { label: 'Shipments', href: '#shipments', icon: <Truck /> },
      { label: 'Returns', href: '#returns', icon: <Inbox />, count: 3 },
    ],
  },
  {
    title: 'Catalogue',
    icon: <Boxes />,
    defaultOpen: false,
    items: [
      { label: 'Products', href: '#products', icon: <Box /> },
      { label: 'Inventory', href: '#inventory', icon: <Map /> },
    ],
  },
  {
    title: 'Account',
    icon: <UserCog />,
    collapsible: false,
    items: [
      { label: 'Settings', href: '#settings', icon: <Settings /> },
      { label: 'Team', href: '#team', icon: <Users /> },
    ],
  },
]

const newTask = (project: string) => (
  <IconButton label={`New task in ${project}`} variant="ghost" size="sm">
    <Plus aria-hidden="true" />
  </IconButton>
)

const NESTED_GROUPS: SidebarGroup[] = [
  {
    title: 'Projects',
    icon: <FolderKanban />,
    items: [
      {
        label: 'Spring restock',
        href: '#spring-restock',
        icon: <Folder />,
        count: 2,
        action: newTask('Spring restock'),
        children: [
          { label: 'Count bay 4', href: '#count-bay-4', icon: <Circle />, current: true },
          { label: 'Order shelf labels', href: '#order-labels', icon: <CircleCheck /> },
        ],
      },
      {
        label: 'Warehouse move',
        href: '#warehouse-move',
        icon: <Folder />,
        action: newTask('Warehouse move'),
        children: [
          { label: 'Book the trucks', href: '#book-trucks', icon: <Circle /> },
          { label: 'Label the racks', href: '#label-racks', icon: <Circle /> },
        ],
      },
      { label: 'Returns audit', href: '#returns-audit', icon: <Folder />, count: 14 },
    ],
  },
]

const RESIZABLE_GROUPS: SidebarGroup[] = [
  {
    ...NESTED_GROUPS[0],
    action: (
      <IconButton label="New project" variant="ghost" size="sm">
        <Plus aria-hidden="true" />
      </IconButton>
    ),
  },
  GROUPS[2],
]

function ResizableExample() {
  const [width, setWidth] = useState<number>(SIDEBAR_WIDTH.default)
  return (
    <div className="flex min-w-0">
      <Sidebar label="Resizable navigation" groups={RESIZABLE_GROUPS} header={HEADER} width={width} onWidthChange={setWidth} />
      <div className="hidden min-w-0 flex-1 flex-col gap-2 p-6 sm:flex">
        <p className="font-display font-semibold">Orders</p>
        <p className="font-data text-sm text-[var(--color-text-secondary)]">Sidebar: {width}px</p>
      </div>
    </div>
  )
}

const HEADER = <p className="font-display font-semibold">Hexline ops</p>

<ResizableExample />
```

### A warning badge for tasks waiting in review: the label truncates, the badge stays whole

```tsx
const BADGE_GROUPS: SidebarGroup[] = [
  {
    title: 'Projects',
    icon: <FolderKanban />,
    items: [
      { label: 'Spring restock', href: '#spring-restock', icon: <Folder />, current: true, badge: { text: '2', tone: 'warning', label: '2 in review' } },
      { label: 'Warehouse move and the new loading bay', href: '#warehouse-move', icon: <Folder />, badge: { text: '1', tone: 'warning', label: '1 in review' } },
      { label: 'Returns audit', href: '#returns-audit', icon: <Folder /> },
    ],
  },
]

<div className="max-w-60">
  <Sidebar label="Projects with reviews" groups={BADGE_GROUPS} />
</div>
```

### In a sheet on a narrow screen: picking a link closes the sheet, through renderLink

```tsx
const GROUPS: SidebarGroup[] = [
  {
    title: 'Operations',
    icon: <Warehouse />,
    items: [
      { label: 'Overview', href: '#overview', icon: <LayoutDashboard /> },
      { label: 'Orders', href: '#orders', icon: <Package />, current: true, count: 12 },
      { label: 'Shipments', href: '#shipments', icon: <Truck /> },
      { label: 'Returns', href: '#returns', icon: <Inbox />, count: 3 },
    ],
  },
  {
    title: 'Catalogue',
    icon: <Boxes />,
    defaultOpen: false,
    items: [
      { label: 'Products', href: '#products', icon: <Box /> },
      { label: 'Inventory', href: '#inventory', icon: <Map /> },
    ],
  },
  {
    title: 'Account',
    icon: <UserCog />,
    collapsible: false,
    items: [
      { label: 'Settings', href: '#settings', icon: <Settings /> },
      { label: 'Team', href: '#team', icon: <Users /> },
    ],
  },
]

const HEADER = <p className="font-display font-semibold">Hexline ops</p>

const FOOTER = <p className="text-xs text-[var(--color-text-secondary)]">Signed in as Ana Pop</p>

const closeOnChoose = ({ onClick, ...props }: LinkRenderProps) => (
  <SheetClose asChild type={undefined}>
    <a {...props} onClick={onClick} />
  </SheetClose>
)

<Sheet>
  <SheetTrigger asChild>
    <Button variant="secondary">Open navigation</Button>
  </SheetTrigger>
  <SheetContent side="left" title="Navigation">
    <Sidebar
      label="Dashboard navigation, in a sheet"
      groups={GROUPS}
      header={HEADER}
      footer={FOOTER}
      renderLink={closeOnChoose}
      className="border-e-0"
    />
  </SheetContent>
</Sheet>
```

## Keyboard

| Keys | Result |
|---|---|
| `Tab` | Moves through each group title that can fold, then each visible item, its action and its fold toggle ("<label> items", which reads as expanded or collapsed). Folded children are skipped. |
| `Enter` | Follows an item, or folds and unfolds a group or an item's children. |
| `Space` | Folds and unfolds a group or an item's children. |
| `←` `→` | On the resize handle: narrower and wider by 16px, by 64px with Shift. |
| `Home` `End` | On the resize handle: the narrowest and the widest. |

## Do

- Only show counts for things that need attention: open orders, not total products.
- Keep the group that holds the current page open.
- On a narrow screen, put the whole sidebar in a Sheet behind a button.
- Give a badge a label that says what its number counts: { text: '2', tone: 'warning', label: '2 in review' }.
- Remember the width people drag it to.

## Don't

- Don't nest groups inside groups, or items more than one level deep.
- Don't give the action a second job. It does one thing to its item, such as New task.
- Don't show a count of zero, or a badge of zero. Leave it off.
- Don't use a badge for a plain total. It marks something waiting on the reader; a total is a count.
- Don't rely on icons alone. Every item keeps its label.

## Anatomy

- **nav**: The navigation region. Screen readers call it by the label prop. A strong hairline on its inline-end edge (the right, in left-to-right text) keeps it separate from the main content. Inside a Sheet, where nothing sits beside it, pass className="border-e-0".
- **Group title**: A disclosure button (one that shows and hides the list) when the group can fold, plain text when it can't. It's text.secondary, so it still reads on a raised panel. Its list opens and closes by animating its height. Opening also fades and slides each item in, each one a little later than the one before (capped, so a long group never feels slow). Closing fades everything out together, all at once. If someone has asked their system for less motion (prefers-reduced-motion: reduce), both happen instantly.
- **Item**: An icon, a label and an optional badge and count. The current page gets the selected look the NavRail and Tabs share: the neutral surface.selected, primary text in semibold, and a 2px signal bar on its inline-start edge. Orange is only that bar, never a fill. It also gets aria-current, an ARIA attribute (Accessible Rich Internet Applications, the labels screen readers rely on) that tells screen readers this is the page you are on. Hovering a resting item adds a 12% signal tint.
- **Item badge**: Optional. A solid Badge in a status tone, after the label and before the count, at the end of the row: "2" in warning for two tasks waiting in review. A long label is cut short with an ellipsis; the badge never is. Screen readers hear it as part of the link's name, after a comma: the badge's label when you give one ("Spring restock, 2 in review"), else its text ("Spring restock, 2"). Give a label whenever the text is a bare number.
- **Nested items**: Optional. Pages under an item, such as a project's tasks, indented one level. A chevron button beside the item's link, named "<label> items" with aria-expanded saying whether they show (as a group's title does), folds them with the same height animation as a group. Folded, they can't be reached by Tab. One level only. When any item in a group has children, every item without them keeps the chevron's width free at the end of its row, so the counts line up in one column. A child never does: it cannot fold.
- **Item action**: Optional. A small icon button at the right of an item's row, such as New task. It sits beside the link, not inside it, and shows when the pointer is over the row or anything in the row has focus. It stays in the tab order while it is hidden, and on a touch screen it always shows. When one item has an action, the items beside it without one keep its width free, so the counts stay in one column; that slot is one sm icon button wide.
- **Group action**: Optional. A small icon button at the right end of the title row, such as New project. It sits next to the fold toggle, not inside it, so pressing it never folds the group. A long title is cut short before it can push the action out.
- **Group footer**: Optional. Under the group's items and lined up with them: an Add project button. It folds away with the items.
- **Resize handle**: Only with onWidthChange. An 8px strip just inside the inline-end edge, over 8px of end padding the Sidebar keeps free for it, so it never covers an action or a fold toggle: a vertical separator (role="separator") whose value is the width, between minWidth and maxWidth. Drag it, or focus it and use the arrow keys. Its line turns accent.signal.indicator on hover, on focus and while dragging, and its focus ring is drawn inside it, so a parent that clips never hides it. The same behaviour as the SidePanel's edge, from one shared hook.
- **Header**: Sits above the groups: a product name, a workspace switcher.
- **Footer**: Pinned below the groups: the signed-in account, a help link.
