[🐴] Global event mgmt (#3897)

* Add global event bus for messages logs

* Add rev to state

* Better handle error

* Clean up polling, add backgrounding

* Add trailConvo method

* Extend polling until we're ready for this
This commit is contained in:
Eric Bailey 2024-05-07 17:54:34 -05:00 committed by GitHub
parent 0625a914bd
commit 87cb4c105e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 686 additions and 41 deletions

View file

@ -0,0 +1,67 @@
import React from 'react'
import {AppState} from 'react-native'
import {BskyAgent} from '@atproto-labs/api'
import {isWeb} from '#/platform/detection'
import {MessagesEventBus} from '#/state/messages/events/agent'
import {MessagesEventBusState} from '#/state/messages/events/types'
import {useAgent} from '#/state/session'
import {useDmServiceUrlStorage} from '#/screens/Messages/Temp/useDmServiceUrlStorage'
import {IS_DEV} from '#/env'
const MessagesEventBusContext =
React.createContext<MessagesEventBusState | null>(null)
export function useMessagesEventBus() {
const ctx = React.useContext(MessagesEventBusContext)
if (!ctx) {
throw new Error('useChat must be used within a ChatProvider')
}
return ctx
}
export function MessagesEventBusProvider({
children,
}: {
children: React.ReactNode
}) {
const {serviceUrl} = useDmServiceUrlStorage()
const {getAgent} = useAgent()
const [bus] = React.useState(
() =>
new MessagesEventBus({
agent: new BskyAgent({
service: serviceUrl,
}),
__tempFromUserDid: getAgent().session?.did!,
}),
)
const service = React.useSyncExternalStore(bus.subscribe, bus.getSnapshot)
if (isWeb && IS_DEV) {
// @ts-ignore
window.messagesEventBus = service
}
React.useEffect(() => {
const handleAppStateChange = (nextAppState: string) => {
if (nextAppState === 'active') {
bus.resume()
} else {
bus.background()
}
}
const sub = AppState.addEventListener('change', handleAppStateChange)
return () => {
sub.remove()
}
}, [bus])
return (
<MessagesEventBusContext.Provider value={service}>
{children}
</MessagesEventBusContext.Provider>
)
}