diff --git a/packages/g6/__tests__/unit/utils/shortcut.spec.ts b/packages/g6/__tests__/unit/utils/shortcut.spec.ts index 73423dd632e..d39555cf7ad 100644 --- a/packages/g6/__tests__/unit/utils/shortcut.spec.ts +++ b/packages/g6/__tests__/unit/utils/shortcut.spec.ts @@ -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); + }); }); diff --git a/packages/g6/src/utils/shortcut.ts b/packages/g6/src/utils/shortcut.ts index bbc8e429225..f7dbe24713f 100644 --- a/packages/g6/src/utils/shortcut.ts +++ b/packages/g6/src/utils/shortcut.ts @@ -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); } }