TanStack

Angular Example: Accessibility

import { Component, inject, model, signal, viewChild } from '@angular/core'
import {
  injectFormatForAria,
  injectFormatForDisplay,
  injectHotkey,
  injectHotkeyHint,
  injectHotkeyScopesState,
  provideHotkeys,
} from '@tanstack/angular-hotkeys'
import type { ElementRef } from '@angular/core'

@Component({
  selector: 'app-announce',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Announce shortcuts to screen readers</h2>
      <p>
        A screen reader reads a button's shortcut from its
        <code>aria-keyshortcuts</code> attribute, not from the visible label.
        ARIA has no syntax for sequences, so a sequence gets no attribute.
      </p>
      <div class="hotkey-list">
        <div class="hotkey-row">
          <!-- formatForAria gives Meta+S on macOS and Control+S elsewhere.
               Render the visible label from the same hotkey. -->
          <button
            (click)="lastAction.set('Save')"
            [attr.aria-keyshortcuts]="formatForAria('Mod+S')"
          >
            Save <kbd>{{ formatForDisplay('Mod+S') }}</kbd>
          </button>
          <code>aria-keyshortcuts: {{ formatForAria('Mod+S') ?? 'none' }}</code>
        </div>
        <div class="hotkey-row">
          <!-- formatForAria returns undefined for a sequence, so the
               [attr.aria-keyshortcuts] binding leaves the attribute off.
               List sequences in visible text instead. -->
          <button
            (click)="lastAction.set('Go to inbox')"
            [attr.aria-keyshortcuts]="formatForAria(['G', 'I'])"
          >
            Go to inbox <kbd>{{ formatForDisplay(['G', 'I']) }}</kbd>
          </button>
          <code
            >aria-keyshortcuts: {{ formatForAria(['G', 'I']) ?? 'none' }}</code
          >
        </div>
      </div>
      <p role="status">Last action: {{ lastAction() }}</p>
    </section>
  `,
})
export class AnnounceSection {
  readonly formatForAria = injectFormatForAria()
  readonly formatForDisplay = injectFormatForDisplay()
  readonly lastAction = signal('none')

  constructor() {
    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default.
    injectHotkey('Mod+S', () => this.lastAction.set('Save'))
    injectHotkey(['G', 'I'], () => this.lastAction.set('Go to inbox'))
  }
}

@Component({
  selector: 'app-character-keys',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Turn off character key shortcuts</h2>
      <p>
        Speech input and accidental key presses can fire single-key shortcuts.
        WCAG 2.1.4 asks for a way to turn them off. Clear the checkbox, then
        press both shortcuts.
      </p>
      <label>
        <input
          #checkbox
          type="checkbox"
          [checked]="singleKeyShortcuts()"
          (change)="singleKeyShortcuts.set(checkbox.checked)"
        />
        Single-key shortcuts
      </label>
      <div class="hotkey-list">
        <div class="hotkey-row">
          <!-- The ARIA formatter returns undefined while L can't fire, so the
               attribute goes away while character keys are suspended. -->
          <button
            (click)="likes.set(likes() + 1)"
            [attr.aria-keyshortcuts]="formatForAria('L')"
          >
            Like <kbd>{{ formatForDisplay('L') }}</kbd>
          </button>
          <code>aria-keyshortcuts: {{ formatForAria('L') ?? 'none' }}</code>
        </div>
        <div class="hotkey-row">
          <button
            (click)="bookmarks.set(bookmarks() + 1)"
            [attr.aria-keyshortcuts]="formatForAria('Alt+[KeyB]')"
          >
            Bookmark <kbd>{{ formatForDisplay('Alt+[KeyB]') }}</kbd>
          </button>
          <code
            >aria-keyshortcuts:
            {{ formatForAria('Alt+[KeyB]') ?? 'none' }}</code
          >
        </div>
      </div>
      <p role="status">
        Character keys {{ scopes().characterKeysSuspended ? 'off' : 'on' }}.
        Likes: {{ likes() }}. Bookmarks: {{ bookmarks() }}
      </p>
    </section>
  `,
})
export class CharacterKeysSection {
  // The user's setting, bound two-way to the root component, whose provider
  // reads it.
  readonly singleKeyShortcuts = model.required<boolean>()
  readonly formatForAria = injectFormatForAria()
  readonly formatForDisplay = injectFormatForDisplay()
  // `characterKeysSuspended` is true while any provider suspends character
  // keys. Use it to show whether single-key shortcuts work right now, and
  // bind the checkbox to the setting.
  readonly scopes = injectHotkeyScopesState()
  readonly likes = signal(0)
  readonly bookmarks = signal(0)

