feat: 按键触发条件

This commit is contained in:
unanmed 2023-11-18 23:03:33 +08:00
parent 253445eb6e
commit 9bf27f58e3

View File

@ -1,8 +1,6 @@
import { KeyCode } from '@/plugin/keyCodes';
import { getLocFromMouseLoc } from '@/plugin/ui/fixed';
import { deleteWith, generateBinary, has, spliceBy, tip } from '@/plugin/utils';
import { deleteWith, spliceBy } from '@/plugin/utils';
import { EmitableEvent, EventEmitter } from '../../common/eventEmitter';
import { GameStorage } from '../storage';
interface HotkeyEvent extends EmitableEvent {}
@ -45,6 +43,7 @@ export class Hotkey extends EventEmitter<HotkeyEvent> {
none: []
};
enabled: boolean = false;
conditionMap: Map<symbol, () => boolean> = new Map();
private scope: symbol = Symbol();
private scopeStack: symbol[] = [];
@ -57,7 +56,7 @@ export class Hotkey extends EventEmitter<HotkeyEvent> {
}
/**
*
* id可以包含数字后缀
* @param data
*/
register(data: RegisterHotkeyData) {
@ -84,7 +83,7 @@ export class Hotkey extends EventEmitter<HotkeyEvent> {
/**
*
* @param id id
* @param id id
* @param func
*/
realize(id: string, func: HotkeyFunc) {
@ -113,6 +112,7 @@ export class Hotkey extends EventEmitter<HotkeyEvent> {
spliceBy(this.scopeStack, symbol);
this.scopeStack.push(symbol);
this.scope = symbol;
this.conditionMap.set(symbol, () => true);
for (const key of Object.values(this.data)) {
key.func.set(symbol, () => {});
}
@ -162,6 +162,8 @@ export class Hotkey extends EventEmitter<HotkeyEvent> {
ev: KeyboardEvent
) {
if (!this.enabled) return;
const when = this.conditionMap.get(this.scope)!;
if (!when()) return;
const toEmit = this.keyMap.get(key);
if (!toEmit) return;
const { ctrl, shift, alt } = this.unwarpBinary(assist);
@ -203,6 +205,15 @@ export class Hotkey extends EventEmitter<HotkeyEvent> {
this.enabled = false;
}
/**
*
* @param fn
*/
when(fn: () => boolean) {
this.conditionMap.set(this.scope, fn);
return this;
}
private unwarpBinary(bin: number): AssistHoykey {
return {
ctrl: !!(bin & (1 << 0)),