Новое измнений в код

This commit is contained in:
Web-serfer 2026-03-31 18:45:18 +05:00
parent 735146fbfb
commit aa40fac43b
4 changed files with 337 additions and 274 deletions

View file

@ -5,7 +5,25 @@ import { CONTACT_CONSTANTS } from '@constants/constants.ts';
const dynamicStats = getDynamicStats(); const dynamicStats = getDynamicStats();
const yearsOfPractice = getYearsOfPractice(); const yearsOfPractice = getYearsOfPractice();
const achievements = [ // Отдельный тип для числовых статов (исключаем "24/7")
interface NumericStat {
number: number;
suffix: string;
text: string;
type: 'years' | 'cases' | 'clients';
icon: 'calendar' | 'briefcase' | 'users';
}
// Специальный тип для support
interface SupportStat {
number: "24/7";
suffix: '';
text: 'На связи';
type: 'support';
icon: 'clock';
}
const numericAchievements: NumericStat[] = [
{ {
number: yearsOfPractice, number: yearsOfPractice,
suffix: '', suffix: '',
@ -26,15 +44,16 @@ const achievements = [
text: 'довольных клиентов', text: 'довольных клиентов',
type: 'clients', type: 'clients',
icon: 'users' icon: 'users'
},
{
number: "24/7",
suffix: '',
text: 'На связи',
type: 'support',
icon: 'clock'
} }
] as const; ];
const supportStat: SupportStat = {
number: "24/7",
suffix: '',
text: 'На связи',
type: 'support',
icon: 'clock'
};
const iconPaths = { const iconPaths = {
calendar: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z", calendar: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z",
@ -43,16 +62,17 @@ const iconPaths = {
clock: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" clock: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
} as const; } as const;
type StatType = typeof achievements[number]['type']; const getStatText = (stat: NumericStat | SupportStat): string => {
if (stat.type === 'years') {
const getStatText = (stat: typeof achievements[number]): string => { return `${stat.number} ${getYearDeclension(stat.number)} практики`;
const texts: Record<StatType, string> = { }
years: `${stat.number} ${getYearDeclension(stat.number)} практики`, if (stat.type === 'cases') {
cases: 'Успешных дел', return 'Успешных дел';
clients: `${stat.number} ${getClientDeclension(stat.number)}`, }
support: 'Поддержка клиентов' if (stat.type === 'clients') {
}; return `${stat.number} ${getClientDeclension(stat.number as number)}`;
return texts[stat.type]; }
return 'Поддержка клиентов';
}; };
--- ---
@ -68,38 +88,51 @@ const getStatText = (stat: typeof achievements[number]): string => {
<!-- Сетка достижений --> <!-- Сетка достижений -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-6 mb-16"> <div class="grid grid-cols-2 lg:grid-cols-4 gap-6 mb-16">
{achievements.map((stat) => ( {numericAchievements.map((stat) => (
<div class="group bg-white/80 backdrop-blur-xl rounded-2xl p-6 md:p-8 shadow-lg border border-white/50 hover:shadow-2xl hover:shadow-[var(--color-blue-primary)]/10 hover:-translate-y-1 transition-all duration-500 text-center relative overflow-hidden"> <div class="group bg-white/80 backdrop-blur-xl rounded-2xl p-6 md:p-8 shadow-lg border border-white/50 hover:shadow-2xl hover:shadow-[var(--color-blue-primary)]/10 hover:-translate-y-1 transition-all duration-500 text-center relative overflow-hidden">
<!-- Декоративный фон --> <div class="absolute inset-0 bg-gradient-to-br from-[var(--color-blue-primary)]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
<div class="absolute inset-0 bg-gradient-to-br from-[var(--color-blue-primary)]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
<div class="relative z-10"> <div class="relative z-10">
<!-- Иконка --> <div class="w-12 h-12 mx-auto bg-[var(--color-blue-primary)]/10 rounded-xl flex items-center justify-center mb-4 group-hover:bg-[var(--color-blue-primary)] transition-colors duration-300">
<div class="w-12 h-12 mx-auto bg-[var(--color-blue-primary)]/10 rounded-xl flex items-center justify-center mb-4 group-hover:bg-[var(--color-blue-primary)] transition-colors duration-300"> <svg class="w-6 h-6 text-[var(--color-blue-primary)] group-hover:text-white transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg class="w-6 h-6 text-[var(--color-blue-primary)] group-hover:text-white transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d={iconPaths[stat.icon]}/>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d={iconPaths[stat.icon]}/> </svg>
</svg> </div>
</div>
<!-- Число --> <div class="flex items-baseline justify-center gap-1 mb-2">
<div class="flex items-baseline justify-center gap-1 mb-2"> <span class="stat-counter text-4xl md:text-5xl font-extrabold text-gray-900" data-target={stat.number}>
{stat.type !== 'support' ? ( 0
<span class="stat-counter text-4xl md:text-5xl font-extrabold text-gray-900" data-target={stat.number}> </span>
0 <span class="text-2xl font-bold text-[var(--color-blue-primary)]">{stat.suffix}</span>
</span> </div>
) : (
<span class="text-3xl md:text-4xl font-extrabold text-[var(--color-blue-primary)]">{stat.number}</span>
)}
<span class="text-2xl font-bold text-[var(--color-blue-primary)]">{stat.suffix}</span>
</div>
<!-- Текст --> <span class="text-xs md:text-sm font-bold text-gray-500 uppercase tracking-wider">
<span class="text-xs md:text-sm font-bold text-gray-500 uppercase tracking-wider">
{getStatText(stat)} {getStatText(stat)}
</span> </span>
</div>
</div> </div>
</div>
))} ))}
<!-- Support статик -->
<div class="group bg-white/80 backdrop-blur-xl rounded-2xl p-6 md:p-8 shadow-lg border border-white/50 hover:shadow-2xl hover:shadow-[var(--color-blue-primary)]/10 hover:-translate-y-1 transition-all duration-500 text-center relative overflow-hidden">
<div class="absolute inset-0 bg-gradient-to-br from-[var(--color-blue-primary)]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
<div class="relative z-10">
<div class="w-12 h-12 mx-auto bg-[var(--color-blue-primary)]/10 rounded-xl flex items-center justify-center mb-4 group-hover:bg-[var(--color-blue-primary)] transition-colors duration-300">
<svg class="w-6 h-6 text-[var(--color-blue-primary)] group-hover:text-white transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d={iconPaths[supportStat.icon]}/>
</svg>
</div>
<div class="flex items-baseline justify-center gap-1 mb-2">
<span class="text-3xl md:text-4xl font-extrabold text-[var(--color-blue-primary)]">{supportStat.number}</span>
</div>
<span class="text-xs md:text-sm font-bold text-gray-500 uppercase tracking-wider">
{getStatText(supportStat)}
</span>
</div>
</div>
</div> </div>
<!-- CTA Блок --> <!-- CTA Блок -->
@ -112,8 +145,8 @@ const getStatText = (stat: typeof achievements[number]): string => {
Получите профессиональную консультацию адвоката уже сегодня Получите профессиональную консультацию адвоката уже сегодня
</p> </p>
<button <button
data-consultation-modal data-consultation-modal
class="inline-block px-8 py-4 bg-white text-[var(--color-blue-primary)] font-bold rounded-xl hover:bg-gray-100 hover:scale-105 hover:shadow-xl transition-all duration-300 shadow-lg cursor-pointer" class="inline-block px-8 py-4 bg-white text-[var(--color-blue-primary)] font-bold rounded-xl hover:bg-gray-100 hover:scale-105 hover:shadow-xl transition-all duration-300 shadow-lg cursor-pointer"
> >
Получить консультацию Получить консультацию
</button> </button>
@ -133,7 +166,7 @@ const getStatText = (stat: typeof achievements[number]): string => {
entries.forEach(entry => { entries.forEach(entry => {
if (!entry.isIntersecting) return; if (!entry.isIntersecting) return;
const counter = entry.target; const counter = entry.target as HTMLElement; // <-- Исправление: явное приведение к HTMLElement
const target = parseInt(counter.dataset.target || '0', 10); const target = parseInt(counter.dataset.target || '0', 10);
let startTime: number | null = null; let startTime: number | null = null;
@ -141,7 +174,7 @@ const getStatText = (stat: typeof achievements[number]): string => {
if (!startTime) startTime = timestamp; if (!startTime) startTime = timestamp;
const progress = Math.min((timestamp - startTime) / speed, 1); const progress = Math.min((timestamp - startTime) / speed, 1);
const ease = 1 - Math.pow(1 - progress, 3); const ease = 1 - Math.pow(1 - progress, 3);
counter.textContent = Math.floor(ease * target).toString(); counter.textContent = Math.floor(ease * target).toString();
if (progress < 1) { if (progress < 1) {
@ -164,10 +197,7 @@ const getStatText = (stat: typeof achievements[number]): string => {
counters.forEach(counter => observer.observe(counter)); counters.forEach(counter => observer.observe(counter));
}; };
// Запускаем анимацию
initStatsAnimation(); initStatsAnimation();
// Для Astro View Transitions
document.addEventListener('astro:after-swap', initStatsAnimation); document.addEventListener('astro:after-swap', initStatsAnimation);
document.addEventListener('astro:page-load', initStatsAnimation); document.addEventListener('astro:page-load', initStatsAnimation);
</script> </script>

View file

@ -27,6 +27,12 @@ interface ApiComment {
}; };
} }
// Тип для toast-уведомлений
interface ToastMessage {
type: "success" | "error";
message: string;
}
export default function Comments(props: CommentsProps) { export default function Comments(props: CommentsProps) {
const [isAuthenticated, setIsAuthenticated] = createSignal(false); const [isAuthenticated, setIsAuthenticated] = createSignal(false);
const [currentUser, setCurrentUser] = createSignal<{ const [currentUser, setCurrentUser] = createSignal<{
@ -39,6 +45,15 @@ export default function Comments(props: CommentsProps) {
const [replyTo, setReplyTo] = createSignal<string | null>(null); const [replyTo, setReplyTo] = createSignal<string | null>(null);
const [commentAuthors, setCommentAuthors] = createSignal<Record<string, string>>({}); const [commentAuthors, setCommentAuthors] = createSignal<Record<string, string>>({});
const [toastVisible, setToastVisible] = createSignal<string | null>(null); const [toastVisible, setToastVisible] = createSignal<string | null>(null);
// Добавляем сигнал для toast-уведомлений
const [toast, setToast] = createSignal<ToastMessage | null>(null);
// Функция показа toast-уведомлений
const showToast = (message: ToastMessage): void => {
setToast(message);
// Автоматически скрываем через 3 секунды
setTimeout(() => setToast(null), 3000);
};
onMount(async () => { onMount(async () => {
console.log("[Comments] Начало проверки авторизации..."); console.log("[Comments] Начало проверки авторизации...");
@ -68,8 +83,8 @@ export default function Comments(props: CommentsProps) {
} finally { } finally {
setIsLoading(false); setIsLoading(false);
console.log( console.log(
"[Comments] Загрузка завершена, isAuthenticated:", "[Comments] Загрузка завершена, isAuthenticated:",
isAuthenticated() isAuthenticated()
); );
} }
}); });
@ -77,11 +92,11 @@ export default function Comments(props: CommentsProps) {
const loadComments = async () => { const loadComments = async () => {
try { try {
const response = await fetch( const response = await fetch(
`/api/comments?post_slug=${encodeURIComponent(props.postSlug)}&parent=null`, `/api/comments?post_slug=${encodeURIComponent(props.postSlug)}&parent=null`,
{ {
method: "GET", method: "GET",
credentials: "include", credentials: "include",
} }
); );
if (!response.ok) { if (!response.ok) {
@ -101,20 +116,20 @@ export default function Comments(props: CommentsProps) {
setCommentAuthors(authors); setCommentAuthors(authors);
const commentsWithReplies: CommentWithReplies[] = await Promise.all( const commentsWithReplies: CommentWithReplies[] = await Promise.all(
data.items.map(async (comment: ApiComment) => { data.items.map(async (comment: ApiComment) => {
const repliesResponse = await fetch( const repliesResponse = await fetch(
`/api/comments?post_slug=${encodeURIComponent(props.postSlug)}&parent=${comment.id}`, `/api/comments?post_slug=${encodeURIComponent(props.postSlug)}&parent=${comment.id}`,
{ {
method: "GET", method: "GET",
credentials: "include", credentials: "include",
} }
); );
const repliesData = await repliesResponse.json(); const repliesData = await repliesResponse.json();
return { return {
...comment, ...comment,
replies: repliesData.items || [], replies: repliesData.items || [],
}; };
}) })
); );
setComments(commentsWithReplies); setComments(commentsWithReplies);
@ -157,8 +172,8 @@ export default function Comments(props: CommentsProps) {
}; };
const handleReply = async ( const handleReply = async (
commentId: string, commentId: string,
data: { content: string } data: { content: string }
) => { ) => {
try { try {
const response = await fetch("/api/comments", { const response = await fetch("/api/comments", {
@ -228,22 +243,22 @@ export default function Comments(props: CommentsProps) {
const sizeClasses = { sm: "w-8 h-8 text-sm", md: "w-12 h-12 text-lg" }; const sizeClasses = { sm: "w-8 h-8 text-sm", md: "w-12 h-12 text-lg" };
return ( return (
<Show <Show
when={props.avatar} when={props.avatar}
fallback={ fallback={
<div <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`} 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)} {props.author.charAt(0)}
</div> </div>
} }
> >
<img <img
src={props.avatar} src={props.avatar}
alt={props.author} alt={props.author}
class={`${sizeClasses[size]} rounded-full object-cover shrink-0`} class={`${sizeClasses[size]} rounded-full object-cover shrink-0`}
/> />
</Show> </Show>
); );
}; };
@ -259,164 +274,179 @@ export default function Comments(props: CommentsProps) {
}; };
return ( return (
<> <>
{isLoading() ? ( {/* Глобальное toast-уведомление */}
<div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200"> <Show when={toast()}>
<div class="flex items-center gap-3 mb-8"> {(t) => (
<h3 class="text-2xl font-bold text-gray-900">Комментарии</h3> <div
<span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full"> 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 0
</span> </span>
</div> </div>
<div class="text-center py-12"> <div class="text-center py-12">
<div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div> <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
<p class="mt-4 text-gray-600">Загрузка...</p> <p class="mt-4 text-gray-600">Загрузка...</p>
</div> </div>
</div> </div>
) : ( ) : (
<Show when={isAuthenticated()} fallback={<CommentLock />}> <Show when={isAuthenticated()} fallback={<CommentLock />}>
<div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200"> <div class="max-w-4xl mx-auto mt-12 pt-8 border-t border-gray-200">
<div class="flex items-center gap-3 mb-8"> <div class="flex items-center gap-3 mb-8">
<h3 class="text-2xl font-bold text-gray-900">Комментарии</h3> <h3 class="text-2xl font-bold text-gray-900">Комментарии</h3>
<span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full"> <span class="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">
{comments().length} {comments().length}
</span> </span>
</div>
<Show
when={comments().length > 0}
fallback={
<div class="text-center py-12 text-gray-500">
<p>Пока нет комментариев. Будьте первым!</p>
</div> </div>
}
> <Show
<div class="space-y-6 mb-10"> when={comments().length > 0}
<For each={comments()}> fallback={
{(comment) => ( <div class="text-center py-12 text-gray-500">
<div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100"> <p>Пока нет комментариев. Будьте первым!</p>
<div class="flex items-start gap-4"> </div>
<Avatar }
author={comment.expand?.user?.name || "Аноним"} >
avatar={comment.expand?.user?.avatar} <div class="space-y-6 mb-10">
/> <For each={comments()}>
<div class="flex-1 min-w-0"> {(comment) => (
<div class="flex items-center gap-2 mb-2 flex-wrap"> <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"> <span class="font-semibold text-gray-900">
{comment.expand?.user?.name || "Аноним"} {comment.expand?.user?.name || "Аноним"}
</span> </span>
<Show when={comment.is_verified}> <Show when={comment.is_verified}>
<svg <svg
class="w-4 h-4 text-blue-500" 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" fill="currentColor"
viewBox="0 0 20 20" viewBox="0 0 20 20"
> >
<path <path
fill-rule="evenodd" 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" 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" clip-rule="evenodd"
/> />
</svg> </svg>
</Show> </Show>
<span class="text-xs text-gray-400 ml-auto"> <span class="text-sm text-gray-400 ml-auto">
{formatDate(reply.created)} {formatDate(comment.created)}
</span> </span>
</div> </div>
<p class="text-gray-700 text-sm leading-relaxed"> <p class="text-gray-700 leading-relaxed mb-3">
{reply.content} {comment.content}
</p> </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> </div>
)} </div>
</For>
</div> <Show when={replyTo() === comment.id}>
</Show> <div class="mt-4 ml-16 pl-4 border-l-2 border-blue-200">
</div> <CommentForm
)} isReply={true}
</For> 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> </div>
</Show> </Show>
)}
{/* Основная форма с передачей данных пользователя */} </>
<CommentForm onSubmit={handleNewComment} user={currentUser()} />
</div>
</Show>
)}
</>
); );
} }

View file

@ -1,4 +1,5 @@
import PocketBase from 'pocketbase'; import PocketBase from 'pocketbase';
import type { RecordModel } from 'pocketbase';
// URL PocketBase сервера // URL PocketBase сервера
const POCKETBASE_URL = import.meta.env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090'; const POCKETBASE_URL = import.meta.env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
@ -22,39 +23,35 @@ export function saveAuthToCookie(): void {
// Автоматическое восстановление сессии при загрузке страницы // Автоматическое восстановление сессии при загрузке страницы
if (typeof document !== 'undefined') { if (typeof document !== 'undefined') {
// Загружаем из cookies при инициализации
pb.authStore.loadFromCookie(document.cookie); pb.authStore.loadFromCookie(document.cookie);
// Подписываемся на изменения
pb.authStore.onChange(() => { pb.authStore.onChange(() => {
saveAuthToCookie(); saveAuthToCookie();
}, true); }, true);
} }
// Типы для аутентификации // Типы для аутентификации — расширяем RecordModel вместо дублирования
export interface AuthRecord { export interface AuthRecord extends RecordModel {
id: string;
email: string; email: string;
name: string; name: string;
avatar?: string; avatar?: string;
emailVisibility: boolean; emailVisibility: boolean;
verified: boolean; verified: boolean;
created: string;
updated: string;
} }
// Функция входа пользователя // Функция входа пользователя
export async function login(email: string, password: string): Promise<AuthRecord> { export async function login(email: string, password: string): Promise<AuthRecord> {
const authData = await pb.collection('users').authWithPassword(email, password); const authData = await pb.collection('users').authWithPassword(email, password);
// Теперь приведение типа безопасно, так как AuthRecord extends RecordModel
return authData.record as AuthRecord; return authData.record as AuthRecord;
} }
// Функция регистрации пользователя // Функция регистрации пользователя
export async function register( export async function register(
email: string, email: string,
password: string, password: string,
passwordConfirm: string, passwordConfirm: string,
name?: string name?: string
): Promise<AuthRecord> { ): Promise<AuthRecord> {
const record = await pb.collection('users').create({ const record = await pb.collection('users').create({
email, email,
@ -63,10 +60,9 @@ export async function register(
name: name || email.split('@')[0], name: name || email.split('@')[0],
emailVisibility: true, emailVisibility: true,
}); });
// Автоматический вход после регистрации
await login(email, password); await login(email, password);
return record as AuthRecord; return record as AuthRecord;
} }
@ -103,4 +99,4 @@ export async function resendVerificationEmail(email: string): Promise<void> {
// Функция подтверждения email // Функция подтверждения email
export async function confirmVerification(token: string): Promise<void> { export async function confirmVerification(token: string): Promise<void> {
await pb.collection('users').confirmVerification(token); await pb.collection('users').confirmVerification(token);
} }

View file

@ -9,10 +9,10 @@ const seo = {
--- ---
<Layout <Layout
title={seo.title} title={seo.title}
description={seo.description} description={seo.description}
pagePath="/auth/verify" pagePath="/auth/verify"
bodyClass="bg-[#F6F7FA]" bodyClass="bg-[#F6F7FA]"
> >
<div class="min-h-[calc(100vh-400px)] flex items-center justify-center py-12"> <div class="min-h-[calc(100vh-400px)] flex items-center justify-center py-12">
<div class="w-full max-w-md"> <div class="w-full max-w-md">
@ -39,7 +39,7 @@ const seo = {
<h2 class="text-xl font-semibold text-gray-900 mb-2"> <h2 class="text-xl font-semibold text-gray-900 mb-2">
Проверьте вашу почту Проверьте вашу почту
</h2> </h2>
<p class="text-gray-600 text-sm mb-6"> <p class="text-gray-600 text-sm mb-6">
Мы отправили ссылку для подтверждения на <span id="user-email" class="font-medium text-gold"></span> Мы отправили ссылку для подтверждения на <span id="user-email" class="font-medium text-gold"></span>
</p> </p>
@ -54,9 +54,9 @@ const seo = {
<!-- Кнопка повторной отправки --> <!-- Кнопка повторной отправки -->
<button <button
id="resend-btn" id="resend-btn"
type="button" type="button"
class="w-full bg-gold hover:bg-gold/90 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed" class="w-full bg-gold hover:bg-gold/90 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
> >
Отправить повторно Отправить повторно
</button> </button>
@ -71,7 +71,7 @@ const seo = {
Уже подтвердили email? <a Уже подтвердили email? <a
href="/auth/login" href="/auth/login"
class="text-gold hover:underline font-medium">Войти</a class="text-gold hover:underline font-medium">Войти</a
> >
</p> </p>
</div> </div>
</div> </div>
@ -82,19 +82,19 @@ const seo = {
<script> <script>
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const email = urlParams.get('email'); const email = urlParams.get('email');
const resendBtn = document.getElementById('resend-btn'); const resendBtn = document.getElementById('resend-btn') as HTMLButtonElement | null;
const timerText = document.getElementById('timer-text'); const timerText = document.getElementById('timer-text');
const countdownEl = document.getElementById('countdown'); const countdownEl = document.getElementById('countdown');
const userEmailEl = document.getElementById('user-email'); const userEmailEl = document.getElementById('user-email');
// Логирование // Логирование
function log(message, data) { function log(message: string, data?: unknown): void {
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
console.log(`[VERIFY PAGE][${timestamp}] ${message}`, data || ''); console.log(`[VERIFY PAGE][${timestamp}] ${message}`, data || '');
} }
// Отображение email // Отображение email
if (email) { if (email && userEmailEl) {
userEmailEl.textContent = email; userEmailEl.textContent = email;
log(`Страница загружена для email: ${email}`); log(`Страница загружена для email: ${email}`);
} else { } else {
@ -105,23 +105,29 @@ const seo = {
let countdown = 60; let countdown = 60;
let canResend = true; let canResend = true;
function startTimer() { function startTimer(): void {
if (!resendBtn || !timerText || !countdownEl) return;
canResend = false; canResend = false;
resendBtn.disabled = true; resendBtn.disabled = true;
timerText.classList.remove('hidden'); timerText.classList.remove('hidden');
countdown = 60; countdown = 60;
countdownEl.textContent = countdown; countdownEl.textContent = countdown.toString();
log('Таймер запущен'); log('Таймер запущен');
const interval = setInterval(() => { const interval = setInterval(() => {
if (!countdownEl) return;
countdown--; countdown--;
countdownEl.textContent = countdown; countdownEl.textContent = countdown.toString();
if (countdown <= 0) { if (countdown <= 0) {
clearInterval(interval); clearInterval(interval);
canResend = true; canResend = true;
resendBtn.disabled = false; if (resendBtn) {
timerText.classList.add('hidden'); resendBtn.disabled = false;
}
timerText?.classList.add('hidden');
log('Таймер завершен, кнопка активна'); log('Таймер завершен, кнопка активна');
} }
}, 1000); }, 1000);
@ -129,14 +135,14 @@ const seo = {
// Отправка повторного письма // Отправка повторного письма
resendBtn?.addEventListener('click', async () => { resendBtn?.addEventListener('click', async () => {
if (!canResend || !email) { if (!canResend || !email || !resendBtn) {
log(`Клик отклонен: canResend=${canResend}, email=${email}`); log(`Клик отклонен: canResend=${canResend}, email=${email}`);
return; return;
} }
log('Отправка повторного письма подтверждения...'); log('Отправка повторного письма подтверждения...');
const originalText = resendBtn.textContent; const originalText = resendBtn.textContent || '';
resendBtn.textContent = 'Отправка...'; resendBtn.textContent = 'Отправка...';
resendBtn.disabled = true; resendBtn.disabled = true;
@ -149,7 +155,7 @@ const seo = {
log(`Ответ сервера: ${response.status}`); log(`Ответ сервера: ${response.status}`);
const data = await response.json(); const data = await response.json() as { error?: string };
log('Данные ответа:', data); log('Данные ответа:', data);
if (!response.ok) { if (!response.ok) {
@ -159,12 +165,13 @@ const seo = {
alert('Письмо отправлено повторно! Проверьте вашу почту.'); alert('Письмо отправлено повторно! Проверьте вашу почту.');
log('✅ Письмо отправлено успешно'); log('✅ Письмо отправлено успешно');
startTimer(); startTimer();
} catch (error) { } catch (error: unknown) {
console.error('Ошибка:', error); console.error('Ошибка:', error);
log('❌ Ошибка отправки:', error.message); const errorMessage = error instanceof Error ? error.message : 'Неизвестная ошибка';
alert(error.message || 'Ошибка отправки письма'); log('❌ Ошибка отправки:', errorMessage);
alert(errorMessage || 'Ошибка отправки письма');
} finally { } finally {
if (canResend) { if (canResend && resendBtn) {
resendBtn.textContent = originalText; resendBtn.textContent = originalText;
} }
} }
@ -173,4 +180,4 @@ const seo = {
// Запуск таймера при загрузке // Запуск таймера при загрузке
log('Инициализация страницы'); log('Инициализация страницы');
startTimer(); startTimer();
</script> </script>