import {
FormatForDisplayController,
HotkeyController,
hotkey,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, nothing, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import { createRef, ref } from 'lit/directives/ref.js'
import appStyles from './index.css?raw'
import type { HotkeyChordCallbackContext } from '@tanstack/lit-hotkeys'
@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),
]
private formatForDisplay = new FormatForDisplayController(this)
@state() private lastBasic = 'none'
@hotkey('Mod+S', { meta: { name: 'Save', description: 'Save the document' } })
@hotkey('F2')
@hotkey('Alt+ArrowUp')
@hotkey('Escape')
@hotkey({ key: 'S', mod: true, shift: true })
showChord(
_event: KeyboardEvent,
{ hotkey, parsedChord }: HotkeyChordCallbackContext,
) {
this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
}
@state() private resetCount = 0
@hotkey('Mod+K', { requireReset: true })
countReset() {
this.resetCount++
}
@state() private previewShown = false
@hotkey('Mod+P')
showPreview() {
this.previewShown = true
}
@hotkey('Mod+P', { eventType: 'keyup' })
hidePreview() {
this.previewShown = false
}
@state() private stateEnabled = true
@state() private modECount = 0
@state() private modGCount = 0
private getterCheckboxRef = createRef<HTMLInputElement>()
private modE = new HotkeyController(
this,
'Mod+E',
() => this.modECount++,
() => ({ enabled: this.stateEnabled }),
)
private modG = new HotkeyController(this, 'Mod+G', () => this.modGCount++, {
enabled: () => this.getterCheckboxRef.value?.checked ?? false,
})
@state() private panelCount = 0
@state() private drawerCount = 0
@state() private drawerOpen = false
private panelRef = createRef<HTMLDivElement>()
private drawerRef = createRef<HTMLDivElement>()
private panelEnter = new HotkeyController(
this,
'Enter',
() => this.panelCount++,
() => ({ target: this.panelRef.value }),
)
private drawerEnter = new HotkeyController(
this,
'Enter',
() => this.drawerCount++,
() => ({ target: this.drawerRef.value }),
)
@state() private lastInputs = 'none'
@hotkey('N')
@hotkey('Mod+Enter')
@hotkey('Mod+A', { ignoreInputs: true })
@hotkey('Shift+Enter', { ignoreInputs: false })
showInputHotkey(
_event: KeyboardEvent,
{ hotkey }: HotkeyChordCallbackContext,
) {
this.lastInputs = hotkey
}
@state() private lastPrevent = 'none'
private digitsRef = createRef<HTMLInputElement>()
private digitOne = new HotkeyController(
this,
'1',
(_event, { hotkey }) => (this.lastPrevent = hotkey),
() => ({ target: this.digitsRef.value }),
)
private digitTwo = new HotkeyController(
this,
'2',
(_event, { hotkey }) => (this.lastPrevent = hotkey),
() => ({ target: this.digitsRef.value, preventDefault: false }),
)
private digitThree = new HotkeyController(
this,
'3',
(_event, { hotkey }) => (this.lastPrevent = hotkey),
() => ({
target: this.digitsRef.value,
enabled: false,
preventDefault: 'always',
}),
)
@state() private stopPanel = true
@state() private stopPanelCount = 0
@state() private stopPageCount = 0
private stopPanelRef = createRef<HTMLDivElement>()
private panelModD = new HotkeyController(
this,
'Mod+D',
() => this.stopPanelCount++,
() => ({
target: this.stopPanelRef.value,
stopPropagation: this.stopPanel,
}),
)
@hotkey('Mod+D')
countPageModD() {
this.stopPageCount++
}
@state() private bubbleCount = 0
@state() private captureCount = 0
@hotkey('Mod+ArrowUp')
countBubble() {
this.bubbleCount++
}
@hotkey('Mod+ArrowDown', { capture: true })
countCapture() {
this.captureCount++
}
@state() private modBCount = 0
@state() private modICount = 0
@hotkey('Mod+B', { ignoreDefaultPrevented: true })
countModB() {
this.modBCount++
}
@hotkey('Mod+I')
countModI() {
this.modICount++
}
@state() private modYCount = 0
@state() private modUCount = 0
@hotkey('Mod+Y', { conflictBehavior: 'allow' })
@hotkey('Mod+Y', { conflictBehavior: 'allow' })
countModY() {
this.modYCount++
}
@hotkey('Mod+U')
@hotkey('Mod+U')
countModU() {
this.modUCount++
}
render() {
const formatForDisplay = this.formatForDisplay.format
return html`
<div class="app">
<header>
<h1>@hotkey</h1>
<p>
@hotkey registers one hotkey while its element is connected, and
HotkeyController does the same for options that change. 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>
<p>
Press <kbd>${formatForDisplay('Mod+S')}</kbd>,
<kbd>${formatForDisplay('F2')}</kbd>,
<kbd>${formatForDisplay('Alt+ArrowUp')}</kbd>,
<kbd>${formatForDisplay('Escape')}</kbd>, or
<kbd>${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 hotkey-alternates example. For sequences such as G then H, see
hotkey-sequences.
</p>
</section>
<section class="demo-section">
<h2>Fire once while held</h2>
<p>
Hold <kbd>${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>
<p>
Hold <kbd>${formatForDisplay('Mod+P')}</kbd> to show the preview.
Release it to hide the preview.
</p>
<p role="status" class="info-box">
${this.previewShown ? 'Preview shown' : 'Preview hidden'}
</p>
</section>
<section class="demo-section">
<h2>Turn hotkeys on and off</h2>
<p>
<kbd>${formatForDisplay('Mod+E')}</kbd> reads
<code>enabled</code> from element state.
<kbd>${formatForDisplay('Mod+G')}</kbd> reads it from a function
on each key press.
</p>
<label class="control">
<input
type="checkbox"
.checked=${this.stateEnabled}
@change=${(event: Event) =>
(this.stateEnabled = (
event.target as HTMLInputElement
).checked)}
/>
Enable Mod+E
</label>
<label class="control">
<input type="checkbox" checked ${ref(this.getterCheckboxRef)} />
Enable Mod+G
</label>
<p role="status" class="info-box">
Mod+E: ${this.modECount}, Mod+G: ${this.modGCount}
</p>
</section>
<section class="demo-section">
<h2>Listen on one element</h2>
<p>
Click the panel or the drawer, then press
<kbd>${formatForDisplay('Enter')}</kbd>. Each has its own hotkey.
</p>
<div class="target-grid">
<div ${ref(this.panelRef)} tabindex="0" class="target-area">
Panel
</div>
<div>
<button
aria-expanded=${this.drawerOpen ? 'true' : 'false'}
@click=${() => (this.drawerOpen = !this.drawerOpen)}
>
Toggle drawer
</button>
${
this.drawerOpen
? html`<div
${ref(this.drawerRef)}
tabindex="0"
class="target-area"
>
Drawer
</div>`
: nothing
}
</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>
<p>
Press <kbd>${formatForDisplay('N')}</kbd>,
<kbd>${formatForDisplay('Mod+Enter')}</kbd>,
<kbd>${formatForDisplay('Mod+A')}</kbd>, and
<kbd>${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 <input type="text" ${ref(this.digitsRef)} />
</label>
<p role="status" class="info-box">
Last fired: ${this.lastPrevent}
</p>
</section>
<section class="demo-section">
<h2>Stop outer hotkeys</h2>
<p>
The panel and the page each have a
<kbd>${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}
@change=${(event: Event) =>
(this.stopPanel = (event.target as HTMLInputElement).checked)}
/>
Stop propagation in the panel
</label>
<div ${ref(this.stopPanelRef)} tabindex="0" class="target-area">
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>
<p>
Click the widget, which stops every key from reaching the page.
Then press <kbd>${formatForDisplay('Mod+ArrowUp')}</kbd> and
<kbd>${formatForDisplay('Mod+ArrowDown')}</kbd>. Only the capture
hotkey fires.
</p>
<!-- Stands in for a component that handles keys itself. -->
<div
tabindex="0"
class="target-area"
@keydown=${(event: KeyboardEvent) => event.stopPropagation()}
>
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>
<p>
Click the editor and press
<kbd>${formatForDisplay('Mod+B')}</kbd> and
<kbd>${formatForDisplay('Mod+I')}</kbd>. The editor prevents both,
so only Mod+I fires. Outside the editor, both fire.
</p>
<!-- Stands in for a rich text editor that handles its own chords. -->
<div
tabindex="0"
class="target-area"
@keydown=${(event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey) event.preventDefault()
}}
>
Editor
</div>
<p role="status" class="info-box">
Mod+B: ${this.modBCount}, Mod+I: ${this.modICount}
</p>
</section>
<section class="demo-section">
<h2>Duplicate hotkeys</h2>
<p>
<kbd>${formatForDisplay('Mod+Y')}</kbd> and
<kbd>${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.modYCount}, Mod+U: ${this.modUCount}
</p>
</section>
</main>
</div>
`
}
}
declare global {
interface HTMLElementTagNameMap {
'my-app': MyApp
}
}