Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
import utils from "./utils.js";
type ElementType = HTMLElement | Document;
export type Handler = (e: KeyboardEvent) => void;
export interface ShortcutBinding {
element: HTMLElement | Document;
shortcut: string;
handler: Handler;
namespace: string | null;
listener: (evt: Event) => void;
}
// Store all active shortcut bindings for management
const activeBindings: Map<string, ShortcutBinding[]> = new Map();
// Handle special key mappings and aliases
const keyMap: { [key: string]: string[] } = {
'return': ['Enter'],
'enter': ['Enter'], // alias for return
'del': ['Delete'],
'delete': ['Delete'], // alias for del
'esc': ['Escape'],
'escape': ['Escape'], // alias for esc
'space': [' ', 'Space'],
'tab': ['Tab'],
'backspace': ['Backspace'],
'home': ['Home'],
'end': ['End'],
'pageup': ['PageUp'],
'pagedown': ['PageDown'],
'up': ['ArrowUp'],
'down': ['ArrowDown'],
'left': ['ArrowLeft'],
'right': ['ArrowRight'],
// "+" doubles as the shortcut separator, so the plus key is referred to by the named "plus" token
// (e.g. "Ctrl+Plus"). Matches any key that produces "+": the dedicated key on QWERTZ/AZERTY
// layouts, Shift+"=" on US layouts, and the numpad "+".
'plus': ['+']
};
// Function keys
const functionKeyCodes: string[] = [];
for (let i = 1; i <= 19; i++) {
const keyCode = `F${i}`;
functionKeyCodes.push(keyCode);
keyMap[`f${i}`] = [ keyCode ];
}
// Key codes (e.g. function keys, Delete, Enter) that are allowed as shortcuts without a modifier.
export const KEYCODES_WITH_NO_MODIFIER = new Set([
"Delete",
"Enter",
"NumpadEnter",
...functionKeyCodes
]);
/**
* Whether a keystroke carries an application-level modifier, and so belongs to Trilium's own shortcuts
* rather than to whichever widget holds focus. A widget that binds bare keys has to stand aside for these:
* global shortcuts are bound on `document` in the bubble phase and don't check `defaultPrevented`, so a
* widget acting on a modified key either swallows the app shortcut (if it stops propagation) or fires
* alongside it. Shift is deliberately not one of them — it modifies a widget's own key (the image viewer
* pans faster with it held) and no shortcut is Shift-only.
*
* A widget may still claim a specific chord where the modifier *is* its gesture (Ctrl+= zooms the focused
* image rather than the whole UI); those are exceptions the widget states for itself.
*/
export function isAppShortcutChord(e: { ctrlKey: boolean; metaKey: boolean; altKey: boolean }): boolean {
return e.ctrlKey || e.metaKey || e.altKey;
}
/**
* Check if IME (Input Method Editor) is composing
* This is used to prevent keyboard shortcuts from firing during IME composition
* @param e - The keyboard event to check
* @returns true if IME is currently composing, false otherwise
*/
export function isIMEComposing(e: KeyboardEvent): boolean {
// Handle null/undefined events gracefully
if (!e) {
return false;
}
// Standard check for composition state
// e.isComposing is true when IME is actively composing
// e.keyCode === 229 is a fallback for older browsers where 229 indicates IME processing
return e.isComposing || e.keyCode === 229;
}
function removeGlobalShortcut(namespace: string) {
bindGlobalShortcut("", null, namespace);
}
function bindGlobalShortcut(keyboardShortcut: string, handler: Handler | null, namespace: string | null = null) {
bindElShortcut($(document), keyboardShortcut, handler, namespace);
}
function bindElShortcut($el: JQuery<ElementType | Element>, keyboardShortcut: string, handler: Handler | null, namespace: string | null = null) {
if (utils.isDesktop()) {
keyboardShortcut = normalizeShortcut(keyboardShortcut);
// If namespace is provided, remove all previous bindings for this namespace
if (namespace) {
removeNamespaceBindings(namespace);
}
// Method can be called to remove the shortcut (e.g. when keyboardShortcut label is deleted)
if (keyboardShortcut && handler) {
const element = $el.length > 0 ? $el[0] as (HTMLElement | Document) : document;
const listener = (evt: Event) => {
// Only handle keyboard events
if (evt.type !== 'keydown' || !(evt instanceof KeyboardEvent)) {
return;
}
const e = evt as KeyboardEvent;
// Skip processing if IME is composing to prevent shortcuts from
// interfering with text input in CJK languages
if (isIMEComposing(e)) {
return;
}
if (matchesShortcut(e, keyboardShortcut)) {
e.preventDefault();
e.stopPropagation();
handler(e);
}
};
// Add the event listener
element.addEventListener('keydown', listener);
// Store the binding for later cleanup
const binding: ShortcutBinding = {
element,
shortcut: keyboardShortcut,
handler,
namespace,
listener
};
const key = namespace || 'global';
if (!activeBindings.has(key)) {
activeBindings.set(key, []);
}
activeBindings.get(key)!.push(binding);
return binding;
}
}
}
export function removeIndividualBinding(binding: ShortcutBinding) {
const key = binding.namespace ?? "global";
const activeBindingsInNamespace = activeBindings.get(key);
if (activeBindingsInNamespace) {
activeBindings.set(key, activeBindingsInNamespace.filter(aBinding => aBinding !== binding));
}
binding.element.removeEventListener("keydown", binding.listener);
}
function removeNamespaceBindings(namespace: string) {
const bindings = activeBindings.get(namespace);
if (bindings) {
// Remove all event listeners for this namespace
bindings.forEach(binding => {
binding.element.removeEventListener('keydown', binding.listener);
});
activeBindings.delete(namespace);
}
}
export function matchesShortcut(e: KeyboardEvent, shortcut: string): boolean {
if (!shortcut) return false;
// Ensure we have a proper KeyboardEvent with key property
if (!e || typeof e.key !== 'string') {
console.warn('matchesShortcut called with invalid event:', e);
return false;
}
const { modifiers, key } = splitShortcut(shortcut);
// Defensive check - ensure we have a valid key
if (!key || key.trim() === '') {
console.warn('Invalid shortcut format:', shortcut);
return false;
}
// Check if the main key matches
if (!keyMatches(e, key)) {
return false;
}
// Check modifiers
const expectedCtrl = modifiers.includes('ctrl') || modifiers.includes('control');
const expectedAlt = modifiers.includes('alt');
const expectedShift = modifiers.includes('shift');
const expectedMeta = modifiers.includes('meta') || modifiers.includes('cmd') || modifiers.includes('command');
// Refuse key combinations that don't include modifiers because they interfere with the normal usage of the application.
// Some keys such as function keys are an exception.
if (!(expectedCtrl || expectedAlt || expectedShift || expectedMeta) && !KEYCODES_WITH_NO_MODIFIER.has(e.code)) {
return false;
}
return e.ctrlKey === expectedCtrl &&
e.altKey === expectedAlt &&
e.shiftKey === expectedShift &&
e.metaKey === expectedMeta;
}
export function keyMatches(e: KeyboardEvent, key: string): boolean {
// Defensive check for undefined/null key
if (!key) {
console.warn('keyMatches called with undefined/null key');
return false;
}
const mappedKeys = keyMap[key.toLowerCase()];
if (mappedKeys) {
return mappedKeys.includes(e.key) || mappedKeys.includes(e.code);
}
// For number keys, use the physical key code regardless of modifiers
// This works across all keyboard layouts
if (key >= '0' && key <= '9') {
return e.code === `Digit${key}`;
}
// For letter keys, use the physical key code for consistency
// On macOS, Option/Alt key produces special characters, so we must use e.code
if (key.length === 1 && key >= 'a' && key <= 'z') {
if (e.altKey) {
// e.code is like "KeyA", "KeyB", etc.
const expectedCode = `Key${key.toUpperCase()}`;
return e.code === expectedCode || e.key.toLowerCase() === key.toLowerCase();
}
return e.key.toLowerCase() === key.toLowerCase() || matchesUsPhysicalKey(e, key);
}
// For regular keys, check both key and code as fallback
return e.key.toLowerCase() === key.toLowerCase() ||
e.code.toLowerCase() === key.toLowerCase() ||
matchesUsPhysicalKey(e, key);
}
// `KeyboardEvent.code` of the US QWERTY key that produces each punctuation character.
const usPunctuationCodes: Record<string, string> = {
"-": "Minus",
"=": "Equal",
"[": "BracketLeft",
"]": "BracketRight",
"\\": "Backslash",
";": "Semicolon",
"'": "Quote",
",": "Comma",
".": "Period",
"/": "Slash",
"`": "Backquote"
};
// A letter outside the Latin script, such as Cyrillic, Greek or Hebrew.
const NON_LATIN_LETTER = /^(?=\p{L}$)(?![\p{Script=Latin}\p{Script=Common}])/u;
/**
* Matches a key that types a non-Latin letter by its position on US QWERTY, since such a layout
* cannot type the shortcut's character at all. Every other key is left to `e.key`, so AZERTY's
* Ctrl+Z stays on the key labeled Z and French `ù` or German `ö` don't stand in for punctuation.
*/
function matchesUsPhysicalKey(e: KeyboardEvent, key: string): boolean {
if (!NON_LATIN_LETTER.test(e.key)) {
return false;
}
const expectedCode = key.length === 1 && key >= "a" && key <= "z"
? `Key${key.toUpperCase()}`
: usPunctuationCodes[key];
return expectedCode !== undefined && e.code === expectedCode;
}
/**
* Reduces a shortcut string to a canonical form so that two shortcuts that fire on the *same*
* physical key combination compare equal, mirroring the runtime semantics of {@link matchesShortcut}:
* - modifiers are compared as an unordered set (so `Ctrl+Shift+J` === `Shift+Ctrl+J`),
* - modifier aliases collapse (`Control`→`ctrl`, `Cmd`/`Command`→`meta`),
* - the final key is mapped through {@link keyMap} so aliases collapse (`Del`===`Delete`, `Enter`===`Return`).
*
* Intended for conflict detection in the settings UI, not for binding.
*/
export function canonicalizeShortcut(shortcut: string): string {
const { modifiers: rawModifiers, key: rawKey } = splitShortcut(shortcut);
if (!rawKey) {
return "";
}
const modifiers = new Set<string>();
for (const modifier of rawModifiers) {
if (modifier === "ctrl" || modifier === "control") modifiers.add("ctrl");
else if (modifier === "meta" || modifier === "cmd" || modifier === "command") modifiers.add("meta");
else if (modifier === "alt" || modifier === "shift") modifiers.add(modifier);
else if (modifier) modifiers.add(modifier);
}
// Collapse key aliases (e.g. "del" and "delete" both resolve to the same canonical token, and
// the named "plus" token resolves to the raw "+" key).
const canonicalKey = keyMap[rawKey]?.[0]?.toLowerCase() ?? rawKey;
return [ ...[ ...modifiers ].sort(), canonicalKey ].join("+");
}
/**
* Splits a shortcut string into its modifier list and final key, returning both lowercased and
* trimmed. Handles the one key that collides with the "+" separator: the plus key is encoded either
* as a lone "+" (no modifiers) or as a trailing "++" (e.g. "Ctrl++"), both of which yield a key of
* "+". Aliases like the named "plus" token are left untouched here and collapsed by the callers via
* {@link keyMap}.
*/
function splitShortcut(shortcut: string): { modifiers: string[]; key: string } {
const lower = (shortcut ?? "").toLowerCase().trim();
// A trailing "+" (the whole string is "+", or it ends in "++") denotes the plus key, since a key
// is always the final token and "+" is otherwise the separator.
if (lower === "+" || lower.endsWith("++")) {
const modifiers = lower.slice(0, -1).split("+").map((p) => p.trim()).filter(Boolean);
return { modifiers, key: "+" };
}
const parts = lower.split("+").map((p) => p.trim());
return { modifiers: parts.slice(0, -1), key: parts[parts.length - 1] };
}
/**
* Simple normalization - just lowercase and trim whitespace
*/
function normalizeShortcut(shortcut: string): string {
if (!shortcut) {
return shortcut;
}
const normalized = shortcut.toLowerCase().trim().replace(/\s+/g, '');
// Warn about potentially problematic shortcuts: a missing key (e.g. "ctrl+") or an empty modifier
// (e.g. "+a" or the double-separator "ctrl++a"). A genuine plus-key binding like "ctrl++" parses
// to a "+" key with no empty modifiers and is left alone.
const { modifiers, key } = splitShortcut(normalized);
if (!key || modifiers.some((modifier) => !modifier)) {
console.warn('Potentially malformed shortcut:', shortcut, '-> normalized to:', normalized);
}
return normalized;
}
export default {
bindGlobalShortcut,
bindElShortcut,
removeGlobalShortcut,
normalizeShortcut
};