  constructor() {
    // L types a character, so it stops while character keys are suspended.
    injectHotkey('L', () => this.likes.update((n) => n + 1))
    // Alt keeps this one working. The physical code `[KeyB]` matches the key,
    // because Alt+B types a character such as ∫ on macOS.
    injectHotkey('Alt+[KeyB]', () => this.bookmarks.update((n) => n + 1))
  }
}

@Component({
  selector: 'app-target',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Scope character keys to an element</h2>
      <p>
        Focus the list, then press <kbd>{{ formatForDisplay('J') }}</kbd> and
        <kbd>{{ formatForDisplay('K') }}</kbd> to move the selection.
      </p>
      <!-- An element only receives key events while it or a descendant has
           focus, so the list needs tabindex. -->
      <ul #list tabindex="0" aria-label="Messages" class="list">
        <li [class.selected]="selected() === 1">Message 1</li>
        <li [class.selected]="selected() === 2">Message 2</li>
        <li [class.selected]="selected() === 3">Message 3</li>
      </ul>
      <p role="status">Selected: Message {{ selected() }}</p>
    </section>
  `,
})
export class TargetSection {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly list = viewChild<ElementRef<HTMLUListElement>>('list')
  readonly selected = signal(1)

  constructor() {
    // With an element `target`, J and K fire only while focus is inside the
    // list, which WCAG 2.1.4 allows for single-key shortcuts. They keep
    // working while single-key shortcuts are off. Without `target`, they
    // would fire anywhere on the page.
    injectHotkey('J', () => this.selected.update((n) => Math.min(n + 1, 3)), {
      target: this.list,
    })
    injectHotkey('K', () => this.selected.update((n) => Math.max(n - 1, 1)), {
      target: this.list,
    })
  }
}

@Component({
  selector: 'app-hint',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Show hints while a modifier is held</h2>
      <p>
        Hold <kbd>{{ formatForDisplay('Alt') }}</kbd> to show the shortcut on
        the button. The <code>aria-keyshortcuts</code> attribute stays set
        either way.
      </p>
      <button
        (click)="archived.set(archived() + 1)"
        [attr.aria-keyshortcuts]="formatForAria('Alt+[KeyA]')"
      >
        Archive
        @if (showHint()) {
          <kbd>{{ formatForDisplay('Alt+[KeyA]') }}</kbd>
        }
      </button>
      <p role="status">Archived: {{ archived() }}</p>
    </section>
  `,
})
export class HintSection {
  readonly formatForAria = injectFormatForAria()
  readonly formatForDisplay = injectFormatForDisplay()
  // True while the user holds Alt, the modifier of an active Alt+A hotkey.
  // It only reports state and registers nothing.
  readonly showHint = injectHotkeyHint('Alt+[KeyA]')
  readonly archived = signal(0)

  constructor() {
    // The physical code `[KeyA]` matches the key, because Alt+A types å on
    // macOS.
    injectHotkey('Alt+[KeyA]', () => this.archived.update((n) => n + 1))
  }
}

