Skip to content

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

DEV: Include reaction data on the topic list (#35843)

Isaac Janzenbb79b653b505
diff --git a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs
index 54025478363..bb14c7ebd6f 100644
--- a/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs
+++ b/plugins/discourse-reactions/assets/javascripts/discourse/components/discourse-reactions-actions.gjs
@@ -117,22 +117,26 @@ export default class DiscourseReactionsActions extends Component {
@service siteSettings;
@service site;
@service currentUser;
+ @service appEvents;
@tracked reactionsPickerExpanded = false;
@tracked statePanelExpanded = false;
@tracked clickOutsideDisabled = false;
+ get data() {
+ return this.args.post;
+ }
+
get classes() {
- const { post } = this.args;
- if (!post.reactions) {
+ if (!this.data?.reactions) {
return;
}
- const hasReactions = post.reactions.length;
- const hasReacted = post.current_user_reaction;
+ const hasReactions = this.data.reactions.length;
+ const hasReacted = this.data.current_user_reaction;
const customReactionUsed =
- post.reactions.length &&
- post.reactions.filter(
+ this.data.reactions.length &&
+ this.data.reactions.filter(
(reaction) =>
reaction.id !==
this.siteSettings.discourse_reactions_reaction_for_like
@@ -143,7 +147,7 @@ export default class DiscourseReactionsActions extends Component {
classes.push("custom-reaction-used");
}
- if (post.yours) {
+ if (this.data.yours) {
classes.push("my-post");
}
@@ -155,13 +159,14 @@ export default class DiscourseReactionsActions extends Component {
classes.push("has-reacted");
}
- if (post.current_user_used_main_reaction) {
+ if (this.data.current_user_used_main_reaction) {
classes.push("has-used-main-reaction");
}
if (
- (!post.current_user_reaction || post.current_user_reaction.can_undo) &&
- post.likeAction?.canToggle
+ (!this.data.current_user_reaction ||
+ this.data.current_user_reaction.can_undo) &&
+ this.data.likeAction?.canToggle
) {
classes.push("can-toggle-reaction");
}
@@ -258,9 +263,10 @@ export default class DiscourseReactionsActions extends Component {
) ||
event.target.classList.contains("reaction-button"))
) {
+ const data = this.data;
this.toggleFromButton({
- reaction: this.args.post.current_user_reaction
- ? this.args.post.current_user_reaction.id
+ reaction: data.current_user_reaction
+ ? data.current_user_reaction.id
: this.siteSettings.discourse_reactions_reaction_for_like,
});
}
@@ -277,9 +283,9 @@ export default class DiscourseReactionsActions extends Component {
}
if (
- !this.args.post.current_user_reaction ||
- (this.args.post.current_user_reaction.can_undo &&
- this.args.post.likeAction.canToggle)
+ !this.data.current_user_reaction ||
+ (this.data.current_user_reaction.can_undo &&
+ this.data.likeAction?.canToggle)
) {
if (this.capabilities.userHasBeenActive && this.capabilities.canVibrate) {
navigator.vibrate(VIBRATE_DURATION);
@@ -297,38 +303,37 @@ export default class DiscourseReactionsActions extends Component {
return new Promise((resolve) => {
if (!pickedReaction) {
this.toggleReaction(params);
- const post = this.args.post;
- CustomReaction.toggle(post, params.reaction)
+ CustomReaction.toggle(this.data, params.reaction, this.appEvents)
.then(resolve)
.catch((err) => {
this.dialog.alert(this._extractErrors(err));
- this._rollbackState(post);
+ this._rollbackState(this.data);
});
} else {
scaleReactionAnimation(pickedReaction, scales[0], scales[1], () => {
scaleReactionAnimation(pickedReaction, scales[1], scales[0], () => {
- const post = this.args.post;
const postContainer = document.querySelector(
`[data-post-id="${params.postId}"]`
);
if (
- post.current_user_reaction &&
- post.current_user_reaction.id === params.reaction
+ this.data.current_user_reaction &&
+ this.data.current_user_reaction.id === params.reaction
) {
this.toggleReaction(params);
later(() => {
dropReaction(postContainer, params.reaction, () => {
return CustomReaction.toggle(
- this.args.post,
- params.reaction
+ this.data,
+ params.reaction,
+ this.appEvents
)
.then(resolve)
.catch((err) => {
this.dialog.alert(this._extractErrors(err));
- this._rollbackState(post);
+ this._rollbackState(this.data);
});
});
}, 100);
@@ -336,11 +341,15 @@ export default class DiscourseReactionsActions extends Component {
addReaction(postContainer, params.reaction, () => {
this.toggleReaction(params);
- CustomReaction.toggle(this.args.post, params.reaction)
+ CustomReaction.toggle(
+ this.data,
+ params.reaction,
+ this.appEvents
+ )
.then(resolve)
.catch((err) => {
this.dialog.alert(this._extractErrors(err));
- this._rollbackState(post);
+ this._rollbackState(this.data);
});
});
}
@@ -357,25 +366,23 @@ export default class DiscourseReactionsActions extends Component {
this.collapseAllPanels();
if (
- this.args.post.current_user_reaction &&
- !this.args.post.current_user_reaction.can_undo &&
- !this.args.post.likeAction.canToggle
+ this.data.current_user_reaction &&
+ !this.data.current_user_reaction.can_undo &&
+ !this.data.likeAction?.canToggle
) {
return;
}
- const post = this.args.post;
-
- if (post.current_user_reaction) {
- post.reactions.every((reaction, index) => {
+ if (this.data.current_user_reaction) {
+ this.data.reactions.every((reaction, index) => {
if (
reaction.count <= 1 &&
- reaction.id === post.current_user_reaction.id
+ reaction.id === this.data.current_user_reaction.id
) {
- post.reactions.splice(index, 1);
+ this.data.reactions.splice(index, 1);
return false;
- } else if (reaction.id === post.current_user_reaction.id) {
- post.reactions[index].count -= 1;
+ } else if (reaction.id === this.data.current_user_reaction.id) {
+ this.data.reactions[index].count -= 1;
return false;
}
@@ -386,14 +393,14 @@ export default class DiscourseReactionsActions extends Component {
if (
attrs.reaction &&
- (!post.current_user_reaction ||
- attrs.reaction !== post.current_user_reaction.id)
+ (!this.data.current_user_reaction ||
+ attrs.reaction !== this.data.current_user_reaction.id)
) {
let isAvailable = false;
- post.reactions.every((reaction, index) => {
+ this.data.reactions.every((reaction, index) => {
if (reaction.id === attrs.reaction) {
- post.reactions[index].count += 1;
+ this.data.reactions[index].count += 1;
isAvailable = true;
return false;
}
@@ -407,7 +414,7 @@ export default class DiscourseReactionsActions extends Component {
count: 1,
};
- const tempReactions = Object.assign([], post.reactions);
+ const tempReactions = Object.assign([], this.data.reactions);
tempReactions.push(newReaction);
@@ -431,36 +438,36 @@ export default class DiscourseReactionsActions extends Component {
})
.indexOf(newReaction);
- post.reactions.splice(newReactionIndex, 0, newReaction);
+ this.data.reactions.splice(newReactionIndex, 0, newReaction);
}
- if (!post.current_user_reaction) {
- post.reaction_users_count += 1;
+ if (!this.data.current_user_reaction) {
+ this.data.reaction_users_count += 1;
}
- post.current_user_reaction = {
+ this.data.current_user_reaction = {
id: attrs.reaction,
type: "emoji",
can_undo: true,
};
} else {
- post.reaction_users_count -= 1;
- post.current_user_reaction = null;
+ this.data.reaction_users_count -= 1;
+ this.data.current_user_reaction = null;
}
if (
- post.current_user_reaction &&
- post.current_user_reaction.id ===
+ this.data.current_user_reaction &&
+ this.data.current_user_reaction.id ===
this.siteSettings.discourse_reactions_reaction_for_like
) {
- post.current_user_used_main_reaction = true;
+ this.data.current_user_used_main_reaction = true;
} else {
- post.current_user_used_main_reaction = false;
+ this.data.current_user_used_main_reaction = false;
}
// Trigger re-render for anything autotracking reactions.
// In future, we should make reactions a deeply-trackable structure.
// eslint-disable-next-line no-self-assign
- post.reactions = post.reactions;
+ this.data.reactions = this.data.reactions;
}
@action
@@ -475,24 +482,23 @@ export default class DiscourseReactionsActions extends Component {
const mainReactionName =
this.siteSettings.discourse_reactions_reaction_for_like;
- const post = this.args.post;
- const current_user_reaction = post.current_user_reaction;
+ const current_user_reaction = this.data.current_user_reaction;
if (
- post.likeAction &&
- !(post.likeAction.canToggle || post.likeAction.can_undo)
+ this.data.likeAction &&
+ !(this.data.likeAction.canToggle || this.data.likeAction.can_undo)
) {
return;
}
if (
- this.args.post.current_user_reaction &&
- !this.args.post.current_user_reaction.can_undo
+ this.data.current_user_reaction &&
+ !this.data.current_user_reaction.can_undo
) {
return;
}
- if (!this.currentUser || post.user_id === this.currentUser.id) {
+ if (!this.currentUser || this.data.user_id === this.currentUser.id) {
return;
}
@@ -502,26 +508,28 @@ export default class DiscourseReactionsActions extends Component {
if (current_user_reaction && current_user_reaction.id === attrs.reaction) {
this.toggleReaction(attrs);
- return CustomReaction.toggle(this.args.post, attrs.reaction).catch(
- (e) => {
- this.dialog.alert(this._extractErrors(e));
- this._rollbackState(post);
- }
- );
+ return CustomReaction.toggle(
+ this.data,
+ attrs.reaction,
+ this.appEvents
+ ).catch((e) => {
+ this.dialog.alert(this._extractErrors(e));
+ this._rollbackState(this.data);
+ });
}
let selector;
if (
- post.reactions &&
- post.reactions.length === 1 &&
- post.reactions[0].id === mainReactionName
+ this.data.reactions &&
+ this.data.reactions.length === 1 &&
+ this.data.reactions[0].id === mainReactionName
) {
- selector = `[data-post-id="${this.args.post.id}"] .discourse-reactions-double-button .discourse-reactions-reaction-button .d-icon`;
+ selector = `[data-post-id="${this.data.id}"] .discourse-reactions-double-button .discourse-reactions-reaction-button .d-icon`;
} else {
if (!attrs.reaction || attrs.reaction === mainReactionName) {
- selector = `[data-post-id="${this.args.post.id}"] .discourse-reactions-reaction-button .d-icon`;
+ selector = `[data-post-id="${this.data.id}"] .discourse-reactions-reaction-button .d-icon`;
} else {
- selector = `[data-post-id="${this.args.post.id}"] .discourse-reactions-reaction-button .reaction-button .btn-toggle-reaction-emoji`;
+ selector = `[data-post-id="${this.data.id}"] .discourse-reactions-reaction-button .reaction-button .btn-toggle-reaction-emoji`;
}
}
@@ -538,11 +546,11 @@ export default class DiscourseReactionsActions extends Component {
? attrs.reaction
: this.siteSettings.discourse_reactions_reaction_for_like;
- CustomReaction.toggle(this.args.post, toggleReaction)
+ CustomReaction.toggle(this.data, toggleReaction, this.appEvents)
.then(resolve)
.catch((err) => {
this.dialog.alert(this._extractErrors(err));
- this._rollbackState(post);
+ this._rollbackState(this.data);
});
});
});
@@ -583,7 +591,10 @@ export default class DiscourseReactionsActions extends Component {
}
get elementId() {
- return `discourse-reactions-actions-${this.args.post.id}-${
+ if (!this.data?.id) {
+ return null;
+ }
+ return `discourse-reactions-actions-${this.data.id}-${
this.args.position || "right"
}`;
}
@@ -654,7 +665,10 @@ export default class DiscourseReactionsActions extends Component {
_setupPopper(selectors) {
schedule("afterRender", () => {
const position = this.args.position || "right";
- const id = this.args.post.id;
+ if (!this.data?.id) {
+ return;
+ }
+ const id = this.data.id;
const trigger = document.querySelector(
`#discourse-reactions-actions-${id}-${position} ${selectors[0]}`
);
@@ -724,8 +738,8 @@ export default class DiscourseReactionsActions extends Component {
get onlyOneMainReaction() {
return (
- this.args.post.reactions?.length === 1 &&
- this.args.post.reactions[0].id ===
+ this.data.reactions?.length === 1 &&
+ this.data.reactions[0].id ===
this.siteSettings.discourse_reactions_reaction_for_like
);
}
@@ -733,7 +747,7 @@ export default class DiscourseReactionsActions extends Component {
get showReactionsPicker() {
return (
this.currentUser &&
- this.args.post.user_id !== this.currentUser.id &&
+ this.data.user_id !== this.currentUser.id &&
this.reactionsPickerExpanded
);
}
@@ -752,7 +766,7 @@ export default class DiscourseReactionsActions extends Component {
counter=(curryComponent
DiscourseReactionsCounter
(lazyHash
- post=@post
+ post=this.data
position=@position
reactionsPickerExpanded=this.reactionsPickerExpanded
statePanelExpanded=this.statePanelExpanded
@@ -767,7 +781,7 @@ export default class DiscourseReactionsActions extends Component {
button=(curryComponent
DiscourseReactionsReactionButton
(lazyHash
- post=@post
+ post=this.data
position=@position
cancelCollapse=this.cancelCollapse
toggleFromButton=this.toggleFromButton
@@ -781,7 +795,7 @@ export default class DiscourseReactionsActions extends Component {
}}
{{#if this.showReactionsPicker}}
<DiscourseReactionsPicker
- @post={{@post}}
+ @post={{this.data}}
@scheduleCollapse={{this.scheduleCollapse}}
@cancelCollapse={{this.cancelCollapse}}
@disableClickOutside={{this.disableClickOutside}}
@@ -795,18 +809,20 @@ export default class DiscourseReactionsActions extends Component {
<components.counter />
{{else if this.onlyOneMainReaction}}
<DiscourseReactionsDoubleButton
- @post={{@post}}
+ @post={{this.data}}
@counterComponent={{components.counter}}
@buttonComponent={{components.button}}
/>
{{else if this.site.mobileView}}
- {{#if (not @post.yours)}}
+ {{#if (not this.data.yours)}}
<components.counter />
<components.button />
- {{else if (and @post.yours @post.reactions @post.reactions.length)}}
+ {{else if
+ (and this.data.yours this.data.reactions this.data.reactions.length)
+ }}
<components.counter />
{{/if}}
- {{else if (not @post.yours)}}
+ {{else if (not this.data.yours)}}
<components.button />
{{/if}}
{{/let}}
diff --git a/plugins/discourse-reactions/assets/javascripts/discourse/models/discourse-reactions-custom-reaction.js b/plugins/discourse-reactions/assets/javascripts/discourse/models/discourse-reactions-custom-reaction.js
index caac3893d8b..103d97a0651 100644
--- a/plugins/discourse-reactions/assets/javascripts/discourse/models/discourse-reactions-custom-reaction.js
+++ b/plugins/discourse-reactions/assets/javascripts/discourse/models/discourse-reactions-custom-reaction.js
@@ -7,12 +7,12 @@ import Topic from "discourse/models/topic";
import User from "discourse/models/user";
export default class CustomReaction extends RestModel {
- static toggle(post, reactionId) {
+ static toggle(post, reactionId, appEvents) {
return ajax(
`/discourse-reactions/posts/${post.id}/custom-reactions/${reactionId}/toggle.json`,
{ type: "PUT" }
).then((result) => {
- post.appEvents.trigger("discourse-reactions:reaction-toggled", {
+ appEvents.trigger("discourse-reactions:reaction-toggled", {
post: result,
reaction: result.current_user_reaction,
});
diff --git a/plugins/discourse-reactions/plugin.rb b/plugins/discourse-reactions/plugin.rb
index bb66aa4a0dc..b5dd8f2aa09 100644
--- a/plugins/discourse-reactions/plugin.rb
+++ b/plugins/discourse-reactions/plugin.rb
@@ -62,129 +62,191 @@ after_initialize do
Discourse::Application.routes.append { mount DiscourseReactions::Engine, at: "/" }
- add_to_serializer(:post, :reactions) do
- reactions = []
- reaction_users_counting_as_like = Set.new
-
- object
- .emoji_reactions
- .select { |reaction| reaction[:reaction_users_count] }
- .each do |reaction|
- reactions << {
- id: reaction.reaction_value,
- type: reaction.reaction_type.to_sym,
- count: reaction.reaction_users_count,
- }
-
- # NOTE: It does not matter if the reaction is currently an enabled one,
- # we need to handle historical data here too so we don't see double-ups in the UI.
- if !DiscourseReactions::Reaction.reactions_excluded_from_like.include?(
- reaction.reaction_value,
- ) && reaction.reaction_value != DiscourseReactions::Reaction.main_reaction_id
- reaction_users_counting_as_like.merge(reaction.reaction_users.pluck(:user_id))
+ # Helper module for shared reactions serialization logic
+ module ReactionsSerializerHelpers
+ def self.reactions_for_post(post)
+ reactions = []
+ reaction_users_counting_as_like = Set.new
+
+ post
+ .emoji_reactions
+ .select { |reaction| reaction[:reaction_users_count] }
+ .each do |reaction|
+ reactions << {
+ id: reaction.reaction_value,
+ type: reaction.reaction_type.to_sym,
+ count: reaction.reaction_users_count,
+ }
+
+ # NOTE: It does not matter if the reaction is currently an enabled one,
+ # we need to handle historical data here too so we don't see double-ups in the UI.
+ if !DiscourseReactions::Reaction.reactions_excluded_from_like.include?(
+ reaction.reaction_value,
+ ) && reaction.reaction_value != DiscourseReactions::Reaction.main_reaction_id
+ reaction_users_counting_as_like.merge(reaction.reaction_users.pluck(:user_id))
+ end
end
- end
- likes =
- object.post_actions.reject do |post_action|
- # Get rid of any PostAction records that match up to a ReactionUser
- # that is NOT main_reaction_id and is NOT excluded, otherwise we double
- # up on the count/reaction shown in the UI.
- next true if reaction_users_counting_as_like.include?(post_action.user_id)
-
- # Also get rid of any PostAction records that match up to a ReactionUser
- # that is now the main_reaction_id and has historical data.
- object
- .post_actions_with_reaction_users
- &.dig(post_action.id)
- &.reaction_user
- &.reaction
- &.reaction_value == DiscourseReactions::Reaction.main_reaction_id
- end
+ likes =
+ post.post_actions.reject do |post_action|
+ # Get rid of any PostAction records that match up to a ReactionUser
+ # that is NOT main_reaction_id and is NOT excluded, otherwise we double
+ # up on the count/reaction shown in the UI.
+ next true if reaction_users_counting_as_like.include?(post_action.user_id)
+
+ # Also get rid of any PostAction records that match up to a ReactionUser
+ # that is now the main_reaction_id and has historical data.
+ post
+ .post_actions_with_reaction_users
+ &.dig(post_action.id)
+ &.reaction_user
+ &.reaction
+ &.reaction_value == DiscourseReactions::Reaction.main_reaction_id
+ end
- # Likes will only be blank if there are only reactions where the reaction is in
- # discourse_reactions_excluded_from_like. All other reactions will have a `PostAction` record.
- return reactions.sort_by { |reaction| [-reaction[:count].to_i, reaction[:id]] } if likes.blank?
+ # Likes will only be blank if there are only reactions where the reaction is in
+ # discourse_reactions_excluded_from_like. All other reactions will have a `PostAction` record.
+ if likes.blank?
+ return(reactions.sort_by { |reaction| [-reaction[:count].to_i, reaction[:id]] })
+ end
- # Reactions using main_reaction_id only have a `PostAction` record,
- # not any `ReactionUser` records, as long as the main_reaction_id was never
- # changed -- if it was then we could have a ReactionUser as well.
- reaction_likes, reactions =
- reactions.partition { |r| r[:id] == DiscourseReactions::Reaction.main_reaction_id }
+ # Reactions using main_reaction_id only have a `PostAction` record,
+ # not any `ReactionUser` records, as long as the main_reaction_id was never
+ # changed -- if it was then we could have a ReactionUser as well.
+ reaction_likes, reactions =
+ reactions.partition { |r| r[:id] == DiscourseReactions::Reaction.main_reaction_id }
- reactions << {
- id: DiscourseReactions::Reaction.main_reaction_id,
- type: :emoji,
- count: likes.size + reaction_likes.sum { |r| r[:count] },
- }
+ reactions << {
+ id: DiscourseReactions::Reaction.main_reaction_id,
+ type: :emoji,
+ count: likes.size + reaction_likes.sum { |r| r[:count] },
+ }
- reactions.sort_by { |reaction| [-reaction[:count].to_i, reaction[:id]] }
- end
+ reactions.sort_by { |reaction| [-reaction[:count].to_i, reaction[:id]] }
+ end
- add_to_serializer(:post, :current_user_reaction) do
- return nil if scope.is_anonymous?
+ def self.current_user_reaction_for_post(post, scope)
+ return nil if scope.is_anonymous?
- object.emoji_reactions.each do |reaction|
- reaction_user = reaction.reaction_users.find { |ru| ru.user_id == scope.user.id }
- next if reaction_user.blank?
+ post.emoji_reactions.each do |reaction|
+ reaction_user = reaction.reaction_users.find { |ru| ru.user_id == scope.user.id }
+ next if reaction_user.blank?
- if reaction.reaction_users_count
- return(
- {
- id: reaction.reaction_value,
- type: reaction.reaction_type.to_sym,
- can_undo: reaction_user.can_undo?,
- }
- )
+ if reaction.reaction_users_count
+ return(
+ {
+ id: reaction.reaction_value,
+ type: reaction.reaction_type.to_sym,
+ can_undo: reaction_user.can_undo?,
+ }
+ )
+ end
end
+
+ # Any PostAction Like that doesn't have a matching ReactionUser record
+ # will count as the main_reaction_id.
+ like =
+ post.post_actions.find do |post_action|
+ post_action.post_action_type_id == PostActionType::LIKE_POST_ACTION_ID &&
+ !post_action.trashed? && post_action.user_id == scope.user.id
+ end
+
+ return nil if like.blank?
+
+ {
+ id: DiscourseReactions::Reaction.main_reaction_id,
+ type: :emoji,
+ can_undo: scope.can_delete_post_action?(like),
+ }
end
- # Any PostAction Like that doesn't have a matching ReactionUser record
- # will count as the main_reaction_id.
- like =
- object.post_actions.find do |post_action|
- post_action.post_action_type_id == PostActionType::LIKE_POST_ACTION_ID &&
- !post_action.trashed? && post_action.user_id == scope.user.id
- end
+ def self.reaction_users_count_for_post(post)
+ return post.reaction_users_count unless post.reaction_users_count.nil?
+ TopicViewSerializer.posts_reaction_users_count(post.id)[post.id]
+ end
- return nil if like.blank?
+ def self.current_user_used_main_reaction_for_post(post, scope)
+ return false if scope.is_anonymous?
- {
- id: DiscourseReactions::Reaction.main_reaction_id,
- type: :emoji,
- can_undo: scope.can_delete_post_action?(like),
- }
+ like_post_action =
+ post.post_actions.find do |post_action|
+ post_action.post_action_type_id == PostActionType::LIKE_POST_ACTION_ID &&
+ post_action.user_id == scope.user.id && !post_action.trashed?
+ end
+
+ has_matching_reaction_user =
+ post.emoji_reactions.any? do |reaction|
+ reaction.reaction_users.any? { |ru| ru.user_id == scope.user.id } &&
+ (
+ if SiteSetting.discourse_reactions_allow_any_emoji
+ reaction.reaction_value != DiscourseReactions::Reaction.main_reaction_id
+ else
+ DiscourseReactions::Reaction.reactions_counting_as_like.include?(
+ reaction.reaction_value,
+ )
+ end
+ )
+ end
+
+ like_post_action.present? && !has_matching_reaction_user
+ end
+ end
+
+ add_to_serializer(:post, :reactions) { ReactionsSerializerHelpers.reactions_for_post(object) }
+
+ add_to_serializer(:post, :current_user_reaction) do
+ ReactionsSerializerHelpers.current_user_reaction_for_post(object, scope)
end
add_to_serializer(:post, :reaction_users_count) do
- return object.reaction_users_count unless object.reaction_users_count.nil?
- TopicViewSerializer.posts_reaction_users_count(object.id)[object.id]
+ ReactionsSerializerHelpers.reaction_users_count_for_post(object)
end
add_to_serializer(:post, :current_user_used_main_reaction) do
- return false if scope.is_anonymous?
-
- like_post_action =
- object.post_actions.find do |post_action|
- post_action.post_action_type_id == PostActionType::LIKE_POST_ACTION_ID &&
- post_action.user_id == scope.user.id && !post_action.trashed?
- end
+ ReactionsSerializerHelpers.current_user_used_main_reaction_for_post(object, scope)
+ end
- has_matching_reaction_user =
- object.emoji_reactions.any? do |reaction|
- reaction.reaction_users.any? { |ru| ru.user_id == scope.user.id } &&
- (
- if SiteSetting.discourse_reactions_allow_any_emoji
- reaction.reaction_value != DiscourseReactions::Reaction.main_reaction_id
- else
- DiscourseReactions::Reaction.reactions_counting_as_like.include?(
- reaction.reaction_value,
- )
- end
+ add_to_serializer(
+ :topic_list_item,
+ :op_reactions_data,
+ include_condition: -> do
+ object.association(:first_post).loaded? &&
+ DiscoursePluginRegistry.apply_modifier(
+ :include_discourse_reactions_data_on_topic_list,
+ false,
+ scope.user,
+ )
+ end,
+ ) do
+ return nil unless object.first_post
+
+ post = object.first_post
+ like_action =
+ (
+ if scope.user
+ PostAction.find_by(
+ user_id: scope.user.id,
+ post_id: post.id,
+ post_action_type_id: PostActionType.types[:like],
)
- end
+ else
+ nil
+ end
+ )
- like_post_action.present? && !has_matching_reaction_user
+ {
+ id: post.id,
+ user_id: post.user_id,
+ yours: post.user_id == scope.current_user&.id,
+ reactions: ReactionsSerializerHelpers.reactions_for_post(post),
+ current_user_reaction: ReactionsSerializerHelpers.current_user_reaction_for_post(post, scope),
+ current_user_used_main_reaction:
+ ReactionsSerializerHelpers.current_user_used_main_reaction_for_post(post, scope),
+ reaction_users_count: ReactionsSerializerHelpers.reaction_users_count_for_post(post) || 0,
+ likeAction: {
+ canToggle: like_action ? scope.can_delete_post_action?(like_action) : true,
+ },
+ }
end
add_to_serializer(:topic_view, :valid_reactions) { DiscourseReactions::Reaction.valid_reactions }
diff --git a/plugins/discourse-reactions/spec/serializers/topic_list_item_serializer_spec.rb b/plugins/discourse-reactions/spec/serializers/topic_list_item_serializer_spec.rb
new file mode 100644
index 00000000000..ad5b47aad1b
--- /dev/null
+++ b/plugins/discourse-reactions/spec/serializers/topic_list_item_serializer_spec.rb
@@ -0,0 +1,493 @@
+# frozen_string_literal: true
+
+require_relative "../fabricators/reaction_fabricator"
+require_relative "../fabricators/reaction_user_fabricator"
+
+describe TopicListItemSerializer do
+ fab!(:user_1, :user)
+ fab!(:user_2, :user)
+ fab!(:user_3, :user)
+ fab!(:topic) { Fabricate(:topic, user: user_1) }
+ fab!(:first_post) { Fabricate(:post, user: user_1, topic: topic, post_number: 1) }
+
+ let(:plugin_instance) { Plugin::Instance.new }
+ let(:modifier_block) { Proc.new { true } }
+
+ before do
+ SiteSetting.discourse_reactions_enabled = true
+ SiteSetting.discourse_reactions_enabled_reactions = "otter|+1|tada"
+ SiteSetting.discourse_reactions_like_icon = "heart"
+
+ plugin_instance.register_modifier(
+ :include_discourse_reactions_data_on_topic_list,
+ &modifier_block
+ )
+ end
+
+ after do
+ DiscoursePluginRegistry.unregister_modifier(
+ plugin_instance,
+ :include_discourse_reactions_data_on_topic_list,
+ &modifier_block
+ )
+ end
+
+ describe "#op_reactions_data" do
+ context "when first_post is not loaded" do
+ it "does not include op_reactions_data" do
+ topic_without_first_post = Fabricate(:topic)
+ json =
+ TopicListItemSerializer.new(
+ topic_without_first_post,
+ scope: Guardian.new(user_1),
+ root: false,
+ ).as_json
+
+ expect(json[:op_reactions_data]).to be_nil
+ end
+ end
+
+ context "when modifier returns false" do
+ let(:false_plugin_instance) { Plugin::Instance.new }
+ let(:false_modifier_block) { Proc.new { false } }
+
+ before do
+ DiscoursePluginRegistry.unregister_modifier(
+ plugin_instance,
+ :include_discourse_reactions_data_on_topic_list,
+ &modifier_block
+ )
+ false_plugin_instance.register_modifier(
+ :include_discourse_reactions_data_on_topic_list,
+ &false_modifier_block
+ )
+ end
+
+ after do
+ DiscoursePluginRegistry.unregister_modifier(
+ false_plugin_instance,
+ :include_discourse_reactions_data_on_topic_list,
+ &false_modifier_block
+ )
+ # Re-register the original modifier for subsequent tests
+ plugin_instance.register_modifier(
+ :include_discourse_reactions_data_on_topic_list,
+ &modifier_block
+ )
+ end
+
+ it "does not include op_reactions_data" do
+ topic.association(:first_post).target = first_post
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data]).to be_nil
+ end
+ end
+
+ context "when first_post is loaded and modifier is true" do
+ before do
+ topic.association(:first_post).target = first_post
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "includes basic post information" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data]).to be_present
+ expect(json[:op_reactions_data][:id]).to eq(first_post.id)
+ expect(json[:op_reactions_data][:user_id]).to eq(user_1.id)
+ expect(json[:op_reactions_data][:yours]).to eq(true)
+ end
+
+ it "shows yours as false for other users" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(user_2), root: false).as_json
+
+ expect(json[:op_reactions_data][:yours]).to eq(false)
+ end
+
+ context "with reactions" do
+ let(:reaction_otter) { Fabricate(:reaction, reaction_value: "otter", post: first_post) }
+ let(:reaction_plus_1) { Fabricate(:reaction, reaction_value: "+1", post: first_post) }
+
+ before do
+ Fabricate(:reaction_user, reaction: reaction_otter, user: user_1, post: first_post)
+ Fabricate(:reaction_user, reaction: reaction_otter, user: user_2, post: first_post)
+ Fabricate(:reaction_user, reaction: reaction_plus_1, user: user_3, post: first_post)
+
+ first_post.reload
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "includes reactions sorted by count" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ # otter has 2 users, +1 has 1 user
+ expect(json[:op_reactions_data][:reactions]).to eq(
+ [{ id: "otter", type: :emoji, count: 2 }, { id: "+1", type: :emoji, count: 1 }],
+ )
+ end
+
+ it "includes current_user_reaction for reacting user" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to eq(
+ { id: "otter", type: :emoji, can_undo: true },
+ )
+ end
+
+ it "includes current_user_used_main_reaction" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ # User 1 used "otter" reaction, not the main reaction "heart"
+ expect(json[:op_reactions_data][:current_user_used_main_reaction]).to eq(false)
+ end
+
+ it "includes reaction_users_count" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ # 3 reaction users: user_1 and user_2 for otter, user_3 for +1
+ expect(json[:op_reactions_data][:reaction_users_count]).to eq(3)
+ end
+ end
+
+ context "with only likes (no custom reactions)" do
+ before do
+ Fabricate(
+ :post_action,
+ post: first_post,
+ user: user_2,
+ post_action_type_id: PostActionType::LIKE_POST_ACTION_ID,
+ )
+
+ first_post.reload
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "shows likes as main_reaction_id" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data][:reactions]).to eq(
+ [{ id: "heart", type: :emoji, count: 1 }],
+ )
+ end
+
+ it "includes current_user_reaction as nil for non-liking user" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to be_nil
+ end
+
+ it "includes current_user_reaction for liking user" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_2), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to eq(
+ { id: "heart", type: :emoji, can_undo: true },
+ )
+ end
+ end
+
+ context "with likeAction" do
+ let!(:like_action) do
+ Fabricate(
+ :post_action,
+ post: first_post,
+ user: user_2,
+ post_action_type_id: PostActionType::LIKE_POST_ACTION_ID,
+ )
+ end
+
+ before do
+ first_post.reload
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "shows canToggle as true when user has a like action they can delete" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_2), root: false).as_json
+
+ expect(json[:op_reactions_data][:likeAction][:canToggle]).to eq(true)
+ end
+
+ it "shows canToggle as true when user has no like action" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data][:likeAction][:canToggle]).to eq(true)
+ end
+
+ it "shows canToggle as false when user cannot delete their like action" do
+ SiteSetting.post_undo_action_window_mins = 10
+ like_action.update!(created_at: 11.minutes.ago)
+
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_2), root: false).as_json
+
+ expect(json[:op_reactions_data][:likeAction][:canToggle]).to eq(false)
+ end
+ end
+
+ context "for anonymous users" do
+ it "returns nil for current_user_reaction" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to be_nil
+ expect(json[:op_reactions_data][:yours]).to eq(false)
+ expect(json[:op_reactions_data][:likeAction][:canToggle]).to eq(true)
+ end
+
+ it "shows current_user_used_main_reaction as false" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_used_main_reaction]).to eq(false)
+ end
+
+ it "includes basic post data regardless of reactions" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:id]).to eq(first_post.id)
+ expect(json[:op_reactions_data][:user_id]).to eq(user_1.id)
+ expect(json[:op_reactions_data][:yours]).to eq(false)
+ end
+
+ context "with existing reactions from other users" do
+ let(:reaction_otter) { Fabricate(:reaction, reaction_value: "otter", post: first_post) }
+ let(:reaction_tada) { Fabricate(:reaction, reaction_value: "tada", post: first_post) }
+
+ before do
+ Fabricate(:reaction_user, reaction: reaction_otter, user: user_1, post: first_post)
+ Fabricate(:reaction_user, reaction: reaction_otter, user: user_2, post: first_post)
+ Fabricate(:reaction_user, reaction: reaction_tada, user: user_3, post: first_post)
+
+ topic.reload
+ topic.association(:first_post).target = first_post.reload
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "can see all reactions from other users" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:reactions]).to match_array(
+ [{ id: "otter", type: :emoji, count: 2 }, { id: "tada", type: :emoji, count: 1 }],
+ )
+ end
+
+ it "can see the reaction_users_count" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:reaction_users_count]).to eq(3)
+ end
+
+ it "does not show any current_user_reaction" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to be_nil
+ end
+
+ it "shows current_user_used_main_reaction as false" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_used_main_reaction]).to eq(false)
+ end
+ end
+
+ context "with likes from other users" do
+ before do
+ Fabricate(
+ :post_action,
+ post: first_post,
+ user: user_1,
+ post_action_type_id: PostActionType::LIKE_POST_ACTION_ID,
+ )
+ Fabricate(
+ :post_action,
+ post: first_post,
+ user: user_2,
+ post_action_type_id: PostActionType::LIKE_POST_ACTION_ID,
+ )
+
+ topic.reload
+ topic.association(:first_post).target = first_post.reload
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "can see likes as main_reaction_id" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:reactions]).to eq(
+ [{ id: "heart", type: :emoji, count: 2 }],
+ )
+ end
+
+ it "shows canToggle as true even without being logged in" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:likeAction][:canToggle]).to eq(true)
+ end
+
+ it "does not show current_user_reaction" do
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(nil), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to be_nil
+ end
+ end
+ end
+
+ context "with mixed reactions and likes" do
+ let(:reaction_otter) { Fabricate(:reaction, reaction_value: "otter", post: first_post) }
+
+ before do
+ # User 1 uses custom reaction (otter counts as a like, so it will create a PostAction)
+ Fabricate(:reaction_user, reaction: reaction_otter, user: user_1, post: first_post)
+
+ # User 2 uses main reaction (like) - manually create just the PostAction
+ # We use skip_post_action: true to prevent the reaction_user fabricator from creating a duplicate
+ Fabricate(
+ :post_action,
+ post: first_post,
+ user: user_2,
+ post_action_type_id: PostActionType::LIKE_POST_ACTION_ID,
+ )
+
+ first_post.reload
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+ end
+
+ it "correctly combines reactions and likes" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ # User 1 has otter reaction (counts as like)
+ # User 2 has main reaction (PostAction only, no ReactionUser)
+ # So we should see: otter (1) and heart (2 - includes both user 1's shadow like and user 2's direct like)
+ expect(json[:op_reactions_data][:reactions]).to match_array(
+ [{ id: "otter", type: :emoji, count: 1 }, { id: "heart", type: :emoji, count: 1 }],
+ )
+ end
+
+ it "shows correct current_user_reaction for user with custom reaction" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to eq(
+ { id: "otter", type: :emoji, can_undo: true },
+ )
+ # User 1 used otter, not the main reaction
+ expect(json[:op_reactions_data][:current_user_used_main_reaction]).to eq(false)
+ end
+
+ it "shows correct current_user_reaction for user with main reaction" do
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_2), root: false).as_json
+
+ expect(json[:op_reactions_data][:current_user_reaction]).to eq(
+ { id: "heart", type: :emoji, can_undo: true },
+ )
+ expect(json[:op_reactions_data][:current_user_used_main_reaction]).to eq(true)
+ end
+ end
+ context "when modifier returns false" do
+ let(:false_plugin_instance) { Plugin::Instance.new }
+ let(:false_modifier_block) { Proc.new { false } }
+
+ before do
+ DiscoursePluginRegistry.unregister_modifier(
+ plugin_instance,
+ :include_discourse_reactions_data_on_topic_list,
+ &modifier_block
+ )
+ false_plugin_instance.register_modifier(
+ :include_discourse_reactions_data_on_topic_list,
+ &false_modifier_block
+ )
+ end
+
+ after do
+ DiscoursePluginRegistry.unregister_modifier(
+ false_plugin_instance,
+ :include_discourse_reactions_data_on_topic_list,
+ &false_modifier_block
+ )
+ # Re-register the original modifier for subsequent tests
+ plugin_instance.register_modifier(
+ :include_discourse_reactions_data_on_topic_list,
+ &modifier_block
+ )
+ end
+
+ it "excludes op_reactions_data" do
+ topic.association(:first_post).target = first_post
+
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json.key?(:op_reactions_data)).to eq(false)
+ end
+
+ it "returns false" do
+ topic.association(:first_post).target = first_post
+
+ json =
+ TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json.key?(:op_reactions_data)).to eq(false)
+ end
+ end
+
+ it "returns true when first_post is loaded and modifier returns true" do
+ topic.association(:first_post).target = first_post
+ first_post.post_actions_with_reaction_users =
+ DiscourseReactions::TopicViewSerializerExtension.load_post_action_reaction_users_for_posts(
+ [first_post.id],
+ )[
+ first_post.id
+ ]
+
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(user_1), root: false).as_json
+
+ expect(json.key?(:op_reactions_data)).to eq(true)
+ end
+ end
+ end
+end