UNPKG

@tanstack/hotkeys

Version:

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

472 lines • 24.8 kB
import { Store } from "./_store.js"; import { HotkeyChordOptions, HotkeyRegistrationStatus, HotkeyRegistrationView, HotkeySequenceOptions } from "./hotkey-manager.js"; import { Hotkey, HotkeyChord, HotkeyMeta, HotkeySequence, KnownHotkey, PlatformHotkeyEntries, PlatformHotkeys } from "./hotkey.types.js"; import { HotkeyPlatform } from "./platform.js"; import { Register } from "./register.js"; type DeclaredOptionKeys = 'capture' | 'conflictBehavior' | 'eventType' | 'ignoreInputs' | 'preventDefault' | 'stopPropagation'; /** Declared options for an app hotkey whose default is a chord. */ export type AppHotkeyChordOptions = Pick<HotkeyChordOptions, DeclaredOptionKeys | 'requireReset'>; /** Declared options for an app hotkey whose default is a sequence. */ export type AppHotkeySequenceOptions = Pick<HotkeySequenceOptions, DeclaredOptionKeys | 'timeout'>; /** Every declared option. Kind-specific options apply only while the effective hotkey has that kind. */ export type AppHotkeyOptions = AppHotkeyChordOptions & AppHotkeySequenceOptions; /** * The hotkey of an app hotkey: a chord, a sequence, one of those per * platform, or `null` for none. Read every hotkey of one for a platform with * `resolveHotkeys`, or its entry alone with `resolvePlatformHotkey`. */ export type AppHotkeyBinding = Hotkey | PlatformHotkeys<Hotkey> | null; /** One declaration passed to `defineAppHotkeys`. */ export interface AppHotkeyInput { /** * Default hotkey: a chord, a sequence, one of those per platform, or `null` * for an action without a default. */ hotkey: AppHotkeyBinding; /** Display metadata for cheat sheets and settings screens. */ meta?: HotkeyMeta; /** * Scope this hotkey fires in, such as `'editor'`. Overrides the scope of the * provider it registers under. App hotkeys in different scopes may share a * hotkey; one in the `'global'` scope conflicts with any app hotkey that * shares its hotkey. */ scope?: string; /** * Options that describe the hotkey itself. Chord defaults accept * `requireReset`; sequence defaults accept `timeout`. */ options?: AppHotkeyOptions; } /** * A declared app hotkey. It never holds a callback: register it with * `useHotkey(appHotkey, callback)` or the equivalent adapter API. * * `TDefault` is the kind of the declared default (`HotkeyChord`, * `HotkeySequence`, `PlatformHotkeys` of either, or `null`). Adapters use it * to type kind-specific options. */ export interface AppHotkey<TId extends string = string, TDefault extends AppHotkeyBinding = AppHotkeyBinding> { /** Brand that distinguishes app hotkeys from raw hotkey objects. */ readonly '~appHotkey': true; /** Stable id. Saved custom hotkeys are keyed by this value. */ readonly id: TId; /** * Effective hotkey: the user's custom hotkey, or the default. `null` means * unbound. A default declared per platform stays an object here. */ readonly hotkey: AppHotkeyBinding; /** Hotkey declared in `defineAppHotkeys`. */ readonly defaultHotkey: TDefault; readonly meta?: HotkeyMeta; readonly scope?: string; readonly options?: AppHotkeyOptions; } /** A map of app hotkeys keyed by id. */ export type AppHotkeys = Readonly<Record<string, AppHotkey>>; type AllowedOptions<THotkey> = THotkey extends ReadonlyArray<unknown> ? AppHotkeySequenceOptions : THotkey extends null ? AppHotkeyOptions : THotkey extends string | UncheckedHotkey ? AppHotkeyChordOptions : AllowedEntryOptions<PlatformHotkeyEntries<THotkey>>; type AllowedEntryOptions<TEntry> = [TEntry] extends [never] ? AppHotkeyOptions : [TEntry] extends [ReadonlyArray<unknown>] ? AppHotkeySequenceOptions : [Extract<TEntry, ReadonlyArray<unknown>>] extends [never] ? AppHotkeyChordOptions : AppHotkeyOptions; type StrictOptions<TOptions, TAllowed> = TOptions extends object ? { [P in Exclude<keyof TOptions, keyof TAllowed>]: never; } & TAllowed : TAllowed; declare const uncheckedHotkey: unique symbol; /** * A marker in `AppHotkeyDeclaration['hotkey']` that no hotkey value has. A * hotkey type that includes it is the constraint itself, seen while the * declarations are still being inferred, not a value someone wrote. */ interface UncheckedHotkey { readonly [uncheckedHotkey]: true; } /** The entries of a hotkey object before `defineAppHotkeys` checks them. */ type UncheckedPlatformEntries = { readonly [K in HotkeyPlatform | 'default']?: string | ReadonlyArray<string> | null; }; /** A hotkey object before `defineAppHotkeys` checks its entries. */ type UncheckedPlatformHotkeys = UncheckedPlatformEntries & { readonly alternates?: ReadonlyArray<string | ReadonlyArray<string> | UncheckedPlatformEntries>; }; /** * The shape of a declaration before `defineAppHotkeys` checks its hotkey and * options. `DefinedAppHotkeys` takes a map of these. * * It names no hotkey type on purpose. While TypeScript infers the * declarations, it checks every literal in the call against contextual types * built from this shape, and each check walks any union it finds. With the * chord union (thousands of members) here, each keystroke in a large * declaration took seconds in editors. `ValidatedAppHotkeyInputs` checks each * hotkey once the declarations are inferred. */ export interface AppHotkeyDeclaration { /** * Default hotkey: a chord, a sequence, one of those per platform, or `null` * for an action without a default. */ hotkey: string | ReadonlyArray<string> | UncheckedHotkey | null | UncheckedPlatformHotkeys; /** Display metadata for cheat sheets and settings screens. */ meta?: HotkeyMeta; /** * Scope this hotkey fires in, such as `'editor'`. Overrides the scope of the * provider it registers under. App hotkeys in different scopes may share a * hotkey; one in the `'global'` scope conflicts with any app hotkey that * shares its hotkey. */ scope?: string; /** * Options that describe the hotkey itself. Chord defaults accept * `requireReset`; sequence defaults accept `timeout`. */ options?: AppHotkeyOptions; } /** * The property docs of a declaration, for hover in editors. Each property is * `unknown`, so intersecting it leaves the declaration's types unchanged. */ interface AppHotkeyDeclarationDocs { /** * Default hotkey: a chord, a sequence, one of those per platform, or `null` * for an action without a default. */ hotkey?: unknown; /** Display metadata for cheat sheets and settings screens. */ meta?: unknown; /** * Scope this hotkey fires in, such as `'editor'`. Overrides the scope of the * provider it registers under. App hotkeys in different scopes may share a * hotkey; one in the `'global'` scope conflicts with any app hotkey that * shares its hotkey. */ scope?: unknown; /** * Options that describe the hotkey itself. Chord defaults accept * `requireReset`; sequence defaults accept `timeout`. */ options?: unknown; } /** * Whether a declared hotkey is valid. A string is checked against the chord * union and a sequence step by step, which avoids relating each sequence to * every chord. The unresolved constraint, seen while the declarations are * still being inferred, counts as valid so that contextual types stay free * of the hotkey unions. */ type IsValidHotkey<THotkey> = [UncheckedHotkey] extends [THotkey] ? [0] extends [THotkey] ? false : true : [THotkey] extends [string | ReadonlyArray<unknown> | null] ? IsValidEntry<THotkey> : [THotkey] extends [object] ? IsValidPlatformHotkeys<THotkey> : [THotkey] extends [AppHotkeyBinding] ? true : false; /** Whether a chord, a sequence, or `null` is valid. */ type IsValidEntry<THotkey> = [THotkey] extends [null] ? true : [THotkey] extends [string] ? [THotkey] extends [HotkeyChord] ? true : false : [THotkey] extends [ReadonlyArray<infer TStep>] ? [TStep] extends [HotkeyChord] ? true : false : [THotkey] extends [Hotkey | null] ? true : false; /** * Whether a hotkey object is valid: it names only platforms, `default`, and * `alternates`, it has a `default`, every entry is a valid chord, sequence, * or `null`, and every alternate is a valid chord, sequence, or object of * entries. */ type IsValidPlatformHotkeys<THotkey> = [THotkey extends unknown ? IsValidPlatformObject<THotkey> : never] extends [true] ? true : false; type IsValidPlatformObject<THotkey> = [keyof THotkey] extends [HotkeyPlatform | 'default' | 'alternates'] ? [IsValidPlatformEntries<THotkey>] extends [true] ? [THotkey] extends [{ alternates?: infer TAlternates; }] ? [unknown] extends [TAlternates] ? true : [NonNullable<TAlternates>] extends [never] ? true : [NonNullable<TAlternates>] extends [ReadonlyArray<infer TAlternate>] ? [TAlternate extends string | ReadonlyArray<unknown> ? IsValidEntry<TAlternate> : TAlternate extends object ? keyof TAlternate extends HotkeyPlatform | 'default' ? IsValidPlatformEntries<TAlternate> : false : false] extends [true] ? true : false : false : true : false : false; /** Whether an object has a `default` and only valid entries. */ type IsValidPlatformEntries<THotkey> = [THotkey] extends [{ default: unknown; }] ? [{ [K in Exclude<keyof THotkey, 'alternates'>]: IsValidEntry<THotkey[K]>; }[Exclude<keyof THotkey, 'alternates'>]] extends [true] ? true : false : false; /** * The kind of a spread-in app hotkey's `hotkey`: its declared kind while it * is the unchanged `AppHotkeyBinding`, or the kind of a replacement. */ type SpreadInKind<THotkey, TDefault> = [THotkey] extends [null] ? null : [AppHotkeyBinding] extends [THotkey] ? TDefault : AppHotkeyDefaultKind<THotkey>; /** * Rejects options that do not apply to a declaration's default kind. A * spread-in app hotkey keeps its declared kind unless the declaration * replaces its `hotkey`, and its unchanged options were checked by its own * `defineAppHotkeys` call. */ type ValidatedOptions<TInput, THotkey> = TInput extends AppHotkey<string, infer TDefault> ? [AppHotkeyOptions] extends [NonNullable<TInput['options']>] ? unknown : { options?: StrictOptions<TInput['options'], AllowedOptions<SpreadInKind<THotkey, TDefault>>>; } : { options?: StrictOptions<TInput extends { options: infer TOptions; } ? TOptions : {}, AllowedOptions<THotkey>>; }; /** * Checks each declaration once `T` is inferred. Options must match the * default's kind. An invalid hotkey string or step is reported against * `Hotkey | null`, which gives TypeScript's "Did you mean" suggestion. Each * checked entry is intersected with `AppHotkeyDeclarationDocs` so editors * show its property docs on hover. * * The valid branch repeats the declaration (`T[K]`) rather than its * `hotkey` type. Repeating the hotkey type makes TypeScript 5.7 and later * intersect two copies of the hotkey unions, which takes seconds and * gigabytes for a few dozen entries. */ type ValidatedAppHotkeyInputs<T> = { [K in keyof T]: T[K] extends { hotkey: infer THotkey; } ? IsValidHotkey<THotkey> extends true ? T[K] & AppHotkeyDeclarationDocs & ValidatedOptions<T[K], THotkey> : Omit<T[K], 'hotkey'> & { hotkey: InvalidHotkeyFallback<THotkey>; } & AppHotkeyDeclarationDocs & ValidatedOptions<T[K], THotkey> : 'defineAppHotkeys needs TypeScript 6.0 or later'; }; /** * What an invalid hotkey is checked against, so the error names the hotkey. * An object from a variable keeps extra keys, so each key that * `PlatformHotkeys` doesn't know becomes `never`, for every member of a union * and for each object in `alternates`. */ type InvalidHotkeyFallback<THotkey> = (THotkey extends string | ReadonlyArray<unknown> | null ? Hotkey | null : PlatformHotkeys<Hotkey>) & ([UnknownPlatformKeys<THotkey>] extends [never] ? unknown : { [P in UnknownPlatformKeys<THotkey>]: never; }) & KnownHotkey<Exclude<THotkey, null>, unknown>; type UnknownPlatformKeys<THotkey> = THotkey extends string | ReadonlyArray<unknown> | null ? never : Exclude<keyof THotkey, keyof PlatformHotkeys>; /** * The kind of a declared default hotkey; a one-step sequence is a chord. A * hotkey per platform is `PlatformHotkeys` of the kinds of its entries. */ export type AppHotkeyDefaultKind<THotkey> = THotkey extends string | ReadonlyArray<unknown> | null | UncheckedHotkey ? AppHotkeyEntryKind<THotkey> : PlatformHotkeys<[PlatformHotkeyEntries<THotkey>] extends [never] ? Hotkey : AppHotkeyEntryKind<PlatformHotkeyEntries<THotkey>>>; type AppHotkeyEntryKind<THotkey> = THotkey extends null ? null : THotkey extends readonly [unknown] ? HotkeyChord : THotkey extends ReadonlyArray<unknown> ? HotkeySequence : HotkeyChord; /** * The app hotkeys returned by `defineAppHotkeys` for a declaration object. An * entry that is already an app hotkey, spread in from another * `defineAppHotkeys` call, keeps the kind of its default. Spread the results * of `defineAppHotkeys`, not app hotkeys read from a store: their `hotkey` is * the user's custom hotkey, which would become the new default. */ export type DefinedAppHotkeys<T extends Record<string, AppHotkeyDeclaration>> = { readonly [K in keyof T & string]: AppHotkey<K, DeclaredDefaultKind<T[K]>>; }; /** * The default kind of one declaration. A spread-in app hotkey keeps its own * kind unless the declaration replaces its `hotkey`. The hotkey type is read * with `infer`: inside the `AppHotkey` branch, `TInput['hotkey']` would be * intersected with `Hotkey | null`, and with a generic id, such as * `typeof appHotkeys[TId]`, that intersection is too large to represent. */ type DeclaredDefaultKind<TInput extends AppHotkeyDeclaration> = TInput extends { hotkey: infer THotkey; } ? TInput extends AppHotkey<string, infer TDefault> ? SpreadInKind<THotkey, TDefault> : AppHotkeyDefaultKind<THotkey> : never; /** The app hotkeys type from `Register`, or a generic map when none is registered. */ export type RegisteredAppHotkeys = Register extends { appHotkeys: infer T extends AppHotkeys; } ? T : AppHotkeys; /** Ids of the registered app hotkeys. */ export type AppHotkeyId = keyof RegisteredAppHotkeys & string; /** * The user's hotkeys that differ from the declared defaults, keyed by app * hotkey id. This is the shape to save. `null` means the user unbound it. */ export type CustomHotkeys<T extends AppHotkeys = RegisteredAppHotkeys> = { -readonly [K in keyof T]?: Hotkey | null; }; /** * Declares every app hotkey up front, without registering any, so cheat * sheets and settings screens can list hotkeys whose components have not * mounted. Pass the result to `HotkeysProvider` as `appHotkeys`. * * Spread the results of other `defineAppHotkeys` calls to combine * declarations from several files. To pick declarations at runtime, call * `defineAppHotkeys` in each branch: a union of declaration objects doesn't * type-check. * * @example * ```ts * export const appHotkeys = defineAppHotkeys({ * 'doc.save': { hotkey: 'Mod+S', meta: { name: 'Save', group: 'Document' } }, * 'nav.home': { hotkey: ['G', 'H'], meta: { name: 'Go home' }, options: { timeout: 800 } }, * 'palette.open': { hotkey: null, meta: { name: 'Command palette' } }, * }) * ``` */ export declare function defineAppHotkeys<const T extends Record<string, AppHotkeyDeclaration>>(definitions: ValidatedAppHotkeyInputs<T>): DefinedAppHotkeys<T>; /** * Lets providers in this bundle create stores for app hotkeys. * `defineAppHotkeys` calls it. Adapters call it where the declarations can * arrive from another bundle, such as from a React Server Component. */ export declare function installAppHotkeysStore(): void; /** Whether a value is an app hotkey created by `defineAppHotkeys`. */ export declare function isAppHotkey(value: unknown): value is AppHotkey; /** Whether an app hotkey's effective hotkey differs from its default. */ export declare function isCustomHotkey(appHotkey: AppHotkey, platform?: HotkeyPlatform): boolean; /** * The key presses that recorded a hotkey. A recorder passes them to `validate` * and `onRecord` as its context, which can be passed on as is. */ export interface RecordedKeyPresses { /** The key press that recorded a chord. */ event?: KeyboardEvent; /** The key press that recorded each step of a sequence. */ events?: ReadonlyArray<KeyboardEvent>; } /** * Status of an app hotkey in the running app. * - `'active'`: at least one enabled registration * - `'suspended'`: has an enabled registration, but none can fire: its scope is * inactive, or it is a character key shortcut while character keys are suspended * - `'disabled'`: registered, but every registration is disabled * - `'inactive'`: has a hotkey, but nothing has registered it * - `'unbound'`: no hotkey assigned, or none for the store's platform */ export type AppHotkeyStatus = HotkeyRegistrationStatus | 'inactive' | 'unbound'; /** One row of an app hotkey cheat sheet. */ export interface AppHotkeyListItem<T extends AppHotkey = AppHotkey> { appHotkey: T; status: AppHotkeyStatus; /** Whether the effective hotkey differs from the declared default. */ isCustom: boolean; /** Live registrations of this app hotkey (for example, one per list row). */ registrations: Array<HotkeyRegistrationView>; } /** State of an `AppHotkeysStore`. */ export interface AppHotkeysState<T extends AppHotkeys = AppHotkeys> { /** Effective app hotkeys: declarations with custom hotkeys applied. */ appHotkeys: T; /** The user's hotkeys that differ from the defaults. */ customHotkeys: CustomHotkeys<T>; } /** A cheat sheet row for one of the registered app hotkeys. */ export type RegisteredAppHotkeyListItem = AppHotkeyListItem<RegisteredAppHotkeys[keyof RegisteredAppHotkeys]>; /** Actions that change the user's custom hotkeys, as adapters return them. */ export interface CustomHotkeyActions { /** * Sets the user's hotkey for an app hotkey. `null` unbinds it. * Returns conflicting app hotkeys; when any exist, nothing changes. Pass * the recorder's `context` for a recorded hotkey, as for `findConflicts`. */ setCustomHotkey: (id: AppHotkeyId, hotkey: Hotkey | null, recordedWith?: RecordedKeyPresses) => Array<AppHotkey>; /** Restores the default hotkey for an app hotkey. */ resetCustomHotkey: (id: AppHotkeyId) => void; /** Restores every default hotkey. */ resetCustomHotkeys: () => void; /** * Other app hotkeys that would collide if `id` used `hotkey`. Pass the * recorder's `context` for a recorded hotkey: it has the key press, which * also finds a hotkey written differently that the same press fires. */ findConflicts: (id: AppHotkeyId, hotkey: Hotkey, recordedWith?: RecordedKeyPresses) => Array<AppHotkey>; } /** Options for `AppHotkeysStore`. */ export interface AppHotkeysStoreOptions<T extends AppHotkeys = AppHotkeys> { /** * The user's saved custom hotkeys. Unknown ids and invalid entries are * ignored. Passing a different value to `setOptions` later, such as data * that finished loading or another user's data, replaces the current * custom hotkeys. `undefined` leaves them unchanged; a change to `null` * clears them. */ customHotkeys?: CustomHotkeys<T> | null; /** Called with the custom hotkeys after every change, ready to save. */ onCustomHotkeysChange?: (customHotkeys: CustomHotkeys<T>) => void; /** Platform used to compare hotkeys. Defaults to detection. */ platform?: HotkeyPlatform; } /** * Holds declared app hotkeys and the user's custom hotkeys. Framework * providers create one and expose it through hooks; devtools read it from * `HotkeyManager.appHotkeys`. * * @example * ```ts * const store = new AppHotkeysStore(appHotkeys, { * customHotkeys: JSON.parse(localStorage.getItem('hotkeys') ?? '{}'), * onCustomHotkeysChange: (custom) => * localStorage.setItem('hotkeys', JSON.stringify(custom)), * }) * store.setCustomHotkey('doc.save', 'Mod+Shift+S') * ``` */ export declare class AppHotkeysStore<T extends AppHotkeys = AppHotkeys> { #private; readonly store: Store<AppHotkeysState<T>>; constructor(appHotkeys: T, options?: AppHotkeysStoreOptions<T>); /** The platform this store compares hotkeys on: the `platform` option, or detection. */ get platform(): HotkeyPlatform; /** Effective app hotkeys. */ get appHotkeys(): T; /** The user's hotkeys that differ from the defaults. */ get customHotkeys(): CustomHotkeys<T>; /** * Updates options. Providers call it with their props on every update. * * When `customHotkeys` differs from the value last passed in, it replaces * the current custom hotkeys. An equal value, such as the same saved data * parsed again, keeps changes the user made since. `undefined` changes * nothing, such as while saved data loads; `null` clears them, such as on * sign-out. Replacing does not call `onCustomHotkeysChange`, because the * data came from the app. */ setOptions(options: AppHotkeysStoreOptions<T>): void; /** * Replaces the declarations, for example after hot module replacement. * Custom hotkeys for ids that still exist are kept. */ setAppHotkeys(appHotkeys: T): void; /** Effective app hotkey for an id, or `undefined` when it is not declared. */ get(id: string): AppHotkey | undefined; /** * Other app hotkeys that would collide if `id` used `hotkey`. App hotkeys * collide when their scopes match or either is `'global'`, and their * hotkeys are equal or one sequence starts with the other. * * Pass the recorder's `context` for a recorded hotkey. Two hotkeys written * differently can fire for one key press, such as `Shift+[Slash]` recorded * by code and a declared `?` on a US keyboard. Only the key press shows that. * * @example * ```ts * const recorder = new HotkeyRecorder({ * validate: (hotkey, context) => * store.findConflicts('doc.save', hotkey, context).length === 0 || * 'Already in use', * onRecord: (hotkey, context) => * store.setCustomHotkey('doc.save', hotkey, context), * }) * ``` */ findConflicts(id: keyof T & string, hotkey: Hotkey, recordedWith?: RecordedKeyPresses): Array<AppHotkey>; /** * Sets the user's hotkey for an app hotkey. `null` unbinds it. A hotkey * equal to the default removes the customization. Pass the recorder's * `context` for a recorded hotkey, as for `findConflicts`. * * @returns Conflicting app hotkeys. When any exist, nothing changes. * Nothing changes either for an unknown id or a value that isn't a valid * hotkey, such as `''`, and both return an empty array. */ setCustomHotkey(id: keyof T & string, hotkey: Hotkey | null, recordedWith?: RecordedKeyPresses): Array<AppHotkey>; /** Restores the default hotkey for an app hotkey. */ resetCustomHotkey(id: keyof T & string): void; /** Restores every default hotkey. */ resetCustomHotkeys(): void; /** * Joins app hotkeys with live registrations, in declaration order. * Adapters call this with the manager's registration views. */ getList(registrations: Iterable<HotkeyRegistrationView>): Array<AppHotkeyListItem<T[keyof T]>>; } /** * Returns the provider's version of an app hotkey, so custom hotkeys apply * even when a component imports the declaration directly. Falls back to the * given app hotkey when no store declares it. */ export declare function resolveAppHotkey(appHotkey: AppHotkey, store: AppHotkeysStore | null | undefined): AppHotkey; /** * Options that adapters pass to the manager when registering an app hotkey: * declared options, scope, meta, and the app hotkey id. The manager drops options * that do not apply to the effective hotkey's kind. */ export declare function getAppHotkeyRegistrationOptions(appHotkey: AppHotkey): AppHotkeyOptions & { meta?: HotkeyMeta; appHotkeyId: string; scope?: string; }; /** * Publishes a provider's store on the HotkeyManager so devtools can list * declared hotkeys. Returns a cleanup function that unpublishes it if it is * still the published store. */ export declare function publishAppHotkeysStore(store: AppHotkeysStore): () => void; /** * Creates an app hotkeys store and publishes it on the HotkeyManager, for * adapters without a provider component (such as Lit and Alpine). Hotkey * APIs in those adapters resolve app hotkeys and custom hotkeys from the * published store. Call it once at startup. Returns the store and a function * that unpublishes it. * * @example * ```ts * provideAppHotkeys(appHotkeys, { * customHotkeys: JSON.parse(localStorage.getItem('hotkeys') ?? '{}'), * onCustomHotkeysChange: (custom) => * localStorage.setItem('hotkeys', JSON.stringify(custom)), * }) * ``` */ export declare function provideAppHotkeys<T extends AppHotkeys>(appHotkeys: T, options?: AppHotkeysStoreOptions<T>): { store: AppHotkeysStore<T>; dispose: () => void; }; export type { Register };