You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hotkeys/dist/hotkeys.esm.js

588 lines
17 KiB
JavaScript

3 years ago
/**!
* hotkeys-js v3.13.1
3 years ago
* A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
7 years ago
*
* Copyright (c) 2023 kenny wong <wowohoo@qq.com>
* https://github.com/jaywcjlove/hotkeys-js.git
*
* @website: https://jaywcjlove.github.io/hotkeys-js
3 years ago
* Licensed under the MIT license
7 years ago
*/
const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false;
7 years ago
// 绑定事件
function addEvent(object, event, method, useCapture) {
7 years ago
if (object.addEventListener) {
object.addEventListener(event, method, useCapture);
7 years ago
} else if (object.attachEvent) {
object.attachEvent("on".concat(event), () => {
7 years ago
method(window.event);
});
7 years ago
}
}
7 years ago
// 修饰键转换成对应的键码
7 years ago
function getMods(modifier, key) {
const mods = key.slice(0, key.length - 1);
for (let i = 0; i < mods.length; i++) mods[i] = modifier[mods[i].toLowerCase()];
6 years ago
return mods;
}
7 years ago
// 处理传的key字符串转换成数组
7 years ago
function getKeys(key) {
6 years ago
if (typeof key !== 'string') key = '';
7 years ago
key = key.replace(/\s/g, ''); // 匹配任何空白字符,包括空格、制表符、换页符等等
const keys = key.split(','); // 同时设置多个快捷键,以','分割
let index = keys.lastIndexOf('');
7 years ago
// 快捷键可能包含',',需特殊处理
7 years ago
for (; index >= 0;) {
keys[index - 1] += ',';
keys.splice(index, 1);
index = keys.lastIndexOf('');
}
return keys;
}
7 years ago
// 比较修饰键的数组
7 years ago
function compareArray(a1, a2) {
const arr1 = a1.length >= a2.length ? a1 : a2;
const arr2 = a1.length >= a2.length ? a2 : a1;
let isIndex = true;
for (let i = 0; i < arr1.length; i++) {
7 years ago
if (arr2.indexOf(arr1[i]) === -1) isIndex = false;
7 years ago
}
7 years ago
return isIndex;
7 years ago
}
// Special Keys
const _keyMap = {
7 years ago
backspace: 8,
'⌫': 8,
7 years ago
tab: 9,
clear: 12,
enter: 13,
'↩': 13,
4 years ago
return: 13,
7 years ago
esc: 27,
escape: 27,
space: 32,
left: 37,
up: 38,
right: 39,
down: 40,
del: 46,
4 years ago
delete: 46,
7 years ago
ins: 45,
insert: 45,
home: 36,
end: 35,
pageup: 33,
pagedown: 34,
capslock: 20,
4 years ago
num_0: 96,
num_1: 97,
num_2: 98,
num_3: 99,
num_4: 100,
num_5: 101,
num_6: 102,
num_7: 103,
num_8: 104,
num_9: 105,
num_multiply: 106,
num_add: 107,
num_enter: 108,
num_subtract: 109,
num_decimal: 110,
num_divide: 111,
7 years ago
'⇪': 20,
',': 188,
'.': 190,
'/': 191,
'`': 192,
'-': isff ? 173 : 189,
'=': isff ? 61 : 187,
';': isff ? 59 : 186,
'\'': 222,
'[': 219,
']': 221,
7 years ago
'\\': 220
};
// Modifier Keys
const _modifier = {
6 years ago
// shiftKey
7 years ago
'⇧': 16,
shift: 16,
6 years ago
// altKey
7 years ago
'⌥': 18,
alt: 18,
option: 18,
6 years ago
// ctrlKey
7 years ago
'⌃': 17,
ctrl: 17,
control: 17,
6 years ago
// metaKey
'⌘': 91,
cmd: 91,
command: 91
7 years ago
};
const modifierMap = {
7 years ago
16: 'shiftKey',
18: 'altKey',
17: 'ctrlKey',
91: 'metaKey',
shiftKey: 16,
ctrlKey: 17,
altKey: 18,
metaKey: 91
};
const _mods = {
6 years ago
16: false,
18: false,
17: false,
91: false
};
const _handlers = {};
7 years ago
// F1~F12 special key
for (let k = 1; k < 20; k++) {
6 years ago
_keyMap["f".concat(k)] = 111 + k;
6 years ago
}
7 years ago
let _downKeys = []; // 记录摁下的绑定键
let winListendFocus = false; // window是否已经监听了focus事件
let _scope = 'all'; // 默认热键范围
const elementHasBindEvent = []; // 已绑定事件的节点记录
6 years ago
// 返回键码
const code = x => _keyMap[x.toLowerCase()] || _modifier[x.toLowerCase()] || x.toUpperCase().charCodeAt(0);
const getKey = x => Object.keys(_keyMap).find(k => _keyMap[k] === x);
const getModifier = x => Object.keys(_modifier).find(k => _modifier[k] === x);
7 years ago
// 设置获取当前范围(默认为'所有'
7 years ago
function setScope(scope) {
_scope = scope || 'all';
}
// 获取当前范围
7 years ago
function getScope() {
return _scope || 'all';
}
// 获取摁下绑定键的键值
7 years ago
function getPressedKeyCodes() {
return _downKeys.slice(0);
}
function getPressedKeyString() {
return _downKeys.map(c => getKey(c) || getModifier(c) || String.fromCharCode(c));
}
function getAllKeyCodes() {
const result = [];
Object.keys(_handlers).forEach(k => {
_handlers[k].forEach(_ref => {
let {
key,
scope,
mods,
shortcut
} = _ref;
result.push({
scope,
shortcut,
mods,
keys: key.split('+').map(v => code(v))
});
});
});
return result;
}
7 years ago
// 表单控件控件判断 返回 Boolean
// hotkey is effective only when filter return true
7 years ago
function filter(event) {
const target = event.target || event.srcElement;
const {
tagName
} = target;
let flag = true;
// ignore: isContentEditable === 'true', <input> and <textarea> when readOnly state is false, <select>
5 years ago
if (target.isContentEditable || (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') && !target.readOnly) {
flag = false;
}
return flag;
}
7 years ago
// 判断摁下的键是否为某个键返回true或者false
7 years ago
function isPressed(keyCode) {
7 years ago
if (typeof keyCode === 'string') {
7 years ago
keyCode = code(keyCode); // 转换成键码
}
return _downKeys.indexOf(keyCode) !== -1;
}
7 years ago
// 循环删除handlers中的所有 scope(范围)
7 years ago
function deleteScope(scope, newScope) {
let handlers;
let i;
7 years ago
// 没有指定scope获取scope
7 years ago
if (!scope) scope = getScope();
for (const key in _handlers) {
7 years ago
if (Object.prototype.hasOwnProperty.call(_handlers, key)) {
handlers = _handlers[key];
for (i = 0; i < handlers.length;) {
7 years ago
if (handlers[i].scope === scope) handlers.splice(i, 1);else i++;
7 years ago
}
7 years ago
}
}
7 years ago
// 如果scope被删除将scope重置为all
7 years ago
if (getScope() === scope) setScope(newScope || 'all');
}
7 years ago
// 清除修饰键
7 years ago
function clearModifier(event) {
let key = event.keyCode || event.which || event.charCode;
const i = _downKeys.indexOf(key);
7 years ago
// 从列表中清除按压过的键
6 years ago
if (i >= 0) {
_downKeys.splice(i, 1);
}
// 特殊处理 cmmand 键,在 cmmand 组合快捷键 keyup 只执行一次的问题
6 years ago
if (event.key && event.key.toLowerCase() === 'meta') {
_downKeys.splice(0, _downKeys.length);
}
7 years ago
// 修饰键 shiftKey altKey ctrlKey (command||metaKey) 清除
7 years ago
if (key === 93 || key === 224) key = 91;
if (key in _mods) {
_mods[key] = false;
7 years ago
// 将修饰键重置为false
for (const k in _modifier) if (_modifier[k] === key) hotkeys[k] = false;
7 years ago
}
6 years ago
}
function unbind(keysInfo) {
// unbind(), unbind all keys
if (typeof keysInfo === 'undefined') {
Object.keys(_handlers).forEach(key => delete _handlers[key]);
6 years ago
} else if (Array.isArray(keysInfo)) {
// support like : unbind([{key: 'ctrl+a', scope: 's1'}, {key: 'ctrl-a', scope: 's2', splitKey: '-'}])
keysInfo.forEach(info => {
6 years ago
if (info.key) eachUnbind(info);
});
5 years ago
} else if (typeof keysInfo === 'object') {
6 years ago
// support like unbind({key: 'ctrl+a, ctrl+b', scope:'abc'})
if (keysInfo.key) eachUnbind(keysInfo);
} else if (typeof keysInfo === 'string') {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// support old method
// eslint-disable-line
let [scope, method] = args;
6 years ago
if (typeof scope === 'function') {
method = scope;
scope = '';
}
eachUnbind({
key: keysInfo,
scope,
method,
6 years ago
splitKey: '+'
});
}
}
6 years ago
// 解除绑定某个范围的快捷键
const eachUnbind = _ref2 => {
let {
key,
scope,
method,
splitKey = '+'
} = _ref2;
const multipleKeys = getKeys(key);
multipleKeys.forEach(originKey => {
const unbindKeys = originKey.split(splitKey);
const len = unbindKeys.length;
const lastKey = unbindKeys[len - 1];
const keyCode = lastKey === '*' ? '*' : code(lastKey);
if (!_handlers[keyCode]) return;
// 判断是否传入范围,没有就获取范围
6 years ago
if (!scope) scope = getScope();
const mods = len > 1 ? getMods(_modifier, unbindKeys) : [];
_handlers[keyCode] = _handlers[keyCode].filter(record => {
6 years ago
// 通过函数判断,是否解除绑定,函数相等直接返回
const isMatchingMethod = method ? record.method === method : true;
return !(isMatchingMethod && record.scope === scope && compareArray(record.mods, mods));
6 years ago
});
});
};
7 years ago
// 对监听对应快捷键的回调函数进行处理
function eventHandler(event, handler, scope, element) {
if (handler.element !== element) {
return;
}
let modifiersMatch;
// 看它是否在当前范围
7 years ago
if (handler.scope === scope || handler.scope === 'all') {
7 years ago
// 检查是否匹配修饰符如果有返回true
7 years ago
modifiersMatch = handler.mods.length > 0;
for (const y in _mods) {
7 years ago
if (Object.prototype.hasOwnProperty.call(_mods, y)) {
6 years ago
if (!_mods[y] && handler.mods.indexOf(+y) > -1 || _mods[y] && handler.mods.indexOf(+y) === -1) {
modifiersMatch = false;
}
7 years ago
}
}
7 years ago
// 调用处理程序,如果是修饰键不做处理
7 years ago
if (handler.mods.length === 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91] || modifiersMatch || handler.shortcut === '*') {
handler.keys = [];
handler.keys = handler.keys.concat(_downKeys);
7 years ago
if (handler.method(event, handler) === false) {
7 years ago
if (event.preventDefault) event.preventDefault();else event.returnValue = false;
7 years ago
if (event.stopPropagation) event.stopPropagation();
if (event.cancelBubble) event.cancelBubble = true;
}
}
}
}
7 years ago
// 处理keydown事件
function dispatch(event, element) {
const asterisk = _handlers['*'];
let key = event.keyCode || event.which || event.charCode;
// 表单控件过滤 默认表单控件不触发快捷键
if (!hotkeys.filter.call(this, event)) return;
6 years ago
// Gecko(Firefox)的command键值224在Webkit(Chrome)中保持一致
// Webkit左右 command 键值不一样
6 years ago
if (key === 93 || key === 224) key = 91;
6 years ago
/**
* Collect bound keys
* If an Input Method Editor is processing key input and the event is keydown, return 229.
* https://stackoverflow.com/questions/25043934/is-it-ok-to-ignore-keydown-events-with-keycode-229
* http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
*/
6 years ago
if (_downKeys.indexOf(key) === -1 && key !== 229) _downKeys.push(key);
6 years ago
/**
* Jest test cases are required.
* ===============================
*/
['ctrlKey', 'altKey', 'shiftKey', 'metaKey'].forEach(keyName => {
const keyNum = modifierMap[keyName];
6 years ago
if (event[keyName] && _downKeys.indexOf(keyNum) === -1) {
_downKeys.push(keyNum);
} else if (!event[keyName] && _downKeys.indexOf(keyNum) > -1) {
_downKeys.splice(_downKeys.indexOf(keyNum), 1);
} else if (keyName === 'metaKey' && event[keyName] && _downKeys.length === 3) {
/**
* Fix if Command is pressed:
* ===============================
*/
if (!(event.ctrlKey || event.shiftKey || event.altKey)) {
_downKeys = _downKeys.slice(_downKeys.indexOf(keyNum));
}
6 years ago
}
});
/**
* -------------------------------
*/
7 years ago
if (key in _mods) {
_mods[key] = true;
7 years ago
// 将特殊字符的key注册到 hotkeys 上
for (const k in _modifier) {
7 years ago
if (_modifier[k] === key) hotkeys[k] = true;
}
if (!asterisk) return;
}
7 years ago
// 将 modifierMap 里面的修饰键绑定到 event 中
for (const e in _mods) {
7 years ago
if (Object.prototype.hasOwnProperty.call(_mods, e)) {
_mods[e] = event[modifierMap[e]];
}
}
/**
* https://github.com/jaywcjlove/hotkeys/pull/129
* This solves the issue in Firefox on Windows where hotkeys corresponding to special characters would not trigger.
* An example of this is ctrl+alt+m on a Swedish keyboard which is used to type μ.
* Browser support: https://caniuse.com/#feat=keyboardevent-getmodifierstate
*/
if (event.getModifierState && !(event.altKey && !event.ctrlKey) && event.getModifierState('AltGraph')) {
if (_downKeys.indexOf(17) === -1) {
_downKeys.push(17);
}
if (_downKeys.indexOf(18) === -1) {
_downKeys.push(18);
}
_mods[17] = true;
_mods[18] = true;
}
7 years ago
// 获取范围 默认为 `all`
const scope = getScope();
// 对任何快捷键都需要做的处理
7 years ago
if (asterisk) {
for (let i = 0; i < asterisk.length; i++) {
if (asterisk[i].scope === scope && (event.type === 'keydown' && asterisk[i].keydown || event.type === 'keyup' && asterisk[i].keyup)) {
eventHandler(event, asterisk[i], scope, element);
6 years ago
}
7 years ago
}
}
// key 不在 _handlers 中返回
7 years ago
if (!(key in _handlers)) return;
for (let i = 0; i < _handlers[key].length; i++) {
if (event.type === 'keydown' && _handlers[key][i].keydown || event.type === 'keyup' && _handlers[key][i].keyup) {
if (_handlers[key][i].key) {
const record = _handlers[key][i];
const {
splitKey
} = record;
const keyShortcut = record.key.split(splitKey);
const _downKeysCurrent = []; // 记录当前按键键值
for (let a = 0; a < keyShortcut.length; a++) {
6 years ago
_downKeysCurrent.push(code(keyShortcut[a]));
}
if (_downKeysCurrent.sort().join('') === _downKeys.sort().join('')) {
6 years ago
// 找到处理内容
eventHandler(event, record, scope, element);
6 years ago
}
}
6 years ago
}
7 years ago
}
}
6 years ago
// 判断 element 是否已经绑定事件
6 years ago
function isElementBind(element) {
return elementHasBindEvent.indexOf(element) > -1;
7 years ago
}
7 years ago
function hotkeys(key, option, method) {
6 years ago
_downKeys = [];
const keys = getKeys(key); // 需要处理的快捷键列表
let mods = [];
let scope = 'all'; // scope默认为all所有范围都有效
let element = document; // 快捷键事件绑定节点
let i = 0;
let keyup = false;
let keydown = true;
let splitKey = '+';
let capture = false;
let single = false; // 单个callback
7 years ago
// 对为设定范围的判断
7 years ago
if (method === undefined && typeof option === 'function') {
method = option;
7 years ago
}
if (Object.prototype.toString.call(option) === '[object Object]') {
7 years ago
if (option.scope) scope = option.scope; // eslint-disable-line
6 years ago
if (option.element) element = option.element; // eslint-disable-line
if (option.keyup) keyup = option.keyup; // eslint-disable-line
if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
if (option.capture !== undefined) capture = option.capture; // eslint-disable-line
6 years ago
if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
if (option.single === true) single = true; // eslint-disable-line
7 years ago
}
if (typeof option === 'string') scope = option;
7 years ago
// 对于每个快捷键进行处理
7 years ago
for (; i < keys.length; i++) {
6 years ago
key = keys[i].split(splitKey); // 按键列表
mods = [];
7 years ago
// 如果是组合快捷键取得组合快捷键
if (key.length > 1) mods = getMods(_modifier, key);
7 years ago
// 将非修饰键转化为键码
7 years ago
key = key[key.length - 1];
key = key === '*' ? '*' : code(key); // *表示匹配所有快捷键
6 years ago
// 判断key是否在_handlers中不在就赋一个空数组
7 years ago
if (!(key in _handlers)) _handlers[key] = [];
// 如果只允许单个callback重新设置_handlers
if (single) _handlers[key] = [];
7 years ago
_handlers[key].push({
keyup,
keydown,
scope,
mods,
7 years ago
shortcut: keys[i],
method,
6 years ago
key: keys[i],
splitKey,
element
7 years ago
});
}
// 在全局document上设置快捷键
if (typeof element !== 'undefined' && !isElementBind(element) && window) {
6 years ago
elementHasBindEvent.push(element);
addEvent(element, 'keydown', e => {
dispatch(e, element);
}, capture);
3 years ago
if (!winListendFocus) {
winListendFocus = true;
addEvent(window, 'focus', () => {
3 years ago
_downKeys = [];
}, capture);
3 years ago
}
addEvent(element, 'keyup', e => {
dispatch(e, element);
6 years ago
clearModifier(e);
}, capture);
7 years ago
}
7 years ago
}
function trigger(shortcut) {
let scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';
Object.keys(_handlers).forEach(key => {
const dataList = _handlers[key].filter(item => item.scope === scope && item.shortcut === shortcut);
dataList.forEach(data => {
if (data && data.method) {
data.method();
}
});
});
}
const _api = {
getPressedKeyString,
setScope,
getScope,
deleteScope,
getPressedKeyCodes,
getAllKeyCodes,
isPressed,
filter,
trigger,
unbind,
keyMap: _keyMap,
modifier: _modifier,
modifierMap
7 years ago
};
for (const a in _api) {
7 years ago
if (Object.prototype.hasOwnProperty.call(_api, a)) {
hotkeys[a] = _api[a];
}
}
if (typeof window !== 'undefined') {
const _hotkeys = window.hotkeys;
hotkeys.noConflict = deep => {
7 years ago
if (deep && window.hotkeys === hotkeys) {
window.hotkeys = _hotkeys;
}
return hotkeys;
};
window.hotkeys = hotkeys;
}
export { hotkeys as default };