Новые правки в компоенты

This commit is contained in:
Web-serfer 2026-04-18 18:25:10 +05:00
parent e85d1ce668
commit 6f727aae7b
23 changed files with 1483 additions and 37 deletions

View file

@ -0,0 +1,126 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = new Collection({
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text4274335913",
"max": 0,
"min": 0,
"name": "content",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1372126313",
"max": 0,
"min": 0,
"name": "post_slug",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "_pb_users_auth_",
"hidden": false,
"id": "relation2375276105",
"maxSelect": 1,
"minSelect": 0,
"name": "user",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1032740943",
"max": 0,
"min": 0,
"name": "parent",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text2063623452",
"max": 0,
"min": 0,
"name": "status",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_533777971",
"indexes": [],
"listRule": null,
"name": "comments",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
});
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_533777971");
return app.delete(collection);
})

View file

@ -0,0 +1,28 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_533777971")
// update collection data
unmarshal({
"createRule": "@request.auth.id != \"\"",
"deleteRule": "user.id = @request.auth.id ",
"listRule": " status = \"published\" || @request.auth.id != \"\" ",
"updateRule": " user.id = @request.auth.id ",
"viewRule": " status = \"published\" || @request.auth.id != \"\" "
}, collection)
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_533777971")
// update collection data
unmarshal({
"createRule": null,
"deleteRule": null,
"listRule": null,
"updateRule": null,
"viewRule": null
}, collection)
return app.save(collection)
})

BIN
bun.lockb Normal file

Binary file not shown.

View file

@ -5,6 +5,7 @@ import node from '@astrojs/node';
import mdx from '@astrojs/mdx'; import mdx from '@astrojs/mdx';
import icon from "astro-icon"; import icon from "astro-icon";
import sitemap from '@astrojs/sitemap'; import sitemap from '@astrojs/sitemap';
import solidJs from '@astrojs/solid-js';
// https://astro.build/config // https://astro.build/config
export default defineConfig({ export default defineConfig({
@ -14,7 +15,7 @@ export default defineConfig({
const blockedPaths = ['/auth/', '/blog/search', '/404']; const blockedPaths = ['/auth/', '/blog/search', '/404'];
return !blockedPaths.some(path => page.includes(path)); return !blockedPaths.some(path => page.includes(path));
}, },
})], }), solidJs()],
vite: { vite: {
plugins: [tailwindcss()], plugins: [tailwindcss()],
build: { build: {

View file

@ -13,14 +13,16 @@
}, },
"dependencies": { "dependencies": {
"@astrojs/mdx": "^5.0.3", "@astrojs/mdx": "^5.0.3",
"nodemailer": "^6.9.14",
"@astrojs/node": "^10.0.4", "@astrojs/node": "^10.0.4",
"@astrojs/sitemap": "^3.7.2", "@astrojs/sitemap": "^3.7.2",
"@astrojs/solid-js": "^6.0.1",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.2.2",
"astro": "^6.0.8", "astro": "^6.0.8",
"astro-icon": "^1.1.5", "astro-icon": "^1.1.5",
"marked": "^18.0.0", "marked": "^18.0.0",
"nodemailer": "^6.9.14",
"pocketbase": "^0.21.0", "pocketbase": "^0.21.0",
"solid-js": "^1.9.12",
"tailwindcss": "^4.2.2" "tailwindcss": "^4.2.2"
}, },
"devDependencies": { "devDependencies": {

View file

@ -6,6 +6,7 @@ export interface Props {
categoryColor?: string; categoryColor?: string;
date: string; date: string;
readTime: string; readTime: string;
readmeTime?: string;
image?: string; image?: string;
slug?: string; slug?: string;
} }
@ -17,6 +18,7 @@ const {
categoryColor = 'bg-gold', categoryColor = 'bg-gold',
date, date,
readTime, readTime,
readmeTime,
image, image,
slug = '#' slug = '#'
} = Astro.props; } = Astro.props;
@ -52,7 +54,7 @@ const imageUrl = image || '/images/blog/default.avif';
<circle cx="12" cy="12" r="10"></circle> <circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline> <polyline points="12 6 12 12 16 14"></polyline>
</svg> </svg>
{readTime} {readmeTime || readTime}
</span> </span>
</div> </div>
</div> </div>

View file

@ -224,18 +224,25 @@ 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() {
if (!pb.authStore.isValid) return;
try { try {
console.log('[Vote] Загрузка голосов для post:', postId);
const response = await fetch(`/api/votes?post_id=${postId}`, { const response = await fetch(`/api/votes?post_id=${postId}`, {
credentials: 'include', credentials: 'include',
}); });
console.log('[Vote] Ответ:', response.status);
if (response.ok) { if (response.ok) {
const result = await response.json(); const result = await response.json();
if (result.userVote === 'like') { console.log('[Vote] Данные:', result);
likeBtn?.classList.add('active'); // Обновляем счетчики
} else if (result.userVote === 'dislike') { if (likesCount) likesCount.textContent = result.likes.toString();
dislikeBtn?.classList.add('active'); 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) { } catch (e) {
@ -243,8 +250,16 @@ const { initialLikes = 0, initialDislikes = 0, postId } = Astro.props;
} }
} }
// Вызываем при загрузке и при изменении авторизации
loadUserVote(); loadUserVote();
// Также при изменении авторизации
window.addEventListener('storage', (e) => {
if (e.key === 'pb_auth') {
loadUserVote();
}
});
likeBtn?.addEventListener('click', () => { likeBtn?.addEventListener('click', () => {
if (postId) handleVote(postId, 'like'); if (postId) handleVote(postId, 'like');
}); });

View file

@ -11,6 +11,7 @@ interface Post {
categoryColor: string; categoryColor: string;
date: string; date: string;
readTime: string; readTime: string;
readmeTime?: string;
image: string; image: string;
} }
@ -48,6 +49,7 @@ const filteredPosts = currentSlug
categoryColor={post.categoryColor} categoryColor={post.categoryColor}
date={formatDate(post.date)} date={formatDate(post.date)}
readTime={post.readTime} readTime={post.readTime}
readmeTime={post.readmeTime}
image={getPostImageUrl(post)} image={getPostImageUrl(post)}
slug={`/blog/${post.slug}`} slug={`/blog/${post.slug}`}
/> />

View 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, "&quot;")
.replace(/'/g, "&#x27;")
.replace(/&/g, "&amp;");
};
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>
);
}

