Skip to content

Octane Example: Scopes

import { createPortal, createRoot, useState } from 'octane'

import {
  HotkeysProvider,
  useFormatForDisplay,
  useHotkey,
  useHotkeyScopesState,
} from '@tanstack/octane-hotkeys'

import './index.css'

// Every hotkey below is a plain `useHotkey` 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() @{
  <HotkeysProvider>
    <div className="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>
  </HotkeysProvider>
}

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

  <section className="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 = useFormatForDisplay()
  const [opened, setOpened] = useState(0)
  // Mod+K would focus the browser's search bar on Windows and Linux. A
  // matched hotkey calls `preventDefault` by default.
  useHotkey('Mod+K', () => setOpened((n) => n + 1))

  <section className="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 = useFormatForDisplay()
  const [saves, setSaves] = useState(0)
  const [posts, setPosts] = useState(0)
  const [showComments, setShowComments] = useState(true)
  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default.
  useHotkey('Mod+S', () => setSaves((n) => n + 1))

  <section className="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>
    @if (showComments) {
      <HotkeysProvider scope="comments">
        <CommentBox onPost={() => setPosts((n) => n + 1)} />
      </HotkeysProvider>
    }
    <p role="status">
      Document saves: {saves}. Comments posted: {posts}.
    </p>
  </section>
}

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

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

  <section className="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 className="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({
  name,
  count,
  selected,
  onSelect,
  onAdd,
}: {
  name: string
  count: number
  selected: boolean
  onSelect: () => void
  onAdd: () => void
}) @{
  // The same call in every folder. Only the enabled folder's scope fires it.
  useHotkey('Alt+[KeyN]', onAdd)
  <button className="panel folder" aria-pressed={selected} onClick={onSelect}>
    {name}: {count} {count === 1 ? 'item' : 'items'}
  </button>
}

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

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

  <section className="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>
    @if (open) {
      // `exclusive` without `allow` suspends every other scope. The `allow`
      // array is compared by value, so a new array each render doesn't
      // reactivate the scope.
      <HotkeysProvider scope="dialog" exclusive={{ allow }}>
        <Dialog
          onClose={() => setOpen(false)}
          onSave={() => {
            setSaves((n) => n + 1)
            setOpen(false)
          }}
        />
      </HotkeysProvider>
    }
    <p role="status">
      Dialog is {open ? 'open' : 'closed'}. Saved {saves}{' '}
      {saves === 1 ? 'time' : 'times'}.
    </p>
  </section>
}

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

  // Portaled to the body, outside the section. The scope comes from the
  // provider around this component, not from where its DOM renders.
  <>
    {createPortal(
      <div className="backdrop">
        <div
          className="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 className="actions">
            <button className="secondary" onClick={onClose}>
              Cancel
            </button>
            <button onClick={onSave}>Save</button>
          </div>
        </div>
      </div>,
      document.body,
    )}
  </>
}

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

  <p className="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 = useHotkeyScopesState()
  // 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'

  <section className="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>
}

const root = createRoot(document.getElementById('root')!)
root.render(App)
import.meta.hot?.dispose(() => root.unmount())