@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
61 lines • 3.1 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCommentsToTree = void 0;
var handleError_1 = require("../utils/handleError");
function addSingleCommentToTree(entityCommentsTree, newComment, newlyAdded) {
var _a, _b, _c;
var _d;
try {
if (newComment.parentId) {
// Previously, changing the comment sort order and triggering a fresh fetch caused issues: replies from previously loaded comments
// would sometimes be re-added to the comment tree, likely due to a state change triggering re-insertion before the UI fully cleared them.
// This led to partial items in the tree (replies without their parent comment), resulting in crashes.
//
// The condition below ensures we don't add replies if their parent comment isn't present.
// TODO: This solution prevents errors and serves as a useful safeguard. However, it's worth investigating why replies are re-fetching and attempting to re-add, as this causes redundant server calls, even though it no longer leads to errors.
if (!entityCommentsTree[newComment.parentId])
return entityCommentsTree;
return __assign(__assign({}, entityCommentsTree), (_a = {}, _a[newComment.parentId] = __assign(__assign({}, entityCommentsTree[newComment.parentId]), { replies: __assign(__assign({}, (((_d = entityCommentsTree[newComment.parentId]) === null || _d === void 0 ? void 0 : _d.replies) || [])), (_b = {}, _b[newComment.id] = __assign(__assign({}, newComment), { new: !!newlyAdded }), _b)) }), _a[newComment.id] = {
comment: newComment,
replies: {},
new: !!newlyAdded,
}, _a));
}
else {
return __assign(__assign({}, entityCommentsTree), (_c = {}, _c[newComment.id] = {
comment: newComment,
replies: {},
new: !!newlyAdded,
}, _c));
}
}
catch (err) {
(0, handleError_1.handleError)(err, "Failed to add a comment to the tree");
throw new Error();
}
}
var addCommentsToTree = function (setEntityCommentsTree, newComments, newlyAdded) {
setEntityCommentsTree(function (prevCommentsTree) {
var newTree = prevCommentsTree;
if (newComments) {
for (var _i = 0, newComments_1 = newComments; _i < newComments_1.length; _i++) {
var comment = newComments_1[_i];
newTree = addSingleCommentToTree(newTree, comment, newlyAdded);
}
}
return newTree;
});
};
exports.addCommentsToTree = addCommentsToTree;
//# sourceMappingURL=addCommentsToTree.js.map