import { useContext, useState } from 'react'; import { Screen } from '../Package/Models/Screen'; import { EchoCallback, EchoContext } from '../Context/EchoContext'; import { ChannelContext } from '../Context/ChannelContext'; type EchoSubscribe = (screen: Screen, callback: EchoCallback) => void; type EchoUnsubscribe = (callback?: EchoCallback) => void; interface UseEchoResult { screen?: Screen; subscribe: EchoSubscribe; unsubscribe: EchoUnsubscribe; } const useEcho = (): UseEchoResult => { const [screen, setScreen] = useState(); const { echo } = useContext(EchoContext); const { channel, setChannel } = useContext(ChannelContext); const listen = (channel: string, listen: string, callback: EchoCallback) => { setChannel && setChannel(channel); echo?.channel(channel).listen(listen, callback); }; const subscribe: EchoSubscribe = (screen, callback) => { channel && echo?.leave(channel); setScreen(screen); listen(`screens.${screen.id}`, '.update-screen-content', callback); }; const unsubscribe: EchoUnsubscribe = (callback) => { channel && echo?.leave(channel); setScreen(undefined); if (callback) { listen('screens', '.update-screen-identity', callback); } else { setChannel && setChannel(); } }; return { screen, subscribe, unsubscribe }; }; export default useEcho;