Skip to content

Svelte Example: Scopes

<script lang="ts">
  import {
    HotkeysProvider,
    createHotkey,
    getFormatForDisplay,
    getHotkeyScopesState,
  } from '@tanstack/svelte-hotkeys'
  import EnabledScopes from './EnabledScopes.svelte'
  import ExclusiveScopes from './ExclusiveScopes.svelte'
  import NestedScopes from './NestedScopes.svelte'
  import Palette from './Palette.svelte'

  // Every hotkey in this example is a plain `createHotkey` call with no
  // `scope` option. It registers in the scope of the nearest
  // `HotkeysProvider` that sets one, or in `global` when no provider above it
  // sets a scope.

  const formatForDisplay = getFormatForDisplay()
  let helpOpened = $state(0)
  // Under the root provider in Root.svelte, which sets no scope, so it's in
  // `global`.
  createHotkey('Alt+[KeyH]', () => helpOpened++)

  // The hotkey manager's scope state, which updates as scopes change.
  const scopes = getHotkeyScopesState()
  // Sorted, because the order scopes activate in depends on the order the
  // framework mounts components. `global` is always active and isn't listed.
  const list = (names: ReadonlyArray<string>) =>
    names.length > 0 ? [...names].sort().join(', ') : 'none'
</script>

<div class="app">
  <header>
    <h1>Hotkey scopes</h1>
    <p>
      Each <code>HotkeysProvider</code> with a <code>scope</code> groups the hotkeys
      inside it. They fire while the provider is mounted and enabled, and no exclusive
      scope suspends them.
    </p>
  </header>
  <main>
    <section class="demo-section">
      <h2>Global scope</h2>
      <p>
        <kbd>{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 {helpOpened}
        {helpOpened === 1 ? 'time' : 'times'}
      </p>
    </section>
    <HotkeysProvider scope="palette">
      <Palette />
    </HotkeysProvider>
    <HotkeysProvider scope="document">
      <NestedScopes />
    </HotkeysProvider>
    <HotkeysProvider scope="mail">
      <EnabledScopes />
    </HotkeysProvider>
    <HotkeysProvider scope="settings">
      <ExclusiveScopes />
    </HotkeysProvider>
    <section class="demo-section">
      <h2>Scope state</h2>
      <div role="status">
        <p>Active: {list(scopes.state.active)}</p>
        <p>Exclusive: {scopes.state.exclusive ?? 'none'}</p>
        <p>Allowed: {list(scopes.state.allowed)}</p>
        <p>Suspended: {list(scopes.state.suspended)}</p>
      </div>
    </section>
  </main>
</div>