Новые правки в компоенты
This commit is contained in:
parent
e85d1ce668
commit
6f727aae7b
23 changed files with 1483 additions and 37 deletions
|
|
@ -6,6 +6,7 @@ export interface Props {
|
|||
categoryColor?: string;
|
||||
date: string;
|
||||
readTime: string;
|
||||
readmeTime?: string;
|
||||
image?: string;
|
||||
slug?: string;
|
||||
}
|
||||
|
|
@ -17,6 +18,7 @@ const {
|
|||
categoryColor = 'bg-gold',
|
||||
date,
|
||||
readTime,
|
||||
readmeTime,
|
||||
image,
|
||||
slug = '#'
|
||||
} = Astro.props;
|
||||
|
|
@ -52,7 +54,7 @@ const imageUrl = image || '/images/blog/default.avif';
|
|||
<circle cx="12" cy="12" r="10"></circle>
|
||||
<polyline points="12 6 12 12 16 14"></polyline>
|
||||
</svg>
|
||||
{readTime}
|
||||
{readmeTime || readTime}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -224,18 +224,25 @@ const { initialLikes = 0, initialDislikes = 0, postId } = Astro.props;
|
|||
const dislikeBtn = container.querySelector('.dislike-btn');
|
||||
|
||||
async function loadUserVote() {
|
||||
if (!pb.authStore.isValid) return;
|
||||
|
||||
try {
|
||||
console.log('[Vote] Загрузка голосов для post:', postId);
|
||||
const response = await fetch(`/api/votes?post_id=${postId}`, {
|
||||
credentials: 'include',
|
||||
});
|
||||
console.log('[Vote] Ответ:', response.status);
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
if (result.userVote === 'like') {
|
||||
likeBtn?.classList.add('active');
|
||||
} else if (result.userVote === 'dislike') {
|
||||
dislikeBtn?.classList.add('active');
|
||||
console.log('[Vote] Данные:', result);
|
||||
// Обновляем счетчики
|
||||
if (likesCount) likesCount.textContent = result.likes.toString();
|
||||
if (dislikesCount) dislikesCount.textContent = result.dislikes.toString();
|
||||
// Показываем голос пользователя
|
||||
if (pb.authStore.isValid) {
|
||||
if (result.userVote === 'like') {
|
||||
likeBtn?.classList.add('active');
|
||||
} else if (result.userVote === 'dislike') {
|
||||
dislikeBtn?.classList.add('active');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -243,7 +250,15 @@ const { initialLikes = 0, initialDislikes = 0, postId } = Astro.props;
|
|||
}
|
||||
}
|
||||
|
||||
// Вызываем при загрузке и при изменении авторизации
|
||||
loadUserVote();
|
||||
|
||||
// Также при изменении авторизации
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key === 'pb_auth') {
|
||||
loadUserVote();
|
||||
}
|
||||
});
|
||||
|
||||
likeBtn?.addEventListener('click', () => {
|
||||
if (postId) handleVote(postId, 'like');
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ interface Post {
|
|||
categoryColor: string;
|
||||
date: string;
|
||||
readTime: string;
|
||||
readmeTime?: string;
|
||||
image: string;
|
||||
}
|
||||
|
||||
|
|
@ -48,6 +49,7 @@ const filteredPosts = currentSlug
|
|||
categoryColor={post.categoryColor}
|
||||
date={formatDate(post.date)}
|
||||
readTime={post.readTime}
|
||||
readmeTime={post.readmeTime}
|
||||
image={getPostImageUrl(post)}
|
||||
slug={`/blog/${post.slug}`}
|
||||
/>
|
||||
|
|
|
|||
197
frontend/src/components/blog/comments/CommentForm.tsx
Normal file
197
frontend/src/components/blog/comments/CommentForm.tsx
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import { createSignal, Show } from "solid-js";
|
||||
|
||||
interface CommentFormData {
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface ValidationErrors {
|
||||
content?: string;
|
||||
}
|
||||
|
||||
interface CommentFormProps {
|
||||
onSubmit: (data: CommentFormData) => void;
|
||||
isReply?: boolean;
|
||||
onCancel?: () => void;
|
||||
user?: {
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_MESSAGE_LENGTH = 2000;
|
||||
const MIN_MESSAGE_LENGTH = 10;
|
||||
|
||||
const DANGEROUS_PATTERNS = [
|
||||
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
|
||||
/javascript:/gi,
|
||||
/on\w+\s*=/gi,
|
||||
/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
|
||||
/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,
|
||||
/<embed\b[^<]*>/gi,
|
||||
/data:text\/html/gi,
|
||||
/expression\s*\(/gi,
|
||||
/url\s*\(\s*['"]*\s*javascript:/gi,
|
||||
];
|
||||
|
||||
export default function CommentForm(props: CommentFormProps) {
|
||||
const [content, setContent] = createSignal("");
|
||||
const [errors, setErrors] = createSignal<ValidationErrors>({});
|
||||
const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({});
|
||||
|
||||
const sanitizeInput = (input: string): string => {
|
||||
return input
|
||||
.replace(/[<>]/g, "")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, "&");
|
||||
};
|
||||
|
||||
const containsDangerousContent = (input: string): boolean => {
|
||||
return DANGEROUS_PATTERNS.some((pattern) => pattern.test(input));
|
||||
};
|
||||
|
||||
const validateContent = (value: string): string | undefined => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return "Комментарий обязателен";
|
||||
if (trimmed.length < MIN_MESSAGE_LENGTH)
|
||||
return `Минимум ${MIN_MESSAGE_LENGTH} символов`;
|
||||
if (trimmed.length > MAX_MESSAGE_LENGTH)
|
||||
return `Максимум ${MAX_MESSAGE_LENGTH} символов`;
|
||||
if (containsDangerousContent(trimmed)) return "Обнаружен опасный контент";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const handleContentChange = (e: Event) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
let value = target.value;
|
||||
|
||||
if (containsDangerousContent(value)) {
|
||||
DANGEROUS_PATTERNS.forEach((pattern) => {
|
||||
value = value.replace(pattern, "");
|
||||
});
|
||||
}
|
||||
|
||||
if (value.length > MAX_MESSAGE_LENGTH) {
|
||||
value = value.slice(0, MAX_MESSAGE_LENGTH);
|
||||
}
|
||||
|
||||
setContent(value);
|
||||
if (touched().content) {
|
||||
setErrors((prev) => ({ ...prev, content: validateContent(value) }));
|
||||
}
|
||||
};
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const contentError = validateContent(content());
|
||||
setErrors({ content: contentError });
|
||||
setTouched({ content: true });
|
||||
return !contentError;
|
||||
};
|
||||
|
||||
const handleSubmit = (e: Event) => {
|
||||
e.preventDefault();
|
||||
if (!validateForm()) return;
|
||||
|
||||
props.onSubmit({
|
||||
content: sanitizeInput(content().trim()),
|
||||
});
|
||||
|
||||
setContent("");
|
||||
setErrors({});
|
||||
setTouched({});
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
setTouched((prev) => ({ ...prev, content: true }));
|
||||
setErrors((prev) => ({ ...prev, content: validateContent(content()) }));
|
||||
};
|
||||
|
||||
const isValid = () => {
|
||||
return !errors().content && content().trim();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
class={`bg-linear-to-br from-gray-50 to-gray-100 rounded-2xl border border-gray-200 ${props.isReply ? "p-4" : "p-6 md:p-8"}`}
|
||||
>
|
||||
<h4
|
||||
class={`font-semibold text-gray-900 mb-4 flex items-center gap-2 ${props.isReply ? "text-base" : "text-lg"}`}
|
||||
>
|
||||
<svg
|
||||
class="w-5 h-5 text-blue-600"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
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>
|
||||
{props.isReply ? "Написать ответ" : "Оставить комментарий"}
|
||||
</h4>
|
||||
|
||||
<form onSubmit={handleSubmit} class="space-y-4">
|
||||
<div class="space-y-1">
|
||||
<textarea
|
||||
placeholder={props.user ? `Написать комментарий как ${props.user.name || props.user.email}...` : "Ваш комментарий... *"}
|
||||
value={content()}
|
||||
onInput={handleContentChange}
|
||||
onBlur={handleBlur}
|
||||
rows={props.isReply ? 3 : 4}
|
||||
class={`w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none ${
|
||||
errors().content && touched().content
|
||||
? "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="flex justify-between items-center">
|
||||
<Show when={errors().content && touched().content}>
|
||||
<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">
|
||||
<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>
|
||||
{errors().content}
|
||||
</p>
|
||||
</Show>
|
||||
<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}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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">
|
||||
{props.user
|
||||
? `Вы авторизованы как ${props.user.name || props.user.email}`
|
||||
: "Ваш email не будет опубликован"}
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<Show when={props.isReply && props.onCancel}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={props.onCancel}
|
||||
class="px-6 py-3 text-gray-600 hover:text-gray-800 font-medium transition-colors"
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</Show>
|
||||
<button
|
||||
type="submit"
|
||||
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"
|
||||
>
|
||||
<svg 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>
|
||||
{props.isReply ? "Отправить" : "Отправить комментарий"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
73
frontend/src/components/blog/comments/CommentLock.tsx
Normal file
73
frontend/src/components/blog/comments/CommentLock.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { createSignal, onMount } from "solid-js";
|
||||
|
||||
export default function CommentLock() {
|
||||
const [currentPath, setCurrentPath] = createSignal("/auth/login");
|
||||
|
||||
onMount(() => {
|
||||
const path = window.location.pathname;
|
||||
setCurrentPath(`/auth/login?redirect=${encodeURIComponent(path)}`);
|
||||
});
|
||||
|
||||
return (
|
||||
<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">
|
||||
<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>
|
||||
</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 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">
|
||||
<svg
|
||||
class="w-10 h-10 text-blue-600"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<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"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<h4 class="text-xl font-semibold text-gray-900 mb-3">
|
||||
Комментарии доступны только авторизованным пользователям
|
||||
</h4>
|
||||
|
||||
<a
|
||||
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"
|
||||
>
|
||||
<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="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>
|
||||
Войти в аккаунт
|
||||
</a>
|
||||
|
||||
<p class="mt-4 text-sm text-gray-600">
|
||||
Нет аккаунта?{" "}
|
||||
<a
|
||||
href={`/auth/register?redirect=${encodeURIComponent(window.location.pathname)}`}
|
||||
class="text-blue-600 hover:text-blue-700 font-medium hover:underline"
|
||||
>
|
||||
Зарегистрироваться
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
351
frontend/src/components/blog/comments/Comments.tsx
Normal file
351
frontend/src/components/blog/comments/Comments.tsx
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
import { createSignal, For, Show, onMount } from "solid-js";
|
||||
import CommentLock from "./CommentLock";
|
||||
import CommentForm from "./CommentForm";
|
||||
import type { CommentWithReplies } from "../../types/comments";
|
||||
|
||||
interface CommentsProps {
|
||||
postSlug: string;
|
||||
}
|
||||
|
||||
interface ApiComment {
|
||||
id: string;
|
||||
post_slug: string;
|
||||
user: string;
|
||||
content: string;
|
||||
parent?: string | null;
|
||||
is_verified: boolean;
|
||||
status: "pending" | "published" | "spam";
|
||||
created: string;
|
||||
updated: string;
|
||||
expand?: {
|
||||
user?: {
|
||||
id: string;
|
||||
firstName: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface ToastMessage {
|
||||
type: "success" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
export default function Comments(props: CommentsProps) {
|
||||
const [isAuthenticated, setIsAuthenticated] = createSignal(false);
|
||||
const [currentUser, setCurrentUser] = createSignal<{
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
} | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = createSignal(true);
|
||||
const [comments, setComments] = createSignal<CommentWithReplies[]>([]);
|
||||
const [replyTo, setReplyTo] = createSignal<string | null>(null);
|
||||
const [commentAuthors, setCommentAuthors] = createSignal<Record<string, string>>({});
|
||||
const [toastVisible, setToastVisible] = createSignal<string | null>(null);
|
||||
const [toast, setToast] = createSignal<ToastMessage | null>(null);
|
||||
|
||||
const showToast = (message: ToastMessage): void => {
|
||||
setToast(message);
|
||||
setTimeout(() => setToast(null), 3000);
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/auth/me", {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.authenticated && data.user) {
|
||||
setIsAuthenticated(true);
|
||||
setCurrentUser({
|
||||
name: data.user.name || "Пользователь",
|
||||
email: data.user.email,
|
||||
avatar: data.user.avatar,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[Comments] Ошибка проверки авторизации:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
const loadComments = async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/comments?post_slug=${encodeURIComponent(props.postSlug)}&parent=null`,
|
||||
{
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch comments");
|
||||
}
|
||||
|
||||
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(
|
||||
data.items.map(async (comment: ApiComment) => {
|
||||
const repliesResponse = await fetch(
|
||||
`/api/comments?post_slug=${encodeURIComponent(props.postSlug)}&parent=${comment.id}`,
|
||||
{
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
}
|
||||
);
|
||||
const repliesData = await repliesResponse.json();
|
||||
return {
|
||||
...comment,
|
||||
replies: repliesData.items || [],
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
setComments(commentsWithReplies);
|
||||
} catch (error) {
|
||||
console.error("[Comments] Ошибка загрузки комментариев:", error);
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
if (props.postSlug) {
|
||||
loadComments();
|
||||
}
|
||||
});
|
||||
|
||||
const handleNewComment = async (data: { content: string }) => {
|
||||
try {
|
||||
const response = await fetch("/api/comments", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
content: data.content,
|
||||
post_slug: props.postSlug,
|
||||
parent: null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to create comment");
|
||||
}
|
||||
|
||||
await loadComments();
|
||||
} catch (error) {
|
||||
console.error("[Comments] Ошибка создания комментария:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReply = async (commentId: string, data: { content: string }) => {
|
||||
try {
|
||||
const response = await fetch("/api/comments", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
content: data.content,
|
||||
post_slug: props.postSlug,
|
||||
parent: commentId,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
if (errorData.error) {
|
||||
showToast({ type: "error", message: errorData.error });
|
||||
return;
|
||||
}
|
||||
throw new Error(errorData.error || "Failed to create reply");
|
||||
}
|
||||
|
||||
showToast({ type: "success", message: "Ответ успешно отправлен!" });
|
||||
await loadComments();
|
||||
setReplyTo(null);
|
||||
} catch (error) {
|
||||
console.error("[Comments] Ошибка создания ответа:", error);
|
||||
showToast({ type: "error", message: "Не удалось создать ответ. Попробуйте позже." });
|
||||
}
|
||||
};
|
||||
|
||||
const handleReplyClick = (commentId: string) => {
|
||||
const checkAuthAndReply = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/auth/me", {
|
||||
credentials: "include",
|
||||
});
|
||||
const data = await response.json();
|
||||
const currentUserId = data.user?.id;
|
||||
const commentAuthorId = commentAuthors()[commentId];
|
||||
|
||||
if (commentAuthorId && currentUserId === commentAuthorId) {
|
||||
setToastVisible(commentId);
|
||||
setTimeout(() => setToastVisible(null), 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
setReplyTo(replyTo() === commentId ? null : commentId);
|
||||
} catch (error) {
|
||||
console.error("[handleReplyClick] Ошибка проверки автора:", error);
|
||||
setReplyTo(replyTo() === commentId ? null : commentId);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuthAndReply();
|
||||
};
|
||||
|
||||
const Avatar = (props: { author: string; avatar?: string; size?: "sm" | "md" }) => {
|
||||
const size = props.size || "md";
|
||||
const sizeClasses = { sm: "w-8 h-8 text-sm", md: "w-12 h-12 text-lg" };
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={props.avatar}
|
||||
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`}>
|
||||
{props.author.charAt(0)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<img src={props.avatar} alt={props.author} class={`${sizeClasses[size]} rounded-full object-cover shrink-0`} />
|
||||
</Show>
|
||||
);
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString("ru-RU", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Show when={toast()}>
|
||||
{(t) => (
|
||||
<div 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}
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
{isLoading() ? (
|
||||
<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">
|
||||
<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>
|
||||
</div>
|
||||
<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>
|
||||
<p class="mt-4 text-gray-600">Загрузка...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Show when={isAuthenticated()} fallback={<CommentLock />}>
|
||||
<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">
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<Show when={comments().length > 0} fallback={
|
||||
<div class="text-center py-12 text-gray-500">
|
||||
<p>Пока нет комментариев. Будьте первым!</p>
|
||||
</div>
|
||||
}>
|
||||
<div class="space-y-6 mb-10">
|
||||
<For each={comments()}>
|
||||
{(comment) => (
|
||||
<div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
|
||||
<div class="flex items-start gap-4">
|
||||
<Avatar author={comment.expand?.user?.firstName || "Аноним"} avatar={comment.expand?.user?.avatar} />
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 mb-2 flex-wrap">
|
||||
<span class="font-semibold text-gray-900">{comment.expand?.user?.firstName || "Аноним"}</span>
|
||||
<Show when={comment.is_verified}>
|
||||
<svg class="w-4 h-4 text-blue-500" 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>
|
||||
</Show>
|
||||
<span class="text-sm text-gray-400 ml-auto">{formatDate(comment.created)}</span>
|
||||
</div>
|
||||
<p class="text-gray-700 leading-relaxed mb-3">{comment.content}</p>
|
||||
<div class="flex items-center gap-1">
|
||||
<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">
|
||||
<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>
|
||||
{replyTo() === comment.id ? "Отменить" : "Ответить"}
|
||||
</button>
|
||||
<Show when={toastVisible() === comment.id}>
|
||||
<span class="text-xs text-yellow-700 bg-yellow-100 px-2 py-1 rounded-md whitespace-nowrap">
|
||||
Нельзя ответить на свой комментарий
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Show when={replyTo() === comment.id}>
|
||||
<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()} />
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={comment.replies && comment.replies.length > 0}>
|
||||
<div class="mt-4 ml-16 space-y-4">
|
||||
<For each={comment.replies}>
|
||||
{(reply) => (
|
||||
<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" />
|
||||
<div class="flex-1 bg-gray-50 rounded-xl p-4">
|
||||
<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>
|
||||
<Show when={reply.is_verified}>
|
||||
<svg class="w-3 h-3 text-blue-500" 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>
|
||||
</Show>
|
||||
<span class="text-xs text-gray-400 ml-auto">{formatDate(reply.created)}</span>
|
||||
</div>
|
||||
<p class="text-gray-700 text-sm leading-relaxed">{reply.content}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<CommentForm onSubmit={handleNewComment} user={currentUser()} />
|
||||
</div>
|
||||
</Show>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue