laravel-comments 0.2.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! Events the package dispatches. Listen to them as to any Laravel Rust event; each one carries
//! keys, so a listener loads what it needs.
//!
//! With `COMMENTS_BROADCAST=public` or `private`, they also broadcast on the channel
//! `comments.{commentable_type}.{commentable_id}` of the model the comment belongs to, as
//! [`CommentEvent::channel`] names it, unless they concern a comment nobody else may see yet:
//! a pending reply, say, or its approval by a moderator. Each broadcast carries the event's
//! fields, never a comment's text, so subscribers load what they may see.

use laravel::broadcast::{Broadcast, Channel};
use laravel::event::Event;

use crate::Status;
use crate::config::BroadcastChannel;
use crate::ops;

/// What every event of the package knows: the model the comment belongs to.
pub trait CommentEvent {
    /// The morph name of the model the comment belongs to, such as `post`.
    fn commentable_type(&self) -> &str;

    /// The key of the model the comment belongs to.
    fn commentable_id(&self) -> i64;

    /// The name of the channel the event broadcasts on, without its `private-` prefix:
    /// `comments.post.42`.
    fn channel(&self) -> String {
        format!("comments.{}.{}", self.commentable_type(), self.commentable_id())
    }
}

/// The channels for `event`: none while broadcasting is off or `shown` is `false`.
fn channels(event: &impl CommentEvent, shown: bool) -> laravel::Result<Vec<Channel>> {
    if !shown {
        return Ok(Vec::new());
    }
    Ok(match ops::config().broadcast {
        BroadcastChannel::Off => Vec::new(),
        BroadcastChannel::Public => vec![Channel::public(event.channel())?],
        BroadcastChannel::Private => vec![Channel::private(event.channel())?],
    })
}

macro_rules! comment_event {
    ($name:ident, |$event:ident| $shown:expr) => {
        impl CommentEvent for $name {
            fn commentable_type(&self) -> &str {
                &self.commentable_type
            }

            fn commentable_id(&self) -> i64 {
                self.commentable_id
            }
        }

        impl Broadcast for $name {
            fn broadcast_on(&self) -> laravel::Result<Vec<Channel>> {
                let $event = self;
                let shown = $shown;
                let _ = $event;
                channels(self, shown)
            }
        }
    };
}

/// A comment or a reply was posted.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct CommentPosted {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to, such as `post`.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// The parent's key, for replies.
    pub parent_id: Option<i64>,
    /// The author's key, for comments by users.
    pub author_id: Option<i64>,
    /// The status the comment got.
    pub status: Status,
}
comment_event!(CommentPosted, |event| event.status == Status::Approved);

/// A moderator approved a comment. A comment approved at posting dispatches only
/// [`CommentPosted`], whose `status` says so.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct CommentApproved {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
}
comment_event!(CommentApproved, |event| true);

/// A moderator changed a comment's status.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct CommentModerated {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// The status before.
    pub from: Status,
    /// The status now.
    pub to: Status,
}
comment_event!(CommentModerated, |event| event.from == Status::Approved
    || event.to == Status::Approved);

/// A comment's text was edited.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct CommentEdited {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// The comment's status, which decides whether the edit broadcasts.
    pub status: Status,
}
comment_event!(CommentEdited, |event| event.status == Status::Approved);

/// A comment was removed.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct CommentDeleted {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// Whether a placeholder stays because the comment has replies. Otherwise the row is gone.
    pub placeholder: bool,
    /// The comment's status when it was removed, which decides whether the removal broadcasts.
    pub status: Status,
}
comment_event!(CommentDeleted, |event| event.status == Status::Approved);

/// Someone reacted to a comment.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct ReactionAdded {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// The user's key.
    pub user_id: i64,
    /// The reaction, such as `like`.
    pub reaction: String,
}
comment_event!(ReactionAdded, |event| true);

/// Someone took a reaction back.
#[derive(Debug, Clone, Event)]
#[event(broadcast)]
#[non_exhaustive]
pub struct ReactionRemoved {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// The user's key.
    pub user_id: i64,
    /// The reaction, such as `like`.
    pub reaction: String,
}
comment_event!(ReactionRemoved, |event| true);

/// A visible comment mentions a user with `@name`. Dispatched once per user and comment: when
/// the comment is posted approved, when a moderator approves it, or when an edit adds the
/// mention. It never broadcasts: notify the user from a listener.
#[derive(Debug, Clone, Event)]
#[non_exhaustive]
pub struct UserMentioned {
    /// The comment's key.
    pub comment_id: i64,
    /// The morph name of the model it belongs to.
    pub commentable_type: String,
    /// The key of the model it belongs to.
    pub commentable_id: i64,
    /// The mentioned user's key.
    pub user_id: i64,
    /// The author's key, for comments by users.
    pub author_id: Option<i64>,
}