feat(comments): implement delete comment functionality with confirmation modal

This commit is contained in:
2026-04-24 09:26:53 -04:00
parent 63b77bece9
commit 95ca811d42
3 changed files with 133 additions and 8 deletions
@@ -1,13 +1,14 @@
<script lang="ts"> <script lang="ts">
import type { CommentReaction, CommentTreeNode } from '$lib/types/comment'; import type { CommentReaction, CommentTreeNode } from '$lib/types/comment';
import { dateToRelativeString } from '$lib/utils/misc'; import { dateToRelativeString, tooltip } from '$lib/utils/misc';
import { parseCommentMarkdown } from '$lib/utils/markdown'; import { parseCommentMarkdown } from '$lib/utils/markdown';
import { escapeHtml } from '$lib/utils/html'; import { escapeHtml } from '$lib/utils/html';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import PasteCommentItem from '$lib/components/PasteCommentItem.svelte'; import PasteCommentItem from '$lib/components/PasteCommentItem.svelte';
import { ThumbsUp, ThumbsDown } from '@lucide/svelte'; import { ThumbsUp, ThumbsDown, Trash2, Shredder } from '@lucide/svelte';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import { hasRole } from '$lib/utils/auth';
interface Props { interface Props {
node: CommentTreeNode; node: CommentTreeNode;
@@ -16,9 +17,19 @@
reactingIds: Record<number, boolean>; reactingIds: Record<number, boolean>;
onReact: (commentId: number, target: 1 | 2, current: CommentReaction) => Promise<void>; onReact: (commentId: number, target: 1 | 2, current: CommentReaction) => Promise<void>;
onReply: (parentCommentID: number, content: string) => Promise<boolean>; onReply: (parentCommentID: number, content: string) => Promise<boolean>;
deleteCommentAction: (commentId: number, hardDelete?: boolean) => Promise<boolean>;
} }
let { node, depth = 1, now, reactingIds, onReact, onReply }: Props = $props(); let {
node,
depth = 1,
now,
reactingIds,
onReact,
onReply,
deleteCommentAction
}: Props = $props();
let deleting = $state(false);
const maxCommentLength = 320; const maxCommentLength = 320;
let expanded = $state(false); let expanded = $state(false);
@@ -29,7 +40,7 @@
let replyError = $state(''); let replyError = $state('');
let replyEditor = $state<{ focus: () => void } | undefined>(undefined); let replyEditor = $state<{ focus: () => void } | undefined>(undefined);
let commentText = $derived(node.content ?? 'Deleted comment'); let commentText = $derived(node.content ?? '*[Deleted comment]*');
let isLongComment = $derived(commentText.length > maxCommentLength); let isLongComment = $derived(commentText.length > maxCommentLength);
let isDeleted = $derived(node.content === null); let isDeleted = $derived(node.content === null);
let parsedHtml = $derived( let parsedHtml = $derived(
@@ -73,6 +84,13 @@
replyEditor?.focus(); replyEditor?.focus();
}); });
} }
async function handleDelete(hardDelete = false) {
if (deleting) return;
deleting = true;
await deleteCommentAction(node.id, hardDelete);
deleting = false;
}
</script> </script>
<div class="p-3"> <div class="p-3">
@@ -94,7 +112,11 @@
</a> </a>
{/if} {/if}
{#if node.updatedAt} {#if node.updatedAt}
<span class="text-neutral-500">edited</span> <span
class="text-sm text-neutral-500"
use:tooltip={`Edited on ${new Date(node.updatedAt * 1000).toLocaleString()} • ${dateToRelativeString(new Date(node.updatedAt * 1000), true, true, now, 3)}`}
>edited</span
>
{/if} {/if}
</div> </div>
<span class="shrink-0" <span class="shrink-0"
@@ -103,7 +125,7 @@
</div> </div>
<div class="text-sm leading-relaxed text-neutral-200"> <div class="text-sm leading-relaxed text-neutral-200">
<div class="wrap-break-word" class:text-neutral-500={isDeleted}> <div class="wrap-break-word" class:italic={isDeleted} class:text-neutral-800={isDeleted}>
{#if expanded || !isLongComment} {#if expanded || !isLongComment}
<!-- eslint-disable-next-line svelte/no-at-html-tags --> <!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html parsedHtml} {@html parsedHtml}
@@ -164,7 +186,7 @@
{#if !replyOpen} {#if !replyOpen}
<button <button
type="button" type="button"
class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:text-neutral-100" class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => { onclick={() => {
openReply(node.content ? `> ${node.content.replace(/\n/g, '\n> ')}\n\n` : ''); openReply(node.content ? `> ${node.content.replace(/\n/g, '\n> ')}\n\n` : '');
}} }}
@@ -174,7 +196,7 @@
{/if} {/if}
<button <button
type="button" type="button"
class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:text-neutral-100" class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => { onclick={() => {
if (replyOpen) { if (replyOpen) {
replyOpen = false; replyOpen = false;
@@ -187,6 +209,26 @@
> >
{replyOpen ? 'Cancel' : 'Reply'} {replyOpen ? 'Cancel' : 'Reply'}
</button> </button>
<div class="ml-auto">
<button
type="button"
class="h-7 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => handleDelete(false)}
disabled={deleting}
>
<Trash2 class="inline h-3.5 w-3.5" />
</button>
{#if hasRole($user.roles, 4)}
<button
type="button"
class="h-7 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => handleDelete(true)}
disabled={deleting}
>
<Shredder class="inline h-3.5 w-3.5" />
</button>
{/if}
</div>
{/if} {/if}
</div> </div>
@@ -227,6 +269,7 @@
{reactingIds} {reactingIds}
{onReact} {onReact}
{onReply} {onReply}
{deleteCommentAction}
/> />
{/each} {/each}
</div> </div>
@@ -11,6 +11,7 @@
import PasteCommentItem from '$lib/components/PasteCommentItem.svelte'; import PasteCommentItem from '$lib/components/PasteCommentItem.svelte';
import { SvelteMap } from 'svelte/reactivity'; import { SvelteMap } from 'svelte/reactivity';
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import { openModal } from '$lib/stores/modal';
interface Props { interface Props {
pasteId: string; pasteId: string;
@@ -187,6 +188,52 @@
async function submitTopLevelComment(content: string) { async function submitTopLevelComment(content: string) {
await postComment(content, null); await postComment(content, null);
} }
async function deleteComment(commentId: number, hardDelete = false): Promise<boolean> {
errorMessage = '';
const token = getToken();
if (!token) {
errorMessage = 'You must be signed in to delete comments.';
return false;
}
const title = hardDelete ? 'Hard delete comment?' : 'Delete comment?';
const message = hardDelete
? 'This permanently removes the comment from the thread. This cannot be undone.'
: 'This will remove the comment content while preserving the thread structure.';
const confirmButtonText = hardDelete ? 'Hard delete' : 'Delete';
const ok = await openModal<boolean>({
mode: 'confirm',
title,
message,
confirmButtonText,
cancelValue: false
});
if (!ok) {
return false;
}
try {
const query = hardDelete ? '?hardDelete=true' : '';
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}${query}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`
}
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
errorMessage = err?.message || 'Failed to delete comment.';
return false;
}
await refreshComments();
return true;
} catch {
errorMessage = 'Failed to delete comment.';
return false;
}
}
</script> </script>
<section id="comments-section" class="mt-6 rounded border border-neutral-800 p-4"> <section id="comments-section" class="mt-6 rounded border border-neutral-800 p-4">
@@ -239,6 +286,7 @@
{reactingIds} {reactingIds}
onReact={reactToComment} onReact={reactToComment}
onReply={(parentCommentID, content) => postComment(content, parentCommentID)} onReply={(parentCommentID, content) => postComment(content, parentCommentID)}
deleteCommentAction={deleteComment}
/> />
{/each} {/each}
</div> </div>
@@ -514,6 +514,40 @@ namespace SharpbinV3.Server.Controllers
); );
} }
[HttpDelete]
[Authorize(Policy = "JwtOnly")]
[Route("{id}/comments/{commentId}")]
public async Task<IActionResult> DeleteComment(string id, long commentId, bool hardDelete = false)
{
var paste = await _pasteService.Get(id);
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" });
var comment = await _commentService.GetCommentByID(commentId, paste.PID);
if (comment == null)
return NotFound(new { success = false, message = "Comment not found for this paste." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return Unauthorized(new { success = false, message = "User not authenticated." });
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (comment.UserUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this comment." });
if (hardDelete && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to hard delete this comment." });
bool result;
if (hardDelete)
result = await _commentService.HardDeleteComment(comment);
else
result = await _commentService.DeleteComment(comment);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the comment." });
return Ok(new { success = true, message = "Comment deleted successfully." });
}
[HttpGet] [HttpGet]
[EnableRateLimiting("NoLimit")] [EnableRateLimiting("NoLimit")]
[Route("info")] [Route("info")]