laravel-comments 0.2.1

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! `CommentModel`: the trait the application's comment model implements, and the
//! [`comment_model!`](crate::comment_model) macro that declares one.

use std::future::Future;

use laravel::db::{Builder, Condition};
use laravel::model::{Column, Model, Morph, MorphType};
use laravel::time::Timestamp;
use laravel_nestedset::NestedSet;
use serde::Serialize;

use crate::author::{Author, Commenter};
use crate::revisions::CommentRevision;
use crate::status::{Status, Visibility};
use crate::thread::Threads;
use crate::{ops, reactions};

/// The application's comment model.
///
/// Declare it with [`comment_model!`](crate::comment_model), which writes the model and this
/// trait's implementation for you. The trait's provided methods are the package's API: posting,
/// replying, moderating, editing, and removing comments, and reading threads.
pub trait CommentModel: NestedSet<Key = i64> + Serialize {
    /// The `#[morph]` enum of the models comments may belong to, such as `Post` and `Video`.
    type Commentable: Morph<Key = i64>;

    /// The model of the users who write comments.
    type Author: Model<Key = i64> + Commenter;

    /// The model's columns.
    const COLUMNS: CommentColumns<Self>;

    /// The values of the columns the package reads.
    fn row(&self) -> CommentRow<'_, Self>;

    /// A query on every comment. `comment_model!` returns `Self::query()`.
    fn new_query() -> Builder<Self>;

    /// Adds the eager loading of the author to `query`. `comment_model!` loads `Self::author`.
    fn with_author(query: Builder<Self>) -> Builder<Self>;

    /// Posts a top-level comment on `on`, a model of [`Self::Commentable`]. The comment gets the
    /// status that the moderation rule gives it, and [`CommentPosted`](crate::events::CommentPosted)
    /// is dispatched.
    ///
    /// # Errors
    ///
    /// Fails with a [`CommentError`](crate::CommentError) when the text or the guest is invalid,
    /// or when a query fails.
    fn post(
        on: impl Into<Self::Commentable> + Send,
        author: Author<'_, Self::Author>,
        body: &str,
    ) -> impl Future<Output = laravel::Result<Self>> + Send {
        Box::pin(ops::post::<Self>(on.into(), author, body))
    }

    /// Posts a reply to this comment, and reloads it. Below `COMMENTS_MAX_DEPTH`, the reply joins
    /// this comment's parent's replies instead, as on Reddit.
    ///
    /// # Errors
    ///
    /// Fails with a [`CommentError`](crate::CommentError) when this comment is removed or isn't
    /// approved, when replies are off, when the text or the guest is invalid, or when a query
    /// fails.
    fn reply(
        &mut self,
        author: Author<'_, Self::Author>,
        body: &str,
    ) -> impl Future<Output = laravel::Result<Self>> + Send {
        Box::pin(ops::reply(self, author, body))
    }

    /// Replaces the text and sets `edited_at`.
    ///
    /// # Errors
    ///
    /// Fails with a [`CommentError`](crate::CommentError) when the comment is removed or the text
    /// is invalid, or when a query fails.
    fn edit(&mut self, body: &str) -> impl Future<Output = laravel::Result<()>> + Send {
        Box::pin(ops::edit(self, body))
    }

    /// Approves the comment.
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    fn approve(&mut self) -> impl Future<Output = laravel::Result<()>> + Send {
        Box::pin(ops::moderate(self, Status::Approved))
    }

    /// Turns the comment down.
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    fn reject(&mut self) -> impl Future<Output = laravel::Result<()>> + Send {
        Box::pin(ops::moderate(self, Status::Rejected))
    }

    /// Marks the comment as spam.
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    fn mark_spam(&mut self) -> impl Future<Output = laravel::Result<()>> + Send {
        Box::pin(ops::moderate(self, Status::Spam))
    }

    /// Gives the comment any status, such as back to [`Status::Pending`].
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    fn set_status(&mut self, status: Status) -> impl Future<Output = laravel::Result<()>> + Send {
        Box::pin(ops::moderate(self, status))
    }

