// Copyright 2019-2021 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT import { invokeTauriCommand } from './helpers/tauri' import { emit as emitEvent } from './helpers/event' import { transformCallback } from './tauri' export interface Event { /** Event name */ event: string /** Event identifier used to unlisten */ id: number /** Event payload */ payload: T } export type EventCallback = (event: Event) => void export type UnlistenFn = () => void /** * Unregister the event listener associated with the given id. * * @ignore * @param eventId Event identifier * @returns */ async function _unlisten(eventId: number): Promise { return invokeTauriCommand({ __tauriModule: 'Event', message: { cmd: 'unlisten', eventId } }) } /** * Listen to an event from the backend. * * @param event Event name * @param handler Event handler callback * @return A promise resolving to a function to unlisten to the event. */ async function listen( event: string, handler: EventCallback ): Promise { return invokeTauriCommand({ __tauriModule: 'Event', message: { cmd: 'listen', event, handler: transformCallback(handler) } }).then((eventId) => { return async () => _unlisten(eventId) }) } /** * Listen to an one-off event from the backend. * * @param event Event name * @param handler Event handler callback * @returns A promise resolving to a function to unlisten to the event. */ async function once( event: string, handler: EventCallback ): Promise { return listen(event, (eventData) => { handler(eventData) _unlisten(eventData.id).catch(() => {}) }) } /** * Emits an event to the backend. * * @param event Event name * @param [payload] Event payload * @returns */ async function emit(event: string, payload?: string): Promise { return emitEvent(event, undefined, payload) } export { listen, once, emit }