Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions packages/hooks/src/useKeyPress/__tests__/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,49 @@ describe('useKeyPress ', () => {
expect(callback).toHaveBeenCalled();
});

test('shift key should work in keyup event with exactMatch', async () => {
renderHook(() =>
useKeyPress(['shift'], callback, {
events: ['keyup'],
exactMatch: true,
}),
);

fireEvent.keyUp(document, { key: 'Shift', keyCode: 16, shiftKey: false });
expect(callback).toHaveBeenCalled();
});

test('ctrl key should work in keyup event with exactMatch', async () => {
renderHook(() =>
useKeyPress(['ctrl'], callback, {
events: ['keyup'],
exactMatch: true,
}),
);

fireEvent.keyUp(document, { key: 'Control', keyCode: 17, ctrlKey: false });
expect(callback).toHaveBeenCalled();
});

test('alt key should work in keyup event with exactMatch', async () => {
renderHook(() =>
useKeyPress(['alt'], callback, {
events: ['keyup'],
exactMatch: true,
}),
);

fireEvent.keyUp(document, { key: 'Alt', keyCode: 18, altKey: false });
expect(callback).toHaveBeenCalled();
});

test('modifier key keyup should not break combination keys', async () => {
renderHook(() => useKeyPress(['shift.c'], callback));

fireEvent.keyDown(document, { key: 'c', shiftKey: true, keyCode: 67 });
expect(callback).toHaveBeenCalled();
});

test('test `keyFilter` function parameter', async () => {
const callback1 = vi.fn();
const callback2 = vi.fn();
Expand Down
21 changes: 18 additions & 3 deletions packages/hooks/src/useKeyPress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,24 @@ const aliasKeyCodeMap = {

// 修饰键
const modifierKey = {
ctrl: (event: KeyboardEvent) => event.ctrlKey,
shift: (event: KeyboardEvent) => event.shiftKey,
alt: (event: KeyboardEvent) => event.altKey,
ctrl: (event: KeyboardEvent) => {
if (event.type === 'keyup') {
return event.keyCode === 17;
}
return event.ctrlKey;
},
shift: (event: KeyboardEvent) => {
if (event.type === 'keyup') {
return event.keyCode === 16;
}
return event.shiftKey;
},
alt: (event: KeyboardEvent) => {
if (event.type === 'keyup') {
return event.keyCode === 18;
}
return event.altKey;
},
meta: (event: KeyboardEvent) => {
if (event.type === 'keyup') {
return aliasKeyCodeMap.meta.includes(event.keyCode);
Expand Down