# Master-detail

A list and a detail view driven by the URL: the detail sits beside the list in a wide container and opens in a `vig-drawer` in a narrow one, decided by a container query rather than the viewport, with focus following the selection.

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

## Live demo

Pick a ticket: the URL gets `?ticket=` and focus moves to the ticket's heading. Narrow the demo's container to get the drawer layout without resizing the window.

A list of records with the selected record's detail. The selection lives in the URL
(`?ticket=T-1042`). Where the page has room, the detail sits beside the list; in a narrow space it
opens in a drawer. The page decides by its own width (a container query), not the viewport's, so it
works the same in a sidebar layout, a split view or full screen.

## When to use

- Users scan a list and read one item at a time: inboxes, support tickets, orders, logs.
- The detail is read more than edited; for editing, link to a form page (see the `form-page`
  recipe).
- For a table with many columns where rows are compared, use the `crud-list` recipe and open the
  detail from a row action instead.

## Component choices

| Need                                | Component                                         | Why                                                                                                                                  | Alternatives                                                              |
| ----------------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------- |
| The list                            | A list of links (`routerLink` with `queryParams`) | Selection is navigation: the URL updates, back and forward work, middle-click opens a new tab; `aria-current` marks the selected one | `vig-table` with `selectionMode="single"` when the list needs columns     |
| Status                              | `vig-badge`                                       | Text plus color, never color alone                                                                                                   | `vig-chip` when the user can remove it                                    |
| Detail beside the list              | A `section` named "Ticket details"                | Stays in the reading order after the list                                                                                            | —                                                                         |
| Detail on narrow screens            | `vig-drawer`                                      | Native modal: focus moves in, Escape and the backdrop close it, focus returns to the link                                            | A separate detail route (`/tickets/:id`) that replaces the list on phones |
| Nothing selected, not found, errors | `vig-empty-state`                                 | Explains the state, offers a retry where it helps                                                                                    | —                                                                         |
| Loading                             | `vig-skeleton`                                    | Keeps the layout stable while data arrives                                                                                           | `vig-spinner` for short waits without layout                              |

## Folder structure

### Angular CLI

```text
src/app/features/tickets/
  data-access/
    ticket.ts                  TicketSummary for the list, Ticket for the detail
    tickets-api.ts             abstract API = DI token, TicketNotFoundError
    http-tickets-api.ts
    in-memory-tickets-api.ts
    tickets-store.ts           list, selected id, selected ticket
  feature/
    tickets-page.ts            routed smart page: URL, layout, focus
    tickets.routes.ts
  ui/
    ticket-labels.ts           texts and badge variants
    ticket-list.ts             presentational list of links
    ticket-detail.ts           presentational detail
```

```ts title="app.routes.ts"
{
  path: 'tickets',
  providers: [{ provide: TicketsApi, useClass: HttpTicketsApi }],
  loadChildren: () =>
    import('./features/tickets/feature/tickets.routes').then((m) => m.ticketsRoutes),
}
```

The `ticket` query parameter reaches the page's `ticket` input through `withComponentInputBinding()`
in `provideRouter`.

### Nx

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

## Key decisions

- **The URL owns the selection.** Picking a ticket is a link to `?ticket=<id>`; the page mirrors the
  query parameter into the store, which loads that ticket. Reloading, sharing the URL and the back
  button all restore the same view. A query parameter (rather than `/tickets/:id`) keeps the list
  component alive while the selection changes; with a path parameter, use one route whose component
  reads an optional `:id` child param the same way.
- **Light list, full detail.** The list endpoint returns `TicketSummary` objects; the detail loads
  the full `Ticket` by id. The store holds both as `rxResource`s; deselecting idles the detail.
- **Container query, not viewport.** The grid switches to two columns with Tailwind's `@3xl`
  container variant (48rem) on the page's own `@container`. The drawer needs the same answer in
  code, so a `ResizeObserver` on the page compares its width with `WIDE_LAYOUT_MIN_WIDTH_REM`
  (also 48rem). On the server, without `ResizeObserver`, the wide layout renders.
- **One detail template, two places.** The detail states (none selected, loading, not found, error,
  loaded) are written once in an `ng-template` and rendered either in the side pane or in the
  drawer.
- **Closing the drawer clears the selection.** Escape, the close button and the backdrop all end in
  `openChange(false)`, which removes `?ticket` from the URL. Growing the container while a ticket is
  open simply moves the detail out of the drawer.

## Accessibility

- Each ticket is a real link, the selected one has `aria-current="true"`, and the selected state is
  shown by a border as well as a tint, so it survives forced-colors mode.
- After a pick, focus moves to the detail's heading (`tabindex="-1"`), so screen readers start
  reading the new content and keyboard users continue from there; in the drawer the native dialog
  moves focus and returns it to the link on close.
