# Sidebar

The navigation of an application shell. It collapses to an icon rail on wide screens and turns into a drawer on narrow ones, with one set of markup: a header, a navigation landmark of grouped links and a footer.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-sidebar`, `vig-sidebar-nav`, `vig-sidebar-group`, `a[vigSidebarItem]`, `button[vigSidebarTrigger]`
- Source: [libs/ui/src/lib/organisms/sidebar/sidebar.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/sidebar/sidebar.ts)

```typescript title="Import"
import { Sidebar, SidebarNav, SidebarGroup, SidebarItem, SidebarTrigger, SidebarHeader, SidebarFooter } from '@vigdx/ui/sidebar';
```

## Basic

Compose `vig-sidebar-header`, a `vig-sidebar-nav` of `vig-sidebar-group`s and a `vig-sidebar-footer`. Items are your own `<a>` or `<button>` with `vigSidebarItem`, an optional `icon` and `badge`; the current page has `aria-current="page"`. A `<button vigSidebarTrigger>` toggles the sidebar bound to `[(collapsed)]`; left empty, it shows a menu icon named by `triggerAriaLabel`. `tooltip` adds a hint to an item.

```typescript title="sidebar-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import {
  Sidebar,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader,
  SidebarItem,
  SidebarNav,
  SidebarTrigger,
} from '@vigdx/ui/sidebar';

@Component({
  selector: 'app-sidebar-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    Sidebar,
    SidebarHeader,
    SidebarNav,
    SidebarGroup,
    SidebarItem,
    SidebarFooter,
    SidebarTrigger,
  ],
  template: `
    <div class="flex h-[26rem] w-full overflow-hidden rounded-card border border-border bg-app">
      <vig-sidebar #sidebar [(collapsed)]="collapsed">
        <vig-sidebar-header>
          <span
            aria-hidden="true"
            class="inline-flex size-8 shrink-0 items-center justify-center rounded-button bg-primary font-bold text-primary-foreground"
            >A</span
          >
          <span class="truncate font-semibold">Acme</span>
        </vig-sidebar-header>
        <vig-sidebar-nav>
          <vig-sidebar-group heading="Workspace">
            @for (page of pages; track page.id) {
              <button
                vigSidebarItem
                [icon]="page.icon"
                [badge]="page.badge"
                [attr.aria-current]="current() === page.id ? 'page' : null"
                (click)="current.set(page.id)"
              >
                {{ page.label }}
              </button>
            }
          </vig-sidebar-group>
        </vig-sidebar-nav>
        <vig-sidebar-footer>
          <button vigSidebarItem icon="user" (click)="current.set('account')">Account</button>
        </vig-sidebar-footer>
      </vig-sidebar>
      <div class="flex min-w-0 flex-1 flex-col gap-3 p-4">
        <div class="flex items-center gap-2">
          <!-- Empty: the trigger shows a menu icon named "Toggle navigation". -->
          <!-- eslint-disable-next-line @angular-eslint/template/elements-content -->
          <button type="button" [vigSidebarTrigger]="sidebar"></button>
          <span class="font-semibold capitalize">{{ current() }}</span>
        </div>
        <p class="text-sm text-muted-foreground">
          The trigger collapses the sidebar to an icon rail; below 48rem of viewport width it opens
          the sidebar as a drawer instead.
        </p>
      </div>
    </div>
  `,
})
export class SidebarBasicDemo {
  protected readonly collapsed = signal(false);
  protected readonly current = signal('dashboard');
  protected readonly pages = [
    { id: 'dashboard', label: 'Dashboard', icon: 'home', badge: undefined },
    { id: 'inbox', label: 'Inbox', icon: 'inbox', badge: 4 },
    { id: 'documents', label: 'Documents', icon: 'file', badge: undefined },
  ];
}
```

## With the router

The kit has no dependency on `@angular/router`: it styles the item that has `aria-current="page"`, and `routerLinkActive` sets exactly that with `ariaCurrentWhenActive`. Use `exact` matching for the start page, or it stays current everywhere.

```html
<vig-sidebar-nav>
  <vig-sidebar-group heading="Workspace">
    <a vigSidebarItem routerLink="/" routerLinkActive ariaCurrentWhenActive="page"
       [routerLinkActiveOptions]="{ exact: true }" icon="home">Dashboard</a>
    <a vigSidebarItem routerLink="/inbox" routerLinkActive ariaCurrentWhenActive="page"
       icon="inbox" [badge]="unread()">Inbox</a>
  </vig-sidebar-group>
