Skip to content

Octane Example: UseHotkey Alternates

import { createRoot, useState } from 'octane'

import {
  HotkeysProvider,
  defineAppHotkeys,
  detectPlatform,
  resolveHotkeyAlternates,
  useAppHotkeys,
  useCustomHotkeys,
  useFormatForDisplay,
  useHotkey,
  useHotkeys,
} from '@tanstack/octane-hotkeys'

import type { Hotkey, HotkeyPlatform } from '@tanstack/octane-hotkeys'

import './index.css'

const appHotkeys = defineAppHotkeys({
  'help.open': {
    hotkey: { default: '?', alternates: ['F1'] },
    meta: { name: 'Open help' },
  },
})

// Types `useAppHotkeys()` and `useCustomHotkeys()` with the ids above.
declare module '@tanstack/octane-hotkeys' {
  interface Register {
    appHotkeys: typeof appHotkeys
  }
}

function App({ platform }: { platform: HotkeyPlatform }) @{
  // Formats for the provider's platform.
  const formatForDisplay = useFormatForDisplay()
  const [lastFired, setLastFired] = useState<string | null>(null)

  // `context.hotkey` is the hotkey that fired: the first one or an alternate.
  const fire = (action: string, hotkey: Hotkey) =>
    setLastFired(
      `${action} fired from ${formatForDisplay(hotkey, { sequenceSeparator: ' then ' })}`,
    )

  // A platform replaces `default`.
  useHotkey({ default: 'Delete', mac: 'Mod+Backspace' }, (_event, context) =>
    fire('Delete item', context.hotkey),
  )
  useHotkey({ default: 'F3', mac: 'Mod+G' }, (_event, context) =>
    fire('Find next', context.hotkey),
  )

  // `null` leaves a platform without a hotkey.
  useHotkey({ default: null, mac: 'Mod+,' }, (_event, context) =>
    fire('Preferences', context.hotkey),
  )
  useHotkey({ default: 'Alt+Enter', mac: null }, (_event, context) =>
    fire('Properties', context.hotkey),
  )

  // `alternates` adds hotkeys. All of them fire the callback.
  useHotkey(
    { default: 'Space', alternates: ['K', 'MediaPlayPause'] },
    (_event, context) => fire('Play or pause', context.hotkey),
  )

  // An alternate can be a chord string, a chord object, or a sequence. The
  // hotkeys mix chords and a sequence, so both kinds' options are accepted.
  useHotkey(
    {
      default: 'Mod+K',
      alternates: ['/', { key: 'F', mod: true, shift: true }, ['G', 'S']],
    },
    (_event, context) => fire('Open search', context.hotkey),
    { timeout: 800, requireReset: true },
  )

  // An alternate can differ by platform. Windows and Linux take either
  // hotkey, and macOS takes only Mod+Shift+Z.
  useHotkey(
    {
      default: 'Mod+Y',
      mac: 'Mod+Shift+Z',
      alternates: [{ default: 'Mod+Shift+Z', mac: null }],
    },
    (_event, context) => fire('Redo', context.hotkey),
  )

  // An array in `alternates` is a sequence, so these two differ.
  useHotkey({ default: 'X', alternates: ['Q', 'W'] }, (_event, context) =>
    fire('Two alternates', context.hotkey),
  )
  useHotkey({ default: 'Z', alternates: [['Q', 'E']] }, (_event, context) =>
    fire('One sequence', context.hotkey),
  )

  // `useHotkeys` takes the same objects.
  useHotkeys([
    {
      hotkey: { default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] },
      callback: (_event, context) => fire('Zoom in', context.hotkey),
    },
    {
      hotkey: { default: 'Mod+-', alternates: ['Mod+[NumpadSubtract]'] },
      callback: (_event, context) => fire('Zoom out', context.hotkey),
    },
  ])

  // App hotkeys take them too. A custom hotkey replaces the whole object.
  const helpHotkey = useAppHotkeys()['help.open']
  const { setCustomHotkey, resetCustomHotkey } = useCustomHotkeys()
  useHotkey(helpHotkey, (_event, context) => fire('Open help', context.hotkey))

  <main>
      <div className={lastFired ? 'info-box success' : 'info-box'}>
        {lastFired ?? 'Press any hotkey from the tables below.'}
      </div>

      <section className="demo-section">
        <h2>A hotkey per platform</h2>
        <p>
          <code>default</code> is the hotkey. <code>mac</code>,{' '}
          <code>windows</code>, and <code>linux</code> replace it on that
          platform, so the default does not fire there.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Hotkey</th>
              <th>Written as</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Delete item</td>
              <td>
                <kbd>
                  {formatForDisplay({
                    default: 'Delete',
                    mac: 'Mod+Backspace',
                  })}
                </kbd>
              </td>
              <td className="source">{`{ default: 'Delete', mac: 'Mod+Backspace' }`}</td>
            </tr>
            <tr>
              <td>Find next</td>
              <td>
                <kbd>{formatForDisplay({ default: 'F3', mac: 'Mod+G' })}</kbd>
              </td>
              <td className="source">{`{ default: 'F3', mac: 'Mod+G' }`}</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section className="demo-section">
        <h2>A hotkey on some platforms only</h2>
        <p>
          <code>null</code> leaves a platform without a hotkey, and nothing
          registers there. <code>formatForDisplay</code> returns an empty string
          for it. <code>default</code> is required, so a platform is never left
          out by accident.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Hotkey</th>
              <th>Written as</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Preferences</td>
              <td>
                <kbd>
                  {formatForDisplay({ default: null, mac: 'Mod+,' }) || 'None'}
                </kbd>
              </td>
              <td className="source">{`{ default: null, mac: 'Mod+,' }`}</td>
            </tr>
            <tr>
              <td>Properties</td>
              <td>
                <kbd>
                  {formatForDisplay({ default: 'Alt+Enter', mac: null }) ||
                    'None'}
                </kbd>
              </td>
              <td className="source">{`{ default: 'Alt+Enter', mac: null }`}</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section className="demo-section">
        <h2>Alternates</h2>
        <p>
          <code>alternates</code> lists more hotkeys for the same action. Each
          one is a chord string, a chord object, or a sequence.{' '}
          <code>formatForDisplay</code> shows the first hotkey, or every hotkey
          when you pass <code>alternatesSeparator</code>.{' '}
          <code>resolveHotkeyAlternates</code> returns the alternates, to format
          each one yourself.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Hotkey</th>
              <th>Alternates</th>
              <th>Written as</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Play or pause</td>
              <td>
                <kbd>
                  {formatForDisplay({
                    default: 'Space',
                    alternates: ['K', 'MediaPlayPause'],
                  })}
                </kbd>
              </td>
              <td>
                @for (const alternate of resolveHotkeyAlternates(
                  { default: 'Space', alternates: ['K', 'MediaPlayPause'] },
                  platform,
                ); index index; key index) {
                  <kbd>{formatForDisplay(alternate)}</kbd>
                }
              </td>
              <td className="source">{`{ default: 'Space', alternates: ['K', 'MediaPlayPause'] }`}</td>
            </tr>
            <tr>
              <td>Open search</td>
              <td>
                <kbd>
                  {formatForDisplay({
                    default: 'Mod+K',
                    alternates: ['/', { key: 'F', mod: true, shift: true }, ['G', 'S']],
                  })}
                </kbd>
              </td>
              <td>
                @for (const alternate of resolveHotkeyAlternates(
                  {
                    default: 'Mod+K',
                    alternates: [
                      '/',
                      { key: 'F', mod: true, shift: true },
                      ['G', 'S'],
                    ],
                  },
                  platform,
                ); index index; key index) {
                  <kbd>
                    {formatForDisplay(alternate, {
                      sequenceSeparator: ' then ',
                    })}
                  </kbd>
                }
              </td>
              <td className="source">{`{
  default: 'Mod+K',
  alternates: [
    '/',
    { key: 'F', mod: true, shift: true },
    ['G', 'S'],
  ],
}`}</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section className="demo-section">
        <h2>Alternates per platform</h2>
        <p>
          An alternate can be an object with a <code>default</code> and
          platforms. It resolves the same way as the first hotkey. Switch the
          platform above to see the alternate come and go.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Hotkey</th>
              <th>Alternates</th>
              <th>Written as</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Redo</td>
              <td>
                <kbd>
                  {formatForDisplay({ default: 'Mod+Y', mac: 'Mod+Shift+Z' })}
                </kbd>
              </td>
              <td>
                @for (const alternate of resolveHotkeyAlternates(
                  {
                    default: 'Mod+Y',
                    mac: 'Mod+Shift+Z',
                    alternates: [{ default: 'Mod+Shift+Z', mac: null }],
                  },
                  platform,
                ); index index; key index) {
                  <kbd>{formatForDisplay(alternate)}</kbd>
                }
              </td>
              <td className="source">{`{
  default: 'Mod+Y',
  mac: 'Mod+Shift+Z',
  alternates: [{ default: 'Mod+Shift+Z', mac: null }],
}`}</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section className="demo-section">
        <h2>Two alternates or one sequence</h2>
        <p>
          An array in <code>alternates</code> is a sequence. The first row fires
          from <kbd>X</kbd>, <kbd>Q</kbd>, or <kbd>W</kbd>. The second fires
          from <kbd>Z</kbd>, or from <kbd>Q</kbd> then <kbd>E</kbd>.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Written as</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Two alternates</td>
              <td className="source">{`{ default: 'X', alternates: ['Q', 'W'] }`}</td>
            </tr>
            <tr>
              <td>One sequence</td>
              <td className="source">{`{ default: 'Z', alternates: [['Q', 'E']] }`}</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section className="demo-section">
        <h2>With useHotkeys</h2>
        <p>
          Each item's <code>hotkey</code> accepts the same objects. The
          alternates here name the numpad keys by position, and the labels use{' '}
          <code>alternatesSeparator</code> to list every hotkey.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Hotkey</th>
              <th>Written as</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Zoom in</td>
              <td>
                <kbd>
                  {formatForDisplay(
                    { default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] },
                    { alternatesSeparator: ' or ' },
                  )}
                </kbd>
              </td>
              <td className="source">{`{ default: 'Mod+=', alternates: ['Mod+[NumpadAdd]'] }`}</td>
            </tr>
            <tr>
              <td>Zoom out</td>
              <td>
                <kbd>
                  {formatForDisplay(
                    { default: 'Mod+-', alternates: ['Mod+[NumpadSubtract]'] },
                    { alternatesSeparator: ' or ' },
                  )}
                </kbd>
              </td>
              <td className="source">{`{ default: 'Mod+-', alternates: ['Mod+[NumpadSubtract]'] }`}</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section className="demo-section">
        <h2>With app hotkeys</h2>
        <p>
          <code>defineAppHotkeys</code> accepts the same objects. A custom
          hotkey replaces the first hotkey and the alternates, so after you set
          one, <kbd>?</kbd> and <kbd>F1</kbd> stop working.
        </p>
        <table className="shortcut-table">
          <thead>
            <tr>
              <th>Action</th>
              <th>Hotkey</th>
              <th>Alternates</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Open help</td>
              <td>
                <kbd>
                  {(helpHotkey.hotkey && formatForDisplay(helpHotkey.hotkey)) ||
                    'Unassigned'}
                </kbd>
              </td>
              <td>
                @for (const alternate of resolveHotkeyAlternates(
                  helpHotkey.hotkey,
                  platform,
                ); index index; key index) {
                  <kbd>{formatForDisplay(alternate)}</kbd>
                }
              </td>
            </tr>
          </tbody>
        </table>
        <p>
          <button onClick={() => setCustomHotkey('help.open', 'H')}>
            Set the custom hotkey to H
          </button>
          <button onClick={() => resetCustomHotkey('help.open')}>
            Restore the default
          </button>
        </p>
      </section>

      <section className="demo-section">
        <h2>Usage</h2>
        <pre className="code-block">{`import { useHotkey } from '@tanstack/octane-hotkeys'

// A platform replaces the default
useHotkey({ default: 'Mod+Y', mac: 'Mod+Shift+Z' }, redo)

// macOS only
useHotkey({ default: null, mac: 'Mod+,' }, openPreferences)

// Alternates fire the same callback
useHotkey({ default: 'Space', alternates: ['K', 'MediaPlayPause'] }, togglePlay)

// An alternate can be a sequence
useHotkey({ default: 'Mod+K', alternates: ['/', ['G', 'S']] }, openSearch)

// An alternate can differ by platform
useHotkey(
  {
    default: 'Mod+Y',
    mac: 'Mod+Shift+Z',
    alternates: [{ default: 'Mod+Shift+Z', mac: null }],
  },
  redo,
)`}</pre>
      </section>
    </main>
}

function Root() @{
  const [platform, setPlatform] = useState(detectPlatform)

  <div className="app">
      <header>
        <h1>Platform hotkeys and alternates</h1>
        <p>
          Pass an object to <code>useHotkey</code> to give each platform its own
          hotkey, or to give one action more than one hotkey.
        </p>
        <div>
          <button
            aria-pressed={platform === 'mac'}
            onClick={() => setPlatform('mac')}
          >
            macOS
          </button>
          <button
            aria-pressed={platform === 'windows'}
            onClick={() => setPlatform('windows')}
          >
            Windows
          </button>
          <button
            aria-pressed={platform === 'linux'}
            onClick={() => setPlatform('linux')}
          >
            Linux
          </button>
        </div>
        <p>
          These buttons set the provider's platform, which resolves every hotkey
          object and label. <code>Mod</code> then means that platform's key:
          Command for macOS, Control for the others.
        </p>
      </header>

      {/* The provider registers everything again when its platform changes. */}
      <HotkeysProvider
        appHotkeys={appHotkeys}
        defaultOptions={{ platform }}
      >
        <App platform={platform} />
      </HotkeysProvider>
    </div>
}

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