@Component({
  selector: 'app-right-to-left',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Keep labels in order on right-to-left pages</h2>
      <p>
        Each row shows "Previous page" in Hebrew with the shortcut
        <kbd>{{ formatForDisplay('Alt+[BracketLeft]') }}</kbd
        >. Without a fix, the browser reverses the label and mirrors the
        bracket.
      </p>
      <div class="hotkey-list">
        <div class="hotkey-row">
          <span class="caption">kbd without dir</span>
          <span dir="rtl" lang="he"
            >הדף הקודם
            <kbd>{{ formatForDisplay('Alt+[BracketLeft]') }}</kbd></span
          >
        </div>
        <div class="hotkey-row">
          <!-- dir="ltr" keeps the label in order where it has its own element. -->
          <span class="caption">kbd with dir="ltr"</span>
          <span dir="rtl" lang="he"
            >הדף הקודם
            <kbd dir="ltr">{{
              formatForDisplay('Alt+[BracketLeft]')
            }}</kbd></span
          >
        </div>
        <div class="hotkey-row">
          <span class="caption">String without isolate</span>
          <span dir="rtl" lang="he">{{
            'הדף הקודם ' + formatForDisplay('Alt+[BracketLeft]')
          }}</span>
        </div>
        <div class="hotkey-row">
          <!-- A string, such as a placeholder or a translated message, can't
               hold a dir attribute. isolate: true wraps the label in the
               invisible characters U+2066 and U+2069, so the text around it
               can't reorder it. -->
          <span class="caption">String with isolate</span>
          <span dir="rtl" lang="he">{{
            'הדף הקודם ' +
              formatForDisplay('Alt+[BracketLeft]', { isolate: true })
          }}</span>
        </div>
      </div>
      <p role="status">Previous page: {{ previousPage() }}</p>
    </section>
  `,
})
export class RightToLeftSection {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly previousPage = signal(0)

  constructor() {
    // A bracket shows the mirroring. The physical code `[BracketLeft]`
    // matches the key, because Alt+[ types a quote mark on macOS.
    injectHotkey('Alt+[BracketLeft]', () =>
      this.previousPage.update((n) => n + 1),
    )
  }
}

@Component({
  selector: 'app-dialog',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Let an open dialog handle Escape</h2>
      <p>
        Press Escape on the page, then open the dialog and press Escape again.
        The dialog closes and the page hotkey stays quiet.
      </p>
      <button (click)="dialog.showModal(); dialogOpen.set(true)">
        Open dialog
      </button>
      <!-- The browser closes a modal dialog on Escape and fires close. -->
      <dialog
        #dialog
        aria-labelledby="dialog-title"
        (close)="dialogOpen.set(false)"
      >
        <h3 id="dialog-title">Dialog</h3>
        <p>Press Escape to close this dialog.</p>
        <button (click)="dialog.close()">Close</button>
      </dialog>
      <p role="status">
        Dialog {{ dialogOpen() ? 'open' : 'closed' }}. Page Escape:
        {{ escapes() }}
      </p>
    </section>
  `,
})
export class DialogSection {
  readonly dialogOpen = signal(false)
  readonly escapes = signal(0)

  constructor() {
    // A page-level Escape hotkey. While focus is inside an open modal
    // `<dialog>`, the library skips it, so Escape closes the dialog and this
    // callback doesn't run. Escape types no character, so it keeps working
    // while single-key shortcuts are off.
    injectHotkey('Escape', () => this.escapes.update((n) => n + 1))
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    AnnounceSection,
    CharacterKeysSection,
    DialogSection,
    HintSection,
    RightToLeftSection,
    TargetSection,
  ],
  // While `suspendCharacterKeys` returns true, document-level shortcuts made
  // only of keys that type a character, such as `L` or `['G', 'I']`, stop
  // firing across the whole app. Shortcuts with Control, Alt, or Meta, keys
  // that type nothing, such as Escape, and hotkeys with an element `target`
  // keep working. The getter runs in this component's injector, so it can
  // read the component's setting.
  providers: [
    provideHotkeys({
      suspendCharacterKeys: () => !inject(AppComponent).singleKeyShortcuts(),
    }),
  ],
  template: `
    <div class="app">
      <header>
        <h1>Accessibility</h1>
        <p>
          Announce shortcuts to screen readers, let users turn off single-key
          shortcuts, and leave Escape to an open dialog.
        </p>
      </header>

      <main>
        <app-announce />
        <app-character-keys [(singleKeyShortcuts)]="singleKeyShortcuts" />
        <app-target />
        <app-hint />
        <app-right-to-left />
        <app-dialog />
      </main>
    </div>
  `,
})
export class AppComponent {
  // The user's setting. A real app would save it with the user's preferences.
  readonly singleKeyShortcuts = signal(true)
}