23 lines
1.1 KiB
TypeScript
23 lines
1.1 KiB
TypeScript
/** Keys for the screens of a world, like the shortcuts in Die Stämme: one letter, no modifier. */
|
|
export const SHORTCUTS = { overview: 'v', build: 'h', recruit: 't', rally: 'p', workforce: 'w', map: 'm', reports: 'r', ranking: 'k' } as const
|
|
|
|
/**
|
|
* Jumps between screens by key while the page is mounted. Keys typed into a field,
|
|
* or pressed with a modifier, are left alone.
|
|
*/
|
|
export function useShortcuts(targets: () => Partial<Record<keyof typeof SHORTCUTS, string>>) {
|
|
function onKey(e: KeyboardEvent) {
|
|
if (e.ctrlKey || e.metaKey || e.altKey || e.repeat) return
|
|
const el = e.target as HTMLElement | null
|
|
if (el && (el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName))) return
|
|
const key = e.key.toLowerCase()
|
|
const name = (Object.keys(SHORTCUTS) as (keyof typeof SHORTCUTS)[]).find((n) => SHORTCUTS[n] === key)
|
|
const to = name ? targets()[name] : undefined
|
|
if (!to) return
|
|
e.preventDefault()
|
|
navigateTo(to)
|
|
}
|
|
onMounted(() => window.addEventListener('keydown', onKey))
|
|
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
|
}
|