qotnews/webclient/src/Comments.js

98 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-08-24 05:04:51 +00:00
import React from 'react';
import { Link } from 'react-router-dom';
import { HashLink } from 'react-router-hash-link';
import { Helmet } from 'react-helmet';
2019-08-24 05:04:51 +00:00
import moment from 'moment';
import { sourceLink, infoLine, ToggleDot } from './utils.js';
2019-08-24 05:04:51 +00:00
class Article extends React.Component {
constructor(props) {
super(props);
const id = this.props.match.params.id;
this.state = {
story: JSON.parse(localStorage.getItem(id)) || false,
error: false,
};
}
2019-10-12 05:32:17 +00:00
componentDidMount() {
2019-08-24 05:04:51 +00:00
const id = this.props.match.params.id;
2019-10-12 05:32:17 +00:00
fetch('/api/' + id)
.then(res => res.json())
.then(
(result) => {
localStorage.setItem(id, JSON.stringify(result.story));
this.setState({ story: result.story }, () => {
const hash = window.location.hash.substring(1);
if (hash) {
document.getElementById(hash).scrollIntoView();
}
});
2019-10-12 05:32:17 +00:00
},
(error) => {
this.setState({ error: true });
}
);
2019-08-24 05:04:51 +00:00
}
2019-08-26 01:37:50 +00:00
displayComment(story, c, level) {
2019-08-24 05:04:51 +00:00
return (
<div className={level ? 'comment lined' : 'comment'}>
<div className='info'>
<p>
{c.author === story.author ? '[OP]' : ''} {c.author || '[Deleted]'}
&#8203; | <HashLink to={'#'+c.author+c.date} id={c.author+c.date}>{moment.unix(c.date).fromNow()}</HashLink>
</p>
2019-08-24 05:04:51 +00:00
</div>
<div className='text' dangerouslySetInnerHTML={{ __html: c.text }} />
{level < 5 ?
2019-08-26 01:37:50 +00:00
c.comments.map(i => this.displayComment(story, i, level + 1))
:
<div className='info'><p>[replies snipped]</p></div>
}
2019-08-24 05:04:51 +00:00
</div>
);
}
render() {
const id = this.props.match.params.id;
2019-08-24 05:04:51 +00:00
const story = this.state.story;
const error = this.state.error;
return (
<div className='container'>
{error && <p>Connection error?</p>}
{story ?
<div className='article'>
<Helmet>
<title>{story.title} - QotNews Comments</title>
</Helmet>
<h1>{story.title}</h1>
2019-08-24 05:04:51 +00:00
<div className='info'>
<Link to={'/' + story.id}>View article</Link>
</div>
2019-08-24 05:04:51 +00:00
{infoLine(story)}
2019-08-24 05:04:51 +00:00
<div className='comments'>
{story.comments.map(c => this.displayComment(story, c, 0))}
</div>
2019-08-24 05:04:51 +00:00
</div>
:
<p>loading...</p>
2019-08-24 05:04:51 +00:00
}
<ToggleDot id={id} article={true} />
2019-08-24 05:04:51 +00:00
</div>
);
}
}
export default Article;