</vig-sidebar-nav>
```

## Groups and the rail

`collapsible` turns a group heading into a disclosure button, bound with `[(expanded)]`. On the collapsed rail, headings are visually hidden and every item shows, with its name as a tooltip on hover and focus.

```typescript title="sidebar-groups.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Sidebar, SidebarGroup, SidebarItem, SidebarNav } from '@vigdx/ui/sidebar';
import { ToggleSwitch } from '@vigdx/ui/toggle-switch';

@Component({
  selector: 'app-sidebar-groups',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Sidebar, SidebarNav, SidebarGroup, SidebarItem, ToggleSwitch],
  template: `
    <vig-toggle-switch label="Collapsed rail" [(value)]="collapsed" />
    <div class="flex h-[22rem] overflow-hidden rounded-card border border-border">
      <vig-sidebar [(collapsed)]="collapsed" breakpoint="1px">
        <vig-sidebar-nav ariaLabel="Projects">
          <vig-sidebar-group heading="Active" collapsible [(expanded)]="activeOpen">
            <button vigSidebarItem icon="calendar" aria-current="page">Apollo launch</button>
            <button vigSidebarItem icon="calendar">Mercury</button>
          </vig-sidebar-group>
          <vig-sidebar-group heading="Archived" collapsible [expanded]="false">
            <button vigSidebarItem icon="file">Gemini</button>
            <button vigSidebarItem icon="file">Vostok</button>
          </vig-sidebar-group>
        </vig-sidebar-nav>
      </vig-sidebar>
    </div>
  `,
  host: { class: 'flex flex-col gap-4' },
})
export class SidebarGroupsDemo {
  protected readonly collapsed = signal(false);
  protected readonly activeOpen = signal(true);
}
```

## Drawer on small screens

Below `breakpoint` (a viewport width, `48rem` by default) the sidebar is an off-canvas `vig-drawer` on the `start` edge, opened by the trigger or `[(open)]`. Following a link item closes it (not a Ctrl/⌘ or middle click, which open the link elsewhere); a button item runs its action and leaves it open, so this demo closes it from the action. Focus returns to the trigger. This demo's breakpoint is wider than any screen.

```typescript title="sidebar-drawer.ts"
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  Sidebar,
  SidebarGroup,
  SidebarHeader,
  SidebarItem,
  SidebarNav,
  SidebarTrigger,
} from '@vigdx/ui/sidebar';

@Component({
  selector: 'app-sidebar-drawer',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Sidebar, SidebarHeader, SidebarNav, SidebarGroup, SidebarItem, SidebarTrigger],
  template: `
    <div class="flex items-center gap-2">
      <!-- eslint-disable-next-line @angular-eslint/template/elements-content -->
      <button type="button" [vigSidebarTrigger]="sidebar"></button>
      <span class="text-sm text-muted-foreground">Last picked: {{ current() }}</span>
    </div>
    <!-- A breakpoint wider than any screen: always the drawer layout. -->
    <vig-sidebar #sidebar breakpoint="999rem" [labels]="{ drawerAriaLabel: 'Demo navigation' }">
      <vig-sidebar-header><span class="font-semibold">Acme</span></vig-sidebar-header>
      <vig-sidebar-nav ariaLabel="Demo">
        <vig-sidebar-group heading="Workspace">
          @for (page of pages; track page) {
            <button
              vigSidebarItem
              icon="file"
              [attr.aria-current]="current() === page ? 'page' : null"
              (click)="pick(page)"
            >
              {{ page }}
            </button>
          }
        </vig-sidebar-group>
      </vig-sidebar-nav>
    </vig-sidebar>
  `,
  host: { class: 'flex flex-col gap-4' },
})
export class SidebarDrawerDemo {
  protected readonly current = signal('Dashboard');
  protected readonly pages = ['Dashboard', 'Inbox', 'Documents'];
  private readonly sidebar = viewChild.required(Sidebar);

