TanStack

Lit Example: Accessibility

import {
  FormatForAriaController,
  FormatForDisplayController,
  HotkeyController,
  HotkeyHintController,
  HotkeyScopesStateController,
  getHotkeyManager,
  hotkey,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import { ifDefined } from 'lit/directives/if-defined.js'
import { createRef, ref } from 'lit/directives/ref.js'
import appStyles from './index.css?raw'

@customElement('my-app')
export class MyApp extends LitElement {
  static styles = [
    css`
      :host {
        display: block;
        margin: 0;
        font-family: system-ui, -apple-system, sans-serif;
        background: #f5f5f5;
        color: #333;
        box-sizing: border-box;
      }
      :host *,
      :host *::before,
      :host *::after {
        box-sizing: border-box;
      }
    `,
    unsafeCSS(appStyles),
  ]

  // The user's setting. A real app would save it with the user's preferences.
  @state() private singleKeyShortcuts = true
  @state() private lastAction = 'none'
  @state() private likes = 0
  @state() private bookmarks = 0
  @state() private selected = 1
  @state() private archived = 0
  @state() private previousPage = 0
  @state() private dialogOpen = false
  @state() private escapes = 0

  private list = createRef<HTMLUListElement>()
  private dialog = createRef<HTMLDialogElement>()
  // Resumes character key shortcuts. Set while they are suspended.
  private resumeCharacterKeys: (() => void) | undefined

  // Its `format` returns undefined for a hotkey that can't fire right now, so
  // pass it through `ifDefined` and Lit leaves the attribute off.
  private formatForAria = new FormatForAriaController(this)
  private formatForDisplay = new FormatForDisplayController(this)
  // `characterKeysSuspended` is true while any part of the app suspends
  // character keys. Use it to show whether single-key shortcuts work right
  // now, and bind the checkbox to the setting.
  private scopes = new HotkeyScopesStateController(this)
  // True while the user holds Alt, the modifier of an active Alt+A hotkey.
  // It only reports state and registers nothing.
  private archiveHint = new HotkeyHintController(this, 'Alt+[KeyA]')

  constructor() {
    super()
    // 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. A getter re-reads the target after
    // each render, and an unset target waits until the list renders.
    new HotkeyController(
      this,
      'J',
      () => {
        this.selected = Math.min(this.selected + 1, 3)
      },
      () => ({ target: this.list.value }),
    )
    new HotkeyController(
      this,
      'K',
      () => {
        this.selected = Math.max(this.selected - 1, 1)
      },
      () => ({ target: this.list.value }),
    )
  }

  // While character keys are suspended, 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. Lit has no provider, so suspend them on the hotkey manager and
  // keep the function that resumes them.
  private setSingleKeyShortcuts(on: boolean) {
    this.singleKeyShortcuts = on
    if (on) {
      this.resumeCharacterKeys?.()
      this.resumeCharacterKeys = undefined
    } else {
      this.resumeCharacterKeys ??= getHotkeyManager().suspendCharacterKeys()
    }
  }

  override disconnectedCallback() {
    super.disconnectedCallback()
    // Suspensions are counted, so release this one when the element goes.
    this.resumeCharacterKeys?.()
    this.resumeCharacterKeys = undefined
  }

  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default.
  @hotkey('Mod+S')
  save() {
    this.lastAction = 'Save'
  }

  @hotkey(['G', 'I'])
  goToInbox() {
    this.lastAction = 'Go to inbox'
  }

  // L types a character, so it stops while character keys are suspended.
  @hotkey('L')
  like() {
    this.likes++
  }

  // Alt keeps this one working. The physical code `[KeyB]` matches the key,
  // because Alt+B types a character such as ∫ on macOS.
  @hotkey('Alt+[KeyB]')
  bookmark() {
    this.bookmarks++
  }

  // The physical code `[KeyA]` matches the key, because Alt+A types å on
  // macOS.
  @hotkey('Alt+[KeyA]')
  archive() {
    this.archived++
  }

  // A bracket shows the mirroring. The physical code `[BracketLeft]` matches
  // the key, because Alt+[ types a quote mark on macOS.
  @hotkey('Alt+[BracketLeft]')
  goToPreviousPage() {
    this.previousPage++
  }

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

  render() {
    const formatForAria = this.formatForAria.format
    const formatForDisplay = this.formatForDisplay.format

    return html`
      <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>
          <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=${() => (this.lastAction = 'Save')}
                  aria-keyshortcuts=${ifDefined(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
                     ifDefined leaves the attribute off. List sequences in
                     visible text instead. -->
                <button
                  @click=${() => (this.lastAction = 'Go to inbox')}
                  aria-keyshortcuts=${ifDefined(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: ${this.lastAction}</p>
          </section>

          <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
                type="checkbox"
                .checked=${this.singleKeyShortcuts}
                @change=${(e: Event) =>
                  this.setSingleKeyShortcuts(
                    (e.target as HTMLInputElement).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=${() => this.likes++}
                  aria-keyshortcuts=${ifDefined(formatForAria('L'))}
                >
                  Like <kbd>${formatForDisplay('L')}</kbd>
                </button>
                <code>aria-keyshortcuts: ${formatForAria('L') ?? 'none'}</code>
              </div>
              <div class="hotkey-row">
                <button
                  @click=${() => this.bookmarks++}
                  aria-keyshortcuts=${ifDefined(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
              ${this.scopes.value.characterKeysSuspended ? 'off' : 'on'}. Likes:
              ${this.likes}. Bookmarks: ${this.bookmarks}
            </p>
          </section>

          <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
              ${ref(this.list)}
              tabindex="0"
              aria-label="Messages"
              class="list"
            >
              <li class=${this.selected === 1 ? 'selected' : ''}>Message 1</li>
              <li class=${this.selected === 2 ? 'selected' : ''}>Message 2</li>
              <li class=${this.selected === 3 ? 'selected' : ''}>Message 3</li>
            </ul>
            <p role="status">Selected: Message ${this.selected}</p>
          </section>

          <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=${() => this.archived++}
              aria-keyshortcuts=${ifDefined(formatForAria('Alt+[KeyA]'))}
            >
              Archive
              ${
                this.archiveHint.value
                  ? html`<kbd>${formatForDisplay('Alt+[KeyA]')}</kbd>`
                  : null
              }
            </button>
            <p role="status">Archived: ${this.archived}</p>
          </section>

          <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: ${this.previousPage}</p>
          </section>

          <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=${() => {
                this.dialog.value?.showModal()
                this.dialogOpen = true
              }}
            >
              Open dialog
            </button>
            <!-- The browser closes a modal dialog on Escape and fires close. -->
            <dialog
              ${ref(this.dialog)}
              aria-labelledby="dialog-title"
              @close=${() => (this.dialogOpen = false)}
            >
              <h3 id="dialog-title">Dialog</h3>
              <p>Press Escape to close this dialog.</p>
              <button @click=${() => this.dialog.value?.close()}>Close</button>
            </dialog>
            <p role="status">
              Dialog ${this.dialogOpen ? 'open' : 'closed'}. Page Escape:
              ${this.escapes}
            </p>
          </section>
        </main>
      </div>
    `
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'my-app': MyApp
  }
}