Skip to content

Solid Example: Scopes

import { Portal, render } from '@solidjs/web'
import { TanStackDevtools } from '@tanstack/solid-devtools'
import {
  HotkeysProvider,
  createFormatForDisplay,
  createHotkey,
  createHotkeyScopesState,
} from '@tanstack/solid-hotkeys'
import { hotkeysDevtoolsPlugin } from '@tanstack/solid-hotkeys-devtools'
import { Show, createSignal } from 'solid-js'
import './index.css'

// Every hotkey below 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.

function App() {
  return (
    <HotkeysProvider>
      <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>
          <GlobalScope />
          <HotkeysProvider scope="palette">
            <Palette />
          </HotkeysProvider>
          <HotkeysProvider scope="document">
            <NestedScopes />
          </HotkeysProvider>
          <HotkeysProvider scope="mail">
            <EnabledScopes />
          </HotkeysProvider>
          <HotkeysProvider scope="settings">
            <ExclusiveScopes />
          </HotkeysProvider>
          <ScopeState />
        </main>
      </div>
      <TanStackDevtools plugins={[hotkeysDevtoolsPlugin()]} />
    </HotkeysProvider>
  )
}

/** Under the root provider, which sets no scope, so it's in `global`. */
function GlobalScope() {
  const formatForDisplay = createFormatForDisplay()
  const [opened, setOpened] = createSignal(0)
  createHotkey('Alt+[KeyH]', () => setOpened((n) => n + 1))

  return (
    <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 {opened()} {opened() === 1 ? 'time' : 'times'}
      </p>
    </section>
  )
}

/** In its own `palette` scope, so the dialog below can allow just this. */
function Palette() {
  const formatForDisplay = createFormatForDisplay()
  const [opened, setOpened] = createSignal(0)
  // Mod+K would focus the browser's search bar on Windows and Linux. A
  // matched hotkey calls `preventDefault` by default.
  createHotkey('Mod+K', () => setOpened((n) => n + 1))

  return (
    <section class="demo-section">
      <h2>Command palette</h2>
      <p>
        <kbd>{formatForDisplay('Mod+K')}</kbd> opens the palette. It's in the{' '}
        <code>palette</code> scope.
      </p>
      <p role="status">
        Palette opened {opened()} {opened() === 1 ? 'time' : 'times'}
      </p>
    </section>
  )
}

/** In the `document` scope. The comment box nests `comments` inside it. */
function NestedScopes() {
  const formatForDisplay = createFormatForDisplay()
  const [saves, setSaves] = createSignal(0)
  const [posts, setPosts] = createSignal(0)
  const [showComments, setShowComments] = createSignal(true)
  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default.
  createHotkey('Mod+S', () => setSaves((n) => n + 1))

  return (
    <section class="demo-section">
      <h2>Nested scopes</h2>
      <p>
        The document and its comment box both register{' '}
        <kbd>{formatForDisplay('Mod+S')}</kbd>. The <code>comments</code> scope
        is nested in <code>document</code>, so it wins while it's mounted. Hide
        the comment box and the document saves again.
      </p>
      <label>
        <input
          type="checkbox"
          checked={showComments()}
          onChange={(e) => setShowComments(e.currentTarget.checked)}
        />{' '}
        Show comment box
      </label>
      <Show when={showComments()}>
        <HotkeysProvider scope="comments">
          <CommentBox onPost={() => setPosts((n) => n + 1)} />
        </HotkeysProvider>
      </Show>
      <p role="status">
        Document saves: {saves()}. Comments posted: {posts()}.
      </p>
    </section>
  )
}

function CommentBox(props: { onPost: () => void }) {
  // Only this one runs while both are active, because `comments` is nested.
  createHotkey('Mod+S', () => props.onPost())
  return <div class="panel">Comment box</div>
}

/** In the `mail` scope. Each folder nests its own scope inside it. */
function EnabledScopes() {
  const formatForDisplay = createFormatForDisplay()
  const [current, setCurrent] = createSignal('Inbox')
  const [items, setItems] = createSignal({ Inbox: 0, Archive: 0, Spam: 0 })
  createHotkey('Alt+[KeyI]', () => setCurrent('Inbox'))
  createHotkey('Alt+[KeyA]', () => setCurrent('Archive'))
  createHotkey('Alt+[KeyS]', () => setCurrent('Spam'))

  return (
    <section class="demo-section">
      <h2>Enabled scopes</h2>
      <p>
        All three folders stay mounted and register{' '}
        <kbd>{formatForDisplay('Alt+[KeyN]')}</kbd>. Only the selected folder's
        provider is <code>enabled</code>, so the key adds to that one. Select
        with <kbd>{formatForDisplay('Alt+[KeyI]')}</kbd>,{' '}
        <kbd>{formatForDisplay('Alt+[KeyA]')}</kbd>, and{' '}
        <kbd>{formatForDisplay('Alt+[KeyS]')}</kbd>.
      </p>
      <div class="folders">
        {/* With `enabled={false}`, the scope stays mounted but inactive, so
            its hotkeys don't fire. Unmounting would lose the folder's state. */}
        <HotkeysProvider scope="inbox" enabled={current() === 'Inbox'}>
          <Folder
            name="Inbox"
            count={items().Inbox}
            selected={current() === 'Inbox'}
            onSelect={() => setCurrent('Inbox')}
            onAdd={() => setItems((i) => ({ ...i, Inbox: i.Inbox + 1 }))}
          />
        </HotkeysProvider>
        <HotkeysProvider scope="archive" enabled={current() === 'Archive'}>
          <Folder
            name="Archive"
            count={items().Archive}
            selected={current() === 'Archive'}
            onSelect={() => setCurrent('Archive')}
            onAdd={() => setItems((i) => ({ ...i, Archive: i.Archive + 1 }))}
          />
        </HotkeysProvider>
        <HotkeysProvider scope="spam" enabled={current() === 'Spam'}>
          <Folder
            name="Spam"
            count={items().Spam}
            selected={current() === 'Spam'}
            onSelect={() => setCurrent('Spam')}
            onAdd={() => setItems((i) => ({ ...i, Spam: i.Spam + 1 }))}
          />
        </HotkeysProvider>
      </div>
      <p role="status">
        {`Selected: ${current()}. Items: Inbox ${items().Inbox}, Archive ${items().Archive}, Spam ${items().Spam}`}
      </p>
    </section>
  )
}

