UNPKG

@tanstack/hotkeys

Version:

Type-safe, framework-agnostic keyboard hotkey management for the browser

431 lines • 20.7 kB
import { CanonicalModifier, Key, LogicalKey, ShiftableKey } from "./key.types.js"; import { HotkeyPlatform } from "./platform.js"; /** An element, document, or window that hotkeys can listen on. */ export type Target = HTMLElement | Document | Window; /** The keyboard event a hotkey listens for. */ export type HotkeyEventType = 'keydown' | 'keyup'; /** * Single modifier + key combinations. * Uses canonical modifiers (4) + Mod (1) = 5 modifiers. * * The `Mod` modifier is platform-adaptive: * - **macOS**: Resolves to `Meta` (Command key ⌘) * - **Windows/Linux**: Resolves to `Control` (Ctrl key) * * This enables cross-platform hotkey definitions that automatically adapt to the platform. * For example, `Mod+S` becomes `Command+S` on Mac and `Ctrl+S` on Windows/Linux. */ export type SingleModifierHotkeyChord = `Control+${Key}` | `Alt+${Key}` | `Shift+${ShiftableKey}` | `Meta+${Key}` | `Mod+${Key}`; /** * Two modifier + key combinations. * * **Platform-adaptive `Mod` combinations:** * - `Mod+Alt` and `Mod+Shift` are included (safe on all platforms) * - `Mod+Control` and `Mod+Meta` are excluded because they create duplicate modifiers: * - `Mod+Control` duplicates `Control` on Windows/Linux (Mod = Control) * - `Mod+Meta` duplicates `Meta` on macOS (Mod = Meta) */ export type TwoModifierHotkeyChord = `Control+Alt+${Key}` | `Control+Shift+${ShiftableKey}` | `Control+Meta+${Key}` | `Alt+Shift+${ShiftableKey}` | `Alt+Meta+${Key}` | `Mod+Alt+${Key}` | `Shift+Meta+${ShiftableKey}` | `Mod+Shift+${ShiftableKey}`; /** * Three modifier + key combinations. * * **Platform-adaptive `Mod` combinations:** * - `Mod+Alt+Shift` is included (safe on all platforms) * - `Mod+Control+Shift` and `Mod+Shift+Meta` are excluded because they create duplicate modifiers: * - `Mod+Control+Shift` duplicates `Control` on Windows/Linux (Mod = Control) * - `Mod+Shift+Meta` duplicates `Meta` on macOS (Mod = Meta) */ export type ThreeModifierHotkeyChord = `Control+Alt+Shift+${ShiftableKey}` | `Control+Alt+Meta+${Key}` | `Control+Shift+Meta+${ShiftableKey}` | `Alt+Shift+Meta+${ShiftableKey}` | `Mod+Alt+Shift+${ShiftableKey}`; /** * Four modifier + key combinations. * * Only the canonical `Control+Alt+Shift+Meta` combination is included. * * **Why no `Mod` combinations?** * Since `Mod` resolves to either `Control` (Windows/Linux) or `Meta` (macOS), any * four-modifier combination with `Mod` would create duplicate modifiers on one platform. * For example: * - `Mod+Control+Alt+Shift` → duplicates `Control` on Windows/Linux * - `Mod+Alt+Shift+Meta` → duplicates `Meta` on macOS */ export type FourModifierHotkeyChord = `Control+Alt+Shift+Meta+${ShiftableKey}`; /** * A type-safe hotkey string. * * Provides autocomplete for: * - All single keys (letters, numbers, function keys, navigation, editing, punctuation) * - Single modifier + common key (Control+S, Mod+A, Mod+/, etc.) * - Two modifiers + common key (Mod+Shift+S, Control+Alt+A, etc.) * - Three modifiers + common key (Control+Alt+Shift+A, Mod+Alt+Shift+S, etc.) * - Four modifiers + common key (Control+Alt+Shift+Meta+A, etc.) * * ## Modifier Names * * Use canonical modifier names: * - `Control` (not Ctrl) - The Control key * - `Alt` (not Option) - The Alt key (Option on macOS) * - `Meta` (not Command/Cmd) - The Meta/Command key (macOS only) * - `Shift` - The Shift key * * ## Platform-Adaptive `Mod` Modifier * * The `Mod` modifier is a special platform-adaptive modifier that automatically resolves * to the "primary modifier" on each platform: * * - **macOS**: `Mod` → `Meta` (Command key ⌘) * - **Windows/Linux**: `Mod` → `Control` (Ctrl key) * * This enables cross-platform hotkey definitions that work correctly on all platforms * without platform-specific code. The `Mod` modifier is resolved at runtime based on * the detected platform. * * **When to use `Mod` vs platform-specific modifiers:** * - Use `Mod` for cross-platform shortcuts (e.g., `Mod+S` for save) * - Use `Meta` or `Control` when you need platform-specific behavior * - Use `Mod` when you want your shortcuts to follow platform conventions automatically * * **Limitations:** * - `Mod+Control` and `Mod+Meta` combinations are not allowed (they create duplicate * modifiers on one platform) * - In four-modifier combinations, only canonical modifiers are allowed (no `Mod`) * * @example * ```ts * // Cross-platform shortcuts (recommended) * const save: HotkeyChord = 'Mod+S' // Command+S on Mac, Ctrl+S on Windows/Linux * const saveAs: HotkeyChord = 'Mod+Shift+S' // Command+Shift+S on Mac, Ctrl+Shift+S elsewhere * const comment: HotkeyChord = 'Mod+/' // Command+/ on Mac, Ctrl+/ elsewhere * * // Platform-specific shortcuts * const macOnly: HotkeyChord = 'Meta+S' // Command+S on Mac only * const windowsOnly: HotkeyChord = 'Control+S' // Ctrl+S on Windows/Linux only * ``` */ export type HotkeyChord = Key | SingleModifierHotkeyChord | TwoModifierHotkeyChord | ThreeModifierHotkeyChord | FourModifierHotkeyChord; /** Resolved modifier flags shared by both parsed binding variants. */ export interface ParsedModifiers { /** Whether Control is required. */ ctrl: boolean; /** Whether Shift is required. */ shift: boolean; /** Whether Alt is required. */ alt: boolean; /** Whether Meta (Command) is required. */ meta: boolean; /** Required modifiers in canonical order. */ modifiers: Array<CanonicalModifier>; } /** * A parsed chord matches either a logical key or a physical code, never both. * Check `code !== undefined` to narrow to a physical binding. Its logical * character is unknown without a keyboard event and is not stored in `key`. * * @example * parseHotkey('Alt+S') // { key: 'S', alt: true, ... } * parseHotkey('Alt+[KeyS]') // { code: 'KeyS', alt: true, ... } with no key property */ export type ParsedHotkeyChord = ParsedModifiers & ({ key: LogicalKey | (string & {}); code?: never; } | { code: string; key?: never; }); /** Modifier flags shared by logical-key and physical-code registrations. */ export interface RawModifiers { /** Platform-adaptive modifier: Command on macOS, Control on Windows/Linux. Defaults to false. */ mod?: boolean; /** Whether the Control key is required. Defaults to false. */ ctrl?: boolean; /** Whether the Shift key is required. Defaults to false. */ shift?: boolean; /** Whether the Alt key is required. Defaults to false. */ alt?: boolean; /** Whether the Meta (Command) key is required. Defaults to false. */ meta?: boolean; } /** * A chord written as an object instead of a string, for building chords from * data. Set `key` for a logical key or `code` for a physical one, and set a * boolean for each modifier. Omitted modifiers default to `false`. * * The `mod` modifier is platform-adaptive: Command on macOS, Control on Windows/Linux. * Sequence steps can be objects too: `[{ key: 'K', mod: true }, 'C']`. * * @example * ```ts * useHotkey({ key: 'S', mod: true }, handler) // Mod+S (cross-platform) * useHotkey({ key: 'S', ctrl: true }, handler) // Control+S * useHotkey({ key: 'Escape' }, handler) // Escape (no modifiers) * useHotkey({ key: 'A', shift: true, meta: true }, handler) // Shift+Meta+A * useHotkey({ key: 'S', mod: true, shift: true }, handler) // Mod+Shift+S * useHotkey({ code: 'KeyW', mod: true }, handler) // Physical Mod+KeyW * useHotkey({ code: 'NumpadAdd', mod: true }, handler) // Physical numpad plus * ``` */ export type RawHotkeyChord = (({ key: LogicalKey | (string & {}); code?: never; } & RawModifiers) | ({ code: string; key?: never; } & RawModifiers)) & { [K in HotkeyPlatform | 'default' | 'alternates']?: never; }; /** * A sequence of chord strings pressed one after another (Vim-style), such as * `['G', 'G']`. Registered sequences are stored in this form. To register * steps written as objects, see {@link RegisterableHotkeySequence}. * * Steps may include modifiers; the same modifier can appear on consecutive * steps (e.g. `['Shift+R', 'Shift+T']`). Modifier-only key events do not * advance or reset matching. Automatic repeats and IME composition are ignored. * A one-step sequence is treated as its single chord. */ export type HotkeySequence = ReadonlyArray<HotkeyChord>; /** * A hotkey: one chord (`'Mod+S'`) or a sequence of chords (`['G', 'G']`). */ export type Hotkey = HotkeyChord | HotkeySequence; /** A single chord as a type-safe string (`HotkeyChord`) or an object (`RawHotkeyChord`). */ export type RegisterableHotkeyChord = HotkeyChord | RawHotkeyChord; /** * A sequence whose steps are chord strings or chord objects, such as * `['G', { key: 'H', shift: true }]`. */ export type RegisterableHotkeySequence = ReadonlyArray<RegisterableHotkeyChord>; /** * A chord or a sequence, with each chord written as a string or an object. * `RegisterableHotkey` also accepts one of these per platform. */ export type RegisterableChordOrSequence = RegisterableHotkeyChord | RegisterableHotkeySequence; /** The `default` and the platform entries of a hotkey object. */ type PlatformEntries<T> = { default: T | null; } & Partial<Record<HotkeyPlatform, T | null>> & { [K in 'key' | 'code' | keyof RawModifiers]?: never; }; /** * One more hotkey for the same action: a chord, a sequence, or one of those * per platform. It can't have alternates of its own. */ export type HotkeyAlternate<T = RegisterableChordOrSequence> = T | (PlatformEntries<T> & { alternates?: never; }); /** * A hotkey object, for a shortcut that follows each platform's convention or * has more than one hotkey. * * `default` is the hotkey. `mac`, `windows`, and `linux` replace it on that * platform. `null` leaves a platform without a hotkey, and a `default` of * `null` leaves every platform you don't name without one. The entry is * chosen by the same platform that resolves `Mod`: the `platform` option, * then a provider's, then detection. Each entry is a chord or a sequence, so * an array inside is still a sequence. * * `alternates` lists more hotkeys that fire the same callback. Each is a * chord, a sequence, or an object with a `default` and platforms, resolved * the same way. An array in the list is a sequence: `['G', 'P']` is two * alternates and `[['G', 'P']]` is one. Labels show the first hotkey, not * the alternates. * * @example * ```ts * useHotkey({ default: 'Mod+Y', mac: 'Mod+Shift+Z' }, redo) * useHotkey({ default: null, mac: 'Mod+,' }, openPreferences) * useHotkey({ default: 'Space', alternates: ['K', 'MediaPlayPause'] }, togglePlay) * useHotkey( * { * default: 'Mod+Y', * mac: 'Mod+Shift+Z', * alternates: [{ default: 'Mod+Shift+Z', mac: null }], * }, * redo, * ) * ``` */ export type PlatformHotkeys<T = RegisterableChordOrSequence> = PlatformEntries<T> & { alternates?: ReadonlyArray<HotkeyAlternate<T>>; }; /** * Anything that can be registered: a chord or a sequence, with each chord * written as a string or an object, or one of those per platform. */ export type RegisterableHotkey = RegisterableChordOrSequence | PlatformHotkeys; /** * The parameter type for a function that infers its hotkey's type `T`. It is * `TParam`, unless the hotkey is an object with a key that no hotkey object * has, such as a misspelled platform (`macos`) or modifier (`shfit`). That * key is then an error, at the top level, in a step of a sequence, in the * chord object of a platform entry, and in an alternate. A type parameter * alone accepts extra keys. * * @example * ```ts * function useHotkey<const T extends RegisterableHotkey>( * hotkey: KnownHotkey<T, T | null | undefined>, * ): void * ``` */ export type KnownHotkey<T, TParam = T> = [UnknownHotkeyKeys<T> | UnknownStepKeys<T> | UnknownEntryKeys<T> | UnknownAlternateKeys<T>] extends [never] ? TParam : [T] extends [infer THotkey] ? [THotkey] extends [ReadonlyArray<unknown>] ? KnownSteps<THotkey> : THotkey & { [K in UnknownHotkeyKeys<THotkey>]: never; } & ([UnknownEntryKeys<THotkey>] extends [never] ? unknown : KnownEntries<THotkey>) & ([UnknownAlternateKeys<THotkey>] extends [never] ? unknown : { alternates: KnownAlternates<THotkey>; }) : never; type UnknownStepKeys<T> = [T] extends [string | ReadonlyArray<string> | null | undefined] ? never : T extends ReadonlyArray<infer TStep> ? UnknownHotkeyKeys<TStep> : never; type KnownSteps<T> = { [I in keyof T]: T[I] & { [K in UnknownHotkeyKeys<T[I]>]: never; }; }; type KnownEntry<T> = T extends ReadonlyArray<unknown> ? KnownSteps<T> : T & { [K in UnknownHotkeyKeys<T>]: never; }; type UnknownEntryKeys<T> = [T] extends [string | ReadonlyArray<unknown>] ? never : T extends string | ReadonlyArray<unknown> | { '~appHotkey': true; } ? never : UnknownHotkeyKeys<T[Extract<keyof T, HotkeyPlatform | 'default'>]> | UnknownStepKeys<T[Extract<keyof T, HotkeyPlatform | 'default'>]>; type KnownEntries<T> = { [K in Extract<keyof T, HotkeyPlatform | 'default'>]: KnownEntry<T[K]>; }; type UnknownAlternateKeys<T> = [T] extends [string | ReadonlyArray<unknown>] ? never : UnknownHotkeyKeys<AlternatesOf<T>> | UnknownStepKeys<AlternatesOf<T>> | UnknownEntryKeys<AlternatesOf<T>>; type KnownAlternates<T> = T extends { alternates?: infer TAlternates; } ? { [I in keyof NonNullable<TAlternates>]: KnownEntry<NonNullable<TAlternates>[I]> & KnownEntries<NonNullable<TAlternates>[I]>; } : never; type UnknownHotkeyKeys<T> = [T] extends [string | ReadonlyArray<unknown>] ? never : T extends string | ReadonlyArray<unknown> | { '~appHotkey': true; } ? never : Exclude<keyof T, HotkeyPlatform | 'default' | 'alternates' | 'key' | 'code' | keyof RawModifiers>; /** * The hotkeys a registerable hotkey can resolve to: every entry of a * `PlatformHotkeys` object that isn't `null`, including the entries of its * alternates, or the hotkey itself. */ export type PlatformHotkeyEntries<T> = [T] extends [string | ReadonlyArray<unknown>] ? T : T extends string | ReadonlyArray<unknown> | { key: unknown; } | { code: unknown; } ? T : OwnPlatformEntries<T> | (AlternatesOf<T> extends (infer TAlternate) ? TAlternate extends string | ReadonlyArray<unknown> | { key: unknown; } | { code: unknown; } ? TAlternate : OwnPlatformEntries<TAlternate> : never); type AlternatesOf<T> = [T] extends [string | ReadonlyArray<unknown>] ? never : T extends { alternates?: infer TAlternates; } ? [NonNullable<TAlternates>] extends [never] ? never : NonNullable<TAlternates> extends ReadonlyArray<infer TAlternate> ? TAlternate : never : never; type EntriesOf<T> = [T] extends [string | ReadonlyArray<unknown>] ? never : T extends string | ReadonlyArray<unknown> ? never : T[Extract<keyof T, HotkeyPlatform | 'default'>]; /** * A type that TypeScript relates to every unresolved type parameter and to * no hotkey. TypeScript relates a mapped type `{ [P in Q]: X }` to a type * parameter `T` when `keyof T` is in `Q` and `X` is in `T[P]`, and `never` is * in every `T[P]`. */ type TypeParameterProbe = { [K in PropertyKey]: never; }; /** * `TThen` while the hotkey type `T`, one of its entries, alternates, or * sequence steps is still generic: a type parameter, or a type built from * one, such as `Shortcuts[K]`, as in a wrapper around a hotkey * function, and `TElse` once `T` is a hotkey type. * * A function that checks its hotkey with a conditional type, such as * `KnownHotkey`, can't check a type parameter: the condition stays * unresolved, and TypeScript rejects the call. With this type the function * takes `TThen` in a wrapper and keeps its check everywhere else, in one * signature. TypeScript relates an argument to an unresolved conditional * type by its branches, and skips the false branch when the checked type is * assignable to the extends type for any `T`. The probe is. * * @example * ```ts * function useHotkey<const T extends RegisterableHotkey>( * hotkey: IfTypeParameter<T, RegisterableHotkey, KnownHotkey<T>>, * ): void * * // Compiles: `T` is a type parameter here. * function useShortcut<T extends Hotkey>(hotkey: T) { * useHotkey(hotkey) * } * ``` */ export type IfTypeParameter<T, TThen, TElse> = [TypeParameterProbe] extends [HotkeyPartsOf<T> | StepsOf<HotkeyPartsOf<T>>] ? TThen : IfGenericHotkey<T, TThen, TElse>; type IfGenericHotkey<T, TThen, TElse> = [[HotkeyPartsOf<T> | StepsOf<HotkeyPartsOf<T>>] extends [NotANumber] ? 1 : 2] extends [[HotkeyPartsOf<T> | StepsOf<HotkeyPartsOf<T>> | 0] extends [NotANumber] ? 1 : 2] ? TThen : TElse; type NotANumber = string | object | null | undefined; type HotkeyPartsOf<T> = T | EntriesOf<T> | AlternatesOf<T> | EntriesOf<AlternatesOf<T>>; type StepsOf<T> = [T] extends [string] ? never : T extends ReadonlyArray<infer TStep> ? TStep : never; /** * The hotkeys `resolvePlatformHotkey` can return: every entry of a * `PlatformHotkeys` object that isn't `null`, without its alternates, or the * hotkey itself. */ export type PlatformHotkeyEntry<T> = [T] extends [string | ReadonlyArray<unknown>] ? T : T extends string | ReadonlyArray<unknown> | { key: unknown; } | { code: unknown; } ? T : OwnPlatformEntries<T>; type OwnPlatformEntries<T> = Exclude<T[Exclude<keyof T, 'alternates'>], null | undefined>; /** Context passed to a chord's callback. */ export interface HotkeyChordCallbackContext { kind: 'chord'; /** The registered chord */ hotkey: HotkeyChord; /** The chord with `Mod` resolved for the registration's platform */ parsedChord: ParsedHotkeyChord; } /** Context passed to a sequence's callback. */ export interface HotkeySequenceCallbackContext { kind: 'sequence'; /** The registered sequence */ hotkey: HotkeySequence; /** Each step with `Mod` resolved for the registration's platform */ parsedSequence: Array<ParsedHotkeyChord>; } /** * Context passed to hotkey callbacks along with the keyboard event. * Narrow with `kind` to read `parsedChord` or `parsedSequence`. */ export type HotkeyCallbackContext = HotkeyChordCallbackContext | HotkeySequenceCallbackContext; /** * The callback context for a hotkey: chord context for chords (including * one-step tuples), sequence context for sequences, and either when the kind * is not known statically. A hotkey per platform takes the kinds of its * entries. */ export type HotkeyCallbackContextFor<T> = [PlatformHotkeyEntries<T>] extends [never] ? HotkeyCallbackContext : PlatformHotkeyEntries<T> extends (infer TEntry) ? TEntry extends readonly [RegisterableHotkeyChord] ? HotkeyChordCallbackContext : TEntry extends RegisterableHotkeySequence ? HotkeySequenceCallbackContext : HotkeyChordCallbackContext : never; /** * Callback function type for hotkey handlers. * * @param event - The keyboard event that triggered the hotkey * @param context - The registered hotkey and its parsed form. APIs that take * one hotkey narrow it to chord or sequence context from the hotkey you pass. * * @example * ```ts * const handler: HotkeyCallback = (event, context) => { * if (context.kind === 'chord') { * console.log(context.hotkey, context.parsedChord.modifiers) * } else { * console.log(context.hotkey.join(' '), context.parsedSequence.length) * } * } * ``` */ export type HotkeyCallback<TContext extends HotkeyCallbackContext = HotkeyCallbackContext> = (event: KeyboardEvent, context: TContext) => void; /** * Metadata for hotkey registrations, chords and sequences alike. * Includes `name`, `description`, and `group` by default. Extend via declaration * merging on the adapter package you import from. With pnpm, `@tanstack/hotkeys` * itself can't be resolved from your app, so augmenting it fails. * * @example * ```ts * declare module '@tanstack/react-hotkeys' { * interface HotkeyMeta { * category?: string * icon?: string * } * } * ``` */ export interface HotkeyMeta { /** Human-readable name for this hotkey (e.g., "Save Document") */ name?: string; /** Description of what this hotkey does */ description?: string; /** Optional display group. Does not affect matching or scope. */ group?: string; } /** * Behavior when registering a hotkey/sequence that conflicts with an existing registration. * * - `'warn'` - Log a warning to the console but allow both registrations (default) * - `'error'` - Throw an error and prevent the new registration * - `'allow'` - Allow multiple registrations without warning */ export type ConflictBehavior = 'warn' | 'error' | 'allow'; /** A value, or a function that returns it, for options read when needed. */ export type MaybeGetter<T> = T | (() => T); export {};