Hotkeys Docs
Ember Example: UseHotkey
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import { hash } from '@ember/helper'
import { on } from '@ember/modifier'
import { modifier } from 'ember-modifier'
import {
onHotkey,
useFormatForDisplay,
useHotkey,
} from '@tanstack/ember-hotkeys'
import type { HotkeyCallback } from '@tanstack/ember-hotkeys'
// Ember has no provider component. To set defaults for every hotkey, create
// a scope with `createHotkeysScope({ hotkey: { ... } })` and use the helpers
// it returns. Options passed to a helper override the scope's defaults.
export default class App extends Component {
formatForDisplay = useFormatForDisplay()
// Chords as strings and objects
@tracked lastBasic = 'none'
// `hotkey` is the chord as registered, with `Mod` kept. `parsedChord` has
// `Mod` resolved for this platform: Meta on macOS, Control elsewhere.
// A helper can't tell its callback which kind of hotkey it has, so check
// `context.kind` before reading `parsedChord`.
showChord: HotkeyCallback = (_event, context) => {
if (context.kind === 'chord') {
this.lastBasic = `${context.hotkey} (modifiers: ${context.parsedChord.modifiers.join('+') || 'none'})`
}
}
// Fire once while held
@tracked resetCount = 0
countReset = () => this.resetCount++
// Fire on key release
@tracked previewShown = false
showPreview = () => (this.previewShown = true)
hidePreview = () => (this.previewShown = false)
// Turn hotkeys on and off
@tracked stateEnabled = true
@tracked eCount = 0
@tracked gCount = 0
toggleStateEnabled = (event: Event) =>
(this.stateEnabled = (event.target as HTMLInputElement).checked)
countE = () => this.eCount++
countG = () => this.gCount++
// Keeps the Mod+G checkbox element, so `enabled` can read it.
getterCheckbox: HTMLInputElement | undefined
storeGetterCheckbox = modifier((element: HTMLInputElement) => {
this.getterCheckbox = element
})
// A function is read on each key press, for state that Ember doesn't
// track. This one reads an uncontrolled checkbox, so toggling it doesn't
// re-render. Keep the function cheap: it runs on every key press.
isGEnabled = () => this.getterCheckbox?.checked ?? false
// Listen on one element
@tracked drawerOpen = false
@tracked panelCount = 0
@tracked drawerCount = 0
toggleDrawer = () => (this.drawerOpen = !this.drawerOpen)
countPanel = () => this.panelCount++
countDrawer = () => this.drawerCount++
// Typing in text fields
@tracked lastInputs = 'none'
// `context.hotkey` is typed as a chord or a sequence until `context.kind`
// narrows it.
showInputs: HotkeyCallback = (_event, context) => {
if (context.kind === 'chord') this.lastInputs = context.hotkey
}
// The browser's default action
@tracked lastPrevent = 'none'
showPrevent: HotkeyCallback = (_event, context) => {
if (context.kind === 'chord') this.lastPrevent = context.hotkey
}
// Stop outer hotkeys
@tracked stopPanel = true
@tracked stopPanelCount = 0
@tracked stopPageCount = 0
toggleStopPanel = (event: Event) =>
(this.stopPanel = (event.target as HTMLInputElement).checked)
countStopPanel = () => this.stopPanelCount++
countStopPage = () => this.stopPageCount++
// Run before a widget's own handler
@tracked bubbleCount = 0
@tracked captureCount = 0
countBubble = () => this.bubbleCount++
countCapture = () => this.captureCount++
// Stands in for a component that handles keys itself.
stopEveryKey = (event: KeyboardEvent) => event.stopPropagation()
// Keys another listener already handled
@tracked bCount = 0
@tracked iCount = 0
countB = () => this.bCount++
countI = () => this.iCount++
// Stands in for a rich text editor that handles its own chords.
preventChords = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey) event.preventDefault()
}
// Duplicate hotkeys
@tracked yCount = 0
@tracked uCount = 0
countY = () => this.yCount++
countU = () => this.uCount++
<template>
<div class='app'>
<header>
<h1>useHotkey</h1>
<p>
useHotkey registers one hotkey while the helper is rendered. Each
section below shows one way to write a hotkey or one of its options.
</p>
</header>
<main>
<section class='demo-section'>
<h2>Chords as strings and objects</h2>
{{! Mod+S would open the browser's Save dialog. A matched hotkey
calls preventDefault by default, so the dialog stays closed.
`meta` doesn't change matching. The devtools and cheat sheets
read it. }}
{{useHotkey
'Mod+S'
this.showChord
meta=(hash name='Save' description='Save the document')
}}
{{! Function keys, arrow keys, and named keys use their event.key
names. To match a key by position instead, write its code:
'Mod+[KeyS]'. }}
{{useHotkey 'F2' this.showChord}}
{{useHotkey 'Alt+ArrowUp' this.showChord}}
{{useHotkey 'Escape' this.showChord}}
{{! The same chord as an object, for chords built from data such as
modifier checkboxes. `hotkey` reports it as the string
'Mod+Shift+S'. }}
{{useHotkey (hash key='S' mod=true shift=true) this.showChord}}
<p>
Press
<kbd>{{this.formatForDisplay 'Mod+S'}}</kbd>,
<kbd>{{this.formatForDisplay 'F2'}}</kbd>,
<kbd>{{this.formatForDisplay 'Alt+ArrowUp'}}</kbd>,
<kbd>{{this.formatForDisplay 'Escape'}}</kbd>, or
<kbd>{{this.formatForDisplay 'Mod+Shift+S'}}</kbd>. The last one is
written as an object.
</p>
<p role='status' class='info-box'>Last fired: {{this.lastBasic}}</p>
<p class='hint'>
For a hotkey per platform or more than one hotkey per action, see
the useHotkey-alternates example. For sequences such as G then H,
see useHotkey-sequences.
</p>
</section>
<section class='demo-section'>
<h2>Fire once while held</h2>
{{! Chords only. Without requireReset, holding Mod+K fires again on
every key repeat. With it, Mod+K fires once until you release a
key. }}
{{useHotkey 'Mod+K' this.countReset requireReset=true}}
<p>
Hold
<kbd>{{this.formatForDisplay 'Mod+K'}}</kbd>. The count goes up
once per press, not on every key repeat.
</p>
<p role='status' class='info-box'>Mod+K: {{this.resetCount}}</p>
</section>
<section class='demo-section'>
<h2>Fire on key release</h2>
{{! Hold Mod+P to show the preview. The keydown hotkey shows it, and
the keyup hotkey hides it when you release P or Mod. The two
don't conflict because their eventType differs. A keyup hotkey
still calls preventDefault on the keydown, so the print dialog
doesn't open. }}
{{useHotkey 'Mod+P' this.showPreview}}
{{useHotkey 'Mod+P' this.hidePreview eventType='keyup'}}
<p>
Hold
<kbd>{{this.formatForDisplay 'Mod+P'}}</kbd>
to show the preview. Release it to hide the preview.
</p>
<p role='status' class='info-box'>{{if
this.previewShown
'Preview shown'
'Preview hidden'
}}</p>
</section>
<section class='demo-section'>
<h2>Turn hotkeys on and off</h2>
{{! A disabled hotkey stays registered and visible in the devtools.
It doesn't call preventDefault, so the browser handles Mod+E. }}
{{useHotkey 'Mod+E' this.countE enabled=this.stateEnabled}}
{{! isGEnabled is a function, read on each key press. }}
{{useHotkey 'Mod+G' this.countG enabled=this.isGEnabled}}
<p>
<kbd>{{this.formatForDisplay 'Mod+E'}}</kbd>
reads
<code>enabled</code>
from a tracked property.
<kbd>{{this.formatForDisplay 'Mod+G'}}</kbd>
reads it from a function on each key press.
</p>
<label class='control'>
<input
type='checkbox'
checked={{this.stateEnabled}}
{{on 'change' this.toggleStateEnabled}}
/>
Enable Mod+E
</label>
<label class='control'>
<input type='checkbox' checked {{this.storeGetterCheckbox}} />
Enable Mod+G
</label>
<p role='status' class='info-box'>Mod+E: {{this.eCount}}, Mod+G: {{this.gCount}}</p>
</section>
<section class='demo-section'>
<h2>Listen on one element</h2>
<p>
Click the panel or the drawer, then press
<kbd>{{this.formatForDisplay 'Enter'}}</kbd>. Each has its own
hotkey.
</p>
<div class='target-grid'>
{{! The onHotkey modifier listens on its element. An element only
gets key events while it or something inside it has focus, so
the panel has tabindex 0. Enter does nothing elsewhere. }}
<div
tabindex='0'
class='target-area'
{{onHotkey 'Enter' this.countPanel}}
>
Panel
</div>
<div>
<button
type='button'
aria-expanded={{if this.drawerOpen 'true' 'false'}}
{{on 'click' this.toggleDrawer}}
>
Toggle drawer
</button>
{{! The modifier registers the drawer's Enter when the element
renders and unregisters it when the element is removed. Each
element gets its own Enter, so the two don't conflict. }}
{{#if this.drawerOpen}}
<div
tabindex='0'
class='target-area'
{{onHotkey 'Enter' this.countDrawer}}
>
Drawer
</div>
{{/if}}
</div>
</div>
<p role='status' class='info-box'>Panel: {{this.panelCount}}, drawer: {{this.drawerCount}}</p>
</section>
<section class='demo-section'>
<h2>Typing in text fields</h2>
{{! The default ignoreInputs: 'auto' decides from the hotkey. A key
that types or edits text, such as N, Shift+N, Alt+N, or an arrow
key, is skipped while a text field has focus, so N types into
the field. }}
{{useHotkey 'N' this.showInputs}}
{{! With 'auto', Control and Meta chords, Escape, and function keys
fire in text fields too, because they type nothing. }}
{{useHotkey 'Mod+Enter' this.showInputs}}
{{! true skips text fields for every hotkey. Mod+A then selects the
field's text, and selects nothing on the rest of the page. }}
{{useHotkey 'Mod+A' this.showInputs ignoreInputs=true}}
{{! false fires in text fields too. 'auto' would skip Shift+Enter
there. }}
{{useHotkey 'Shift+Enter' this.showInputs ignoreInputs=false}}
<p>
Press
<kbd>{{this.formatForDisplay 'N'}}</kbd>,
<kbd>{{this.formatForDisplay 'Mod+Enter'}}</kbd>,
<kbd>{{this.formatForDisplay 'Mod+A'}}</kbd>, and
<kbd>{{this.formatForDisplay 'Shift+Enter'}}</kbd>
on the page, then in the text field. In the field, N types and
Mod+A selects the text.
</p>
<label class='control'>
Text field
<input type='text' />
</label>
<p role='status' class='info-box'>Last fired: {{this.lastInputs}}</p>
</section>
<section class='demo-section'>
<h2>The browser's default action</h2>
<p>
Type 1, 2, and 3 in the field. Only 2 types, because the hotkeys
for 1 and 3 call
<code>preventDefault</code>. The hotkey for 3 is disabled, so it
doesn't fire.
</p>
<label class='control'>
Digits
{{! These hotkeys listen on the text field. A hotkey on a field
always gets its keys, whatever ignoreInputs says. By default a
matched hotkey calls preventDefault, so 1 doesn't type.
preventDefault=false lets the browser act too, so 2 fires the
hotkey and types. A disabled hotkey normally leaves the key to
the browser. 'always' keeps calling preventDefault while the
hotkey is disabled, so 3 doesn't type and the callback doesn't
run. }}
<input
type='text'
{{onHotkey '1' this.showPrevent}}
{{onHotkey '2' this.showPrevent preventDefault=false}}
{{onHotkey
'3'
this.showPrevent
enabled=false
preventDefault='always'
}}
/>
</label>
<p role='status' class='info-box'>Last fired: {{this.lastPrevent}}</p>
</section>
<section class='demo-section'>
<h2>Stop outer hotkeys</h2>
{{useHotkey 'Mod+D' this.countStopPage}}
<p>
The panel and the page each have a
<kbd>{{this.formatForDisplay 'Mod+D'}}</kbd>
hotkey. Click the panel and press it, then turn off stopping and
press it again.
</p>
<label class='control'>
<input
type='checkbox'
checked={{this.stopPanel}}
{{on 'change' this.toggleStopPanel}}
/>
Stop propagation in the panel
</label>
{{! With focus inside the panel, its hotkey runs before the page's
hotkey for the same key. stopPropagation=true, the default,
stops the event there, so the page's Mod+D doesn't fire. With
false, both fire. }}
<div
tabindex='0'
class='target-area'
{{onHotkey
'Mod+D'
this.countStopPanel
stopPropagation=this.stopPanel
}}
>
Panel
</div>
<p role='status' class='info-box'>Panel: {{this.stopPanelCount}}, page: {{this.stopPageCount}}</p>
</section>
<section class='demo-section'>
<h2>Run before a widget's own handler</h2>
{{! Hotkeys listen in the bubble phase, after the focused element's
own handlers. The widget below calls stopPropagation on every
key, so Mod+ArrowUp never reaches the page while the widget has
focus. }}
{{useHotkey 'Mod+ArrowUp' this.countBubble}}
{{! capture=true runs the hotkey on the way down, before the
widget's handler. With the default stopPropagation=true, the
widget then doesn't see Mod+ArrowDown at all. }}
{{useHotkey 'Mod+ArrowDown' this.countCapture capture=true}}
<p>
Click the widget, which stops every key from reaching the page.
Then press
<kbd>{{this.formatForDisplay 'Mod+ArrowUp'}}</kbd>
and
<kbd>{{this.formatForDisplay 'Mod+ArrowDown'}}</kbd>. Only the
capture hotkey fires.
</p>
<div tabindex='0' class='target-area' {{on 'keydown' this.stopEveryKey}}>
Widget
</div>
<p role='status' class='info-box'>Bubble: {{this.bubbleCount}}, capture: {{this.captureCount}}</p>
</section>
<section class='demo-section'>
<h2>Keys another listener already handled</h2>
{{! The editor below calls preventDefault on its Control and Meta
chords, as rich text editors do for Mod+B. With
ignoreDefaultPrevented=true, the hotkey skips a key press that
another listener already prevented. }}
{{useHotkey 'Mod+B' this.countB ignoreDefaultPrevented=true}}
{{! By default a hotkey fires even when the key was already
prevented. }}
{{useHotkey 'Mod+I' this.countI}}
<p>
Click the editor and press
<kbd>{{this.formatForDisplay 'Mod+B'}}</kbd>
and
<kbd>{{this.formatForDisplay 'Mod+I'}}</kbd>. The editor prevents
both, so only Mod+I fires. Outside the editor, both fire.
</p>
<div
tabindex='0'
class='target-area'
{{on 'keydown' this.preventChords}}
>
Editor
</div>
<p role='status' class='info-box'>Mod+B: {{this.bCount}}, Mod+I: {{this.iCount}}</p>
</section>
<section class='demo-section'>
<h2>Duplicate hotkeys</h2>
{{! Two registrations of the same hotkey on the same target both
run. conflictBehavior is checked when the second one registers,
so set it on each registration that may register second. 'allow'
registers both silently. }}
{{useHotkey 'Mod+Y' this.countY conflictBehavior='allow'}}
{{useHotkey 'Mod+Y' this.countY conflictBehavior='allow'}}
{{! The default, 'warn', also registers both, and logs
"[hotkeys] 'Mod+U' is already registered" in development. This
example triggers that warning on purpose. 'error' throws when
the second one registers instead. }}
{{useHotkey 'Mod+U' this.countU}}
{{useHotkey 'Mod+U' this.countU}}
<p>
<kbd>{{this.formatForDisplay 'Mod+Y'}}</kbd>
and
<kbd>{{this.formatForDisplay 'Mod+U'}}</kbd>
are each registered twice, so one press runs two callbacks. Mod+U
uses the default
<code>conflictBehavior</code>, so the console shows a warning for
it in development.
</p>
<p role='status' class='info-box'>Mod+Y: {{this.yCount}}, Mod+U: {{this.uCount}}</p>
</section>
</main>
</div>
</template>
}