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

This commit is contained in:
Web-serfer 2026-04-19 19:00:42 +05:00
parent 36a3d37ad3
commit 815986969a
19 changed files with 1703 additions and 143 deletions

View file

@ -0,0 +1,510 @@
---
import Button from '@components/base/Button.astro';
import { Icon } from 'astro-icon/components';
interface HeroProps {
badgeText: string;
titleWhite: string;
titleGold: string;
description: string;
btnText?: string;
btnHref?: string;
btnSecondary?: string;
btnSecondaryHref?: string;
btnSecondaryClass?: string;
modalTarget?: string;
bgImage?: string;
minHeight?: string;
headerOffset?: string;
layout?: 'default' | 'with-image';
sideImage?: string;
sideImageAlt?: string;
experienceBadge?: {
number: string;
text: string;
};
icon?: string;
}
const {
badgeText,
titleWhite,
titleGold,
description,
btnText,
btnHref = "#contact",
btnSecondary,
btnSecondaryHref = "/services",
btnSecondaryClass = "",
modalTarget,
bgImage = "",
minHeight = "100vh",
headerOffset = "80px",
layout = "default",
sideImage = "",
sideImageAlt = "",
experienceBadge,
icon
} = Astro.props as HeroProps;
const showImage = layout === 'with-image' && sideImage;
---
<section
class="hero-section hero-home"
style={`min-height: ${minHeight}; padding-top: ${headerOffset}; ${bgImage ? `background-image: url("${bgImage}")` : ''}`}
>
{bgImage && (
<img
src={bgImage}
alt=""
class="hero-bg-lcp"
fetchpriority="high"
decoding="async"
width="1920"
height="1080"
/>
)}
<div class="hero-overlay"></div>
<div class="site-container hero-grid">
<div class="hero-content">
<div class="badge">
{icon ? (
<span class="badge-icon">
<Icon name={icon} />
</span>
) : (
<span class="status-dot"></span>
)}
{badgeText}
</div>
<h1 class="hero-title">
<span class="text-white">{titleWhite}</span>
<br />
<span class="text-gold">{titleGold}</span>
</h1>
<p class="hero-description">{description}</p>
{btnText && (
<div class="hero-actions">
{modalTarget ? (
<Button variant="gold" size="lg" data-modal-target={modalTarget}>
{btnText}
</Button>
) : (
<Button variant="gold" size="lg" href={btnHref}>
{btnText}
</Button>
)}
{btnSecondary && (
<Button variant="outline" size="lg" href={btnSecondaryHref} class={btnSecondaryClass}>
{btnSecondary}
</Button>
)}
</div>
)}
</div>
{showImage && (
<div class="hero-image-wrapper">
<div class="image-composition">
<img
src={sideImage}
alt={sideImageAlt || "Юрист"}
class="main-image"
width="380"
height="500"
loading="eager"
fetchpriority="high"
decoding="async"
/>
{experienceBadge && (
<div class="experience-badge">
<span class="exp-number">{experienceBadge.number}</span>
<span class="exp-text">{experienceBadge.text}</span>
</div>
)}
</div>
</div>
)}
</div>
</section>
<style>
.hero-section {
position: relative;
width: 100%;
min-height: 100vh;
display: flex;
align-items: center;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
margin: 0 !important;
box-sizing: border-box;
overflow: hidden;
transition: padding-top 0.3s ease;
}
.hero-bg-lcp {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
pointer-events: none;
z-index: -1;
}
.hero-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(90deg, #0a2540 0%, rgba(10, 37, 64, 0.9) 50%, rgba(10, 37, 64, 0.7) 100%);
z-index: 1;
}
.site-container {
position: relative;
z-index: 2;
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
width: 100%;
}
/* --- GRID LAYOUT --- */
.hero-grid {
display: flex;
justify-content: space-between;
align-items: center;
gap: 3rem;
width: 100%;
padding-bottom: 4rem;
}
.hero-content {
flex: 1.2;
max-width: 700px;
}
/* --- BADGE --- */
.badge {
display: inline-flex;
align-items: center;
gap: 0.6rem;
background-color: rgba(234, 194, 110, 0.15);
border: 1px solid rgba(234, 194, 110, 0.3);
color: #eac26e;
padding: 0.5rem 1rem;
border-radius: 6px;
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 1.5px;
margin-bottom: 2.5rem;
}
.badge svg {
color: #eac26e;
flex-shrink: 0;
}
/* Мерцающая точка - оптимизированная анимация */
.status-dot {
width: 10px;
height: 10px;
background: #22c55e;
border-radius: 50%;
position: relative;
flex-shrink: 0;
}
.status-dot::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 50%;
background: #22c55e;
animation: pulse-ring 2s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
z-index: -1;
}
.badge-icon {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.badge-icon svg {
width: 20px !important;
height: 20px !important;
stroke-width: 2 !important;
}
@keyframes pulse-ring {
0% {
transform: scale(1);
opacity: 0.8;
}
100% {
transform: scale(2.5);
opacity: 0;
}
}
/* --- TITLE --- */
.hero-title {
font-size: clamp(2rem, 5vw, 3.8rem);
font-weight: 800;
line-height: 1.15;
margin: 0 0 2rem 0;
}
.text-white {
color: #ffffff;
}
.text-gold {
color: #eac26e;
}
/* --- DESCRIPTION --- */
.hero-description {
color: rgba(255, 255, 255, 0.85);
font-size: 1.15rem;
line-height: 1.6;
margin-bottom: 2.5rem;
max-width: 580px;
}
/* --- ACTIONS --- */
.hero-actions {
display: flex;
gap: 1.5rem;
align-items: stretch;
}
.hero-actions > * {
display: flex;
align-items: center;
}
/* --- IMAGE BLOCK --- */
.hero-image-wrapper {
flex: 1;
display: flex;
justify-content: flex-end;
position: relative;
}
.image-composition {
position: relative;
width: 100%;
max-width: 480px;
}
.image-composition::before {
content: '';
position: absolute;
top: -10px;
left: 20px;
right: -20px;
bottom: 10px;
background-color: #ffffff;
border-radius: 12px;
transform: rotate(3deg);
z-index: -1;
opacity: 0;
animation: fadeInRotate 0.8s ease 0.6s forwards;
}
@keyframes fadeInRotate {
from {
opacity: 0;
transform: rotate(0deg) translateY(20px);
}
to {
opacity: 1;
transform: rotate(3deg) translateY(0);
}
}
.main-image {
width: 100%;
border-radius: 12px;
border: 8px solid #ffffff;
filter: grayscale(100%);
box-shadow: 0 30px 60px rgba(0,0,0,0.4);
}
.experience-badge {
position: absolute;
bottom: 30px;
left: -30px;
background: #ffffff;
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 15px 35px rgba(0,0,0,0.2);
min-width: 180px;
}
.exp-number {
font-size: 2.2rem;
font-weight: 900;
color: #1e3050;
line-height: 1;
display: block;
}
.exp-text {
font-size: 0.7rem;
font-weight: 800;
color: #535e6c;
text-transform: uppercase;
}
/* --- АДАПТАЦИЯ --- */
@media (max-width: 992px) {
.hero-section {
padding-top: 70px;
min-height: auto;
}
.hero-grid {
flex-direction: column;
text-align: center;
padding-top: 1.5rem;
}
.hero-content {
align-items: center;
}
.hero-actions {
justify-content: center;
}
.hero-image-wrapper {
margin-top: 3rem;
justify-content: center;
}
.experience-badge {
left: 0;
bottom: -20px;
}
}
@media (max-width: 767px) {
.hero-section {
padding-top: 64px;
}
.hero-title {
font-size: 1.8rem;
}
.hero-actions {
flex-direction: column;
width: 100%;
}
.hero-actions > * {
width: 100%;
}
.image-composition::before {
display: none;
}
}
@media (max-width: 480px) {
.hero-section {
padding-top: 64px;
}
.hero-title {
font-size: 1.8rem;
}
}
/* Кастомные стили для кнопки "Мои услуги" */
:global(.btn-services) {
background: transparent !important;
border: 2px solid #ffffff !important;
color: #ffffff !important;
padding: 0.875rem 1.5rem !important;
font-size: 1.125rem !important;
line-height: 1.75rem !important;
position: relative;
overflow: hidden;
z-index: 1;
height: auto !important;
min-height: 3.25rem !important;
transition: all 0.3s ease;
}
:global(.btn-services)::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: left 0.5s ease;
z-index: -1;
}
:global(.btn-services)::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background: linear-gradient(90deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.2));
transition: width 0.4s ease;
z-index: -1;
}
:global(.btn-services:hover) {
background: rgba(255, 255, 255, 0.1) !important;
border-color: #eac26e !important;
color: #eac26e !important;
transform: translateY(-3px);
box-shadow: 0 8px 25px rgba(234, 194, 110, 0.3);
}
:global(.btn-services:hover)::before {
left: 100%;
}
:global(.btn-services:hover)::after {
width: 100%;
}
:global(.btn-services:active) {
transform: translateY(-1px);
box-shadow: 0 4px 15px rgba(234, 194, 110, 0.2);
}
</style>