- The list and the detail are named sections; loading skeletons sit in a named `role="status"`
  container.
- Error states say what failed and offer a retry in user-facing texts (`TICKETS_PAGE_TEXT`); the
  technical `error.message` stays out of the UI.
- Dates are `<time datetime>` elements; badges carry text.

## Performance

- `track ticket.id` keeps list items stable across reloads.
- Only the selected ticket's body is loaded; the list stays small.
- `OnPush` everywhere; the layout signal changes only when the width crosses the breakpoint.
- The feature is lazy-loaded; consider `@defer (on viewport)` for heavy detail parts such as
  attachments or history.

## Definition of done

- [ ] `nx build <app>` (or `ng build`) succeeds; `nx lint` passes.
- [ ] The specs pass: list, selection from the URL, focus after picking, not found, list error and
      retry, the narrow layout in a drawer, closing it clears the URL.
- [ ] axe reports no violations in the wide and the narrow layout (drawer open), light and dark.
- [ ] Keyboard only: tab to a ticket, open it, read it, go back to the list; in the narrow layout
      close the drawer with Escape and land on the same link.
- [ ] Reload with `?ticket=` in the URL shows that ticket; back and forward move between selections.

## Source files

```typescript title="data-access/http-tickets-api.ts"
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { type Observable, catchError, throwError } from 'rxjs';

import type { Ticket, TicketSummary } from './ticket';
import { TicketNotFoundError, type TicketsApi } from './tickets-api';

/** Base URL of the tickets resource; adapt it to your backend. */
export const TICKETS_URL = '/api/tickets';

/** `TicketsApi` over HTTP. Needs `provideHttpClient()` in the application config. */
@Injectable()
export class HttpTicketsApi implements TicketsApi {
  private readonly http = inject(HttpClient);

  list(): Observable<TicketSummary[]> {
    return this.http.get<TicketSummary[]>(TICKETS_URL);
  }

  get(id: string): Observable<Ticket> {
    return this.http
      .get<Ticket>(`${TICKETS_URL}/${encodeURIComponent(id)}`)
      .pipe(
        catchError((error: unknown) =>
          throwError(() =>
            error instanceof HttpErrorResponse && error.status === 404
              ? new TicketNotFoundError(id)
              : error,
          ),
        ),
      );
  }
}
```

```typescript title="data-access/in-memory-tickets-api.ts"
import { Injectable, InjectionToken, inject, signal } from '@angular/core';
import { type Observable, map, timer } from 'rxjs';

import type { Ticket, TicketSummary } from './ticket';
import { TicketNotFoundError, type TicketsApi } from './tickets-api';

/** Simulated network latency of `InMemoryTicketsApi` in ms; tests set 0. */
export const TICKETS_API_LATENCY = new InjectionToken<number>('TICKETS_API_LATENCY', {
  factory: () => 300,
});

const TICKETS: Ticket[] = [
  {
    id: 'T-1042',
    subject: 'Invoice shows the wrong VAT rate',
    requester: 'Ada Lovelace',
    requesterEmail: 'ada@northwind.example',
    status: 'open',
    priority: 'urgent',
    updatedAt: '2026-11-14',
    body: 'Our November invoice applies 19% VAT, but we are registered in Austria.\n\nCould you reissue it with 20%? Our accounting closes on Friday.',
  },
  {
    id: 'T-1041',
    subject: 'Export to CSV misses the notes column',
    requester: 'Grace Hopper',
    requesterEmail: 'grace@contoso.example',
    status: 'pending',
    priority: 'normal',
    updatedAt: '2026-11-13',
    body: 'When I export the customer list, the notes column is empty in the CSV although every customer has notes on screen.',
  },
  {
    id: 'T-1040',
    subject: 'Add a second admin to our account',
    requester: 'Alan Turing',
    requesterEmail: 'alan@fabrikam.example',
    status: 'solved',
    priority: 'low',
    updatedAt: '2026-11-12',
    body: 'Please give Joan Clarke admin rights as well, so she can manage billing while I am away.',
  },
  {
    id: 'T-1039',
    subject: 'Dark mode turns charts unreadable',
    requester: 'Barbara Liskov',
    requesterEmail: 'barbara@tailspin.example',
    status: 'open',
    priority: 'normal',
    updatedAt: '2026-11-11',
    body: 'With the dark theme on, the line colors of the revenue chart are almost invisible on the background.\n\nScreenshots are attached to my previous email.',
  },
  {
    id: 'T-1038',
    subject: 'Password reset email never arrives',
    requester: 'Dennis Ritchie',
    requesterEmail: 'dennis@wingtip.example',
    status: 'pending',
    priority: 'urgent',
    updatedAt: '2026-11-10',
    body: 'I requested a password reset three times today. Nothing arrived, not even in the spam folder.',
  },
  {
    id: 'T-1037',
    subject: 'Feature request: keyboard shortcuts',
    requester: 'Margaret Hamilton',
    requesterEmail: 'margaret@litware.example',
    status: 'solved',
    priority: 'low',
    updatedAt: '2026-11-08',
    body: 'It would speed us up a lot to triage tickets with the keyboard: next, previous, assign to me.',
  },
];

function summary(ticket: Ticket): TicketSummary {
  const { id, subject, requester, status, priority, updatedAt } = ticket;
  return { id, subject, requester, status, priority, updatedAt };
}

/**
 * `TicketsApi` over a fixed in-memory list with simulated latency, for
 * demos, prototypes and tests. Deterministic: no clock, no randomness.
 */
@Injectable()
export class InMemoryTicketsApi implements TicketsApi {
  private readonly latency = inject(TICKETS_API_LATENCY);

  /** When true every request fails, to exercise the error states. */
  readonly failing = signal(false);

  list(): Observable<TicketSummary[]> {
    return this.respond(() => TICKETS.map(summary));
  }

  get(id: string): Observable<Ticket> {
    return this.respond(() => {
      const ticket = TICKETS.find((candidate) => candidate.id === id);
      if (!ticket) throw new TicketNotFoundError(id);
      return { ...ticket };
    });
  }

  private respond<T>(work: () => T): Observable<T> {
    return timer(this.latency).pipe(
      map(() => {
        if (this.failing()) throw new Error('The server is not responding.');
        return work();
      }),
    );
  }
}
```

