Files
NodeBB/public/src/client/topic/posts.js

413 lines
13 KiB
JavaScript
Raw Normal View History

'use strict';
define('forum/topic/posts', [
'forum/pagination',
'forum/infinitescroll',
'forum/topic/postTools',
2017-03-02 18:11:31 +03:00
'forum/topic/images',
'navigator',
2017-02-17 19:31:21 -07:00
'components',
2019-09-12 14:47:36 -04:00
'translator',
'hooks',
'helpers',
], function (pagination, infinitescroll, postTools, images, navigator, components, translator, hooks, helpers) {
const Posts = { };
Posts.onNewPost = function (data) {
2021-02-04 02:07:29 -07:00
if (
!data ||
!data.posts ||
!data.posts.length ||
parseInt(data.posts[0].tid, 10) !== parseInt(ajaxify.data.tid, 10)
) {
2015-09-13 15:14:29 -04:00
return;
}
data.loggedIn = !!app.user.uid;
2016-06-15 21:04:36 +03:00
data.privileges = ajaxify.data.privileges;
// if not a scheduled topic, prevent timeago in future by setting timestamp to 1 sec behind now
data.posts[0].timestamp = data.posts[0].topic.scheduled ? data.posts[0].timestamp : Date.now() - 1000;
data.posts[0].timestampISO = utils.toISOString(data.posts[0].timestamp);
2016-10-31 11:20:52 +03:00
Posts.modifyPostsByPrivileges(data.posts);
2015-09-29 16:36:37 -04:00
updatePostCounts(data.posts);
2016-05-09 23:39:00 +03:00
updatePostIndices(data.posts);
ajaxify.data.postcount += 1;
postTools.updatePostCount(ajaxify.data.postcount);
if (config.usePagination) {
onNewPostPagination(data);
} else {
onNewPostInfiniteScroll(data);
}
require(['forum/topic/replies'], function (replies) {
replies.onNewPost(data);
});
};
2016-10-31 11:20:52 +03:00
Posts.modifyPostsByPrivileges = function (posts) {
posts.forEach(function (post) {
post.selfPost = !!app.user.uid && parseInt(post.uid, 10) === parseInt(app.user.uid, 10);
2020-11-25 17:58:44 -05:00
post.topicOwnerPost = parseInt(post.uid, 10) === parseInt(ajaxify.data.uid, 10);
2016-10-31 11:20:52 +03:00
post.display_edit_tools = (ajaxify.data.privileges['posts:edit'] && post.selfPost) || ajaxify.data.privileges.isAdminOrMod;
post.display_delete_tools = (ajaxify.data.privileges['posts:delete'] && post.selfPost) || ajaxify.data.privileges.isAdminOrMod;
post.display_moderator_tools = post.display_edit_tools || post.display_delete_tools;
post.display_move_tools = ajaxify.data.privileges.isAdminOrMod;
2020-11-25 17:58:44 -05:00
post.display_post_menu = ajaxify.data.privileges.isAdminOrMod ||
(post.selfPost && !ajaxify.data.locked && !post.deleted) ||
(post.selfPost && post.deleted && parseInt(post.deleterUid, 10) === parseInt(app.user.uid, 10)) ||
((app.user.uid || ajaxify.data.postSharing.length) && !post.deleted);
2016-10-31 11:20:52 +03:00
});
};
function updatePostCounts(posts) {
for (let i = 0; i < posts.length; i += 1) {
const cmp = components.get('user/postcount', posts[i].uid);
cmp.html(parseInt(cmp.attr('data-postcount'), 10) + 1);
2015-03-27 16:27:28 -04:00
utils.addCommasToNumbers(cmp);
}
2015-09-13 15:14:29 -04:00
}
function updatePostIndices(posts) {
if (config.topicPostSort === 'newest_to_oldest') {
posts[0].index = 1;
components.get('post').not('[data-index=0]').each(function () {
const newIndex = parseInt($(this).attr('data-index'), 10) + 1;
$(this).attr('data-index', newIndex);
});
}
}
function onNewPostPagination(data) {
2015-02-17 18:52:54 -05:00
function scrollToPost() {
2016-03-21 10:16:10 +02:00
scrollToPostIfSelf(data.posts[0]);
2015-02-17 18:52:54 -05:00
}
const posts = data.posts;
2015-02-17 18:52:54 -05:00
2018-01-23 15:52:54 -05:00
ajaxify.data.pagination.pageCount = Math.max(1, Math.ceil(posts[0].topic.postcount / config.postsPerPage));
const direction = config.topicPostSort === 'oldest_to_newest' || config.topicPostSort === 'most_votes' ? 1 : -1;
const isPostVisible = (
2021-02-04 02:07:29 -07:00
ajaxify.data.pagination.currentPage === ajaxify.data.pagination.pageCount &&
direction === 1
) || (ajaxify.data.pagination.currentPage === 1 && direction === -1);
2015-02-17 18:52:54 -05:00
if (isPostVisible) {
const repliesSelector = $('[component="post"]:not([data-index=0]), [component="topic/event"]');
createNewPosts(data, repliesSelector, direction, false, scrollToPost);
} else if (ajaxify.data.scrollToMyPost && parseInt(posts[0].uid, 10) === parseInt(app.user.uid, 10)) {
2016-09-15 00:50:24 +03:00
// https://github.com/NodeBB/NodeBB/issues/5004#issuecomment-247157441
setTimeout(function () {
2016-09-15 00:50:24 +03:00
pagination.loadPage(ajaxify.data.pagination.pageCount, scrollToPost);
}, 250);
2016-05-09 23:39:00 +03:00
} else {
updatePagination();
}
}
2016-05-09 23:39:00 +03:00
function updatePagination() {
2017-02-18 12:30:49 -07:00
$.get(config.relative_path + '/api/topic/pagination/' + ajaxify.data.tid, { page: ajaxify.data.pagination.currentPage }, function (paginationData) {
2020-04-23 21:50:08 -04:00
app.parseAndTranslate('partials/paginator', paginationData, function (html) {
2016-05-09 23:39:00 +03:00
$('[component="pagination"]').after(html).remove();
});
});
}
function onNewPostInfiniteScroll(data) {
const direction = (config.topicPostSort === 'oldest_to_newest' || config.topicPostSort === 'most_votes') ? 1 : -1;
const isPreviousPostAdded = $('[component="post"][data-index="' + (data.posts[0].index - 1) + '"]').length;
2017-02-03 16:24:58 +03:00
if (!isPreviousPostAdded && (!data.posts[0].selfPost || !ajaxify.data.scrollToMyPost)) {
return;
}
2017-08-03 13:29:28 -04:00
if (!isPreviousPostAdded && data.posts[0].selfPost) {
return ajaxify.go('post/' + data.posts[0].pid);
}
const repliesSelector = $('[component="post"]:not([data-index=0]), [component="topic/event"]');
createNewPosts(data, repliesSelector, direction, false, function (html) {
if (html) {
html.addClass('new');
}
scrollToPostIfSelf(data.posts[0]);
});
}
function scrollToPostIfSelf(post) {
2017-02-03 16:24:58 +03:00
if (post.selfPost && ajaxify.data.scrollToMyPost) {
navigator.scrollBottom(post.index);
}
}
function createNewPosts(data, repliesSelector, direction, userScrolled, callback) {
callback = callback || function () {};
if (!data || (data.posts && !data.posts.length)) {
2015-02-26 15:14:27 -05:00
return callback();
}
function removeAlreadyAddedPosts() {
const newPosts = $('[component="post"].new');
if (newPosts.length === data.posts.length) {
let allSamePids = true;
newPosts.each(function (index, el) {
if (parseInt($(el).attr('data-pid'), 10) !== parseInt(data.posts[index].pid, 10)) {
allSamePids = false;
}
});
if (allSamePids) {
newPosts.each(function () {
$(this).removeClass('new');
});
data.posts.length = 0;
return;
}
}
if (newPosts.length && data.posts.length > 1) {
data.posts.forEach(function (post) {
const p = components.get('post', 'pid', post.pid);
if (p.hasClass('new')) {
2015-09-26 18:29:27 -04:00
p.remove();
}
});
}
2015-09-26 18:29:27 -04:00
data.posts = data.posts.filter(function (post) {
2015-10-04 01:13:47 -04:00
return $('[component="post"][data-pid="' + post.pid + '"]').length === 0;
});
}
removeAlreadyAddedPosts();
2015-02-26 15:14:27 -05:00
if (!data.posts.length) {
return callback();
}
let after;
let before;
if (direction > 0 && repliesSelector.length) {
after = repliesSelector.last();
} else if (direction < 0 && repliesSelector.length) {
before = repliesSelector.first();
}
hooks.fire('action:posts.loading', { posts: data.posts, after: after, before: before });
2015-07-20 17:12:41 -04:00
app.parseAndTranslate('topic', 'posts', Object.assign({}, ajaxify.data, data), function (html) {
html = html.filter(function () {
const pid = $(this).attr('data-pid');
const isPost = $(this).is('[component="post"]');
return !isPost || (pid && $('[component="post"][data-pid="' + pid + '"]').length === 0);
2016-03-24 22:22:07 +02:00
});
2015-02-26 15:14:27 -05:00
if (after) {
html.insertAfter(after);
2015-02-26 15:14:27 -05:00
} else if (before) {
// Save document height and position for future reference (about 5 lines down)
const height = $(document).height();
const scrollTop = $(window).scrollTop();
html.insertBefore(before);
// Now restore the relative position the user was on prior to new post insertion
if (userScrolled || scrollTop > 0) {
$(window).scrollTop(scrollTop + ($(document).height() - height));
}
} else {
components.get('topic').append(html);
}
infinitescroll.removeExtra($('[component="post"]'), direction, Math.max(20, config.postsPerPage * 2));
2015-09-26 18:29:27 -04:00
hooks.fire('action:posts.loaded', { posts: data.posts });
Posts.onNewPostsAddedToDom(html);
2015-09-29 16:36:37 -04:00
callback(html);
});
}
Posts.loadMorePosts = function (direction) {
if (!components.get('topic').length || navigator.scrollActive) {
return;
}
const replies = components.get('topic').find(components.get('post').not('[data-index=0]').not('.new'));
const afterEl = direction > 0 ? replies.last() : replies.first();
const after = parseInt(afterEl.attr('data-index'), 10) || 0;
const tid = ajaxify.data.tid;
if (!utils.isNumber(tid) || !utils.isNumber(after) || (direction < 0 && components.get('post', 'index', 0).length)) {
return;
}
const indicatorEl = $('.loading-indicator');
if (!indicatorEl.is(':animated')) {
indicatorEl.fadeIn();
}
infinitescroll.loadMore('topics.loadMore', {
tid: tid,
after: after,
2017-03-10 12:50:19 -05:00
count: config.postsPerPage,
2016-08-31 22:50:48 +03:00
direction: direction,
2017-02-17 19:31:21 -07:00
topicPostSort: config.topicPostSort,
}, function (data, done) {
indicatorEl.fadeOut();
if (data && data.posts && data.posts.length) {
const repliesSelector = $('[component="post"]:not([data-index=0]):not(.new), [component="topic/event"]');
createNewPosts(data, repliesSelector, direction, true, done);
} else {
navigator.update();
done();
}
});
};
Posts.onTopicPageLoad = function (posts) {
handlePrivateUploads(posts);
2018-11-29 11:26:57 -05:00
images.wrapImagesInLinks(posts);
2015-10-24 22:29:22 -04:00
Posts.showBottomPostBar();
2015-11-10 13:18:06 -05:00
posts.find('[component="post/content"] img:not(.not-responsive)').addClass('img-responsive');
2019-01-25 11:08:51 -05:00
Posts.addBlockquoteEllipses(posts);
hidePostToolsForDeletedPosts(posts);
addNecroPostMessage();
};
Posts.addTopicEvents = function (events) {
const html = helpers.renderEvents.call(ajaxify.data, events);
translator.translate(html, (translated) => {
document.querySelector('[component="topic"]').insertAdjacentHTML('beforeend', translated);
$('[component="topic/event"] .timeago').timeago();
});
};
function addNecroPostMessage(callback) {
const necroThreshold = ajaxify.data.necroThreshold * 24 * 60 * 60 * 1000;
if (!necroThreshold || (config.topicPostSort !== 'newest_to_oldest' && config.topicPostSort !== 'oldest_to_newest')) {
return callback && callback();
2019-08-27 10:00:13 -04:00
}
const postEls = $('[component="post"]').toArray();
Promise.all(postEls.map(function (post) {
post = $(post);
const prev = post.prev('[component="post"]');
2019-06-27 12:05:31 -04:00
if (post.is(':has(.necro-post)') || !prev.length) {
return;
}
2019-08-27 10:00:13 -04:00
if (config.topicPostSort === 'newest_to_oldest' && parseInt(prev.attr('data-index'), 10) === 0) {
return;
}
2019-06-27 12:05:31 -04:00
const diff = post.attr('data-timestamp') - prev.attr('data-timestamp');
return new Promise(function (resolve) {
if (Math.abs(diff) >= necroThreshold) {
const suffixAgo = $.timeago.settings.strings.suffixAgo;
const prefixAgo = $.timeago.settings.strings.prefixAgo;
const suffixFromNow = $.timeago.settings.strings.suffixFromNow;
const prefixFromNow = $.timeago.settings.strings.prefixFromNow;
$.timeago.settings.strings.suffixAgo = '';
$.timeago.settings.strings.prefixAgo = '';
$.timeago.settings.strings.suffixFromNow = '';
$.timeago.settings.strings.prefixFromNow = '';
const translationText = (diff > 0 ? '[[topic:timeago_later,' : '[[topic:timeago_earlier,') + $.timeago.inWords(diff) + ']]';
$.timeago.settings.strings.suffixAgo = suffixAgo;
$.timeago.settings.strings.prefixAgo = prefixAgo;
$.timeago.settings.strings.suffixFromNow = suffixFromNow;
$.timeago.settings.strings.prefixFromNow = prefixFromNow;
app.parseAndTranslate('partials/topic/necro-post', { text: translationText }, function (html) {
html.insertBefore(post);
resolve();
});
} else {
resolve();
}
});
})).then(function () {
2021-08-10 21:19:01 -04:00
if (typeof callback === 'function') {
callback();
}
2019-06-27 12:05:31 -04:00
});
}
function handlePrivateUploads(posts) {
if (app.user.uid || !ajaxify.data.privateUploads) {
return;
}
// Replace all requests for uploaded images/files with a login link
const loginEl = document.createElement('a');
loginEl.className = 'login-required';
loginEl.href = config.relative_path + '/login';
2019-09-12 14:47:36 -04:00
translator.translate('[[topic:login-to-view]]', function (translated) {
loginEl.appendChild(document.createTextNode(translated));
posts.each(function (idx, postEl) {
$(postEl).find('[component="post/content"] img').each(function (idx, imgEl) {
imgEl = $(imgEl);
if (imgEl.attr('src').startsWith(config.relative_path + config.upload_url)) {
imgEl.replaceWith(loginEl.cloneNode(true));
}
});
});
});
}
Posts.onNewPostsAddedToDom = function (posts) {
Posts.onTopicPageLoad(posts);
app.createUserTooltips(posts);
2015-05-29 16:19:04 -04:00
utils.addCommasToNumbers(posts.find('.formatted-number'));
utils.makeNumbersHumanReadable(posts.find('.human-readable-number'));
posts.find('.timeago').timeago();
2015-10-28 15:16:14 -04:00
};
Posts.showBottomPostBar = function () {
const mainPost = components.get('post', 'index', 0);
const placeHolder = $('.post-bar-placeholder');
const posts = $('[component="post"]');
2016-07-06 12:25:57 +03:00
if (!!mainPost.length && posts.length > 1 && $('.post-bar').length < 2 && placeHolder.length) {
$('.post-bar').clone().insertAfter(placeHolder);
placeHolder.remove();
2015-10-24 23:03:12 -04:00
} else if (mainPost.length && posts.length < 2) {
mainPost.find('.post-bar').remove();
2015-10-24 22:29:22 -04:00
}
2015-10-15 12:18:21 -04:00
};
2015-05-29 16:19:04 -04:00
function hidePostToolsForDeletedPosts(posts) {
posts.each(function () {
2015-05-29 16:19:04 -04:00
if ($(this).hasClass('deleted')) {
2015-07-06 12:39:05 -04:00
postTools.toggle($(this).attr('data-pid'), true);
2015-05-29 16:19:04 -04:00
}
});
}
2019-01-25 11:08:51 -05:00
Posts.addBlockquoteEllipses = function (posts) {
const blockquotes = posts.find('[component="post/content"] > blockquote > blockquote');
blockquotes.each(function () {
const $this = $(this);
if ($this.find(':hidden:not(br)').length && !$this.find('.toggle').length) {
$this.append('<i class="fa fa-angle-down pointer toggle"></i>');
}
});
2019-01-25 11:08:51 -05:00
};
return Posts;
});