@tanstack/react-hotkeys
Version:
React adapter for TanStack Hotkeys
42 lines (39 loc) • 1.67 kB
JavaScript
'use client';
import { useDefaultHotkeysOptions } from "./HotkeysProvider.js";
import { getKeyboardLayoutStore, loadKeyboardLayout } from "@tanstack/hotkeys";
import { useEffect, useSyncExternalStore } from "react";
// src/useKeyboardLayout.ts
const subscribe = (onChange) => getKeyboardLayoutStore().subscribe(onChange).unsubscribe;
const getSnapshot = () => getKeyboardLayoutStore().get();
const subscribeToNothing = () => () => {};
const getNothing = () => null;
const getServerSnapshot = () => null;
/**
* The browser's keyboard layout, or `null` until it loads and in browsers
* that don't report one. The layout maps each physical code to the character
* it types, such as `KeyQ` to `a` on a French AZERTY keyboard. Only Chromium
* browsers report one.
*
* The layout loads after the first component that uses this hook mounts, so
* server-rendered output hydrates unchanged. `useFormatForDisplay` uses this
* hook, so you only need it for labels you draw yourself.
*
* To never ask the browser for the layout, set `keyboardLayout: false` in
* `HotkeysProvider`'s `defaultOptions`. This hook then returns `null`.
*
* @example
* ```tsx
* function MoveKeys() {
* const layoutMap = useKeyboardLayout()
* const label = (code: string) => (layoutMap?.get(code) ?? code).toUpperCase()
*
* return <kbd>{label('KeyW')}</kbd>
* }
* ```
*/
function useKeyboardLayout() {
const enabled = useDefaultHotkeysOptions().keyboardLayout !== false;
useEffect(() => enabled ? loadKeyboardLayout() : void 0, [enabled]);
return useSyncExternalStore(enabled ? subscribe : subscribeToNothing, enabled ? getSnapshot : getNothing, getServerSnapshot);
}
export { useKeyboardLayout };