```typescript title="data-access/ticket.ts"
export type TicketStatus = 'open' | 'pending' | 'solved';
export type TicketPriority = 'low' | 'normal' | 'urgent';

/** What the list shows of a ticket. */
export interface TicketSummary {
  id: string;
  subject: string;
  requester: string;
  status: TicketStatus;
  priority: TicketPriority;
  /** Calendar date of the last update, `YYYY-MM-DD`. */
  updatedAt: string;
}

/** The full ticket for the detail view. */
export interface Ticket extends TicketSummary {
  requesterEmail: string;
  /** The request as the customer wrote it, paragraphs separated by blank lines. */
  body: string;
}
```

````typescript title="data-access/tickets-api.ts"
import type { Observable } from 'rxjs';

import type { Ticket, TicketSummary } from './ticket';

/**
 * The tickets backend as the master-detail screen needs it: a light list and
 * one full ticket at a time. The abstract class is the DI token:
 *
 * ```ts
 * providers: [{ provide: TicketsApi, useClass: HttpTicketsApi }]
 * ```
 */
export abstract class TicketsApi {
  abstract list(): Observable<TicketSummary[]>;
  /** Errors with `TicketNotFoundError` when there is no such ticket. */
  abstract get(id: string): Observable<Ticket>;
}

export class TicketNotFoundError extends Error {
  constructor(readonly id: string) {
    super(`Ticket ${id} does not exist.`);
    this.name = 'TicketNotFoundError';
  }
}
````

```typescript title="data-access/tickets-store.ts"
import { Injectable, type Signal, computed, inject, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs-interop';

import { TicketNotFoundError, TicketsApi } from './tickets-api';

/**
 * State of the tickets screen: the list, the selected ticket's id (the page
 * connects it to the URL) and that ticket in full. Provided by the page.
 */
@Injectable()
export class TicketsStore {
  private readonly api = inject(TicketsApi);

  private readonly listResource = rxResource({ stream: () => this.api.list() });

  /** Where the selected id comes from; see {@link connect}. */
  private readonly source = signal<Signal<string | null>>(signal(null));
  readonly selectedId = computed(() => this.source()());

  private readonly ticketResource = rxResource({
    // No selection keeps the detail idle.
    params: () => this.selectedId() ?? undefined,
    stream: ({ params }) => this.api.get(params),
  });

  readonly tickets = computed(() =>
    this.listResource.hasValue() ? this.listResource.value() : [],
  );
  readonly listLoading = this.listResource.isLoading;
  readonly listError = this.listResource.error;

  /** The selected ticket once loaded; `null` while loading or without selection. */
  readonly ticket = computed(() =>
    this.ticketResource.hasValue() ? (this.ticketResource.value() ?? null) : null,
  );
  readonly ticketLoading = this.ticketResource.isLoading;
  readonly ticketError = computed(() =>
    this.ticketResource.error() instanceof TicketNotFoundError
      ? undefined
      : this.ticketResource.error(),
  );
  readonly ticketNotFound = computed(
    () => this.ticketResource.error() instanceof TicketNotFoundError,
  );

  /**
   * Follows the selected ticket's id — `null` for none — from a signal the
   * page owns (the URL), so the store derives what to load instead of being
   * told after every change.
   */
  connect(selectedId: Signal<string | null>): void {
    this.source.set(selectedId);
  }

  reloadList(): void {
    this.listResource.reload();
  }

  reloadTicket(): void {
    this.ticketResource.reload();
  }
}
```

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