  /** Link items close the drawer themselves; a button item does it from its action. */
  protected pick(page: string): void {
    this.current.set(page);
    this.sidebar().open.set(false);
  }
}
```

## Server rendering

The server cannot measure the viewport, so the layout starts `pending` (`data-layout="pending"`): the server and the first, hydrating render in the browser both render the panel inline, and only then does the sidebar measure and switch. Below the default `48rem` a CSS rule already hides the pending panel, so phones never see the inline sidebar flash in, and wide screens keep it where it was: no layout shift. CSS cannot read the `breakpoint` input, so with another value add the same rule for yours:

```css
/* <vig-sidebar breakpoint="64rem"> */
@media (width < 64rem) {
  [data-scope='sidebar'][data-part='root'][data-layout='pending'] {
    display: none;
  }
}
```

## Remembering the collapsed state

`collapsed` is a plain model, so the app decides where it lives. Restore it after the first render, so the server-rendered HTML (always expanded) hydrates without a mismatch:

```typescript
const KEY = 'sidebar-collapsed';

export class Shell {
  protected readonly collapsed = signal(false); // <vig-sidebar [(collapsed)]="collapsed">
  private restored = false;

  constructor() {
    afterNextRender(() => {
      this.collapsed.set(localStorage.getItem(KEY) === 'true');
      this.restored = true;
    });
    effect(() => {
      const collapsed = String(this.collapsed());
      if (this.restored) localStorage.setItem(KEY, collapsed);
    });
  }
}
```

Restoring a collapsed state changes the width after the first paint, which the rail would animate on every load. Turn the transition off until the restored state has rendered (the recipe binds `[style.transition]="ready() ? null : 'none'"`). To render the restored state on the server instead, keep it in a cookie and read it there through the `REQUEST` token.

The [App shell recipe](https://vigdx.com/recipes/app-shell.md) does the same for the recently used commands of the command menu.

## Customize

`SidebarHeader` and `SidebarFooter` only lay out what you put in them: a brand, a workspace switcher, an account item. The widths and the item radius are theme tokens:

- `--container-sidebar` — expanded width (`16rem`).
- `--container-sidebar-collapsed` — rail width (`3.5rem`).
- `--radius-sidebar` — items and group buttons.

Colors come from the shared tokens (`--color-background`, `--color-subtle`, `--color-primary` for the current-page bar). For layout tweaks, select a part by its scope and name, as in the styling hooks below:

```css
/* A wider rail for larger icons */
[data-scope='sidebar'][data-part='root'][data-state='collapsed'] {
  --container-sidebar-collapsed: 4.5rem;
}
/* Uppercase group headings */
[data-scope='sidebar'][data-part='group-heading'],
[data-scope='sidebar'][data-part='group-trigger'] {
  text-transform: uppercase;
  letter-spacing: 0.04em;
}
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="sidebar"][data-part="root"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

### Sidebar `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `root` | The `vig-sidebar` host: the inline column (`display: contents` in the drawer layout). Also carries `data-layout` (`pending`, `inline`, `drawer`) and `data-position` (`start`, `end`). | `expanded, collapsed` |
| `panel` | The column holding the projected header, nav and footer, inline or in the drawer. | `expanded, collapsed` |
| `drawer` | The `vig-drawer` below the breakpoint; style its own `[data-scope="drawer"]` parts. |   |

### SidebarHeader `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `header` | The `vig-sidebar-header` host. |   |

### SidebarNav `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `nav` | The scrolling `<nav>` landmark. |   |

### SidebarGroup `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `group` | The `vig-sidebar-group` host (`role="group"`). | `open, closed` |
| `group-trigger` | The disclosure button of a `collapsible` group. |   |
| `group-heading` | The heading of a group that does not collapse. |   |
| `group-content` | The wrapper of the items. | `open, closed` |

### SidebarItem `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `item` | The `<a>` or `<button>` host; the current page has `aria-current="page"`. | `expanded, collapsed` |
| `icon` | The `vig-icon` of `icon`. |   |
| `label` | The projected text (visually hidden on the rail). | `expanded, collapsed` |
| `badge` | The `badge` count. |   |

### SidebarFooter `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `footer` | The `vig-sidebar-footer` host. |   |

### SidebarTrigger `[data-scope="sidebar"]`

| Part | Element | data-state |
| --- | --- | --- |
| `trigger` | The `button[vigSidebarTrigger]` host. | `open, closed` |

## Accessibility

- `vig-sidebar-nav` is a `<nav>` landmark named "Main" (the `navAriaLabel`); name each one with `ariaLabel` when a page has several.
- Groups are `role="group"`, named by their heading. A collapsible heading is a disclosure button with `aria-expanded` and `aria-controls`.
- The current page is marked with `aria-current="page"` and shown by a heavier weight and a bar at the start edge, not by the tint alone; the bar is a border, so forced-colors mode keeps it (in the system Highlight color).
- On the rail the text of an item is visually hidden but still names it, and a tooltip repeats it on hover and keyboard focus. Every item stays reachable, even in a closed group.
- The trigger reports `aria-expanded` and points at the sidebar with `aria-controls`. Below the breakpoint the drawer is a native modal dialog: focus moves in, Escape and the backdrop close it, focus returns to the trigger. When the window crosses the breakpoint, focus stays on the item it was on, or moves to the trigger when that item went into the closed drawer.
- An item already hosts the rail's `vigTooltip`; a second one on it throws (NG0309). Give a hint with the item's `tooltip` input instead: it describes the item, and on the rail it follows the name.
- The rail's width animation is skipped when the user prefers reduced motion. Positions are logical: `start` is the right edge in right-to-left pages.
- Every text (nav name, trigger name, drawer name and its close button) is a key of the typed `labels` input, over the locale defaults of `provideVigdxUi`.

## API

### Sidebar

Selector: `vig-sidebar` · Kind: component

App-shell navigation panel. Inline it is a column at the `start` (or `end`) edge that collapses to an icon rail (`[(collapsed)]`); below the `breakpoint` viewport width it becomes an off-canvas `vig-drawer`, opened with `[(open)]` or a `vigSidebarTrigger` button.

**Example :**

```html
<vig-sidebar [(collapsed)]="collapsed">
  <vig-sidebar-header>Acme</vig-sidebar-header>
  <vig-sidebar-nav>
    <vig-sidebar-group heading="Workspace">
      <a vigSidebarItem routerLink="/inbox" routerLinkActive ariaCurrentWhenActive="page" icon="inbox">Inbox</a>
    </vig-sidebar-group>
  </vig-sidebar-nav>
</vig-sidebar>
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `breakpoint` | — | `DEFAULT_BREAKPOINT` | Viewport width (any CSS length) below which the sidebar becomes an off-canvas drawer. Measured in the browser. Until then (server render, hydration) the layout is `pending`: the panel renders inline and, for the default `48rem`, CSS already hides it on narrower screens. With another value, add that rule yourself (see the docs). |
| `collapsed` (model) | `boolean` | `false` | Inline layout only: shows the icon rail. Keep it across visits in your app's storage. |
| `labels` | `Partial<SidebarLabels>` | — | Texts of the nav, trigger and drawer (i18n); locale defaults. |
| `open` (model) | `boolean` | `false` | Drawer layout only: whether the off-canvas drawer is open. |
| `position` | `SidebarPosition` | `'start'` | Edge of the sidebar; logical, so `start` follows the text direction. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `collapsedChange` | `boolean` | Inline layout only: shows the icon rail. Keep it across visits in your app's storage. |
| `openChange` | `boolean` | Drawer layout only: whether the off-canvas drawer is open. |

#### Methods

| Signature | Description |
| --- | --- |
| `toggle(): void` | Opens or closes the drawer (drawer layout), or collapses or expands the rail. |

### SidebarNav

Selector: `vig-sidebar-nav` · Kind: component

The scrolling `<nav>` landmark of a sidebar. Name it with `ariaLabel` when the page has more than one navigation; the sidebar's `navAriaLabel` ("Main") otherwise.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `ariaLabel` | `string \| undefined` | `undefined` | Accessible name of the landmark; the sidebar's `navAriaLabel` by default. |

### SidebarGroup

Selector: `vig-sidebar-group` · Kind: component

A labelled group of sidebar items. With `collapsible`, its `heading` is a disclosure button (`aria-expanded`, `aria-controls`) that shows or hides the items, bound with `[(expanded)]`. On the collapsed rail the heading is visually hidden and every item shows, so no page becomes unreachable.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `collapsible` | `boolean` | `false` | Turns the heading into a disclosure button that shows or hides the items. |
| `expanded` (model) | `boolean` | `true` | Whether a collapsible group shows its items. |
| `heading` | `string \| undefined` | `undefined` | Visible label of the group, and its accessible name. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `expandedChange` | `boolean` | Whether a collapsible group shows its items. |

### SidebarItem

Selector: `a[vigSidebarItem], button[vigSidebarItem]` · Kind: component

A link or button of a sidebar, with an optional `icon` and `badge`. The projected text is its name; on the collapsed rail it is visually hidden but still names the item, and a `vigTooltip` shows it on hover and focus.

Mark the current page with `aria-current="page"` — with the router, `routerLinkActive` sets it for you through `ariaCurrentWhenActive="page"`:

**Example :**

```html
<a vigSidebarItem routerLink="/inbox" routerLinkActive ariaCurrentWhenActive="page" icon="inbox" badge="3">Inbox</a>
<button vigSidebarItem icon="plus" (click)="create()">New project</button>
```

Following a link item (`<a href>`, `routerLink`) closes the sidebar's drawer on narrow screens, unless a modifier key or a middle click opens it elsewhere. A button item leaves the drawer open; close it from its action with the sidebar's `[(open)]` when that suits.

The item already hosts a `vigTooltip` (its name on the rail), so another `vigTooltip` on it throws (NG0309): give a hint with `tooltip` instead.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `badge` | `string \| number \| undefined` | `undefined` | Short count or status after the text, e.g. unread items; part of the item's name. |
| `icon` | `string \| undefined` | `undefined` | Name of a registered icon shown before the text (see `vig-icon`). |
| `tooltip` | `string \| undefined` | `undefined` | Hint shown as a tooltip on hover and focus, and read as the item's description; on the rail it follows the item's name. |

### SidebarTrigger

Selector: `button[vigSidebarTrigger]` · Kind: component

Turns a native `<button>` into the toggle of a sidebar: it opens and closes the drawer on narrow screens and collapses or expands the icon rail otherwise. Inside a `vig-sidebar` it controls that sidebar; elsewhere (a top bar) pass it: `<button [vigSidebarTrigger]="sidebar">Menu</button>`. It reports the state with `aria-expanded` and points at the panel with `aria-controls`. Without projected content it shows a menu icon named by the sidebar's `triggerAriaLabel` (template linters that require button content, such as angular-eslint's `elements-content`, cannot see that default: project an icon and text, or disable the rule for that line). When a layout switch leaves focus nowhere, the sidebar focuses a trigger.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `vigSidebarTrigger` | `Sidebar \| ''` | `''` | The sidebar to control; the enclosing one when left empty. |

### SidebarHeader

Selector: `vig-sidebar-header` · Kind: component

Top of the sidebar: brand, workspace switcher or the collapse trigger.

### SidebarFooter

Selector: `vig-sidebar-footer` · Kind: component

Bottom of the sidebar: account, settings or help links.
