laravel-comments 0.2.1

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! Reading threads: a page of top-level comments with their replies, in a fixed number of queries.

use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};

use laravel::db::{Builder, Condition};
use laravel::model::Morph;
use serde::Serialize;

use crate::author::Commenter;
use crate::model::CommentModel;
use crate::reactions::{reaction_counts, reactions_of};
use crate::status::Visibility;

/// The order of top-level comments, and of the replies to each comment.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Sort {
    /// Oldest first.
    #[default]
    Oldest,
    /// Newest first.
    Newest,
    /// Most reactions first, then oldest first.
    Best,
}

/// A query for threads, from [`CommentModel::threads`] or [`CommentModel::thread_tree`].
///
/// ```no_run
/// # use laravel::model::{model, morph};
/// # use laravel_comments::{CommentModel, Commenter, Sort};
/// # #[model] pub struct User { pub id: i64 }
/// # impl Commenter for User { fn commenter_id(&self) -> i64 { self.id } }
/// # #[model] pub struct Post { pub id: i64 }
/// # #[morph] pub enum Commentable { Post(Post) }
/// # laravel_comments::comment_model! { pub struct Comment { commentable: Commentable, author: User } }
/// # async fn example(post: Post, viewer: User) -> laravel::Result<()> {
/// let page = Comment::threads(post)
///     .sort(Sort::Best)
///     .depth(3)
///     .viewer(&viewer)
///     .page(2)
///     .get()
///     .await?;
/// # Ok(()) }
/// ```
#[must_use]
pub struct Threads<C: CommentModel> {
    source: Source<C>,
    sort: Sort,
    page: u64,
    per_page: u64,
    depth: Option<i64>,
    viewer: Option<i64>,
}

enum Source<C: CommentModel> {
    On(C::Commentable),
    Thread(String),
}

/// Where a comment shows on the pages of [`Threads`], from [`Threads::locate`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Location {
    /// The page its thread is on, from 1.
    pub page: u64,
    /// The key of the thread's top-level comment.
    pub thread_id: i64,
    /// The comment's key.
    pub comment_id: i64,
    /// When the comment is deeper than the pages load, the key of its ancestor at the last
    /// loaded level, whose `more_replies` leads to it.
    pub cut_at: Option<i64>,
}

/// A page of threads.
#[derive(Debug, Serialize)]
#[serde(bound = "C: Serialize")]
pub struct ThreadPage<C> {
    /// The threads on this page.
    pub threads: Vec<ThreadNode<C>>,
    /// The page's number, from 1.
    pub page: u64,
    /// The most threads a page holds.
    pub per_page: u64,
    /// The number of threads on every page.
    pub total: u64,
    /// Whether a later page has threads.
    pub has_more: bool,
}

/// A comment in a thread, with its replies.
#[derive(Debug, Serialize)]
#[serde(bound = "C: Serialize")]
pub struct ThreadNode<C> {
    /// The comment's key.
    pub id: i64,
    /// How the comment shows.
    pub visibility: Visibility,
    /// The comment with its author, when it's [`Visibility::Visible`]. A placeholder carries
    /// nothing of a removed or unapproved comment.
    pub comment: Option<C>,
    /// The comment's text as safe HTML, rendered from Markdown, when it's visible.
    #[cfg(feature = "markdown")]
    pub body_html: Option<String>,
    /// The number of each reaction.
    pub reactions: BTreeMap<String, i64>,
    /// The viewer's reactions, when the query has a viewer.
    pub viewer_reactions: Vec<String>,
    /// The replies that are shown.
    pub replies: Vec<ThreadNode<C>>,
    /// The number of approved replies below the depth the query loaded.
    pub more_replies: i64,
}

impl<C: CommentModel> Threads<C> {
    pub(crate) fn on(on: C::Commentable) -> Self {
        Self::new(Source::On(on))
    }

    pub(crate) fn thread(thread: String) -> Self {
        Self::new(Source::Thread(thread))
    }

    fn new(source: Source<C>) -> Self {
        Self {
            source,
            sort: Sort::default(),
            page: 1,
            per_page: 20,
            depth: None,
            viewer: None,
        }
    }

