generated from discourse/discourse-plugin-skeleton
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.rb
More file actions
334 lines (287 loc) · 13 KB
/
plugin.rb
File metadata and controls
334 lines (287 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# frozen_string_literal: true
# name: discourse-nested-replies
# about: Reddit-style nested/threaded view for Discourse topics
# version: 0.1.1
# authors: Discourse
# url: https://github.com/discourse/discourse-nested-replies
# required_version: 2.7.0
enabled_site_setting :nested_replies_enabled
register_asset "stylesheets/common/nested-view.scss"
register_svg_icon "nested-circle-plus"
register_svg_icon "nested-circle-minus"
register_svg_icon "nested-thread"
module ::DiscourseNestedReplies
PLUGIN_NAME = "discourse-nested-replies"
CATEGORY_DEFAULT_FIELD = "nested_replies_default_for_category"
PINNED_POST_NUMBER_FIELD = "nested_replies_pinned_post_number"
TOPIC_NESTED_VIEW_FIELD = "nested"
end
require_relative "lib/discourse_nested_replies/engine"
require_relative "lib/discourse_nested_replies/ancestor_walker"
require_relative "lib/discourse_nested_replies/tree_loader"
require_relative "lib/discourse_nested_replies/post_preloader"
require_relative "lib/discourse_nested_replies/post_tree_serializer"
after_initialize do
add_to_class(:topic_view, :nested_replies_direct_reply_counts) do
@nested_replies_direct_reply_counts
end
add_to_class(:topic_view, :nested_replies_direct_reply_counts=) do |counts|
@nested_replies_direct_reply_counts = counts
end
add_to_class(:topic_view, :nested_replies_skip_preload) { @nested_replies_skip_preload }
add_to_class(:topic_view, :nested_replies_skip_preload=) do |val|
@nested_replies_skip_preload = val
end
# --- TopicView.on_preload: make the flat view nested-aware ---
# After TopicView loads posts for the flat view, batch-load direct reply
# counts so the flat topic JSON response includes reply count metadata.
# This powers the "View as nested (N replies)" toggle link.
TopicView.on_preload do |topic_view|
next unless SiteSetting.nested_replies_enabled
next if topic_view.nested_replies_skip_preload
post_numbers = topic_view.posts.map(&:post_number)
next if post_numbers.empty?
visible_types = [Post.types[:regular], Post.types[:moderator_action]]
visible_types << Post.types[:whisper] if topic_view.guardian.user&.whisperer?
counts =
Post
.where(topic_id: topic_view.topic.id, deleted_at: nil)
.where(reply_to_post_number: post_numbers)
.where(post_type: visible_types)
.group(:reply_to_post_number)
.count
topic_view.nested_replies_direct_reply_counts = counts
end
# --- Serialize direct_reply_count on posts (gated) ---
# Included when the TopicView.on_preload hook above populated reply counts.
# Zero overhead on serialization paths where no counts were preloaded.
add_to_serializer(
:post,
:direct_reply_count,
include_condition: -> { @topic_view&.nested_replies_direct_reply_counts.present? },
) do
counts = @topic_view.nested_replies_direct_reply_counts
counts[object.post_number] || 0
end
# --- Category custom field: nested_replies_default_for_category ---
register_category_custom_field_type(DiscourseNestedReplies::CATEGORY_DEFAULT_FIELD, :boolean)
register_preloaded_category_custom_fields(DiscourseNestedReplies::CATEGORY_DEFAULT_FIELD)
# Serialize the category default on BasicCategorySerializer so the
# frontend can check it without extra requests.
add_to_serializer(:basic_category, :nested_replies_default) do
object.custom_fields[DiscourseNestedReplies::CATEGORY_DEFAULT_FIELD]
end
# --- Pinned reply: staff can pin one top-level reply per topic ---
register_topic_custom_field_type(DiscourseNestedReplies::PINNED_POST_NUMBER_FIELD, :integer)
register_editable_topic_custom_field(
DiscourseNestedReplies::PINNED_POST_NUMBER_FIELD,
staff_only: true,
)
# --- Topic-level nested view field ---
# Each topic carries its own "nested" flag so the frontend can decide
# which view to render without looking up category settings every time.
register_topic_custom_field_type(DiscourseNestedReplies::TOPIC_NESTED_VIEW_FIELD, :boolean)
add_preloaded_topic_list_custom_field(DiscourseNestedReplies::TOPIC_NESTED_VIEW_FIELD)
add_to_serializer(:topic_list_item, :is_nested_view) do
object.custom_fields[DiscourseNestedReplies::TOPIC_NESTED_VIEW_FIELD]
end
add_to_serializer(:topic_view, :is_nested_view) do
object.topic.custom_fields[DiscourseNestedReplies::TOPIC_NESTED_VIEW_FIELD]
end
# Auto-set the nested field on new topics when the category or global
# setting calls for nested view.
on(:topic_created) do |topic, _opts, _user|
next unless SiteSetting.nested_replies_enabled
is_nested =
SiteSetting.nested_replies_default ||
topic.category&.custom_fields&.dig(DiscourseNestedReplies::CATEGORY_DEFAULT_FIELD)
if is_nested
topic.custom_fields[DiscourseNestedReplies::TOPIC_NESTED_VIEW_FIELD] = true
topic.save_custom_fields
end
end
# --- Preserve ?post_number through URL canonicalization redirects ---
register_modifier(:redirect_to_correct_topic_additional_query_parameters) do |params|
params + %w[post_number]
end
# --- Batch reactions precompute support ---
# ReactionsSerializerHelpers.reactions_for_post fires a per-post COUNT query.
# To avoid N+1, we batch-precompute the reactions result and store it on
# post.precomputed_reactions. The prepend below short-circuits the serializer's
# `reactions` method to use precomputed data.
#
# We prepend on PostSerializer (not ReactionsSerializerHelpers) because our
# plugin loads alphabetically before discourse-reactions, so
# ReactionsSerializerHelpers doesn't exist yet at boot time. Prepending on
# PostSerializer works regardless of load order — Ruby's MRO ensures our
# method is checked first, and `super` resolves at call time.
add_to_class(:post, :precomputed_reactions) { @precomputed_reactions }
add_to_class(:post, "precomputed_reactions=") { |val| @precomputed_reactions = val }
# Batch-compute the full reactions result for all posts in one SQL query.
# Replicates ReactionsSerializerHelpers.reactions_for_post logic without
# the per-post COUNT that causes N+1. Expects reactions associations to be
# preloaded on the posts before calling.
def DiscourseNestedReplies.batch_precompute_reactions(posts, post_ids)
main_reaction = DiscourseReactions::Reaction.main_reaction_id
excluded = DiscourseReactions::Reaction.reactions_excluded_from_like
excluded_filter =
if excluded.present?
"AND dr.reaction_value NOT IN (:excluded)"
else
""
end
sql_params = {
post_ids: post_ids,
like_type: PostActionType::LIKE_POST_ACTION_ID,
main_reaction: main_reaction,
}
sql_params[:excluded] = excluded if excluded.present?
rows = DB.query(<<~SQL, **sql_params)
SELECT pa.post_id, COUNT(*) as likes_count
FROM post_actions pa
WHERE pa.deleted_at IS NULL
AND pa.post_id IN (:post_ids)
AND pa.post_action_type_id = :like_type
AND NOT EXISTS (
SELECT 1 FROM discourse_reactions_reaction_users dru
JOIN discourse_reactions_reactions dr ON dr.id = dru.reaction_id
WHERE dru.post_id = pa.post_id
AND dru.user_id = pa.user_id
AND dr.reaction_value != :main_reaction
#{excluded_filter}
)
AND NOT EXISTS (
SELECT 1 FROM discourse_reactions_reaction_users dru
JOIN discourse_reactions_reactions dr ON dr.id = dru.reaction_id
WHERE dru.post_id = pa.post_id
AND dru.user_id = pa.user_id
AND dr.reaction_value = :main_reaction
)
GROUP BY pa.post_id
SQL
likes_map = rows.each_with_object({}) { |row, h| h[row.post_id] = row.likes_count }
posts.each do |post|
emoji_reactions = post.emoji_reactions.select { |r| r.reaction_users_count.to_i > 0 }
reactions =
emoji_reactions.map do |reaction|
{
id: reaction.reaction_value,
type: reaction.reaction_type.to_sym,
count: reaction.reaction_users_count,
}
end
likes = likes_map[post.id] || 0
if likes > 0
reaction_likes, reactions = reactions.partition { |r| r[:id] == main_reaction }
reactions << {
id: main_reaction,
type: :emoji,
count: likes + reaction_likes.sum { |r| r[:count] },
}
end
post.precomputed_reactions = reactions.sort_by { |r| [-r[:count].to_i, r[:id]] }
end
end
module ::DiscourseNestedReplies::PostSerializerReactionsPatch
def reactions
if SiteSetting.nested_replies_enabled && object.respond_to?(:precomputed_reactions) &&
(data = object.precomputed_reactions)
return data
end
super
end
end
reloadable_patch { PostSerializer.prepend(DiscourseNestedReplies::PostSerializerReactionsPatch) }
# --- Stats maintenance callbacks ---
# Keep nested_view_post_stats counts in sync when posts are created or deleted.
# direct_reply_count: incremented on the immediate parent only.
# total_descendant_count: incremented on ALL ancestors up the reply chain.
# whisper_* columns track the whisper subset so non-staff users see
# counts that exclude whispers (prevents leaking whisper existence).
add_model_callback(:post, :after_create) do
next if reply_to_post_number.blank?
# Walk ancestors (excluding deleted, including OP) for stats increment
ancestors =
DiscourseNestedReplies.walk_ancestors(
topic_id: topic_id,
start_post_number: reply_to_post_number,
exclude_deleted: true,
)
next if ancestors.empty?
ancestor_ids = ancestors.map(&:id)
direct_parent_id = ancestors.find { |a| a.depth == 1 }&.id
is_whisper = post_type == Post.types[:whisper] ? 1 : 0
# Single upsert: increment total_descendant_count for all ancestors,
# direct_reply_count only for the immediate parent.
# whisper_* columns are incremented only when the new post is a whisper.
DB.exec(<<~SQL, ids: ancestor_ids, parent_id: direct_parent_id, whisper: is_whisper)
INSERT INTO nested_view_post_stats (post_id, direct_reply_count, total_descendant_count,
whisper_direct_reply_count, whisper_total_descendant_count,
created_at, updated_at)
SELECT aid,
CASE WHEN aid = :parent_id THEN 1 ELSE 0 END,
1,
CASE WHEN aid = :parent_id THEN :whisper ELSE 0 END,
:whisper,
NOW(), NOW()
FROM unnest(ARRAY[:ids]::int[]) AS aid
ON CONFLICT (post_id) DO UPDATE SET
total_descendant_count = nested_view_post_stats.total_descendant_count + 1,
direct_reply_count = nested_view_post_stats.direct_reply_count +
CASE WHEN nested_view_post_stats.post_id = :parent_id THEN 1 ELSE 0 END,
whisper_total_descendant_count = nested_view_post_stats.whisper_total_descendant_count + :whisper,
whisper_direct_reply_count = nested_view_post_stats.whisper_direct_reply_count +
CASE WHEN nested_view_post_stats.post_id = :parent_id THEN :whisper ELSE 0 END,
updated_at = NOW()
SQL
end
add_model_callback(:post, :after_destroy) do
if reply_to_post_number.present?
stat =
NestedViewPostStat.where(post_id: id).pick(
:total_descendant_count,
:whisper_total_descendant_count,
)
my_descendants = stat&.first || 0
my_whisper_descendants = stat&.second || 0
removed = 1 + my_descendants
is_whisper = post_type == Post.types[:whisper] ? 1 : 0
whisper_removed = is_whisper + my_whisper_descendants
# Walk ancestors (including deleted — post may already be soft-deleted) for stats decrement
ancestors =
DiscourseNestedReplies.walk_ancestors(
topic_id: topic_id,
start_post_number: reply_to_post_number,
exclude_deleted: false,
)
if ancestors.present?
ancestor_ids = ancestors.map(&:id)
direct_parent_id = ancestors.find { |a| a.depth == 1 }&.id
# Single UPDATE: decrement stats for all ancestors, clamped at 0
DB.exec(
<<~SQL,
UPDATE nested_view_post_stats
SET total_descendant_count = GREATEST(total_descendant_count - :removed, 0),
direct_reply_count = GREATEST(
direct_reply_count - CASE WHEN post_id = :parent_id THEN 1 ELSE 0 END,
0
),
whisper_total_descendant_count = GREATEST(whisper_total_descendant_count - :whisper_removed, 0),
whisper_direct_reply_count = GREATEST(
whisper_direct_reply_count - CASE WHEN post_id = :parent_id THEN :is_whisper ELSE 0 END,
0
),
updated_at = NOW()
WHERE post_id = ANY(ARRAY[:ids]::int[])
SQL
ids: ancestor_ids,
parent_id: direct_parent_id,
removed: removed,
whisper_removed: whisper_removed,
is_whisper: is_whisper,
)
end
end
NestedViewPostStat.where(post_id: id).delete_all
end
end