first commit
This commit is contained in:
commit
4a589825c2
297 changed files with 33019 additions and 0 deletions
140
frontend/src/components/single-post/AuthorConsultation.astro
Normal file
140
frontend/src/components/single-post/AuthorConsultation.astro
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
---
|
||||
import Button from "../base/Button.astro";
|
||||
import { CONTACT_CONSTANTS } from "@constants/constants.ts";
|
||||
|
||||
export interface Props {
|
||||
author: {
|
||||
name: string;
|
||||
avatar: string;
|
||||
role?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const { author } = Astro.props;
|
||||
|
||||
const benefits = [
|
||||
{ text: "Анализ ситуации и перспектив дела" },
|
||||
{ text: "Понятные рекомендации по действиям" },
|
||||
{ text: "Оценка рисков и варианты решения" },
|
||||
];
|
||||
---
|
||||
|
||||
<div
|
||||
class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 sticky top-30"
|
||||
>
|
||||
<!-- Автор -->
|
||||
<div class="text-center pb-6 border-b border-gray-100">
|
||||
<img
|
||||
src={author.avatar}
|
||||
alt={author.name}
|
||||
class="w-20 h-20 rounded-full object-cover mx-auto mb-4 border-4 border-blue-primary"
|
||||
/>
|
||||
<h3 class="text-lg font-bold text-gray-900">
|
||||
{author.name}
|
||||
</h3>
|
||||
<p class="text-sm text-gray-500">
|
||||
{author.role || "Юрист"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Блок консультации -->
|
||||
<div
|
||||
class="mt-6 relative overflow-hidden rounded-xl bg-gradient-to-br from-[var(--color-navy)] via-[var(--color-navy-dark)] to-[var(--color-navy-darker)] p-6 text-white shadow-xl"
|
||||
>
|
||||
<!-- Декоративные элементы -->
|
||||
<div
|
||||
class="absolute top-0 right-0 -mt-8 -mr-8 w-32 h-32 bg-gold opacity-20 rounded-full blur-3xl"
|
||||
>
|
||||
</div>
|
||||
<div
|
||||
class="absolute bottom-0 left-0 -mb-8 -ml-8 w-24 h-24 bg-blue-primary opacity-10 rounded-full blur-2xl"
|
||||
>
|
||||
</div>
|
||||
|
||||
<!-- Иконка по центру -->
|
||||
<div class="relative flex justify-center mb-5">
|
||||
<div
|
||||
class="w-16 h-16 bg-linear-to-br from-[var(--color-gold)] to-[var(--color-gold-hover)] rounded-2xl flex items-center justify-center shadow-lg shadow-[var(--color-gold)]/30"
|
||||
>
|
||||
<svg
|
||||
class="w-8 h-8 text-white"
|
||||
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"
|
||||
></path>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Контент -->
|
||||
<div class="relative text-center">
|
||||
<h4 class="text-xl font-bold mb-2">Требуется консультация?</h4>
|
||||
<p class="text-slate-300 text-sm leading-relaxed mb-5">
|
||||
Получите профессиональную правовую помощь по вашему вопросу. Первичная
|
||||
консультация бесплатно.
|
||||
</p>
|
||||
|
||||
<!-- Преимущества -->
|
||||
<ul class="space-y-3 mb-6 text-sm text-white text-left">
|
||||
{
|
||||
benefits.map((benefit) => (
|
||||
<li class="flex items-start gap-3">
|
||||
<div class="w-5 h-5 rounded-full bg-gold flex items-center justify-center shrink-0 mt-0.5">
|
||||
<svg
|
||||
class="w-3 h-3 text-white"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<span>{benefit.text}</span>
|
||||
</li>
|
||||
))
|
||||
}
|
||||
</ul>
|
||||
|
||||
<!-- Кнопка -->
|
||||
<Button
|
||||
text="Получить консультацию"
|
||||
variant="primary-white-text"
|
||||
size="md"
|
||||
data-consultation-modal
|
||||
className="flex items-center justify-center gap-2 group cursor-pointer"
|
||||
/>
|
||||
|
||||
<!-- Дополнительная информация -->
|
||||
<div
|
||||
class="flex items-center justify-center gap-4 mt-4 text-xs text-slate-400"
|
||||
>
|
||||
<span class="flex items-center gap-1">
|
||||
<svg
|
||||
class="w-3 h-3"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
|
||||
</svg>
|
||||
Ответ за 15 минут
|
||||
</span>
|
||||
<span class="w-1 h-1 bg-slate-500 rounded-full"></span>
|
||||
<span>Конфиденциально</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
567
frontend/src/components/single-post/BlogPost.astro
Normal file
567
frontend/src/components/single-post/BlogPost.astro
Normal file
|
|
@ -0,0 +1,567 @@
|
|||
---
|
||||
import { MONTHS } from "@lib/constants";
|
||||
import NumberedContent from "./NumberedContent.astro";
|
||||
import AuthorConsultation from "./AuthorConsultation.astro";
|
||||
|
||||
export interface Props {
|
||||
title: string;
|
||||
excerpt: string;
|
||||
author: {
|
||||
name: string;
|
||||
avatar: string;
|
||||
role?: string;
|
||||
};
|
||||
publishDate: string | Date;
|
||||
readTime?: string;
|
||||
tags?: string[];
|
||||
featuredImage?: string;
|
||||
tableOfContents?: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
}>;
|
||||
content?: string;
|
||||
postId?: string;
|
||||
likes?: number;
|
||||
dislikes?: number;
|
||||
}
|
||||
|
||||
function formatDate(dateInput: string | Date): string {
|
||||
const date = new Date(dateInput);
|
||||
return `${date.getDate()} ${MONTHS[date.getMonth()]} ${date.getFullYear()} года`;
|
||||
}
|
||||
|
||||
const {
|
||||
title,
|
||||
excerpt,
|
||||
author,
|
||||
publishDate,
|
||||
readTime = "5 мин чтения",
|
||||
tags = [],
|
||||
featuredImage,
|
||||
tableOfContents = [],
|
||||
content,
|
||||
postId,
|
||||
likes = 0,
|
||||
dislikes = 0,
|
||||
} = Astro.props;
|
||||
|
||||
// дата поста
|
||||
const formattedPublishDate = typeof publishDate === "string"
|
||||
? publishDate
|
||||
: formatDate(publishDate);
|
||||
---
|
||||
|
||||
<article class="min-h-screen bg-gray-50">
|
||||
{
|
||||
featuredImage && (
|
||||
<div class="relative w-full h-64 md:h-96 lg:h-125 overflow-hidden">
|
||||
<img
|
||||
src={featuredImage}
|
||||
alt={title}
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
{/* Затемнение для контраста текста */}
|
||||
<div class="absolute inset-0 bg-linear-to-t from-black/75 via-black/70 to-black/40" />
|
||||
|
||||
{/* Декоративные элементы */}
|
||||
<div class="absolute top-0 left-0 w-full h-full pointer-events-none">
|
||||
{/* Золотая линия сверху */}
|
||||
<div class="absolute top-0 left-1/2 -translate-x-1/2 w-24 h-1 bg-linear-to-r from-transparent via-[var(--color-gold)] to-transparent opacity-80"></div>
|
||||
<!-- Уголки -->
|
||||
<div class="absolute top-8 left-8 w-16 h-16 border-t-2 border-l-2 border-gold/40 rounded-tl-lg"></div>
|
||||
<div class="absolute top-8 right-8 w-16 h-16 border-t-2 border-r-2 border-gold/40 rounded-tr-lg"></div>
|
||||
</div>
|
||||
|
||||
<div class="absolute bottom-0 left-0 right-0 p-6 md:p-12">
|
||||
<div class="max-w-4xl mx-auto relative z-10">
|
||||
<!-- Категория/тег -->
|
||||
<div class="flex items-center gap-2 mb-4">
|
||||
<span class="px-4 py-1.5 bg-gold/90 backdrop-blur-sm text-white text-xs font-bold uppercase tracking-wider rounded-full shadow-lg">
|
||||
Статья
|
||||
</span>
|
||||
<div class="h-px w-12 bg-linear-to-r from-[var(--color-gold)] to-transparent opacity-60"></div>
|
||||
</div>
|
||||
|
||||
<!-- Заголовок -->
|
||||
<h1 class="text-3xl md:text-4xl lg:text-5xl xl:text-6xl font-extrabold text-white mb-6 leading-tight drop-shadow-2xl">
|
||||
{title}
|
||||
</h1>
|
||||
|
||||
<!-- Декоративная линия под заголовком -->
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="h-1 w-20 bg-linear-to-r from-[var(--color-gold)] to-[var(--color-gold)]/60 rounded-full"></div>
|
||||
<div class="h-1 w-1 bg-[var(--color-gold)] rounded-full"></div>
|
||||
<div class="h-1 w-1 bg-[var(--color-gold)] rounded-full"></div>
|
||||
<div class="h-1 w-1 bg-[var(--color-gold)] rounded-full"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
|
||||
<div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
|
||||
<main class="lg:col-span-8">
|
||||
{
|
||||
!featuredImage && (
|
||||
<div class="mb-8">
|
||||
<h1 class="text-3xl md:text-4xl lg:text-5xl font-bold text-gray-900 mb-4 leading-tight">
|
||||
{title}
|
||||
</h1>
|
||||
<p class="text-xl text-gray-600 leading-relaxed">{excerpt}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
<div class="flex flex-col gap-4 mb-8 pb-8 border-b border-gray-200">
|
||||
<div class="flex justify-between items-center">
|
||||
<time class="flex items-center gap-1 text-sm text-gray-500">
|
||||
<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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
></path></svg
|
||||
>
|
||||
{formattedPublishDate}
|
||||
</time>
|
||||
<span class="flex items-center gap-1 text-sm text-gray-500">
|
||||
<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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg
|
||||
>
|
||||
{readTime}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{
|
||||
tags.length > 0 && (
|
||||
<div class="flex flex-wrap gap-2 mb-8">
|
||||
{tags.map((tag) => (
|
||||
<span class="px-3 py-1 bg-blue-50 text-blue-600 text-sm font-medium rounded-full hover:bg-blue-100 transition-colors cursor-pointer">
|
||||
#{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{
|
||||
tableOfContents.length > 0 && (
|
||||
<details
|
||||
open
|
||||
class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8 group"
|
||||
>
|
||||
<summary class="flex items-center justify-between cursor-pointer list-none font-semibold text-gray-900 text-lg select-none">
|
||||
<span class="flex items-center gap-2">
|
||||
<svg
|
||||
class="w-5 h-5 text-blue-500"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M4 6h16M4 12h16M4 18h7"
|
||||
/>
|
||||
</svg>
|
||||
Содержание
|
||||
</span>
|
||||
<svg
|
||||
class="w-5 h-5 text-gray-400 transition-transform group-open:rotate-180"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</summary>
|
||||
<div class="mt-4 pt-4 border-t border-gray-100">
|
||||
<ol class="space-y-2">
|
||||
{tableOfContents.map((item, index) => (
|
||||
<li>
|
||||
<a
|
||||
href={`#${item.id}`}
|
||||
class="flex items-start gap-2 text-gray-700 hover:text-blue-600 hover:bg-blue-50 p-2 rounded-lg transition-colors group/item"
|
||||
>
|
||||
<span class="shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm font-medium group-hover/item:bg-blue-200">
|
||||
{index + 1}
|
||||
</span>
|
||||
<span class="leading-tight">{item.title}</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
|
||||
<!-- ТЕЛО СТАТЬИ -->
|
||||
<div
|
||||
class="bg-white rounded-2xl shadow-sm border border-gray-200 p-8 md:p-10"
|
||||
>
|
||||
<NumberedContent tableOfContents={tableOfContents}>
|
||||
<slot />
|
||||
</NumberedContent>
|
||||
</div>
|
||||
|
||||
<blockquote
|
||||
class="relative p-8 my-8 bg-linear-to-r from-blue-50 to-indigo-50 rounded-2xl border-l-4 border-blue-500"
|
||||
>
|
||||
<svg
|
||||
class="absolute top-4 left-4 w-8 h-8 text-blue-200"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
><path
|
||||
d="M14.017 21v-7.391c0-5.704 3.731-9.57 8.983-10.609l.995 2.151c-2.432.917-3.995 3.638-3.995 5.849h4v10h-9.983zm-14.017 0v-7.391c0-5.704 3.748-9.57 9-10.609l.996 2.151c-2.433.917-3.996 3.638-3.996 5.849h3.983v10h-9.983z"
|
||||
></path></svg
|
||||
>
|
||||
<p
|
||||
class="relative text-lg md:text-xl text-gray-800 font-medium italic pl-8"
|
||||
>
|
||||
"Правовая грамотность — лучшая защита ваших интересов в любой
|
||||
жизненной ситуации."
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
<!-- Блок голосования -->
|
||||
<div class="mt-6 mb-8 flex justify-center">
|
||||
<div
|
||||
class="post-likes-widget"
|
||||
data-post-id={postId}
|
||||
data-initial-likes={likes}
|
||||
data-initial-dislikes={dislikes}
|
||||
>
|
||||
<div class="vote-group">
|
||||
<button
|
||||
type="button"
|
||||
class="vote-btn like-btn"
|
||||
aria-label="Нравится"
|
||||
>
|
||||
<svg
|
||||
class="thumb-icon"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path
|
||||
d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="vote-count like-count">{likes}</span>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="vote-group">
|
||||
<button
|
||||
type="button"
|
||||
class="vote-btn dislike-btn"
|
||||
aria-label="Не нравится"
|
||||
>
|
||||
<svg
|
||||
class="thumb-icon"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path
|
||||
d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="vote-count dislike-count">{dislikes}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<script>
|
||||
// Инициализация виджета голосования
|
||||
(function() {
|
||||
const widgets = document.querySelectorAll('.post-likes-widget');
|
||||
|
||||
widgets.forEach(widget => {
|
||||
const postId = widget.getAttribute('data-post-id');
|
||||
const likeBtn = widget.querySelector('.like-btn');
|
||||
const dislikeBtn = widget.querySelector('.dislike-btn');
|
||||
const likeCount = widget.querySelector('.like-count');
|
||||
const dislikeCount = widget.querySelector('.dislike-count');
|
||||
|
||||
let likes = parseInt(widget.getAttribute('data-initial-likes') || '0');
|
||||
let dislikes = parseInt(widget.getAttribute('data-initial-dislikes') || '0');
|
||||
let userVote = null;
|
||||
let isLoading = false;
|
||||
let isDisabled = false; // Блокировка кнопок
|
||||
|
||||
console.log('[PostLikes] Инициализация:', { postId, likes, dislikes });
|
||||
|
||||
// Блокировка/разблокировка кнопок
|
||||
function setButtonsDisabled(disabled) {
|
||||
isDisabled = disabled;
|
||||
if (likeBtn) likeBtn.disabled = disabled;
|
||||
if (dislikeBtn) dislikeBtn.disabled = disabled;
|
||||
widget.style.opacity = disabled ? '0.6' : '1';
|
||||
widget.style.pointerEvents = disabled ? 'none' : 'auto';
|
||||
}
|
||||
|
||||
// Загрузка реальных данных
|
||||
async function loadVotes() {
|
||||
if (!postId) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/likes?post_id=${encodeURIComponent(postId)}`);
|
||||
console.log('[PostLikes] Ответ API:', response.status);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
console.log('[PostLikes] Данные:', data);
|
||||
|
||||
likes = data.likes || 0;
|
||||
dislikes = data.dislikes || 0;
|
||||
userVote = data.userVote;
|
||||
updateUI();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[PostLikes] Ошибка загрузки:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Голосование
|
||||
async function handleVote(action) {
|
||||
// Двойная проверка блокировки
|
||||
if (isLoading || isDisabled) {
|
||||
console.log('[PostLikes] Заблокировано, пропускаем');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[PostLikes] Голосование:', action);
|
||||
|
||||
if (!postId) return;
|
||||
|
||||
// Блокируем кнопки СРАЗУ
|
||||
isLoading = true;
|
||||
setButtonsDisabled(true);
|
||||
|
||||
// Оптимистичное обновление
|
||||
if (action === 'like') {
|
||||
if (userVote === 'like') {
|
||||
likes = Math.max(0, likes - 1);
|
||||
userVote = null;
|
||||
} else if (userVote === 'dislike') {
|
||||
dislikes = Math.max(0, dislikes - 1);
|
||||
likes++;
|
||||
userVote = 'like';
|
||||
} else {
|
||||
likes++;
|
||||
userVote = 'like';
|
||||
}
|
||||
} else {
|
||||
if (userVote === 'dislike') {
|
||||
dislikes = Math.max(0, dislikes - 1);
|
||||
userVote = null;
|
||||
} else if (userVote === 'like') {
|
||||
likes = Math.max(0, likes - 1);
|
||||
dislikes++;
|
||||
userVote = 'dislike';
|
||||
} else {
|
||||
dislikes++;
|
||||
userVote = 'dislike';
|
||||
}
|
||||
}
|
||||
updateUI();
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/likes', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ post_id: postId, vote_type: action }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log('[PostLikes] Ответ сервера:', response.status, data);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
alert('Для голосования необходимо войти в систему');
|
||||
loadVotes(); // Откат
|
||||
return;
|
||||
}
|
||||
throw new Error(data.error || 'Ошибка');
|
||||
}
|
||||
|
||||
// Обновляем реальными данными с сервера
|
||||
likes = data.likes || 0;
|
||||
dislikes = data.dislikes || 0;
|
||||
userVote = data.userVote;
|
||||
updateUI();
|
||||
|
||||
console.log('[PostLikes] Успешно:', { likes, dislikes, userVote });
|
||||
} catch (error) {
|
||||
console.error('[PostLikes] Ошибка:', error);
|
||||
alert('Не удалось сохранить голос');
|
||||
loadVotes(); // Откат
|
||||
} finally {
|
||||
isLoading = false;
|
||||
// НЕ разблокируем кнопки - голосование окончено
|
||||
// Кнопки остаются заблокированными для повторного голосования
|
||||
console.log('[PostLikes] Голосование завершено');
|
||||
}
|
||||
}
|
||||
|
||||
// Обновление UI
|
||||
function updateUI() {
|
||||
if (likeCount) likeCount.textContent = likes.toString();
|
||||
if (dislikeCount) dislikeCount.textContent = dislikes.toString();
|
||||
|
||||
if (likeBtn && dislikeBtn) {
|
||||
if (userVote === 'like') {
|
||||
likeBtn.classList.add('active');
|
||||
dislikeBtn.classList.remove('active');
|
||||
} else if (userVote === 'dislike') {
|
||||
dislikeBtn.classList.add('active');
|
||||
likeBtn.classList.remove('active');
|
||||
} else {
|
||||
likeBtn.classList.remove('active');
|
||||
dislikeBtn.classList.remove('active');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Обработчики
|
||||
likeBtn?.addEventListener('click', () => handleVote('like'));
|
||||
dislikeBtn?.addEventListener('click', () => handleVote('dislike'));
|
||||
|
||||
// Загружаем реальные данные
|
||||
loadVotes();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
|
||||
</main>
|
||||
|
||||
<!-- Боковой блок -->
|
||||
<aside class="lg:col-span-4">
|
||||
<AuthorConsultation author={author} />
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<style>
|
||||
.post-likes-widget {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
background: #ffffff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.vote-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.vote-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 0.75rem;
|
||||
background: #ffffff;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.vote-btn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
/* Лайк */
|
||||
.vote-btn.like-btn:hover {
|
||||
border-color: #86efac;
|
||||
background: #f0fdf4;
|
||||
color: #16a34a;
|
||||
}
|
||||
|
||||
.vote-btn.like-btn.active {
|
||||
background: #16a34a;
|
||||
border-color: #16a34a;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
/* Дизлайк */
|
||||
.vote-btn.dislike-btn:hover {
|
||||
border-color: #fca5a5;
|
||||
background: #fef2f2;
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.vote-btn.dislike-btn.active {
|
||||
background: #dc2626;
|
||||
border-color: #dc2626;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.thumb-icon {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.vote-count {
|
||||
min-width: 1.5rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.divider {
|
||||
width: 1px;
|
||||
height: 1.5rem;
|
||||
background: #e5e7eb;
|
||||
margin: 0 0.25rem;
|
||||
}
|
||||
</style>
|
||||
232
frontend/src/components/single-post/CommentForm.tsx
Normal file
232
frontend/src/components/single-post/CommentForm.tsx
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
import { createSignal, Show } from "solid-js";
|
||||
|
||||
interface CommentFormData {
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface ValidationErrors {
|
||||
content?: string;
|
||||
}
|
||||
|
||||
interface CommentFormProps {
|
||||
onSubmit: (data: CommentFormData) => void;
|
||||
isReply?: boolean;
|
||||
onCancel?: () => void;
|
||||
// Данные авторизованного пользователя из PocketBase
|
||||
user?: {
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
};
|
||||
}
|
||||
|
||||
// 🔒 Запрещённые паттерны для защиты от XSS
|
||||
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,
|
||||
];
|
||||
|
||||
// Лимиты
|
||||
const MAX_MESSAGE_LENGTH = 2000;
|
||||
const MIN_MESSAGE_LENGTH = 10;
|
||||
|
||||
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}...` : "Ваш комментарий... *"}
|
||||
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.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>
|
||||
);
|
||||
}
|
||||
80
frontend/src/components/single-post/CommentLock.tsx
Normal file
80
frontend/src/components/single-post/CommentLock.tsx
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
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>
|
||||
);
|
||||
}
|
||||
422
frontend/src/components/single-post/Comments.tsx
Normal file
422
frontend/src/components/single-post/Comments.tsx
Normal file
|
|
@ -0,0 +1,422 @@
|
|||
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;
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: 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);
|
||||
|
||||
onMount(async () => {
|
||||
console.log("[Comments] Начало проверки авторизации...");
|
||||
try {
|
||||
const response = await fetch("/api/auth/me", {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
console.log("[Comments] Ответ API:", response.status);
|
||||
const data = await response.json();
|
||||
console.log("[Comments] Данные авторизации:", data);
|
||||
|
||||
if (data.authenticated && data.user) {
|
||||
console.log("[Comments] Пользователь авторизован:", data.user);
|
||||
setIsAuthenticated(true);
|
||||
setCurrentUser({
|
||||
name: data.user.name || "Пользователь",
|
||||
email: data.user.email,
|
||||
avatar: data.user.avatar,
|
||||
});
|
||||
} else {
|
||||
console.log("[Comments] Пользователь НЕ авторизован");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[Comments] Ошибка проверки авторизации:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
console.log(
|
||||
"[Comments] Загрузка завершена, isAuthenticated:",
|
||||
isAuthenticated()
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
console.log("[Comments] Загружены комментарии:", data);
|
||||
|
||||
// Сохраняем авторов комментариев для проверки
|
||||
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");
|
||||
}
|
||||
|
||||
const newComment = await response.json();
|
||||
console.log("[Comments] Комментарий создан:", newComment);
|
||||
|
||||
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: "Ответ успешно отправлен!" });
|
||||
console.log("[Comments] Ответ создан");
|
||||
await loadComments();
|
||||
setReplyTo(null);
|
||||
} catch (error) {
|
||||
console.error("[Comments] Ошибка создания ответа:", error);
|
||||
showToast({ type: "error", message: "Не удалось создать ответ. Попробуйте позже." });
|
||||
}
|
||||
};
|
||||
|
||||
const handleReplyClick = (commentId: string) => {
|
||||
// Получаем ID текущего пользователя из API авторизации
|
||||
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 (
|
||||
<>
|
||||
{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?.name || "Аноним"}
|
||||
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?.name || "Аноним"}
|
||||
</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 animate-slide-in">
|
||||
⚠️ Нельзя ответить на свой комментарий
|
||||
</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?.name || "Аноним"}
|
||||
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?.name || "Аноним"}
|
||||
</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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
120
frontend/src/components/single-post/NumberedContent.astro
Normal file
120
frontend/src/components/single-post/NumberedContent.astro
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
---
|
||||
export interface Props {
|
||||
tableOfContents?: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
const { tableOfContents = [] } = Astro.props;
|
||||
|
||||
// Создаем Map id -> номер
|
||||
const idToNumber = new Map();
|
||||
tableOfContents.forEach((item, index) => {
|
||||
idToNumber.set(item.id, index + 1);
|
||||
});
|
||||
---
|
||||
|
||||
<div class="numbered-content">
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.numbered-content {
|
||||
color: #111827;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.numbered-content :global(h2) {
|
||||
font-size: 1.875rem;
|
||||
font-weight: 700;
|
||||
color: #111827;
|
||||
margin-top: 2.5rem;
|
||||
margin-bottom: 1.25rem;
|
||||
line-height: 1.3;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
/* Нумерация через CSS счетчик */
|
||||
.numbered-content {
|
||||
counter-reset: section;
|
||||
}
|
||||
|
||||
.numbered-content :global(h2) {
|
||||
counter-increment: section;
|
||||
}
|
||||
|
||||
.numbered-content :global(h2)::before {
|
||||
content: counter(section);
|
||||
flex-shrink: 0;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
background: linear-gradient(135deg, #3b82f6, #2563eb);
|
||||
color: white;
|
||||
border-radius: 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.numbered-content :global(h3) {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
margin-top: 2rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.numbered-content :global(p) {
|
||||
color: #374151;
|
||||
margin-bottom: 1.25rem;
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.numbered-content :global(ul),
|
||||
.numbered-content :global(ol) {
|
||||
padding-left: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.numbered-content :global(ul) {
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.numbered-content :global(ol) {
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.numbered-content :global(li) {
|
||||
color: #374151;
|
||||
margin-bottom: 0.75rem;
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.numbered-content :global(a) {
|
||||
color: #2563eb;
|
||||
text-decoration: none;
|
||||
border-bottom: 1px solid #2563eb;
|
||||
}
|
||||
|
||||
.numbered-content :global(a:hover) {
|
||||
color: #1d4ed8;
|
||||
border-bottom-width: 2px;
|
||||
}
|
||||
|
||||
.numbered-content :global(strong) {
|
||||
color: #111827;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.numbered-content :global(h2 span[id]),
|
||||
.numbered-content :global(h3 span[id]) {
|
||||
scroll-margin-top: 100px;
|
||||
}
|
||||
</style>
|
||||
152
frontend/src/components/single-post/RelatedPosts.astro
Normal file
152
frontend/src/components/single-post/RelatedPosts.astro
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
---
|
||||
import { MONTHS } from "@lib/constants";
|
||||
|
||||
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
|
||||
|
||||
export interface Props {
|
||||
currentPostId?: string;
|
||||
currentPostSlug?: string;
|
||||
}
|
||||
|
||||
const { currentPostId, currentPostSlug } = Astro.props;
|
||||
|
||||
interface PostRecord {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
excerpt: string;
|
||||
image?: string;
|
||||
tags?: string;
|
||||
created: string;
|
||||
}
|
||||
|
||||
interface PocketBaseResponse {
|
||||
items: PostRecord[];
|
||||
}
|
||||
|
||||
// Получаем похожие посты (исключая текущий)
|
||||
let relatedPosts: PostRecord[] = [];
|
||||
|
||||
try {
|
||||
const filter = currentPostId ? `id!="${currentPostId}"` : "";
|
||||
const response = await fetch(
|
||||
`${POCKETBASE_URL}/api/collections/posts/records?filter=${encodeURIComponent(filter)}&perPage=3`
|
||||
);
|
||||
const data: PocketBaseResponse = await response.json();
|
||||
|
||||
if (data.items) {
|
||||
relatedPosts = data.items;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching related posts:", error);
|
||||
}
|
||||
|
||||
// Форматируем дату
|
||||
function formatDate(dateString: string) {
|
||||
const date = new Date(dateString);
|
||||
return `${date.getDate()} ${MONTHS[date.getMonth()]} ${date.getFullYear()}`;
|
||||
}
|
||||
|
||||
// Парсим tags
|
||||
function parseTags(tagsString?: string): string {
|
||||
if (!tagsString) return "НОВОСТИ";
|
||||
try {
|
||||
const tags = typeof tagsString === "string" ? JSON.parse(tagsString) : tagsString;
|
||||
return Array.isArray(tags) && tags.length > 0 ? tags[0].toUpperCase() : "НОВОСТИ";
|
||||
} catch {
|
||||
return "НОВОСТИ";
|
||||
}
|
||||
}
|
||||
---
|
||||
|
||||
<section
|
||||
class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 border-t border-gray-200"
|
||||
>
|
||||
{/* Заголовок */}
|
||||
<div class="flex items-center justify-between mb-8">
|
||||
<h2 class="text-2xl font-bold text-gray-900">Похожие публикации</h2>
|
||||
<a
|
||||
href="/blog"
|
||||
class="text-blue-600 hover:text-blue-800 font-medium text-sm flex items-center gap-1 transition-colors group"
|
||||
>
|
||||
Все статьи
|
||||
<svg
|
||||
class="w-4 h-4 transition-transform group-hover:translate-x-1"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M9 5l7 7-7 7"></path>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Сетка карточек */}
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{relatedPosts && relatedPosts.length > 0 ? (
|
||||
relatedPosts.map((post) => {
|
||||
const imageUrl = post.image
|
||||
? `${POCKETBASE_URL}/api/files/posts/${post.id}/${post.image}`
|
||||
: "https://images.unsplash.com/photo-1589829085413-56de8ae18c73?q=80&w=800&auto=format&fit=crop";
|
||||
|
||||
return (
|
||||
<article class="group bg-white rounded-2xl overflow-hidden shadow-sm border border-gray-100 hover:shadow-lg transition-all duration-300">
|
||||
{/* Изображение */}
|
||||
<a
|
||||
href={`/blog/${post.slug}`}
|
||||
class="block relative overflow-hidden aspect-video"
|
||||
>
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={post.title}
|
||||
class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
|
||||
/>
|
||||
<div class="absolute inset-0 bg-gradient-to-t from-black/30 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
|
||||
</a>
|
||||
|
||||
{/* Контент */}
|
||||
<div class="p-6">
|
||||
<span class="inline-block px-3 py-1 bg-blue-50 text-blue-600 text-xs font-medium rounded-full mb-3">
|
||||
{parseTags(post.tags)}
|
||||
</span>
|
||||
|
||||
<h3 class="text-lg font-bold text-gray-900 mb-3 line-clamp-2 group-hover:text-blue-600 transition-colors">
|
||||
<a href={`/blog/${post.slug}`}>{post.title}</a>
|
||||
</h3>
|
||||
|
||||
<p class="text-gray-600 text-sm line-clamp-3 mb-4 leading-relaxed">
|
||||
{post.excerpt}
|
||||
</p>
|
||||
|
||||
<a
|
||||
href={`/blog/${post.slug}`}
|
||||
class="inline-flex items-center gap-2 text-blue-600 font-medium text-sm hover:text-blue-800 transition-colors group/link"
|
||||
>
|
||||
Читать далее
|
||||
<svg
|
||||
class="w-4 h-4 transition-transform group-hover/link:translate-x-1"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M17 8l4 4m0 0l-4 4m4-4H3"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<p class="col-span-full text-center text-gray-500 py-8">Нет связанных публикаций</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
Loading…
Add table
Add a link
Reference in a new issue