import { InMemoryTicketsApi, TICKETS_API_LATENCY } from './in-memory-tickets-api';
import { TicketsApi } from './tickets-api';
import { TicketsStore } from './tickets-store';

describe('TicketsStore', () => {
  let store: TicketsStore;
  let api: InMemoryTicketsApi;
  /** Stands in for the page's `ticket` query parameter. */
  const selected = signal<string | null>(null);

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        TicketsStore,
        InMemoryTicketsApi,
        { provide: TicketsApi, useExisting: InMemoryTicketsApi },
        { provide: TICKETS_API_LATENCY, useValue: 0 },
      ],
    });
    store = TestBed.inject(TicketsStore);
    api = TestBed.inject(InMemoryTicketsApi);
    selected.set(null);
    store.connect(selected);
  });

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

  it('loads the list without a selection', async () => {
    const get = vi.spyOn(api, 'get');
    await settle();
    expect(store.tickets()).toHaveLength(6);
    expect(store.tickets()[0]).not.toHaveProperty('body');
    expect(store.ticket()).toBeNull();
    expect(get).not.toHaveBeenCalled();
  });

  it('loads the selected ticket in full and drops it when deselected', async () => {
    selected.set('T-1042');
    await settle();
    expect(store.ticket()?.requesterEmail).toBe('ada@northwind.example');

    selected.set(null);
    await settle();
    expect(store.ticket()).toBeNull();
  });

  it('tells a missing ticket from a failed request', async () => {
    selected.set('T-0');
    await settle();
    expect(store.ticketNotFound()).toBe(true);
    expect(store.ticketError()).toBeUndefined();

    api.failing.set(true);
    selected.set('T-1042');
    await settle();
    expect(store.ticketNotFound()).toBe(false);
    expect(store.ticketError()?.message).toBe('The server is not responding.');

    api.failing.set(false);
    store.reloadTicket();
    await settle();
    expect(store.ticket()?.id).toBe('T-1042');
  });
});
```

```typescript title="feature/tickets-page.ts"
import { DOCUMENT, NgTemplateOutlet } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  ElementRef,
  Injector,
  afterNextRender,
  computed,
  effect,
  inject,
  input,
  signal,
  untracked,
  viewChild,
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Button } from '@vigdx/ui/button';
import { Drawer } from '@vigdx/ui/drawer';
import { EmptyState, EmptyStateActions } from '@vigdx/ui/empty-state';
import { Skeleton } from '@vigdx/ui/skeleton';

import { TicketsStore } from '../data-access/tickets-store';
import { TicketDetail } from '../ui/ticket-detail';
import { TicketList } from '../ui/ticket-list';

/**
 * Width (in rem) from which the detail sits beside the list. Matches the
 * `@3xl` container variant (48rem) used for the grid below.
 */
export const WIDE_LAYOUT_MIN_WIDTH_REM = 48;

export const TICKETS_PAGE_TEXT = {
  title: 'Support tickets',
  list: 'Ticket list',
  detail: 'Ticket details',
  loadingList: 'Loading tickets',
  loadingTicket: 'Loading the ticket',
  listErrorTitle: 'Tickets could not be loaded',
  listErrorDescription: 'Check your connection and try again.',
  emptyTitle: 'No tickets',
  emptyDescription: 'New requests from customers show up here.',
  noSelectionTitle: 'No ticket selected',
  noSelectionDescription: 'Choose a ticket from the list to read it here.',
  notFoundTitle: 'Ticket not found',
  notFoundDescription: 'It may have been merged or deleted.',
  ticketErrorTitle: 'The ticket could not be loaded',
  ticketErrorDescription: 'Check your connection and try again.',
  drawerFallback: 'Ticket',
  retry: 'Try again',
};

/**
 * Master-detail screen. The selection lives in the URL (`?ticket=T-1042`,
 * bound to the `ticket` input). In a wide container the detail sits beside
 * the list; in a narrow one it opens in a drawer. When the user picks a
 * ticket, focus moves to its heading (the drawer moves focus itself).
 */
