@tanstack/react-hotkeys
Version:
React adapter for TanStack Hotkeys
79 lines (77 loc) • 2.52 kB
JavaScript
import { useAppHotkeysStoreState } from "./_appHotkeysStore.js";
import { useHotkeyRegistrations } from "./useHotkeyRegistrations.js";
//#region src/useAppHotkeys.ts
function useRequiredStore(hook) {
const store = useAppHotkeysStoreState();
if (!store) throw new Error(`${hook} requires a HotkeysProvider with an appHotkeys prop`);
return store;
}
/**
* Returns the effective app hotkeys from `HotkeysProvider`, typed by
* `Register`: each declaration with the user's custom hotkey applied.
* Pass an entry to `useHotkey` or `useHotkeys` to register it.
*
* @example
* ```tsx
* const appHotkeys = useAppHotkeys()
* useHotkey(appHotkeys['doc.save'], () => save())
* ```
*/
function useAppHotkeys() {
return useRequiredStore("useAppHotkeys").appHotkeys;
}
/**
* Lists every app hotkey with its live status, in declaration order, for
* cheat sheets and settings screens. App hotkeys whose components have not
* mounted are `'inactive'`; those without a hotkey are `'unbound'`.
*
* @example
* ```tsx
* function CheatSheet() {
* const items = useAppHotkeyList()
* return (
* <ul>
* {items.map(({ appHotkey, status }) => (
* <li key={appHotkey.id} data-status={status}>
* {appHotkey.meta?.name}:{' '}
* {appHotkey.hotkey ? formatForDisplay(appHotkey.hotkey) : 'Unassigned'}
* </li>
* ))}
* </ul>
* )
* }
* ```
*/
function useAppHotkeyList() {
const store = useRequiredStore("useAppHotkeyList");
const registrations = useHotkeyRegistrations();
return store.getList(registrations);
}
/**
* Reads and changes the user's custom hotkeys. Changes apply to every
* registered app hotkey immediately and are passed to the provider's
* `onCustomHotkeysChange`, ready to save.
*
* @example
* ```tsx
* const { setCustomHotkey, findConflicts } = useCustomHotkeys()
* const recorder = useHotkeyRecorder({
* maxSteps: Infinity,
* validate: (hotkey) =>
* findConflicts('doc.save', hotkey).length === 0 || 'Already in use',
* onRecord: (hotkey) => setCustomHotkey('doc.save', hotkey),
* })
* ```
*/
function useCustomHotkeys() {
const store = useRequiredStore("useCustomHotkeys");
return {
customHotkeys: store.customHotkeys,
setCustomHotkey: (id, hotkey) => store.setCustomHotkey(id, hotkey),
resetCustomHotkey: (id) => store.resetCustomHotkey(id),
resetCustomHotkeys: () => store.resetCustomHotkeys(),
findConflicts: (id, hotkey) => store.findConflicts(id, hotkey)
};
}
//#endregion
export { useAppHotkeyList, useAppHotkeys, useCustomHotkeys };