View 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>
);
}

View 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>
)}
</>
);
}

View file

@ -8,6 +8,7 @@ export interface Post {
categoryColor: string; categoryColor: string;
date: string; date: string;
readTime: string; readTime: string;
readmeTime: string;
image: string; image: string;
content?: string; content?: string;
draft: boolean; draft: boolean;

View file

@ -22,6 +22,7 @@ export interface Props {
date: string; date: string;
author: string; author: string;
readTime: string; readTime: string;
readmeTime: string;
postId: string; postId: string;
postUrl: string; postUrl: string;
initialLikes?: number; initialLikes?: number;
@ -40,6 +41,7 @@ const {
date, date,
author, author,
readTime, readTime,
readmeTime,
postId, postId,
postUrl, postUrl,
initialLikes = 0, initialLikes = 0,
@ -100,7 +102,7 @@ const {
</span> </span>
<span class="meta-item"> <span class="meta-item">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="meta-icon"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="meta-icon"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
{readTime} {readmeTime} мин
</span> </span>
</div> </div>
@ -216,6 +218,23 @@ const {
content: none !important; content: none !important;
} }
/* Исключаем секцию комментариев из нумерации */
#post-content .comments-wrapper h2,
#post-content .comments-wrapper h2::before {
counter-increment: none !important;
content: none !important;
}
#post-content .comments-wrapper h3,
#post-content .comments-wrapper h3::before {
counter-increment: none !important;
content: none !important;
}
#post-content .comments-wrapper .section-title,
#post-content .comments-wrapper .section-title::before {
counter-increment: none !important;
content: none !important;
}
/* СКРОЛЛ-ФИКС */ /* СКРОЛЛ-ФИКС */
#post-content h2, #post-content h3 { scroll-margin-top: 125px; } #post-content h2, #post-content h3 { scroll-margin-top: 125px; }

View file