function Folder(props: {
  name: string
  count: number
  selected: boolean
  onSelect: () => void
  onAdd: () => void
}) {
  // The same call in every folder. Only the enabled folder's scope fires it.
  createHotkey('Alt+[KeyN]', () => props.onAdd())
  return (
    <button
      class="panel folder"
      aria-pressed={props.selected ? 'true' : 'false'}
      onClick={() => props.onSelect()}
    >
      {props.name}: {props.count} {props.count === 1 ? 'item' : 'items'}
    </button>
  )
}

/** In the `settings` scope. The dialog nests an exclusive scope inside it. */
function ExclusiveScopes() {
  const formatForDisplay = createFormatForDisplay()
  const [open, setOpen] = createSignal(false)
  const [saves, setSaves] = createSignal(0)
  const [allowGlobal, setAllowGlobal] = createSignal(false)
  const [allowPalette, setAllowPalette] = createSignal(true)
  createHotkey('Alt+[KeyO]', () => setOpen(true))

  const allow = () => [
    ...(allowGlobal() ? ['global'] : []),
    ...(allowPalette() ? ['palette'] : []),
  ]

  return (
    <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={allowGlobal()}
            onChange={(e) => setAllowGlobal(e.currentTarget.checked)}
          />{' '}
          global
        </label>
        <label>
          <input
            type="checkbox"
            checked={allowPalette()}
            onChange={(e) => setAllowPalette(e.currentTarget.checked)}
          />{' '}
          palette
        </label>
      </fieldset>
      <button onClick={() => setOpen(true)}>
        Open dialog <kbd>{formatForDisplay('Alt+[KeyO]')}</kbd>
      </button>
      <Show when={open()}>
        {/* `exclusive` without `allow` suspends every other scope. The
            `allow` array is compared by value, so a new array on each read
            doesn't reactivate the scope. */}
        <HotkeysProvider scope="dialog" exclusive={{ allow: allow() }}>
          <Dialog
            onClose={() => setOpen(false)}
            onSave={() => {
              setSaves((n) => n + 1)
              setOpen(false)
            }}
          />
        </HotkeysProvider>
      </Show>
      <p role="status">
        Dialog is {open() ? 'open' : 'closed'}. Saved {saves()}{' '}
        {saves() === 1 ? 'time' : 'times'}.
      </p>
    </section>
  )
}

function Dialog(props: { onClose: () => void; onSave: () => void }) {
  const formatForDisplay = createFormatForDisplay()
  createHotkey('Escape', () => props.onClose())
  // Saves the dialog. The document's Mod+S is suspended while it's open.
  createHotkey('Mod+S', () => props.onSave())

  // Portaled to the body, outside the section. The scope comes from the
  // provider around this component, not from where its DOM renders.
  return (
    <Portal>
      <div class="backdrop">
        <div
          class="dialog"
          role="dialog"
          aria-modal="true"
          aria-labelledby="dialog-title"
        >
          <h2 id="dialog-title">Edit settings</h2>
          <p>
            <kbd>{formatForDisplay('Mod+S')}</kbd> saves this dialog instead of
            the document. <kbd>{formatForDisplay('Escape')}</kbd> closes it.
          </p>
          <HotkeysProvider scope="dialog-steps">
            <Steps />
          </HotkeysProvider>
          <div class="actions">
            <button class="secondary" onClick={() => props.onClose()}>
              Cancel
            </button>
            <button onClick={() => props.onSave()}>Save</button>
          </div>
        </div>
      </div>
    </Portal>
  )
}

/** Nested in the exclusive `dialog` scope, so it stays active. */
function Steps() {
  const formatForDisplay = createFormatForDisplay()
  const [step, setStep] = createSignal(1)
  // The folders register Alt+N too, but their scopes are suspended.
  createHotkey('Alt+[KeyN]', () => setStep((n) => (n % 3) + 1))

  return (
    <p class="panel">
      Step {step()} of 3. <kbd>{formatForDisplay('Alt+[KeyN]')}</kbd> moves to
      the next step.
    </p>
  )
}

/** Reads the hotkey manager's scope state, which updates as scopes change. */
function ScopeState() {
  const scopes = createHotkeyScopesState()
  // 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'

  return (
    <section class="demo-section">
      <h2>Scope state</h2>
      <div role="status">
        <p>Active: {list(scopes().active)}</p>
        <p>Exclusive: {scopes().exclusive ?? 'none'}</p>
        <p>Allowed: {list(scopes().allowed)}</p>
        <p>Suspended: {list(scopes().suspended)}</p>
      </div>
    </section>
  )
}

render(() => <App />, document.getElementById('root')!)