Skip to content

Alpine Example: Scopes

import {
  createHotkeysScope,
  getHotkeyManager,
  hotkeysPlugin,
} from '@tanstack/alpine-hotkeys'
import Alpine from 'alpinejs'
import './index.css'

// Gives every hotkeys scope the app's Alpine instance.
Alpine.plugin(hotkeysPlugin)

// Alpine has no provider component, so a scope is just a name. Activate it on
// the hotkey manager while that part of the page is in use, and pass the same
// name as `scope` to each hotkey that belongs to it. A hotkey without `scope`
// is in `global`. `activateScope` returns a function that releases the scope.

class App {
  // Owns this component's hotkeys and subscriptions until `destroy()`.
  private hotkeysScope = createHotkeysScope()
  private releasePage: Array<() => void> = []
  private releaseComments: (() => void) | undefined
  private releaseFolder: (() => void) | undefined
  private releaseDialog: (() => void) | undefined

  formatForDisplay = this.hotkeysScope.createFormatForDisplay()
  // The manager's `active`, `exclusive`, `allowed`, and `suspended` scopes in
  // `.value`, updated as scopes activate and release.
  scopes = this.hotkeysScope.createHotkeyScopesState()

  helpOpened = 0
  paletteOpened = 0
  saves = 0
  posts = 0
  showComments = true
  current: 'Inbox' | 'Archive' | 'Spam' = 'Inbox'
  items = { Inbox: 0, Archive: 0, Spam: 0 }
  open = false
  dialogSaves = 0
  allowGlobal = false
  allowPalette = true
  step = 1

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

  setShowComments(show: boolean) {
    this.showComments = show
    this.releaseComments?.()
    this.releaseComments = undefined
    if (show) {
      // `parent: 'document'` nests `comments` in `document`, so its Mod+S
      // wins while both are active. Without it, `comments` wins only because
      // it activated later.
      this.releaseComments = getHotkeyManager().activateScope('comments', {
        parent: 'document',
      })
    }
  }

  selectFolder(folder: 'Inbox' | 'Archive' | 'Spam') {
    this.current = folder
    // Only the selected folder's scope is active, so Alt+N adds to that one.
    // The other folders' hotkeys stay registered and don't fire.
    this.releaseFolder?.()
    this.releaseFolder = getHotkeyManager().activateScope(
      folder.toLowerCase(),
      {
        parent: 'mail',
      },
    )
  }

  openDialog() {
    if (this.open) return
    this.open = true
    this.step = 1
    // `exclusive` without `allow` suspends every other scope, including
    // `global`. To change `allow` while the dialog is open, release and
    // activate again. The backdrop stops that here.
    const releaseDialog = getHotkeyManager().activateScope('dialog', {
      exclusive: {
        allow: [
          ...(this.allowGlobal ? ['global'] : []),
          ...(this.allowPalette ? ['palette'] : []),
        ],
      },
      parent: 'settings',
    })
    // Without `parent: 'dialog'`, the exclusive dialog scope would suspend
    // this one too, and Alt+N in the dialog would do nothing.
    const releaseSteps = getHotkeyManager().activateScope('dialog-steps', {
      parent: 'dialog',
    })
    this.releaseDialog = () => {
      releaseSteps()
      releaseDialog()
    }
  }

  closeDialog() {
    this.open = false
    this.releaseDialog?.()
    this.releaseDialog = undefined
  }

  saveDialog() {
    this.dialogSaves++
    this.closeDialog()
  }

  init() {
    this.releasePage = [
      getHotkeyManager().activateScope('palette'),
      getHotkeyManager().activateScope('document'),
      getHotkeyManager().activateScope('mail'),
      getHotkeyManager().activateScope('settings'),
    ]
    this.setShowComments(true)
    this.selectFolder('Inbox')

    // No `scope` option, so it's in `global`. Only an exclusive scope
    // suspends it.
    this.hotkeysScope.createHotkey('Alt+[KeyH]', () => {
      this.helpOpened++
    })

    // In its own `palette` scope, so the dialog below can allow just this.
    // Mod+K would focus the browser's search bar on Windows and Linux. A
    // matched hotkey calls `preventDefault` by default.
    this.hotkeysScope.createHotkey(
      'Mod+K',
      () => {
        this.paletteOpened++
      },
      { scope: 'palette' },
    )

    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default.
    this.hotkeysScope.createHotkey(
      'Mod+S',
      () => {
        this.saves++
      },
      { scope: 'document' },
    )
    // Only this one runs while both are active, because `comments` is nested
    // in `document`.
    this.hotkeysScope.createHotkey(
      'Mod+S',
      () => {
        this.posts++
      },
      { scope: 'comments' },
    )

    this.hotkeysScope.createHotkey(
      'Alt+[KeyI]',
      () => this.selectFolder('Inbox'),
      { scope: 'mail' },
    )
    this.hotkeysScope.createHotkey(
      'Alt+[KeyA]',
      () => this.selectFolder('Archive'),
      { scope: 'mail' },
    )
    this.hotkeysScope.createHotkey(
      'Alt+[KeyS]',
      () => this.selectFolder('Spam'),
      { scope: 'mail' },
    )
    // The same hotkey in every folder. Only the active folder's scope fires
    // it.
    this.hotkeysScope.createHotkey(
      'Alt+[KeyN]',
      () => {
        this.items.Inbox++
      },
      { scope: 'inbox' },
    )
    this.hotkeysScope.createHotkey(
      'Alt+[KeyN]',
      () => {
        this.items.Archive++
      },
      { scope: 'archive' },
    )
    this.hotkeysScope.createHotkey(
      'Alt+[KeyN]',
      () => {
        this.items.Spam++
      },
      { scope: 'spam' },
    )

    this.hotkeysScope.createHotkey('Alt+[KeyO]', () => this.openDialog(), {
      scope: 'settings',
    })
    // These fire only while the dialog is open, because its scope is active
    // only then. The document's Mod+S is suspended meanwhile.
    this.hotkeysScope.createHotkey('Escape', () => this.closeDialog(), {
      scope: 'dialog',
    })
    this.hotkeysScope.createHotkey('Mod+S', () => this.saveDialog(), {
      scope: 'dialog',
    })
    // The folders register Alt+N too, but their scopes are suspended.
    this.hotkeysScope.createHotkey(
      'Alt+[KeyN]',
      () => {
        this.step = (this.step % 3) + 1
      },
      { scope: 'dialog-steps' },
    )
  }

  destroy() {
    this.closeDialog()
    this.releaseFolder?.()
    this.releaseComments?.()
    for (const release of this.releasePage) release()
    this.hotkeysScope.destroy()
  }
}

Alpine.data('app', () => new App())
Alpine.start()