save comments collapsed state

closes #43
This commit is contained in:
igoradamenko
2018-06-03 17:37:25 +03:00
parent 11353388af
commit e5f9961a81
2 changed files with 43 additions and 3 deletions
+2
View File
@@ -12,6 +12,7 @@ const PROVIDER_NAMES = {
facebook: 'Facebook',
github: 'GitHub',
};
const LS_COLLAPSE_KEY = '__remarkCollapsed';
module.exports = {
BASE_URL,
@@ -24,4 +25,5 @@ module.exports = {
DEFAULT_MAX_COMMENT_SIZE,
PROVIDER_NAMES,
DEFAULT_SORT,
LS_COLLAPSE_KEY,
};
+41 -3
View File
@@ -1,21 +1,51 @@
import { h, Component } from 'preact';
import { LS_COLLAPSE_KEY } from 'common/constants';
import { siteId, url } from 'common/settings';
import Comment from 'components/comment';
export default class Thread extends Component {
constructor(props) {
super(props);
this.state = {
collapsed: false,
};
if (this.props.data && this.props.data.comment) {
this.updateCollapsedState(this.props.data.comment);
}
this.onCollapseToggle = this.onCollapseToggle.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.data && nextProps.data.comment) {
this.updateCollapsedState(nextProps.data.comment);
}
}
updateCollapsedState(comment) {
this.lsCollapsedID = `${siteId}_${url}_${comment.id}`;
this.state = {
collapsed: getCollapsedComments().includes(this.lsCollapsedID),
};
}
onCollapseToggle() {
const collapsed = !this.state.collapsed;
this.setState({ collapsed: !this.state.collapsed });
let collapsedComments = getCollapsedComments();
if (collapsed) {
if (!collapsedComments.includes(this.lsCollapsedID)) {
collapsedComments = collapsedComments.concat(this.lsCollapsedID);
}
} else {
collapsedComments = collapsedComments.filter(id => id !== this.lsCollapsedID);
}
saveCollapsedComments(collapsedComments);
}
render(props, { collapsed }) {
@@ -49,3 +79,11 @@ export default class Thread extends Component {
);
}
}
function getCollapsedComments() {
return JSON.parse(localStorage.getItem(LS_COLLAPSE_KEY) || '[]');
}
function saveCollapsedComments(comments) {
localStorage.setItem(LS_COLLAPSE_KEY, JSON.stringify(comments));
}