import { getHotkeyManager } from '@tanstack/hotkeys'
import { getHotkeyRegistrationViews } from '@tanstack/hotkeys/adapter'
import { isServer } from './_server'
import type { HotkeyRegistrationView } from '@tanstack/hotkeys'
import type { ReactiveController, ReactiveControllerHost } from 'lit'
/**
* A Lit ReactiveController that reads every hotkey registration, chords and
* sequences, from the singleton HotkeyManager and requests an update when
* they change. Narrow each view with `kind`.
*
* @example
* ```ts
* class ShortcutPalette extends LitElement {
* private registrations = new HotkeyRegistrationsController(this)
* private formatForDisplay = new FormatForDisplayController(this)
*
* render() {
* return html`
* ${this.registrations.hotkeys.map(
* (reg) => html`- ${reg.options.meta?.name}: ${this.formatForDisplay.format(reg.hotkey)}
`,
* )}
*
`
* }
* }
* ```
*/
export class HotkeyRegistrationsController implements ReactiveController {
private _unsubscribe: (() => void) | undefined
private _hotkeys: Array = []
/** Every registration, chords and sequences (public view, no callbacks). */
public get hotkeys(): Array {
return this._hotkeys
}
constructor(private _host: ReactiveControllerHost) {
this._host.addController(this)
}
public hostConnected(): void {
// Adding the controller again while connected calls this twice.
if (this._unsubscribe) return
const manager = getHotkeyManager()
const read = () => getHotkeyRegistrationViews(manager.registrations.state)
this._hotkeys = read()
if (isServer()) return
const subscription = manager.registrations.subscribe(() => {
this._hotkeys = read()
this._host.requestUpdate()
})
this._unsubscribe = () => subscription.unsubscribe()
}
public hostDisconnected(): void {
this._unsubscribe?.()
this._unsubscribe = undefined
this._hotkeys = []
}
/**
* Releases the controller now and removes it from its host. Use it to
* remove a controller early: Lit's `removeController` alone leaves it active.
*/
public dispose(): void {
this.hostDisconnected()
this._host.removeController(this)
}
}