Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add trending vote sort to topic voting plugin (#38839)

Régis HANOL1e03a43b37c4
diff --git a/frontend/discourse/app/components/d-navigation.gjs b/frontend/discourse/app/components/d-navigation.gjs
index 9bef4b76258..53b1d7f8636 100644
--- a/frontend/discourse/app/components/d-navigation.gjs
+++ b/frontend/discourse/app/components/d-navigation.gjs
@@ -153,7 +153,7 @@ export default class DNavigation extends Component {
"skipCategoriesNavItem"
)
get navItems() {
- return NavItem.buildList(this.category, {
+ const items = NavItem.buildList(this.category, {
filterType: this.filterType,
noSubcategories: this.noSubcategories,
currentRouteQueryParams: this.router?.currentRoute?.queryParams,
@@ -161,6 +161,12 @@ export default class DNavigation extends Component {
siteSettings: this.siteSettings,
skipCategoriesNavItem: this.skipCategoriesNavItem,
});
+
+ return applyValueTransformer("navigation-items", items, {
+ category: this.category,
+ tag: this.tag,
+ filterType: this.filterType,
+ });
}
@computed("filterType")
diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.js
index b7954ae2adc..1068537856b 100644
--- a/frontend/discourse/app/lib/registry/transformers.js
+++ b/frontend/discourse/app/lib/registry/transformers.js
@@ -72,6 +72,7 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"move-to-topic-move-options",
"navigation-bar-dropdown-icon",
"navigation-bar-dropdown-mode",
+ "navigation-items",
"notifications-tracking-description",
"parent-category-row-class",
"parent-category-row-class-mobile",
diff --git a/plugins/discourse-topic-voting/app/models/discourse_topic_voting/vote.rb b/plugins/discourse-topic-voting/app/models/discourse_topic_voting/vote.rb
index 5e0ccca637c..79e957a6537 100644
--- a/plugins/discourse-topic-voting/app/models/discourse_topic_voting/vote.rb
+++ b/plugins/discourse-topic-voting/app/models/discourse_topic_voting/vote.rb
@@ -14,13 +14,14 @@ end
# Table name: topic_voting_votes
#
# id :bigint not null, primary key
-# topic_id :integer
-# user_id :integer
# archive :boolean default(FALSE)
# created_at :datetime not null
# updated_at :datetime not null
+# topic_id :integer
+# user_id :integer
#
# Indexes
#
-# topic_voting_votes_user_id_topic_id_idx (user_id,topic_id) UNIQUE
+# index_topic_voting_votes_on_topic_id_and_created_at (topic_id,created_at)
+# topic_voting_votes_user_id_topic_id_idx (user_id,topic_id) UNIQUE
#
diff --git a/plugins/discourse-topic-voting/assets/javascripts/discourse/initializers/discourse-topic-voting.js b/plugins/discourse-topic-voting/assets/javascripts/discourse/initializers/discourse-topic-voting.js
index 125c4b6f6a3..d0a14a919b5 100644
--- a/plugins/discourse-topic-voting/assets/javascripts/discourse/initializers/discourse-topic-voting.js
+++ b/plugins/discourse-topic-voting/assets/javascripts/discourse/initializers/discourse-topic-voting.js
@@ -20,6 +20,19 @@ export default {
const siteSettings = api.container.lookup("service:site-settings");
if (siteSettings.topic_voting_enabled) {
+ api.registerValueTransformer(
+ "navigation-items",
+ ({ value, context }) => {
+ if (context.category?.can_vote) {
+ const hotItem = value.find((item) => item.name === "hot");
+ if (hotItem) {
+ hotItem.title = i18n("topic_voting.hot_nav_help");
+ }
+ }
+ return value;
+ }
+ );
+
const pageSearchController = api.container.lookup(
"controller:full-page-search"
);
@@ -29,43 +42,29 @@ export default {
term: "order:votes",
});
- api.addNavigationBarItem({
- name: "votes",
- before: "top",
- customFilter: (category) => {
- return category && category.can_vote;
- },
- customHref: (category, args) => {
- const path = NavItem.pathFor("latest", args);
- return `${path}?order=votes`;
- },
- forceActive: (category, args, router) => {
- const queryParams = router.currentRoute.queryParams;
- return (
- queryParams &&
- Object.keys(queryParams).length === 1 &&
- queryParams["order"] === "votes"
- );
- },
- });
- api.addNavigationBarItem({
- name: "my_votes",
- before: "top",
- customFilter: (category) => {
- return category && category.can_vote && api.getCurrentUser();
- },
- customHref: (category, args) => {
- const path = NavItem.pathFor("latest", args);
- return `${path}?state=my_votes`;
- },
- forceActive: (category, args, router) => {
- const queryParams = router.currentRoute.queryParams;
- return (
- queryParams &&
- Object.keys(queryParams).length === 1 &&
- queryParams["state"] === "my_votes"
- );
- },
+ const addVotingNavItem = (name, param, { requiresUser } = {}) => {
+ const [key, value] = param.split("=");
+ api.addNavigationBarItem({
+ name,
+ before: "top",
+ customFilter: (category) =>
+ category?.can_vote && (!requiresUser || api.getCurrentUser()),
+ customHref: (_category, args) =>
+ `${NavItem.pathFor("latest", args)}?${param}`,
+ forceActive: (_category, _args, router) => {
+ const queryParams = router.currentRoute.queryParams;
+ return (
+ queryParams &&
+ Object.keys(queryParams).length === 1 &&
+ queryParams[key] === value
+ );
+ },
+ });
+ };
+
+ addVotingNavItem("votes", "order=votes");
+ addVotingNavItem("my_votes", "state=my_votes", {
+ requiresUser: true,
});
}
diff --git a/plugins/discourse-topic-voting/config/locales/client.en.yml b/plugins/discourse-topic-voting/config/locales/client.en.yml
index 65ccc5e7eaf..4aa2e0fbed4 100755
--- a/plugins/discourse-topic-voting/config/locales/client.en.yml
+++ b/plugins/discourse-topic-voting/config/locales/client.en.yml
@@ -9,7 +9,8 @@ en:
title: "Topic voting"
reached_limit: "You are out of votes, remove an existing vote!"
list_votes: "List your votes"
- votes_nav_help: "topics with the most votes"
+ votes_nav_help: "topics with the all time most votes"
+ hot_nav_help: "top recent topics, including those with recent votes"
voted: "You voted on this topic"
allow_topic_voting: "Allow users to vote on topics in this category"
vote_title: "Vote"
@@ -33,7 +34,7 @@ en:
filters:
votes:
title: "Votes"
- help: "topics with the most votes"
+ help: "topics with the all time most votes"
my_votes:
title: "My Votes"
help: "topics you voted on"
diff --git a/plugins/discourse-topic-voting/db/migrate/20260324200000_add_topic_id_created_at_index_to_topic_voting_votes.rb b/plugins/discourse-topic-voting/db/migrate/20260324200000_add_topic_id_created_at_index_to_topic_voting_votes.rb
new file mode 100644
index 00000000000..fb32a9dea74
--- /dev/null
+++ b/plugins/discourse-topic-voting/db/migrate/20260324200000_add_topic_id_created_at_index_to_topic_voting_votes.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+class AddTopicIdCreatedAtIndexToTopicVotingVotes < ActiveRecord::Migration[7.2]
+ disable_ddl_transaction!
+
+ def up
+ remove_index :topic_voting_votes, %i[topic_id created_at], if_exists: true
+ add_index :topic_voting_votes, %i[topic_id created_at], algorithm: :concurrently
+ end
+
+ def down
+ remove_index :topic_voting_votes, %i[topic_id created_at], if_exists: true
+ end
+end
diff --git a/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_query_extension.rb b/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_query_extension.rb
index 5877dd7cc19..283c890b9e0 100644
--- a/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_query_extension.rb
+++ b/plugins/discourse-topic-voting/lib/discourse_topic_voting/topic_query_extension.rb
@@ -1,6 +1,14 @@
# frozen_string_literal: true
module DiscourseTopicVoting
+ TRENDING_SCORE_SQL = <<~SQL.squish
+ COALESCE((
+ SELECT SUM(1.0 / (EXTRACT(EPOCH FROM (NOW() - tv.created_at)) / 3600.0 + 2.0))
+ FROM topic_voting_votes tv
+ WHERE tv.topic_id = topics.id
+ ), 0)
+ SQL
+
module TopicQueryExtension
def list_voted_by(user)
create_list(:user_topics) do |topics|
@@ -17,5 +25,21 @@ module DiscourseTopicVoting
).order("COALESCE(dvtvc.votes_count,'0')::integer DESC, topics.bumped_at DESC")
end
end
+
+ def list_hot
+ category_id = get_category_id(@options[:category]) || @options[:category_id]
+ if category_id && Category.can_vote?(category_id)
+ create_list(:hot, unordered: true, prioritize_pinned: true) do |topics|
+ topics = remove_muted(topics, user, options)
+ topics.joins(
+ "LEFT JOIN topic_voting_topic_vote_count dvtvc ON dvtvc.topic_id = topics.id",
+ ).order(
+ "#{DiscourseTopicVoting::TRENDING_SCORE_SQL} DESC, COALESCE(dvtvc.votes_count, 0) DESC, topics.bumped_at DESC",
+ )
+ end
+ else
+ super
+ end
+ end
end
end
diff --git a/plugins/discourse-topic-voting/plugin.rb b/plugins/discourse-topic-voting/plugin.rb
index 009ff28f73b..29aa47ba0ee 100755
--- a/plugins/discourse-topic-voting/plugin.rb
+++ b/plugins/discourse-topic-voting/plugin.rb
@@ -165,12 +165,10 @@ after_initialize do
DiscourseTopicVoting::TopicVotesFilter.apply(scope, max_votes: value)
end
- filter_order_votes = ->(scope, order_direction, _guardian) do
+ add_filter_custom_filter("order:votes") do |scope, order_direction, _guardian|
DiscourseTopicVoting::TopicVotesFilter.apply(scope, order_direction:)
end
- add_filter_custom_filter("order:votes", &filter_order_votes)
-
on(:topic_status_updated) do |topic, status, enabled|
next if topic.trashed?
next if %w[closed autoclosed archived].exclude?(status)
diff --git a/plugins/discourse-topic-voting/spec/lib/topic_query_spec.rb b/plugins/discourse-topic-voting/spec/lib/topic_query_spec.rb
index ce3d6fbb1f0..4ad099f1148 100644
--- a/plugins/discourse-topic-voting/spec/lib/topic_query_spec.rb
+++ b/plugins/discourse-topic-voting/spec/lib/topic_query_spec.rb
@@ -42,4 +42,53 @@ describe TopicQuery do
[topic3.id],
)
end
+
+ describe "#list_hot" do
+ fab!(:voting_category, :category)
+ fab!(:non_voting_category, :category)
+
+ before { DiscourseTopicVoting::CategorySetting.create!(category: voting_category) }
+
+ it "uses vote-trending logic for voting categories" do
+ user1 = Fabricate(:user)
+ user2 = Fabricate(:user)
+
+ old_topic = Fabricate(:topic, category: voting_category)
+ DiscourseTopicVoting::Vote.create!(
+ topic_id: old_topic.id,
+ user_id: user1.id,
+ created_at: 60.days.ago,
+ )
+ DiscourseTopicVoting::Vote.create!(
+ topic_id: old_topic.id,
+ user_id: user2.id,
+ created_at: 60.days.ago,
+ )
+ DiscourseTopicVoting::TopicVoteCount.create!(topic_id: old_topic.id, votes_count: 2)
+
+ recent_topic = Fabricate(:topic, category: voting_category)
+ DiscourseTopicVoting::Vote.create!(
+ topic_id: recent_topic.id,
+ user_id: user1.id,
+ created_at: 1.hour.ago,
+ )
+ DiscourseTopicVoting::TopicVoteCount.create!(topic_id: recent_topic.id, votes_count: 1)
+
+ result = TopicQuery.new(user0, { category: voting_category.slug }).list_hot.topics.map(&:id)
+
+ expect(result.index(recent_topic.id)).to be < result.index(old_topic.id)
+ end
+
+ it "uses standard hot logic for non-voting categories" do
+ topic_a = Fabricate(:topic, category: non_voting_category)
+ topic_b = Fabricate(:topic, category: non_voting_category)
+ TopicHotScore.create!(topic_id: topic_a.id, score: 5.0)
+ TopicHotScore.create!(topic_id: topic_b.id, score: 10.0)
+
+ result =
+ TopicQuery.new(user0, { category: non_voting_category.slug }).list_hot.topics.map(&:id)
+
+ expect(result).to eq([topic_b.id, topic_a.id])
+ end
+ end
end
diff --git a/plugins/discourse-topic-voting/spec/system/voting_spec.rb b/plugins/discourse-topic-voting/spec/system/voting_spec.rb
index 6474f653c6a..7b4ba70aa5d 100644
--- a/plugins/discourse-topic-voting/spec/system/voting_spec.rb
+++ b/plugins/discourse-topic-voting/spec/system/voting_spec.rb
@@ -125,6 +125,27 @@ RSpec.describe "Topic voting" do
end
end
+ context "when viewing navigation tooltips" do
+ before { DiscourseTopicVoting::CategorySetting.create!(category: voting_category) }
+
+ it "shows custom tooltips in voting categories" do
+ category_page.visit(voting_category)
+
+ hot_item = find("#navigation-bar .nav-item_hot")
+ votes_item = find("#navigation-bar .nav-item_votes")
+
+ expect(hot_item["title"]).to eq(I18n.t("js.topic_voting.hot_nav_help"))
+ expect(votes_item["title"]).to eq(I18n.t("js.filters.votes.help"))
+ end
+
+ it "shows default Hot tooltip in non-voting categories" do
+ category_page.visit(category1)
+
+ hot_item = find("#navigation-bar .nav-item_hot")
+ expect(hot_item["title"]).to eq(I18n.t("js.filters.hot.help"))
+ end
+ end
+
context "when vote limits are disabled" do
fab!(:voting_post) { Fabricate(:post, topic: voting_topic1) }
fab!(:voting_post2) { Fabricate(:post, topic: voting_topic2) }