stacker.news/lib/new-comments.js
soxa d4efacadc0
Fix count of viewed comments of a post (#2297)
* fix: parse existingRootComments as Number to correctly add new comments to the count

* return commentsViewedAt and commentsViewedNum parsed as Number

* hotfix: commentsViewedNum accepts itemId directly

* consistently receive itemId on new-comments functions that only uses IDs
2025-07-18 13:02:39 -05:00

36 lines
1.2 KiB
JavaScript

const COMMENTS_VIEW_PREFIX = 'commentsViewedAt'
const COMMENTS_NUM_PREFIX = 'commentsViewNum'
export function commentsViewed (item) {
if (!item.parentId && item.lastCommentAt) {
window.localStorage.setItem(`${COMMENTS_VIEW_PREFIX}:${item.id}`, new Date(item.lastCommentAt).getTime())
window.localStorage.setItem(`${COMMENTS_NUM_PREFIX}:${item.id}`, item.ncomments)
}
}
export function commentsViewedAt (itemId) {
return Number(window.localStorage.getItem(`${COMMENTS_VIEW_PREFIX}:${itemId}`))
}
export function commentsViewedNum (itemId) {
return Number(window.localStorage.getItem(`${COMMENTS_NUM_PREFIX}:${itemId}`))
}
export function commentsViewedAfterComment (rootId, createdAt) {
window.localStorage.setItem(`${COMMENTS_VIEW_PREFIX}:${rootId}`, new Date(createdAt).getTime())
window.localStorage.setItem(`${COMMENTS_NUM_PREFIX}:${rootId}`, commentsViewedNum(rootId) + 1)
}
export function newComments (item) {
if (!item.parentId) {
const viewedAt = commentsViewedAt(item.id)
const viewNum = commentsViewedNum(item.id)
if (viewedAt && viewNum) {
return viewedAt < new Date(item.lastCommentAt).getTime() || viewNum < item.ncomments
}
}
return false
}