import { Injectable, NgZone } from '@angular/core'; import { ShortcutHandler, register, unregister } from '@tauri-apps/api/globalShortcut'; import { Observable, Subscriber } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ShortcutService { private internalHandlers: Map, () => void]> = new Map, () => void]>(); constructor(private zone: NgZone) {} register(shortcut: string) { return new Observable((subscriber) => { let originalHandler: ShortcutHandler = (s) => this.zone.run(() => subscriber.next(s)); const teardown = () => { unregister(shortcut); this.internalHandlers.delete(shortcut); }; this.internalHandlers.set(shortcut, [originalHandler, subscriber, teardown]); register(shortcut, originalHandler) return teardown; }); } rebind_from_to(previousShortcut: string, nextShortcut: string) { let [oldHandler, subscriber, teardown] = this.internalHandlers.get(previousShortcut)!; subscriber.remove(teardown); teardown(); teardown = () => { unregister(nextShortcut); this.internalHandlers.delete(nextShortcut); }; register(nextShortcut, oldHandler); this.internalHandlers.set(nextShortcut, [oldHandler, subscriber, teardown]); } }