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

This commit is contained in:
Web-serfer 2026-04-21 20:04:13 +05:00
parent ddc0a26635
commit 189768971d
7 changed files with 549 additions and 589 deletions

View file

@ -1,55 +0,0 @@
---
// Компонент иконки поиска (лупа)
---
<button class="search-icon-btn" id="search-icon-btn" data-modal-target="search-modal" aria-label="Поиск статей">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
</svg>
</button>
<script>
(function() {
const btn = document.getElementById('search-icon-btn');
btn?.addEventListener('click', () => {
window.dispatchEvent(new CustomEvent('open-modal', {
detail: 'search-modal'
}));
});
})();
</script>
<style>
.search-icon-btn {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
color: #ffffff;
padding: 0.75rem;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}
.search-icon-btn:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(234, 194, 110, 0.5);
color: #eac26e;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(234, 194, 110, 0.2);
}
.search-icon-btn:active {
transform: translateY(0);
}
@media (max-width: 768px) {
.search-icon-btn {
padding: 0.6rem;
}
}
</style>

View file

@ -72,41 +72,28 @@ const formatDate = (dateStr: string) => {
<!-- Блок голосования -->
<div class="voting-section" data-review-id={reviewId}>
<p class="voting-question">Полезен ли этот отзыв?</p>
<div class="voting-buttons">
<button
type="button"
class="vote-btn vote-btn-up"
data-vote="like"
aria-label="Полезно"
>
<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="reaction-icon">
<path d="M7 10v12"></path>
<path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"></path>
</svg>
<span class="vote-label">Да</span>
</button>
<button
type="button"
class="vote-btn vote-btn-down"
data-vote="dislike"
aria-label="Бесполезно"
>
<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="reaction-icon">
<path d="M17 14V2"></path>
<path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"></path>
</svg>
<span class="vote-label">Нет</span>
</button>
</div>
<div class="voting-stats">
<span class="votes-count">
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 20 20" fill="currentColor">
<path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />
</svg>
<span class="votes-number">{votesCount}</span>
</span>
</div>
<button
type="button"
class="vote-btn vote-btn-up"
data-vote="likes"
aria-label="Полезно"
>
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 20 20" fill="currentColor">
<path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />
</svg>
<span class="votes-number">{votesCount}</span>
</button>
<button
type="button"
class="vote-btn vote-btn-down"
data-vote="dislikes"
aria-label="Бесполезно"
>
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 20 20" fill="currentColor">
<path d="M18 9.5a1.5 1.5 0 11-3 0v-6a1.5 1.5 0 013 0v6zM14 9.667v-5.43a2 2 0 00-1.106-1.79l-.05-.025A4 4 0 0011.057 2H5.64a2 2 0 00-1.962 1.608l-1.2 6A2 2 0 004.44 12H8v4a2 2 0 002 2 1 1 0 001-1v-.667a4 4 0 01.8-2.4l1.4-2.4a4 4 0 00.8-2.4z"/>
</svg>
<span class="votes-number dislikes-count">0</span>
</button>
</div>
</article>
@ -211,70 +198,43 @@ const formatDate = (dateStr: string) => {
.voting-section {
margin-top: auto;
padding-top: 1.5rem;
padding-top: 1.25rem;
border-top: 1px solid #e2e8f0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.voting-question {
color: #475569;
font-size: 0.875rem;
font-weight: 600;
margin: 0;
}
.voting-auth-note {
color: #dc2626 !important;
font-size: 0.7rem !important;
font-style: italic;
margin: 0;
}
.voting-buttons {
display: flex;
gap: 0.75rem;
align-items: center;
gap: 1rem;
justify-content: center;
}
.vote-btn {
display: inline-flex;
align-items: center;
gap: 0.375rem;
padding: 0.5rem 0.875rem;
border: 2px solid #e2e8f0;
gap: 0.5rem;
padding: 0.625rem 1rem;
border: 1px solid #e2e8f0;
border-radius: 0.5rem;
background: #ffffff;
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.875rem;
font-weight: 600;
font-weight: 500;
color: #64748b;
}
.vote-btn svg {
width: 1.25rem;
height: 1.25rem;
width: 1.125rem;
height: 1.125rem;
}
.reaction-icon {
width: 1.25rem;
height: 1.25rem;
.vote-btn:hover {
border-color: #1e3050;
color: #1e3050;
background: #f8fafc;
}
.vote-btn-up:hover,
.vote-btn-up.active {
border-color: #22c55e;
color: #22c55e;
background: rgba(34, 197, 94, 0.1);
}
.vote-btn-down:hover,
.vote-btn-down.active {
border-color: #ef4444;
color: #ef4444;
background: rgba(239, 68, 68, 0.1);
.vote-btn.active {
background: #1e3050;
border-color: #1e3050;
color: #ffffff;
}
.vote-btn:disabled {
@ -302,27 +262,6 @@ const formatDate = (dateStr: string) => {
}
}
.voting-stars {
display: flex;
align-items: center;
}
.voting-stats {
display: flex;
align-items: center;
gap: 1rem;
margin-top: 0.5rem;
}
.votes-count {
display: inline-flex;
align-items: center;
gap: 0.375rem;
color: #64748b;
font-size: 0.875rem;
font-weight: 500;
}
.icon {
width: 1.125rem;
height: 1.125rem;
@ -492,13 +431,12 @@ const formatDate = (dateStr: string) => {
return;
}
const data = await response.json();
buttons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const votesNumber = section.querySelector('.votes-number');
if (votesNumber && typeof data.likes === 'number') {
votesNumber.textContent = data.likes.toString();
const resData = await response.json();
const btnCountEl = btn.querySelector('.votes-number');
if (btnCountEl) {
const isLike = voteType === 'likes';
const newCount = isLike ? (resData.likes || 0) : (resData.dislikes || 0);
btnCountEl.textContent = String(newCount);
}
} catch (err) {
console.error('[ReviewCard] Vote failed:', err);
@ -541,17 +479,21 @@ const formatDate = (dateStr: string) => {
return;
}
if (!response.ok) {
if (!response.ok) {
const errorText = await response.text();
console.error('[Vote JS] Error:', errorText);
return;
}
const data = await response.json();
buttons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const votesNumber = section.querySelector('.votes-number');
if (votesNumber && typeof data.likes === 'number') {
votesNumber.textContent = data.likes.toString();
const resData = await response.json();
console.log('[Vote JS] Response:', resData);
const btnCountEl = btn.querySelector('.votes-number');
if (btnCountEl) {
const isLike = voteType === 'likes';
const newCount = isLike ? (resData.likes || 0) : (resData.dislikes || 0);
btnCountEl.textContent = String(newCount);
console.log('[Vote JS] Set count to:', newCount);
}
} catch (err) {
console.error('[ReviewCard] Vote failed:', err);

View file

@ -16,12 +16,6 @@ interface ReviewFormProps {
};
}
const EMOJIS = [
"👍", "👎", "❤️", "😊", "😂", "🎉", "🔥", "👏",
"😢", "😮", "😡", "🙏", "⭐", "💯", "❤️‍🔥", "🤔",
"👀", "💪", "🚀", "✨"
];
const DANGEROUS_PATTERNS = [
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
/javascript:/gi,
@ -34,7 +28,7 @@ const DANGEROUS_PATTERNS = [
/url\s*\(\s*['"]*\s*javascript:/gi,
];
const MAX_TEXT_LENGTH = 2000;
const MAX_TEXT_LENGTH = 500;
const MIN_TEXT_LENGTH = 50;
const MAX_NAME_LENGTH = 50;
const MAX_PROFESSION_LENGTH = 100;
@ -47,15 +41,23 @@ interface ValidationErrors {
text?: string;
}
const RATING_LABELS: Record<number, string> = {
1: "Плохо",
2: "Не очень",
3: "Нормально",
4: "Хорошо",
5: "Отлично",
};
export default function ReviewForm(props: ReviewFormProps) {
const [name, setName] = createSignal("");
const [surname, setSurname] = createSignal("");
const [profession, setProfession] = createSignal("");
const [rating, setRating] = createSignal(0);
const [hoverRating, setHoverRating] = createSignal(0);
const [text, setText] = createSignal("");
const [errors, setErrors] = createSignal<ValidationErrors>({});
const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({});
const [showEmojiPicker, setShowEmojiPicker] = createSignal(false);
createEffect(() => {
if (props.user?.name) {
@ -83,38 +85,38 @@ export default function ReviewForm(props: ReviewFormProps) {
const validateName = (value: string): string | undefined => {
const trimmed = value.trim();
if (!trimmed) return "Имя обязательно";
if (trimmed.length > MAX_NAME_LENGTH) return `Максимум ${MAX_NAME_LENGTH} символов`;
if (!trimmed) return "Введите имя";
if (trimmed.length > MAX_NAME_LENGTH) return `Макс. ${MAX_NAME_LENGTH} символов`;
return undefined;
};
const validateSurname = (value: string): string | undefined => {
const trimmed = value.trim();
if (!trimmed) return "Фамилия обязательна";
if (trimmed.length > MAX_NAME_LENGTH) return `Максимум ${MAX_NAME_LENGTH} символов`;
if (!trimmed) return "Введите фамилию";
if (trimmed.length > MAX_NAME_LENGTH) return `Макс. ${MAX_NAME_LENGTH} символов`;
return undefined;
};
const validateProfession = (value: string): string | undefined => {
const trimmed = value.trim();
if (!trimmed) return "Профессия обязательна";
if (trimmed.length > MAX_PROFESSION_LENGTH) return `Максимум ${MAX_PROFESSION_LENGTH} символов`;
if (!trimmed) return "Укажите профессию";
if (trimmed.length > MAX_PROFESSION_LENGTH) return `Макс. ${MAX_PROFESSION_LENGTH} символов`;
return undefined;
};
const validateRating = (value: number): string | undefined => {
if (!value || value < 1 || value > 5) return "Выберите оценку";
if (!value || value < 1 || value > 5) return "Поставьте оценку";
return undefined;
};
const validateText = (value: string): string | undefined => {
const trimmed = value.trim();
if (!trimmed) return "Текст отзыва обязателен";
if (!trimmed) return "Напишите отзыв";
if (trimmed.length < MIN_TEXT_LENGTH)
return `Минимум ${MIN_TEXT_LENGTH} символов`;
if (trimmed.length > MAX_TEXT_LENGTH)
return `Максимум ${MAX_TEXT_LENGTH} символов`;
if (containsDangerousContent(trimmed)) return "Обнаружен опасный контент";
return `Макс. ${MAX_TEXT_LENGTH} символов`;
if (containsDangerousContent(trimmed)) return "Недопустимый контент";
return undefined;
};
@ -138,11 +140,6 @@ export default function ReviewForm(props: ReviewFormProps) {
}
};
const addEmoji = (emoji: string) => {
setText((prev) => prev + emoji);
setShowEmojiPicker(false);
};
const validateForm = (): boolean => {
const newErrors: ValidationErrors = {
name: validateName(name()),
@ -187,7 +184,7 @@ export default function ReviewForm(props: ReviewFormProps) {
const handleBlur = (field: string) => {
setTouched((prev) => ({ ...prev, [field]: true }));
const fieldValidators: Record<string, () => string | undefined> = {
name: () => validateName(name()),
surname: () => validateSurname(surname()),
@ -203,21 +200,13 @@ export default function ReviewForm(props: ReviewFormProps) {
};
const isValid = () => {
return !errors().name && !errors().surname && !errors().profession &&
!errors().rating && !errors().text &&
name().trim() && surname().trim() && profession().trim() &&
return !errors().name && !errors().surname && !errors().profession &&
!errors().rating && !errors().text &&
name().trim() && surname().trim() && profession().trim() &&
rating() > 0 && text().trim();
};
const ratingOptions = [
{ value: 5, label: "5 — Отлично" },
{ value: 4, label: "4 — Хорошо" },
{ value: 3, label: "3 — Удовлетворительно" },
{ value: 2, label: "2 — Плохо" },
{ value: 1, label: "1 — Очень плохо" },
];
const getInputClass = (field: keyof ValidationErrors) => {
const getFieldClass = (field: keyof ValidationErrors) => {
const hasError = errors()[field] && touched()[field];
return `w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none ${
hasError
@ -226,172 +215,430 @@ export default function ReviewForm(props: ReviewFormProps) {
}`;
};
const displayRating = () => hoverRating() || rating();
return (
<form onSubmit={handleSubmit} class="review-form max-w-700px mx-auto flex flex-col gap-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="flex flex-col gap-1">
<label class="text-sm font-semibold text-gray-900">Имя *</label>
<input
type="text"
value={name()}
onInput={(e) => setName(e.currentTarget.value)}
onBlur={() => handleBlur("name")}
placeholder="Иван"
class={getInputClass("name")}
/>
<Show when={errors().name && touched().name}>
<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().name}
</p>
</Show>
<div class="review-form-wrapper">
<div class="review-form-card">
<div class="review-form-header">
<h3 class="review-form-title">Оставить отзыв</h3>
<p class="review-form-subtitle">Ваш опыт поможет другим клиентам</p>
</div>
<div class="flex flex-col gap-1">
<label class="text-sm font-semibold text-gray-900">Фамилия *</label>
<input
type="text"
value={surname()}
onInput={(e) => setSurname(e.currentTarget.value)}
onBlur={() => handleBlur("surname")}
placeholder="Иванов"
class={getInputClass("surname")}
/>
<Show when={errors().surname && touched().surname}>
<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().surname}
</p>
</Show>
</div>
</div>
<form onSubmit={handleSubmit} class="review-form">
<div class="form-section">
<div class="name-row">
<div class="field-group">
<label class="field-label">Имя</label>
<input
type="text"
value={name()}
onInput={(e) => setName(e.currentTarget.value)}
onBlur={() => handleBlur("name")}
placeholder="Иван"
class={getFieldClass("name")}
/>
<Show when={errors().name && touched().name}>
<p class="field-error">{errors().name}</p>
</Show>
</div>
<div class="field-group">
<label class="field-label">Фамилия</label>
<input
type="text"
value={surname()}
onInput={(e) => setSurname(e.currentTarget.value)}
onBlur={() => handleBlur("surname")}
placeholder="Иванов"
class={getFieldClass("surname")}
/>
<Show when={errors().surname && touched().surname}>
<p class="field-error">{errors().surname}</p>
</Show>
</div>
</div>
</div>
<div class="flex flex-col gap-1">
<label class="text-sm font-semibold text-gray-900">Профессия *</label>
<input
type="text"
value={profession()}
onInput={(e) => setProfession(e.currentTarget.value)}
onBlur={() => handleBlur("profession")}
placeholder="Например: Предприниматель, Врач, Инженер..."
class={getInputClass("profession")}
/>
<Show when={errors().profession && touched().profession}>
<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().profession}
</p>
</Show>
</div>
<div class="form-section">
<div class="field-group">
<label class="field-label">Профессия</label>
<input
type="text"
value={profession()}
onInput={(e) => setProfession(e.currentTarget.value)}
onBlur={() => handleBlur("profession")}
placeholder="Например: Водитель, Предприниматель..."
class={getFieldClass("profession")}
/>
<Show when={errors().profession && touched().profession}>
<p class="field-error">{errors().profession}</p>
</Show>
</div>
</div>
<div class="flex flex-col gap-1">
<label class="text-sm font-semibold text-gray-900">Оценка *</label>
<select
value={rating()}
onChange={(e) => setRating(parseInt(e.currentTarget.value))}
onBlur={() => handleBlur("rating")}
class={getInputClass("rating")}
>
<option value="">Выберите оценку</option>
<For each={ratingOptions}>
{(option) => (
<option value={option.value}>{option.label}</option>
)}
</For>
</select>
<Show when={errors().rating && touched().rating}>
<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().rating}
</p>
</Show>
</div>
<div class="flex flex-col gap-1">
<div class="flex justify-between items-center">
<label class="text-sm font-semibold text-gray-900">Ваш отзыв *</label>
<div class="relative">
<button
type="button"
onClick={() => setShowEmojiPicker(!showEmojiPicker())}
class="p-2 text-gray-400 hover:text-blue-600 transition-colors rounded-lg hover:bg-gray-100"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</button>
<Show when={showEmojiPicker()}>
<div class="absolute bottom-full right-0 mb-2 bg-white rounded-xl shadow-lg border border-gray-200 p-3 z-10 w-64">
<div class="grid grid-cols-5 gap-2">
<For each={EMOJIS}>
{(emoji) => (
<div class="form-section">
<div class="field-group">
<label class="field-label">Ваша оценка</label>
<div class="rating-stars-wrapper">
<div class="rating-stars">
<For each={[1, 2, 3, 4, 5]}>
{(star) => (
<button
type="button"
onClick={() => addEmoji(emoji)}
class="p-2 text-xl hover:bg-gray-100 rounded-lg transition-colors"
class={`star-btn ${star <= displayRating() ? "active" : ""}`}
onClick={() => {
setRating(star);
if (touched().rating) {
setErrors((prev) => ({ ...prev, rating: validateRating(star) }));
}
setTouched((prev) => ({ ...prev, rating: true }));
}}
onMouseEnter={() => setHoverRating(star)}
onMouseLeave={() => setHoverRating(0)}
aria-label={`Оценка ${star}`}
>
{emoji}
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
</svg>
</button>
)}
</For>
</div>
<Show when={rating() > 0}>
<span class="rating-label">{RATING_LABELS[rating()]}</span>
</Show>
</div>
</Show>
<Show when={errors().rating && touched().rating}>
<p class="field-error">{errors().rating}</p>
</Show>
</div>
</div>
</div>
<textarea
value={text()}
onInput={handleTextChange}
onBlur={() => handleBlur("text")}
placeholder="Расскажите о вашем опыте работы с нами..."
rows={5}
class={getInputClass("text")}
/>
<div class="flex justify-between items-center">
<Show when={errors().text && touched().text}>
<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().text}
</p>
</Show>
<p
class={`text-xs text-right ml-auto ${text().length > MAX_TEXT_LENGTH * 0.9 ? "text-orange-500" : "text-gray-400"}`}
<div class="form-section">
<div class="field-group">
<label class="field-label">Ваш отзыв</label>
<div class="review-textarea-wrapper">
<textarea
value={text()}
onInput={handleTextChange}
onBlur={() => handleBlur("text")}
placeholder="Расскажите о вашем опыте работы с нами..."
rows={5}
class={getFieldClass("text")}
/>
<div class="textarea-progress">
<div
class="progress-bar"
style={{ width: `${Math.min(100, (text().length / MIN_TEXT_LENGTH) * 100)}%` }}
/>
</div>
</div>
<div class="textarea-footer">
<div class="textarea-info">
<Show when={text().length > 0 && text().length < MIN_TEXT_LENGTH}>
<p class="min-chars-hint">
Ещё {MIN_TEXT_LENGTH - text().length} символов до отправки
</p>
</Show>
<Show when={text().length >= MIN_TEXT_LENGTH}>
<p class="text-ready-hint">Готово к отправке</p>
</Show>
</div>
<p
class={`char-count ${text().length > MAX_TEXT_LENGTH * 0.9 ? "warning" : ""}`}
>
{text().length}/{MAX_TEXT_LENGTH}
</p>
</div>
<div class="moderation-notice">
<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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
<span>Все отзывы проходят модерацию перед публикацией</span>
</div>
</div>
</div>
<button
type="submit"
disabled={!isValid()}
class="submit-btn"
>
{text().length}/{MAX_TEXT_LENGTH}
<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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
</svg>
Отправить отзыв
</button>
<p class="privacy-note">
Нажимая кнопку, вы соглашаетесь с{" "}
<a href="/privacy" class="privacy-link">политикой конфиденциальности</a>
</p>
</div>
</form>
</div>
<button
type="submit"
disabled={!isValid()}
class="px-8 py-3 bg-gradient-to-b from-blue-600 to-blue-800 hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-all flex items-center gap-2 hover:cursor-pointer group"
>
<svg
class="w-5 h-5 transition-transform duration-300 group-hover:rotate-90"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
</svg>
Отправить отзыв
</button>
<style>{`
.review-form-wrapper {
display: flex;
justify-content: center;
padding: 2rem 1rem;
}
<p class="text-xs text-gray-500 text-center">
Нажимая кнопку, вы соглашаетесь с{" "}
<a href="/privacy" class="text-blue-600 hover:underline">политикой конфиденциальности</a>
</p>
</form>
.review-form-card {
width: 100%;
max-width: 520px;
background: #ffffff;
border-radius: 20px;
border: 1px solid #e2e8f0;
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
overflow: hidden;
}
.review-form-header {
padding: 1.75rem 2rem;
background: linear-gradient(135deg, #1e3050 0%, #2d4a6f 100%);
text-align: center;
}
.review-form-title {
color: #ffffff;
font-size: 1.35rem;
font-weight: 700;
margin: 0 0 0.25rem 0;
}
.review-form-subtitle {
color: rgba(255, 255, 255, 0.7);
font-size: 0.9rem;
margin: 0;
}
.review-form {
padding: 1.5rem 2rem 2rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.form-section {
display: flex;
flex-direction: column;
}
.name-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
@media (max-width: 480px) {
.name-row {
grid-template-columns: 1fr;
}
}
.field-group {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.field-label {
font-size: 0.85rem;
font-weight: 600;
color: #1e3050;
}
.field-error {
font-size: 0.8rem;
color: #ef4444;
margin: 0;
display: flex;
align-items: center;
gap: 0.25rem;
}
.rating-stars-wrapper {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem 0;
}
.rating-stars {
display: flex;
gap: 0.35rem;
}
.star-btn {
background: none;
border: none;
padding: 0;
cursor: pointer;
color: #e2e8f0;
transition: all 0.2s ease;
transform-origin: center;
}
.star-btn:hover,
.star-btn.active {
color: #eac26e;
}
.star-btn:hover {
transform: scale(1.15);
}
.star-btn svg {
width: 28px;
height: 28px;
}
.rating-label {
font-size: 0.9rem;
font-weight: 600;
color: #1e3050;
}
.char-count {
font-size: 0.75rem;
color: #94a3b8;
margin: 0;
}
.char-count.warning {
color: #f59e0b;
}
.review-textarea-wrapper {
position: relative;
}
.review-textarea-wrapper textarea {
padding-bottom: 6px;
}
.textarea-progress {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 3px;
background: #e2e8f0;
border-radius: 0 0 12px 12px;
overflow: hidden;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #eac26e 0%, #ce9f40 100%);
transition: width 0.3s ease;
border-radius: 0 0 12px 12px;
}
.textarea-footer {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.35rem;
min-height: 1.2rem;
}
.textarea-info {
display: flex;
align-items: center;
}
.min-chars-hint {
font-size: 0.75rem;
color: #94a3b8;
margin: 0;
}
.text-ready-hint {
font-size: 0.75rem;
color: #22c55e;
margin: 0;
font-weight: 600;
}
.moderation-notice {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 0.75rem;
background: #f8fafc;
border-radius: 8px;
margin-top: 0.5rem;
border: 1px solid #e2e8f0;
}
.moderation-notice svg {
width: 14px;
height: 14px;
color: #64748b;
flex-shrink: 0;
}
.moderation-notice span {
font-size: 0.75rem;
color: #64748b;
}
.submit-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
width: 100%;
padding: 1rem 1.5rem;
background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%);
border: none;
border-radius: 12px;
color: #ffffff;
font-size: 1rem;
font-weight: 700;
cursor: pointer;
transition: all 0.3s ease;
margin-top: 0.5rem;
}
.submit-btn:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(234, 194, 110, 0.4);
}
.submit-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.privacy-note {
font-size: 0.75rem;
color: #94a3b8;
text-align: center;
margin: 0;
}
.privacy-link {
color: #2563eb;
text-decoration: none;
}
.privacy-link:hover {
text-decoration: underline;
}
@media (max-width: 480px) {
.review-form {
padding: 1.25rem 1.25rem 1.5rem;
}
.review-form-header {
padding: 1.5rem 1.25rem;
}
}
`}</style>
</div>
);
}

View file

@ -1,166 +0,0 @@
import { createSignal, For, Show, onMount, createMemo } from "solid-js";
import ReviewCard from "./ReviewCard.astro";
import type { Review } from "../../data/reviewsData";
interface ReviewRecord {
id: string;
name: string;
surname?: string;
profession?: string;
text: string;
rating: number;
status: string;
votesCount: number;
created: string;
expand?: {
user?: {
id: string;
name: string;
firstName?: string;
email: string;
avatar?: string;
};
};
}
interface ReviewsListProps {
initialReviews?: Review[];
}
const colors = [
"bg-blue-100 text-blue-600", "bg-teal-100 text-teal-600", "bg-orange-100 text-orange-600",
"bg-pink-100 text-pink-600", "bg-purple-100 text-purple-600", "bg-indigo-100 text-indigo-600",
"bg-green-100 text-green-600", "bg-yellow-100 text-yellow-600", "bg-red-100 text-red-600"
];
export default function ReviewsList(props: ReviewsListProps) {
const [isLoading, setIsLoading] = createSignal(true);
const [reviews, setReviews] = createSignal<ReviewRecord[]>([]);
const [error, setError] = createSignal<string | null>(null);
const loadReviews = async () => {
try {
setIsLoading(true);
const response = await fetch("/api/reviews", {
credentials: "include",
});
if (!response.ok) {
throw new Error("Failed to fetch reviews");
}
const data = await response.json();
setReviews(data.items || []);
} catch (err) {
console.error("[ReviewsList] Error:", err);
setError("Не удалось загрузить отзывы");
} finally {
setIsLoading(false);
}
};
onMount(() => {
loadReviews();
});
const formatDate = (dateStr: string) => {
const date = new Date(dateStr);
return date.toLocaleDateString("ru-RU", {
day: "numeric",
month: "long",
year: "numeric"
});
};
const getAvatarInfo = (name: string) => {
const initial = name.charAt(0).toUpperCase();
const color = colors[initial.charCodeAt(0) % colors.length];
return { initial, color };
};
const votingSummary = createMemo(() => {
const allReviews = reviews();
const totalReviews = allReviews.length;
const totalRating = allReviews.reduce((sum, r) => sum + r.rating, 0);
const averageRating = totalReviews > 0 ? parseFloat((totalRating / totalReviews).toFixed(1)) : 0;
const totalVotes = allReviews.reduce((sum, r) => sum + (r.votesCount || 0), 0);
const distribution = allReviews.reduce((acc, r) => {
acc[r.rating] = (acc[r.rating] || 0) + 1;
return acc;
}, {} as Record<number, number>);
return { averageRating, totalVotes, totalReviews, ratingDistribution: distribution };
});
return (
<>
<Show when={isLoading()}>
</Show>
<Show when={error()}>
<div class="text-center py-12 text-red-500">
<p>{error()}</p>
</div>
</Show>
<Show when={!isLoading() && !error()}>
{/* Статистика голосования - можно вынести в отдельный компонент */}
<Show when={reviews().length > 0}>
<div class="voting-summary mb-12 p-6 bg-white rounded-2xl border border-gray-100 shadow-sm">
<div class="flex items-center justify-between flex-wrap gap-4">
<div class="flex items-center gap-4">
<div class="text-5xl font-bold text-gray-900">{votingSummary().averageRating}</div>
<div>
<div class="flex gap-1 mb-1">
<For each={[1, 2, 3, 4, 5]}>
{(star) => (
<svg
class={`w-5 h-5 ${star <= Math.round(votingSummary().averageRating) ? "text-yellow-400" : "text-gray-300"}`}
fill="currentColor"
viewBox="0 0 20 20"
>
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
</svg>
)}
</For>
</div>
<p class="text-sm text-gray-500">{votingSummary().totalReviews} отзывов</p>
</div>
</div>
<div class="text-right">
<p class="text-sm text-gray-500">{votingSummary().totalVotes} голосов</p>
</div>
</div>
</div>
</Show>
{/* Сетка отзывов */}
<Show when={reviews().length > 0} fallback={
<div class="text-center py-12 text-gray-500">
<p>Пока нет отзывов. Будьте первым!</p>
</div>
}>
<div class="reviews-grid">
<For each={reviews()}>
{(review) => {
const avatarInfo = getAvatarInfo(review.name);
return (
<ReviewCard
name={`${review.name} ${review.surname || ""}`.trim()}
profession={review.profession || "Клиент"}
text={review.text}
rating={review.rating}
initial={avatarInfo.initial}
color={avatarInfo.color}
date={formatDate(review.created)}
votesCount={review.votesCount || 0}
isHelpful={false}
/>
);
}}
</For>
</div>
</Show>
</Show>
</>
);
}

View file

@ -1,6 +1,8 @@
import type { APIRoute } from "astro";
import { sendEmail } from "../../../lib/email";
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
const ADMIN_EMAIL = import.meta.env.PB_ADMIN_EMAIL || "redibedi2019@gmail.com";
export const POST: APIRoute = async ({ request, cookies }) => {
const pbAuthCookie = cookies.get("pb_auth")?.value;
@ -75,7 +77,7 @@ export const POST: APIRoute = async ({ request, cookies }) => {
profession,
rating,
text,
status: "pending",
status: "published",
votesCount: 0,
user: userId,
}),
@ -91,6 +93,32 @@ export const POST: APIRoute = async ({ request, cookies }) => {
});
}
try {
await sendEmail({
to: ADMIN_EMAIL,
subject: `Новый отзыв на сайте: ${rating} звёзд от ${name} ${surname}`,
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #1e3050;">Новый отзыв на сайте</h2>
<div style="background: #f8fafc; padding: 20px; border-radius: 12px; margin: 20px 0;">
<p><strong>Автор:</strong> ${name} ${surname}</p>
<p><strong>Профессия:</strong> ${profession}</p>
<p><strong>Оценка:</strong> ${"⭐".repeat(rating)} (${rating}/5)</p>
<p><strong>Дата:</strong> ${new Date().toLocaleDateString("ru-RU")}</p>
</div>
<div style="background: #ffffff; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px;">
<p style="margin: 0; line-height: 1.6;">${text}</p>
</div>
<p style="color: #64748b; font-size: 14px; margin-top: 20px;">
Это письмо отправлено автоматически с сайта avtourist-surgut.ru
</p>
</div>
`,
});
} catch (emailError) {
console.error("[Reviews API] Email error:", emailError);
}
return new Response(JSON.stringify(data), {
status: 201,
headers: { "Content-Type": "application/json" },

View file

@ -2,7 +2,7 @@ import type { APIRoute } from 'astro';
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/;
const PB_ID_REGEX = /^[a-z0-9]{15}$/;
export const POST: APIRoute = async ({ request, cookies }) => {
try {
@ -28,7 +28,7 @@ export const POST: APIRoute = async ({ request, cookies }) => {
if (!authResponse.ok) {
return new Response(
JSON.stringify({ error: 'Недействительная сессия' }),
JSON.stringify({ error: 'Нед<EFBFBD><EFBFBD>йствительная сессия' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
);
}
@ -36,9 +36,9 @@ export const POST: APIRoute = async ({ request, cookies }) => {
const authData = await authResponse.json();
const userId = authData.record?.id;
if (!userId || !POCKETBASE_ID_REGEX.test(userId)) {
if (!userId || !PB_ID_REGEX.test(userId)) {
return new Response(
JSON.stringify({ error: 'Ошибка идентификации пользователя' }),
JSON.stringify({ error: 'Ошибка идентификации' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
@ -46,14 +46,14 @@ export const POST: APIRoute = async ({ request, cookies }) => {
const body = await request.json();
const { review_id, vote_type } = body;
if (!review_id || !POCKETBASE_ID_REGEX.test(review_id)) {
if (!review_id || !PB_ID_REGEX.test(review_id)) {
return new Response(
JSON.stringify({ error: 'Некорректный review_id' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
if (!vote_type || !['like', 'dislike'].includes(vote_type)) {
if (!vote_type || !['likes', 'dislikes'].includes(vote_type)) {
return new Response(
JSON.stringify({ error: 'Некорректный vote_type' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
@ -61,19 +61,16 @@ export const POST: APIRoute = async ({ request, cookies }) => {
}
const existingVoteRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?` +
new URLSearchParams({
filter: `review="${review_id}" && user="${userId}"`,
}),
`${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${review_id}")&&(user="${userId}")`,
{
headers: { 'Authorization': `Bearer ${token}` },
}
);
let userVote: 'likes' | 'dislikes' | null = null;
let method = 'POST';
let url = `${POCKETBASE_URL}/api/collections/review_votes/records`;
let voteId = null;
let userVote: 'like' | 'dislike' | null = null;
let voteId: string | null = null;
if (existingVoteRes.ok) {
const existingData = await existingVoteRes.json();
@ -93,58 +90,43 @@ export const POST: APIRoute = async ({ request, cookies }) => {
}
const voteBody = method === 'POST'
? JSON.stringify({ review: review_id, user: userId, vote_type })
? JSON.stringify({ review: review_id, user: userId, vote_type: vote_type })
: method === 'PATCH'
? JSON.stringify({ vote_type })
: null;
? JSON.stringify({ vote_type: vote_type })
: undefined;
const voteRes = await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Content-Type': method !== 'DELETE' ? 'application/json' : undefined,
},
body: voteBody,
});
if (!voteRes.ok && method !== 'DELETE') {
const errorText = await voteRes.text();
console.error('[ReviewVote API] Failed to save vote:', errorText);
console.error('[ReviewVote API] Vote error:', errorText);
throw new Error('Failed to save vote');
}
if (method === 'POST') userVote = vote_type;
if (method === 'DELETE') userVote = null;
const likesRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?` +
new URLSearchParams({
filter: `review="${review_id}"`,
fields: 'vote_type',
})
const votesRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${review_id}")`,
{}
);
let likes = 0;
let dislikes = 0;
if (likesRes.ok) {
const votesData = await likesRes.json();
likes = votesData.items.filter((v: any) => v.vote_type === 'like').length;
dislikes = votesData.items.filter((v: any) => v.vote_type === 'dislike').length;
if (votesRes.ok) {
const votesData = await votesRes.json();
likes = votesData.items?.filter((v: any) => v.vote_type === 'likes').length || 0;
dislikes = votesData.items?.filter((v: any) => v.vote_type === 'dislikes').length || 0;
}
await fetch(
`${POCKETBASE_URL}/api/collections/reviews/records/${review_id}`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ votesCount: likes }),
}
);
return new Response(
JSON.stringify({ likes, dislikes, userVote }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
@ -152,7 +134,7 @@ export const POST: APIRoute = async ({ request, cookies }) => {
} catch (error) {
console.error('[ReviewVote API] Error:', error);
return new Response(
JSON.stringify({ error: 'Внутренняя ошибка сервера' }),
JSON.stringify({ error: 'Внутренняя ошибка' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}
@ -163,30 +145,16 @@ export const GET: APIRoute = async ({ url, cookies }) => {
const reviewId = url.searchParams.get('review_id');
const token = cookies.get('pb_auth')?.value;
if (!reviewId || !POCKETBASE_ID_REGEX.test(reviewId)) {
if (!reviewId || !PB_ID_REGEX.test(reviewId)) {
return new Response(
JSON.stringify({ error: 'Некорректный review_id' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
}
const reviewRes = await fetch(
`${POCKETBASE_URL}/api/collections/reviews/records/${reviewId}`
);
if (!reviewRes.ok) {
return new Response(
JSON.stringify({ error: 'Отзыв не найден' }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
);
}
const votesRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?` +
new URLSearchParams({
filter: `review="${reviewId}"`,
fields: 'vote_type',
})
`${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${reviewId}")`,
{}
);
let likes = 0;
@ -194,11 +162,11 @@ export const GET: APIRoute = async ({ url, cookies }) => {
if (votesRes.ok) {
const votesData = await votesRes.json();
likes = votesData.items.filter((v: any) => v.vote_type === 'like').length;
dislikes = votesData.items.filter((v: any) => v.vote_type === 'dislike').length;
likes = votesData.items?.filter((v: any) => v.vote_type === 'likes').length || 0;
dislikes = votesData.items?.filter((v: any) => v.vote_type === 'dislikes').length || 0;
}
let userVote: 'like' | 'dislike' | null = null;
let userVote: 'likes' | 'dislikes' | null = null;
if (token) {
try {
@ -214,12 +182,9 @@ export const GET: APIRoute = async ({ url, cookies }) => {
const authData = await authRes.json();
const userId = authData.record?.id;
if (userId && POCKETBASE_ID_REGEX.test(userId)) {
if (userId && PB_ID_REGEX.test(userId)) {
const userVoteRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?` +
new URLSearchParams({
filter: `review="${reviewId}" && user="${userId}"`,
}),
`${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${reviewId}")&&(user="${userId}")`,
{
headers: { 'Authorization': `Bearer ${token}` },
}
@ -234,7 +199,7 @@ export const GET: APIRoute = async ({ url, cookies }) => {
}
}
} catch (e) {
console.error('[ReviewVote API] Error fetching user vote:', e);
console.error('[ReviewVote API GET] Error:', e);
}
}
@ -245,7 +210,7 @@ export const GET: APIRoute = async ({ url, cookies }) => {
} catch (error) {
console.error('[ReviewVote API GET] Error:', error);
return new Response(
JSON.stringify({ error: 'Внутренняя ошибка сервера' }),
JSON.stringify({ error: 'Внутренняя ошибка' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
}

View file

@ -2,7 +2,6 @@
import Layout from '@layouts/Layout.astro';
import { SITE_URL } from '@constants';
import PageHero from "@components/base/PageHero.astro";
import CTA from "@components/base/CTA.astro";
import Pagination from "@components/base/Pagination.astro";
import ServiceCategories from "@components/services/ServiceCategories.astro";
---