import React, { useState, useEffect, useRef, useContext } from 'react'; import { TokenContext } from '../utilities/token-provider'; import { io } from 'socket.io-client'; import '../../styles/popup-chat.css'; const socket = io(`${process.env.CHAT_URI}/chat`); const PopupChat = props => { const [open, setOpen] = useState(false); const [chatlog, setChatlog] = useState([]); const inputRef = useRef(); const sendRef = useRef(); const endRef = useRef(); const authTokens = useContext(TokenContext); const pushChatlog = line => setChatlog(prevChatlog => [...prevChatlog, line]); useEffect(() => { socket.on('message', message => pushChatlog(message)); socket.on('backlog', messages => setChatlog(prev => [...prev, ...messages])); socket.on('disconnect', reason => pushChatlog({ emphasis: true, text: 'Lost connection' })); }, []); useEffect(() => { if (open) { endRef.current.scrollIntoView(); } }, [chatlog, open]); if (!open) { return (
); } return (
evt.key == 'Enter' ? sendRef.current.click() : ''} ref={inputRef} />
); }; //handlers const handleOpen = (setOpen, accessToken) => { setOpen(true); socket.emit('open chat', { accessToken }); }; const handleClose = setOpen => { setOpen(false); }; const handleSend = (inputRef, pushChatlog, username, accessToken) => { if (inputRef.current.value == '') { return; } socket.emit('message', { accessToken, text: inputRef.current.value }); if (!inputRef.current.value.startsWith('/')) { pushChatlog({ username: username, text: inputRef.current.value }); } inputRef.current.value = ''; }; //render each line const processLine = (line, index) => { let content = {line.username ? {line.username}: : ''}{line.text ? {line.text} : ''}; //decorators if (line.emphasis) { content = {content}; } if (line.strong) { content = {content}; } return
  • {content}
  • ; }; export default PopupChat;