    /// Removes the comment. A comment with replies becomes a placeholder that keeps them in place;
    /// one without is deleted, together with every placeholder above it left without replies.
    /// Returns whether a placeholder stays.
    ///
    /// # Errors
    ///
    /// Fails when the comment no longer exists or a query fails.
    fn remove(self) -> impl Future<Output = laravel::Result<bool>> + Send {
        Box::pin(ops::remove(self))
    }

    /// Adds a reaction by `user`, such as `like`. Returns `false` when the user already reacted
    /// so: one reaction of each kind per user.
    ///
    /// # Errors
    ///
    /// Fails with a [`CommentError`](crate::CommentError) when the reaction isn't allowed or the
    /// comment isn't visible, or when a query fails.
    fn react(&self, user: &Self::Author, reaction: &str) -> impl Future<Output = laravel::Result<bool>> + Send {
        Box::pin(reactions::react(self, user.commenter_id(), reaction))
    }

    /// Takes a reaction by `user` back. Returns `false` when there was none.
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    fn unreact(&self, user: &Self::Author, reaction: &str) -> impl Future<Output = laravel::Result<bool>> + Send {
        Box::pin(reactions::unreact(self, user.commenter_id(), reaction))
    }

    /// Adds the reaction when `user` hasn't reacted so, and takes it back otherwise. Returns
    /// whether the reaction is there now.
    ///
    /// # Errors
    ///
    /// Fails with a [`CommentError`](crate::CommentError) when the reaction isn't allowed or the
    /// comment isn't visible, or when a query fails.
    fn toggle_reaction(
        &self,
        user: &Self::Author,
        reaction: &str,
    ) -> impl Future<Output = laravel::Result<bool>> + Send {
        Box::pin(reactions::toggle(self, user.commenter_id(), reaction))
    }

    /// The texts the comment had before its edits, newest first. `COMMENTS_REVISIONS=false`
    /// stops keeping them; a removed comment's are deleted with its text.
    fn revisions(&self) -> Builder<CommentRevision> {
        CommentRevision::query()
            .filter(CommentRevision::comment_id.eq(self.row().id))
            .order_by(CommentRevision::id.desc())
    }

    /// The text as safe HTML, rendered from Markdown by [`markdown::to_html`](crate::markdown::to_html).
    #[cfg(feature = "markdown")]
    fn body_html(&self) -> String {
        crate::markdown::to_html(self.row().body)
    }

    /// The threads on `on`: its top-level comments with their replies, a page at a time.
    fn threads(on: impl Into<Self::Commentable>) -> Threads<Self> {
        Threads::on(on.into())
    }

    /// The thread this comment is in, from its top-level comment.
    fn thread_tree(&self) -> Threads<Self> {
        Threads::thread(self.row().thread.to_owned())
    }

    /// Every comment on `on`, in any status: a query to add conditions to.
    fn on(on: impl Into<Self::Commentable>) -> Builder<Self> {
        let on = on.into();
        Self::new_query()
            .filter(Self::COLUMNS.commentable_type.eq(on.morph()) & Self::COLUMNS.commentable_id.eq(*on.key()))
    }

    /// The comments waiting for a moderator, oldest first.
    fn pending() -> Builder<Self> {
        Self::new_query()
            .filter(Self::where_status(Status::Pending))
            .order_by(Self::META.key.asc())
    }

    /// Comments with `status`.
    #[must_use]
    fn where_status(status: Status) -> Condition {
        Self::COLUMNS.status.eq(status)
    }

    /// Comments everyone may see: approved and not removed. Use it to count comments on a model
    /// without N+1 queries: `#[morph_many(Comment::commentable, filter = Comment::where_visible())]`
    /// and `with_count`.
    #[must_use]
    fn where_visible() -> Condition {
        Self::COLUMNS.status.eq(Status::Approved) & Self::COLUMNS.deleted_at.is_null()
    }

    /// How the comment shows in a thread.
    fn visibility(&self) -> Visibility {
        let row = self.row();
        if row.deleted_at.is_some() {
            Visibility::Deleted
        } else if row.status == Status::Approved {
            Visibility::Visible
        } else {
            Visibility::Hidden
        }
    }
}

