fix: fix shortcut key incorrect after blur (#6022)

This commit is contained in:
Aaron 2024-07-11 17:22:52 +08:00 committed by GitHub
parent e3b1d48745
commit adbd9eb59f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 0 deletions

View File

@ -81,4 +81,23 @@ describe('shortcut', () => {
expect(drag.mock.calls[0][0].deltaX).toBe(10);
expect(drag.mock.calls[0][0].deltaY).toBe(0);
});
it('focus', () => {
const wheel = jest.fn();
shortcut.bind(['Control', 'wheel'], wheel);
emitter.emit(CommonEvent.KEY_DOWN, { key: 'Control' });
emitter.emit(CommonEvent.WHEEL, { deltaX: 0, deltaY: 10 });
expect(wheel).toHaveBeenCalledTimes(1);
emitter.emit(CommonEvent.KEY_DOWN, { key: 'Control' });
window.dispatchEvent(new FocusEvent('focus'));
// @ts-expect-error private property
expect(shortcut.recordKey.size).toBe(0);
emitter.emit(CommonEvent.KEY_DOWN, { key: 'Control' });
emitter.emit(CommonEvent.WHEEL, { deltaX: 0, deltaY: 10 });
expect(wheel).toHaveBeenCalledTimes(2);
});
});

View File

@ -54,6 +54,10 @@ export class Shortcut {
emitter.on(CommonEvent.KEY_UP, this.onKeyUp);
emitter.on(CommonEvent.WHEEL, this.onWheel);
emitter.on(CommonEvent.DRAG, this.onDrag);
// 窗口重新获得焦点后清空按键,避免按键状态异常
// Clear the keys when the window regains focus to avoid abnormal key states
window.addEventListener('focus', this.onFocus);
}
private onKeyDown = (event: KeyboardEvent) => {
@ -103,11 +107,16 @@ export class Shortcut {
this.triggerExtendKey(CommonEvent.DRAG, event);
};
private onFocus = () => {
this.recordKey.clear();
};
public destroy() {
this.unbindAll();
this.emitter.off(CommonEvent.KEY_DOWN, this.onKeyDown);
this.emitter.off(CommonEvent.KEY_UP, this.onKeyUp);
this.emitter.off(CommonEvent.WHEEL, this.onWheel);
this.emitter.off(CommonEvent.DRAG, this.onDrag);
window.removeEventListener('blur', this.onFocus);
}
}