Skip to content

Commit

Permalink
fix: fix shortcut key incorrect after blur (#6022)
Browse files Browse the repository at this point in the history
  • Loading branch information
Aarebecca authored Jul 11, 2024
1 parent e3b1d48 commit adbd9eb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/g6/__tests__/unit/utils/shortcut.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
9 changes: 9 additions & 0 deletions packages/g6/src/utils/shortcut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
}
}

0 comments on commit adbd9eb

Please sign in to comment.