@Component({
  selector: 'app-tickets-page',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [TicketsStore],
  imports: [
    NgTemplateOutlet,
    Button,
    Drawer,
    EmptyState,
    EmptyStateActions,
    Skeleton,
    TicketDetail,
    TicketList,
  ],
  host: { class: 'block @container' },
  template: `
    <div class="flex flex-col gap-4">
      <h1 class="text-h2 text-foreground">{{ text.title }}</h1>

      <div class="grid items-start gap-4 @3xl:grid-cols-[minmax(16rem,22rem)_minmax(0,1fr)]">
        <section
          class="overflow-hidden rounded-card border border-border bg-background"
          [attr.aria-label]="text.list"
        >
          @if (store.listError()) {
            <vig-empty-state
              size="sm"
              icon="error"
              [headingLevel]="2"
              [heading]="text.listErrorTitle"
              [description]="text.listErrorDescription"
            >
              <div vigEmptyStateActions class="contents">
                <vig-button size="sm" [label]="text.retry" (click)="store.reloadList()" />
              </div>
            </vig-empty-state>
          } @else if (store.listLoading()) {
            <div class="flex flex-col gap-3 p-4" role="status" [attr.aria-label]="text.loadingList">
              <vig-skeleton [lines]="2" />
              <vig-skeleton [lines]="2" />
              <vig-skeleton [lines]="2" />
            </div>
          } @else if (store.tickets().length) {
            <app-ticket-list
              [tickets]="store.tickets()"
              [selectedId]="store.selectedId()"
              (activate)="focusRequest.set($event)"
            />
          } @else {
            <vig-empty-state
              size="sm"
              icon="inbox"
              [headingLevel]="2"
              [heading]="text.emptyTitle"
              [description]="text.emptyDescription"
            />
          }
        </section>

        @if (wide()) {
          <section
            class="rounded-card border border-border bg-background p-5"
            [attr.aria-label]="text.detail"
          >
            <ng-container *ngTemplateOutlet="detail" />
          </section>
        }
      </div>
    </div>

    <vig-drawer
      width="32rem"
      [open]="drawerOpen()"
      [heading]="store.ticket()?.id ?? text.drawerFallback"
      (openChange)="onDrawerOpenChange($event)"
    >
      @if (!wide()) {
        <ng-container *ngTemplateOutlet="detail" />
      }
    </vig-drawer>

    <ng-template #detail>
      @if (!store.selectedId()) {
        <vig-empty-state
          size="sm"
          icon="inbox"
          [headingLevel]="2"
          [heading]="text.noSelectionTitle"
          [description]="text.noSelectionDescription"
        />
      } @else if (store.ticketNotFound()) {
        <vig-empty-state
          size="sm"
          icon="search"
          [headingLevel]="2"
          [heading]="text.notFoundTitle"
          [description]="text.notFoundDescription"
        />
      } @else if (store.ticketError()) {
        <vig-empty-state
          size="sm"
          icon="error"
          [headingLevel]="2"
          [heading]="text.ticketErrorTitle"
          [description]="text.ticketErrorDescription"
        >
          <div vigEmptyStateActions class="contents">
            <vig-button size="sm" [label]="text.retry" (click)="store.reloadTicket()" />
          </div>
        </vig-empty-state>
      } @else if (store.ticket(); as ticket) {
        <app-ticket-detail [ticket]="ticket" />
      } @else {
        <div class="flex flex-col gap-3" role="status" [attr.aria-label]="text.loadingTicket">
          <vig-skeleton width="60%" />
          <vig-skeleton [lines]="4" />
        </div>
      }
    </ng-template>
  `,
})
export class TicketsPage {
  protected readonly store = inject(TicketsStore);
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);
  private readonly injector = inject(Injector);

  /** The `ticket` query parameter (component input binding). */
  readonly ticket = input<string>();

  protected readonly text = TICKETS_PAGE_TEXT;

  /** Whether the container is wide enough for the side-by-side layout. */
  protected readonly wide = signal(true);
  protected readonly drawerOpen = computed(() => !this.wide() && !!this.store.selectedId());

  /** The ticket the user just picked, whose heading takes focus once it is shown. */
  protected readonly focusRequest = signal<string | null>(null);

  private readonly detail = viewChild(TicketDetail);

  constructor() {
    this.store.connect(computed(() => this.ticket() ?? null));

    effect(() => {
      const requested = this.focusRequest();
      const ticket = this.store.ticket();
      if (!requested || ticket?.id !== requested) return;
      untracked(() => {
        this.focusRequest.set(null);
        // In the drawer the dialog moves focus itself (and back on close).
        if (this.wide()) {
          afterNextRender(() => this.detail()?.focusHeading(), { injector: this.injector });
        }
      });
    });

    this.observeWidth();
  }

  /** Closing the drawer (close button, Escape, backdrop) clears the selection from the URL. */
  protected onDrawerOpenChange(open: boolean): void {
    if (open) return;
    void this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { ticket: null },
      queryParamsHandling: 'merge',
    });
  }

  /**
   * The layout follows the space the page gets (a container query), not the
   * viewport; the drawer needs the same answer in code, hence the observer.
   */
  private observeWidth(): void {
    const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
    const document = inject(DOCUMENT);
    const destroyRef = inject(DestroyRef);
    afterNextRender(() => {
      if (typeof ResizeObserver === 'undefined') return;
      const rem = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
      const observer = new ResizeObserver(([entry]) =>
        this.wide.set(entry.contentRect.width >= WIDE_LAYOUT_MIN_WIDTH_REM * rem),
      );
      observer.observe(host);
      destroyRef.onDestroy(() => observer.disconnect());
    });
  }
}
```

```typescript title="feature/tickets-page.spec.ts"
import { ApplicationRef, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Router, provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideVigdxUi } from '@vigdx/ui/core';
import { Drawer } from '@vigdx/ui/drawer';

