UNPKG

@rwh/keystrokes

Version:

Keystrokes is an easy to use library for binding functions to keys and key combos. It can be used with any TypeScript or JavaScript project, even in non-browser environments.

435 lines (434 loc) • 15 kB
// src/browser-bindings.ts var e = { addEventListener: (...e) => {}, removeEventListener: (...e) => {}, dispatchEvent: (...e) => {} }, t = { userAgent: "" }, n = () => typeof document < "u" ? document : e, r = () => typeof navigator < "u" ? navigator : t, i = () => r().userAgent.toLowerCase().includes("mac"), a = !1, o = (e) => { i() && e.key === "Meta" && (a = !0); }, s = (e) => { a && e.key === "Meta" && (a = !1, p()); }, c = [ "Meta", "Shift", "Control", "Alt", "CapsLock", "Tab" ], l = (e) => { a && !c.includes(e.key) && (f(e), n().dispatchEvent(new KeyboardEvent("keyup", { key: e.key, code: e.code, bubbles: !0, cancelable: !0 }))); }, u = /* @__PURE__ */ new Map(), d = (e) => { u.set(e.key, e); }, f = (e) => { u.delete(e.key); }, p = () => { for (let e of u.values()) { let t = new KeyboardEvent("keyup", { key: e.key, code: e.code, bubbles: !0, cancelable: !0 }); n().dispatchEvent(t); } u.clear(); }, m = (e) => { try { let t = () => e(); return addEventListener("focus", t), () => { removeEventListener("focus", t); }; } catch {} }, h = (e) => { try { let t = () => { p(), e(); }; return addEventListener("blur", t), () => removeEventListener("blur", t); } catch {} }, g = (e) => { try { let t = (t) => { t.key && (d(t), o(t), e({ key: t.key, aliases: [`@${t.code}`], originalEvent: t, composedPath: () => t.composedPath(), preventDefault: () => t.preventDefault() }), l(t)); }; return n().addEventListener("keydown", t), () => n().removeEventListener("keydown", t); } catch {} }, _ = (e) => { try { let t = (t) => { t.key && (f(t), s(t), e({ key: t.key, aliases: [`@${t.code}`], originalEvent: t, composedPath: () => t.composedPath(), preventDefault: () => t.preventDefault() })); }; return n().addEventListener("keyup", t), () => n().removeEventListener("keyup", t); } catch {} }, v = class { _onPressed; _onPressedWithRepeat; _onReleased; _isPressed; _identity; constructor(e) { this._isPressed = !1, this._identity = e, typeof e == "function" ? this._onPressedWithRepeat = e : (this._onPressed = e.onPressed, this._onPressedWithRepeat = e.onPressedWithRepeat, this._onReleased = e.onReleased); } get isEmpty() { return !this._onPressed && !this._onPressedWithRepeat && !this._onReleased; } isOwnHandler(e) { return this._identity === e; } executePressed(e) { this._isPressed || this._onPressed?.(e), this._isPressed = !0, this._onPressedWithRepeat?.(e); } executeReleased(e) { this._isPressed && this._onReleased?.(e), this._isPressed = !1; } }, y = class e { static _parseCache = {}; static _normalizationCache = {}; static parseKeyCombo(t) { if (e._parseCache[t]) return e._parseCache[t]; let n = t.toLowerCase(), r = "", i = [], a = [i], o = [a], s = [o], c = !1; for (let e = 0; e < t.length; e += 1) if (n[e] === "\\") c = !0; else if ((n[e] === "+" || n[e] === ">" || n[e] === ",") && !c) { if (r) throw Error("cannot have two operators in a row"); r = n[e]; } else n[e].match(/[^\s]/) && (r &&= (r === "," ? (i = [], a = [i], o = [a], s.push(o)) : r === ">" ? (i = [], a = [i], o.push(a)) : r === "+" && (i = [], a.push(i)), ""), c = !1, i.push(n[e])); let l = s.map((e) => e.map((e) => e.map((e) => e.join("")))); return e._parseCache[t] = l, l; } static stringifyKeyCombo(e) { return e.map((e) => e.map((e) => e.map((e) => e === "+" ? "\\+" : e === ">" ? "\\>" : e === "," ? "\\," : e).join("+")).join(">")).join(","); } static normalizeKeyCombo(t) { if (e._normalizationCache[t]) return e._normalizationCache[t]; let n = this.stringifyKeyCombo(this.parseKeyCombo(t)); return e._normalizationCache[t] = n, n; } get isPressed() { return !!this._isPressedWithFinalUnit; } get sequenceIndex() { return this.isPressed ? this._parsedKeyCombo.length : this._sequenceIndex; } get sequenceLength() { return this._parsedKeyCombo.length; } get isNewlyPressed() { return this._isNewlyPressed; } get hasAdvancedSequence() { return this._hasAdvancedSequence; } _normalizedKeyCombo; _parsedKeyCombo; _handlerState; _keyComboEventMapper; _movingToNextSequenceAt; _sequenceIndex; _unitIndex; _lastActiveKeyPresses; _lastActiveKeyCount; _isPressedWithFinalUnit; _isNewlyPressed; _hasAdvancedSequence; _isSuppressed; constructor(t, n, r = {}) { this._normalizedKeyCombo = e.normalizeKeyCombo(t), this._parsedKeyCombo = e.parseKeyCombo(t), this._handlerState = new v(r), this._keyComboEventMapper = n, this._movingToNextSequenceAt = 0, this._sequenceIndex = 0, this._unitIndex = 0, this._lastActiveKeyPresses = [], this._lastActiveKeyCount = 0, this._isPressedWithFinalUnit = null, this._isNewlyPressed = !1, this._hasAdvancedSequence = !1, this._isSuppressed = !1; } isOwnHandler(e) { return this._handlerState.isOwnHandler(e); } suppress() { this._isSuppressed = !0; } executePressed(e) { this._isSuppressed || (this._isPressedWithFinalUnit?.has(e.key) || e.aliases?.some((e) => this._isPressedWithFinalUnit?.has(e))) && this._handlerState.executePressed(this._wrapEvent(this._lastActiveKeyPresses, { key: e.key, aliases: new Set(e.aliases), event: e })); } executeReleased(e) { (this._isPressedWithFinalUnit?.has(e.key) || e.aliases?.some((e) => this._isPressedWithFinalUnit?.has(e))) && (this._handlerState.executeReleased(this._wrapEvent(this._lastActiveKeyPresses, { key: e.key, aliases: new Set(e.aliases), event: e })), this._isPressedWithFinalUnit = null, this._isSuppressed = !1); } updateState(e, t) { let n = e.length, r = n < this._lastActiveKeyCount; this._lastActiveKeyCount = n; let i = this._sequenceIndex > 0 || this._movingToNextSequenceAt !== 0; this._isNewlyPressed = !1, this._hasAdvancedSequence = !1; let a = this._parsedKeyCombo[this._sequenceIndex], o = a.slice(0, this._unitIndex), s = a.slice(this._unitIndex), c = () => { this._movingToNextSequenceAt = 0, this._sequenceIndex = 0, this._unitIndex = 0, this._lastActiveKeyPresses.length = 0, this._hasAdvancedSequence = !1, this._handlerState.isEmpty && (this._isPressedWithFinalUnit = null); }, l = 0; if (r) { if (this._movingToNextSequenceAt === 0 || this._movingToNextSequenceAt + t < Date.now()) return c(); if (n !== 0) return; this._movingToNextSequenceAt = 0, this._sequenceIndex += 1, this._unitIndex = 0; } else { for (let t of o) { for (let n of t) { let r = !1; for (let i = l; i < e.length && i < l + t.length; i += 1) if (e[i].key === n || e[i].aliases.has(n)) { r = !0; break; } if (!r) return c(); } l += t.length; } if (this._movingToNextSequenceAt === 0) { for (let t of s) { for (let n of t) { let r = !1; for (let i = l; i < e.length && i < l + t.length; i += 1) if (e[i].key === n || e[i].aliases.has(n)) { r = !0; break; } if (!r) return; } this._unitIndex += 1, l += t.length, i && (this._hasAdvancedSequence = !0); } if (l < n - 1) return c(); this._lastActiveKeyPresses[this._sequenceIndex] = e.slice(0), this._sequenceIndex < this._parsedKeyCombo.length - 1 ? this._movingToNextSequenceAt = Date.now() : (this._isNewlyPressed = !this._isPressedWithFinalUnit, this._isPressedWithFinalUnit = new Set(a[a.length - 1])); } } } _wrapEvent(e, t) { return { ...this._keyComboEventMapper(e, t), keyCombo: this._normalizedKeyCombo, keyEvents: e.flat().map((e) => e.event), finalKeyEvent: t.event }; } }, b = 1e3, x = class { sequenceTimeout; _isActive; _unbinder; _onActiveBinder; _onInactiveBinder; _onKeyPressedBinder; _onKeyReleasedBinder; _keyComboEventMapper; _selfReleasingKeys; _keyRemap; _handlerStates; _keyComboStates; _keyComboStatesArray; _activeKeyPresses; _activeKeyMap; _watchedKeyComboStates; constructor(e = {}) { this.sequenceTimeout = b, this._isActive = !0, this._onActiveBinder = () => {}, this._onInactiveBinder = () => {}, this._onKeyPressedBinder = () => {}, this._onKeyReleasedBinder = () => {}, this._keyComboEventMapper = () => ({}), this._selfReleasingKeys = [], this._keyRemap = {}, this._handlerStates = {}, this._keyComboStates = {}, this._keyComboStatesArray = [], this._activeKeyPresses = [], this._activeKeyMap = /* @__PURE__ */ new Map(), this._watchedKeyComboStates = {}, this.bindEnvironment(e); } get pressedKeys() { return this._activeKeyPresses.map((e) => e.key); } bindKey(e, t) { if (typeof e == "object") { for (let n of e) this.bindKey(n, t); return; } e = e.toLowerCase(); let n = new v(t); this._handlerStates[e] ??= [], this._handlerStates[e].push(n); } unbindKey(e, t) { if (typeof e == "object") { for (let n of e) this.unbindKey(n, t); return; } e = e.toLowerCase(); let n = this._handlerStates[e]; if (n) { if (t) for (let e = 0; e < n.length; e += 1) n[e].isOwnHandler(t) && (n.splice(e, 1), --e); else n.length = 0; } } bindKeyCombo(e, t) { if (typeof e == "object") { for (let n of e) this.bindKeyCombo(n, t); return; } e = y.normalizeKeyCombo(e); let n = new y(e, this._keyComboEventMapper, t); this._keyComboStates[e] ??= [], this._keyComboStates[e].push(n), this._keyComboStatesArray.push(n); } unbindKeyCombo(e, t) { if (typeof e == "object") { for (let n of e) this.unbindKeyCombo(n, t); return; } e = y.normalizeKeyCombo(e); let n = this._keyComboStates[e]; if (n) { for (let e = 0; e < n.length; e += 1) if (!t || n[e].isOwnHandler(t)) { for (let t = 0; t < this._keyComboStatesArray.length; t += 1) this._keyComboStatesArray[t] === n[e] && (this._keyComboStatesArray.splice(t, 1), --t); n.splice(e, 1), --e; } } } checkKey(e) { return e = e.toLowerCase(), this._activeKeyPresses.some((t) => t.key === e || t.aliases.has(e)); } checkKeyCombo(e) { return this._ensureCachedKeyComboState(e).isPressed; } checkKeyComboSequenceIndex(e) { return this._ensureCachedKeyComboState(e).sequenceIndex; } bindEnvironment(e = {}) { this.unbindEnvironment(), this._onActiveBinder = e.onActive ?? m, this._onInactiveBinder = e.onInactive ?? h, this._onKeyPressedBinder = e.onKeyPressed ?? g, this._onKeyReleasedBinder = e.onKeyReleased ?? _, this._keyComboEventMapper = e.mapKeyComboEvent ?? (() => ({})), this._selfReleasingKeys = e.selfReleasingKeys ?? [], this._keyRemap = e.keyRemap ?? {}; let t = this._onActiveBinder(() => { this._isActive = !0; }), n = this._onInactiveBinder(() => { this._isActive = !1; }), r = this._onKeyPressedBinder((e) => { this._handleKeyPress(e); }), i = this._onKeyReleasedBinder((e) => { this._handleKeyRelease(e); }); this._unbinder = () => { t?.(), n?.(), r?.(), i?.(); }; } unbindEnvironment() { this._unbinder?.(); } _ensureCachedKeyComboState(e) { e = y.normalizeKeyCombo(e), this._watchedKeyComboStates[e] || (this._watchedKeyComboStates[e] = new y(e, this._keyComboEventMapper)); let t = this._watchedKeyComboStates[e]; return t.updateState(this._activeKeyPresses, this.sequenceTimeout), t; } _handleKeyPress(e) { if (!this._isActive) return; e = { ...e, key: e.key.toLowerCase(), aliases: e.aliases?.map((e) => e.toLowerCase()) ?? [] }; let t = this._keyRemap[e.key]; t && (e.key = t); for (let t = 0; t < e.aliases.length; t += 1) { let n = this._keyRemap[e.aliases[t]]; n && (e.aliases[t] = n); } let n = this._handlerStates[e.key]; if (n) for (let t of n) t.executePressed(e); for (let t = 0; t < e.aliases.length; t += 1) { let n = this._handlerStates[e.aliases[t]]; if (n) for (let t of n) t.executePressed(e); } let r = this._activeKeyMap.get(e.key); if (r) r.event = e; else { let t = { key: e.key, aliases: new Set(e.aliases), event: e }; this._activeKeyMap.set(e.key, t), this._activeKeyPresses.push(t); } this._updateKeyComboStates(), this._suppressOverlappedKeyCombos(); for (let t of this._keyComboStatesArray) t.executePressed(e); } _handleKeyRelease(e) { e = { ...e, key: e.key.toLowerCase(), aliases: e.aliases?.map((e) => e.toLowerCase()) ?? [] }; let t = this._keyRemap[e.key]; if (t && (e.key = t), e.aliases) for (let t = 0; t < e.aliases.length; t += 1) { let n = this._keyRemap[e.aliases[t]]; n && (e.aliases[t] = n); } let n = this._handlerStates[e.key]; if (n) for (let t of n) t.executeReleased(e); for (let t = 0; t < e.aliases.length; t += 1) { let n = this._handlerStates[e.aliases[t]]; if (n) for (let t of n) t.executeReleased(e); } if (this._activeKeyMap.has(e.key)) { this._activeKeyMap.delete(e.key); for (let t = 0; t < this._activeKeyPresses.length; t += 1) if (this._activeKeyPresses[t].key === e.key) { this._activeKeyPresses.splice(t, 1); break; } } this._tryReleaseSelfReleasingKeys(), this._updateKeyComboStates(); for (let t of this._keyComboStatesArray) t.executeReleased(e); } _updateKeyComboStates() { for (let e of this._keyComboStatesArray) e.updateState(this._activeKeyPresses, this.sequenceTimeout); } _suppressOverlappedKeyCombos() { let e = !1, t = 0; for (let n of this._keyComboStatesArray) n.hasAdvancedSequence && (e = !0, n.isPressed && n.sequenceLength > t && (t = n.sequenceLength)); if (e) for (let e of this._keyComboStatesArray) e.isNewlyPressed && (e.hasAdvancedSequence && e.sequenceLength === t || e.suppress()); } _tryReleaseSelfReleasingKeys() { for (let e of this._activeKeyPresses) for (let t of this._selfReleasingKeys) e.key === t && this._handleKeyRelease(e.event); } }, S, C, w = (e) => { C = e ?? new x(S); }, T = () => (C || w(), C), E = (e) => { S = e; }, D = (...e) => T().bindKey(...e), O = (...e) => T().unbindKey(...e), k = (...e) => T().bindKeyCombo(...e), A = (...e) => T().unbindKeyCombo(...e), j = (...e) => T().checkKey(...e), M = (...e) => T().checkKeyCombo(...e), N = y.normalizeKeyCombo, P = y.stringifyKeyCombo, F = y.parseKeyCombo, I = (e = {}) => { let t, n, r, i; return Object.assign(new x({ ...e, onActive(e) { t = e; }, onInactive(e) { n = e; }, onKeyPressed(e) { r = e; }, onKeyReleased(e) { i = e; } }), { activate() { t(); }, deactivate() { n(); }, press(e) { r({ composedPath: () => [], preventDefault: () => {}, ...e }); }, release(e) { i({ composedPath: () => [], preventDefault: () => {}, ...e }); } }); }; export { v as HandlerState, y as KeyComboState, x as Keystrokes, D as bindKey, k as bindKeyCombo, m as browserOnActiveBinder, h as browserOnInactiveBinder, g as browserOnKeyPressedBinder, _ as browserOnKeyReleasedBinder, j as checkKey, M as checkKeyCombo, I as createTestKeystrokes, b as defaultSequenceTimeout, T as getGlobalKeystrokes, N as normalizeKeyCombo, F as parseKeyCombo, w as setGlobalKeystrokes, E as setGlobalKeystrokesOptions, P as stringifyKeyCombo, O as unbindKey, A as unbindKeyCombo };