    /// The order of top-level comments and of replies. Oldest first by default.
    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = sort;
        self
    }

    /// The page to read, from 1.
    pub fn page(mut self, page: u64) -> Self {
        self.page = page.max(1);
        self
    }

    /// The most threads a page holds. 20 by default.
    pub fn per_page(mut self, per_page: u64) -> Self {
        self.per_page = per_page.max(1);
        self
    }

    /// Loads replies down to this depth, where top-level comments are `0`. A comment at that
    /// depth reports its other replies in `more_replies`. Every level by default.
    pub fn depth(mut self, depth: i64) -> Self {
        self.depth = Some(depth.max(0));
        self
    }

    /// The user whose reactions `viewer_reactions` lists.
    pub fn viewer(mut self, viewer: &C::Author) -> Self {
        self.viewer = Some(viewer.commenter_id());
        self
    }

    /// Where `comment` shows on these pages: the page its thread is on, the thread's top-level
    /// comment, and, when the comment is deeper than [`depth`](Self::depth), the comment whose
    /// `more_replies` leads to it. `None` when its thread isn't on these pages, as for a comment
    /// on another model or in a thread with nothing approved. For a link to one comment, such as
    /// in a notification, ask with the same sort, page size, and depth the page uses:
    ///
    /// ```no_run
    /// # use laravel::model::{model, morph};
    /// # use laravel_comments::{CommentModel, Commenter, Sort};
    /// # #[model] pub struct User { pub id: i64 }
    /// # impl Commenter for User { fn commenter_id(&self) -> i64 { self.id } }
    /// # #[model] pub struct Post { pub id: i64 }
    /// # #[morph] pub enum Commentable { Post(Post) }
    /// # laravel_comments::comment_model! { pub struct Comment { commentable: Commentable, author: User } }
    /// # async fn example(post: Post, comment: Comment) -> laravel::Result<()> {
    /// if let Some(place) = Comment::threads(post.clone()).sort(Sort::Best).depth(3).locate(&comment).await? {
    ///     let anchor = place.cut_at.unwrap_or(place.comment_id);
    ///     let url = format!("/posts/{}?sort=best&page={}#comment-{anchor}", post.id, place.page);
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// The page comes from one query counting the threads before this one, so it's right for
    /// the order at the time of asking: with [`Sort::Best`], new reactions may move a thread.
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    pub async fn locate(&self, comment: &C) -> laravel::Result<Option<Location>> {
        let columns = C::COLUMNS;
        let key = C::META.key;
        let row = comment.row();
        let Some(root) = C::new_query()
            .filter(self.roots_condition() & columns.thread.eq(row.thread.to_owned()))
            .first()
            .await?
        else {
            return Ok(None);
        };

        let top = root.row();
        let (created_at, id, reactions) = (top.created_at, top.id, top.reactions_count);
        let same_time = columns.created_at.eq(created_at);
        let before = match self.sort {
            Sort::Oldest => columns.created_at.lt(created_at) | (same_time & key.lt(id)),
            Sort::Newest => columns.created_at.gt(created_at) | (same_time & key.gt(id)),
            Sort::Best => {
                columns.reactions_count.gt(reactions)
                    | (columns.reactions_count.eq(reactions)
                        & (columns.created_at.lt(created_at) | (columns.created_at.eq(created_at) & key.lt(id))))
            }
        };
        let ahead = C::new_query().filter(self.roots_condition() & before).count().await?;

        let cut_at = match (self.depth, C::depth_column()) {
            (Some(depth), Some(column)) if row.depth > depth => comment
                .ancestors()
                .filter(column.eq(depth))
                .first()
                .await?
                .map(|cut| cut.row().id),
            _ => None,
        };
        Ok(Some(Location {
            page: ahead / self.per_page + 1,
            thread_id: id,
            comment_id: row.id,
            cut_at,
        }))
    }

    /// The top-level comments these pages list.
    fn roots(&self) -> Builder<C> {
        C::new_query().filter(self.roots_condition())
    }

    fn roots_condition(&self) -> Condition {
        let columns = C::COLUMNS;
        match &self.source {
            Source::On(on) => {
                // The threads with something to show: an approved comment anywhere in them. A
                // removed or unapproved top-level comment shows as a placeholder above its
                // approved replies, and a thread with nothing approved is left out.
                let shown = C::new_query()
                    .filter(
                        columns.commentable_type.eq(on.morph())
                            & columns.commentable_id.eq(*on.key())
                            & C::where_visible(),
                    )
                    .select_column(columns.thread);
                columns.commentable_type.eq(on.morph())
                    & columns.commentable_id.eq(*on.key())
                    & C::where_root()
                    & columns.thread.is_in(shown)
            }
            Source::Thread(thread) => columns.thread.eq(thread.clone()) & C::where_root(),
        }
    }

    /// Reads the page: a query counting the threads, one for the top-level comments, one for
    /// their replies, one for each eager-loaded author query, one for the reaction counts, and
    /// one for the viewer's reactions, however many comments there are.
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    pub async fn get(self) -> laravel::Result<ThreadPage<C>> {
        let columns = C::COLUMNS;
        let roots = self.roots();
        let total = roots.count().await?;
        let offset = (self.page - 1) * self.per_page;
        let roots = C::with_author(order(roots, self.sort))
            .offset(offset)
            .limit(self.per_page)
            .get()
            .await?;

        let threads: Vec<String> = roots.iter().map(|root| root.row().thread.to_owned()).collect();
        let mut replies = C::new_query().filter(columns.thread.is_in(threads) & C::where_has_parent());
        if let (Some(depth), Some(column)) = (self.depth, C::depth_column()) {
            replies = replies.filter(column.le(depth));
        }
        let replies = if roots.is_empty() {
            Vec::new()
        } else {
            C::with_author(replies.order_by(C::lft_column().asc())).get().await?
        };

        let ids: Vec<i64> = roots.iter().chain(&replies).map(|comment| comment.row().id).collect();
        let mut counts = reaction_counts(&ids).await?;
        let mut mine = match self.viewer {
            Some(viewer) => reactions_of(viewer, &ids).await?,
            None => HashMap::new(),
        };

        let mut children: HashMap<i64, Vec<C>> = HashMap::new();
        for reply in replies {
            if let Some(parent) = reply.row().parent_id {
                children.entry(parent).or_default().push(reply);
            }
        }
        let arrange = Arrange {
            sort: self.sort,
            depth: self.depth,
        };
        let threads = roots
            .into_iter()
            .filter_map(|root| arrange.node(root, &mut children, &mut counts, &mut mine))
            .collect();

        Ok(ThreadPage {
            threads,
            page: self.page,
            per_page: self.per_page,
            total,
            has_more: offset + self.per_page < total,
        })
    }
}