import { InMemoryTicketsApi, TICKETS_API_LATENCY } from '../data-access/in-memory-tickets-api';
import { TicketsApi } from '../data-access/tickets-api';
import { TicketsPage } from './tickets-page';
import { ticketsRoutes } from './tickets.routes';

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

  beforeEach(async () => {
    // jsdom has no modal <dialog>; the kit opens drawers 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'));
    };
    TestBed.configureTestingModule({
      providers: [
        provideZonelessChangeDetection(),
        provideVigdxUi(),
        provideRouter([{ path: 'tickets', children: ticketsRoutes }], withComponentInputBinding()),
        InMemoryTicketsApi,
        { provide: TicketsApi, useExisting: InMemoryTicketsApi },
        { provide: TICKETS_API_LATENCY, useValue: 0 },
      ],
    });
    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;
  }

  const page = () =>
    harness.fixture.debugElement.query(By.directive(TicketsPage)).componentInstance as TicketsPage;
  const links = (el: HTMLElement) =>
    Array.from(el.querySelectorAll<HTMLAnchorElement>('app-ticket-list a'));

  it('lists the tickets and asks for a selection', async () => {
    const el = await open('/tickets');
    expect(links(el)).toHaveLength(6);
    expect(links(el)[0].getAttribute('href')).toBe('/tickets?ticket=T-1042');
    expect(el.textContent).toContain('No ticket selected');
  });

  it('shows the ticket named in the URL and marks it current', async () => {
    const el = await open('/tickets?ticket=T-1041');
    expect(el.querySelector('app-ticket-detail h2')?.textContent).toContain(
      'Export to CSV misses the notes column',
    );
    const current = el.querySelector('a[aria-current="true"]');
    expect(current?.getAttribute('href')).toContain('T-1041');
  });

  it('moves focus to the detail heading after picking a ticket', async () => {
    const el = await open('/tickets');
    links(el)[2].click();
    await settle();
    expect(TestBed.inject(Router).url).toBe('/tickets?ticket=T-1040');
    const heading = el.querySelector<HTMLElement>('app-ticket-detail h2');
    expect(heading?.textContent).toContain('Add a second admin');
    expect(document.activeElement).toBe(heading);
  });

  it('reports a ticket that does not exist', async () => {
    const el = await open('/tickets?ticket=T-1');
    expect(el.textContent).toContain('Ticket not found');
  });

  it('opens the detail in a drawer when the container is narrow, and closing clears the URL', async () => {
    const el = await open('/tickets?ticket=T-1042');
    (page() as unknown as { wide: { set(value: boolean): void } }).wide.set(false);
    await settle();

    const dialog = el.querySelector('vig-drawer dialog');
    expect(dialog?.hasAttribute('open')).toBe(true);
    expect(dialog?.textContent).toContain('Invoice shows the wrong VAT rate');
    expect(el.querySelectorAll('app-ticket-detail')).toHaveLength(1);

    const drawer = harness.fixture.debugElement.query(By.directive(Drawer))
      .componentInstance as Drawer;
    drawer.open.set(false);
    await settle();
    expect(TestBed.inject(Router).url).toBe('/tickets');
  });

  it('shows a retry when the list fails', async () => {
    const api = TestBed.inject(InMemoryTicketsApi);
    api.failing.set(true);
    const el = await open('/tickets');
    expect(el.textContent).toContain('Tickets could not be loaded');
    expect(el.textContent).toContain('Check your connection and try again.');
    expect(el.textContent).not.toContain('The server is not responding.');

    api.failing.set(false);
    Array.from(el.querySelectorAll('button'))
      .find((button) => button.textContent?.includes('Try again'))
      ?.click();
    await settle();
    expect(links(el)).toHaveLength(6);
  });
});
```

````typescript title="feature/tickets.routes.ts"
import type { Routes } from '@angular/router';

/**
 * Routes of the tickets feature. The selected ticket travels as the `ticket`
 * query parameter and reaches the page as its `ticket` input, which needs
 * `withComponentInputBinding()` in `provideRouter`. Load them from the app:
 *
 * ```ts
 * {
 *   path: 'tickets',
 *   providers: [{ provide: TicketsApi, useClass: HttpTicketsApi }],
 *   loadChildren: () => import('./features/tickets/feature/tickets.routes').then((m) => m.ticketsRoutes),
 * }
 * ```
 */
export const ticketsRoutes: Routes = [
  {
    path: '',
    title: 'Support tickets',
    loadComponent: () => import('./tickets-page').then((m) => m.TicketsPage),
  },
];
````

```typescript title="ui/ticket-detail.ts"
import { DatePipe } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  computed,
  input,
  viewChild,
} from '@angular/core';
import { Badge } from '@vigdx/ui/badge';