@ -60,13 +60,15 @@ export async function getPostVotes(postId: string): Promise<VoteStats> {
} }
export async function getPostVotesStats(postId: string): Promise<{ likes: number; dislikes: number }> { export async function getPostVotesStats(postId: string): Promise<{ likes: number; dislikes: number }> {
// Получаем данные поста напрямую (likes/dislikes хранятся в самом посте) // Получаем данные из коллекции голосов
const post = await pb.collection('posts').getOne(postId); const votes = await pb.collection('post_votes').getList(1, 1000, {
filter: `post="${postId}"`,
});
return { const likes = votes.items.filter((v: any) => v.vote_type === 'like').length;
likes: post.likes || 0, const dislikes = votes.items.filter((v: any) => v.vote_type === 'dislike').length;
dislikes: post.dislikes || 0,
}; return { likes, dislikes };
} }
export async function vote(postId: string, voteType: 'like' | 'dislike'): Promise<VoteStats> { export async function vote(postId: string, voteType: 'like' | 'dislike'): Promise<VoteStats> {

View file

@ -0,0 +1,109 @@
import type { APIRoute } from 'astro';
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://localhost:8090';
const PASSWORD_MIN_LENGTH = 8;
const PASSWORD_MAX_LENGTH = 12;
const PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/;
function validatePassword(password: string): { valid: boolean; error?: string } {
if (!password || password.length < PASSWORD_MIN_LENGTH) {
return { valid: false, error: 'Пароль должен быть не менее 8 символов' };
}
if (password.length > PASSWORD_MAX_LENGTH) {
return { valid: false, error: 'Пароль не должен превышать 12 символов' };
}
if (!PASSWORD_REGEX.test(password)) {
return { valid: false, error: 'Пароль должен содержать хотя бы одну букву и одну цифру' };
}
return { valid: true };
}
export const POST: APIRoute = async ({ request }) => {
try {
let body;
try {
body = await request.json();
} catch {
return new Response(
JSON.stringify({ error: 'Неверный формат данных' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const { token, password, passwordConfirm } = body;
if (!token) {
return new Response(
JSON.stringify({ error: 'Токен сброса пароля обязателен' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
if (!password || !passwordConfirm) {
return new Response(
JSON.stringify({ error: 'Пароль и подтверждение обязательны' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
if (password !== passwordConfirm) {
return new Response(
JSON.stringify({ error: 'Пароли не совпадают' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const passwordValidation = validatePassword(password);
if (!passwordValidation.valid) {
return new Response(
JSON.stringify({ error: passwordValidation.error }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const confirmUrl = `${POCKETBASE_URL}/api/collections/users/confirm-password-reset`;
const response = await fetch(confirmUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, password, passwordConfirm }),
});
if (response.status === 204) {
return new Response(
JSON.stringify({
success: true,
message: 'Пароль успешно изменён'
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
);
}
let data;
try {
data = await response.json();
} catch {
return new Response(
JSON.stringify({ error: 'Ошибка обработки ответа' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
return new Response(
JSON.stringify({
error: data.message || 'Неверный или истёкший токен сброса пароля'
}),
{ status: response.status, headers: { 'Content-Type': 'application/json' } }
);
} catch (error) {
console.error('[CONFIRM_RESET] Error:', error);
return new Response(
JSON.stringify({
error: 'Внутренняя ошибка сервера'
}),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
};

View file

@ -0,0 +1,73 @@
import type { APIRoute } from "astro";
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
export const GET: APIRoute = async ({ cookies, request }) => {
try {
const pbAuthCookie = cookies.get("pb_auth")?.value;
if (!pbAuthCookie) {
return new Response(
JSON.stringify({ authenticated: false, user: null }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
const token = pbAuthCookie.trim();
const response = await fetch(
`${POCKETBASE_URL}/api/collections/users/auth-refresh`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
if (cookies.has("pb_auth")) {
cookies.delete("pb_auth", { path: "/" });
}
return new Response(
JSON.stringify({ authenticated: false, user: null }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
const data = await response.json();
const isHttps = request.headers.get("x-forwarded-proto") === "https";
cookies.set("pb_auth", data.token, {
path: "/",
maxAge: 60 * 60 * 24 * 7,
httpOnly: false,
secure: isHttps,
sameSite: "lax",
});
const fullName = [data.record.firstName, data.record.lastName].filter(Boolean).join(" ") || data.record.email;
return new Response(
JSON.stringify({
authenticated: true,
user: {
id: data.record.id,
email: data.record.email,
name: fullName,
avatar: data.record.avatar,
verified: data.record.verified,
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
} catch (error) {
console.error("[AUTH ME] Error:", error);
return new Response(
JSON.stringify({ authenticated: false, error: "Ошибка сервера" }),
{ status: 500, headers: { "Content-Type": "application/json" } }
);
}
};

View file

@ -0,0 +1,124 @@
import type { APIRoute } from 'astro';
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://localhost:8090';
const RATE_LIMIT_MAX_REQUESTS = 3;
const RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000;
const rateLimitStore = new Map<string, number[]>();
function cleanOldRecords(email: string, now: number) {
const timestamps = rateLimitStore.get(email) || [];
const windowStart = now - RATE_LIMIT_WINDOW_MS;
const validTimestamps = timestamps.filter(ts => ts > windowStart);
if (validTimestamps.length === 0) {
rateLimitStore.delete(email);
} else {
rateLimitStore.set(email, validTimestamps);
}
}
function checkRateLimit(email: string): { allowed: boolean; remaining?: number; resetIn?: number } {
const now = Date.now();
const normalizedEmail = email.toLowerCase().trim();
cleanOldRecords(normalizedEmail, now);
const timestamps = rateLimitStore.get(normalizedEmail) || [];
if (timestamps.length >= RATE_LIMIT_MAX_REQUESTS) {
const oldestTimestamp = timestamps[0];
const resetIn = RATE_LIMIT_WINDOW_MS - (now - oldestTimestamp);
return { allowed: false, resetIn };
}
timestamps.push(now);
rateLimitStore.set(normalizedEmail, timestamps);
return { allowed: true, remaining: RATE_LIMIT_MAX_REQUESTS - timestamps.length };
}
export const POST: APIRoute = async ({ request }) => {
try {
let body;
try {
body = await request.json();
} catch {
return new Response(
JSON.stringify({ error: 'Неверный формат данных' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const { email } = body;
if (!email) {
return new Response(
JSON.stringify({ error: 'Email обязателен' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const rateLimitResult = checkRateLimit(email);
if (!rateLimitResult.allowed) {
const resetMinutes = Math.ceil((rateLimitResult.resetIn || 0) / 60000);
return new Response(
JSON.stringify({
error: 'Слишком много запросов. Попробуйте позже',
retryAfter: resetMinutes
}),
{
status: 429,
headers: {
'Content-Type': 'application/json',
'Retry-After': String(resetMinutes * 60)
}
}
);
}
const resetUrl = `${POCKETBASE_URL}/api/collections/users/request-password-reset`;
const response = await fetch(resetUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
if (response.status === 204) {
return new Response(
JSON.stringify({
success: true,
message: 'Письмо для сброса пароля отправлено'
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
);
}
let data;
try {
data = await response.json();
} catch {
return new Response(
JSON.stringify({ error: 'Ошибка обработки ответа' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
return new Response(
JSON.stringify({
error: data.message || 'Ошибка при отправке письма для сброса пароля'
}),
{ status: response.status, headers: { 'Content-Type': 'application/json' } }
);
} catch (error) {
console.error('[PASSWORD_RESET] Error:', error);
return new Response(
JSON.stringify({
error: 'Внутренняя ошибка сервера'
}),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
};

View file

@ -0,0 +1,248 @@
import type { APIRoute } from "astro";
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
export const GET: APIRoute = async ({ url, cookies }) => {
const postSlug = url.searchParams.get("post_slug");
const parent = url.searchParams.get("parent");
if (!postSlug) {
return new Response(
JSON.stringify({ error: "post_slug required" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
}
);
}
const pbAuthCookie = cookies.get("pb_auth")?.value;
const token = pbAuthCookie?.trim();
// Фильтр: комментарии для поста + статус published
let filter = `post_slug = "${postSlug}" && status = "published"`;
// Если parent = null — это основные комментарии (не ответы)
// Если parent указан — это ответы на конкретный комментарий
if (parent === "null" || parent === null) {
filter += ` && parent = ""`;
} else if (parent) {
filter += ` && parent = "${parent}"`;
}
const expand = "user";
const sort = "-created";
try {
const response = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records?expand=${expand}&filter=${encodeURIComponent(filter)}&sort=${sort}`,
{
headers: token ? { Authorization: `Bearer ${token}` } : {},
}
);
const data = await response.json();
return new Response(JSON.stringify(data), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("[Comments API GET] Error:", error);
return new Response(
JSON.stringify({ error: "Failed to fetch comments" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
};
export const POST: APIRoute = async ({ request, cookies }) => {
const pbAuthCookie = cookies.get("pb_auth")?.value;
const token = pbAuthCookie?.trim();
console.log("[Comments API POST] Токен получен:", !!token);
console.log("[Comments API POST] Длина токена:", token?.length);
console.log("[Comments API POST] Cookie:", pbAuthCookie ? "да" : "нет");
if (!token) {
console.log("[Comments API POST] Токен не найден - 401");
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
// Получаем данные пользователя из токена
let userId: string | null = null;
try {
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;
}
} catch (e) {
console.error("[Comments API POST] Не удалось получить данные пользователя:", e);
}
if (!userId) {
console.log("[Comments API POST] Не удалось получить ID пользователя");
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
try {
const body = await request.json();
const { content, post_slug, parent = null } = body;
// Валидация
if (!content || !post_slug) {
return new Response(
JSON.stringify({ error: "content and post_slug required" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
}
);
}
if (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" },
}
);
}
// Проверка: если это ответ на комментарий
if (parent) {
const parentCommentResponse = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records/${parent}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (parentCommentResponse.ok) {
const parentComment = await parentCommentResponse.json();
// Если родительский комментарий уже сам является ответом — запрещаем (только 2 уровня)
if (parentComment.parent && parentComment.parent !== "") {
return new Response(
JSON.stringify({ error: "Нельзя отвечать на ответы. Вы можете ответить только на основные комментарии." }),
{
status: 403,
headers: { "Content-Type": "application/json" },
}
);
}
// Нельзя отвечать на свой комментарий
if (parentComment.user === userId) {
return new Response(
JSON.stringify({ error: "Нельзя отвечать на свой собственный коммен<D0B5><D0BD>арий" }),
{
status: 403,
headers: { "Content-Type": "application/json" },
}
);
}
// Проверяем: если родительский комментарий уже имеет ответы — запрещаем (только 1 уровень ответов)
const existingRepliesResponse = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records?filter=parent="${parent}"&perPage=1`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (existingRepliesResponse.ok) {
const existingRepliesData = await existingRepliesResponse.json();
if (existingRepliesData.totalItems > 0) {
return new Response(
JSON.stringify({ error: "На этот комментарий уже есть ответ. Вы можете ответить только на основные комментарии." }),
{
status: 403,
headers: { "Content-Type": "application/json" },
}
);
}
}
} else {
return new Response(
JSON.stringify({ error: "Родительский комментарий не найден" }),
{
status: 404,
headers: { "Content-Type": "application/json" },
}
);
}
}
const response = await fetch(
`${POCKETBASE_URL}/api/collections/comments/records`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
content,
post_slug,
parent: parent || "",
status: "published",
user: userId, // Передаём ID текущего пользователя
}),
}
);
const data = await response.json();
console.log("[Comments API POST] Ответ PocketBase:", response.status, JSON.stringify(data));
if (!response.ok) {
return new Response(JSON.stringify(data), {
status: response.status,
headers: { "Content-Type": "application/json" },
});
}
return new Response(JSON.stringify(data), {
status: 201,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("[Comments API POST] Error:", error);
return new Response(
JSON.stringify({ error: "Failed to create comment" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
};

View file

@ -39,11 +39,14 @@ export const POST: APIRoute = async ({ request, cookies }) => {
const authData = await authResponse.json(); const authData = await authResponse.json();
console.log('[Vote API] Auth refresh full response:', JSON.stringify(authData));
// ВАЖНО: Явно берем id, а не email // ВАЖНО: Явно берем id, а не email
const userId = authData.record?.id; const userId = authData.record?.id || authData.record?.ID;
const userEmail = authData.record?.email; const userEmail = authData.record?.email;
console.log('[Vote API] Auth data:', { userId, userEmail, record: authData.record }); console.log('[Vote API] User ID extracted:', userId);
console.log('[Vote API] User Email extracted:', userEmail);
// Защита: проверяем что это действительно ID, а не email // Защита: проверяем что это действительно ID, а не email
if (!userId || EMAIL_REGEX.test(userId)) { if (!userId || EMAIL_REGEX.test(userId)) {
@ -115,9 +118,11 @@ export const POST: APIRoute = async ({ request, cookies }) => {
} }
// Выполняем операцию с голосом // Выполняем операцию с голосом
console.log('[Vote API] Creating vote with:', { post: post_id, user: userId, vote_type });
const voteBody = method === 'POST' ? JSON.stringify({ const voteBody = method === 'POST' ? JSON.stringify({
post: post_id, post: post_id,
user: userId, // Теперь точно ID, а не email user: userId,
vote_type, vote_type,
}) : method === 'PATCH' ? JSON.stringify({ vote_type }) : null; }) : method === 'PATCH' ? JSON.stringify({ vote_type }) : null;
@ -130,6 +135,15 @@ export const POST: APIRoute = async ({ request, cookies }) => {
body: voteBody, body: voteBody,
}); });
console.log('[Vote API] Vote response status:', voteRes.status);
if (!voteRes.ok) {
const errorText = await voteRes.text();
console.log('[Vote API] Vote error response:', errorText);
} else {
const createdVote = await voteRes.json();
console.log('[Vote API] Created vote:', JSON.stringify(createdVote));
}
if (!voteRes.ok && method !== 'DELETE') { if (!voteRes.ok && method !== 'DELETE') {
const errorText = await voteRes.text(); const errorText = await voteRes.text();
console.error('[Vote API] Failed to save vote:', errorText); console.error('[Vote API] Failed to save vote:', errorText);
@ -139,16 +153,13 @@ export const POST: APIRoute = async ({ request, cookies }) => {
if (method === 'POST') userVote = vote_type; if (method === 'POST') userVote = vote_type;
if (method === 'DELETE') userVote = null; if (method === 'DELETE') userVote = null;
// Получаем актуальные счетчики // Получаем актуальные счетчики (без авторизации)
const votesRes = await fetch( const votesRes = await fetch(
`${POCKETBASE_URL}/api/collections/post_votes/records?` + `${POCKETBASE_URL}/api/collections/post_votes/records?` +
new URLSearchParams({ new URLSearchParams({
filter: `post="${post_id}"`, filter: `post="${post_id}"`,
fields: 'vote_type', fields: 'vote_type',
}), })
{
headers: { 'Authorization': `Bearer ${token}` },
}
); );
let likes = 0; let likes = 0;
@ -160,7 +171,8 @@ export const POST: APIRoute = async ({ request, cookies }) => {
dislikes = votesData.items.filter((v: any) => v.vote_type === 'dislike').length; dislikes = votesData.items.filter((v: any) => v.vote_type === 'dislike').length;
} }
// Обновляем счетчики в посте // Обновляем счетчики в посте только если есть токен
if (token) {
await fetch( await fetch(
`${POCKETBASE_URL}/api/collections/posts/records/${post_id}`, `${POCKETBASE_URL}/api/collections/posts/records/${post_id}`,
{ {
@ -172,6 +184,7 @@ export const POST: APIRoute = async ({ request, cookies }) => {
body: JSON.stringify({ likes, dislikes }), body: JSON.stringify({ likes, dislikes }),
} }
); );
}
return new Response( return new Response(
JSON.stringify({ likes, dislikes, userVote }), JSON.stringify({ likes, dislikes, userVote }),
@ -216,6 +229,24 @@ export const GET: APIRoute = async ({ url, cookies }) => {
const post = await postRes.json(); const post = await postRes.json();
// Получаем счетчики из коллекции голосов (без авторизации)
const votesCountRes = await fetch(
`${POCKETBASE_URL}/api/collections/post_votes/records?` +
new URLSearchParams({
filter: `post="${postId}"`,
fields: 'vote_type',
})
);
let likes = post.likes || 0;
let dislikes = post.dislikes || 0;
if (votesCountRes.ok) {
const votesData = await votesCountRes.json();
likes = votesData.items.filter((v: any) => v.vote_type === 'like').length;
dislikes = votesData.items.filter((v: any) => v.vote_type === 'dislike').length;
}
// Определяем голос текущего пользователя // Определяем голос текущего пользователя
let userVote: 'like' | 'dislike' | null = null; let userVote: 'like' | 'dislike' | null = null;
@ -232,9 +263,12 @@ export const GET: APIRoute = async ({ url, cookies }) => {
if (authRes.ok) { if (authRes.ok) {
const authData = await authRes.json(); const authData = await authRes.json();
const userId = authData.record?.id; console.log('[Vote API] GET auth refresh:', JSON.stringify(authData.record));
const userId = authData.record?.id || authData.record?.ID;
if (userId && POCKETBASE_ID_REGEX.test(userId)) { if (userId && POCKETBASE_ID_REGEX.test(userId)) {
console.log('[Vote API] GET: Checking for existing vote with:', { post: postId, user: userId });
const userVoteRes = await fetch( const userVoteRes = await fetch(
`${POCKETBASE_URL}/api/collections/post_votes/records?` + `${POCKETBASE_URL}/api/collections/post_votes/records?` +
new URLSearchParams({ new URLSearchParams({
@ -260,8 +294,8 @@ export const GET: APIRoute = async ({ url, cookies }) => {
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
likes: post.likes || 0, likes,
dislikes: post.dislikes || 0, dislikes,
userVote, userVote,
}), }),
{ status: 200, headers: { 'Content-Type': 'application/json' }} { status: 200, headers: { 'Content-Type': 'application/json' }}

View file

@ -73,7 +73,7 @@ import { SITE_URL } from '@constants';
submitBtn.textContent = 'Отправка...'; submitBtn.textContent = 'Отправка...';
try { try {
const response = await fetch('/api/auth/forgot-password', { const response = await fetch('/api/auth/request-password-reset', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }), body: JSON.stringify({ email }),

View file

@ -157,10 +157,10 @@ const error = Astro.url.searchParams.get('error');
submitBtn.textContent = 'Сохранение...'; submitBtn.textContent = 'Сохранение...';
try { try {
const response = await fetch('/api/auth/reset-password', { const response = await fetch('/api/auth/confirm-password-reset', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, userId, password }), body: JSON.stringify({ token, password, passwordConfirm }),
}); });
const data = await response.json(); const data = await response.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 PostCommentForm from '@components/blog/PostCommentForm.astro'; import Comments from '@components/blog/comments/Comments';
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';
@ -71,6 +71,7 @@ const heroImage = getPostImageUrl(post);
date={formatDate(post.date)} date={formatDate(post.date)}
author={post.author} author={post.author}
readTime={post.readTime} readTime={post.readTime}
readmeTime={post.readmeTime}
postId={post.id} postId={post.id}
postUrl={currentUrl} postUrl={currentUrl}
initialLikes={likes} initialLikes={likes}
@ -79,11 +80,10 @@ const heroImage = getPostImageUrl(post);
<!-- Содержимое статьи --> <!-- Содержимое статьи -->
<div class="post-content" set:html={contentHtml} /> <div class="post-content" set:html={contentHtml} />
<!-- Форма комментариев --> <!-- Система комментариев -->
<PostCommentForm <div class="comments-wrapper">
postId={post.id} <Comments client:only="solid-js" postSlug={post.slug} />
isAuthorized={false} </div>
/>
<!-- Похожие статьи --> <!-- Похожие статьи -->
<RelatedPosts <RelatedPosts

View file

@ -0,0 +1,39 @@
export interface CommentRecord {
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?: UserRecord;
};
}
export interface UserRecord {
id: string;
name: string;
email: string;
avatar?: string;
}
export interface CommentWithReplies extends CommentRecord {
replies?: CommentWithReplies[];
}
export interface CommentFormData {
content: string;
post_slug: string;
parent?: string | null;
}
export interface CommentsApiResponse {
page: number;
perPage: number;
totalItems: number;
totalPages: number;
items: CommentRecord[];
}