Skip to content

Ember Example: Scopes

import { registerDestructor } from '@ember/destroyable'
import { fn } from '@ember/helper'
import { on } from '@ember/modifier'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import {
  getHotkeyManager,
  useFormatForDisplay,
  useHotkey,
  useHotkeyScopesState,
} from '@tanstack/ember-hotkeys'
import type Owner from '@ember/owner'

// Ember has no provider component, so a scope is a name. Activate it on the
// hotkey manager, and pass `scope` to every hotkey that belongs to it. A
// hotkey without `scope` is in `global`. Where a hotkey's DOM renders doesn't
// change its scope.

const eq = (a: unknown, b: unknown) => a === b
const plural = (count: number, word: string) =>
  `${count} ${word}${count === 1 ? '' : 's'}`

type Folder = 'Inbox' | 'Archive' | 'Spam'

class App extends Component {
  formatForDisplay = useFormatForDisplay()
  scopes: ReturnType<typeof useHotkeyScopesState>

  @tracked helpOpened = 0
  @tracked paletteOpened = 0
  @tracked documentSaves = 0
  @tracked commentsPosted = 0
  @tracked showComments = true
  @tracked folder: Folder = 'Inbox'
  @tracked inboxItems = 0
  @tracked archiveItems = 0
  @tracked spamItems = 0
  @tracked dialogOpen = false
  @tracked step = 1
  @tracked settingsSaves = 0
  @tracked allowGlobal = false
  @tracked allowPalette = true

  // `activateScope` returns a function that releases the scope. Scopes
  // change in this constructor and in event handlers. Activating one in the
  // constructor of a component that renders later, such as the comment box,
  // would change scope state that this render already read, which Glimmer
  // rejects.
  releaseComments: (() => void) | undefined
  releaseFolder: () => void
  releaseDialog: (() => void) | undefined

  constructor(owner: Owner, args: object) {
    super(owner, args)
    const manager = getHotkeyManager()
    // Active while the page is rendered. Release each one when it goes away.
    registerDestructor(this, manager.activateScope('palette'))
    registerDestructor(this, manager.activateScope('document'))
    registerDestructor(this, manager.activateScope('mail'))
    registerDestructor(this, manager.activateScope('settings'))
    // `parent` nests `comments` in `document`, as a nested provider would.
    // Without it, `comments` would win Mod+S only because it activated later.
    this.releaseComments = manager.activateScope('comments', {
      parent: 'document',
    })
    // Only the selected folder's scope is active. `parent` nests it in
    // `mail`.
    this.releaseFolder = manager.activateScope('inbox', { parent: 'mail' })
    registerDestructor(this, () => {
      this.releaseComments?.()
      this.releaseFolder()
      this.releaseDialog?.()
    })
    // Read scope state after the activations above. Created earlier, it would
    // track a change made during this render and throw.
    this.scopes = useHotkeyScopesState(this)
  }

  openHelp = () => this.helpOpened++
  openPalette = () => this.paletteOpened++
  saveDocument = () => this.documentSaves++
  postComment = () => this.commentsPosted++
  // `comments` is active only while the comment box shows.
  toggleComments = (event: Event) => {
    this.showComments = (event.target as HTMLInputElement).checked
    if (this.showComments) {
      this.releaseComments ??= getHotkeyManager().activateScope('comments', {
        parent: 'document',
      })
    } else {
      this.releaseComments?.()
      this.releaseComments = undefined
    }
  }

  // Switching folders releases the old folder's scope and activates the new
  // one, so only the selected folder's Alt+N fires. Without `enabled` on a
  // provider, this is how a scope stays registered but inactive.
  selectFolder = (folder: Folder) => {
    this.folder = folder
    this.releaseFolder()
    this.releaseFolder = getHotkeyManager().activateScope(
      folder.toLowerCase(),
      { parent: 'mail' },
    )
  }
  addToInbox = () => this.inboxItems++
  addToArchive = () => this.archiveItems++
  addToSpam = () => this.spamItems++