import type { Ticket } from '../data-access/ticket';
import { STATUS_VARIANTS, TICKET_LABELS } from './ticket-labels';

/**
 * The detail of one ticket. Its heading can take focus (`focusHeading`), so
 * the page can move keyboard and screen-reader users to the content they
 * just selected. Presentational.
 */
@Component({
  selector: 'app-ticket-detail',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [DatePipe, Badge],
  host: { class: 'flex flex-col gap-4' },
  template: `
    <div class="flex flex-col gap-2">
      <p class="text-xs text-muted-foreground">{{ ticket().id }}</p>
      <h2
        #heading
        tabindex="-1"
        class="rounded-button text-h3 text-foreground focus-visible:shadow-(--shadow-focus-ring) focus-visible:outline-hidden"
      >
        {{ ticket().subject }}
      </h2>
      <div class="flex flex-wrap gap-2">
        <vig-badge
          [label]="labels().statuses[ticket().status]"
          [variant]="statusVariants[ticket().status]"
        />
        <vig-badge
          [label]="labels().priority + ': ' + labels().priorities[ticket().priority]"
          [variant]="ticket().priority === 'urgent' ? 'error' : 'secondary'"
        />
      </div>
    </div>

    <dl class="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
      <dt class="text-muted-foreground">{{ labels().requester }}</dt>
      <dd class="text-foreground">
        {{ ticket().requester }}
        <span class="text-muted-foreground">({{ ticket().requesterEmail }})</span>
      </dd>
      <dt class="text-muted-foreground">{{ labels().updated }}</dt>
      <dd class="text-foreground">
        <time [attr.datetime]="ticket().updatedAt">{{
          ticket().updatedAt | date: 'longDate' : 'UTC'
        }}</time>
      </dd>
    </dl>

    <div class="flex flex-col gap-3 text-sm leading-relaxed text-foreground">
      @for (paragraph of paragraphs(); track $index) {
        <p>{{ paragraph }}</p>
      }
    </div>
  `,
})
export class TicketDetail {
  readonly ticket = input.required<Ticket>();
  readonly labels = input(TICKET_LABELS);

  protected readonly statusVariants = STATUS_VARIANTS;
  protected readonly paragraphs = computed(() => this.ticket().body.split(/\n{2,}/));

  private readonly heading = viewChild.required<ElementRef<HTMLElement>>('heading');

  /** Moves focus to the ticket's heading, so reading starts at the new content. */
  focusHeading(): void {
    this.heading().nativeElement.focus();
  }
}
```

```typescript title="ui/ticket-detail.spec.ts"
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideVigdxUi } from '@vigdx/ui/core';

import type { Ticket } from '../data-access/ticket';
import { TicketDetail } from './ticket-detail';

const TICKET: Ticket = {
  id: 'T-1',
  subject: 'Invoice shows the wrong VAT rate',
  requester: 'Ada Lovelace',
  requesterEmail: 'ada@example.com',
  status: 'open',
  priority: 'urgent',
  updatedAt: '2026-11-14',
  body: 'First paragraph.\n\nSecond paragraph.',
};

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

  it('renders the ticket and can take focus on its heading', async () => {
    const fixture = TestBed.createComponent(TicketDetail);
    fixture.componentRef.setInput('ticket', TICKET);
    await fixture.whenStable();
    const el = fixture.nativeElement as HTMLElement;

    expect(el.querySelector('h2')?.textContent).toContain('Invoice shows the wrong VAT rate');
    expect(el.querySelectorAll('p').length).toBeGreaterThanOrEqual(3);
    expect(el.textContent).toContain('Priority: Urgent');

    fixture.componentInstance.focusHeading();
    expect(document.activeElement).toBe(el.querySelector('h2'));
  });
});
```

```typescript title="ui/ticket-labels.ts"
import type { BadgeVariant } from '@vigdx/ui/badge';

import type { TicketPriority, TicketStatus } from '../data-access/ticket';

export interface TicketLabels {
  listName: string;
  statuses: Record<TicketStatus, string>;
  priorities: Record<TicketPriority, string>;
  updated: string;
  requester: string;
  priority: string;
}