View file

@ -45,10 +45,9 @@ import { COMPANY } from "@constants";
</a>
<div class="header-actions" id="auth-section"></div>
</div>
<div class="mobile-actions">
<a href={`tel:${COMPANY.phoneClean}`} class="mobile-phone-btn" aria-label="Позонить: {COMPANY.phone}">
<a href={`tel:${COMPANY.phoneClean}`} class="mobile-phone-btn" aria-label="Позони<EFBFBD><EFBFBD>ь: {COMPANY.phone}">
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
@ -323,7 +322,30 @@ import { COMPANY } from "@constants";
.header-phone {
display: flex;
}
.mobile-phone-btn {
.mobile-phone-btn,
.burger-btn {
display: none;
}
}
@media (max-width: 992px) {
.header-phone {
display: none;
}
.mobile-actions {
display: flex;
align-items: center;
gap: 16px;
}
.mobile-phone-btn,
.burger-btn {
display: flex;
}
.header-right {
gap: 0.5rem;
justify-content: flex-end;
}
.header-right > *:not(.mobile-actions) {
display: none;
}
}

View file

@ -3,7 +3,7 @@ import RatingStars from './RatingStars.astro';
export interface Props {
name: string;
car: string;
profession: string;
text: string;
rating: number;
initial: string;
@ -15,7 +15,7 @@ export interface Props {
const {
name,
car,
profession,
text,
rating,
initial,
@ -45,7 +45,7 @@ const formatDate = (dateStr: string) => {
</div>
<div class="author-details">
<h3 class="author-name">{name}</h3>
<p class="author-car">{car}</p>
<p class="author-profession">{profession}</p>
</div>
</div>
<time class="review-date">{formatDate(date)}</time>
@ -143,7 +143,7 @@ const formatDate = (dateStr: string) => {
margin: 0;
}
.author-car {
.author-profession {
color: #64748b;
font-size: 0.875rem;
margin: 0;

View file

@ -0,0 +1,397 @@
import { createSignal, Show, For, createEffect } from "solid-js";
interface ReviewFormProps {
onSubmit: (data: {
name: string;
surname: string;
profession: string;
rating: number;
text: string;
}) => void;
onCancel?: () => void;
user?: {
name: string;
email: string;
avatar?: string;
};
}
const EMOJIS = [
"👍", "👎", "❤️", "😊", "😂", "🎉", "🔥", "👏",
"😢", "😮", "😡", "🙏", "⭐", "💯", "❤️‍🔥", "🤔",
"👀", "💪", "🚀", "✨"
];
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_TEXT_LENGTH = 2000;
const MIN_TEXT_LENGTH = 50;
const MAX_NAME_LENGTH = 50;
const MAX_PROFESSION_LENGTH = 100;
interface ValidationErrors {
name?: string;
surname?: string;
profession?: string;
rating?: string;
text?: string;
}
export default function ReviewForm(props: ReviewFormProps) {
const [name, setName] = createSignal("");
const [surname, setSurname] = createSignal("");
const [profession, setProfession] = createSignal("");
const [rating, setRating] = 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) {
const parts = props.user.name.split(" ");
if (parts.length >= 2) {
setName(parts[0]);
setSurname(parts.slice(1).join(" "));
} else {
setName(props.user.name);
}
}
});
const sanitizeInput = (input: string): string => {
return input
.replace(/[<>]/g, "")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#x27;")
.replace(/&/g, "&amp;");
};
const containsDangerousContent = (input: string): boolean => {
return DANGEROUS_PATTERNS.some((pattern) => pattern.test(input));
};
const validateName = (value: string): string | undefined => {
const trimmed = value.trim();
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} символов`;
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} символов`;
return undefined;
};
const validateRating = (value: number): string | undefined => {
if (!value || value < 1 || value > 5) return "Выберите оценку";
return undefined;
};
const validateText = (value: string): string | undefined => {
const trimmed = value.trim();
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 undefined;
};
const handleTextChange = (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_TEXT_LENGTH) {
value = value.slice(0, MAX_TEXT_LENGTH);
}
setText(value);
if (touched().text) {
setErrors((prev) => ({ ...prev, text: validateText(value) }));
}
};
const addEmoji = (emoji: string) => {
setText((prev) => prev + emoji);
setShowEmojiPicker(false);
};
const validateForm = (): boolean => {
const newErrors: ValidationErrors = {
name: validateName(name()),
surname: validateSurname(surname()),
profession: validateProfession(profession()),
rating: validateRating(rating()),
text: validateText(text()),
};
setErrors(newErrors);
setTouched({
name: true,
surname: true,
profession: true,
rating: true,
text: true,
});
return !Object.values(newErrors).some((error) => error);
};
const handleSubmit = (e: Event) => {
e.preventDefault();
if (!validateForm()) return;
props.onSubmit({
name: sanitizeInput(name().trim()),
surname: sanitizeInput(surname().trim()),
profession: sanitizeInput(profession().trim()),
rating: rating(),
text: sanitizeInput(text().trim()),
});
setName("");
setSurname("");
setProfession("");
setRating(0);
setText("");
setErrors({});
setTouched({});
};
const handleBlur = (field: string) => {
setTouched((prev) => ({ ...prev, [field]: true }));
const fieldValidators: Record<string, () => string | undefined> = {
name: () => validateName(name()),
surname: () => validateSurname(surname()),
profession: () => validateProfession(profession()),
rating: () => validateRating(rating()),
text: () => validateText(text()),
};
setErrors((prev) => ({
...prev,
[field]: fieldValidators[field](),
}));
};
const isValid = () => {
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 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
? "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"
}`;
};
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>
<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>
<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="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) => (
<button
type="button"
onClick={() => addEmoji(emoji)}
class="p-2 text-xl hover:bg-gray-100 rounded-lg transition-colors"
>
{emoji}
</button>
)}
</For>
</div>
</div>
</Show>
</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"}`}
>
{text().length}/{MAX_TEXT_LENGTH}
</p>
</div>
</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>
<p class="text-xs text-gray-500 text-center">
Нажимая кнопку, вы соглашаетесь с{" "}
<a href="/privacy" class="text-blue-600 hover:underline">политикой конфиденциальности</a>
</p>
</form>
);
}

