export type Scope = "global" | "dialog" | "input"; export type KeyLike = { key: string; metaKey?: boolean; ctrlKey?: boolean; altKey?: boolean; shiftKey?: boolean; isComposing?: boolean; }; export type Binding = { id: string; title: string; combo: string; scope: Scope; enabled: boolean; }; export type Context = "app" | "dialog" | "input"; export function normalizeKey(key: string): string { if (key === " ") return "space"; if (key.length === 1) return key.toLowerCase(); return key.toLowerCase(); } export function normalizeCombo(input: KeyLike): string { const parts: string[] = []; if (input.metaKey) parts.push("meta"); if (input.ctrlKey) parts.push("ctrl"); if (input.altKey) parts.push("alt"); if (input.shiftKey) parts.push("shift"); parts.push(normalizeKey(input.key)); return parts.join("+"); } export function formatCombo(combo: string): string { return combo .split("+") .map((part) => { if (part === "meta") return "⌘"; if (part === "ctrl") return "Ctrl"; if (part === "alt") return "⌥"; if (part === "shift") return "⇧"; if (part === "escape") return "Esc"; if (part === "arrowup") return "↑"; if (part === "arrowdown") return "↓"; return part.length === 1 ? part.toUpperCase() : part; }) .join(" "); } export function findBinding( bindings: Binding[], combo: string, context: Context, ): Binding | undefined { return bindings.find( (binding) => binding.enabled && binding.combo === combo && (binding.scope === "global" || binding.scope === context), ); } export type Conflict = { combo: string; scope: Scope; ids: string[] }; export function findConflicts(bindings: Binding[]): Conflict[] { const groups = new Map(); for (const binding of bindings) { if (!binding.enabled || binding.scope === "dialog") continue; const key = `${binding.scope}:${binding.combo}`; const list = groups.get(key) ?? []; list.push(binding); groups.set(key, list); } const conflicts: Conflict[] = []; for (const list of groups.values()) { if (list.length > 1) { const first = list[0]; if (!first) continue; conflicts.push({ combo: first.combo, scope: first.scope, ids: list.map((binding) => binding.id), }); } } return conflicts; } export function allowsInInput(combo: string): boolean { return ( combo === "escape" || combo === "tab" || combo.startsWith("meta+") || combo.startsWith("ctrl+") || combo.startsWith("alt+") ); } export function isEditable(target: EventTarget | null): boolean { if (!(target instanceof HTMLElement)) return false; if (target.isContentEditable) return true; if (target instanceof HTMLInputElement) { return !["button", "checkbox", "radio", "submit"].includes(target.type); } return target instanceof HTMLTextAreaElement; }