@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
337 lines (335 loc) • 13.9 kB
JavaScript
import { definedOptions, withDefaults } from "./_registration.js";
import { warnServerPlatform } from "./_server.js";
import { resolveMaybeGetter } from "./_getter.js";
import { createStore } from "./_store.js";
import { createAppHotkeysStore, formatForDisplay, formatHotkey, getAppHotkeyRegistrationOptions, getHotkeyManager, getKeyboardLayoutStore, installAppHotkeysStore, isAppHotkey, isPlatformHotkeys, loadKeyboardLayout, matchesHeldModifiers, parseHotkey, resolveAppHotkey, resolveHotkeys, 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();
return {
/**
* Registers new definitions, updates existing ones in place, and removes
* stale ones. `HotkeyManager.register` validates each hotkey, so
* definitions with no hotkey (undefined, null, empty string, or empty
* sequence), an invalid hotkey, or a null target register nothing, and
* are tried again on the next update.
*/
update(definitions, commonOptions = {}) {
const prepared = definitions.map((definition, index) => ({
key: `${index}:${JSON.stringify(definition.hotkey ?? null)}`,
definition,
options: {
...definedOptions(commonOptions, definition.options),
...adapterOptions
}
}));
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 { key, definition, options } of prepared) {
const previous = registrations.get(key);
const { target, platform } = options;
if (previous?.handle.isActive && previous.target === target && previous.platform === platform) {
previous.handle.callback = definition.callback;
const reset = Object.fromEntries(Object.keys(previous.options).map((name) => [name, void 0]));
previous.handle.setOptions({
...reset,
...options
});
previous.options = options;
} else {
previous?.handle.unregister();
registrations.set(key, {
handle: getHotkeyManager().register(definition.hotkey, definition.callback, options),
target,
platform,
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);
if (declared) {
const metas = [
declared.meta,
options.commonOptions?.meta,
definition.options?.meta
].filter((meta) => meta !== void 0);
if (metas.length > 1) merged.meta = definedOptions(...metas);
}
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);
if (isPlatformHotkeys(hotkey)) return Object.values(hotkey).some((entry) => !!entry && namesPhysicalKey(entry));
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 matchesHeldModifiers(resolved, heldKeys, options) && canHintedHotkeyFire(hotkey, options, appHotkeysStore);
}
/**
* Whether the hotkey that a hint belongs to can fire: the hotkey its label
* shows, not just an alternate of it. For an app hotkey, one of its own
* registrations must have it. Adapters that read registrations and held keys
* apart select on this, so a hint follows its hotkey when an alternate stays
* registered.
*/
function canHintedHotkeyFire(hotkey, options = {}, appHotkeysStore) {
const resolved = isAppHotkey(hotkey) ? resolveAppHotkey(hotkey, appHotkeysStore).hotkey : hotkey;
const shown = resolveHotkeys(resolved, options.platform)[0];
if (shown === void 0) return false;
let explicit;
try {
explicit = formatHotkey(parseHotkey(shown, options.platform));
} catch {
return false;
}
return getHotkeyManager().hasActiveRegistration(explicit, isAppHotkey(hotkey) ? hotkey : void 0);
}
/**
* Returns `format`, such as `formatForDisplay` or `formatForAria`, with a
* provider's platform and keyboard layout used when the call doesn't pass
* them. Only a hotkey that names a physical key reads `getLayoutMap`, so
* other hotkeys don't depend on the layout.
*
* @example
* ```ts
* const format = createFormatter(formatForAria, () => provider.platform, () => layoutMap)
* ```
*/
function createFormatter(format, getPlatform, getLayoutMap) {
return ((hotkey, options) => format(hotkey, {
...options,
platform: options?.platform ?? getPlatform(),
layoutMap: options?.layoutMap ?? (hotkey && namesPhysicalKey(hotkey) ? getLayoutMap() ?? void 0 : void 0)
}));
}
/**
* Wraps an ARIA formatter so it returns `undefined` for a hotkey that can't
* fire, so screen readers announce only working shortcuts. A hotkey counts
* when any enabled registration in an active scope announces the same keys,
* so a disabled control's shortcut is still announced while another
* registration uses it. Suspended character keys and hotkeys nothing has
* registered aren't announced. Focus isn't checked, because the attribute
* sits on the control the shortcut acts on. Read the adapter's registrations
* reactively in `getRegistrations`, so the value updates when they change.
*/
function announceLiveHotkeys(format, getRegistrations) {
return (hotkey, options) => {
const value = format(hotkey, options);
if (value === void 0) return void 0;
const registrations = getRegistrations();
const live = value.split(" ").filter((shortcut) => registrations.some((registration) => registration.status === "active" && format(registration.hotkey, {
...options,
platform: registration.options.platform
}) === shortcut));
return live.length > 0 ? live.join(" ") : void 0;
};
}
/**
* A `formatForDisplay` that uses a provider's platform and keyboard layout
* when the call doesn't pass them. Same as
* `createFormatter(formatForDisplay, getPlatform, getLayoutMap)`.
*/
function createFormatForDisplay(getPlatform, getLayoutMap) {
return createFormatter(formatForDisplay, getPlatform, getLayoutMap);
}
/**
* 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, announceLiveHotkeys, bindCustomHotkeyActions, canHintedHotkeyFire, createAppHotkeysStore, createFormatForDisplay, createFormatter, createHotkeyBindings, createStore, definedOptions, followKeyboardLayout, getHotkeyRegistrationViews, getHotkeysProviderScopeKey, getPublishedAppHotkeysStore, getServerPlatformSnapshot, installAppHotkeysStore, isHotkeyHintVisible, mergeHotkeysProviderDefaults, namesPhysicalKey, prepareHotkeyDefinitions, requireAppHotkeysStore, resolveMaybeGetter, resolveRefTarget, subscribePublishedAppHotkeys, syncRecorderOptions, withDefaults };