Support commenting with markdown.

This commit is contained in:
nyne
2025-07-04 13:23:56 +08:00
parent f605485f40
commit 1f22367cc4
13 changed files with 1089 additions and 505 deletions

View File

@@ -0,0 +1,195 @@
import { useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import showToast from "./toast";
import { network } from "../network/network";
import { InfoAlert } from "./alert";
import { app } from "../app";
import { MdOutlineImage, MdOutlineInfo } from "react-icons/md";
import Badge from "./badge";
export function CommentInput({
resourceId,
replyTo,
reload,
}: {
resourceId?: number;
replyTo?: number;
reload: () => void;
}) {
const [commentContent, setCommentContent] = useState("");
const [isLoading, setLoading] = useState(false);
const [isUploadingimage, setUploadingImage] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const { t } = useTranslation();
// Auto-resize textarea based on content
const adjustTextareaHeight = () => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
let height = textareaRef.current.scrollHeight;
if (height < 144) {
height = 144; // Minimum height of 144px (h-36)
}
textareaRef.current.style.height = `${height}px`;
}
};
// Reset textarea height to default
const resetTextareaHeight = () => {
if (textareaRef.current) {
textareaRef.current.style.height = '144px'; // h-36 = 144px
}
};
useEffect(() => {
adjustTextareaHeight();
}, [commentContent]);
const sendComment = async () => {
if (isLoading) {
return;
}
if (commentContent === "") {
showToast({
message: t("Comment content cannot be empty"),
type: "error",
});
return;
}
setLoading(true);
if (resourceId) {
const res = await network.createResourceComment(
resourceId,
commentContent,
);
if (res.success) {
setCommentContent("");
resetTextareaHeight();
showToast({
message: t("Comment created successfully"),
type: "success",
});
reload();
} else {
showToast({ message: res.message, type: "error" });
}
} else if (replyTo) {
const res = await network.replyToComment(replyTo, commentContent);
if (res.success) {
setCommentContent("");
resetTextareaHeight();
showToast({
message: t("Reply created successfully"),
type: "success",
});
reload();
} else {
showToast({ message: res.message, type: "error" });
}
} else {
showToast({
message: t("Invalid resource or reply ID"),
type: "error",
});
}
setLoading(false);
};
const handleAddImage = () => {
if (isUploadingimage) {
return;
}
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.multiple = true;
input.onchange = async (e) => {
const files = (e.target as HTMLInputElement).files;
if (files) {
for (let i = 0; i < files.length; i++) {
if (files[i].size > 8 * 1024 * 1024) {
showToast({
message: t("Image size exceeds 5MB limit"),
type: "error",
});
return;
}
}
setUploadingImage(true);
const imageIds: number[] = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const res = await network.uploadImage(file);
if (res.success) {
imageIds.push(res.data!);
} else {
showToast({ message: res.message, type: "error" });
setUploadingImage(false);
return;
}
}
if (imageIds.length > 0) {
setCommentContent((prev) => {
return (
prev +
"\n" +
imageIds.map((id) => `![Image](/api/image/${id})`).join(" ")
);
});
}
setUploadingImage(false);
}
};
input.click();
};
if (!app.isLoggedIn()) {
return (
<InfoAlert
message={t("You need to log in to comment")}
className={"my-4 alert-info"}
/>
);
}
return (
<div className={"mt-4 mb-6 textarea w-full p-4 flex flex-col"}>
<textarea
ref={textareaRef}
placeholder={t("Write down your comment")}
className={"w-full resize-none grow h-36"}
value={commentContent}
onChange={(e) => setCommentContent(e.target.value)}
/>
<div className={"flex items-center"}>
<button
className={"btn btn-ghost btn-sm btn-circle"}
onClick={handleAddImage}
>
{isUploadingimage ? (
<span className={"loading loading-spinner loading-sm"}></span>
) : (
<MdOutlineImage size={18} />
)}
</button>
<Badge className="badge-ghost">
<MdOutlineInfo size={18} />
<span>
{t("Use markdown format.")}
</span>
</Badge>
<span className={"grow"} />
<button
onClick={sendComment}
className={`btn btn-primary h-8 text-sm mx-2 ${commentContent === "" && "btn-disabled"}`}
>
{isLoading ? (
<span className={"loading loading-spinner loading-sm"}></span>
) : null}
{t("Submit")}
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,246 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router";
import { MdOutlineDelete, MdOutlineEdit, MdOutlineReply } from "react-icons/md";
import { TextArea } from "./input";
import { Comment } from "../network/models";
import { network } from "../network/network";
import Badge from "./badge";
import { app } from "../app";
import showToast from "./toast";
import Markdown from "react-markdown";
export function CommentTile({
comment,
onUpdated,
}: {
comment: Comment;
onUpdated?: () => void;
}) {
const navigate = useNavigate();
const { t } = useTranslation();
const link = `/comments/${comment.id}`;
// @ts-ignore
return (
<a
href={link}
className={
"block card bg-base-100 p-2 my-3 shadow-xs hover:shadow transition-shadow cursor-pointer"
}
onClick={(e) => {
e.preventDefault();
navigate(link);
}}
>
<div className={"flex flex-row items-center my-1 mx-1"}>
<div
className="avatar cursor-pointer"
onClick={() =>
navigate(`/user/${encodeURIComponent(comment.user.username)}`)
}
>
<div className="w-8 rounded-full">
<img src={network.getUserAvatar(comment.user)} alt={"avatar"} />
</div>
</div>
<div className={"w-2"}></div>
<div
className={"text-sm font-bold cursor-pointer"}
onClick={() => {
navigate(`/user/${encodeURIComponent(comment.user.username)}`);
}}
>
{comment.user.username}
</div>
<div className={"grow"}></div>
{comment.reply_count > 0 && (
<Badge className={"badge-soft badge-info badge-sm mr-2"}>
<MdOutlineReply size={16} className={"inline-block"} />
<span className={"w-1"} />
{comment.reply_count}
</Badge>
)}
<Badge className={"badge-soft badge-primary badge-sm"}>
{new Date(comment.created_at).toLocaleString()}
</Badge>
</div>
<div className={"p-2 comment_tile"}>
<CommentContent content={comment.content} />
</div>
<div className={"flex"}>
{comment.content_truncated && (
<Badge className="badge-soft">{t("Click to view more")}</Badge>
)}
<span className={"grow"}></span>
{app.user?.id === comment.user.id && (
<>
<EditCommentDialog comment={comment} onUpdated={onUpdated} />
<DeleteCommentDialog commentId={comment.id} onUpdated={onUpdated} />
</>
)}
</div>
</a>
);
}
function EditCommentDialog({
comment,
onUpdated,
}: {
comment: Comment;
onUpdated?: () => void;
}) {
const [isLoading, setLoading] = useState(false);
const [content, setContent] = useState(comment.content);
const { t } = useTranslation();
const handleUpdate = async () => {
if (isLoading) {
return;
}
setLoading(true);
const res = await network.updateComment(comment.id, content);
const dialog = document.getElementById(
`edit_comment_dialog_${comment.id}`,
) as HTMLDialogElement;
dialog.close();
if (res.success) {
showToast({
message: t("Comment updated successfully"),
type: "success",
});
if (onUpdated) {
onUpdated();
}
} else {
showToast({
message: res.message,
type: "error",
parent: document.getElementById(`dialog_box`),
});
}
setLoading(false);
};
return (
<>
<button
className={"btn btn-sm btn-ghost ml-1"}
onClick={() => {
const dialog = document.getElementById(
`edit_comment_dialog_${comment.id}`,
) as HTMLDialogElement;
dialog.showModal();
}}
>
<MdOutlineEdit size={16} className={"inline-block"} />
{t("Edit")}
</button>
<dialog id={`edit_comment_dialog_${comment.id}`} className="modal">
<div className="modal-box" id={"dialog_box"}>
<h3 className="font-bold text-lg">{t("Edit Comment")}</h3>
<TextArea
label={t("Content")}
value={content}
onChange={(e) => setContent(e.target.value)}
/>
<div className="modal-action">
<form method="dialog">
<button className="btn btn-ghost">{t("Close")}</button>
</form>
<button className="btn btn-primary" onClick={handleUpdate}>
{isLoading ? (
<span className={"loading loading-spinner loading-sm"}></span>
) : null}
{t("Submit")}
</button>
</div>
</div>
</dialog>
</>
);
}
function DeleteCommentDialog({
commentId,
onUpdated,
}: {
commentId: number;
onUpdated?: () => void;
}) {
const [isLoading, setLoading] = useState(false);
const { t } = useTranslation();
const id = `delete_comment_dialog_${commentId}`;
const handleDelete = async () => {
if (isLoading) return;
setLoading(true);
const res = await network.deleteComment(commentId);
const dialog = document.getElementById(id) as HTMLDialogElement;
dialog.close();
if (res.success) {
showToast({
message: t("Comment deleted successfully"),
type: "success",
});
if (onUpdated) {
onUpdated();
}
} else {
showToast({ message: res.message, type: "error" });
}
setLoading(false);
};
return (
<>
<button
className={"btn btn-error btn-sm btn-ghost ml-1"}
onClick={() => {
const dialog = document.getElementById(id) as HTMLDialogElement;
dialog.showModal();
}}
>
<MdOutlineDelete size={16} className={"inline-block"} />
{t("Delete")}
</button>
<dialog id={id} className="modal">
<div className="modal-box">
<h3 className="font-bold text-lg">{t("Delete Comment")}</h3>
<p className="py-4">
{t(
"Are you sure you want to delete this comment? This action cannot be undone.",
)}
</p>
<div className="modal-action">
<form method="dialog">
<button className="btn btn-ghost">{t("Close")}</button>
</form>
<button className="btn btn-error" onClick={handleDelete}>
{isLoading ? (
<span className={"loading loading-spinner loading-sm"}></span>
) : null}
{t("Delete")}
</button>
</div>
</div>
</dialog>
</>
);
}
function CommentContent({ content }: { content: string }) {
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (!line.endsWith(" ")) {
// Ensure that each line ends with two spaces for Markdown to recognize it as a line break
lines[i] = line + " ";
}
}
content = lines.join("\n");
return <Markdown>{content}</Markdown>;
}

View File

@@ -34,7 +34,7 @@ export default function ResourceCard({ resource }: { resource: Resource }) {
</figure>
)}
<div className="flex flex-col p-4">
<h2 className="card-title">{resource.title}</h2>
<h2 className="card-title break-all">{resource.title}</h2>
<div className="h-2"></div>
<p>
{tags.map((tag) => {