@tanstack/hotkeys
Version:
Type-safe, framework-agnostic keyboard hotkey management for the browser
41 lines (39 loc) • 2.12 kB
JavaScript
import { hotkeySteps } from "./_chord.js";
import { getTargetDocument } from "./_event-target.js";
import { managerRef } from "./_manager-ref.js";
import { stepsOverlap } from "./_steps.js";
import { toHotkeyRegistrationView } from "./hotkey-manager.js";
import { parseHotkey } from "./parse.js";
import { detectPlatform } from "./platform.js";
// src/conflicts.ts
/** Whether two targets share a document and one contains the other (or is its window). */
function targetsOverlap(a, b) {
if (a === b) return true;
if (getTargetDocument(a) !== getTargetDocument(b)) return false;
if (!("contains" in a) || !("contains" in b)) return true;
return a.contains(b) || b.contains(a);
}
/**
* Find equivalent bindings and sequence-prefix conflicts in the live registry.
* With source events, also checks observed logical/physical overlap. Does not
* discover unmounted handlers, external listeners, or other keyboard layouts.
*/
function findHotkeyConflicts(candidate, options = {}) {
const steps = hotkeySteps(candidate);
if (steps.length === 0) return [];
const platform = options.platform ?? detectPlatform();
for (const step of steps) parseHotkey(step, platform);
const target = options.target ?? (typeof document === "undefined" ? void 0 : document);
const conflicts = [];
const matches = (registration, bindings) => {
if (!options.includeDisabled && registration.options.enabled === false || (registration.options.eventType ?? "keydown") !== (options.eventType ?? "keydown") || options.excludeIds?.includes(registration.id) || options.exclude?.(registration) || options.scope !== "all" && target && !targetsOverlap(target, registration.target)) return false;
return stepsOverlap(steps, bindings, [platform, registration.options.platform ?? detectPlatform()], options.events);
};
const registrations = managerRef.current?.registrations.state.values() ?? [];
for (const registration of registrations) {
const view = toHotkeyRegistrationView(registration);
if (matches(view, hotkeySteps(view.hotkey))) conflicts.push({ registration: view });
}
return conflicts;
}
export { findHotkeyConflicts };