UNPKG

@tanstack/hotkeys

Version:

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

274 lines • 14.3 kB
import { AppHotkey, AppHotkeysStore, CustomHotkeyActions, RegisteredAppHotkeys } from "./app-hotkeys.js"; import { DisplayHotkey } from "./format.js"; import { HeldModifierOptions } from "./hint.js"; import { ActivateHotkeyScopeOptions, HotkeyChordOptions, HotkeyCommonOptions, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationView, HotkeySequenceOptions } from "./hotkey-manager.js"; import { HotkeyChordRecorderOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeySequenceRecorderOptions } from "./hotkey-recorder.js"; import { HotkeyCallback, HotkeyChord, HotkeySequence, RegisterableHotkey, RegisterableHotkeyChord, RegisterableHotkeySequence, Target } from "./hotkey.types.js"; import { KeyboardLayoutMap } from "./keyboard-layout.js"; import { HotkeyPlatform } from "./platform.js"; import { resolveMaybeGetter } from "./_getter.js"; import { Store, createStore } from "./_store.js"; import { definedOptions, withDefaults } from "./_registration.js"; import { createAppHotkeysStore, formatForDisplay, installAppHotkeysStore } from "@tanstack/hotkeys"; /** * A hotkey and its callback, with optional per-binding options. Chords accept * `requireReset`; sequences accept `timeout`. */ export type HotkeyDefinition = { hotkey: RegisterableHotkeyChord; callback: HotkeyCallback; options?: HotkeyChordOptions; } | { hotkey: RegisterableHotkeySequence; callback: HotkeyCallback; options?: HotkeySequenceOptions; } | { /** No hotkey. Registers nothing. */ hotkey: null | undefined; callback: HotkeyCallback; options?: HotkeyCommonOptions; }; /** Options shared by every definition. Each option applies only to the kinds that support it. */ export type HotkeyBindingsCommonOptions = HotkeyCommonOptions; /** * Reconciles adapter registrations while retaining handles for option updates. * Adapters for frameworks that delegate key events, such as React, pass * `{ afterDelegatedHandlers: true }`. */ export declare function createHotkeyBindings(adapterOptions?: Pick<HotkeyOptions, 'afterDelegatedHandlers'>): { /** * Registers new definitions, updates existing ones in place, and removes * stale ones. Definitions with no hotkey (undefined, null, empty string, or * empty sequence) or a null target are skipped. */ update(definitions: ReadonlyArray<HotkeyDefinition>, commonOptions?: HotkeyBindingsCommonOptions): void; destroy(): void; }; /** Options with a framework-specific target, such as a ref. */ export type WithTarget<TOptions, TTarget> = Omit<TOptions, 'target' | 'appHotkeyId' | 'afterDelegatedHandlers'> & { /** The element to listen on. Defaults to document. */ target?: TTarget; }; /** Options shared by chords and sequences, with a framework target. */ export type AdapterHotkeyOptions<TTarget> = WithTarget<HotkeyOptions, TTarget>; /** Options for a chord such as `'Mod+S'`, with a framework target. */ export type AdapterChordOptions<TTarget> = WithTarget<HotkeyChordOptions, TTarget>; /** Options for a sequence such as `['G', 'G']`, with a framework target. */ export type AdapterSequenceOptions<TTarget> = WithTarget<HotkeySequenceOptions, TTarget>; /** Options applied to every hotkey, such as defaults. Each applies to the kinds that support it. */ export type AdapterCommonOptions<TTarget> = AdapterChordOptions<TTarget> & AdapterSequenceOptions<TTarget>; /** Chord options for chords, sequence options for sequences. */ export type AdapterOptionsFor<T extends RegisterableHotkey, TTarget> = [T] extends [never] ? AdapterCommonOptions<TTarget> : T extends readonly [unknown] ? AdapterChordOptions<TTarget> : T extends ReadonlyArray<unknown> ? AdapterSequenceOptions<TTarget> : AdapterChordOptions<TTarget>; /** * Call-site options for an app hotkey. `meta` comes from the declaration. * Kind-specific options follow the declared default: `requireReset` for a * chord, `timeout` for a sequence, both for an app hotkey without a default. * If the user rebinds it to the other kind, options for the old kind no * longer apply. */ export type AdapterAppHotkeyOptions<T extends AppHotkey, TTarget> = Omit<[T['defaultHotkey']] extends [HotkeySequence] ? AdapterSequenceOptions<TTarget> : [T['defaultHotkey']] extends [HotkeyChord] ? AdapterChordOptions<TTarget> : AdapterCommonOptions<TTarget>, 'meta'>; /** * One hotkey and its callback for adapter APIs such as `useHotkeys`. Chords * accept `requireReset`; sequences accept `timeout`; hotkeys of unknown kind * accept only shared options. */ export type AdapterHotkeyDefinition<TTarget> = { /** A chord string such as `'Mod+S'`, or a chord object */ hotkey: RegisterableHotkeyChord; /** The function to call when the hotkey is pressed */ callback: HotkeyCallback; /** Per-hotkey options (merged on top of common options) */ options?: AdapterChordOptions<TTarget>; } | { /** A sequence such as `['G', 'G']`, with each step a string or an object */ hotkey: RegisterableHotkeySequence; callback: HotkeyCallback; options?: AdapterSequenceOptions<TTarget>; } | { /** * An app hotkey from `defineAppHotkeys`. Kind-specific options apply * only while its effective hotkey has that kind. */ hotkey: AppHotkey; callback: HotkeyCallback; options?: Omit<AdapterCommonOptions<TTarget>, 'meta'>; } | { /** * A hotkey whose kind is not known statically, such as user data typed * `Hotkey`. Accepts only shared options. `undefined`, `null`, and `''` * register nothing, for an optional shortcut. */ hotkey: RegisterableHotkey | null | undefined; callback: HotkeyCallback; options?: AdapterHotkeyOptions<TTarget>; }; /** Context for `prepareHotkeyDefinitions`. */ export interface PrepareHotkeyDefinitionsOptions<TTarget> { /** The provider's app hotkeys store, so app hotkeys use custom hotkeys. */ appHotkeysStore?: AppHotkeysStore | null; /** Provider defaults, applied first. */ defaults?: AdapterCommonOptions<TTarget>; /** Options for every definition, applied after app hotkey declarations. */ commonOptions?: AdapterCommonOptions<TTarget>; /** * Resolves a framework target, such as a ref. Return `null` or `undefined` * to skip registration until the target exists. Without it, targets pass * through. Only an omitted `target` listens on the document; a `target` set * to `null` or `undefined` waits. */ resolveTarget?: (target: TTarget) => Target | null | undefined; } /** * Converts adapter definitions into `createHotkeyBindings` definitions. * Options merge in this order: defaults, app hotkey declaration, common * options, per-definition options. App hotkeys resolve their effective hotkey * from the store, and an unbound app hotkey keeps its position but registers * nothing. */ export declare function prepareHotkeyDefinitions<TTarget>(definitions: ReadonlyArray<AdapterHotkeyDefinition<TTarget>>, options?: PrepareHotkeyDefinitionsOptions<TTarget>): Array<HotkeyDefinition>; /** * Calls `onChange` when the store published with `publishAppHotkeysStore` or * `provideAppHotkeys` changes, or when its app hotkeys or custom hotkeys * change. For adapters that resolve app hotkeys without a provider. Returns an * unsubscribe function. */ export declare function subscribePublishedAppHotkeys(onChange: () => void): () => void; /** Scope props shared by framework providers. */ export interface HotkeysProviderScopeProps { /** * Scope for hotkeys registered inside this provider, active while it is * mounted and enabled. Defaults to the parent provider's scope, or * `'global'` at the root. App hotkeys that declare a scope keep it. */ scope?: string; /** * While mounted and enabled, suspend hotkeys in every other scope, * including `'global'`, except scopes of nested providers. Pass * `{ allow: [...] }` to keep other scopes active, such as `'global'`. Use * with `scope`, for dialogs and other overlays. */ exclusive?: ActivateHotkeyScopeOptions['exclusive']; /** * Set false to deactivate this provider's scope, and the scopes of * providers nested in it, without unmounting. Defaults to true. */ enabled?: boolean; } /** * Provider defaults for every recorder. Each recorder sets its own * `maxSteps`, `onRecord`, and `validate`. */ export type HotkeyRecorderDefaults = Partial<Omit<HotkeyChordRecorderOptions & HotkeySequenceRecorderOptions, 'maxSteps' | 'onRecord' | 'validate'>>; /** * The shape of a provider's default options. Adapters declare their own * interface, documented with their API names, that satisfies this one. */ export interface HotkeysDefaultOptions<THotkeyOptions = object, TRecorderOptions = HotkeyRecorderDefaults> { platform?: HotkeyPlatform; keyboardLayout?: boolean; hotkey?: THotkeyOptions; hotkeyRecorder?: TRecorderOptions; } /** The value a framework provider passes down to its hotkeys and labels. */ export interface HotkeysContextValue<TDefaults> { appHotkeysStore: AppHotkeysStore | null; /** Merged with every ancestor provider's defaults, including `hotkey.scope`. */ defaultOptions: TDefaults; /** Whether this provider and every ancestor are enabled. */ enabled: boolean; } /** * Merges a provider's default options over its parent's. A provider with a * `scope` sets `hotkey.scope`, so hotkeys registered inside it use that scope. * A provider's `platform` is inherited, and is the default platform for its * hotkeys and recorders; `hotkey.platform` and `hotkeyRecorder.platform` win. * `keyboardLayout` is inherited too. */ export declare function mergeHotkeysProviderDefaults<T extends HotkeysDefaultOptions<object, object>>(parent: T | undefined, own: T | undefined, scope: string | undefined): T; /** * The platform to render with during server rendering and hydration when no * provider sets one, for a `useSyncExternalStore` server snapshot. Warns once * in development on the server. */ export declare function getServerPlatformSnapshot(): HotkeyPlatform; /** * A key for a provider's scope activation, or `null` when the scope should not * be active. Equal keys mean the same activation, so adapters reactivate only * when the key changes, not when an inline `exclusive` object is recreated. */ export declare function getHotkeysProviderScopeKey(options: { scope: string | undefined; exclusive: ActivateHotkeyScopeOptions['exclusive']; /** Whether this provider and every ancestor are enabled. */ active: boolean; /** The parent provider's scope. */ parent: string | undefined; }): string | null; /** * Activates the scope described by a key from `getHotkeysProviderScopeKey`. * Returns a function that releases the activation. */ export declare function activateHotkeysProviderScope(key: string): () => void; /** * Whether a hotkey to display names a physical position, such as `[KeyQ]` or * `{ code: 'KeyQ' }`. Only those labels follow the keyboard layout. A label * primitive that reads the layout reactively checks this first, so a label * such as `Mod+S` doesn't render again when the layout loads. */ export declare function namesPhysicalKey(hotkey: DisplayHotkey): boolean; /** * The app hotkeys store, typed by `Register`, or throws when there is none. * `message` says which API needs it and how to provide one. */ export declare function requireAppHotkeysStore(store: AppHotkeysStore | null | undefined, message: string): AppHotkeysStore<RegisteredAppHotkeys>; /** * The store published with `publishAppHotkeysStore` or `provideAppHotkeys`, * or `null`. For adapters that resolve app hotkeys without a provider. */ export declare function getPublishedAppHotkeysStore(): AppHotkeysStore | null; /** * Custom hotkey actions that call the store from `getStore` each time, so they * follow a store that changes. */ export declare function bindCustomHotkeyActions(getStore: () => AppHotkeysStore<RegisteredAppHotkeys>): CustomHotkeyActions; /** Views of every registration, chords and sequences, for registration lists. */ export declare function getHotkeyRegistrationViews(registrations?: ReadonlyMap<string, HotkeyRegistration>): Array<HotkeyRegistrationView>; /** * Whether a hotkey's hint shows: its modifiers are held and a registration * that can fire exists. App hotkeys resolve through `appHotkeysStore`. * Adapters read the held keys and registrations reactively, then call this. */ export declare function isHotkeyHintVisible(hotkey: RegisterableHotkey | AppHotkey | null | undefined, heldKeys: ReadonlyArray<string>, options?: HeldModifierOptions, appHotkeysStore?: AppHotkeysStore | null): boolean; /** * A `formatForDisplay` that uses a provider's platform and keyboard layout * when the call doesn't pass them. Only a label that names a physical key * reads `getLayoutMap`, so other labels don't depend on the layout. */ export declare function createFormatForDisplay(getPlatform: () => HotkeyPlatform | undefined, getLayoutMap: () => KeyboardLayoutMap | null | undefined): typeof formatForDisplay; /** * Loads the browser's keyboard layout and calls `onChange` when it changes. * Pass `load` to run the load differently, such as outside Angular's zone. * Returns a function that stops following and releases the load. */ export declare function followKeyboardLayout(onChange: (layoutMap: KeyboardLayoutMap | null) => void, load?: () => () => void): () => void; /** * A framework ref, element, document, or window to listen on. A `null` or * `undefined` target, or a ref that is still unset, waits for the element. */ export type RefTarget<TRef = { current: HTMLElement | null | undefined; }> = TRef | Target | null; /** * Resolves a ref object to its current element; other targets pass through. * An unset ref resolves to `null` or `undefined`, so registration waits. */ export declare function resolveRefTarget(target: RefTarget<{ current: HTMLElement | null | undefined; }>): Target | null | undefined; /** * Gives a recorder the full set of options an adapter resolved. Unlike * `setOptions`, which merges, an option the caller stopped passing, such as * a conditional `validate`, stops applying. */ export declare function syncRecorderOptions(recorder: HotkeyRecorder, options: HotkeyRecorderOptions): void; export { type Store, createAppHotkeysStore, createStore, definedOptions, installAppHotkeysStore, resolveMaybeGetter, withDefaults };