/// The columns of a [`CommentModel`].
pub struct CommentColumns<C: CommentModel> {
    /// The morph name of the model the comment belongs to.
    pub commentable_type: Column<C, MorphType<C::Commentable>>,
    /// The key of the model the comment belongs to.
    pub commentable_id: Column<C, i64>,
    /// The thread: every comment of one top-level comment's tree shares it.
    pub thread: Column<C, String>,
    /// The author's key, for comments by users.
    pub author_id: Column<C, Option<i64>>,
    /// The guest's name, for comments by guests.
    pub guest_name: Column<C, Option<String>>,
    /// The guest's email address, for comments by guests.
    pub guest_email: Column<C, Option<String>>,
    /// The text.
    pub body: Column<C, String>,
    /// Where the comment stands in moderation.
    pub status: Column<C, Status>,
    /// When a moderator last changed the status.
    pub moderated_at: Column<C, Option<Timestamp>>,
    /// When the author last edited the text.
    pub edited_at: Column<C, Option<Timestamp>>,
    /// When the comment was removed while it had replies, leaving a placeholder.
    pub deleted_at: Column<C, Option<Timestamp>>,
    /// The number of direct replies.
    pub replies_count: Column<C, i64>,
    /// The number of reactions of every kind.
    pub reactions_count: Column<C, i64>,
    /// When the comment was posted.
    pub created_at: Column<C, Option<Timestamp>>,
}

/// The values of a comment's columns, as [`CommentModel::row`] reads them.
pub struct CommentRow<'a, C: CommentModel> {
    /// The key.
    pub id: i64,
    /// The morph name of the model the comment belongs to.
    pub commentable_type: MorphType<C::Commentable>,
    /// The key of the model the comment belongs to.
    pub commentable_id: i64,
    /// The thread.
    pub thread: &'a str,
    /// The parent's key, for replies.
    pub parent_id: Option<i64>,
    /// The depth: `0` for top-level comments.
    pub depth: i64,
    /// The author's key, for comments by users.
    pub author_id: Option<i64>,
    /// The guest's name, for comments by guests.
    pub guest_name: Option<&'a str>,
    /// The text.
    pub body: &'a str,
    /// Where the comment stands in moderation.
    pub status: Status,
    /// When the author last edited the text.
    pub edited_at: Option<Timestamp>,
    /// When the comment was removed while it had replies.
    pub deleted_at: Option<Timestamp>,
    /// The number of direct replies.
    pub replies_count: i64,
    /// The number of reactions of every kind.
    pub reactions_count: i64,
    /// When the comment was posted.
    pub created_at: Option<Timestamp>,
}

