Hotkeys Docs
Lit Example: Held Keys
import {
FormatForDisplayController,
HeldKeyCodesController,
HeldKeysController,
HotkeyController,
HotkeyHintController,
hotkey,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import appStyles from './index.css?raw'
@customElement('my-app')
export class MyApp extends LitElement {
static styles = [
css`
:host {
display: block;
margin: 0;
font-family: system-ui, -apple-system, sans-serif;
background: #f5f5f5;
color: #333;
box-sizing: border-box;
}
:host *,
:host *::before,
:host *::after {
box-sizing: border-box;
}
`,
unsafeCSS(appStyles),
]
@state() private history: Array<string> = []
@state() private lastAction = 'none'
@state() private boldEnabled = true
private formatForDisplay = new FormatForDisplayController(this)
// Held keys in press order, such as ['Shift', 'A']. Updates on every
// keydown and keyup, and empties when the window loses focus.
private heldKeys = new HeldKeysController(this)
// Each held key's physical `event.code`, such as { Shift: 'ShiftLeft' }.
private heldCodes = new HeldKeyCodesController(this)
// True while the user holds Mod, and the Mod+S below can fire. The hint
// registers nothing: it reads the held keys and the registrations.
private saveHint = new HotkeyHintController(this, 'Mod+S')
// False while Bold is disabled, even with Mod held, because no enabled
// registration of Mod+B can fire.
private boldHint = new HotkeyHintController(this, 'Mod+B')
// True while the user holds Mod, Shift, or both. Holding a modifier the
// hotkey doesn't use, such as Alt, hides it.
private exportHint = new HotkeyHintController(this, 'Mod+Shift+E')
// With `exact: true`, only Mod and Shift held together show the hint.
// Without it, Mod or Shift alone would show it, as for Export.
private archiveHint = new HotkeyHintController(this, 'Mod+Shift+A', {
exact: true,
})
// The most keys held at once since nothing was held.
private mostHeld: Array<string> = []
constructor() {
super()
// While `enabled` is false, Mod+B doesn't fire, and its hint stays
// hidden. The options getter is read again after each update.
new HotkeyController(
this,
'Mod+B',
() => {
this.lastAction = 'Bold'
},
() => ({ enabled: this.boldEnabled }),
)
}
// Mod+S would open the browser's Save dialog. A matched hotkey calls
// `preventDefault` by default, so the page handles it instead.
@hotkey('Mod+S')
save() {
this.lastAction = 'Save'
}
@hotkey('Mod+Shift+E')
export() {
this.lastAction = 'Export'
}
@hotkey('Mod+Shift+A')
archive() {
this.lastAction = 'Archive'
}
// Runs before each render, after the held keys change. Once every key is
// released, records the most keys held at once, such as
// 'Shift + Control + A', and keeps the last 10. Setting state here doesn't
// cause another update.
override willUpdate() {
const heldKeys = this.heldKeys.value
if (heldKeys.length > this.mostHeld.length) this.mostHeld = heldKeys
if (heldKeys.length > 0 || this.mostHeld.length === 0) return
const combination = this.mostHeld.join(' + ')
this.mostHeld = []
this.history = [...this.history.slice(-9), combination]
}
render() {
const formatForDisplay = this.formatForDisplay.format
const heldKeys = this.heldKeys.value
const heldCodes = this.heldCodes.value
const shownHints = [
this.saveHint.value && 'Save',
this.boldHint.value && 'Bold',
this.exportHint.value && 'Export',
this.archiveHint.value && 'Archive',
].filter(Boolean)
return html`
<div class="app">
<header>
<h1>HeldKeysController</h1>
<p>
Track which keys the user is holding, and show a hotkey's label only
while its modifiers are held.
</p>
</header>
<main>
<section class="demo-section">
<h2>Held keys</h2>
<p>
Hold <kbd>Shift</kbd> + <kbd>Control</kbd> + <kbd>A</kbd>, or
press several letters at once, then release them one by one.
</p>
<div class="key-display" aria-hidden="true">
${heldKeys.map(
// `{ key }` formats a raw `event.key` value, such as
// 'Control' as ⌃ on macOS.
(key) =>
html`<kbd class="large">${formatForDisplay({ key })}</kbd>`,
)}
</div>
<p role="status">
${
heldKeys.length > 0
? `Held: ${heldKeys.join(' + ')}`
: 'No keys held'
}
</p>
</section>
<section class="demo-section">
<h2>Held key codes</h2>
<p>
The physical key behind each held key. Left and right
<kbd>Shift</kbd> both hold <code>Shift</code>, with different
codes.
</p>
<p role="status">
${
heldKeys.length > 0
? heldKeys
.map((key) => `${key}: ${heldCodes[key]}`)
.join(', ')
: 'No keys held'
}
</p>
</section>
<section class="demo-section">
<h2>Hotkey hints</h2>
<p>
Hold <kbd>${formatForDisplay('Mod')}</kbd>, <kbd>Shift</kbd>, or
both to see which shortcuts they lead to.
</p>
<div class="toolbar">
<button @click=${() => (this.lastAction = 'Save')}>
Save
${
this.saveHint.value
? html`<kbd>${formatForDisplay('Mod+S')}</kbd>`
: null
}
</button>
<button @click=${() => (this.lastAction = 'Bold')}>
Bold
${
this.boldHint.value
? html`<kbd>${formatForDisplay('Mod+B')}</kbd>`
: null
}
</button>
<button @click=${() => (this.lastAction = 'Export')}>
Export
${
this.exportHint.value
? html`<kbd>${formatForDisplay('Mod+Shift+E')}</kbd>`
: null
}
</button>
<button @click=${() => (this.lastAction = 'Archive')}>
Archive
${
this.archiveHint.value
? html`<kbd>${formatForDisplay('Mod+Shift+A')}</kbd>`
: null
}
</button>
</div>
<label>
<input
type="checkbox"
.checked=${this.boldEnabled}
@change=${(e: Event) =>
(this.boldEnabled = (e.target as HTMLInputElement).checked)}
/>
Enable Bold
</label>
<p>Last action: ${this.lastAction}</p>
<p role="status">
${
shownHints.length > 0
? `Hints shown: ${shownHints.join(', ')}`
: 'Hints shown: none'
}
</p>
</section>
<section class="demo-section">
<h2>Recent combinations</h2>
<p>
Each entry is the most keys you held at once, added when you
release them all.
</p>
<p role="status">
Recorded ${this.history.length}
${this.history.length === 1 ? 'combination' : 'combinations'}
</p>
<ol class="history-list">
${this.history.map((combination) => html`<li>${combination}</li>`)}
</ol>
<button @click=${() => (this.history = [])}>Clear history</button>
</section>
</main>
</div>
`
}
}
declare global {
interface HTMLElementTagNameMap {
'my-app': MyApp
}
}