Skip to content

Commit b8fd994

Browse files
author
Ghislain Thau
committed
fix: prevents the shortcut's callback from being executing on registering of duplicated shortcuts
When registering a duplicated shortcut, the `addShortcut` and `addSequenceShortcut` methods return `of(null)` which immediately emits on subscribe. In case of duplicated shortcuts, we instead return EMPTY which doesn't emit and completes immediately on subscribe.
1 parent c61076b commit b8fd994

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,8 @@ That's all for now! Make sure to check out the `playground` inside the `src` [fo
300300
301301
No. It's not possible to define a hotkey multiple times. Each hotkey has a description and a group, so it doesn't make sense assigning a hotkey to different actions.
302302
303+
In case of registering duplicated hotkeys, the `addShortcut` and `addSequenceShortcut` methods return an `EMPTY` observable, allowing to detect duplicated hotkeys registration and execute custom logic.
304+
303305
**Why am I not receiving any event?**
304306
305307
If you've added a hotkey to a particular element of your DOM, make sure it's focusable. Otherwise, hotkeys cannot capture any keyboard event.

projects/ngneat/hotkeys/src/lib/hotkeys.service.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ export class HotkeysService {
137137

138138
if (sequenceSummary.hotkeyMap.has(normalizedKeys)) {
139139
console.error('Duplicated shortcut');
140-
return of(null);
140+
return EMPTY;
141141
}
142142

143143
sequenceSummary.hotkeyMap.set(normalizedKeys, hotkeySummary);
@@ -170,7 +170,7 @@ export class HotkeysService {
170170

171171
if (this.hotkeys.has(normalizedKeys)) {
172172
console.error('Duplicated shortcut');
173-
return of(null);
173+
return EMPTY;
174174
}
175175

176176
this.hotkeys.set(normalizedKeys, mergedOptions);

projects/ngneat/hotkeys/src/lib/tests/hotkeys.service.spec.ts

+10
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ describe('Service: Hotkeys', () => {
2727
expect(spectator.service.getHotkeys().length).toBe(0);
2828
});
2929

30+
it('should not emit after registering duplicated shortcuts', () => {
31+
const spyFcn = createSpy('subscribe', (...args) => {});
32+
spectator.service.addShortcut({ keys: 'a' }).subscribe(spyFcn);
33+
spectator.service.addShortcut({ keys: 'a' }).subscribe(spyFcn);
34+
spectator.service.addSequenceShortcut({ keys: 'g>a' }).subscribe(spyFcn);
35+
spectator.service.addSequenceShortcut({ keys: 'g>a' }).subscribe(spyFcn);
36+
37+
expect(spyFcn).not.toHaveBeenCalled();
38+
});
39+
3040
it('should unsubscribe shortcuts when removed', () => {
3141
const subscription = spectator.service.addShortcut({ keys: 'meta.a' }).subscribe();
3242
spectator.service.removeShortcuts('meta.a');

0 commit comments

Comments
 (0)