traceTreeEventDispatcher.tsx 919 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import type {TraceTree} from './traceTree';
  2. type ArgumentTypes<F> = F extends (...args: infer A) => any ? A : never;
  3. export class TraceTreeEventDispatcher {
  4. listeners: {[K in keyof TraceTree.TraceTreeEvents]: Set<TraceTree.TraceTreeEvents[K]>} =
  5. {
  6. 'trace timeline change': new Set(),
  7. };
  8. on<K extends keyof TraceTree.TraceTreeEvents>(
  9. event: K,
  10. cb: TraceTree.TraceTreeEvents[K]
  11. ): void {
  12. this.listeners[event].add(cb);
  13. }
  14. off<K extends keyof TraceTree.TraceTreeEvents>(
  15. event: K,
  16. cb: TraceTree.TraceTreeEvents[K]
  17. ): void {
  18. this.listeners[event].delete(cb);
  19. }
  20. dispatch<K extends keyof TraceTree.TraceTreeEvents>(
  21. event: K,
  22. ...args: ArgumentTypes<TraceTree.TraceTreeEvents[K]>
  23. ): void {
  24. if (!this.listeners[event]) {
  25. return;
  26. }
  27. for (const handler of this.listeners[event]) {
  28. // @ts-expect-error
  29. handler(...args);
  30. }
  31. }
  32. }