Open History to see the last commit
1import { RpcTarget } from 'capnweb'
2import type { ChatNotification } from '../../chat-server/chat-api'
3
4const handlers = new WeakMap<
5 ChatNotifier,
6 Set<(notification: ChatNotification) => void>
7>()
8
9/** Client-side RpcTarget the server calls to push chat notifications. */
10export class ChatNotifier extends RpcTarget {
11 addHandler(handler: (notification: ChatNotification) => void) {
12 let set = handlers.get(this)
13 if (!set) {
14 set = new Set()
15 handlers.set(this, set)
16 }
17 set.add(handler)
18 return () => {
19 set.delete(handler)
20 }
21 }
22
23 /** @deprecated Prefer addHandler for multiple listeners */
24 setHandler(handler: (notification: ChatNotification) => void) {
25 handlers.set(this, new Set([handler]))
26 }
27
28 notify(notification: ChatNotification) {
29 const set = handlers.get(this)
30 if (!set) return
31 for (const handler of set) {
32 handler(notification)
33 }
34 }
35}