An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add useHotkeys hook for global keyboard shortcuts (#3820)
Cindy Zhangb51f2daa0154
diff --git a/.changeset/use-hotkeys.md b/.changeset/use-hotkeys.mdnew file mode 100644index 0000000000..b2937201b9--- /dev/null+++ b/.changeset/use-hotkeys.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Add `useHotkeys` hook for global keyboard shortcuts. Registers one window `keydown` listener per hook instance with handlers kept in a ref (re-renders never re-subscribe). Combos like `'mod+k'` or `'escape'` — `mod` maps to ⌘ on Apple platforms (same detection as Kbd) and Ctrl elsewhere. Skips typing targets (input/textarea/select/contenteditable) unless `allowInInputs`, skips `defaultPrevented` events, and calls `preventDefault()` on match. SSR-safe.++@thedjpetersendiff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex c15ccb1471..db4b32a05c 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -30,6 +30,9 @@ export type {export {useTreeFocus} from './useTreeFocus';export type {UseTreeFocusOptions, UseTreeFocusReturn} from './useTreeFocus';+export {useHotkeys} from './useHotkeys';+export type {Hotkey} from './useHotkeys';+export {useTypeahead} from './useTypeahead';export {useKeyboardHint} from './useKeyboardHint';diff --git a/packages/core/src/hooks/useHotkeys.doc.mjs b/packages/core/src/hooks/useHotkeys.doc.mjsnew file mode 100644index 0000000000..304706eb27--- /dev/null+++ b/packages/core/src/hooks/useHotkeys.doc.mjs@@ -0,0 +1,52 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('../docs-types').HookDoc} */+export const docs = {+ name: 'useHotkeys',+ displayName: 'useHotkeys',+ keywords: ['hotkey', 'shortcut', 'keyboard', 'keydown', 'command', 'palette', 'mod', 'cmd', 'ctrl', 'kbd'],+ params: [+ {+ name: 'hotkeys',+ type: 'Hotkey[]',+ description:+ 'Shortcut registrations. Each entry: `{ keys, onPress, allowInInputs?, isDisabled? }`. `keys` is a "+"-separated combo like "mod+k", "shift+/", "escape" — "mod" is ⌘ on macOS and Ctrl elsewhere. `onPress` receives the KeyboardEvent after preventDefault(). `allowInInputs` (default false) lets the hotkey fire while typing in inputs/textareas/selects/contenteditable. `isDisabled` temporarily disables the entry.',+ required: true,+ },+ ],+ returns: [],+ usage: {+ description:+ 'Registers global keyboard shortcuts with a single window keydown listener per hook instance. Handlers live in a ref, so re-renders never re-subscribe. Skips events from typing targets (input, textarea, select, contenteditable) unless allowInInputs, skips defaultPrevented events, and calls preventDefault() on match. SSR-safe.',+ bestPractices: [+ { guidance: true, description: 'Use for app-level shortcuts like command palettes (mod+k), help overlays (shift+/), and navigation keys.' },+ { guidance: true, description: 'Pair with the Kbd component to display the same combo you register — both resolve "mod" per platform identically.' },+ { guidance: true, description: 'Use isDisabled to suspend shortcuts while a modal or wizard owns the keyboard, instead of unmounting the hook.' },+ { guidance: false, description: 'Use for focus-scoped keyboard navigation inside a widget; use useListFocus or useGridFocus instead.' },+ ],+ },+ relatedComponents: ['Kbd'],+ relatedHooks: ['useListFocus', 'useGridFocus'],+ importPath: '@astryxdesign/core/hooks',+ category: 'interaction',+};++/** @type {import('../docs-types').HookTranslationDoc} */+export const docsDense = {+ description:+ 'Global keyboard shortcuts w/ one window keydown listener per hook instance. Handlers kept in ref — re-renders never re-subscribe. Skips typing targets (input/textarea/select/contenteditable) unless allowInInputs, skips defaultPrevented, preventDefault() on match. "mod" = ⌘ on macOS, Ctrl elsewhere. SSR-safe.',+ paramDescriptions: {+ hotkeys:+ 'array of { keys, onPress, allowInInputs?, isDisabled? }. keys = "+"-separated combo ("mod+k", "shift+/", "escape").',+ },+ usage: {+ description:+ 'Global keyboard shortcuts w/ one window keydown listener per hook instance. Handlers kept in ref — re-renders never re-subscribe. Skips typing targets unless allowInInputs, skips defaultPrevented, preventDefault() on match. SSR-safe.',+ bestPractices: [+ { guidance: true, description: 'Use for app-level shortcuts: command palettes (mod+k), help overlays (shift+/), navigation keys.' },+ { guidance: true, description: 'Pair w/ Kbd component to display same combo registered — both resolve "mod" per platform identically.' },+ { guidance: true, description: 'Use isDisabled to suspend shortcuts while modal/wizard owns keyboard, instead of unmounting hook.' },+ { guidance: false, description: 'Use for focus-scoped keyboard nav inside widget; use useListFocus / useGridFocus instead.' },+ ],+ },+};diff --git a/packages/core/src/hooks/useHotkeys.test.ts b/packages/core/src/hooks/useHotkeys.test.tsnew file mode 100644index 0000000000..8bff8087ec--- /dev/null+++ b/packages/core/src/hooks/useHotkeys.test.ts@@ -0,0 +1,245 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useHotkeys.test.ts+ * @input Uses vitest, @testing-library/react, useHotkeys hook+ * @output Unit tests for useHotkeys hook+ * @position Testing; validates useHotkeys.ts implementation+ *+ * SYNC: When useHotkeys.ts changes, update tests to match new behavior+ */++import {describe, it, expect, vi, afterEach} from 'vitest';+import {renderHook} from '@testing-library/react';+import {useHotkeys, type Hotkey} from './useHotkeys';++function stubApplePlatform() {+ // jsdom's navigator has no userAgentData; platform drives detection.+ vi.stubGlobal('navigator', {platform: 'MacIntel'});+}++function stubOtherPlatform() {+ vi.stubGlobal('navigator', {platform: 'Win32'});+}++function press(+ key: string,+ init: KeyboardEventInit & {target?: HTMLElement} = {},+): KeyboardEvent {+ const {target, ...eventInit} = init;+ const event = new KeyboardEvent('keydown', {+ key,+ bubbles: true,+ cancelable: true,+ ...eventInit,+ });+ (target ?? window).dispatchEvent(event);+ return event;+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ document.body.innerHTML = '';+});++describe('useHotkeys', () => {+ it('fires on mod+k via metaKey on Apple platforms', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ renderHook(() => useHotkeys([{keys: 'mod+k', onPress}]));++ const event = press('k', {metaKey: true});+ expect(onPress).toHaveBeenCalledTimes(1);+ expect(onPress).toHaveBeenCalledWith(event);+ expect(event.defaultPrevented).toBe(true);+ });++ it('maps mod to ctrlKey on non-Apple platforms', () => {+ stubOtherPlatform();+ const onPress = vi.fn();+ renderHook(() => useHotkeys([{keys: 'mod+k', onPress}]));++ press('k', {metaKey: true});+ expect(onPress).not.toHaveBeenCalled();++ press('k', {ctrlKey: true});+ expect(onPress).toHaveBeenCalledTimes(1);+ });++ it('does not fire a bare key when modifiers are held', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ renderHook(() => useHotkeys([{keys: 'k', onPress}]));++ press('k', {metaKey: true});+ press('k', {ctrlKey: true});+ press('k', {altKey: true});+ expect(onPress).not.toHaveBeenCalled();++ press('k');+ expect(onPress).toHaveBeenCalledTimes(1);+ });++ it('matches named keys: escape, enter, space, arrows', () => {+ stubApplePlatform();+ const onEscape = vi.fn();+ const onEnter = vi.fn();+ const onSpace = vi.fn();+ const onDown = vi.fn();+ renderHook(() =>+ useHotkeys([+ {keys: 'escape', onPress: onEscape},+ {keys: 'enter', onPress: onEnter},+ {keys: 'space', onPress: onSpace},+ {keys: 'down', onPress: onDown},+ ]),+ );++ press('Escape');+ press('Enter');+ press(' ');+ press('ArrowDown');+ expect(onEscape).toHaveBeenCalledTimes(1);+ expect(onEnter).toHaveBeenCalledTimes(1);+ expect(onSpace).toHaveBeenCalledTimes(1);+ expect(onDown).toHaveBeenCalledTimes(1);+ });++ it('requires shift when specified and ignores shift otherwise', () => {+ stubApplePlatform();+ const onSlash = vi.fn();+ const onLetter = vi.fn();+ renderHook(() =>+ useHotkeys([+ {keys: 'shift+/', onPress: onSlash},+ {keys: 'c', onPress: onLetter},+ ]),+ );++ press('/');+ expect(onSlash).not.toHaveBeenCalled();+ press('/', {shiftKey: true});+ expect(onSlash).toHaveBeenCalledTimes(1);++ // Shift not specified → matches regardless of shift state.+ press('C', {shiftKey: true});+ press('c');+ expect(onLetter).toHaveBeenCalledTimes(2);+ });++ it('skips typing targets by default', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ renderHook(() => useHotkeys([{keys: 'mod+k', onPress}]));++ const input = document.createElement('input');+ document.body.appendChild(input);+ press('k', {metaKey: true, target: input});+ expect(onPress).not.toHaveBeenCalled();++ const textarea = document.createElement('textarea');+ document.body.appendChild(textarea);+ press('k', {metaKey: true, target: textarea});+ expect(onPress).not.toHaveBeenCalled();+ });++ it('fires in typing targets when allowInInputs is true', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ renderHook(() =>+ useHotkeys([{keys: 'escape', onPress, allowInInputs: true}]),+ );++ const input = document.createElement('input');+ document.body.appendChild(input);+ press('Escape', {target: input});+ expect(onPress).toHaveBeenCalledTimes(1);+ });++ it('respects isDisabled', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ const {rerender} = renderHook(+ ({isDisabled}: {isDisabled: boolean}) =>+ useHotkeys([{keys: 'mod+k', onPress, isDisabled}]),+ {initialProps: {isDisabled: true}},+ );++ press('k', {metaKey: true});+ expect(onPress).not.toHaveBeenCalled();++ rerender({isDisabled: false});+ press('k', {metaKey: true});+ expect(onPress).toHaveBeenCalledTimes(1);+ });++ it('skips events that are already defaultPrevented', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ renderHook(() => useHotkeys([{keys: 'mod+k', onPress}]));++ const event = new KeyboardEvent('keydown', {+ key: 'k',+ metaKey: true,+ bubbles: true,+ cancelable: true,+ });+ event.preventDefault();+ window.dispatchEvent(event);+ expect(onPress).not.toHaveBeenCalled();+ });++ it('unsubscribes on unmount', () => {+ stubApplePlatform();+ const onPress = vi.fn();+ const removeSpy = vi.spyOn(window, 'removeEventListener');+ const {unmount} = renderHook(() => useHotkeys([{keys: 'mod+k', onPress}]));++ unmount();+ expect(removeSpy).toHaveBeenCalledWith('keydown', expect.any(Function));++ press('k', {metaKey: true});+ expect(onPress).not.toHaveBeenCalled();+ });++ it('does not re-subscribe on re-render, but uses latest handlers', () => {+ stubApplePlatform();+ const addSpy = vi.spyOn(window, 'addEventListener');+ const first = vi.fn();+ const second = vi.fn();++ const {rerender} = renderHook(+ ({hotkeys}: {hotkeys: Hotkey[]}) => useHotkeys(hotkeys),+ {initialProps: {hotkeys: [{keys: 'mod+k', onPress: first}]}},+ );++ const keydownSubscriptions = () =>+ addSpy.mock.calls.filter(([type]) => type === 'keydown').length;+ const initialCount = keydownSubscriptions();++ rerender({hotkeys: [{keys: 'mod+k', onPress: second}]});+ rerender({hotkeys: [{keys: 'mod+k', onPress: second}]});+ expect(keydownSubscriptions()).toBe(initialCount);++ press('k', {metaKey: true});+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledTimes(1);+ });++ it('only fires the first matching hotkey per event', () => {+ stubApplePlatform();+ const first = vi.fn();+ const second = vi.fn();+ renderHook(() =>+ useHotkeys([+ {keys: 'mod+k', onPress: first},+ {keys: 'mod+k', onPress: second},+ ]),+ );++ press('k', {metaKey: true});+ expect(first).toHaveBeenCalledTimes(1);+ expect(second).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/hooks/useHotkeys.ts b/packages/core/src/hooks/useHotkeys.tsnew file mode 100644index 0000000000..e057547c87--- /dev/null+++ b/packages/core/src/hooks/useHotkeys.ts@@ -0,0 +1,203 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useHotkeys.ts+ * @input Uses React useEffect, useRef+ * @output Exports useHotkeys hook and Hotkey interface for global keyboard shortcuts+ * @position Core hook; used by consumers for app-level keyboard shortcuts+ *+ * Registers a single window keydown listener per hook instance. Handlers+ * are kept in a ref so re-renders never re-subscribe (subscribe once on+ * mount, unsubscribe on unmount). SSR-safe — window is only touched+ * inside the effect.+ *+ * Skips events that are already handled (defaultPrevented) and events+ * targeting typing surfaces (input, textarea, select, contenteditable)+ * unless a hotkey opts in via `allowInInputs`.+ *+ * Platform-aware: `mod` maps to metaKey (⌘) on Apple platforms and+ * ctrlKey elsewhere — mirrors the detection used by Kbd.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts+ * - /packages/core/src/hooks/useHotkeys.doc.mjs+ */++import {useEffect, useRef} from 'react';++/**+ * A single keyboard shortcut registration.+ */+export interface Hotkey {+ /**+ * Key combo, e.g. 'mod+k', 'shift+/', 'c', 'escape'.+ * 'mod' = ⌘ on macOS, Ctrl elsewhere.+ *+ * Format: '+'-separated modifiers (mod, ctrl, meta, shift, alt) followed+ * by a final key compared case-insensitively against event.key.+ * Named keys: 'escape', 'enter', 'space', 'up', 'down', 'left', 'right'+ * (arrow names map to ArrowUp/ArrowDown/ArrowLeft/ArrowRight).+ * Use 'plus' for a literal '+' key.+ *+ * Shift semantics: when 'shift' is not specified, shift state is ignored,+ * so single letters match regardless of shift. When 'shift' is specified,+ * shiftKey must be pressed and the final key is still compared against+ * event.key — for punctuation that shift transforms (e.g. shift+/ produces+ * '?' on US layouts), prefer registering the produced character instead.+ */+ keys: string;+ /** Called when the combo matches. The event has preventDefault() applied. */+ onPress: (event: KeyboardEvent) => void;+ /**+ * Fire even when focus is in an input/textarea/select/contenteditable.+ * @default false+ */+ allowInInputs?: boolean;+ /** Temporarily disable this hotkey without unregistering it. */+ isDisabled?: boolean;+}++/** Aliases for the final key of a combo, normalized to event.key values. */+const KEY_ALIASES: Record<string, string> = {+ esc: 'escape',+ space: ' ',+ up: 'arrowup',+ down: 'arrowdown',+ left: 'arrowleft',+ right: 'arrowright',+ return: 'enter',+ plus: '+',+};++/**+ * Detects whether the current platform is macOS/iOS.+ * Prefers the User-Agent Client Hints API when available (modern Chrome/Edge),+ * falls back to navigator.platform (deprecated but universally supported).+ * Mirrors the detection used by Kbd so displayed and handled shortcuts agree.+ */+function isApplePlatform(): boolean {+ if (typeof navigator === 'undefined') {+ return false;+ }+ const uaData = 'userAgentData' in navigator ? navigator.userAgentData : null;+ if (uaData && typeof uaData === 'object' && 'platform' in uaData) {+ return /mac/i.test((uaData as {platform: string}).platform ?? '');+ }+ return /Mac|iPhone|iPad|iPod/.test(navigator.platform ?? '');+}++/**+ * Whether the event target is a typing surface where global shortcuts+ * should stay silent by default.+ */+function isTypingTarget(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) {+ return false;+ }+ if (target.isContentEditable) {+ return true;+ }+ const tag = target.tagName;+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';+}++/**+ * Whether a keydown event matches a '+'-separated combo string.+ */+function matchesCombo(+ keys: string,+ event: KeyboardEvent,+ isApple: boolean,+): boolean {+ const parts = keys+ .toLowerCase()+ .split('+')+ .map(part => part.trim())+ .filter(Boolean);+ if (parts.length === 0) {+ return false;+ }++ const key = parts[parts.length - 1];+ const mods = new Set(parts.slice(0, -1));++ const wantsMod = mods.has('mod');+ const wantsCtrl = mods.has('ctrl') || (wantsMod && !isApple);+ const wantsMeta = mods.has('meta') || (wantsMod && isApple);+ const wantsAlt = mods.has('alt');+ const wantsShift = mods.has('shift');++ // Non-shift modifiers must match exactly so 'k' doesn't fire on 'mod+k'.+ if (event.ctrlKey !== wantsCtrl) {+ return false;+ }+ if (event.metaKey !== wantsMeta) {+ return false;+ }+ if (event.altKey !== wantsAlt) {+ return false;+ }+ // Shift is only enforced when specified — see Hotkey.keys docs.+ if (wantsShift && !event.shiftKey) {+ return false;+ }++ const expected = KEY_ALIASES[key] ?? key;+ return event.key.toLowerCase() === expected;+}++/**+ * Registers global keyboard shortcuts on window.+ *+ * A single keydown listener is attached per hook instance; the hotkey+ * definitions live in a ref, so re-renders update behavior without+ * re-subscribing. First matching hotkey wins per event.+ *+ * @param hotkeys - Shortcut registrations to listen for.+ *+ * @example+ * ```+ * useHotkeys([+ * { keys: 'mod+k', onPress: () => openCommandPalette() },+ * { keys: 'escape', onPress: () => closePanel(), allowInInputs: true },+ * { keys: 'c', onPress: () => compose(), isDisabled: isModalOpen },+ * ]);+ * ```+ */+export function useHotkeys(hotkeys: Hotkey[]): void {+ const hotkeysRef = useRef(hotkeys);++ // Keep the latest definitions available to the stable listener.+ useEffect(() => {+ hotkeysRef.current = hotkeys;+ });++ useEffect(() => {+ const isApple = isApplePlatform();++ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented) {+ return;+ }+ const isTyping = isTypingTarget(event.target);+ for (const hotkey of hotkeysRef.current) {+ if (hotkey.isDisabled) {+ continue;+ }+ if (isTyping && !hotkey.allowInInputs) {+ continue;+ }+ if (matchesCombo(hotkey.keys, event, isApple)) {+ event.preventDefault();+ hotkey.onPress(event);+ return;+ }+ }+ };++ window.addEventListener('keydown', handleKeyDown);+ return () => window.removeEventListener('keydown', handleKeyDown);+ }, []);+}