@tanstack/react-hotkeys
Version:
React adapter for TanStack Hotkeys
129 lines (126 loc) • 3.92 kB
JavaScript
'use client';
import { useHotkeysContext } from "./HotkeysProvider.js";
import { useAppHotkeysStoreState } from "./_appHotkeysStore.js";
import { useIsomorphicLayoutEffect } from "./_useIsomorphicLayoutEffect.js";
import { createHotkeyBindings, prepareHotkeyDefinitions, resolveRefTarget } from "@tanstack/hotkeys/adapter";
import { useEffect, useRef, useState } from "react";
// src/useHotkeys.ts
/**
* Checks one hotkey for `useHotkeys` as `useHotkey` checks its arguments, and
* returns it unchanged. In an array, a hotkey object is checked only when it
* is written inline, and it takes the options of both kinds. Here the hotkey
* can be a variable, a key no hotkey object has is a type error, and the
* callback context and the options follow the kind of the hotkey.
*
* @example
* ```tsx
* const play = defineHotkey({
* hotkey: { default: 'Space', alternates: ['K'] },
* callback: () => togglePlay(),
* options: { requireReset: true },
* })
*
* function Player() {
* useHotkeys([play])
* }
* ```
*/
function defineHotkey(definition) {
return definition;
}
/**
* React hook for registering several hotkeys at once: chords, sequences, and
* app hotkeys. Accepts a dynamic array, so it is safe to use with
* variable-length lists without violating the rules of hooks.
*
* Options merge in this order: provider defaults, app hotkey declaration,
* commonOptions, per-hotkey options. Each option applies only to the kinds
* that support it. Callbacks and options sync on every render.
*
* Per-row `enabled: false` keeps that registration (visible in devtools) and
* only suppresses firing. Unbound app hotkeys and empty sequences register nothing.
*
* @param hotkeys - Hotkeys to register
* @param commonOptions - Options applied to every hotkey (overridden by per-hotkey options)
*
* @example
* ```tsx
* function Editor() {
* useHotkeys([
* { hotkey: 'Mod+S', callback: () => save() },
* { hotkey: ['G', 'G'], callback: () => scrollToTop(), options: { timeout: 500 } },
* { hotkey: 'Escape', callback: () => close() },
* ])
* }
* ```
*
* @example
* ```tsx
* function MenuShortcuts({ items }) {
* // Dynamic hotkeys from data -- safe because it's a single hook call
* useHotkeys(
* items.map((item) => ({
* hotkey: item.shortcut,
* callback: item.action,
* options: { enabled: item.enabled },
* })),
* { preventDefault: true },
* )
* }
* ```
*/
function useHotkeys(hotkeys, commonOptions = {}) {
const defaults = useHotkeysContext()?.defaultOptions.hotkey;
const appHotkeysStore = useAppHotkeysStoreState();
const latestRef = useRef({
hotkeys,
commonOptions,
defaults,
appHotkeysStore
});
latestRef.current = {
hotkeys,
commonOptions,
defaults,
appHotkeysStore
};
const bindingsRef = useRef(null);
const [retryError, setRetryError] = useState();
if (retryError) throw retryError.error;
const waitingRef = useRef(false);
const update = () => {
let waiting = false;
const { hotkeys, ...context } = latestRef.current;
bindingsRef.current?.update(prepareHotkeyDefinitions(hotkeys, {
...context,
resolveTarget: (target) => {
const resolved = resolveRefTarget(target);
if (resolved == null) waiting = true;
return resolved;
}
}));
return waiting;
};
useIsomorphicLayoutEffect(() => {
const bindings = bindingsRef.current ??= createHotkeyBindings({ afterDelegatedHandlers: true });
waitingRef.current = update();
if (waitingRef.current) queueMicrotask(() => {
if (bindingsRef.current !== bindings || !waitingRef.current) return;
try {
waitingRef.current = update();
} catch (error) {
setRetryError({ error });
}
});
});
useEffect(() => {
if (waitingRef.current) waitingRef.current = update();
});
useIsomorphicLayoutEffect(() => {
return () => {
bindingsRef.current?.destroy();
bindingsRef.current = null;
};
}, []);
}
export { defineHotkey, useHotkeys };