  setAllowGlobal = (event: Event) =>
    (this.allowGlobal = (event.target as HTMLInputElement).checked)
  setAllowPalette = (event: Event) =>
    (this.allowPalette = (event.target as HTMLInputElement).checked)
  openDialog = () => {
    if (this.releaseDialog) return
    const manager = getHotkeyManager()
    // `exclusive` without `allow` suspends every other scope, including
    // `global`. The checkboxes can't change while the backdrop covers them,
    // so the scope activates once, with the scopes allowed when it opens.
    const releaseDialog = manager.activateScope('dialog', {
      exclusive: {
        allow: [
          ...(this.allowGlobal ? ['global'] : []),
          ...(this.allowPalette ? ['palette'] : []),
        ],
      },
      parent: 'settings',
    })
    // Without `parent: 'dialog'`, the exclusive scope would suspend this one
    // too, and Alt+N would do nothing.
    const releaseSteps = manager.activateScope('dialog-steps', {
      parent: 'dialog',
    })
    this.releaseDialog = () => {
      releaseSteps()
      releaseDialog()
    }
    this.step = 1
    this.dialogOpen = true
  }
  closeDialog = () => {
    this.releaseDialog?.()
    this.releaseDialog = undefined
    this.dialogOpen = false
  }
  saveSettings = () => {
    this.settingsSaves++
    this.closeDialog()
  }
  nextStep = () => (this.step = (this.step % 3) + 1)

  // Sorted, because the order scopes activate in depends on the order
  // components render. `global` is always active and isn't listed.
  list = (names: ReadonlyArray<string>) =>
    names.length > 0 ? [...names].sort().join(', ') : 'none'

