Skip to main content

laravel_comments/
thread.rs

1//! Reading threads: a page of top-level comments with their replies, in a fixed number of queries.
2
3use std::cmp::Ordering;
4use std::collections::{BTreeMap, HashMap};
5
6use laravel::db::{Builder, Condition};
7use laravel::model::Morph;
8use serde::Serialize;
9
10use crate::author::Commenter;
11use crate::model::CommentModel;
12use crate::reactions::{reaction_counts, reactions_of};
13use crate::status::Visibility;
14
15/// The order of top-level comments, and of the replies to each comment.
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
17#[serde(rename_all = "snake_case")]
18pub enum Sort {
19    /// Oldest first.
20    #[default]
21    Oldest,
22    /// Newest first.
23    Newest,
24    /// Most reactions first, then oldest first.
25    Best,
26}
27
28/// A query for threads, from [`CommentModel::threads`] or [`CommentModel::thread_tree`].
29///
30/// ```no_run
31/// # use laravel::model::{model, morph};
32/// # use laravel_comments::{CommentModel, Commenter, Sort};
33/// # #[model] pub struct User { pub id: i64 }
34/// # impl Commenter for User { fn commenter_id(&self) -> i64 { self.id } }
35/// # #[model] pub struct Post { pub id: i64 }
36/// # #[morph] pub enum Commentable { Post(Post) }
37/// # laravel_comments::comment_model! { pub struct Comment { commentable: Commentable, author: User } }
38/// # async fn example(post: Post, viewer: User) -> laravel::Result<()> {
39/// let page = Comment::threads(post)
40///     .sort(Sort::Best)
41///     .depth(3)
42///     .viewer(&viewer)
43///     .page(2)
44///     .get()
45///     .await?;
46/// # Ok(()) }
47/// ```
48#[must_use]
49pub struct Threads<C: CommentModel> {
50    source: Source<C>,
51    sort: Sort,
52    page: u64,
53    per_page: u64,
54    depth: Option<i64>,
55    viewer: Option<i64>,
56}
57
58enum Source<C: CommentModel> {
59    On(C::Commentable),
60    Thread(String),
61}
62
63/// Where a comment shows on the pages of [`Threads`], from [`Threads::locate`].
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
65pub struct Location {
66    /// The page its thread is on, from 1.
67    pub page: u64,
68    /// The key of the thread's top-level comment.
69    pub thread_id: i64,
70    /// The comment's key.
71    pub comment_id: i64,
72    /// When the comment is deeper than the pages load, the key of its ancestor at the last
73    /// loaded level, whose `more_replies` leads to it.
74    pub cut_at: Option<i64>,
75}
76
77/// A page of threads.
78#[derive(Debug, Serialize)]
79#[serde(bound = "C: Serialize")]
80pub struct ThreadPage<C> {
81    /// The threads on this page.
82    pub threads: Vec<ThreadNode<C>>,
83    /// The page's number, from 1.
84    pub page: u64,
85    /// The most threads a page holds.
86    pub per_page: u64,
87    /// The number of threads on every page.
88    pub total: u64,
89    /// Whether a later page has threads.
90    pub has_more: bool,
91}
92
93/// A comment in a thread, with its replies.
94#[derive(Debug, Serialize)]
95#[serde(bound = "C: Serialize")]
96pub struct ThreadNode<C> {
97    /// The comment's key.
98    pub id: i64,
99    /// How the comment shows.
100    pub visibility: Visibility,
101    /// The comment with its author, when it's [`Visibility::Visible`]. A placeholder carries
102    /// nothing of a removed or unapproved comment.
103    pub comment: Option<C>,
104    /// The comment's text as safe HTML, rendered from Markdown, when it's visible.
105    #[cfg(feature = "markdown")]
106    pub body_html: Option<String>,
107    /// The number of each reaction.
108    pub reactions: BTreeMap<String, i64>,
109    /// The viewer's reactions, when the query has a viewer.
110    pub viewer_reactions: Vec<String>,
111    /// The replies that are shown.
112    pub replies: Vec<ThreadNode<C>>,
113    /// The number of approved replies below the depth the query loaded.
114    pub more_replies: i64,
115}
116
117impl<C: CommentModel> Threads<C> {
118    pub(crate) fn on(on: C::Commentable) -> Self {
119        Self::new(Source::On(on))
120    }
121
122    pub(crate) fn thread(thread: String) -> Self {
123        Self::new(Source::Thread(thread))
124    }
125
126    fn new(source: Source<C>) -> Self {
127        Self {
128            source,
129            sort: Sort::default(),
130            page: 1,
131            per_page: 20,
132            depth: None,
133            viewer: None,
134        }
135    }
136
137    /// The order of top-level comments and of replies. Oldest first by default.
138    pub fn sort(mut self, sort: Sort) -> Self {
139        self.sort = sort;
140        self
141    }
142
143    /// The page to read, from 1.
144    pub fn page(mut self, page: u64) -> Self {
145        self.page = page.max(1);
146        self
147    }
148
149    /// The most threads a page holds. 20 by default.
150    pub fn per_page(mut self, per_page: u64) -> Self {
151        self.per_page = per_page.max(1);
152        self
153    }
154
155    /// Loads replies down to this depth, where top-level comments are `0`. A comment at that
156    /// depth reports its other replies in `more_replies`. Every level by default.
157    pub fn depth(mut self, depth: i64) -> Self {
158        self.depth = Some(depth.max(0));
159        self
160    }
161
162    /// The user whose reactions `viewer_reactions` lists.
163    pub fn viewer(mut self, viewer: &C::Author) -> Self {
164        self.viewer = Some(viewer.commenter_id());
165        self
166    }
167
168    /// Where `comment` shows on these pages: the page its thread is on, the thread's top-level
169    /// comment, and, when the comment is deeper than [`depth`](Self::depth), the comment whose
170    /// `more_replies` leads to it. `None` when its thread isn't on these pages, as for a comment
171    /// on another model or in a thread with nothing approved. For a link to one comment, such as
172    /// in a notification, ask with the same sort, page size, and depth the page uses:
173    ///
174    /// ```no_run
175    /// # use laravel::model::{model, morph};
176    /// # use laravel_comments::{CommentModel, Commenter, Sort};
177    /// # #[model] pub struct User { pub id: i64 }
178    /// # impl Commenter for User { fn commenter_id(&self) -> i64 { self.id } }
179    /// # #[model] pub struct Post { pub id: i64 }
180    /// # #[morph] pub enum Commentable { Post(Post) }
181    /// # laravel_comments::comment_model! { pub struct Comment { commentable: Commentable, author: User } }
182    /// # async fn example(post: Post, comment: Comment) -> laravel::Result<()> {
183    /// if let Some(place) = Comment::threads(post.clone()).sort(Sort::Best).depth(3).locate(&comment).await? {
184    ///     let anchor = place.cut_at.unwrap_or(place.comment_id);
185    ///     let url = format!("/posts/{}?sort=best&page={}#comment-{anchor}", post.id, place.page);
186    /// }
187    /// # Ok(()) }
188    /// ```
189    ///
190    /// The page comes from one query counting the threads before this one, so it's right for
191    /// the order at the time of asking: with [`Sort::Best`], new reactions may move a thread.
192    ///
193    /// # Errors
194    ///
195    /// Fails when a query fails.
196    pub async fn locate(&self, comment: &C) -> laravel::Result<Option<Location>> {
197        let columns = C::COLUMNS;
198        let key = C::META.key;
199        let row = comment.row();
200        let Some(root) = C::new_query()
201            .filter(self.roots_condition() & columns.thread.eq(row.thread.to_owned()))
202            .first()
203            .await?
204        else {
205            return Ok(None);
206        };
207
208        let top = root.row();
209        let (created_at, id, reactions) = (top.created_at, top.id, top.reactions_count);
210        let same_time = columns.created_at.eq(created_at);
211        let before = match self.sort {
212            Sort::Oldest => columns.created_at.lt(created_at) | (same_time & key.lt(id)),
213            Sort::Newest => columns.created_at.gt(created_at) | (same_time & key.gt(id)),
214            Sort::Best => {
215                columns.reactions_count.gt(reactions)
216                    | (columns.reactions_count.eq(reactions)
217                        & (columns.created_at.lt(created_at) | (columns.created_at.eq(created_at) & key.lt(id))))
218            }
219        };
220        let ahead = C::new_query().filter(self.roots_condition() & before).count().await?;
221
222        let cut_at = match (self.depth, C::depth_column()) {
223            (Some(depth), Some(column)) if row.depth > depth => comment
224                .ancestors()
225                .filter(column.eq(depth))
226                .first()
227                .await?
228                .map(|cut| cut.row().id),
229            _ => None,
230        };
231        Ok(Some(Location {
232            page: ahead / self.per_page + 1,
233            thread_id: id,
234            comment_id: row.id,
235            cut_at,
236        }))
237    }
238
239    /// The top-level comments these pages list.
240    fn roots(&self) -> Builder<C> {
241        C::new_query().filter(self.roots_condition())
242    }
243
244    fn roots_condition(&self) -> Condition {
245        let columns = C::COLUMNS;
246        match &self.source {
247            Source::On(on) => {
248                // The threads with something to show: an approved comment anywhere in them. A
249                // removed or unapproved top-level comment shows as a placeholder above its
250                // approved replies, and a thread with nothing approved is left out.
251                let shown = C::new_query()
252                    .filter(
253                        columns.commentable_type.eq(on.morph())
254                            & columns.commentable_id.eq(*on.key())
255                            & C::where_visible(),
256                    )
257                    .select_column(columns.thread);
258                columns.commentable_type.eq(on.morph())
259                    & columns.commentable_id.eq(*on.key())
260                    & C::where_root()
261                    & columns.thread.is_in(shown)
262            }
263            Source::Thread(thread) => columns.thread.eq(thread.clone()) & C::where_root(),
264        }
265    }
266
267    /// Reads the page: a query counting the threads, one for the top-level comments, one for
268    /// their replies, one for each eager-loaded author query, one for the reaction counts, and
269    /// one for the viewer's reactions, however many comments there are.
270    ///
271    /// # Errors
272    ///
273    /// Fails when a query fails.
274    pub async fn get(self) -> laravel::Result<ThreadPage<C>> {
275        let columns = C::COLUMNS;
276        let roots = self.roots();
277        let total = roots.count().await?;
278        let offset = (self.page - 1) * self.per_page;
279        let roots = C::with_author(order(roots, self.sort))
280            .offset(offset)
281            .limit(self.per_page)
282            .get()
283            .await?;
284
285        let threads: Vec<String> = roots.iter().map(|root| root.row().thread.to_owned()).collect();
286        let mut replies = C::new_query().filter(columns.thread.is_in(threads) & C::where_has_parent());
287        if let (Some(depth), Some(column)) = (self.depth, C::depth_column()) {
288            replies = replies.filter(column.le(depth));
289        }
290        let replies = if roots.is_empty() {
291            Vec::new()
292        } else {
293            C::with_author(replies.order_by(C::lft_column().asc())).get().await?
294        };
295
296        let ids: Vec<i64> = roots.iter().chain(&replies).map(|comment| comment.row().id).collect();
297        let mut counts = reaction_counts(&ids).await?;
298        let mut mine = match self.viewer {
299            Some(viewer) => reactions_of(viewer, &ids).await?,
300            None => HashMap::new(),
301        };
302
303        let mut children: HashMap<i64, Vec<C>> = HashMap::new();
304        for reply in replies {
305            if let Some(parent) = reply.row().parent_id {
306                children.entry(parent).or_default().push(reply);
307            }
308        }
309        let arrange = Arrange {
310            sort: self.sort,
311            depth: self.depth,
312        };
313        let threads = roots
314            .into_iter()
315            .filter_map(|root| arrange.node(root, &mut children, &mut counts, &mut mine))
316            .collect();
317
318        Ok(ThreadPage {
319            threads,
320            page: self.page,
321            per_page: self.per_page,
322            total,
323            has_more: offset + self.per_page < total,
324        })
325    }
326}
327
328struct Arrange {
329    sort: Sort,
330    depth: Option<i64>,
331}
332
333impl Arrange {
334    /// The node of `comment` with its replies, or `None` when it's a placeholder with nothing to
335    /// show below it.
336    fn node<C: CommentModel>(
337        &self,
338        comment: C,
339        children: &mut HashMap<i64, Vec<C>>,
340        counts: &mut HashMap<i64, BTreeMap<String, i64>>,
341        mine: &mut HashMap<i64, Vec<String>>,
342    ) -> Option<ThreadNode<C>> {
343        let row = comment.row();
344        let (id, depth, replies_count) = (row.id, row.depth, row.replies_count);
345        let mut below = children.remove(&id).unwrap_or_default();
346        below.sort_by(|a, b| compare(a, b, self.sort));
347        let replies: Vec<ThreadNode<C>> = below
348            .into_iter()
349            .filter_map(|child| self.node(child, children, counts, mine))
350            .collect();
351
352        let visibility = comment.visibility();
353        if visibility != Visibility::Visible && replies.is_empty() {
354            return None;
355        }
356        let cut_here = self.depth == Some(depth) && comment.descendant_count() > 0;
357        Some(ThreadNode {
358            id,
359            visibility,
360            #[cfg(feature = "markdown")]
361            body_html: (visibility == Visibility::Visible).then(|| comment.body_html()),
362            comment: (visibility == Visibility::Visible).then_some(comment),
363            reactions: counts.remove(&id).unwrap_or_default(),
364            viewer_reactions: mine.remove(&id).unwrap_or_default(),
365            replies,
366            more_replies: if cut_here { replies_count } else { 0 },
367        })
368    }
369}
370
371fn order<C: CommentModel>(query: Builder<C>, sort: Sort) -> Builder<C> {
372    let columns = C::COLUMNS;
373    let key = C::META.key;
374    match sort {
375        Sort::Oldest => query.order_by(columns.created_at.asc()).order_by(key.asc()),
376        Sort::Newest => query.order_by(columns.created_at.desc()).order_by(key.desc()),
377        Sort::Best => query
378            .order_by(columns.reactions_count.desc())
379            .order_by(columns.created_at.asc())
380            .order_by(key.asc()),
381    }
382}
383
384fn compare<C: CommentModel>(a: &C, b: &C, sort: Sort) -> Ordering {
385    let (a, b) = (a.row(), b.row());
386    let oldest = a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id));
387    match sort {
388        Sort::Oldest => oldest,
389        Sort::Newest => oldest.reverse(),
390        Sort::Best => b.reactions_count.cmp(&a.reactions_count).then(oldest),
391    }
392}