diff --git a/README.md b/README.md index 1fb2827..7bd709d 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,17 @@ It accepts a second input that allows defining the hotkey that should open the d You can also provide a custom component. To help you with that, the service exposes the `getShortcuts` method. +#### `removeShortcuts` + +Remove previously registered shortcuts. + +```ts +// Remove a single shortcut +this.hotkeys.removeShortcuts({ keys: 'meta.a' }); +// Remove several shortcuts +this.hotkeys.removeShortcuts([{ keys: 'meta.1' }, { keys: 'meta.2' }]); +``` + ## Hotkeys Shortcut Pipe The `hotkeysShortcut` formats the shortcuts when presenting them in a custom help screen: diff --git a/projects/ngneat/hotkeys/src/lib/hotkeys.service.ts b/projects/ngneat/hotkeys/src/lib/hotkeys.service.ts index 534e0f2..6a6bfdb 100644 --- a/projects/ngneat/hotkeys/src/lib/hotkeys.service.ts +++ b/projects/ngneat/hotkeys/src/lib/hotkeys.service.ts @@ -4,6 +4,7 @@ import { EventManager } from '@angular/platform-browser'; import { Observable, of } from 'rxjs'; import { hostPlatform, normalizeKeys } from './utils/platform'; +import { coerceArray } from './utils/array'; interface Options { group: string; @@ -94,6 +95,19 @@ export class HotkeysService { }); } + removeShortcuts(hotkeys: Hotkey | Hotkey[]): void { + const coercedHotkeys = coerceArray(hotkeys); + coercedHotkeys.forEach(hotkey => { + const mergedOptions = { ...this.defaults, ...hotkey }; + const normalizedKeys = normalizeKeys(mergedOptions.keys, hostPlatform()); + if (!this.hotkeys.has(normalizedKeys)) { + console.warn(`Hotkey ${normalizedKeys} not found`); + return; + } + this.hotkeys.delete(normalizedKeys); + }); + } + onShortcut(callback: HotkeyCallback): () => void { this.callbacks.push(callback); diff --git a/projects/ngneat/hotkeys/src/lib/tests/hotkeys.service.spec.ts b/projects/ngneat/hotkeys/src/lib/tests/hotkeys.service.spec.ts index 82c42d8..7c9a949 100644 --- a/projects/ngneat/hotkeys/src/lib/tests/hotkeys.service.spec.ts +++ b/projects/ngneat/hotkeys/src/lib/tests/hotkeys.service.spec.ts @@ -18,6 +18,18 @@ describe('Service: Hotkeys', () => { expect(spectator.service.getHotkeys().length).toBe(1); }); + it('should remove shortcut', () => { + spectator.service.addShortcut({ keys: 'a' }); + spectator.service.addShortcut({ keys: 'b' }); + spectator.service.addShortcut({ keys: 'c' }); + spectator.service.removeShortcuts([{ keys: 'a' }, { keys: 'b' }]); + spectator.service.removeShortcuts({ keys: 'c' }); + expect(spectator.service.getHotkeys().length).toBe(0); + const spy = spyOn(console, 'warn'); + spectator.service.removeShortcuts({ keys: 'c' }); + expect(spy).toHaveBeenCalled(); + }); + it('should listen to keydown', () => { const spyFcn = createSpy('subscribe', e => {}); spectator.service.addShortcut({ keys: 'a' }).subscribe(spyFcn);