Hotkeys Docs
Alpine Example: Keyboard Layouts
import { createHotkeysScope, hotkeysPlugin } from '@tanstack/alpine-hotkeys'
import Alpine from 'alpinejs'
import type { GermanKeys, UsKeys } from '@tanstack/alpine-hotkeys'
import './index.css'
// Hotkey strings accept the keys that US and German keyboards type. Without
// this, only US keys type-check, and `Mod+Ö` is an error. This changes types
// only: matching works the same with or without it. Hotkeys written in HTML
// attributes aren't type-checked, so this applies to TypeScript code only.
declare module '@tanstack/alpine-hotkeys' {
interface Register {
keys: UsKeys | GermanKeys
}
}
// Gives every hotkeys scope the app's Alpine instance.
Alpine.plugin(hotkeysPlugin)
const usage = `import type { GermanKeys, UsKeys } from '@tanstack/alpine-hotkeys'
declare module '@tanstack/alpine-hotkeys' {
interface Register {
keys: UsKeys | GermanKeys
}
}
hotkeys.createHotkey('Mod+Ö', toggleComment) // OK
hotkeys.createHotkey('Mod+[', outdent) // OK, because UsKeys is listed
hotkeys.createHotkey('Mod+Ñ', x) // Type error: Spanish isn't registered`
class App {
private hotkeysScope = createHotkeysScope()
formatForDisplay = this.hotkeysScope.createFormatForDisplay()
usage = usage
lastFired = ''
init() {
// These type-check because German keys are registered above.
this.hotkeysScope.createHotkey('Mod+Ö', () => {
this.lastFired = 'Toggle comment'
})
this.hotkeysScope.createHotkey('Mod+Shift+Ä', () => {
this.lastFired = 'Add annotation'
})
this.hotkeysScope.createHotkey('ß', () => {
this.lastFired = 'Toggle sidebar'
})
this.hotkeysScope.createHotkey('§', () => {
this.lastFired = 'Show sections'
})
// A to Z, 0 to 9, named keys, and physical codes type-check under every
// registration, and fire on every layout.
this.hotkeysScope.createHotkey('Mod+K', () => {
this.lastFired = 'Open command palette'
})
this.hotkeysScope.createHotkey('Alt+[Digit1]', () => {
this.lastFired = 'Go to the first tab'
})
this.hotkeysScope.createHotkey('Escape', () => {
this.lastFired = ''
})
}
destroy() {
this.hotkeysScope.destroy()
}
}
Alpine.data('app', () => new App())
Alpine.start()