import { useEffect, useMemo } from 'react' import { type RoomMeta, useMessagePipeline, useRoomMeta } from '../model/message-pipeline' const MAX_WATCHED = 24 export interface WatchedRoom { id: string name: string } /** * 为侧栏里的房间建立后台订阅:不在当前房间的消息也能进 pipeline, * 并携带名称与跳转地址供 toast 使用。 */ export function RoomWatcher({ spaceName, rooms, dms, activeRoomId, }: { spaceName: string rooms: WatchedRoom[] dms: WatchedRoom[] activeRoomId: string | null }) { const api = useMessagePipeline() const meta = useMemo(() => { const out: Record = {} for (const room of rooms) out[room.id] = { name: room.name, href: spaceName ? `/app/${spaceName}/chat/${room.id}` : `/app/@me/chat/${room.id}`, } for (const dm of dms) out[dm.id] = { name: dm.name, href: `/app/@me/chat/${dm.id}` } return out }, [rooms, dms, spaceName]) useRoomMeta(meta) const ids = useMemo(() => [...rooms, ...dms].slice(0, MAX_WATCHED).map((room) => room.id), [rooms, dms]) useEffect(() => { const releases = ids.map((id) => api.watch(id)) return () => { for (const release of releases) release() } }, [api, ids]) useEffect(() => { api.activate(activeRoomId) return () => api.activate(null) }, [api, activeRoomId]) return null }