/** Texts shared by the ticket list and detail; pass a translated copy as `labels`. */
export const TICKET_LABELS: TicketLabels = {
  listName: 'Tickets',
  statuses: { open: 'Open', pending: 'Pending', solved: 'Solved' },
  priorities: { low: 'Low', normal: 'Normal', urgent: 'Urgent' },
  updated: 'Updated',
  requester: 'Requester',
  priority: 'Priority',
};

export const STATUS_VARIANTS: Record<TicketStatus, BadgeVariant> = {
  open: 'info',
  pending: 'warning',
  solved: 'success',
};
```

```typescript title="ui/ticket-list.ts"
import { DatePipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, input, output } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Badge } from '@vigdx/ui/badge';

import type { TicketSummary } from '../data-access/ticket';
import { STATUS_VARIANTS, TICKET_LABELS } from './ticket-labels';

/**
 * The master list. Each ticket is a link that puts its id in the URL
 * (`?ticket=T-1042`), so selection survives reloads, works with back and
 * forward and opens in a new tab; the selected one is `aria-current`.
 * Presentational: the URL is the only state it touches.
 *
 * The selected link shows a primary start border (a system color in forced
 * colors) on the `app` tint; darker tints such as `subtle` would push the
 * status badges below AA contrast. The focus ring is an inset outline: it stays
 * inside the clipped (`overflow-hidden`) list and shows in forced-colors mode,
 * where box shadows are dropped.
 */
@Component({
  selector: 'app-ticket-list',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [DatePipe, RouterLink, Badge],
  template: `
    <ul class="flex flex-col divide-y divide-border-subtle" [attr.aria-label]="labels().listName">
      @for (ticket of tickets(); track ticket.id) {
        <li>
          <a
            class="flex flex-col gap-1 border-s-4 border-transparent px-4 py-3 text-sm transition-colors hover:bg-app focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary aria-[current=true]:border-s-primary aria-[current=true]:bg-app forced-colors:border-s-[Canvas] forced-colors:aria-[current=true]:border-s-[Highlight]"
            [routerLink]="[]"
            [queryParams]="{ ticket: ticket.id }"
            queryParamsHandling="merge"
            [attr.aria-current]="ticket.id === selectedId() ? 'true' : null"
            (click)="activate.emit(ticket.id)"
          >
            <span class="flex items-start justify-between gap-2">
              <span class="font-medium text-foreground">{{ ticket.subject }}</span>
              <vig-badge
                class="shrink-0"
                [label]="labels().statuses[ticket.status]"
                [variant]="statusVariants[ticket.status]"
              />
            </span>
            <span class="text-xs text-muted-foreground">
              {{ ticket.id }} · {{ ticket.requester }} ·
              <time [attr.datetime]="ticket.updatedAt">{{
                ticket.updatedAt | date: 'mediumDate' : 'UTC'
              }}</time>
            </span>
          </a>
        </li>
      }
    </ul>
  `,
})
export class TicketList {
  readonly tickets = input.required<readonly TicketSummary[]>();
  readonly selectedId = input<string | null>(null);
  readonly labels = input(TICKET_LABELS);

  /** A ticket link was activated (click, Enter); the page moves focus to its detail. */
  readonly activate = output<string>();

  protected readonly statusVariants = STATUS_VARIANTS;
}
```

```typescript title="ui/ticket-list.spec.ts"
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { provideVigdxUi } from '@vigdx/ui/core';

import type { Ticket } from '../data-access/ticket';
import { TicketList } from './ticket-list';

const TICKET: Ticket = {
  id: 'T-1',
  subject: 'Invoice shows the wrong VAT rate',
  requester: 'Ada Lovelace',
  requesterEmail: 'ada@example.com',
  status: 'open',
  priority: 'urgent',
  updatedAt: '2026-11-14',
  body: 'First paragraph.\n\nSecond paragraph.',
};

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

  it('links every ticket by query parameter and marks the selected one', async () => {
    const fixture = TestBed.createComponent(TicketList);
    fixture.componentRef.setInput('tickets', [TICKET, { ...TICKET, id: 'T-2' }]);
    fixture.componentRef.setInput('selectedId', 'T-2');
    const activated: string[] = [];
    fixture.componentInstance.activate.subscribe((id) => activated.push(id));
    await fixture.whenStable();

    const links = Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('a'));
    expect(links.map((a) => a.getAttribute('href'))).toEqual(['/?ticket=T-1', '/?ticket=T-2']);
    expect(links.map((a) => a.getAttribute('aria-current'))).toEqual([null, 'true']);
    expect(links[0].textContent).toContain('Open');
    expect(links[0].querySelector('time')?.getAttribute('datetime')).toBe('2026-11-14');

    links[0].click();
    expect(activated).toEqual(['T-1']);
  });
});
```
