import type { Emitter, EventType } from 'mitt';
import mitt from 'mitt';
import { onUnmounted, provide, type InjectionKey } from 'vue';
export function useEmitter<M extends Record<EventType, unknown>>(
  key?: InjectionKey<Emitter<M>>,
): Emitter<M> {
  const emitter = mitt<M>();
  if (key) provide(key, emitter);
  onUnmounted(() => {
    emitter.all.clear();
  });
  return emitter;
}
export function useEmitterEventListener<M extends Record<EventType, unknown>, T extends keyof M>(
  emitter: Emitter<M>,
  type: T,
  listener: (event: M[T]) => void,
) {
  emitter.on(type, listener);
  onUnmounted(() => {
    emitter.off(type, listener);
  });
}
