Skip to content

Ember Example: Accessibility

import { array, concat, hash } from '@ember/helper'
import { on } from '@ember/modifier'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import {
  getHotkeyManager,
  onHotkey,
  useFormatForAria,
  useFormatForDisplay,
  useHotkey,
  useHotkeyHint,
  useHotkeyScopesState,
} from '@tanstack/ember-hotkeys'

const eq = (a: unknown, b: unknown) => a === b
const or = <T, U>(a: T, b: U) => a || b

class App extends Component {
  // Returns undefined for a sequence, and for a hotkey that can't fire right
  // now, so Glimmer leaves the `aria-keyshortcuts` attribute off.
  formatForAria = useFormatForAria()
  formatForDisplay = useFormatForDisplay()
  // `characterKeysSuspended` is true while anything suspends character keys.
  // Use it to show whether single-key shortcuts work right now, and bind the
  // checkbox to the setting.
  scopes = useHotkeyScopesState(this)
  // True while the user holds Alt, the modifier of an active Alt+A hotkey.
  // It only reports state and registers nothing.
  archiveHint = useHotkeyHint(this, 'Alt+[KeyA]')

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

  save = () => (this.lastAction = 'Save')
  goToInbox = () => (this.lastAction = 'Go to inbox')

  // Ember has no provider, so suspend character keys on the hotkey manager.
  // While 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 on an element keep working.
  resumeCharacterKeys: (() => void) | undefined
  setSingleKeyShortcuts = (event: Event) => {
    this.singleKeyShortcuts = (event.target as HTMLInputElement).checked
    if (this.singleKeyShortcuts) {
      this.resumeCharacterKeys?.()
      this.resumeCharacterKeys = undefined
    } else {
      this.resumeCharacterKeys ??= getHotkeyManager().suspendCharacterKeys()
    }
  }
  willDestroy() {
    super.willDestroy()
    this.resumeCharacterKeys?.()
  }

  like = () => this.likes++
  bookmark = () => this.bookmarks++

  get characterKeysText() {
    const state = this.scopes.value.characterKeysSuspended ? 'off' : 'on'
    return `Character keys ${state}. Likes: ${this.likes}. Bookmarks: ${this.bookmarks}`
  }

  selectNext = () => (this.selected = Math.min(this.selected + 1, 3))
  selectPrevious = () => (this.selected = Math.max(this.selected - 1, 1))

  archive = () => this.archived++
  goToPreviousPage = () => this.previousPage++
  pageEscape = () => this.escapes++

  // Ember has no built-in element ref, so look the dialog up by id.
  dialog = () => document.getElementById('dialog') as HTMLDialogElement
  openDialog = () => {
    this.dialog().showModal()
    this.dialogOpen = true
  }
  closeDialog = () => this.dialog().close()
  dialogClosed = () => (this.dialogOpen = false)

  get dialogText() {
    return `Dialog ${this.dialogOpen ? 'open' : 'closed'}. Page Escape: ${this.escapes}`
  }

