User: 'No one logged in'

Svelte 5 Commenter

Blog posts, forum posts and news articles usually have a comments section.

This project was created using Svelte 5, and demonstrates a 'comment section'; a series of recursive, nested comments, and their replies, and their replies (and so forth).

To accomplish this, import the code in itself, ie, in the code Comments.svelte, add:

import Comments from '$lib/Components/Comments.svelte'

Then invoke it later in the code as appropriate:

<Comments {blog}>

This replaces the pre version 5 (deprecated) <svelte:self>

This purpose of this site is to examine the mechanics of a blog/comment/replies functionality, and UI synergy between login state and blog actions (such as Add and Delete)

The Front End

This:

Comment 1 Reply 1 Sub Reply 1 Sub Reply 2 Reply 2 Comment 2

is generated with this:

{#if blog.replies && showReplies} {#each blog.replies as blog} <div style="margin-left: {indent};"> <Comments {blog}/> </div> {/each} {/if}

The key concept here is that the 'replies' blog property (an array) has its own 'replies' property (again, an array) as a member.

So, if a reply has more replies under it (ie, a non-empty replies array), the component

<Comments {blog}  />

is invoked until there are no more nested replies.

Take careful note of the 'blog.replies' array in the preceeding code and 'replies' array in the following schema. If non-empty, recursion occurs.

export const blogSchema = new Schema({ userid: String, // user id of author username: String, // user name of author title: String, entry: String, likes: Number, dislikes: Number, replies: [] });

The 'Add Item' button just adds another item (blog, in this case) to the list of 'commentable items'. The 'List Users' in the navbar is an admin thing, and is disabled for this demo site. But if you clone the site and want to use it, just remove the class 'noOp' for its anchor in +layout.svelte

For this, the demo site only (the live site you see with the accompanying link), the 'Add Item' and 'Add Comment' buttons are always enabled so the user can try them out. On a real site, enable the $derived disableBtn logic in /+page.svelte and $lib/Components/Comments.svelte. 'Delete' (a blog, comment or reply) is also far more lenient than a real site would be, but deleting other people's texts is not allowed.

The Backend

The database is MongoDB and Mongoose.

Under src/api you will find mongo.js, which connects to a MongoDB Atlas database which uses a .env variable, and schema.js, which contains database schemas for the users and the blogs.

The 'Login' (the /login route) is rudimentary; just a username and password. It does, however, use some simple zod validation, and provides an example of some newer Svelte v5 logic for forms.

Acknowledgements

The project uses picnic.css for styling and ICONPACKS (www.iconpacks.net) for icons.