@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
298 lines (296 loc) • 12.2 kB
JavaScript
import { chordHasKey } from "./_chord.js";
import { canWarn } from "./_dev.js";
import { defaultHotkeyOptions, definedOptions, withDefaults } from "./_registration.js";
import { warnServerPlatform } from "./_server.js";
import { resolveMaybeGetter } from "./_getter.js";
import { createStore } from "./_store.js";
import { createAppHotkeysStore, detectPlatform, formatForDisplay, getAppHotkeyRegistrationOptions, getHotkeyManager, getKeyboardLayoutStore, installAppHotkeysStore, isAppHotkey, isHotkeySequence, loadKeyboardLayout, matchesHeldModifiers, normalizeHotkey, parseHotkey, resolveAppHotkey, toHotkeyRegistrationView } from "@tanstack/hotkeys";
// src/adapter.ts
/**
* Reconciles adapter registrations while retaining handles for option updates.
* Adapters for frameworks that delegate key events, such as React, pass
* `{ afterDelegatedHandlers: true }`.
*/
function createHotkeyBindings(adapterOptions = {}) {
const registrations = /* @__PURE__ */ new Map();
let warned;
return {
/**
* 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, commonOptions = {}) {
const prepared = [];
definitions.forEach((definition, index) => {
const merged = definedOptions(commonOptions, definition.options);
const options = {
...defaultHotkeyOptions,
...merged,
...adapterOptions,
target: "target" in merged ? merged.target ?? null : typeof document === "undefined" ? null : document,
platform: merged.platform ?? detectPlatform()
};
if (!options.target || !definition.hotkey || isHotkeySequence(definition.hotkey) && definition.hotkey.length === 0) return;
const parsed = parseHotkey(definition.hotkey, options.platform);
if (!(Array.isArray(parsed) ? parsed : [parsed]).every(chordHasKey)) {
if (canWarn && process.env.NODE_ENV !== "production") {
const text = JSON.stringify(definition.hotkey);
if (!(warned ??= /* @__PURE__ */ new Set()).has(text)) {
warned.add(text);
console.warn(`[hotkeys] Invalid hotkey ${text} was not registered`);
}
}
return;
}
const hotkey = normalizeHotkey(parsed, options.platform);
if (isHotkeySequence(hotkey)) delete options.requireReset;
else delete options.timeout;
prepared.push({
key: `${index}:${isHotkeySequence(hotkey) ? hotkey.join(" ") : hotkey}`,
callback: definition.callback,
options,
register: () => getHotkeyManager().register(hotkey, definition.callback, options)
});
});
const keys = new Set(prepared.map((binding) => binding.key));
for (const [key, registration] of registrations) if (!keys.has(key)) {
registration.handle.unregister();
registrations.delete(key);
}
for (const binding of prepared) {
const previous = registrations.get(binding.key);
const { target, platform } = binding.options;
if (previous?.handle.isActive && previous.target === target && previous.platform === platform) {
previous.handle.callback = binding.callback;
const reset = Object.fromEntries(Object.keys(previous.options).map((key) => [key, void 0]));
previous.handle.setOptions({
...reset,
...binding.options
});
previous.options = binding.options;
} else {
previous?.handle.unregister();
registrations.set(binding.key, {
handle: binding.register(),
target,
platform,
options: binding.options
});
}
}
},
destroy() {
for (const { handle } of registrations.values()) handle.unregister();
registrations.clear();
}
};
}
/**
* 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.
*/
function prepareHotkeyDefinitions(definitions, options = {}) {
return definitions.map((definition) => {
let hotkey = definition.hotkey;
let declared = {};
if (isAppHotkey(hotkey)) {
const appHotkey = resolveAppHotkey(hotkey, options.appHotkeysStore);
declared = getAppHotkeyRegistrationOptions(appHotkey);
hotkey = appHotkey.hotkey ?? [];
}
const layers = [
options.defaults,
declared,
options.commonOptions,
definition.options
];
const { target, ...merged } = definedOptions(...layers);
const resolved = target === void 0 ? null : options.resolveTarget ? options.resolveTarget(target) : target;
return {
hotkey,
callback: definition.callback,
options: layers.some((layer) => layer && Object.hasOwn(layer, "target")) ? {
...merged,
target: resolved ?? null
} : merged
};
});
}
/**
* 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.
*/
function subscribePublishedAppHotkeys(onChange) {
const slot = getHotkeyManager().appHotkeys;
let inner;
const follow = () => {
inner?.unsubscribe();
inner = slot.state?.store.subscribe(onChange);
};
follow();
const outer = slot.subscribe(() => {
follow();
onChange();
});
return () => {
outer.unsubscribe();
inner?.unsubscribe();
};
}
/**
* 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.
*/
function mergeHotkeysProviderDefaults(parent, own, scope) {
const parentPlatform = { platform: parent?.platform };
const ownPlatform = { platform: own?.platform };
return {
...definedOptions({ keyboardLayout: parent?.keyboardLayout }, { keyboardLayout: own?.keyboardLayout }),
...definedOptions(parentPlatform, ownPlatform),
hotkey: {
...definedOptions(parentPlatform, parent?.hotkey, ownPlatform, own?.hotkey),
...scope && { scope }
},
hotkeyRecorder: definedOptions(parentPlatform, parent?.hotkeyRecorder, ownPlatform, own?.hotkeyRecorder)
};
}
/**
* 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.
*/
function getServerPlatformSnapshot() {
warnServerPlatform();
return "linux";
}
/**
* 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.
*/
function getHotkeysProviderScopeKey(options) {
const { scope, exclusive, active, parent } = options;
if (!scope || !active) return null;
return JSON.stringify([
scope,
typeof exclusive === "object" ? exclusive.allow : !!exclusive,
parent ?? null
]);
}
/**
* Activates the scope described by a key from `getHotkeysProviderScopeKey`.
* Returns a function that releases the activation.
*/
function activateHotkeysProviderScope(key) {
const [scope, exclusive, parent] = JSON.parse(key);
return getHotkeyManager().activateScope(scope, {
exclusive: Array.isArray(exclusive) ? { allow: exclusive } : exclusive,
parent: parent ?? void 0
});
}
/**
* 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.
*/
function namesPhysicalKey(hotkey) {
if (typeof hotkey === "string") return /\[\w+\]/.test(hotkey);
if (Array.isArray(hotkey)) return hotkey.some(namesPhysicalKey);
return hotkey.code !== void 0;
}
/**
* The app hotkeys store, typed by `Register`, or throws when there is none.
* `message` says which API needs it and how to provide one.
*/
function requireAppHotkeysStore(store, message) {
if (!store) throw new Error(`[hotkeys] ${message}`);
return store;
}
/**
* The store published with `publishAppHotkeysStore` or `provideAppHotkeys`,
* or `null`. For adapters that resolve app hotkeys without a provider.
*/
function getPublishedAppHotkeysStore() {
return getHotkeyManager().appHotkeys.state;
}
/**
* Custom hotkey actions that call the store from `getStore` each time, so they
* follow a store that changes.
*/
function bindCustomHotkeyActions(getStore) {
return {
setCustomHotkey: (id, hotkey, recordedWith) => getStore().setCustomHotkey(id, hotkey, recordedWith),
resetCustomHotkey: (id) => getStore().resetCustomHotkey(id),
resetCustomHotkeys: () => getStore().resetCustomHotkeys(),
findConflicts: (id, hotkey, recordedWith) => getStore().findConflicts(id, hotkey, recordedWith)
};
}
/** Views of every registration, chords and sequences, for registration lists. */
function getHotkeyRegistrationViews(registrations = getHotkeyManager().registrations.state) {
return Array.from(registrations.values()).map(toHotkeyRegistrationView);
}
/**
* 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.
*/
function isHotkeyHintVisible(hotkey, heldKeys, options = {}, appHotkeysStore) {
const resolved = isAppHotkey(hotkey) ? resolveAppHotkey(hotkey, appHotkeysStore).hotkey : hotkey;
return resolved !== null && matchesHeldModifiers(resolved, heldKeys, options) && getHotkeyManager().hasActiveRegistration(hotkey);
}
/**
* 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.
*/
function createFormatForDisplay(getPlatform, getLayoutMap) {
return ((hotkey, options) => formatForDisplay(hotkey, {
...options,
platform: options?.platform ?? getPlatform(),
layoutMap: options?.layoutMap ?? (namesPhysicalKey(hotkey) ? getLayoutMap() ?? void 0 : void 0)
}));
}
/**
* 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.
*/
function followKeyboardLayout(onChange, load = loadKeyboardLayout) {
const stop = load();
const { unsubscribe } = getKeyboardLayoutStore().subscribe(onChange);
return () => {
unsubscribe();
stop();
};
}
/**
* Resolves a ref object to its current element; other targets pass through.
* An unset ref resolves to `null` or `undefined`, so registration waits.
*/
function resolveRefTarget(target) {
return target !== null && typeof target === "object" && "current" in target ? target.current : target;
}
/** The option keys each recorder last received from `syncRecorderOptions`. */
const syncedRecorderKeys = /* @__PURE__ */ new WeakMap();
/**
* 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.
*/
function syncRecorderOptions(recorder, options) {
const next = { ...options };
for (const key of syncedRecorderKeys.get(recorder) ?? []) if (!(key in next)) next[key] = void 0;
syncedRecorderKeys.set(recorder, Object.keys(next));
recorder.setOptions(next);
}
export { activateHotkeysProviderScope, bindCustomHotkeyActions, createAppHotkeysStore, createFormatForDisplay, createHotkeyBindings, createStore, definedOptions, followKeyboardLayout, getHotkeyRegistrationViews, getHotkeysProviderScopeKey, getPublishedAppHotkeysStore, getServerPlatformSnapshot, installAppHotkeysStore, isHotkeyHintVisible, mergeHotkeysProviderDefaults, namesPhysicalKey, prepareHotkeyDefinitions, requireAppHotkeysStore, resolveMaybeGetter, resolveRefTarget, subscribePublishedAppHotkeys, syncRecorderOptions, withDefaults };