/// Declares the application's comment model and implements [`CommentModel`] for it.
///
/// List the `#[morph]` enum of the models people may comment on, and the users' model, which
/// implements [`Commenter`]:
///
/// ```no_run
/// use laravel::model::{MorphMany, model, morph};
/// use laravel_comments::{CommentModel, Commenter};
///
/// #[model]
/// pub struct User {
///     pub id: i64,
///     pub name: String,
/// }
///
/// impl Commenter for User {
///     fn commenter_id(&self) -> i64 {
///         self.id
///     }
/// }
///
/// #[model]
/// pub struct Post {
///     pub id: i64,
///     pub title: String,
///     #[morph_many(Comment::commentable, filter = Comment::where_visible())]
///     pub comments: MorphMany<Comment>,
/// }
///
/// #[morph]
/// pub enum Commentable {
///     Post(Post),
/// }
///
/// laravel_comments::comment_model! {
///     pub struct Comment {
///         commentable: Commentable,
///         author: User,
///     }
/// }
/// ```
///
/// Only the models of the enum take comments: posting on any other model doesn't compile.
///
/// ```compile_fail
/// # use laravel::model::{model, morph};
/// # use laravel_comments::{Author, CommentModel, Commenter};
/// # #[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 }
/// # #[model] pub struct Invoice { pub id: i64 }
/// # #[morph] pub enum Commentable { Post(Post) }
/// # laravel_comments::comment_model! { pub struct Comment { commentable: Commentable, author: User } }
/// # async fn example(invoice: Invoice, user: User) -> laravel::Result<()> {
/// Comment::post(invoice, Author::user(&user), "Not a commentable model").await?;
/// # Ok(()) }
/// ```
///
/// The model reads the `comments` table that the package's migrations create. It has a
/// `#[morph_to] commentable` and a `#[belongs_to] author` relation, so the usual eager loading
/// works: `Comment::query().with((Comment::commentable, Comment::author))`. The guest's email
/// address and the tree's bounds are left out of JSON.
#[macro_export]
macro_rules! comment_model {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            commentable: $($commentable:ident)::+,
            author: $($author:ident)::+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[$crate::__private::laravel::model::model(table = "comments")]
        $vis struct $name {
            pub id: i64,
            pub commentable_type: $crate::__private::laravel::model::MorphType<$($commentable)::+>,
            pub commentable_id: i64,
            pub thread: String,
            #[default]
            #[serde(skip)]
            pub lft: i64,
            #[default]
            #[serde(skip)]
            pub rgt: i64,
            #[default]
            pub depth: i64,
            pub parent_id: Option<i64>,
            pub author_id: Option<i64>,
            pub guest_name: Option<String>,
            #[serde(skip)]
            pub guest_email: Option<String>,
            pub body: String,
            pub status: $crate::Status,
            pub moderated_at: Option<$crate::__private::laravel::time::Timestamp>,
            pub edited_at: Option<$crate::__private::laravel::time::Timestamp>,
            pub deleted_at: Option<$crate::__private::laravel::time::Timestamp>,
            #[default]
            pub replies_count: i64,
            #[default]
            pub reactions_count: i64,
            pub created_at: Option<$crate::__private::laravel::time::Timestamp>,
            pub updated_at: Option<$crate::__private::laravel::time::Timestamp>,
            #[morph_to]
            pub commentable: $crate::__private::laravel::model::MorphTo<$($commentable)::+>,
            #[belongs_to]
            pub author: $crate::__private::laravel::model::BelongsTo<Option<$($author)::+>>,
        }

        impl $crate::__private::laravel_nestedset::NestedSet for $name {
            fn lft_column() -> $crate::__private::laravel::model::Column<Self, i64> {
                $name::lft
            }

            fn rgt_column() -> $crate::__private::laravel::model::Column<Self, i64> {
                $name::rgt
            }

            fn parent_column() -> $crate::__private::laravel::model::Column<Self, Option<i64>> {
                $name::parent_id
            }

            fn depth_column() -> Option<$crate::__private::laravel::model::Column<Self, i64>> {
                Some($name::depth)
            }

            fn scope(&self) -> $crate::__private::laravel_nestedset::Scope<Self> {
                $crate::__private::laravel_nestedset::Scope::new().by($name::thread, &self.thread)
            }
        }

        impl $crate::CommentModel for $name {
            type Commentable = $($commentable)::+;
            type Author = $($author)::+;

            const COLUMNS: $crate::CommentColumns<Self> = $crate::CommentColumns {
                commentable_type: $name::commentable_type,
                commentable_id: $name::commentable_id,
                thread: $name::thread,
                author_id: $name::author_id,
                guest_name: $name::guest_name,
                guest_email: $name::guest_email,
                body: $name::body,
                status: $name::status,
                moderated_at: $name::moderated_at,
                edited_at: $name::edited_at,
                deleted_at: $name::deleted_at,
                replies_count: $name::replies_count,
                reactions_count: $name::reactions_count,
                created_at: $name::created_at,
            };

            fn new_query() -> $crate::__private::laravel::db::Builder<Self> {
                $name::query()
            }

            fn with_author(
                query: $crate::__private::laravel::db::Builder<Self>,
            ) -> $crate::__private::laravel::db::Builder<Self> {
                query.with($name::author)
            }

            fn row(&self) -> $crate::CommentRow<'_, Self> {
                $crate::CommentRow {
                    id: self.id,
                    commentable_type: self.commentable_type,
                    commentable_id: self.commentable_id,
                    thread: &self.thread,
                    parent_id: self.parent_id,
                    depth: self.depth,
                    author_id: self.author_id,
                    guest_name: self.guest_name.as_deref(),
                    body: &self.body,
                    status: self.status,
                    edited_at: self.edited_at,
                    deleted_at: self.deleted_at,
                    replies_count: self.replies_count,
                    reactions_count: self.reactions_count,
                    created_at: self.created_at,
                }
            }
        }
    };
}