import React, { useEffect, useState } from 'react'; import ReactRouterPropTypes from 'react-router-prop-types'; import { UserType } from './Types'; import { Link } from 'react-router-dom'; import moment from 'moment'; import Message from './Message'; import MessageInput from './MessageInput'; import Spinner from './Spinner'; import Avatar from './Avatar'; import Button from './Button'; import { format } from '../utils/embed'; import { getMessages, comment, markReadTracker } from '../api'; export default function Thread(props) { const [message, setMessage] = useState(props.location.state || {}); const [replies, setReplies] = useState([]); const [loading, setLoading] = useState(false); const [active, setActive] = useState(0); useEffect(() => { if (props.connection) { props.connection.addEventListener('msg', onReply); } setActive(0); loadReplies(); return () => { if (props.connection) { props.connection.removeEventListener('msg', onReply); } } }, [props.connection]); let loadReplies = () => { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; setReplies([]); setLoading(true); const { mid } = props.match.params; let params = { mid: mid }; if (props.visitor && props.visitor.hash) { params.hash = props.visitor.hash; } getMessages('/api/thread', params) .then(response => { setMessage(response.data.shift()); setReplies(response.data); setLoading(false); setActive(0); } ).catch(ex => { console.log(ex); }); } let onReply = (json) => { const msg = JSON.parse(json.data); if (msg.mid == message.mid) { setReplies([...this.state.replies, msg]); } } let postComment = (template) => { const { mid, rid, body, attach } = template; comment(mid, rid, body, attach).then(res => { loadReplies(); }) .catch(console.log); } const loaders = Math.min(message.replies || 0, 10); return ( <> { message.mid ? ( {active === (message.rid || 0) && Write a comment...} ) : ( ) } ); } const linkStyle = { cursor: 'pointer' }; Thread.propTypes = { location: ReactRouterPropTypes.location, history: ReactRouterPropTypes.history, match: ReactRouterPropTypes.match, visitor: UserType.isRequired };