  <template>
    {{! Mod+S would open the browser's Save dialog. A matched hotkey calls
        `preventDefault` by default. }}
    {{useHotkey 'Mod+S' this.save}}
    {{useHotkey (array 'G' 'I') this.goToInbox}}
    {{! L types a character, so it stops while character keys are suspended. }}
    {{useHotkey 'L' this.like}}
    {{! Alt keeps this one working. The physical code `[KeyB]` matches the key,
        because Alt+B types a character such as ∫ on macOS. }}
    {{useHotkey 'Alt+[KeyB]' this.bookmark}}
    {{! The physical code `[KeyA]` matches the key, because Alt+A types å on
        macOS. }}
    {{useHotkey 'Alt+[KeyA]' this.archive}}
    {{! A bracket shows the mirroring. The physical code `[BracketLeft]`
        matches the key, because Alt+[ types a quote mark on macOS. }}
    {{useHotkey 'Alt+[BracketLeft]' this.goToPreviousPage}}
    {{! 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. }}
    {{useHotkey 'Escape' this.pageEscape}}

    <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
                type='button'
                aria-keyshortcuts={{this.formatForAria 'Mod+S'}}
                {{on 'click' this.save}}
              >
                Save
                <kbd>{{this.formatForDisplay 'Mod+S'}}</kbd>
              </button>
              <code>aria-keyshortcuts: {{or (this.formatForAria 'Mod+S') 'none'}}</code>
            </div>
            <div class='hotkey-row'>
              {{! formatForAria returns undefined for a sequence, so Glimmer
                  leaves the attribute off. List sequences in visible text
                  instead. }}
              <button
                type='button'
                aria-keyshortcuts={{this.formatForAria (array 'G' 'I')}}
                {{on 'click' this.goToInbox}}
              >
                Go to inbox
                <kbd>{{this.formatForDisplay (array 'G' 'I')}}</kbd>
              </button>
              <code>aria-keyshortcuts: {{or (this.formatForAria (array '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}}
              {{on 'change' this.setSingleKeyShortcuts}}
            />
            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
                type='button'
                aria-keyshortcuts={{this.formatForAria 'L'}}
                {{on 'click' this.like}}
              >
                Like
                <kbd>{{this.formatForDisplay 'L'}}</kbd>
              </button>
              <code>aria-keyshortcuts: {{or (this.formatForAria 'L') 'none'}}</code>
            </div>
            <div class='hotkey-row'>
              <button
                type='button'
                aria-keyshortcuts={{this.formatForAria 'Alt+[KeyB]'}}
                {{on 'click' this.bookmark}}
              >
                Bookmark
                <kbd>{{this.formatForDisplay 'Alt+[KeyB]'}}</kbd>
              </button>
              <code>aria-keyshortcuts: {{or (this.formatForAria 'Alt+[KeyB]') 'none'}}</code>
            </div>
          </div>
          <p role='status'>{{this.characterKeysText}}</p>
        </section>

        <section class='demo-section'>
          <h2>Scope character keys to an element</h2>
          <p>
            Focus the list, then press
            <kbd>{{this.formatForDisplay 'J'}}</kbd>
            and
            <kbd>{{this.formatForDisplay 'K'}}</kbd>
            to move the selection.
          </p>
          {{! The `onHotkey` modifier listens on its element, so 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. With `useHotkey`, they would fire anywhere on
              the page. An element only receives key events while it or a
              descendant has focus, so the list needs tabindex. }}
          <ul
            tabindex='0'
            aria-label='Messages'
            class='list'
            {{onHotkey 'J' this.selectNext}}
            {{onHotkey 'K' this.selectPrevious}}
          >
            <li class={{if (eq this.selected 1) 'selected'}}>Message 1</li>
            <li class={{if (eq this.selected 2) 'selected'}}>Message 2</li>
            <li class={{if (eq 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>{{this.formatForDisplay 'Alt'}}</kbd>
            to show the shortcut on the button. The
            <code>aria-keyshortcuts</code>
            attribute stays set either way.
          </p>
          <button
            type='button'
            aria-keyshortcuts={{this.formatForAria 'Alt+[KeyA]'}}
            {{on 'click' this.archive}}
          >
            Archive
            {{#if this.archiveHint.value}}
              <kbd>{{this.formatForDisplay 'Alt+[KeyA]'}}</kbd>
            {{/if}}
          </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>{{this.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>{{this.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'>{{this.formatForDisplay
                    'Alt+[BracketLeft]'
                  }}</kbd></span>
            </div>
            <div class='hotkey-row'>
              <span class='caption'>String without isolate</span>
              <span dir='rtl' lang='he'>{{concat
                  'הדף הקודם '
                  (this.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'>{{concat
                  'הדף הקודם '
                  (this.formatForDisplay
                    'Alt+[BracketLeft]' (hash 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 type='button' {{on 'click' this.openDialog}}>
            Open dialog
          </button>
          {{! The browser closes a modal dialog on Escape and fires `close`. }}
          <dialog
            id='dialog'
            aria-labelledby='dialog-title'
            {{on 'close' this.dialogClosed}}
          >
            <h3 id='dialog-title'>Dialog</h3>
            <p>Press Escape to close this dialog.</p>
            <button type='button' {{on 'click' this.closeDialog}}>Close</button>
          </dialog>
          <p role='status'>{{this.dialogText}}</p>
        </section>
      </main>
    </div>
  </template>
}
export default App