/* Graphictoria 5 (https://gtoria.net) Copyright © XlXi 2022 */ import { Component, createRef } from 'react'; import axios from 'axios'; import Twemoji from 'react-twemoji'; import { buildGenericApiUrl } from '../util/HTTP.js'; import Loader from './Loader'; const commentsId = 'gt-comments'; // XlXi: Keep this in sync with the Item page. axios.defaults.withCredentials = true; class Comments extends Component { constructor(props) { super(props); this.state = { loaded: false, loadingCursor: false, disabled: false, error: '', comments: [], mouseHover: -1 }; this.inputBox = createRef(); this.loadComments = this.loadComments.bind(this); this.loadMore = this.loadMore.bind(this); this.postComment = this.postComment.bind(this); } componentWillMount() { window.addEventListener('scroll', this.loadMore); } componentWillUnmount() { window.removeEventListener('scroll', this.loadMore); } componentDidMount() { let commentsElement = this.props.element; if (commentsElement) { this.assetId = commentsElement.getAttribute('data-asset-id') this.setState({ canComment: (commentsElement.getAttribute('data-can-comment') === '1') }); } this.loadComments(); } loadComments() { axios.get(buildGenericApiUrl('api', `comments/v1/list-json?assetId=${this.assetId}`)) .then(res => { const comments = res.data; this.nextCursor = comments.next_cursor; this.setState({ comments: comments.data, loaded: true }); }); } // XlXi: https://stackoverflow.com/questions/57778950/how-to-load-more-search-results-when-scrolling-down-the-page-in-react-js loadMore() { // XlXi: Taking the height of the footer into account. if (window.innerHeight + document.documentElement.scrollTop >= document.scrollingElement.scrollHeight-200) { if (!!(this.nextCursor) && !this.state.loadingCursor) { this.setState({ loadingCursor: true }); axios.get(buildGenericApiUrl('api', `comments/v1/list-json?assetId=${this.assetId}&cursor=${this.nextCursor}`)) .then(res => { const comments = res.data; this.nextCursor = comments.next_cursor; this.setState({ comments: this.state.comments.concat(comments.data), loadingCursor: false }); }); } } } postComment() { this.setState({ disabled: true }); const postText = this.inputBox.current.value; if (postText == '') { this.setState({ disabled: false, error: 'Your comment cannot be blank.' }); this.inputBox.current.focus(); return; } axios.post(buildGenericApiUrl('api', `comments/v1/share`), { assetId: this.assetId, content: postText }) .then(res => { this.inputBox.current.value = ''; this.setState({ loaded: false, loadingCursor: false, disabled: false }); this.loadComments(); }) .catch(err => { const data = err.response.data; this.setState({ disabled: false, error: data.message }); this.inputBox.current.focus(); }); } render() { return ( <>
{ time }
{ content }
No comments were found. { this.state.canComment ? 'You could be the first!' : null }