Hotkeys Docs
Lit Example: Scopes
import {
FormatForDisplayController,
HotkeyScopesStateController,
getHotkeyManager,
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'
// Lit has no provider, so a scope is a name. Activate it on the hotkey
// manager while it should work, and pass `scope` to every hotkey that
// belongs to it. A hotkey without `scope` is in `global`. Where a scope's
// markup renders doesn't matter: only the `scope` option and the activation
// decide when its hotkeys fire.
@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 helpOpened = 0
@state() private paletteOpened = 0
@state() private documentSaves = 0
@state() private commentsPosted = 0
@state() private showComments = true
@state() private folder: 'Inbox' | 'Archive' | 'Spam' = 'Inbox'
@state() private items = { Inbox: 0, Archive: 0, Spam: 0 }
@state() private dialogOpen = false
@state() private dialogSaves = 0
@state() private allowGlobal = false
@state() private allowPalette = true
@state() private step = 1
private formatForDisplay = new FormatForDisplayController(this)
// The manager's scope state. Updates this element as scopes change.
private scopes = new HotkeyScopesStateController(this)
// Each `activateScope` call returns a function that releases it.
private releasePageScopes: Array<() => void> = []
private releaseComments: (() => void) | undefined
private releaseFolder: (() => void) | undefined
private releaseDialog: (() => void) | undefined
override connectedCallback() {
super.connectedCallback()
const manager = getHotkeyManager()
// Active while the page is connected.
this.releasePageScopes = [
manager.activateScope('palette'),
manager.activateScope('document'),
manager.activateScope('mail'),
manager.activateScope('settings'),
]
this.setShowComments(this.showComments)
this.selectFolder(this.folder)
}
override disconnectedCallback() {
super.disconnectedCallback()
this.releasePageScopes.forEach((release) => release())
this.releasePageScopes = []
this.releaseComments?.()
this.releaseComments = undefined
this.releaseFolder?.()
this.releaseFolder = undefined
this.closeDialog()
}
private setShowComments(show: boolean) {
this.showComments = show
this.releaseComments?.()
this.releaseComments = undefined
// `parent: 'document'` nests `comments` in `document`, so its Mod+S wins
// while both are active. Without it, `comments` would win only because
// it activated later.
if (show) {
this.releaseComments = getHotkeyManager().activateScope('comments', {
parent: 'document',
})
}
}
private selectFolder(folder: 'Inbox' | 'Archive' | 'Spam') {
this.folder = folder
// Only the selected folder's scope is active, so Alt+N adds to that
// folder. The other folders keep their registrations and their counts.
this.releaseFolder?.()
this.releaseFolder = getHotkeyManager().activateScope(
folder.toLowerCase(),
{ parent: 'mail' },
)
}
@hotkey('Alt+[KeyO]', { scope: 'settings' })
openDialog() {
if (this.dialogOpen) return
this.dialogOpen = true
this.step = 1
const manager = getHotkeyManager()
// `exclusive` without `allow` suspends every other scope, including
// `global`. `allow` keeps the listed scopes working. To change it while
// the dialog is open, release the scope and activate it again.
const releaseDialog = manager.activateScope('dialog', {
exclusive: {
allow: [
...(this.allowGlobal ? ['global'] : []),
...(this.allowPalette ? ['palette'] : []),
],
},
parent: 'settings',
})
// Without `parent: 'dialog'`, the exclusive `dialog` scope would suspend
// this one, and Alt+N in the dialog would do nothing.
const releaseSteps = manager.activateScope('dialog-steps', {
parent: 'dialog',
})
this.releaseDialog = () => {
releaseSteps()
releaseDialog()
}
}
@hotkey('Escape', { scope: 'dialog' })
closeDialog() {
this.releaseDialog?.()
this.releaseDialog = undefined
this.dialogOpen = false
}
// Saves the dialog. The document's Mod+S is suspended while it's open.
@hotkey('Mod+S', { scope: 'dialog' })
saveDialog() {
this.dialogSaves++
this.closeDialog()
}
// In `global`, which is always active. Only an exclusive scope suspends it.
@hotkey('Alt+[KeyH]')
openHelp() {
this.helpOpened++
}
// In its own `palette` scope, so the dialog can allow just this. Mod+K
// would focus the browser's search bar on Windows and Linux. A matched
// hotkey calls `preventDefault` by default.
@hotkey('Mod+K', { scope: 'palette' })
openPalette() {
this.paletteOpened++
}
// Mod+S would open the browser's Save dialog. A matched hotkey calls
// `preventDefault` by default.
@hotkey('Mod+S', { scope: 'document' })
saveDocument() {
this.documentSaves++
}
// Only this one runs while both are active, because `comments` is nested
// in `document`.
@hotkey('Mod+S', { scope: 'comments' })
postComment() {
this.commentsPosted++
}
@hotkey('Alt+[KeyI]', { scope: 'mail' })
selectInbox() {
this.selectFolder('Inbox')
}
@hotkey('Alt+[KeyA]', { scope: 'mail' })
selectArchive() {
this.selectFolder('Archive')
}
@hotkey('Alt+[KeyS]', { scope: 'mail' })
selectSpam() {
this.selectFolder('Spam')
}
// The same hotkey in every folder's scope. Only the active folder scope
// fires it.
@hotkey('Alt+[KeyN]', { scope: 'inbox' })
addToInbox() {
this.items = { ...this.items, Inbox: this.items.Inbox + 1 }
}
@hotkey('Alt+[KeyN]', { scope: 'archive' })
addToArchive() {
this.items = { ...this.items, Archive: this.items.Archive + 1 }
}
@hotkey('Alt+[KeyN]', { scope: 'spam' })
addToSpam() {
this.items = { ...this.items, Spam: this.items.Spam + 1 }
}
// Nested in the exclusive `dialog` scope, so it stays active. The folders
// register Alt+N too, but their scopes are suspended.
@hotkey('Alt+[KeyN]', { scope: 'dialog-steps' })
nextStep() {
this.step = (this.step % 3) + 1
}
render() {
const formatForDisplay = this.formatForDisplay.format
const scopes = this.scopes.value
// Sorted, because the order scopes activate in depends on the order the
// code activates them. `global` is always active and isn't listed.
const list = (names: ReadonlyArray<string>) =>
names.length > 0 ? [...names].sort().join(', ') : 'none'
return html`
<div class="app">
<header>
<h1>Hotkey scopes</h1>
<p>
Each scope groups the hotkeys registered in it. They fire while the
scope is active, and no exclusive scope suspends them.
</p>
</header>
<main>
<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 ${this.helpOpened}
${this.helpOpened === 1 ? 'time' : 'times'}
</p>
</section>
<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 ${this.paletteOpened}
${this.paletteOpened === 1 ? 'time' : 'times'}
</p>
</section>
<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 active. Hide the comment box and the document
saves again.
</p>
<label>
<input
type="checkbox"
.checked=${this.showComments}
@change=${(e: Event) =>
this.setShowComments((e.target as HTMLInputElement).checked)}
/>
Show comment box
</label>
${
this.showComments
? html`<div class="panel">Comment box</div>`
: null
}
<p role="status">
Document saves: ${this.documentSaves}. Comments posted:
${this.commentsPosted}.
</p>
</section>
<section class="demo-section">
<h2>Enabled scopes</h2>
<p>
All three folders register
<kbd>${formatForDisplay('Alt+[KeyN]')}</kbd>. Only the selected
folder's scope is active, 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">
<button
class="panel folder"
aria-pressed=${this.folder === 'Inbox'}
@click=${() => this.selectFolder('Inbox')}
>
Inbox: ${this.items.Inbox}
${this.items.Inbox === 1 ? 'item' : 'items'}
</button>
<button
class="panel folder"
aria-pressed=${this.folder === 'Archive'}
@click=${() => this.selectFolder('Archive')}
>
Archive: ${this.items.Archive}
${this.items.Archive === 1 ? 'item' : 'items'}
</button>
<button
class="panel folder"
aria-pressed=${this.folder === 'Spam'}
@click=${() => this.selectFolder('Spam')}
>
Spam: ${this.items.Spam}
${this.items.Spam === 1 ? 'item' : 'items'}
</button>
</div>
<p role="status">
Selected: ${this.folder}. Items: Inbox ${this.items.Inbox},
Archive ${this.items.Archive}, Spam ${this.items.Spam}
</p>
</section>
<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=${this.allowGlobal}
@change=${(e: Event) =>
(this.allowGlobal = (e.target as HTMLInputElement).checked)}
/>
global
</label>
<label>
<input
type="checkbox"
.checked=${this.allowPalette}
@change=${(e: Event) =>
(this.allowPalette = (
e.target as HTMLInputElement
).checked)}
/>
palette
</label>
</fieldset>
<button @click=${() => this.openDialog()}>
Open dialog <kbd>${formatForDisplay('Alt+[KeyO]')}</kbd>
</button>
${
this.dialogOpen
? html`
<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>
<p class="panel">
Step ${this.step} of 3.
<kbd>${formatForDisplay('Alt+[KeyN]')}</kbd> moves to
the next step.
</p>
<div class="actions">
<button
class="secondary"
@click=${() => this.closeDialog()}
>
Cancel
</button>
<button @click=${() => this.saveDialog()}>
Save
</button>
</div>
</div>
</div>
`
: null
}
<p role="status">
Dialog is ${this.dialogOpen ? 'open' : 'closed'}. Saved
${this.dialogSaves} ${this.dialogSaves === 1 ? 'time' : 'times'}.
</p>
</section>
<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>
</main>
</div>
`
}
}
declare global {
interface HTMLElementTagNameMap {
'my-app': MyApp
}
}