Skip to main content

laravel_comments/
model.rs

1//! `CommentModel`: the trait the application's comment model implements, and the
2//! [`comment_model!`](crate::comment_model) macro that declares one.
3
4use std::future::Future;
5
6use laravel::db::{Builder, Condition};
7use laravel::model::{Column, Model, Morph, MorphType};
8use laravel::time::Timestamp;
9use laravel_nestedset::NestedSet;
10use serde::Serialize;
11
12use crate::author::{Author, Commenter};
13use crate::revisions::CommentRevision;
14use crate::status::{Status, Visibility};
15use crate::thread::Threads;
16use crate::{ops, reactions};
17
18/// The application's comment model.
19///
20/// Declare it with [`comment_model!`](crate::comment_model), which writes the model and this
21/// trait's implementation for you. The trait's provided methods are the package's API: posting,
22/// replying, moderating, editing, and removing comments, and reading threads.
23pub trait CommentModel: NestedSet<Key = i64> + Serialize {
24    /// The `#[morph]` enum of the models comments may belong to, such as `Post` and `Video`.
25    type Commentable: Morph<Key = i64>;
26
27    /// The model of the users who write comments.
28    type Author: Model<Key = i64> + Commenter;
29
30    /// The model's columns.
31    const COLUMNS: CommentColumns<Self>;
32
33    /// The values of the columns the package reads.
34    fn row(&self) -> CommentRow<'_, Self>;
35
36    /// A query on every comment. `comment_model!` returns `Self::query()`.
37    fn new_query() -> Builder<Self>;
38
39    /// Adds the eager loading of the author to `query`. `comment_model!` loads `Self::author`.
40    fn with_author(query: Builder<Self>) -> Builder<Self>;
41
42    /// Posts a top-level comment on `on`, a model of [`Self::Commentable`]. The comment gets the
43    /// status that the moderation rule gives it, and [`CommentPosted`](crate::events::CommentPosted)
44    /// is dispatched.
45    ///
46    /// # Errors
47    ///
48    /// Fails with a [`CommentError`](crate::CommentError) when the text or the guest is invalid,
49    /// or when a query fails.
50    fn post(
51        on: impl Into<Self::Commentable> + Send,
52        author: Author<'_, Self::Author>,
53        body: &str,
54    ) -> impl Future<Output = laravel::Result<Self>> + Send {
55        Box::pin(ops::post::<Self>(on.into(), author, body))
56    }
57
58    /// Posts a reply to this comment, and reloads it. Below `COMMENTS_MAX_DEPTH`, the reply joins
59    /// this comment's parent's replies instead, as on Reddit.
60    ///
61    /// # Errors
62    ///
63    /// Fails with a [`CommentError`](crate::CommentError) when this comment is removed or isn't
64    /// approved, when replies are off, when the text or the guest is invalid, or when a query
65    /// fails.
66    fn reply(
67        &mut self,
68        author: Author<'_, Self::Author>,
69        body: &str,
70    ) -> impl Future<Output = laravel::Result<Self>> + Send {
71        Box::pin(ops::reply(self, author, body))
72    }
73
74    /// Replaces the text and sets `edited_at`.
75    ///
76    /// # Errors
77    ///
78    /// Fails with a [`CommentError`](crate::CommentError) when the comment is removed or the text
79    /// is invalid, or when a query fails.
80    fn edit(&mut self, body: &str) -> impl Future<Output = laravel::Result<()>> + Send {
81        Box::pin(ops::edit(self, body))
82    }
83
84    /// Approves the comment.
85    ///
86    /// # Errors
87    ///
88    /// Fails when a query fails.
89    fn approve(&mut self) -> impl Future<Output = laravel::Result<()>> + Send {
90        Box::pin(ops::moderate(self, Status::Approved))
91    }
92
93    /// Turns the comment down.
94    ///
95    /// # Errors
96    ///
97    /// Fails when a query fails.
98    fn reject(&mut self) -> impl Future<Output = laravel::Result<()>> + Send {
99        Box::pin(ops::moderate(self, Status::Rejected))
100    }
101
102    /// Marks the comment as spam.
103    ///
104    /// # Errors
105    ///
106    /// Fails when a query fails.
107    fn mark_spam(&mut self) -> impl Future<Output = laravel::Result<()>> + Send {
108        Box::pin(ops::moderate(self, Status::Spam))
109    }
110
111    /// Gives the comment any status, such as back to [`Status::Pending`].
112    ///
113    /// # Errors
114    ///
115    /// Fails when a query fails.
116    fn set_status(&mut self, status: Status) -> impl Future<Output = laravel::Result<()>> + Send {
117        Box::pin(ops::moderate(self, status))
118    }
119
120    /// Removes the comment. A comment with replies becomes a placeholder that keeps them in place;
121    /// one without is deleted, together with every placeholder above it left without replies.
122    /// Returns whether a placeholder stays.
123    ///
124    /// # Errors
125    ///
126    /// Fails when the comment no longer exists or a query fails.
127    fn remove(self) -> impl Future<Output = laravel::Result<bool>> + Send {
128        Box::pin(ops::remove(self))
129    }
130
131    /// Adds a reaction by `user`, such as `like`. Returns `false` when the user already reacted
132    /// so: one reaction of each kind per user.
133    ///
134    /// # Errors
135    ///
136    /// Fails with a [`CommentError`](crate::CommentError) when the reaction isn't allowed or the
137    /// comment isn't visible, or when a query fails.
138    fn react(&self, user: &Self::Author, reaction: &str) -> impl Future<Output = laravel::Result<bool>> + Send {
139        Box::pin(reactions::react(self, user.commenter_id(), reaction))
140    }
141
142    /// Takes a reaction by `user` back. Returns `false` when there was none.
143    ///
144    /// # Errors
145    ///
146    /// Fails when a query fails.
147    fn unreact(&self, user: &Self::Author, reaction: &str) -> impl Future<Output = laravel::Result<bool>> + Send {
148        Box::pin(reactions::unreact(self, user.commenter_id(), reaction))
149    }
150
151    /// Adds the reaction when `user` hasn't reacted so, and takes it back otherwise. Returns
152    /// whether the reaction is there now.
153    ///
154    /// # Errors
155    ///
156    /// Fails with a [`CommentError`](crate::CommentError) when the reaction isn't allowed or the
157    /// comment isn't visible, or when a query fails.
158    fn toggle_reaction(
159        &self,
160        user: &Self::Author,
161        reaction: &str,
162    ) -> impl Future<Output = laravel::Result<bool>> + Send {
163        Box::pin(reactions::toggle(self, user.commenter_id(), reaction))
164    }
165
166    /// The texts the comment had before its edits, newest first. `COMMENTS_REVISIONS=false`
167    /// stops keeping them; a removed comment's are deleted with its text.
168    fn revisions(&self) -> Builder<CommentRevision> {
169        CommentRevision::query()
170            .filter(CommentRevision::comment_id.eq(self.row().id))
171            .order_by(CommentRevision::id.desc())
172    }
173
174    /// The text as safe HTML, rendered from Markdown by [`markdown::to_html`](crate::markdown::to_html).
175    #[cfg(feature = "markdown")]
176    fn body_html(&self) -> String {
177        crate::markdown::to_html(self.row().body)
178    }
179
180    /// The threads on `on`: its top-level comments with their replies, a page at a time.
181    fn threads(on: impl Into<Self::Commentable>) -> Threads<Self> {
182        Threads::on(on.into())
183    }
184
185    /// The thread this comment is in, from its top-level comment.
186    fn thread_tree(&self) -> Threads<Self> {
187        Threads::thread(self.row().thread.to_owned())
188    }
189
190    /// Every comment on `on`, in any status: a query to add conditions to.
191    fn on(on: impl Into<Self::Commentable>) -> Builder<Self> {
192        let on = on.into();
193        Self::new_query()
194            .filter(Self::COLUMNS.commentable_type.eq(on.morph()) & Self::COLUMNS.commentable_id.eq(*on.key()))
195    }
196
197    /// The comments waiting for a moderator, oldest first.
198    fn pending() -> Builder<Self> {
199        Self::new_query()
200            .filter(Self::where_status(Status::Pending))
201            .order_by(Self::META.key.asc())
202    }
203
204    /// Comments with `status`.
205    #[must_use]
206    fn where_status(status: Status) -> Condition {
207        Self::COLUMNS.status.eq(status)
208    }
209
210    /// Comments everyone may see: approved and not removed. Use it to count comments on a model
211    /// without N+1 queries: `#[morph_many(Comment::commentable, filter = Comment::where_visible())]`
212    /// and `with_count`.
213    #[must_use]
214    fn where_visible() -> Condition {
215        Self::COLUMNS.status.eq(Status::Approved) & Self::COLUMNS.deleted_at.is_null()
216    }
217
218    /// How the comment shows in a thread.
219    fn visibility(&self) -> Visibility {
220        let row = self.row();
221        if row.deleted_at.is_some() {
222            Visibility::Deleted
223        } else if row.status == Status::Approved {
224            Visibility::Visible
225        } else {
226            Visibility::Hidden
227        }
228    }
229}
230
231/// The columns of a [`CommentModel`].
232pub struct CommentColumns<C: CommentModel> {
233    /// The morph name of the model the comment belongs to.
234    pub commentable_type: Column<C, MorphType<C::Commentable>>,
235    /// The key of the model the comment belongs to.
236    pub commentable_id: Column<C, i64>,
237    /// The thread: every comment of one top-level comment's tree shares it.
238    pub thread: Column<C, String>,
239    /// The author's key, for comments by users.
240    pub author_id: Column<C, Option<i64>>,
241    /// The guest's name, for comments by guests.
242    pub guest_name: Column<C, Option<String>>,
243    /// The guest's email address, for comments by guests.
244    pub guest_email: Column<C, Option<String>>,
245    /// The text.
246    pub body: Column<C, String>,
247    /// Where the comment stands in moderation.
248    pub status: Column<C, Status>,
249    /// When a moderator last changed the status.
250    pub moderated_at: Column<C, Option<Timestamp>>,
251    /// When the author last edited the text.
252    pub edited_at: Column<C, Option<Timestamp>>,
253    /// When the comment was removed while it had replies, leaving a placeholder.
254    pub deleted_at: Column<C, Option<Timestamp>>,
255    /// The number of direct replies.
256    pub replies_count: Column<C, i64>,
257    /// The number of reactions of every kind.
258    pub reactions_count: Column<C, i64>,
259    /// When the comment was posted.
260    pub created_at: Column<C, Option<Timestamp>>,
261}
262
263/// The values of a comment's columns, as [`CommentModel::row`] reads them.
264pub struct CommentRow<'a, C: CommentModel> {
265    /// The key.
266    pub id: i64,
267    /// The morph name of the model the comment belongs to.
268    pub commentable_type: MorphType<C::Commentable>,
269    /// The key of the model the comment belongs to.
270    pub commentable_id: i64,
271    /// The thread.
272    pub thread: &'a str,
273    /// The parent's key, for replies.
274    pub parent_id: Option<i64>,
275    /// The depth: `0` for top-level comments.
276    pub depth: i64,
277    /// The author's key, for comments by users.
278    pub author_id: Option<i64>,
279    /// The guest's name, for comments by guests.
280    pub guest_name: Option<&'a str>,
281    /// The text.
282    pub body: &'a str,
283    /// Where the comment stands in moderation.
284    pub status: Status,
285    /// When the author last edited the text.
286    pub edited_at: Option<Timestamp>,
287    /// When the comment was removed while it had replies.
288    pub deleted_at: Option<Timestamp>,
289    /// The number of direct replies.
290    pub replies_count: i64,
291    /// The number of reactions of every kind.
292    pub reactions_count: i64,
293    /// When the comment was posted.
294    pub created_at: Option<Timestamp>,
295}
296
297/// Declares the application's comment model and implements [`CommentModel`] for it.
298///
299/// List the `#[morph]` enum of the models people may comment on, and the users' model, which
300/// implements [`Commenter`]:
301///
302/// ```no_run
303/// use laravel::model::{MorphMany, model, morph};
304/// use laravel_comments::{CommentModel, Commenter};
305///
306/// #[model]
307/// pub struct User {
308///     pub id: i64,
309///     pub name: String,
310/// }
311///
312/// impl Commenter for User {
313///     fn commenter_id(&self) -> i64 {
314///         self.id
315///     }
316/// }
317///
318/// #[model]
319/// pub struct Post {
320///     pub id: i64,
321///     pub title: String,
322///     #[morph_many(Comment::commentable, filter = Comment::where_visible())]
323///     pub comments: MorphMany<Comment>,
324/// }
325///
326/// #[morph]
327/// pub enum Commentable {
328///     Post(Post),
329/// }
330///
331/// laravel_comments::comment_model! {
332///     pub struct Comment {
333///         commentable: Commentable,
334///         author: User,
335///     }
336/// }
337/// ```
338///
339/// Only the models of the enum take comments: posting on any other model doesn't compile.
340///
341/// ```compile_fail
342/// # use laravel::model::{model, morph};
343/// # use laravel_comments::{Author, CommentModel, Commenter};
344/// # #[model] pub struct User { pub id: i64 }
345/// # impl Commenter for User { fn commenter_id(&self) -> i64 { self.id } }
346/// # #[model] pub struct Post { pub id: i64 }
347/// # #[model] pub struct Invoice { pub id: i64 }
348/// # #[morph] pub enum Commentable { Post(Post) }
349/// # laravel_comments::comment_model! { pub struct Comment { commentable: Commentable, author: User } }
350/// # async fn example(invoice: Invoice, user: User) -> laravel::Result<()> {
351/// Comment::post(invoice, Author::user(&user), "Not a commentable model").await?;
352/// # Ok(()) }
353/// ```
354///
355/// The model reads the `comments` table that the package's migrations create. It has a
356/// `#[morph_to] commentable` and a `#[belongs_to] author` relation, so the usual eager loading
357/// works: `Comment::query().with((Comment::commentable, Comment::author))`. The guest's email
358/// address and the tree's bounds are left out of JSON.
359#[macro_export]
360macro_rules! comment_model {
361    (
362        $(#[$meta:meta])*
363        $vis:vis struct $name:ident {
364            commentable: $($commentable:ident)::+,
365            author: $($author:ident)::+ $(,)?
366        }
367    ) => {
368        $(#[$meta])*
369        #[$crate::__private::laravel::model::model(table = "comments")]
370        $vis struct $name {
371            pub id: i64,
372            pub commentable_type: $crate::__private::laravel::model::MorphType<$($commentable)::+>,
373            pub commentable_id: i64,
374            pub thread: String,
375            #[default]
376            #[serde(skip)]
377            pub lft: i64,
378            #[default]
379            #[serde(skip)]
380            pub rgt: i64,
381            #[default]
382            pub depth: i64,
383            pub parent_id: Option<i64>,
384            pub author_id: Option<i64>,
385            pub guest_name: Option<String>,
386            #[serde(skip)]
387            pub guest_email: Option<String>,
388            pub body: String,
389            pub status: $crate::Status,
390            pub moderated_at: Option<$crate::__private::laravel::time::Timestamp>,
391            pub edited_at: Option<$crate::__private::laravel::time::Timestamp>,
392            pub deleted_at: Option<$crate::__private::laravel::time::Timestamp>,
393            #[default]
394            pub replies_count: i64,
395            #[default]
396            pub reactions_count: i64,
397            pub created_at: Option<$crate::__private::laravel::time::Timestamp>,
398            pub updated_at: Option<$crate::__private::laravel::time::Timestamp>,
399            #[morph_to]
400            pub commentable: $crate::__private::laravel::model::MorphTo<$($commentable)::+>,
401            #[belongs_to]
402            pub author: $crate::__private::laravel::model::BelongsTo<Option<$($author)::+>>,
403        }
404
405        impl $crate::__private::laravel_nestedset::NestedSet for $name {
406            fn lft_column() -> $crate::__private::laravel::model::Column<Self, i64> {
407                $name::lft
408            }
409
410            fn rgt_column() -> $crate::__private::laravel::model::Column<Self, i64> {
411                $name::rgt
412            }
413
414            fn parent_column() -> $crate::__private::laravel::model::Column<Self, Option<i64>> {
415                $name::parent_id
416            }
417
418            fn depth_column() -> Option<$crate::__private::laravel::model::Column<Self, i64>> {
419                Some($name::depth)
420            }
421
422            fn scope(&self) -> $crate::__private::laravel_nestedset::Scope<Self> {
423                $crate::__private::laravel_nestedset::Scope::new().by($name::thread, &self.thread)
424            }
425        }
426
427        impl $crate::CommentModel for $name {
428            type Commentable = $($commentable)::+;
429            type Author = $($author)::+;
430
431            const COLUMNS: $crate::CommentColumns<Self> = $crate::CommentColumns {
432                commentable_type: $name::commentable_type,
433                commentable_id: $name::commentable_id,
434                thread: $name::thread,
435                author_id: $name::author_id,
436                guest_name: $name::guest_name,
437                guest_email: $name::guest_email,
438                body: $name::body,
439                status: $name::status,
440                moderated_at: $name::moderated_at,
441                edited_at: $name::edited_at,
442                deleted_at: $name::deleted_at,
443                replies_count: $name::replies_count,
444                reactions_count: $name::reactions_count,
445                created_at: $name::created_at,
446            };
447
448            fn new_query() -> $crate::__private::laravel::db::Builder<Self> {
449                $name::query()
450            }
451
452            fn with_author(
453                query: $crate::__private::laravel::db::Builder<Self>,
454            ) -> $crate::__private::laravel::db::Builder<Self> {
455                query.with($name::author)
456            }
457
458            fn row(&self) -> $crate::CommentRow<'_, Self> {
459                $crate::CommentRow {
460                    id: self.id,
461                    commentable_type: self.commentable_type,
462                    commentable_id: self.commentable_id,
463                    thread: &self.thread,
464                    parent_id: self.parent_id,
465                    depth: self.depth,
466                    author_id: self.author_id,
467                    guest_name: self.guest_name.as_deref(),
468                    body: &self.body,
469                    status: self.status,
470                    edited_at: self.edited_at,
471                    deleted_at: self.deleted_at,
472                    replies_count: self.replies_count,
473                    reactions_count: self.reactions_count,
474                    created_at: self.created_at,
475                }
476            }
477        }
478    };
479}