Новые изменения

This commit is contained in:
Web-serfer 2026-04-18 20:55:07 +05:00
parent 6f727aae7b
commit b5b31f8a88
9 changed files with 600 additions and 166 deletions

View file

@ -224,6 +224,9 @@ const { initialLikes = 0, initialDislikes = 0, postId } = Astro.props;
const dislikeBtn = container.querySelector('.dislike-btn'); const dislikeBtn = container.querySelector('.dislike-btn');
async function loadUserVote() { async function loadUserVote() {
const likesCountEl = container.querySelector('[data-count="likes"]');
const dislikesCountEl = container.querySelector('[data-count="dislikes"]');
try { try {
console.log('[Vote] Загрузка голосов для post:', postId); console.log('[Vote] Загрузка голосов для post:', postId);
const response = await fetch(`/api/votes?post_id=${postId}`, { const response = await fetch(`/api/votes?post_id=${postId}`, {
@ -234,8 +237,8 @@ const { initialLikes = 0, initialDislikes = 0, postId } = Astro.props;
const result = await response.json(); const result = await response.json();
console.log('[Vote] Данные:', result); console.log('[Vote] Данные:', result);
// Обновляем счетчики // Обновляем счетчики
if (likesCount) likesCount.textContent = result.likes.toString(); if (likesCountEl) likesCountEl.textContent = result.likes.toString();
if (dislikesCount) dislikesCount.textContent = result.dislikes.toString(); if (dislikesCountEl) dislikesCountEl.textContent = result.dislikes.toString();
// Показываем голос пользователя // Показываем голос пользователя
if (pb.authStore.isValid) { if (pb.authStore.isValid) {
if (result.userVote === 'like') { if (result.userVote === 'like') {

View file

@ -1,15 +1,11 @@
import { createSignal, Show } from "solid-js"; import { createSignal, Show, For } from "solid-js";
interface CommentFormData {
content: string;
}
interface ValidationErrors { interface ValidationErrors {
content?: string; content?: string;
} }
interface CommentFormProps { interface CommentFormProps {
onSubmit: (data: CommentFormData) => void; onSubmit: (data: { content: string }) => void;
isReply?: boolean; isReply?: boolean;
onCancel?: () => void; onCancel?: () => void;
user?: { user?: {
@ -17,10 +13,17 @@ interface CommentFormProps {
email: string; email: string;
avatar?: string; avatar?: string;
}; };
initialContent?: string;
isEdit?: boolean;
onUpdate?: (data: { content: string }) => void;
onDelete?: () => void;
} }
const MAX_MESSAGE_LENGTH = 2000; const EMOJIS = [
const MIN_MESSAGE_LENGTH = 10; "👍", "👎", "❤️", "😊", "😂", "🎉", "🔥", "👏",
"😢", "😮", "😡", "🙏", "⭐", "💯", "❤️‍🔥", "🤔",
"👀", "💪", "🚀", "✨"
];
const DANGEROUS_PATTERNS = [ const DANGEROUS_PATTERNS = [
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
@ -34,10 +37,14 @@ const DANGEROUS_PATTERNS = [
/url\s*\(\s*['"]*\s*javascript:/gi, /url\s*\(\s*['"]*\s*javascript:/gi,
]; ];
const MAX_MESSAGE_LENGTH = 2000;
const MIN_MESSAGE_LENGTH = 10;
export default function CommentForm(props: CommentFormProps) { export default function CommentForm(props: CommentFormProps) {
const [content, setContent] = createSignal(""); const [content, setContent] = createSignal(props.initialContent || "");
const [errors, setErrors] = createSignal<ValidationErrors>({}); const [errors, setErrors] = createSignal<ValidationErrors>({});
const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({}); const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({});
const [showEmojiPicker, setShowEmojiPicker] = createSignal(false);
const sanitizeInput = (input: string): string => { const sanitizeInput = (input: string): string => {
return input return input
@ -82,6 +89,11 @@ export default function CommentForm(props: CommentFormProps) {
} }
}; };
const addEmoji = (emoji: string) => {
setContent((prev) => prev + emoji);
setShowEmojiPicker(false);
};
const validateForm = (): boolean => { const validateForm = (): boolean => {
const contentError = validateContent(content()); const contentError = validateContent(content());
setErrors({ content: contentError }); setErrors({ content: contentError });
@ -93,13 +105,17 @@ export default function CommentForm(props: CommentFormProps) {
e.preventDefault(); e.preventDefault();
if (!validateForm()) return; if (!validateForm()) return;
props.onSubmit({ if (props.isEdit && props.onUpdate) {
content: sanitizeInput(content().trim()), props.onUpdate({ content: sanitizeInput(content().trim()) });
}); } else {
props.onSubmit({ content: sanitizeInput(content().trim()) });
}
setContent(""); if (!props.isEdit) {
setErrors({}); setContent("");
setTouched({}); setErrors({});
setTouched({});
}
}; };
const handleBlur = () => { const handleBlur = () => {
@ -131,33 +147,67 @@ export default function CommentForm(props: CommentFormProps) {
d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
/> />
</svg> </svg>
{props.isReply ? "Написать ответ" : "Оставить комментарий"} {props.isEdit ? "Редактировать комментарий" : props.isReply ? "Написать ответ" : "Оставить комментарий"}
</h4> </h4>
<form onSubmit={handleSubmit} class="space-y-4"> <form onSubmit={handleSubmit} class="space-y-4">
<div class="space-y-1"> <div class="space-y-1">
<textarea <div class="relative">
placeholder={props.user ? `Написать комментарий как ${props.user.name || props.user.email}...` : "Ваш комментарий... *"} <textarea
value={content()} placeholder={props.user ? `Написать комментарий как ${props.user.name}...` : "Ваш комментарий... *"}
onInput={handleContentChange} value={content()}
onBlur={handleBlur} onInput={handleContentChange}
rows={props.isReply ? 3 : 4} onBlur={handleBlur}
class={`w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none ${ rows={props.isReply ? 3 : props.isEdit ? 3 : 4}
errors().content && touched().content class={`w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none ${
? "border-red-300 focus:border-red-500 focus:ring-2 focus:ring-red-200" errors().content && touched().content
: "border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-200" ? "border-red-300 focus:border-red-500 focus:ring-2 focus:ring-red-200"
}`} : "border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
/> }`}
/>
<div class="absolute bottom-3 right-3 flex items-center gap-1">
<div class="relative">
<button
type="button"
onClick={() => setShowEmojiPicker(!showEmojiPicker())}
class="p-2 text-gray-400 hover:text-blue-600 transition-colors rounded-lg hover:bg-gray-100"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</button>
<Show when={showEmojiPicker()}>
<div class="absolute bottom-full right-0 mb-2 bg-white rounded-xl shadow-lg border border-gray-200 p-3 z-10 w-64">
<div class="grid grid-cols-5 gap-2">
<For each={EMOJIS}>
{(emoji) => (
<button
type="button"
onClick={() => addEmoji(emoji)}
class="p-2 text-xl hover:bg-gray-100 rounded-lg transition-colors"
>
{emoji}
</button>
)}
</For>
</div>
</div>
</Show>
</div>
</div>
</div>
<div class="flex justify-between items-center"> <div class="flex justify-between items-center">
<Show when={errors().content && touched().content}> <Show when={errors().content && touched().content}>
<p class="text-sm text-red-500 flex items-center gap-1"> <p class="text-sm text-red-500 flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg> </svg>
{errors().content} {errors().content}
</p> </p>
</Show> </Show>
<p class={`text-xs text-right ml-auto ${content().length > MAX_MESSAGE_LENGTH * 0.9 ? "text-orange-500" : "text-gray-400"}`}> <p
class={`text-xs text-right ml-auto ${content().length > MAX_MESSAGE_LENGTH * 0.9 ? "text-orange-500" : "text-gray-400"}`}
>
{content().length}/{MAX_MESSAGE_LENGTH} {content().length}/{MAX_MESSAGE_LENGTH}
</p> </p>
</div> </div>
@ -166,11 +216,11 @@ export default function CommentForm(props: CommentFormProps) {
<div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pt-2"> <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pt-2">
<p class="text-sm text-gray-500"> <p class="text-sm text-gray-500">
{props.user {props.user
? `Вы авторизованы как ${props.user.name || props.user.email}` ? `Вы авторизованы как ${props.user.name}`
: "Ваш email не будет опубликован"} : "Ваш email не будет опубликован"}
</p> </p>
<div class="flex gap-2"> <div class="flex gap-2">
<Show when={props.isReply && props.onCancel}> <Show when={props.isEdit && props.onCancel}>
<button <button
type="button" type="button"
onClick={props.onCancel} onClick={props.onCancel}
@ -182,12 +232,17 @@ export default function CommentForm(props: CommentFormProps) {
<button <button
type="submit" type="submit"
disabled={!isValid()} disabled={!isValid()}
class="px-8 py-3 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-colors shadow-lg shadow-blue-200 flex items-center gap-2 hover:cursor-pointer group" class="px-8 py-3 bg-gradient-to-b from-blue-600 to-blue-800 hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-all flex items-center gap-2 hover:cursor-pointer group"
> >
<svg class="w-5 h-5 transition-transform duration-300 group-hover:rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /> class="w-5 h-5 transition-transform duration-300 group-hover:rotate-90"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
</svg> </svg>
{props.isReply ? "Отправить" : "Отправить комментарий"} {props.isEdit ? "Сохранить" : props.isReply ? "Отправить" : "Отправить комментарий"}
</button> </button>
</div> </div>
</div> </div>

View file

@ -1,11 +1,11 @@
import { createSignal, onMount } from "solid-js"; import { createSignal, onMount } from "solid-js";
export default function CommentLock() { export default function CommentLock() {
const [currentPath, setCurrentPath] = createSignal("/auth/login"); const [currentPath, setCurrentPath] = createSignal("/auth/sign-in");
onMount(() => { onMount(() => {
const path = window.location.pathname; const path = window.location.pathname;
setCurrentPath(`/auth/login?redirect=${encodeURIComponent(path)}`); setCurrentPath(`/auth/sign-in?redirect=${encodeURIComponent(path)}`);
}); });
return ( return (
@ -17,52 +17,38 @@ export default function CommentLock() {
</span> </span>
</div> </div>
<div class="bg-linear-to-br from-gray-50 to-gray-100 rounded-2xl p-8 md:p-12 border border-gray-200 text-center"> <div
<div class="w-20 h-20 mx-auto mb-6 bg-linear-to-br from-blue-100 to-blue-200 rounded-full flex items-center justify-center"> class="bg-linear-to-br from-gray-50 to-gray-100 rounded-2xl p-8 md:p-12 border border-gray-200 text-center"
<svg style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);"
class="w-10 h-10 text-blue-600" >
fill="none" <div
stroke="currentColor" class="w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center"
viewBox="0 0 24 24" style="background: linear-gradient(135deg, rgba(234, 194, 110, 0.2) 0%, rgba(234, 194, 110, 0.3) 100%);"
> >
<path <svg class="w-10 h-10 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
stroke-linecap="round" <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
stroke-linejoin="round"
stroke-width="2"
d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
/>
</svg> </svg>
</div> </div>
<h4 class="text-xl font-semibold text-gray-900 mb-3"> <h4 class="text-xl font-semibold text-gray-900 mb-3">
Комментарии доступны только авторизованным пользователям Комментарии доступны только авторизованным пользователям
</h4> </h4>
<a <a
href={currentPath()} href={currentPath()}
class="inline-flex items-center gap-2 px-8 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-xl transition-colors shadow-lg shadow-blue-200" class="inline-flex items-center justify-center font-semibold transition-all duration-300 rounded-md cursor-pointer px-6 py-3 text-lg"
style="background: linear-gradient(to bottom, #eac26e, #ce9f40); color: white; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);"
> >
<svg <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
class="w-5 h-5" <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"/>
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"
/>
</svg> </svg>
Войти в аккаунт Войти в аккаунт
</a> </a>
<p class="mt-4 text-sm text-gray-600"> <p class="mt-4 text-sm text-gray-600">
Нет аккаунта?{" "} Нет аккаунта?{" "}
<a <a
href={`/auth/register?redirect=${encodeURIComponent(window.location.pathname)}`} href={`/auth/sign-up?redirect=${encodeURIComponent(window.location.pathname)}`}
class="text-blue-600 hover:text-blue-700 font-medium hover:underline" class="font-medium hover:underline"
style="color: #ce9f40;"
> >
Зарегистрироваться Зарегистрироваться
</a> </a>

View file

@ -0,0 +1,12 @@
---
import Comments from "./Comments";
import type { Props as BaseProps } from "../../../types/comments";
interface Props extends BaseProps {
postSlug: string;
}
const { postSlug } = Astro.props;
---
<Comments postSlug={postSlug} client:load />

View file

@ -20,7 +20,8 @@ interface ApiComment {
expand?: { expand?: {
user?: { user?: {
id: string; id: string;
firstName: string; firstName?: string;
name?: string;
email: string; email: string;
avatar?: string; avatar?: string;
}; };
@ -35,6 +36,7 @@ interface ToastMessage {
export default function Comments(props: CommentsProps) { export default function Comments(props: CommentsProps) {
const [isAuthenticated, setIsAuthenticated] = createSignal(false); const [isAuthenticated, setIsAuthenticated] = createSignal(false);
const [currentUser, setCurrentUser] = createSignal<{ const [currentUser, setCurrentUser] = createSignal<{
id: string;
name: string; name: string;
email: string; email: string;
avatar?: string; avatar?: string;
@ -42,8 +44,8 @@ export default function Comments(props: CommentsProps) {
const [isLoading, setIsLoading] = createSignal(true); const [isLoading, setIsLoading] = createSignal(true);
const [comments, setComments] = createSignal<CommentWithReplies[]>([]); const [comments, setComments] = createSignal<CommentWithReplies[]>([]);
const [replyTo, setReplyTo] = createSignal<string | null>(null); const [replyTo, setReplyTo] = createSignal<string | null>(null);
const [commentAuthors, setCommentAuthors] = createSignal<Record<string, string>>({}); const [editingComment, setEditingComment] = createSignal<string | null>(null);
const [toastVisible, setToastVisible] = createSignal<string | null>(null); const [editContent, setEditContent] = createSignal("");
const [toast, setToast] = createSignal<ToastMessage | null>(null); const [toast, setToast] = createSignal<ToastMessage | null>(null);
const showToast = (message: ToastMessage): void => { const showToast = (message: ToastMessage): void => {
@ -63,6 +65,7 @@ export default function Comments(props: CommentsProps) {
if (data.authenticated && data.user) { if (data.authenticated && data.user) {
setIsAuthenticated(true); setIsAuthenticated(true);
setCurrentUser({ setCurrentUser({
id: data.user.id,
name: data.user.name || "Пользователь", name: data.user.name || "Пользователь",
email: data.user.email, email: data.user.email,
avatar: data.user.avatar, avatar: data.user.avatar,
@ -91,14 +94,6 @@ export default function Comments(props: CommentsProps) {
const data = await response.json(); const data = await response.json();
const authors: Record<string, string> = {};
data.items.forEach((comment: ApiComment) => {
if (comment.user) {
authors[comment.id] = comment.user;
}
});
setCommentAuthors(authors);
const commentsWithReplies: CommentWithReplies[] = await Promise.all( const commentsWithReplies: CommentWithReplies[] = await Promise.all(
data.items.map(async (comment: ApiComment) => { data.items.map(async (comment: ApiComment) => {
const repliesResponse = await fetch( const repliesResponse = await fetch(
@ -149,6 +144,7 @@ export default function Comments(props: CommentsProps) {
await loadComments(); await loadComments();
} catch (error) { } catch (error) {
console.error("[Comments] Ошибка создания комментария:", error); console.error("[Comments] Ошибка создания комментария:", error);
showToast({ type: "error", message: "Не удалось отправить комментарий" });
} }
}; };
@ -183,33 +179,76 @@ export default function Comments(props: CommentsProps) {
} }
}; };
const handleReplyClick = (commentId: string) => { const handleEdit = async (commentId: string, data: { content: string }) => {
const checkAuthAndReply = async () => { try {
try { const response = await fetch(`/api/comments/${commentId}`, {
const response = await fetch("/api/auth/me", { method: "PATCH",
credentials: "include", headers: { "Content-Type": "application/json" },
}); credentials: "include",
const data = await response.json(); body: JSON.stringify({
const currentUserId = data.user?.id; content: data.content,
const commentAuthorId = commentAuthors()[commentId]; }),
});
if (commentAuthorId && currentUserId === commentAuthorId) { if (!response.ok) {
setToastVisible(commentId); const errorData = await response.json();
setTimeout(() => setToastVisible(null), 3000); throw new Error(errorData.error || "Failed to update comment");
return;
}
setReplyTo(replyTo() === commentId ? null : commentId);
} catch (error) {
console.error("[handleReplyClick] Ошибка проверки автора:", error);
setReplyTo(replyTo() === commentId ? null : commentId);
} }
};
checkAuthAndReply(); showToast({ type: "success", message: "Комментарий обновлен!" });
await loadComments();
setEditingComment(null);
setEditContent("");
} catch (error) {
console.error("[Comments] Ошибка обновления комментария:", error);
showToast({ type: "error", message: "Не удалось обновить комментарий" });
}
}; };
const Avatar = (props: { author: string; avatar?: string; size?: "sm" | "md" }) => { const handleDelete = async (commentId: string) => {
try {
const response = await fetch(`/api/comments/${commentId}`, {
method: "DELETE",
credentials: "include",
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Failed to delete comment");
}
showToast({ type: "success", message: "Комментарий удален!" });
await loadComments();
setEditingComment(null);
} catch (error) {
console.error("[Comments] Ошибка удаления комментария:", error);
showToast({ type: "error", message: "Не удалось удалить комментарий" });
}
};
const handleReplyClick = (commentId: string) => {
const currentUserId = currentUser()?.id;
const comment = comments().find(c => c.id === commentId);
const commentUserId = comment?.user;
if (commentUserId && currentUserId === commentUserId) {
showToast({ type: "error", message: "Нельзя ответить на свой комментарий" });
return;
}
setReplyTo(replyTo() === commentId ? null : commentId);
};
const handleEditClick = (commentId: string, content: string) => {
setEditingComment(commentId);
setEditContent(content);
};
const Avatar = (props: {
author: string;
avatar?: string;
size?: "sm" | "md";
}) => {
const size = props.size || "md"; const size = props.size || "md";
const sizeClasses = { sm: "w-8 h-8 text-sm", md: "w-12 h-12 text-lg" }; const sizeClasses = { sm: "w-8 h-8 text-sm", md: "w-12 h-12 text-lg" };
@ -217,12 +256,18 @@ export default function Comments(props: CommentsProps) {
<Show <Show
when={props.avatar} when={props.avatar}
fallback={ fallback={
<div class={`${sizeClasses[size]} rounded-full bg-linear-to-br from-blue-400 to-blue-600 flex items-center justify-center text-white font-bold shrink-0`}> <div
class={`${sizeClasses[size]} rounded-full bg-gradient-to-br from-yellow-400 to-yellow-600 flex items-center justify-center text-white font-bold shrink-0`}
>
{props.author.charAt(0)} {props.author.charAt(0)}
</div> </div>
} }
> >
<img src={props.avatar} alt={props.author} class={`${sizeClasses[size]} rounded-full object-cover shrink-0`} /> <img
src={props.avatar}
alt={props.author}
class={`${sizeClasses[size]} rounded-full object-cover shrink-0`}
/>
</Show> </Show>
); );
}; };
@ -238,13 +283,21 @@ export default function Comments(props: CommentsProps) {
}); });
}; };
const isCommentOwner = (commentUserId?: string) => {
return currentUser()?.id === commentUserId;
};
return ( return (
<> <>
<Show when={toast()}> <Show when={toast()}>
{(t) => ( {(t) => (
<div class={`fixed bottom-4 right-4 px-6 py-3 rounded-xl shadow-lg transition-all duration-300 z-50 ${ <div
t().type === "success" ? "bg-green-500 text-white" : "bg-red-500 text-white" class={`fixed bottom-4 right-4 px-6 py-3 rounded-xl shadow-lg transition-all duration-300 z-50 ${
}`}> t().type === "success"
? "bg-green-500 text-white"
: "bg-red-500 text-white"
}`}
>
{t().message} {t().message}
</div> </div>
)} )}
@ -254,7 +307,9 @@ export default function Comments(props: CommentsProps) {
<div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200"> <div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200">
<div class="flex items-center gap-3 mb-8"> <div class="flex items-center gap-3 mb-8">
<h3 class="text-2xl font-bold text-gray-900">Комментарии</h3> <h3 class="text-2xl font-bold text-gray-900">Комментарии</h3>
<span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">0</span> <span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">
0
</span>
</div> </div>
<div class="text-center py-12"> <div class="text-center py-12">
<div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div> <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
@ -266,42 +321,129 @@ export default function Comments(props: CommentsProps) {
<div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200"> <div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200">
<div class="flex items-center gap-3 mb-8"> <div class="flex items-center gap-3 mb-8">
<h3 class="text-2xl font-bold text-gray-900">Комментарии</h3> <h3 class="text-2xl font-bold text-gray-900">Комментарии</h3>
<span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">{comments().length}</span> <span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">
{comments().length}
</span>
</div> </div>
<Show when={comments().length > 0} fallback={ <Show
<div class="text-center py-12 text-gray-500"> when={comments().length > 0}
<p>Пока нет комментариев. Будьте первым!</p> fallback={
</div> <div class="text-center py-12 text-gray-500">
}> <p>Пока нет комментариев. Будьте первым!</p>
</div>
}
>
<div class="space-y-6 mb-10"> <div class="space-y-6 mb-10">
<For each={comments()}> <For each={comments()}>
{(comment) => ( {(comment) => (
<div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100"> <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
<div class="flex items-start gap-4"> <div class="flex items-start gap-4">
<Avatar author={comment.expand?.user?.firstName || "Аноним"} avatar={comment.expand?.user?.avatar} /> <Avatar
author={comment.expand?.user?.firstName || comment.expand?.user?.name || "Аноним"}
avatar={comment.expand?.user?.avatar}
/>
<div class="flex-1 min-w-0"> <div class="flex-1 min-w-0">
<div class="flex items-center gap-2 mb-2 flex-wrap"> <div class="flex items-center gap-2 mb-2 flex-wrap">
<span class="font-semibold text-gray-900">{comment.expand?.user?.firstName || "Аноним"}</span> <span class="font-semibold text-gray-900">
{comment.expand?.user?.firstName || comment.expand?.user?.name || "Аноним"}
</span>
<Show when={comment.is_verified}> <Show when={comment.is_verified}>
<svg class="w-4 h-4 text-blue-500" fill="currentColor" viewBox="0 0 20 20"> <svg
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" /> class="w-4 h-4 text-blue-600"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
clip-rule="evenodd"
/>
</svg> </svg>
</Show> </Show>
<span class="text-sm text-gray-400 ml-auto">{formatDate(comment.created)}</span> <span class="text-sm text-gray-400 ml-auto">
{formatDate(comment.created)}
</span>
</div> </div>
<p class="text-gray-700 leading-relaxed mb-3">{comment.content}</p> <Show
<div class="flex items-center gap-1"> when={editingComment() === comment.id}
<button onClick={() => handleReplyClick(comment.id)} class="text-sm text-blue-600 hover:text-blue-800 font-medium flex items-center gap-1 transition-colors hover:cursor-pointer"> fallback={
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <p class="text-gray-700 leading-relaxed mb-3">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" /> {comment.content}
</p>
}
>
<CommentForm
isEdit={true}
initialContent={editContent()}
onSubmit={(data) => handleEdit(comment.id, data)}
onCancel={() => {
setEditingComment(null);
setEditContent("");
}}
onDelete={() => handleDelete(comment.id)}
user={currentUser()}
/>
</Show>
<div class="flex items-center gap-1 flex-wrap">
<button
onClick={() => handleReplyClick(comment.id)}
class="text-sm text-blue-600 hover:text-blue-600-dark font-medium flex items-center gap-1 transition-colors hover:cursor-pointer"
>
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"
/>
</svg> </svg>
{replyTo() === comment.id ? "Отменить" : "Ответить"} {replyTo() === comment.id ? "Отменить" : "Ответить"}
</button> </button>
<Show when={toastVisible() === comment.id}> <Show when={isCommentOwner(comment.user)}>
<span class="text-xs text-yellow-700 bg-yellow-100 px-2 py-1 rounded-md whitespace-nowrap"> <button
Нельзя ответить на свой комментарий onClick={() => handleEditClick(comment.id, comment.content)}
</span> class="text-sm text-gray-400 hover:text-blue-600 font-medium flex items-center gap-1 transition-colors hover:cursor-pointer ml-2"
>
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
Редактировать
</button>
<button
onClick={() => handleDelete(comment.id)}
class="text-sm text-gray-400 hover:text-red-500 font-medium flex items-center gap-1 transition-colors hover:cursor-pointer ml-2"
>
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
Удалить
</button>
</Show> </Show>
</div> </div>
</div> </div>
@ -309,7 +451,12 @@ export default function Comments(props: CommentsProps) {
<Show when={replyTo() === comment.id}> <Show when={replyTo() === comment.id}>
<div class="mt-4 ml-16 pl-4 border-l-2 border-blue-200"> <div class="mt-4 ml-16 pl-4 border-l-2 border-blue-200">
<CommentForm isReply={true} onSubmit={(data) => handleReply(comment.id, data)} onCancel={() => setReplyTo(null)} user={currentUser()} /> <CommentForm
isReply={true}
onSubmit={(data) => handleReply(comment.id, data)}
onCancel={() => setReplyTo(null)}
user={currentUser()}
/>
</div> </div>
</Show> </Show>
@ -318,18 +465,36 @@ export default function Comments(props: CommentsProps) {
<For each={comment.replies}> <For each={comment.replies}>
{(reply) => ( {(reply) => (
<div class="flex items-start gap-3 pl-4 border-l-2 border-gray-200"> <div class="flex items-start gap-3 pl-4 border-l-2 border-gray-200">
<Avatar author={reply.expand?.user?.firstName || "Аноним"} avatar={reply.expand?.user?.avatar} size="sm" /> <Avatar
author={reply.expand?.user?.firstName || reply.expand?.user?.name || "Аноним"}
avatar={reply.expand?.user?.avatar}
size="sm"
/>
<div class="flex-1 bg-gray-50 rounded-xl p-4"> <div class="flex-1 bg-gray-50 rounded-xl p-4">
<div class="flex items-center gap-2 mb-1 flex-wrap"> <div class="flex items-center gap-2 mb-1 flex-wrap">
<span class="font-semibold text-gray-900 text-sm">{reply.expand?.user?.firstName || "Аноним"}</span> <span class="font-semibold text-gray-900 text-sm">
{reply.expand?.user?.firstName || reply.expand?.user?.name || "Аноним"}
</span>
<Show when={reply.is_verified}> <Show when={reply.is_verified}>
<svg class="w-3 h-3 text-blue-500" fill="currentColor" viewBox="0 0 20 20"> <svg
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" /> class="w-3 h-3 text-blue-600"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
clip-rule="evenodd"
/>
</svg> </svg>
</Show> </Show>
<span class="text-xs text-gray-400 ml-auto">{formatDate(reply.created)}</span> <span class="text-xs text-gray-400 ml-auto">
{formatDate(reply.created)}
</span>
</div> </div>
<p class="text-gray-700 text-sm leading-relaxed">{reply.content}</p> <p class="text-gray-700 text-sm leading-relaxed">
{reply.content}
</p>
</div> </div>
</div> </div>
)} )}

View file

@ -24,8 +24,6 @@ import { COMPANY } from "@constants";
<!-- Right side --> <!-- Right side -->
<div class="header-column header-right animate-load" data-delay="200"> <div class="header-column header-right animate-load" data-delay="200">
<div class="header-actions" id="auth-section"></div>
<a href={`tel:${COMPANY.phoneClean}`} class="header-phone" id="header-phone"> <a href={`tel:${COMPANY.phoneClean}`} class="header-phone" id="header-phone">
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
@ -45,7 +43,9 @@ import { COMPANY } from "@constants";
</svg> </svg>
<span class="phone-number">{COMPANY.phone}</span> <span class="phone-number">{COMPANY.phone}</span>
</a> </a>
</div>
<div class="header-actions" id="auth-section"></div>
</div>
<div class="mobile-actions"> <div class="mobile-actions">
<a href={`tel:${COMPANY.phoneClean}`} class="mobile-phone-btn" aria-label="Позонить: {COMPANY.phone}"> <a href={`tel:${COMPANY.phoneClean}`} class="mobile-phone-btn" aria-label="Позонить: {COMPANY.phone}">
@ -127,11 +127,21 @@ import { COMPANY } from "@constants";
.header-center { .header-center {
justify-content: center; justify-content: center;
} }
.header-right { .header-right {
justify-content: flex-end; justify-content: flex-end;
gap: 1.5rem; gap: 1.5rem;
} }
.header-actions {
display: flex;
align-items: center;
}
.header-actions {
display: flex;
align-items: center;
}
/* НОМЕР ТЕЛЕФОНА В ШАПКЕ */ /* НОМЕР ТЕЛЕФОНА В ШАПКЕ */
.header-phone { .header-phone {
display: flex; display: flex;
@ -309,29 +319,6 @@ import { COMPANY } from "@constants";
} }
} }
@media (max-width: 992px) {
.header-container {
display: flex;
justify-content: space-between;
height: 70px;
}
.header-center {
display: none;
}
.header-right {
gap: 0.5rem;
}
.header-phone {
display: none;
}
.burger-btn {
display: flex;
}
.mobile-phone-btn {
display: flex;
}
}
@media (min-width: 993px) { @media (min-width: 993px) {
.header-phone { .header-phone {
display: flex; display: flex;
@ -386,8 +373,12 @@ import { COMPANY } from "@constants";
} catch (e) {} } catch (e) {}
localStorage.removeItem('auth_token'); localStorage.removeItem('auth_token');
localStorage.removeItem('user'); localStorage.removeItem('user');
document.querySelector('.header-right')?.classList.remove('auth-active');
window.location.href = '/'; window.location.href = '/';
}); });
// Добавляем класс для изменения порядка
document.querySelector('.header-right')?.classList.add('auth-active');
} catch (e) { } catch (e) {
showPhone(); showPhone();
} }
@ -399,10 +390,22 @@ import { COMPANY } from "@constants";
function showPhone() { function showPhone() {
const authSection = document.getElementById('auth-section'); const authSection = document.getElementById('auth-section');
if (authSection) authSection.innerHTML = ''; if (authSection) authSection.innerHTML = '';
document.querySelector('.header-right')?.classList.remove('auth-active');
} }
// Стили // Стили
const authStyle = ` const authStyle = `
.header-right.auth-active {
display: flex;
flex-direction: row-reverse;
justify-content: flex-start;
}
.header-right.auth-active .header-phone {
order: 2;
}
.header-right.auth-active .header-actions {
order: 1;
}
.user-display { .user-display {
display: flex; display: flex;
align-items: center; align-items: center;

View file

@ -0,0 +1,208 @@
import type { APIRoute } from "astro";
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
export const PATCH: APIRoute = async ({ params, request, cookies }) => {
const pbAuthCookie = cookies.get("pb_auth")?.value;
const token = pbAuthCookie?.trim();
if (!token) {
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
try {
let userId: string | null = null;
const userResponse = await fetch(
`${POCKETBASE_URL}/api/collections/users/auth-refresh`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
if (userResponse.ok) {
const userData = await userResponse.json();
userId = userData.record?.id;
}
if (!userId) {
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
const commentId = params.id;
if (!commentId) {
return new Response(
JSON.stringify({ error: "Comment ID required" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
const commentResponse = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records/${commentId}`,
{
headers: { Authorization: `Bearer ${token}` },
}
);
if (!commentResponse.ok) {
return new Response(
JSON.stringify({ error: "Comment not found" }),
{ status: 404, headers: { "Content-Type": "application/json" } }
);
}
const comment = await commentResponse.json();
if (comment.user !== userId) {
return new Response(
JSON.stringify({ error: "Нет прав на редактирование" }),
{ status: 403, headers: { "Content-Type": "application/json" } }
);
}
const body = await request.json();
const { content } = body;
if (!content || content.length < 10 || content.length > 2000) {
return new Response(
JSON.stringify({ error: "content must be between 10 and 2000 characters" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
const updateResponse = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records/${commentId}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ content }),
}
);
if (!updateResponse.ok) {
const errorData = await updateResponse.json();
return new Response(JSON.stringify(errorData), {
status: updateResponse.status,
headers: { "Content-Type": "application/json" },
});
}
const updatedComment = await updateResponse.json();
return new Response(JSON.stringify(updatedComment), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("[Comments API PATCH] Error:", error);
return new Response(
JSON.stringify({ error: "Failed to update comment" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
};
export const DELETE: APIRoute = async ({ params, cookies }) => {
const pbAuthCookie = cookies.get("pb_auth")?.value;
const token = pbAuthCookie?.trim();
if (!token) {
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
try {
let userId: string | null = null;
const userResponse = await fetch(
`${POCKETBASE_URL}/api/collections/users/auth-refresh`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
if (userResponse.ok) {
const userData = await userResponse.json();
userId = userData.record?.id;
}
if (!userId) {
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
const commentId = params.id;
if (!commentId) {
return new Response(
JSON.stringify({ error: "Comment ID required" }),
{ status: 400, headers: { "Content-Type": "application/json" } }
);
}
const commentResponse = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records/${commentId}`,
{
headers: { Authorization: `Bearer ${token}` },
}
);
if (!commentResponse.ok) {
return new Response(
JSON.stringify({ error: "Comment not found" }),
{ status: 404, headers: { "Content-Type": "application/json" } }
);
}
const comment = await commentResponse.json();
if (comment.user !== userId) {
return new Response(
JSON.stringify({ error: "Нет прав на удаление" }),
{ status: 403, headers: { "Content-Type": "application/json" } }
);
}
const deleteResponse = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records/${commentId}`,
{
method: "DELETE",
headers: { Authorization: `Bearer ${token}` },
}
);
if (!deleteResponse.ok) {
const errorData = await deleteResponse.json();
return new Response(JSON.stringify(errorData), {
status: deleteResponse.status,
headers: { "Content-Type": "application/json" },
});
}
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("[Comments API DELETE] Error:", error);
return new Response(
JSON.stringify({ error: "Failed to delete comment" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
};

View file

@ -1,7 +1,7 @@
--- ---
import ArticleLayout from '@layouts/ArticleLayout.astro'; import ArticleLayout from '@layouts/ArticleLayout.astro';
import { SITE_URL } from '@constants'; import { SITE_URL } from '@constants';
import Comments from '@components/blog/comments/Comments'; import Comments from '@components/blog/comments/Comments.astro';
import RelatedPosts from '@components/blog/RelatedPosts.astro'; import RelatedPosts from '@components/blog/RelatedPosts.astro';
import ArticleTableOfContents from '@components/blog/ArticleTableOfContents.astro'; import ArticleTableOfContents from '@components/blog/ArticleTableOfContents.astro';
import { getPostBySlug, getPosts, getPostImageUrl, getPostVotesStats } from '@lib/pb'; import { getPostBySlug, getPosts, getPostImageUrl, getPostVotesStats } from '@lib/pb';
@ -82,7 +82,7 @@ const heroImage = getPostImageUrl(post);
<!-- Система комментариев --> <!-- Система комментариев -->
<div class="comments-wrapper"> <div class="comments-wrapper">
<Comments client:only="solid-js" postSlug={post.slug} /> <Comments postSlug={post.slug} />
</div> </div>
<!-- Похожие статьи --> <!-- Похожие статьи -->

View file

@ -3,6 +3,8 @@
"include": [".astro/types.d.ts", "**/*"], "include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"], "exclude": ["dist"],
"compilerOptions": { "compilerOptions": {
"jsx": "preserve",
"jsxImportSource": "solid-js",
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@styles/*": ["src/styles/*"], "@styles/*": ["src/styles/*"],