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

@@ -14,6 +14,7 @@ import AboutPage from "./pages/about_page.tsx";
import TagsPage from "./pages/tags_page.tsx";
import RandomPage from "./pages/random_page.tsx";
import ActivitiesPage from "./pages/activities_page.tsx";
import CommentPage from "./pages/comment_page.tsx";
export default function App() {
return (
@@ -34,6 +35,7 @@ export default function App() {
<Route path={"/tags"} element={<TagsPage />} />
<Route path={"/random"} element={<RandomPage />} />
<Route path={"/activity"} element={<ActivitiesPage />} />
<Route path={"/comments/:id"} element={<CommentPage />} />
</Route>
</Routes>
</BrowserRouter>

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) => {

View File

@@ -1,6 +1,7 @@
article {
& {
color: var(--color-base-content);
word-break: break-all;
}
h1 {
@@ -9,59 +10,70 @@ article {
padding: 12px 0;
margin: 24px 0 12px;
}
h2 {
font-size: 20px;
font-weight: bold;
padding: 12px 0;
margin: 16px 0 8px;
}
h3 {
font-size: 16px;
font-weight: bold;
padding: 6px 0;
margin: 12px 0 4px;
}
h4 {
font-size: 14px;
font-weight: bold;
padding: 6px 0;
margin: 12px 0 4px;
}
h5 {
font-size: 12px;
font-weight: bold;
padding: 4px 0;
}
h6 {
font-size: 10px;
font-weight: bold;
padding: 2px 0;
}
p {
font-size: 14px;
line-height: 1.6;
margin: 12px 0;
}
ul {
list-style-type: disc;
margin: 0 0 16px 20px;
padding: 0;
li {
font-size: 14px;
line-height: 1.5;
margin: 0 0 8px;
}
}
ol {
list-style-type: decimal;
margin: 0 0 16px 20px;
padding: 0;
li {
font-size: 14px;
line-height: 1.5;
margin: 0 0 8px;
}
}
blockquote {
font-size: 14px;
line-height: 1.5;
@@ -70,25 +82,31 @@ article {
border-left: 4px solid var(--color-base-300);
background-color: var(--color-base-200);
}
hr {
border: 0;
border-top: 1px solid var(--color-base-300);
margin: 16px 0;
}
a {
color: var(--color-primary);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
img {
border-radius: 8px;
max-height: 400px;
}
p:has(> img) {
margin: 16px 0;
}
p code {
background-color: var(--color-base-200);
padding: 2px 4px;
@@ -96,15 +114,141 @@ article {
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, system-ui;
}
iframe {
width: 100%;
height: 100%;
}
}
.comment_tile {
& {
color: var(--color-base-content);
word-break: break-all;
}
h1 {
font-size: 20px;
font-weight: bold;
padding: 8px 0;
margin: 16px 0 8px;
}
h2 {
font-size: 18px;
font-weight: bold;
padding: 6px 0;
margin: 12px 0 6px;
}
h3 {
font-size: 15px;
font-weight: bold;
padding: 4px 0;
margin: 8px 0 4px;
}
h4 {
font-size: 13px;
font-weight: bold;
padding: 3px 0;
margin: 8px 0 4px;
}
h5 {
font-size: 11px;
font-weight: bold;
padding: 2px 0;
}
h6 {
font-size: 10px;
font-weight: bold;
padding: 1px 0;
}
p {
font-size: 13px;
line-height: 1.4;
margin: 8px 0;
}
ul {
list-style-type: disc;
margin: 0 0 12px 16px;
padding: 0;
li {
font-size: 13px;
line-height: 1.4;
margin: 0 0 4px;
}
}
ol {
list-style-type: decimal;
margin: 0 0 12px 16px;
padding: 0;
li {
font-size: 13px;
line-height: 1.4;
margin: 0 0 4px;
}
}
blockquote {
font-size: 13px;
line-height: 1.4;
margin: 0 0 12px;
padding: 6px;
border-left: 3px solid var(--color-base-300);
background-color: var(--color-base-200);
}
hr {
border: 0;
border-top: 1px solid var(--color-base-300);
margin: 12px 0;
}
a {
color: var(--color-primary);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
img {
border-radius: 6px;
max-height: 180px;
margin: 6px 6px 6px 0;
}
p>img {
display: inline-block;
}
p:has(> img) {
margin: 12px 0;
}
p code {
background-color: var(--color-base-200);
padding: 1px 3px;
border-radius: 3px;
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, system-ui;
font-size: 12px;
}
}
a.no-underline {
text-decoration: none;
&:hover {
text-decoration: none;
}
}
}

View File

@@ -120,6 +120,8 @@ export interface Comment {
created_at: string;
user: User;
images: Image[];
content_truncated: boolean;
reply_count: number;
}
export interface CommentWithResource {
@@ -129,6 +131,19 @@ export interface CommentWithResource {
user: User;
images: Image[];
resource: Resource;
content_truncated: boolean;
reply_count: number;
}
export interface CommentWithRef {
id: number;
content: string;
created_at: string;
user: User;
images: Image[];
reply_count: number;
resource?: Resource;
reply_to?: Comment;
}
export interface ServerConfig {

View File

@@ -18,6 +18,7 @@ import {
RSort,
TagWithCount,
Activity,
CommentWithRef,
} from "./models.ts";
class Network {
@@ -574,12 +575,10 @@ class Network {
async createResourceComment(
resourceID: number,
content: string,
images: number[],
): Promise<Response<any>> {
return this._callApi(() =>
axios.post(`${this.apiBaseUrl}/comments/resource/${resourceID}`, {
content,
images,
}),
);
}
@@ -587,12 +586,21 @@ class Network {
async updateComment(
commentID: number,
content: string,
images: number[],
): Promise<Response<any>> {
return this._callApi(() =>
axios.put(`${this.apiBaseUrl}/comments/${commentID}`, {
content,
images,
}),
);
}
async replyToComment(
commentID: number,
content: string,
): Promise<Response<any>> {
return this._callApi(() =>
axios.post(`${this.apiBaseUrl}/comments/reply/${commentID}`, {
content,
}),
);
}
@@ -622,6 +630,12 @@ class Network {
);
}
async getComment(commentID: number): Promise<Response<CommentWithRef>> {
return this._callApi(() =>
axios.get(`${this.apiBaseUrl}/comments/${commentID}`),
);
}
async deleteComment(commentID: number): Promise<Response<void>> {
return this._callApi(() =>
axios.delete(`${this.apiBaseUrl}/comments/${commentID}`),

View File

@@ -0,0 +1,140 @@
import { useEffect, useState } from "react";
import { network } from "../network/network";
import showToast from "../components/toast";
import { useNavigate, useParams } from "react-router";
import { useTranslation } from "react-i18next";
import { CommentWithRef, Resource } from "../network/models";
import Loading from "../components/loading";
import Markdown from "react-markdown";
import Badge from "../components/badge";
export default function CommentPage() {
const params = useParams();
const commentId = params.id;
const [comment, setComment] = useState<CommentWithRef | null>(null);
const { t } = useTranslation();
const navigate = useNavigate();
useEffect(() => {
const id = parseInt(commentId || "0");
if (isNaN(id) || id <= 0) {
showToast({
message: t("Invalid comment ID"),
type: "error",
});
return;
}
network.getComment(id).then((res) => {
if (res.success) {
setComment(res.data!);
} else {
showToast({
message: res.message,
type: "error",
});
}
});
}, []);
useEffect(() => {
document.title = t("Comment Details");
});
if (!comment) {
return <Loading />;
}
return (
<div className="p-4">
<h1 className="text-2xl font-bold my-2">{t("Comment")}</h1>
<button
onClick={() => {
navigate(`/user/${encodeURIComponent(comment.user.username)}`);
}}
className="border-b-2 py-1 cursor-pointer border-transparent hover:border-primary transition-colors duration-200 ease-in-out"
>
<div className="flex items-center">
<div className="avatar">
<div className="w-6 rounded-full">
<img src={network.getUserAvatar(comment.user)} alt={"avatar"} />
</div>
</div>
<div className="w-2"></div>
<div className="text-sm">{comment.user.username}</div>
</div>
</button>
{comment.resource && <ResourceCard resource={comment.resource} />}
<div className="flex"></div>
<article>
<CommentContent content={comment.content} />
</article>
</div>
);
}
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>;
}
function ResourceCard({ resource }: { resource: Resource }) {
const navigate = useNavigate();
let tags = resource.tags;
if (tags.length > 10) {
tags = tags.slice(0, 10);
}
const link = `/resources/${resource.id}`;
return (
<a
href="link"
className="flex flex-row w-full card bg-base-200 shadow overflow-clip my-2"
onClick={(e) => {
e.preventDefault();
navigate(link);
}}
>
{resource.image != null && (
<img
className="object-cover w-32 sm:w-40 md:w-44 lg:w-52 max-h-64"
src={network.getResampledImageUrl(resource.image.id)}
alt="cover"
/>
)}
<div className="flex flex-col p-4 flex-1">
<h2 className="card-title w-full break-all">{resource.title}</h2>
<div className="h-2"></div>
<p>
{tags.map((tag) => {
return (
<Badge key={tag.id} className={"m-0.5"}>
{tag.name}
</Badge>
);
})}
</p>
<div className="flex-1"></div>
<div className="flex items-center">
<div className="avatar">
<div className="w-6 rounded-full">
<img src={network.getUserAvatar(resource.author)} />
</div>
</div>
<div className="w-2"></div>
<div className="text-sm">{resource.author.username}</div>
</div>
</div>
</a>
);
}

View File

@@ -24,22 +24,18 @@ import "../markdown.css";
import Loading from "../components/loading.tsx";
import {
MdAdd,
MdArrowDownward,
MdArrowUpward,
MdClose,
MdOutlineArticle,
MdOutlineComment,
MdOutlineDataset,
MdOutlineDelete,
MdOutlineDownload,
MdOutlineEdit,
MdOutlineImage,
MdOutlineLink,
MdOutlineOpenInNew,
} from "react-icons/md";
import { app } from "../app.ts";
import { uploadingManager } from "../network/uploading.ts";
import { ErrorAlert, InfoAlert } from "../components/alert.tsx";
import { ErrorAlert } from "../components/alert.tsx";
import { useTranslation } from "react-i18next";
import Pagination from "../components/pagination.tsx";
import showPopup, { useClosePopup } from "../components/popup.tsx";
@@ -48,8 +44,9 @@ import Button from "../components/button.tsx";
import Badge, { BadgeAccent } from "../components/badge.tsx";
import Input, { TextArea } from "../components/input.tsx";
import { useAppContext } from "../components/AppContext.tsx";
import { ImageGrid, SquareImage } from "../components/image.tsx";
import { BiLogoSteam } from "react-icons/bi";
import { CommentTile } from "../components/comment_tile.tsx";
import { CommentInput } from "../components/comment_input.tsx";
export default function ResourcePage() {
const params = useParams();
@@ -1193,147 +1190,6 @@ function Comments({ resourceId }: { resourceId: number }) {
);
}
function CommentInput({
resourceId,
reload,
}: {
resourceId: number;
reload: () => void;
}) {
const [commentContent, setCommentContent] = useState("");
const [isLoading, setLoading] = useState(false);
const [images, setImages] = useState<File[]>([]);
const { t } = useTranslation();
const sendComment = async () => {
if (isLoading) {
return;
}
if (commentContent === "") {
showToast({
message: t("Comment content cannot be empty"),
type: "error",
});
return;
}
setLoading(true);
const imageIds: number[] = [];
for (const image of images) {
const res = await network.uploadImage(image);
if (res.success) {
imageIds.push(res.data!);
} else {
showToast({ message: res.message, type: "error" });
setLoading(false);
return;
}
}
const res = await network.createResourceComment(
resourceId,
commentContent,
imageIds,
);
if (res.success) {
setCommentContent("");
setImages([]);
showToast({
message: t("Comment created successfully"),
type: "success",
});
reload();
} else {
showToast({ message: res.message, type: "error" });
}
setLoading(false);
};
const handleAddImage = () => {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.multiple = true;
input.onchange = (e) => {
const files = (e.target as HTMLInputElement).files;
if ((files?.length ?? 0) + images.length > 9) {
showToast({
message: t("You can only upload up to 9 images"),
type: "error",
});
return;
}
if (files) {
setImages((prev) => [...prev, ...Array.from(files)]);
}
};
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
placeholder={t("Write down your comment")}
className={"w-full resize-none grow h-40"}
value={commentContent}
onChange={(e) => setCommentContent(e.target.value)}
/>
{images.length > 0 && (
<div
className={
"grid grid-cols-3 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-8 gap-2 my-2"
}
>
{images.map((image, index) => (
<div key={index} className={"relative"}>
<img
src={URL.createObjectURL(image)}
alt={`comment-image-${index}`}
className={"rounded-lg aspect-square object-cover"}
/>
<button
className={
"btn btn-xs btn-circle btn-error absolute top-1 right-1"
}
onClick={() => {
setImages((prev) => prev.filter((_, i) => i !== index));
}}
>
<MdClose size={14} />
</button>
</div>
))}
</div>
)}
<div className={"flex"}>
<button
className={"btn btn-ghost btn-sm btn-circle"}
onClick={handleAddImage}
>
<MdOutlineImage size={18} />
</button>
<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>
);
}
function CommentsList({
resourceId,
page,
@@ -1345,6 +1201,8 @@ function CommentsList({
}) {
const [comments, setComments] = useState<Comment[] | null>(null);
const reload = useContext(context);
useEffect(() => {
network.listResourceComments(resourceId, page).then((res) => {
if (res.success) {
@@ -1370,77 +1228,14 @@ function CommentsList({
return (
<>
{comments.map((comment) => {
return <CommentTile comment={comment} key={comment.id} />;
return (
<CommentTile comment={comment} key={comment.id} onUpdated={reload} />
);
})}
</>
);
}
function CommentTile({ comment }: { comment: Comment }) {
const navigate = useNavigate();
const [expanded, setExpanded] = useState(false);
const { t } = useTranslation();
const isLongComment = comment.content.length > 300;
const displayContent =
expanded || !isLongComment
? comment.content
: comment.content.substring(0, 300) + "...";
// @ts-ignore
return (
<div className={"card bg-base-100 p-2 my-3 shadow-xs"}>
<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>
<Badge className={"badge-soft badge-primary badge-sm"}>
{new Date(comment.created_at).toLocaleString()}
</Badge>
</div>
<div className={"text-sm p-2 whitespace-pre-wrap"}>
{displayContent}
{isLongComment && (
<div className={"flex items-center justify-center"}>
<button
onClick={() => setExpanded(!expanded)}
className="mt-2 text-primary text-sm cursor-pointer flex items-center"
>
{expanded ? <MdArrowUpward /> : <MdArrowDownward />}
<span className={"w-1"}></span>
{expanded ? t("Show less") : t("Show more")}
</button>
</div>
)}
</div>
<ImageGrid images={comment.images} />
{app.user?.id === comment.user.id && (
<div className={"flex flex-row-reverse"}>
<DeleteCommentDialog commentId={comment.id} />
<EditCommentDialog comment={comment} />
</div>
)}
</div>
);
}
function DeleteFileDialog({
fileId,
uploaderId,
@@ -1509,234 +1304,3 @@ function DeleteFileDialog({
</>
);
}
function EditCommentDialog({ comment }: { comment: Comment }) {
const [isLoading, setLoading] = useState(false);
const [content, setContent] = useState(comment.content);
const { t } = useTranslation();
const reload = useContext(context);
const [existingImages, setExistingImages] = useState(comment.images);
const [newImages, setNewImages] = useState<File[]>([]);
const handleUpdate = async () => {
if (isLoading) {
return;
}
setLoading(true);
const imageIds: number[] = [];
for (const existingImage of existingImages) {
imageIds.push(existingImage.id);
}
for (const newImage of newImages) {
const res = await network.uploadImage(newImage);
if (res.success) {
imageIds.push(res.data!);
} else {
showToast({
message: res.message,
type: "error",
parent: document.getElementById(`dialog_box`),
});
setLoading(false);
return;
}
}
const res = await network.updateComment(comment.id, content, imageIds);
const dialog = document.getElementById(
`edit_comment_dialog_${comment.id}`,
) as HTMLDialogElement;
dialog.close();
if (res.success) {
showToast({
message: t("Comment updated successfully"),
type: "success",
});
reload();
} 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={"flex flex-col my-2"}>
<p className={"text-sm font-bold mb-2"}>{t("Images")}</p>
<div className={"grid grid-cols-4 sm:grid-cols-5 gap-2"}>
{existingImages.map((image) => (
<div key={image.id} className={"relative"}>
<SquareImage image={image} />
<button
className={
"btn btn-xs btn-circle btn-error absolute top-1 right-1"
}
onClick={() => {
setExistingImages((prev) =>
prev.filter((i) => i.id !== image.id),
);
}}
>
<MdClose size={14} />
</button>
</div>
))}
{newImages.map((image, index) => (
<div key={index} className={"relative"}>
<img
src={URL.createObjectURL(image)}
alt={`comment-image-${index}`}
className={"rounded-lg aspect-square object-cover"}
/>
<button
className={
"btn btn-xs btn-circle btn-error absolute top-1 right-1"
}
onClick={() => {
setNewImages((prev) =>
prev.filter((_, i) => i !== index),
);
}}
>
<MdClose size={14} />
</button>
</div>
))}
</div>
<div className={"flex"}>
<button
className={"btn btn-sm mt-2"}
onClick={() => {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.multiple = true;
input.onchange = (e) => {
const files = (e.target as HTMLInputElement).files;
if (
(files?.length ?? 0) +
existingImages.length +
newImages.length >
9
) {
showToast({
message: t("You can only upload up to 9 images"),
type: "error",
parent: document.getElementById(`dialog_box`),
});
return;
}
if (files) {
setNewImages((prev) => [...prev, ...Array.from(files)]);
}
};
input.click();
}}
>
<MdAdd size={18} />
{t("Add")}
</button>
</div>
</div>
<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 }: { commentId: number }) {
const [isLoading, setLoading] = useState(false);
const reload = useContext(context);
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",
});
reload();
} 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>
</>
);
}