struct Arrange {
    sort: Sort,
    depth: Option<i64>,
}

impl Arrange {
    /// The node of `comment` with its replies, or `None` when it's a placeholder with nothing to
    /// show below it.
    fn node<C: CommentModel>(
        &self,
        comment: C,
        children: &mut HashMap<i64, Vec<C>>,
        counts: &mut HashMap<i64, BTreeMap<String, i64>>,
        mine: &mut HashMap<i64, Vec<String>>,
    ) -> Option<ThreadNode<C>> {
        let row = comment.row();
        let (id, depth, replies_count) = (row.id, row.depth, row.replies_count);
        let mut below = children.remove(&id).unwrap_or_default();
        below.sort_by(|a, b| compare(a, b, self.sort));
        let replies: Vec<ThreadNode<C>> = below
            .into_iter()
            .filter_map(|child| self.node(child, children, counts, mine))
            .collect();

        let visibility = comment.visibility();
        if visibility != Visibility::Visible && replies.is_empty() {
            return None;
        }
        let cut_here = self.depth == Some(depth) && comment.descendant_count() > 0;
        Some(ThreadNode {
            id,
            visibility,
            #[cfg(feature = "markdown")]
            body_html: (visibility == Visibility::Visible).then(|| comment.body_html()),
            comment: (visibility == Visibility::Visible).then_some(comment),
            reactions: counts.remove(&id).unwrap_or_default(),
            viewer_reactions: mine.remove(&id).unwrap_or_default(),
            replies,
            more_replies: if cut_here { replies_count } else { 0 },
        })
    }
}

fn order<C: CommentModel>(query: Builder<C>, sort: Sort) -> Builder<C> {
    let columns = C::COLUMNS;
    let key = C::META.key;
    match sort {
        Sort::Oldest => query.order_by(columns.created_at.asc()).order_by(key.asc()),
        Sort::Newest => query.order_by(columns.created_at.desc()).order_by(key.desc()),
        Sort::Best => query
            .order_by(columns.reactions_count.desc())
            .order_by(columns.created_at.asc())
            .order_by(key.asc()),
    }
}

fn compare<C: CommentModel>(a: &C, b: &C, sort: Sort) -> Ordering {
    let (a, b) = (a.row(), b.row());
    let oldest = a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id));
    match sort {
        Sort::Oldest => oldest,
        Sort::Newest => oldest.reverse(),
        Sort::Best => b.reactions_count.cmp(&a.reactions_count).then(oldest),
    }
}