|
| 1 | +import { createContext, useContext, useEffect } from 'react'; |
| 2 | +import { Props } from '../types.js'; |
| 3 | +import { useClient } from './ClientProvider.js'; |
| 4 | +import { useListenerCounter } from '../hooks/internal/useListenerCounter.js'; |
| 5 | +import { FrameSystemEventRecord } from 'dedot/chaintypes'; |
| 6 | +import { EventEmitter } from 'dedot/utils'; |
| 7 | +import { noop } from '../utils/index.js'; |
| 8 | + |
| 9 | +export type TypinkEventsRegistration = { |
| 10 | + [TypinkEvent.SYSTEM_EVENTS]: (events: FrameSystemEventRecord[]) => void; |
| 11 | +}; |
| 12 | + |
| 13 | +export type Unsub = () => void; |
| 14 | + |
| 15 | +export enum TypinkEvent { |
| 16 | + SYSTEM_EVENTS = 'SYSTEM_EVENTS', |
| 17 | +} |
| 18 | + |
| 19 | +const eventEmitter = new EventEmitter<TypinkEvent>(); |
| 20 | + |
| 21 | +export interface TypinkEventsContextProps { |
| 22 | + subscribeToEvent<T extends TypinkEvent>(event: T, callback: TypinkEventsRegistration[T]): Unsub; |
| 23 | +} |
| 24 | + |
| 25 | +export const TypinkEventsContext = createContext<TypinkEventsContextProps>({} as any); |
| 26 | + |
| 27 | +export const useTypinkEvents = () => { |
| 28 | + return useContext(TypinkEventsContext); |
| 29 | +}; |
| 30 | + |
| 31 | +/** |
| 32 | + * TypinkEventsProvider is a React component that manages event listeners for system events. |
| 33 | + * It provides a context for subscribing to and managing event listeners. |
| 34 | + * |
| 35 | + * @param props - The component props. |
| 36 | + * @param props.children - The child components to be wrapped by the provider. |
| 37 | + */ |
| 38 | +export function TypinkEventsProvider({ children }: Props) { |
| 39 | + const { client } = useClient(); |
| 40 | + const { hasAny, tryIncrease, tryDecrease } = useListenerCounter(TypinkEvent.SYSTEM_EVENTS); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (!client || !hasAny) return; |
| 44 | + |
| 45 | + let unsub: Unsub | undefined; |
| 46 | + let unmounted = false; |
| 47 | + |
| 48 | + (async () => { |
| 49 | + unsub = await client.query.system.events((events) => { |
| 50 | + if (unmounted) { |
| 51 | + unsub && unsub(); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + eventEmitter.emit(TypinkEvent.SYSTEM_EVENTS, events); |
| 56 | + }); |
| 57 | + })(); |
| 58 | + |
| 59 | + return () => { |
| 60 | + unsub && unsub(); |
| 61 | + unmounted = true; |
| 62 | + }; |
| 63 | + }, [client, hasAny]); |
| 64 | + |
| 65 | + const subscribeToEvent = (event: TypinkEvent, callback: (events: any[]) => void): Unsub => { |
| 66 | + if (!client) return noop; |
| 67 | + |
| 68 | + const unsub = eventEmitter.on(event, callback); |
| 69 | + tryIncrease(event); |
| 70 | + |
| 71 | + return () => { |
| 72 | + unsub(); |
| 73 | + tryDecrease(event); |
| 74 | + }; |
| 75 | + }; |
| 76 | + |
| 77 | + return <TypinkEventsContext.Provider value={{ subscribeToEvent }}>{children}</TypinkEventsContext.Provider>; |
| 78 | +} |
0 commit comments