# App shell

The frame around every page: a `vig-sidebar` that collapses to an icon rail and becomes a drawer on phones, a top bar, and a `vig-command-menu` (Cmd+K / Ctrl+K) that goes to any page, remembers recent commands and searches the server.

- Source: [apps/docs/src/app/recipes/app-shell](https://github.com/bakyurekk/vigdx/blob/main/apps/docs/src/app/recipes/app-shell)

## Live demo

Pick a page in the sidebar, collapse it with the trigger (reload: it stays collapsed), or open the command menu with the Search button and type “sales” or a name such as “grace”. On this site Ctrl K opens the site search, so the demo opens its menu from the button.

The frame around every page of an application: a sidebar with the navigation, a top bar and a
Cmd+K / Ctrl+K command menu, rendered once by a layout route while the pages change below it. The
sidebar collapses to an icon rail on wide screens, and the choice is remembered; on narrow screens
it becomes a drawer. The command menu goes to any page, runs the shell's actions and searches
people on the server.

## When to use

- Back-office and SaaS applications with more than a handful of pages: one navigation, always in
  the same place.
- Users who return daily and benefit from keyboard access: the command menu reaches any page in a
  few keystrokes.
- For a public site with a few top-level pages, use a header navigation instead; for a single
  screen, no shell at all.

## Component choices

| Need                         | Component                                              | Why                                                                                                                                                           | Alternatives                                         |
| ---------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| Navigation                   | `vig-sidebar` with `vig-sidebar-nav`, groups and items | A `<nav>` landmark of real links; groups label and fold sections; the current page gets `aria-current="page"`                                                 | `vig-tabs` for two to five sibling views of one page |
| Collapse and mobile          | `[(collapsed)]` and the sidebar's drawer layout        | One component: an icon rail with tooltips on wide screens, a native modal drawer below the breakpoint                                                         | —                                                    |
| Sidebar toggle               | `<button vigSidebarTrigger>`                           | Named, with `aria-expanded` and `aria-controls`; collapses the rail or opens the drawer, whichever applies; gets focus when a layout switch leaves it nowhere | Call the sidebar's `toggle()` from your own control  |
| Jump anywhere                | `vig-command-menu`                                     | A combobox over a listbox in a modal dialog (APG), locale-aware filtering, recent commands, async results with abort                                          | `vig-autocomplete` for search inside one page        |
| Current page from the router | `routerLinkActive` with `ariaCurrentWhenActive="page"` | The router sets `aria-current`, the kit styles it; the kit needs no router dependency                                                                         | Bind `[attr.aria-current]` yourself                  |

## Folder structure

### Angular CLI

```text
src/app/shell/
  data-access/
    shell-nav.ts               the navigation as data, shared by sidebar and command menu
    shell-preferences.ts       collapsed sidebar and recent commands in localStorage
    people-search.ts           the server search the command menu calls
  feature/
    app-shell.ts               layout: sidebar, top bar, content, command menu
    app-shell.routes.ts        the layout route with the pages as children
    shell-page.ts              stand-in page
  ui/
    shell-sidebar-nav.ts       sections and links with routerLink
    top-bar.ts                 trigger, title and the search button
```

```ts title="app.routes.ts"
export const routes: Routes = [{ path: '', children: appShellRoutes }];
```

Route data reaches the components as inputs through `withComponentInputBinding()` in
`provideRouter`. Make the shell fill the window: it is `h-dvh` by default.

### Nx

```bash
npx nx g @nx/angular:library --directory=libs/shell/data-access --name=shell-data-access --tags=type:data-access,scope:shell --prefix=app --no-interactive
npx nx g @nx/angular:library --directory=libs/shell/feature --name=shell-feature --tags=type:feature,scope:shell --prefix=app --no-interactive
npx nx g @nx/angular:library --directory=libs/shell/ui --name=shell-ui --tags=type:ui,scope:shell --prefix=app --no-interactive
```

## Key decisions

- **One navigation model.** `SHELL_NAV` is plain data: the sidebar renders it and every link
  becomes a "Go to" command, so the two never drift apart. The routes are built from it too.
- **The router marks the current page.** Each item is an `<a routerLink>` with `routerLinkActive`
  and `ariaCurrentWhenActive="page"`; the kit styles `aria-current`, so it needs no router of its
  own. The start page uses `exact` matching, or it would stay current on every page.
- **Persistence belongs to the app.** `vig-sidebar` only has a `collapsed` model. `ShellPreferences`
  keeps it, and the recent command ids, in `localStorage`, restored after the first render: the
  server always renders the expanded sidebar, so hydration never sees a mismatch. Until that state
  has rendered the sidebar's width transition is off (`[style.transition]`), so a collapsed rail
  does not slide shut on every load. For a server render that already shows the stored state, keep
  it in a cookie instead and read it on the server through the `REQUEST` token.
- **No flash on phones.** Until the browser measures the viewport the sidebar's layout is
  `pending`: it renders inline, and below the default `48rem` breakpoint CSS hides it, so the
  server's HTML neither flashes the inline panel on a phone nor shifts the layout on a desktop.
  With another `breakpoint`, add the same rule for
  `[data-scope='sidebar'][data-part='root'][data-layout='pending']`.
- **Recent commands from `executed`.** The menu emits the command that ran; the app records its id
  and passes the list back as `recent`, shown while the field is empty.
- **Server search with abort.** `search` returns a promise and receives an `AbortSignal`. The menu
  waits for typing to pause and aborts the previous call when the query changes, so a slow answer
  never replaces a newer one. Pass the signal on to `fetch` or `HttpClient`.
- **One shortcut listener.** The menu registers Cmd+K / Ctrl+K through the kit's shared listener;
  a second palette or a page's own shortcut does not add another document listener.

## Accessibility

- The sidebar is a `<nav>` landmark named "Main"; the content is the page's `<main>`.
- Items are links (or buttons for actions) with visible text. On the collapsed rail the text is
  visually hidden but still names the item, and a tooltip shows it on hover and focus.
- The current page has `aria-current="page"` and is shown by weight and a start-edge bar, not by
  color alone, so it survives forced-colors mode.
- Collapsible groups are disclosure buttons with `aria-expanded` and `aria-controls`.
- The trigger has `aria-expanded` and `aria-controls`. On narrow screens the drawer is a native
  modal dialog: focus moves in, Escape closes it, and focus returns to the trigger; following a
  link closes it too. Crossing the breakpoint keeps focus on the item, or moves it to the trigger.
- The command menu follows the APG combobox pattern; Enter is ignored while an IME composes text,
  and the result count is announced once typing pauses. The search button names its shortcut with
  `aria-keyshortcuts`.
- The width animation of the rail is skipped when the user prefers reduced motion.

## Performance

- The shell renders once; only the routed page changes below it.
- Pages are lazy routes; the shell itself can be eager, since every page needs it.
- `OnPush` everywhere; the command list is a `computed` of the navigation and the sidebar state.
- The server search runs only after a pause in typing and cancels stale requests.

## Definition of done

- [ ] `nx build <app>` (or `ng build`) succeeds; `nx lint` passes.
- [ ] The specs pass: navigation and the current page, opening the menu, going to a page, server
      search, recent commands, collapsing from a command and remembering it.
- [ ] axe reports no violations with the sidebar expanded, collapsed and as an open drawer, and
      with the command menu open, light and dark.
- [ ] Keyboard only: reach every page from the sidebar, collapse it, open the menu with Ctrl+K,
      run a command with Enter, close the drawer with Escape and land on the trigger.
- [ ] Reload keeps the collapsed state; the server HTML shows the expanded sidebar.

## Source files

```typescript title="data-access/people-search.ts"
import { Injectable, InjectionToken, inject } from '@angular/core';

/** A person found by the command menu's server search. */
export interface Person {
  id: string;
  name: string;
  email: string;
}

/** Simulated network latency of the in-memory search, in ms. */
export const PEOPLE_SEARCH_LATENCY = new InjectionToken<number>('PEOPLE_SEARCH_LATENCY', {
  providedIn: 'root',
  factory: () => 300,
});

const PEOPLE: readonly Person[] = [
  { id: 'p-1', name: 'Ada Lovelace', email: 'ada@northwind.example' },
  { id: 'p-2', name: 'Grace Hopper', email: 'grace@northwind.example' },
  { id: 'p-3', name: 'Mary Jackson', email: 'mary@northwind.example' },
  { id: 'p-4', name: 'Katherine Johnson', email: 'katherine@northwind.example' },
];

/**
 * Finds people for a query, as a server would; swap it for an `HttpClient`
 * call (`firstValueFrom(http.get(…))`, or `fetch(url, { signal })`). The
 * command menu passes an `AbortSignal` that aborts when the query changes,
 * so a slow answer never overwrites a newer one.
 */
@Injectable({ providedIn: 'root' })
export class PeopleSearch {
  private readonly latency = inject(PEOPLE_SEARCH_LATENCY);

  find(query: string, signal: AbortSignal): Promise<Person[]> {
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        const needle = query.toLocaleLowerCase();
        resolve(
          PEOPLE.filter(
            (person) =>
              person.name.toLocaleLowerCase().includes(needle) || person.email.includes(needle),
          ),
        );
      }, this.latency);
      signal.addEventListener(
        'abort',
        () => {
          clearTimeout(timer);
          reject(signal.reason);
        },
        { once: true },
      );
    });
  }
}
```

```typescript title="data-access/shell-nav.ts"
/** One page of the app, as the sidebar and the command menu list it. */
export interface ShellLink {
  /** Route path relative to the shell; `''` is its start page. */
  path: string;
  label: string;
  /** A `vig-icon` name. */
  icon: string;
  /** Extra words the command menu matches, e.g. synonyms. */
  keywords?: readonly string[];
}

/** A labelled group of links in the sidebar; also the command menu's group. */
export interface ShellSection {
  heading: string;
  /** A disclosure the user can close; keep the main section always open. */
  collapsible?: boolean;
  links: readonly ShellLink[];
}

/**
 * The app's navigation, written once: the sidebar renders it and the
 * command menu turns every link into a "go to" command. Keep it plain data
 * (no router objects), so it can come from a permissions endpoint later.
 */
export const SHELL_NAV: readonly ShellSection[] = [
  {
    heading: 'Workspace',
    links: [
      { path: '', label: 'Dashboard', icon: 'home', keywords: ['overview', 'start'] },
      { path: 'inbox', label: 'Inbox', icon: 'inbox', keywords: ['messages', 'mail'] },
      { path: 'documents', label: 'Documents', icon: 'file', keywords: ['files', 'uploads'] },
    ],
  },
  {
    heading: 'Reports',
    collapsible: true,
    links: [
      { path: 'reports/sales', label: 'Sales', icon: 'calendar', keywords: ['revenue'] },
      { path: 'reports/customers', label: 'Customers', icon: 'user', keywords: ['clients'] },
    ],
  },
];

/** Every link of `sections`, in order. */
export function shellLinks(sections: readonly ShellSection[]): ShellLink[] {
  return sections.flatMap((section) => section.links);
}
```

```typescript title="data-access/shell-preferences.ts"
import { Injectable, InjectionToken, afterNextRender, effect, inject, signal } from '@angular/core';

/** Where the shell keeps its preferences; `localStorage` in the browser. */
export const SHELL_STORAGE = new InjectionToken<Pick<Storage, 'getItem' | 'setItem'> | null>(
  'SHELL_STORAGE',
  {
    providedIn: 'root',
    factory: () => {
      try {
        return typeof localStorage === 'undefined' ? null : localStorage;
      } catch {
        // Blocked storage (privacy settings, sandboxed iframes) throws on access.
        return null;
      }
    },
  },
);

const KEY = 'app-shell';
/** How many recently run commands the menu offers. */
export const RECENT_LIMIT = 5;

interface StoredPreferences {
  collapsed?: boolean;
  recent?: string[];
}

/**
 * The shell's per-user preferences: whether the sidebar is collapsed and
 * which commands ran last. The kit leaves persistence to the app; this keeps
 * it in `localStorage`, restored after the first render so the server's
 * HTML (always expanded, no recent commands) hydrates without a mismatch.
 */
@Injectable({ providedIn: 'root' })
export class ShellPreferences {
  private readonly storage = inject(SHELL_STORAGE);

  /** Bind to `vig-sidebar` with `[(collapsed)]`. */
  readonly collapsed = signal(false);
  /** Ids of recently run commands, most recent first. */
  readonly recent = signal<readonly string[]>([]);
  /** Whether the stored state has been applied (after the first render). */
  readonly restored = signal(false);

  constructor() {
    afterNextRender(() => {
      const stored = this.read();
      if (typeof stored.collapsed === 'boolean') this.collapsed.set(stored.collapsed);
      if (Array.isArray(stored.recent)) {
        this.recent.set(
          stored.recent.filter((id) => typeof id === 'string').slice(0, RECENT_LIMIT),
        );
      }
      this.restored.set(true);
    });
    effect(() => {
      const value: StoredPreferences = { collapsed: this.collapsed(), recent: [...this.recent()] };
      if (this.restored()) this.write(value);
    });
  }

  /** Records a run command as the most recent one. */
  remember(id: string): void {
    this.recent.update((ids) =>
      [id, ...ids.filter((other) => other !== id)].slice(0, RECENT_LIMIT),
    );
  }

  private read(): StoredPreferences {
    try {
      const parsed: unknown = JSON.parse(this.storage?.getItem(KEY) ?? '{}');
      return parsed && typeof parsed === 'object' ? (parsed as StoredPreferences) : {};
    } catch {
      return {};
    }
  }

  private write(value: StoredPreferences): void {
    try {
      this.storage?.setItem(KEY, JSON.stringify(value));
    } catch {
      // Full or blocked storage: the preference lasts for this visit only.
    }
  }
}
```

```typescript title="data-access/shell-preferences.spec.ts"
import { ApplicationRef, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';

import { PeopleSearch, PEOPLE_SEARCH_LATENCY } from './people-search';
import { SHELL_NAV, shellLinks } from './shell-nav';
import { RECENT_LIMIT, SHELL_STORAGE, ShellPreferences } from './shell-preferences';

/** A `Storage` stand-in that can also fail like a blocked one. */
function memoryStorage(initial: Record<string, string> = {}) {
  const data = new Map(Object.entries(initial));
  return {
    data,
    failing: false,
    getItem(key: string) {
      if (this.failing) throw new Error('blocked');
      return data.get(key) ?? null;
    },
    setItem(key: string, value: string) {
      if (this.failing) throw new Error('blocked');
      data.set(key, value);
    },
  };
}

describe('ShellPreferences', () => {
  async function setup(storage: ReturnType<typeof memoryStorage> | null) {
    TestBed.configureTestingModule({
      providers: [provideZonelessChangeDetection(), { provide: SHELL_STORAGE, useValue: storage }],
    });
    const preferences = TestBed.inject(ShellPreferences);
    // afterNextRender runs with the next application render.
    TestBed.inject(ApplicationRef).tick();
    await TestBed.inject(ApplicationRef).whenStable();
    return preferences;
  }

  it('restores the stored state after the first render and saves changes', async () => {
    const storage = memoryStorage({
      'app-shell': JSON.stringify({ collapsed: true, recent: ['a', 1, 'b'] }),
    });
    const preferences = await setup(storage);
    expect(preferences.collapsed()).toBe(true);
    expect(preferences.recent()).toEqual(['a', 'b']);

    preferences.collapsed.set(false);
    preferences.remember('c');
    TestBed.tick();
    expect(JSON.parse(storage.data.get('app-shell') ?? '')).toEqual({
      collapsed: false,
      recent: ['c', 'a', 'b'],
    });
  });

  it('keeps the most recent commands first, without duplicates, up to the limit', async () => {
    const preferences = await setup(memoryStorage());
    for (const id of ['a', 'b', 'c', 'a', 'd', 'e', 'f']) preferences.remember(id);
    expect(preferences.recent()).toEqual(['f', 'e', 'd', 'a', 'c']);
    expect(preferences.recent()).toHaveLength(RECENT_LIMIT);
  });

  it('starts from the defaults with malformed, missing or blocked storage', async () => {
    expect((await setup(memoryStorage({ 'app-shell': '{oops' }))).collapsed()).toBe(false);
    TestBed.resetTestingModule();
    expect((await setup(memoryStorage({ 'app-shell': 'null' }))).recent()).toEqual([]);
    TestBed.resetTestingModule();
    const none = await setup(null);
    none.collapsed.set(true);
    TestBed.tick();
    expect(none.collapsed()).toBe(true);
    TestBed.resetTestingModule();
    const blocked = memoryStorage();
    blocked.failing = true;
    const preferences = await setup(blocked);
    preferences.remember('x');
    TestBed.tick();
    expect(preferences.recent()).toEqual(['x']);
  });
});

describe('PeopleSearch', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        { provide: PEOPLE_SEARCH_LATENCY, useValue: 0 },
      ],
    });
  });

  it('finds people by name or email', async () => {
    const search = TestBed.inject(PeopleSearch);
    const found = await search.find('grace', new AbortController().signal);
    expect(found.map((p) => p.name)).toEqual(['Grace Hopper']);
    expect((await search.find('northwind', new AbortController().signal)).length).toBe(4);
  });

  it('rejects when aborted', async () => {
    const controller = new AbortController();
    const pending = TestBed.inject(PeopleSearch).find('ada', controller.signal);
    controller.abort(new Error('stale'));
    await expect(pending).rejects.toThrow('stale');
  });
});

describe('SHELL_NAV', () => {
  it('has unique paths and a start page', () => {
    const paths = shellLinks(SHELL_NAV).map((link) => link.path);
    expect(new Set(paths).size).toBe(paths.length);
    expect(paths).toContain('');
  });
});
```

````typescript title="feature/app-shell.routes.ts"
import type { Route, Routes } from '@angular/router';

import { SHELL_NAV, shellLinks } from '../data-access/shell-nav';

/**
 * The shell as a layout route: `AppShell` renders the sidebar, top bar and
 * command menu once, and the pages below it in its `<router-outlet>`. Route
 * data reaches the components as inputs, which needs
 * `withComponentInputBinding()` in `provideRouter`. Mount it at the root:
 *
 * ```ts
 * export const routes: Routes = [{ path: '', children: appShellRoutes }];
 * ```
 */
export const appShellRoutes: Routes = [
  {
    path: '',
    loadComponent: () => import('./app-shell').then((m) => m.AppShell),
    children: shellLinks(SHELL_NAV).map(
      (link): Route => ({
        path: link.path,
        pathMatch: link.path ? 'prefix' : 'full',
        title: link.label,
        data: { heading: link.label },
        loadComponent: () => import('./shell-page').then((m) => m.ShellPage),
      }),
    ),
  },
];
````

```typescript title="feature/app-shell.ts"
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  afterRenderEffect,
  booleanAttribute,
  computed,
  inject,
  input,
  signal,
  viewChild,
} from '@angular/core';
import { ActivatedRoute, Router, RouterOutlet } from '@angular/router';
import { CommandMenu, type CommandItem, type CommandSearch } from '@vigdx/ui/command-menu';
import { Sidebar, SidebarFooter, SidebarHeader, SidebarItem } from '@vigdx/ui/sidebar';

import { PeopleSearch } from '../data-access/people-search';
import { SHELL_NAV } from '../data-access/shell-nav';
import { ShellPreferences } from '../data-access/shell-preferences';
import { ShellSidebarNav } from '../ui/shell-sidebar-nav';
import { TopBar } from '../ui/top-bar';

/** Texts of the shell; pass a translated copy as `labels`. */
export const APP_SHELL_TEXT = {
  appName: 'Northwind',
  goTo: 'Go to',
  actions: 'Actions',
  people: 'People',
  collapseSidebar: 'Collapse sidebar',
  expandSidebar: 'Expand sidebar',
  help: 'Help',
  newTab: '(opens in a new tab)',
  content: 'App content',
};

/**
 * The application layout: sidebar, top bar, content and the command menu,
 * rendered once around every page. The sidebar collapses to a rail (the
 * choice is remembered) and becomes a drawer on narrow screens; the command
 * menu goes to any page, runs actions and searches people on the server.
 */
@Component({
  selector: 'app-shell',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    RouterOutlet,
    CommandMenu,
    Sidebar,
    SidebarHeader,
    SidebarFooter,
    SidebarItem,
    ShellSidebarNav,
    TopBar,
  ],
  host: { class: 'flex h-dvh max-h-full min-h-0 bg-app text-foreground' },
  template: `
    <!-- No width animation until the restored state has rendered: a
         collapsed rail must not slide shut on every load. -->
    <vig-sidebar
      #sidebar
      [(collapsed)]="preferences.collapsed"
      [style.transition]="ready() ? null : 'none'"
    >
      <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"
          >N</span
        >
        @if (!preferences.collapsed() || sidebar.layout() === 'drawer') {
          <span class="truncate font-semibold">{{ text.appName }}</span>
        }
      </vig-sidebar-header>
      <app-shell-sidebar-nav [sections]="sections" />
      <vig-sidebar-footer>
        <a
          vigSidebarItem
          href="https://vigdx.com"
          target="_blank"
          rel="noopener"
          icon="external-link"
          >{{ text.help }}<span class="sr-only"> {{ text.newTab }}</span></a
        >
      </vig-sidebar-footer>
    </vig-sidebar>

    <div class="flex min-w-0 flex-1 flex-col">
      <app-top-bar [sidebar]="sidebar" [title]="text.appName" (searchRequested)="openMenu()" />
      <!-- A <main> landmark in an app; the docs embed it in its own main. -->
      @if (embedded()) {
        <div
          role="region"
          [attr.aria-label]="text.content"
          class="min-h-0 flex-1 overflow-y-auto p-6"
        >
          <router-outlet />
        </div>
      } @else {
        <main class="min-h-0 flex-1 overflow-y-auto p-6">
          <router-outlet />
        </main>
      }
    </div>

    <vig-command-menu
      [(open)]="menuOpen"
      [commands]="commands()"
      [search]="searchPeople"
      [recent]="preferences.recent()"
      (executed)="preferences.remember($event.id)"
    />
  `,
})
export class AppShell {
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);
  private readonly people = inject(PeopleSearch);
  protected readonly preferences = inject(ShellPreferences);

  /** Set by the docs, which show the shell inside their own `<main>`. */
  readonly embedded = input(false, { transform: booleanAttribute });

  protected readonly text = APP_SHELL_TEXT;
  protected readonly sections = SHELL_NAV;
  protected readonly menuOpen = signal(false);
  private readonly sidebar = viewChild.required(Sidebar);
  private readonly sidebarElement = viewChild.required(Sidebar, { read: ElementRef });
  /** Whether the sidebar may animate: the restored state has been painted. */
  protected readonly ready = signal(false);

  constructor() {
    afterRenderEffect(() => {
      if (!this.preferences.restored() || this.ready()) return;
      // The restored width has rendered with the transition off; reading
      // its style commits it before the transition comes back.
      void getComputedStyle(this.sidebarElement().nativeElement).width;
      this.ready.set(true);
    });
  }

  /** Every page as a "go to" command, plus the shell's own actions. */
  protected readonly commands = computed<CommandItem[]>(() => [
    ...this.sections.flatMap((section) =>
      section.links.map(
        (link): CommandItem => ({
          id: `go:${link.path || 'home'}`,
          label: link.label,
          group: this.text.goTo,
          icon: link.icon,
          keywords: [section.heading, ...(link.keywords ?? [])],
          run: () => void this.router.navigate([link.path], { relativeTo: this.route }),
        }),
      ),
    ),
    {
      id: 'toggle-sidebar',
      label: this.preferences.collapsed() ? this.text.expandSidebar : this.text.collapseSidebar,
      group: this.text.actions,
      icon: 'menu',
      keywords: ['navigation', 'rail'],
      run: () => this.sidebar().toggle(),
    },
  ]);

  /** Server results while typing; the menu debounces and aborts stale calls. */
  protected readonly searchPeople: CommandSearch = async (query, signal) =>
    (await this.people.find(query, signal)).map(
      (person): CommandItem => ({
        id: `person:${person.id}`,
        label: person.name,
        group: this.text.people,
        icon: 'user',
        keywords: [person.email],
        run: () =>
          void this.router.navigate(['reports/customers'], {
            relativeTo: this.route,
            queryParams: { q: person.name },
          }),
      }),
    );

  protected openMenu(): void {
    this.menuOpen.set(true);
  }
}
```

```typescript title="feature/app-shell.spec.ts"
import { ApplicationRef, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Router, provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideVigdxUi } from '@vigdx/ui/core';

import { PEOPLE_SEARCH_LATENCY } from '../data-access/people-search';
import { SHELL_STORAGE, ShellPreferences } from '../data-access/shell-preferences';
import { appShellRoutes } from './app-shell.routes';

describe('AppShell', () => {
  let harness: RouterTestingHarness;
  let stored: Map<string, string>;

  beforeEach(async () => {
    // jsdom has no modal <dialog>; the kit opens dialogs with showModal().
    HTMLDialogElement.prototype.showModal ??= function (this: HTMLDialogElement) {
      this.setAttribute('open', '');
    };
    HTMLDialogElement.prototype.close ??= function (this: HTMLDialogElement) {
      this.removeAttribute('open');
      this.dispatchEvent(new Event('close'));
    };
    Element.prototype.scrollIntoView ??= () => undefined;
    stored = new Map();
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        provideVigdxUi(),
        provideRouter([{ path: 'app', children: appShellRoutes }], withComponentInputBinding()),
        { provide: PEOPLE_SEARCH_LATENCY, useValue: 0 },
        {
          provide: SHELL_STORAGE,
          useValue: {
            getItem: (key: string) => stored.get(key) ?? null,
            setItem: (key: string, value: string) => stored.set(key, value),
          },
        },
      ],
    });
    harness = await RouterTestingHarness.create();
  });

  async function settle(): Promise<void> {
    for (let i = 0; i < 3; i++) {
      await new Promise((resolve) => setTimeout(resolve));
      await TestBed.inject(ApplicationRef).whenStable();
    }
  }

  async function open(url: string): Promise<HTMLElement> {
    await harness.navigateByUrl(url);
    await settle();
    return harness.routeNativeElement as HTMLElement;
  }

  function type(el: HTMLElement, text: string): void {
    const input = el.querySelector<HTMLInputElement>('input[role="combobox"]') as HTMLInputElement;
    input.value = text;
    input.dispatchEvent(new Event('input'));
  }

  function key(el: HTMLElement, name: string): void {
    el.querySelector('input[role="combobox"]')?.dispatchEvent(
      new KeyboardEvent('keydown', { key: name, bubbles: true, cancelable: true }),
    );
  }

  it('renders the sidebar, top bar and the routed page in a main landmark', async () => {
    const el = await open('/app/inbox');
    expect(el.querySelector('vig-sidebar nav')?.getAttribute('aria-label')).toBe('Main');
    expect(el.querySelector('main h2')?.textContent).toBe('Inbox');
    expect(el.querySelector('a[aria-current="page"]')?.textContent?.trim()).toBe('Inbox');
    expect(el.querySelector('dialog[aria-label="Command menu"]')).not.toBeNull();
  });

  it('opens the command menu from the top bar and goes to a page', async () => {
    const el = await open('/app');
    const search = el.querySelector<HTMLButtonElement>(
      'button[aria-keyshortcuts]',
    ) as HTMLButtonElement;
    search.click();
    await settle();
    expect(el.querySelector('dialog')?.hasAttribute('open')).toBe(true);
    type(el, 'sales');
    await settle();
    key(el, 'Enter');
    await settle();
    expect(TestBed.inject(Router).url).toBe('/app/reports/sales');
    expect(el.querySelector('main h2')?.textContent).toBe('Sales');
    expect(TestBed.inject(ShellPreferences).recent()).toEqual(['go:reports/sales']);
  });

  it('finds people on the server and opens them', async () => {
    const el = await open('/app');
    el.querySelector<HTMLButtonElement>('button[aria-keyshortcuts]')?.click();
    await settle();
    type(el, 'grace');
    await new Promise((resolve) => setTimeout(resolve, 300));
    await settle();
    const options = Array.from(el.querySelectorAll('[role="option"]')).map((o) =>
      o.textContent?.trim(),
    );
    expect(options).toEqual(['Grace Hopper']);
    key(el, 'Enter');
    await settle();
    expect(TestBed.inject(Router).url).toBe('/app/reports/customers?q=Grace%20Hopper');
    expect(el.querySelector('main')?.textContent).toContain('Showing Grace Hopper.');
  });

  it('collapses the sidebar from a command and remembers it', async () => {
    const el = await open('/app');
    el.querySelector<HTMLButtonElement>('button[aria-keyshortcuts]')?.click();
    await settle();
    type(el, 'collapse');
    await settle();
    key(el, 'Enter');
    await settle();
    expect(el.querySelector('vig-sidebar')?.getAttribute('data-state')).toBe('collapsed');
    expect(JSON.parse(stored.get('app-shell') ?? '{}')).toMatchObject({ collapsed: true });
    // The brand name gives way to the rail.
    expect(el.querySelector('vig-sidebar-header')?.textContent?.trim()).toBe('N');
  });

  it('restores a collapsed sidebar without animating it', async () => {
    stored.set('app-shell', JSON.stringify({ collapsed: true }));
    // Attribute changes on the sidebar, in order: rendered as `[name, value]`.
    const changes: [string, string | null][] = [];
    const observer = new MutationObserver((records) => {
      for (const record of records) {
        const target = record.target as HTMLElement;
        if (target.localName !== 'vig-sidebar' || !record.attributeName) continue;
        changes.push([record.attributeName, target.getAttribute(record.attributeName)]);
      }
    });
    observer.observe(harness.fixture.nativeElement, { subtree: true, attributes: true });
    const el = await open('/app');
    observer.disconnect();
    const sidebar = el.querySelector<HTMLElement>('vig-sidebar') as HTMLElement;
    expect(sidebar.getAttribute('data-state')).toBe('collapsed');
    // The rail appeared while the transition was off; it came back after.
    const collapsed = changes.findIndex(([name]) => name === 'data-state');
    const animatable = changes.findIndex(([name], i) => name === 'style' && i > collapsed);
    expect(collapsed).toBeGreaterThan(-1);
    expect(animatable).toBeGreaterThan(collapsed);
    expect(sidebar.style.transition).toBe('');
  });

  it('uses a labelled region instead of main when embedded', async () => {
    TestBed.inject(Router).resetConfig([
      { path: 'app', data: { embedded: true }, children: appShellRoutes },
    ]);
    const el = await open('/app/documents');
    expect(el.querySelector('main')).toBeNull();
    expect(el.querySelector('[role="region"][aria-label="App content"] h2')?.textContent).toBe(
      'Documents',
    );
  });
});
```

```typescript title="feature/shell-page.ts"
import { ChangeDetectionStrategy, Component, input } from '@angular/core';

/**
 * Stand-in for a feature page under the shell. In an app each link of
 * `SHELL_NAV` loads its own feature routes instead.
 */
@Component({
  selector: 'app-shell-page',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'flex flex-col gap-2' },
  template: `
    <h2 class="text-h3 text-foreground">{{ heading() }}</h2>
    @if (q(); as person) {
      <p class="text-sm text-foreground-soft">Showing {{ person }}.</p>
    } @else {
      <p class="text-sm text-muted-foreground">
        Content of the {{ heading() }} page. Press Ctrl K (⌘K on a Mac) or the search button to jump
        anywhere.
      </p>
    }
  `,
})
export class ShellPage {
  /** From the route's `data` (`withComponentInputBinding()`). */
  readonly heading = input('');
  /** From the `q` query parameter, set by a people search result. */
  readonly q = input<string | undefined>(undefined);
}
```

```typescript title="ui/shell-sidebar-nav.ts"
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { SidebarGroup, SidebarItem, SidebarNav } from '@vigdx/ui/sidebar';

import type { ShellSection } from '../data-access/shell-nav';

/**
 * The sidebar's navigation, from data. Each link is a real `<a routerLink>`;
 * `routerLinkActive` marks the current page with `aria-current="page"`
 * (`ariaCurrentWhenActive`), which the kit styles. Links are relative to the
 * shell's route, so the feature works under any path.
 */
@Component({
  selector: 'app-shell-sidebar-nav',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [RouterLink, RouterLinkActive, SidebarNav, SidebarGroup, SidebarItem],
  host: { class: 'flex min-h-0 flex-1 flex-col' },
  template: `
    <vig-sidebar-nav [ariaLabel]="ariaLabel()">
      @for (section of sections(); track section.heading) {
        <vig-sidebar-group [heading]="section.heading" [collapsible]="!!section.collapsible">
          @for (link of section.links; track link.path) {
            <a
              vigSidebarItem
              [routerLink]="link.path || './'"
              routerLinkActive
              [routerLinkActiveOptions]="{ exact: !link.path }"
              ariaCurrentWhenActive="page"
              [icon]="link.icon"
              >{{ link.label }}</a
            >
          }
        </vig-sidebar-group>
      }
    </vig-sidebar-nav>
  `,
})
export class ShellSidebarNav {
  readonly sections = input.required<readonly ShellSection[]>();
  /** Name of the `<nav>` landmark; the kit's "Main" by default. */
  readonly ariaLabel = input<string | undefined>(undefined);
}
```

```typescript title="ui/shell-sidebar-nav.spec.ts"
import { Component, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideVigdxUi } from '@vigdx/ui/core';
import { Sidebar } from '@vigdx/ui/sidebar';

import { SHELL_NAV } from '../data-access/shell-nav';
import { ShellSidebarNav } from './shell-sidebar-nav';

@Component({
  imports: [Sidebar, ShellSidebarNav],
  template: `
    <vig-sidebar><app-shell-sidebar-nav [sections]="sections" ariaLabel="App" /></vig-sidebar>
  `,
})
class Layout {
  readonly sections = SHELL_NAV;
}

@Component({ template: '' })
class Blank {}

describe('ShellSidebarNav', () => {
  let harness: RouterTestingHarness;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        provideVigdxUi(),
        provideRouter([
          { path: 'app', component: Layout, children: [{ path: '**', component: Blank }] },
        ]),
      ],
    });
    harness = await RouterTestingHarness.create();
  });

  const links = () =>
    Array.from(
      (harness.routeNativeElement as HTMLElement).querySelectorAll<HTMLAnchorElement>('a'),
    );
  const current = () =>
    links()
      .filter((link) => link.getAttribute('aria-current') === 'page')
      .map((link) => link.textContent?.trim());

  it('renders the sections as named groups of links relative to the shell', async () => {
    await harness.navigateByUrl('/app');
    const el = harness.routeNativeElement as HTMLElement;
    expect(el.querySelector('nav')?.getAttribute('aria-label')).toBe('App');
    expect(el.querySelectorAll('[role="group"]')).toHaveLength(2);
    expect(links().map((link) => link.getAttribute('href'))).toEqual([
      '/app',
      '/app/inbox',
      '/app/documents',
      '/app/reports/sales',
      '/app/reports/customers',
    ]);
    // The second section is a disclosure.
    expect(
      el.querySelector('[data-scope="sidebar"][data-part="group-trigger"]')?.textContent?.trim(),
    ).toBe('Reports');
  });

  it('marks exactly the current page', async () => {
    await harness.navigateByUrl('/app');
    expect(current()).toEqual(['Dashboard']);
    await harness.navigateByUrl('/app/reports/sales');
    expect(current()).toEqual(['Sales']);
  });
});
```

```typescript title="ui/top-bar.ts"
import { DOCUMENT } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  afterNextRender,
  inject,
  input,
  output,
  signal,
} from '@angular/core';
import { Icon } from '@vigdx/ui/icon';
import { type Sidebar, SidebarTrigger } from '@vigdx/ui/sidebar';

/** Texts of the top bar; pass a translated copy as `labels`. */
export interface TopBarLabels {
  /** Name of the sidebar toggle. */
  menu: string;
  search: string;
}

export const TOP_BAR_LABELS: TopBarLabels = { menu: 'Toggle navigation', search: 'Search' };

/**
 * The bar above the content: the sidebar trigger (it collapses the rail on
 * wide screens and opens the drawer on narrow ones), the section title and
 * the button that opens the command menu. The shortcut hint is decorative;
 * `aria-keyshortcuts` announces it.
 */
@Component({
  selector: 'app-top-bar',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Icon, SidebarTrigger],
  host: {
    class:
      'flex min-h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-3 text-foreground',
  },
  template: `
    <button type="button" [vigSidebarTrigger]="sidebar()">
      <vig-icon name="menu" class="text-[1.25em]" />
      <span class="sr-only">{{ labels().menu }}</span>
    </button>
    <span class="min-w-0 truncate font-semibold">{{ title() }}</span>
    <button
      type="button"
      aria-haspopup="dialog"
      aria-keyshortcuts="Control+K Meta+K"
      (click)="searchRequested.emit()"
      class="ms-auto inline-flex min-h-9 cursor-pointer items-center gap-2 rounded-button border border-border-control bg-background px-3 text-sm text-muted-foreground hover:bg-subtle hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
    >
      <vig-icon name="search" class="text-[1.25em]" />
      <span>{{ labels().search }}</span>
      <kbd aria-hidden="true" class="hidden font-mono text-xs sm:inline">{{
        mac() ? '⌘K' : 'Ctrl K'
      }}</kbd>
    </button>
  `,
})
export class TopBar {
  private readonly document = inject(DOCUMENT);

  /** The sidebar the trigger controls. */
  readonly sidebar = input.required<Sidebar>();
  readonly title = input('');
  readonly labels = input<TopBarLabels>(TOP_BAR_LABELS);
  /** The search button was pressed: open the command menu. */
  readonly searchRequested = output<void>();

  /** Whether the hint reads ⌘K; known in the browser only. */
  protected readonly mac = signal(false);

  constructor() {
    afterNextRender(() => {
      const nav = this.document.defaultView?.navigator as
        | (Navigator & { userAgentData?: { platform?: string } })
        | undefined;
      this.mac.set(/mac|iphone|ipad/i.test(nav?.userAgentData?.platform ?? nav?.platform ?? ''));
    });
  }
}
```

```typescript title="ui/top-bar.spec.ts"
import { Component, provideZonelessChangeDetection, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideVigdxUi } from '@vigdx/ui/core';
import { Sidebar } from '@vigdx/ui/sidebar';

import { TopBar } from './top-bar';

@Component({
  imports: [Sidebar, TopBar],
  template: `
    <app-top-bar
      [sidebar]="sidebar"
      title="Northwind"
      (searchRequested)="searches.set(searches() + 1)"
    />
    <vig-sidebar #sidebar [(collapsed)]="collapsed" />
  `,
})
class Host {
  readonly collapsed = signal(false);
  readonly searches = signal(0);
}

describe('TopBar', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideZonelessChangeDetection(), provideVigdxUi()],
    });
  });

  async function render() {
    const fixture = TestBed.createComponent(Host);
    await fixture.whenStable();
    const el = fixture.nativeElement as HTMLElement;
    const buttons = Array.from(el.querySelectorAll<HTMLButtonElement>('app-top-bar button'));
    return { fixture, el, trigger: buttons[0], search: buttons[1] };
  }

  it('toggles the sidebar with a named trigger', async () => {
    const { fixture, trigger } = await render();
    expect(trigger.textContent?.trim()).toBe('Toggle navigation');
    expect(trigger.getAttribute('aria-expanded')).toBe('true');
    trigger.click();
    await fixture.whenStable();
    expect(fixture.componentInstance.collapsed()).toBe(true);
    expect(trigger.getAttribute('aria-expanded')).toBe('false');
  });

  it('asks for the command menu and announces the shortcut', async () => {
    const { fixture, search, el } = await render();
    expect(el.textContent).toContain('Northwind');
    expect(search.textContent).toContain('Search');
    expect(search.getAttribute('aria-keyshortcuts')).toBe('Control+K Meta+K');
    expect(search.getAttribute('aria-haspopup')).toBe('dialog');
    expect(search.querySelector('kbd')?.getAttribute('aria-hidden')).toBe('true');
    expect(search.querySelector('kbd')?.textContent?.trim()).toBe('Ctrl K');
    search.click();
    expect(fixture.componentInstance.searches()).toBe(1);
  });

  it('shows the Apple shortcut on Apple platforms', async () => {
    const platform = vi.spyOn(navigator, 'platform', 'get').mockReturnValue('MacIntel');
    const { search } = await render();
    expect(search.querySelector('kbd')?.textContent?.trim()).toBe('⌘K');
    platform.mockRestore();
  });
});
```
