From 76dd445b5936a7bf3e8d69fcfc6a17704e98beba Mon Sep 17 00:00:00 2001 From: xaralis <filip.varecha@fragaria.cz> Date: Sat, 9 Jan 2021 09:11:58 +0100 Subject: [PATCH] feat: re-sort posts after ranking in a throttled manner --- src/containers/PostFilters.jsx | 6 +----- src/ws/handlers/posts.js | 23 +++++++++++++++++------ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/containers/PostFilters.jsx b/src/containers/PostFilters.jsx index 5ade1dd..b5e095d 100644 --- a/src/containers/PostFilters.jsx +++ b/src/containers/PostFilters.jsx @@ -22,16 +22,12 @@ const PostFilters = () => { { title: "Jen pĹ™ĂspÄ›vky", value: "discussionOnly" }, ]; - const setFilter = (prop, newValue, resetPage = true) => { + const setFilter = (prop, newValue) => { PostStore.update((state) => { state.filters[prop] = newValue; state.window.itemCount = state.window.items.length; updateWindowPosts(state); - - if (resetPage) { - state.window.page = 1; - } }); }; diff --git a/src/ws/handlers/posts.js b/src/ws/handlers/posts.js index d2bb0b3..ff99d14 100644 --- a/src/ws/handlers/posts.js +++ b/src/ws/handlers/posts.js @@ -1,9 +1,21 @@ import has from "lodash/has"; +import throttle from "lodash/throttle"; import { markdownConverter } from "markdown"; import { PostStore } from "stores"; import { parseRawPost, postsStateMapping, updateWindowPosts } from "utils"; +/** + * Re-apply sorting by rank but no more than once every 3 seconds. + */ +const sortOnRankThrottled = throttle(() => { + PostStore.update((state) => { + if (state.filters.sort === "byScore") { + updateWindowPosts(state); + } + }); +}, 3000); + export const handlePostRanked = (payload) => { PostStore.update((state) => { if (state.items[payload.id]) { @@ -12,12 +24,11 @@ export const handlePostRanked = (payload) => { state.items[payload.id].ranking.score = state.items[payload.id].ranking.likes - state.items[payload.id].ranking.dislikes; - - if (state.filters.sort === "byScore") { - updateWindowPosts(state); - } } }); + + // Run sorting in a throttled manner. + sortOnRankThrottled(); }; export const handlePostChanged = (payload) => { @@ -33,13 +44,13 @@ export const handlePostChanged = (payload) => { if (has(payload, "state")) { state.items[payload.id].state = postsStateMapping[payload.state]; + updateWindowPosts(state); } if (has(payload, "is_archived")) { state.items[payload.id].archived = payload.is_archived; + updateWindowPosts(state); } - - updateWindowPosts(state); } }); }; -- GitLab