  <template>
    {{! No `scope`, so it's in `global`. }}
    {{useHotkey 'Alt+[KeyH]' this.openHelp}}
    {{! Mod+K would focus the browser's search bar on Windows and Linux. A
        matched hotkey calls `preventDefault` by default. }}
    {{useHotkey 'Mod+K' this.openPalette scope='palette'}}
    {{! Mod+S would open the browser's Save dialog. A matched hotkey calls
        `preventDefault` by default. }}
    {{useHotkey 'Mod+S' this.saveDocument scope='document'}}
    {{useHotkey 'Alt+[KeyI]' (fn this.selectFolder 'Inbox') scope='mail'}}
    {{useHotkey 'Alt+[KeyA]' (fn this.selectFolder 'Archive') scope='mail'}}
    {{useHotkey 'Alt+[KeyS]' (fn this.selectFolder 'Spam') scope='mail'}}
    {{! The same key in every folder. Only the active folder scope fires it. }}
    {{useHotkey 'Alt+[KeyN]' this.addToInbox scope='inbox'}}
    {{useHotkey 'Alt+[KeyN]' this.addToArchive scope='archive'}}
    {{useHotkey 'Alt+[KeyN]' this.addToSpam scope='spam'}}
    {{useHotkey 'Alt+[KeyO]' this.openDialog scope='settings'}}

    <div class='app'>
      <header>
        <h1>Hotkey scopes</h1>
        <p>
          Each scope groups the hotkeys registered in it. They fire while the
          scope is active, and no exclusive scope suspends them.
        </p>
      </header>
      <main>
        <section class='demo-section'>
          <h2>Global scope</h2>
          <p>
            <kbd>{{this.formatForDisplay 'Alt+[KeyH]'}}</kbd>
            opens help. It's in
            <code>global</code>, which is always active. Only an exclusive
            scope suspends it.
          </p>
          <p role='status'>Help opened {{plural this.helpOpened 'time'}}</p>
        </section>

        <section class='demo-section'>
          <h2>Command palette</h2>
          <p>
            <kbd>{{this.formatForDisplay 'Mod+K'}}</kbd>
            opens the palette. It's in the
            <code>palette</code>
            scope.
          </p>
          <p role='status'>Palette opened
            {{plural this.paletteOpened 'time'}}</p>
        </section>

        <section class='demo-section'>
          <h2>Nested scopes</h2>
          <p>
            The document and its comment box both register
            <kbd>{{this.formatForDisplay 'Mod+S'}}</kbd>. The
            <code>comments</code>
            scope is nested in
            <code>document</code>, so it wins while it's active. Hide the
            comment box and the document saves again.
          </p>
          <label>
            <input
              type='checkbox'
              checked={{this.showComments}}
              {{on 'change' this.toggleComments}}
            />
            Show comment box
          </label>
          {{#if this.showComments}}
            {{! Only this one runs while both are active, because `comments`
                is nested in `document`. }}
            {{useHotkey 'Mod+S' this.postComment scope='comments'}}
            <div class='panel'>Comment box</div>
          {{/if}}
          <p role='status'>Document saves: {{this.documentSaves}}. Comments
            posted: {{this.commentsPosted}}.</p>
        </section>

        <section class='demo-section'>
          <h2>Enabled scopes</h2>
          <p>
            All three folders register
            <kbd>{{this.formatForDisplay 'Alt+[KeyN]'}}</kbd>. Only the
            selected folder's scope is active, so the key adds to that one.
            Select with
            <kbd>{{this.formatForDisplay 'Alt+[KeyI]'}}</kbd>,
            <kbd>{{this.formatForDisplay 'Alt+[KeyA]'}}</kbd>, and
            <kbd>{{this.formatForDisplay 'Alt+[KeyS]'}}</kbd>.
          </p>
          <div class='folders'>
            <button
              type='button'
              class='panel folder'
              aria-pressed={{if (eq this.folder 'Inbox') 'true' 'false'}}
              {{on 'click' (fn this.selectFolder 'Inbox')}}
            >Inbox: {{plural this.inboxItems 'item'}}</button>
            <button
              type='button'
              class='panel folder'
              aria-pressed={{if (eq this.folder 'Archive') 'true' 'false'}}
              {{on 'click' (fn this.selectFolder 'Archive')}}
            >Archive: {{plural this.archiveItems 'item'}}</button>
            <button
              type='button'
              class='panel folder'
              aria-pressed={{if (eq this.folder 'Spam') 'true' 'false'}}
              {{on 'click' (fn this.selectFolder 'Spam')}}
            >Spam: {{plural this.spamItems 'item'}}</button>
          </div>
          <p role='status'>Selected: {{this.folder}}. Items: Inbox
            {{this.inboxItems}}, Archive {{this.archiveItems}}, Spam
            {{this.spamItems}}</p>
        </section>

        <section class='demo-section'>
          <h2>Exclusive scopes</h2>
          <p>
            While the dialog is open, its exclusive scope suspends every other
            scope, including
            <code>global</code>. Scopes nested in it keep working, and so do
            the scopes it allows.
          </p>
          <fieldset>
            <legend>Allow while the dialog is open</legend>
            <label>
              <input
                type='checkbox'
                checked={{this.allowGlobal}}
                {{on 'change' this.setAllowGlobal}}
              />
              global
            </label>
            <label>
              <input
                type='checkbox'
                checked={{this.allowPalette}}
                {{on 'change' this.setAllowPalette}}
              />
              palette
            </label>
          </fieldset>
          <button type='button' {{on 'click' this.openDialog}}>
            Open dialog
            <kbd>{{this.formatForDisplay 'Alt+[KeyO]'}}</kbd>
          </button>
          {{#if this.dialogOpen}}
            {{useHotkey 'Escape' this.closeDialog scope='dialog'}}
            {{! Saves the dialog. The document's Mod+S is suspended while it's
                open. }}
            {{useHotkey 'Mod+S' this.saveSettings scope='dialog'}}
            {{! The folders register Alt+N too, but their scopes are
                suspended. }}
            {{useHotkey 'Alt+[KeyN]' this.nextStep scope='dialog-steps'}}
            {{! It renders in place, inside the section. Its hotkeys take their
                scope from the `scope` option and the activation, not from
                where the DOM is. }}
            <div class='backdrop'>
              <div
                class='dialog'
                role='dialog'
                aria-modal='true'
                aria-labelledby='dialog-title'
              >
                <h2 id='dialog-title'>Edit settings</h2>
                <p>
                  <kbd>{{this.formatForDisplay 'Mod+S'}}</kbd>
                  saves this dialog instead of the document.
                  <kbd>{{this.formatForDisplay 'Escape'}}</kbd>
                  closes it.
                </p>
                <p class='panel'>Step {{this.step}} of 3.
                  <kbd>{{this.formatForDisplay 'Alt+[KeyN]'}}</kbd>
                  moves to the next step.</p>
                <div class='actions'>
                  <button
                    type='button'
                    class='secondary'
                    {{on 'click' this.closeDialog}}
                  >
                    Cancel
                  </button>
                  <button type='button' {{on 'click' this.saveSettings}}>
                    Save
                  </button>
                </div>
              </div>
            </div>
          {{/if}}
          <p role='status'>Dialog is
            {{if this.dialogOpen 'open' 'closed'}}. Saved
            {{plural this.settingsSaves 'time'}}.</p>
        </section>

        <section class='demo-section'>
          <h2>Scope state</h2>
          <div role='status'>
            <p>Active: {{this.list this.scopes.value.active}}</p>
            <p>Exclusive: {{if
                this.scopes.value.exclusive
                this.scopes.value.exclusive
                'none'
              }}</p>
            <p>Allowed: {{this.list this.scopes.value.allowed}}</p>
            <p>Suspended: {{this.list this.scopes.value.suspended}}</p>
          </div>
        </section>
      </main>
    </div>
  </template>
}

export default App