From e5f9961a819dd2674016f7ae0f69da1744b61420 Mon Sep 17 00:00:00 2001 From: igoradamenko Date: Sun, 3 Jun 2018 17:37:25 +0300 Subject: [PATCH] save comments collapsed state closes #43 --- web/app/common/constants.js | 2 ++ web/app/components/thread/thread.jsx | 44 ++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/web/app/common/constants.js b/web/app/common/constants.js index 6a7c30b0..3060a35f 100644 --- a/web/app/common/constants.js +++ b/web/app/common/constants.js @@ -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, }; diff --git a/web/app/components/thread/thread.jsx b/web/app/components/thread/thread.jsx index aaf3628b..0ca3b3da 100644 --- a/web/app/components/thread/thread.jsx +++ b/web/app/components/thread/thread.jsx @@ -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)); +}