View file

@ -0,0 +1,151 @@
import { createSignal, onMount, Show } from "solid-js";
import ReviewForm from "./ReviewForm";
interface ToastMessage {
type: "success" | "error";
message: string;
}
interface User {
id: string;
name: string;
email: string;
avatar?: string;
}
export default function ReviewFormContainer() {
const [isAuthenticated, setIsAuthenticated] = createSignal(false);
const [currentUser, setCurrentUser] = createSignal<User | undefined>(undefined);
const [isLoading, setIsLoading] = createSignal(true);
const [toast, setToast] = createSignal<ToastMessage | null>(null);
const showToast = (message: ToastMessage): void => {
setToast(message);
setTimeout(() => setToast(null), 3000);
};
onMount(async () => {
try {
const response = await fetch("/api/auth/me", {
method: "GET",
credentials: "include",
});
const data = await response.json();
if (data.authenticated && data.user) {
setIsAuthenticated(true);
setCurrentUser({
id: data.user.id,
name: data.user.name || "Пользователь",
email: data.user.email,
avatar: data.user.avatar,
});
}
} catch (error) {
console.error("[ReviewForm] Ошибка проверки авторизации:", error);
} finally {
setIsLoading(false);
}
});
const handleSubmit = async (data: {
name: string;
surname: string;
profession: string;
rating: number;
text: string;
}) => {
try {
const response = await fetch("/api/reviews", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
name: data.name,
surname: data.surname,
profession: data.profession,
rating: data.rating,
text: data.text,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Failed to create review");
}
showToast({ type: "success", message: "Спасибо! Ваш отзыв отправлен на модерацию." });
} catch (error) {
console.error("[ReviewForm] Ошибка создания отзыва:", error);
showToast({ type: "error", message: "Не удалось отправить отзыв. Попробуйте позже." });
}
};
return (
<>
<Show when={toast()}>
{(t) => (
<div
class={`fixed bottom-4 right-4 px-6 py-3 rounded-xl shadow-lg transition-all duration-300 z-50 ${
t().type === "success"
? "bg-green-500 text-white"
: "bg-red-500 text-white"
}`}
>
{t().message}
</div>
)}
</Show>
<Show when={isLoading()}>
<div class="max-w-700px mx-auto 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>
</Show>
<Show when={!isLoading()}>
<Show when={isAuthenticated()} fallback={
<div class="max-w-700px mx-auto">
<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" style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);">
<div class="w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center" style="background: linear-gradient(135deg, rgba(37, 99, 235, 0.2) 0%, rgba(30, 64, 175, 0.3) 100%);">
<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>
<p class="text-gray-600 mb-6">
Чтобы поделиться своим опытом, пожалуйста, войдите в личный кабинет.
</p>
<a
href={`/auth/sign-in?redirect=${encodeURIComponent(window.location.pathname)}`}
class="inline-flex items-center justify-center font-semibold transition-all duration-300 rounded-md cursor-pointer px-6 py-3 text-lg"
style="background: linear-gradient(to bottom, #2563eb, #1e40af); color: white; box-shadow: 0 2px 4px rgba(37, 99, 235, 0.3);"
>
<svg class="w-5 h-5 mr-2" 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/sign-up?redirect=${encodeURIComponent(window.location.pathname)}`}
class="font-medium hover:underline"
style="color: #2563eb;"
>
Зарегистрироваться
</a>
</p>
</div>
</div>
}>
<ReviewForm onSubmit={handleSubmit} user={currentUser()} />
</Show>
</Show>
</>
);
}

View file

@ -0,0 +1,170 @@
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()}>
<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>
</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>
</>
);
}