import { customObject } from "../type"; export const forEach = (obj: customObject, callback: (key: string, value: any) => void) => { Object.keys(obj).forEach((key) => { callback(key, obj[key]); }); }; const _keys: string[] = ["Ctrl", "Control", "^", "⇧", "Shift", "⌥", "Alt", "Option", "⌘", "Command"]; // const _modify: customObject = { // "⇧": 16, // Shift: 16, // "⌥": 18, // Alt: 18, // Option: 18, // "⌃": 17, // Ctrl: 17, // Control: 17, // "⌘": 91, // Command: 91, // }; export const isExit = (keys: string[]): boolean => { for (let i = 0; i < _keys.length; i++) { if (keys.includes(_keys[i])) { return true; } } return false; }; export function capitalFirstLetter(str: string): string { return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase(); } // @ts-ignore export const isEqual = (_key, _value, isComposition: boolean): boolean => { const { altKey, ctrlKey, shiftKey } = _key, { keyCode, value, key, compositionKeys } = _value; let str = `${ctrlKey ? "Ctrl+" : ""}${shiftKey ? "Shift+" : ""}${altKey ? "Alt+" : ""}${key}`; const ret = str === compositionKeys && keyCode === value && isComposition; return ret; }; // TODO: 优化缓存策略 使用闭包 减少计算 export const isMatchEvent = (e: KeyboardEvent, keys: number[], compositionKeys:string = ""): boolean => { // console.log(e); let key = capitalFirstLetter(e.key), value = keys[0], keyCode = e.keyCode, _compositionKeys = compositionKeys.split("+") || []; if (keyCode == 93 || keyCode == 224) keyCode = 91; // right command on webkit, command on Gecko const _key = { altKey: e.altKey, ctrlKey: e.ctrlKey || e.metaKey, shiftKey: e.shiftKey, }; // 组合键 if (isExit(_compositionKeys)) { const _value = { keyCode, value, key, compositionKeys, }; if (isEqual(_key, _value, _compositionKeys.length > 1)) return true; return false; } if(_key.altKey || _key.ctrlKey || _key.shiftKey) return false; // 单键 if (keyCode === value) { return true; } return false; } const capitalFirstLetterRegex = /((^[A-Z]{1})|\d).*/; export const validateCompositionKey = (compositionKeys: string): boolean => { const str = compositionKeys.split("+"); for (const s of str) { if (!capitalFirstLetterRegex.test(s)) { return false; } } return true; };