Allow image uploads in lesson comments
Add an image button to the comment toolbar backed by a new upload route (images only, 5 MB, stored under comments/<userId>/), inserted as Markdown. Only images served from our own storage are rendered: a third-party src would be fetched by every reader of the lesson, exposing their address. Such links are shown as plain links instead — this also defuses the external images a few existing comments already carry.
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useRef, useState, useTransition, type ReactNode } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeSanitize from "rehype-sanitize";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import { addComment, deleteComment, editComment } from "@/lib/actions/student-actions";
|
||||
|
||||
const MAX_LEN = 10000;
|
||||
@@ -32,6 +32,8 @@ interface Props {
|
||||
comments: Comment[];
|
||||
currentUserId: string;
|
||||
currentUserRole: string;
|
||||
/** Public host of our own file storage (S3_CDN_URL) — see CommentBody. */
|
||||
imageHost: string;
|
||||
}
|
||||
|
||||
function formatDate(date: Date) {
|
||||
@@ -44,15 +46,42 @@ function formatDate(date: Date) {
|
||||
});
|
||||
}
|
||||
|
||||
// The default schema drops `alt`, so uploaded images would lose their caption.
|
||||
const sanitizeSchema = {
|
||||
...defaultSchema,
|
||||
attributes: {
|
||||
...defaultSchema.attributes,
|
||||
img: [...(defaultSchema.attributes?.img ?? []), "alt"],
|
||||
},
|
||||
};
|
||||
|
||||
// Renders comment text as sanitized Markdown (no raw HTML, safe links).
|
||||
function CommentBody({ text }: { text: string }) {
|
||||
// `imageHost` is our own file storage: images from anywhere else are shown as a
|
||||
// plain link instead of being loaded, since a third-party image would fetch —
|
||||
// and thus expose the address — for every reader of the lesson.
|
||||
function CommentBody({ text, imageHost }: { text: string; imageHost: string }) {
|
||||
return (
|
||||
<div className="comment-md text-sm leading-relaxed break-words">
|
||||
<ReactMarkdown
|
||||
rehypePlugins={[rehypeSanitize]}
|
||||
rehypePlugins={[[rehypeSanitize, sanitizeSchema]]}
|
||||
components={{
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- отбрасываем служебный node от react-markdown, чтобы он не протекал в DOM
|
||||
a: ({ node, ...props }) => <a {...props} target="_blank" rel="noopener noreferrer" />,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
img: ({ node, src, alt, ...props }) => {
|
||||
const url = typeof src === "string" ? src : "";
|
||||
if (!imageHost || !url.startsWith(`${imageHost}/`)) {
|
||||
return (
|
||||
<a href={url} target="_blank" rel="noopener noreferrer">
|
||||
{alt || url}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return (
|
||||
// eslint-disable-next-line @next/next/no-img-element -- пользовательская картинка произвольного размера, next/image здесь не подходит
|
||||
<img {...props} src={url} alt={alt ?? ""} loading="lazy" />
|
||||
);
|
||||
},
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
@@ -107,6 +136,44 @@ interface EditorProps {
|
||||
// new comment, replies, and inline editing.
|
||||
function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: EditorProps) {
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
|
||||
// Insert text at the caret (used for uploaded images).
|
||||
function insertAtCursor(snippet: string) {
|
||||
const el = ref.current;
|
||||
const at = el ? el.selectionStart : value.length;
|
||||
const next = value.slice(0, at) + snippet + value.slice(at);
|
||||
onChange(next);
|
||||
requestAnimationFrame(() => {
|
||||
el?.focus();
|
||||
el?.setSelectionRange(at + snippet.length, at + snippet.length);
|
||||
});
|
||||
}
|
||||
|
||||
async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = ""; // allow picking the same file twice in a row
|
||||
if (!file) return;
|
||||
|
||||
setUploading(true);
|
||||
setUploadError(null);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/student/comment-upload", { method: "POST", body: fd });
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error ?? "Не удалось загрузить изображение");
|
||||
// Square brackets in the filename would break the Markdown link syntax.
|
||||
const caption = file.name.replace(/[[\]]/g, "");
|
||||
insertAtCursor(`\n\n`);
|
||||
} catch (err) {
|
||||
setUploadError(err instanceof Error ? err.message : "Не удалось загрузить изображение");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap the current selection with before/after markers.
|
||||
function wrap(before: string, after: string, placeholderText: string) {
|
||||
@@ -152,6 +219,20 @@ function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: Edi
|
||||
<ToolbarButton title="Цитата" disabled={disabled} onClick={() => prefixLines("> ")}>»</ToolbarButton>
|
||||
<ToolbarButton title="Код" disabled={disabled} onClick={() => wrap("`", "`", "код")}>{"</>"}</ToolbarButton>
|
||||
<ToolbarButton title="Ссылка" disabled={disabled} onClick={() => wrap("[", "](https://)", "текст")}>🔗</ToolbarButton>
|
||||
<ToolbarButton
|
||||
title="Изображение (jpg, png, gif, webp — до 5 МБ)"
|
||||
disabled={disabled || uploading}
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
{uploading ? "…" : "🖼"}
|
||||
</ToolbarButton>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFile}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
ref={ref}
|
||||
@@ -172,6 +253,11 @@ function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: Edi
|
||||
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
||||
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
||||
/>
|
||||
{uploadError && (
|
||||
<div className="text-xs mt-1" style={{ color: "var(--destructive, #b00)" }}>
|
||||
{uploadError}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-xs mt-1" style={{ color: "var(--muted-foreground)" }}>
|
||||
Поддерживается форматирование Markdown{value.length > 0 ? ` · ${value.length}/${MAX_LEN}` : ""}
|
||||
</div>
|
||||
@@ -179,7 +265,7 @@ function CommentEditor({ value, onChange, placeholder, disabled, rows = 3 }: Edi
|
||||
);
|
||||
}
|
||||
|
||||
export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole }: Props) {
|
||||
export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole, imageHost }: Props) {
|
||||
const [text, setText] = useState("");
|
||||
const [replyToId, setReplyToId] = useState<string | null>(null);
|
||||
const [replyText, setReplyText] = useState("");
|
||||
@@ -279,7 +365,7 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<CommentBody text={node.text} />
|
||||
<CommentBody text={node.text} imageHost={imageHost} />
|
||||
)}
|
||||
|
||||
{!node.deleted && !editing && (
|
||||
|
||||
Reference in New Issue
Block a user