Новые изменения компонентов

This commit is contained in:
Web-serfer 2026-04-21 22:43:01 +05:00
parent 2d3d768d3b
commit 5bb4525f63
5 changed files with 399 additions and 286 deletions

View file

@ -0,0 +1,20 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_362615506")
// update collection data
unmarshal({
"listRule": ""
}, collection)
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_362615506")
// update collection data
unmarshal({
"listRule": "@request.auth.id != \"\""
}, collection)
return app.save(collection)
})

View file

@ -0,0 +1,20 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_362615506")
// update collection data
unmarshal({
"viewRule": ""
}, collection)
return app.save(collection)
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_362615506")
// update collection data
unmarshal({
"viewRule": "@request.auth.id != \"\""
}, collection)
return app.save(collection)
})

View file

@ -1,14 +1,16 @@
--- ---
type ColorKey = 'bg-gradient-1' | 'bg-gradient-2' | 'bg-gradient-3' | 'bg-gradient-4' | 'bg-gradient-5' | 'bg-gradient-6';
export interface Props { export interface Props {
name: string; name: string;
profession: string; profession: string;
text: string; text: string;
rating: number; rating: number;
initial: string; initial: string;
color: string; color: ColorKey;
date: string; date: string;
votesCount?: number; reviewId: string;
reviewId?: string; initialLikes?: number;
} }
const { const {
@ -19,8 +21,8 @@ const {
initial, initial,
color, color,
date, date,
votesCount = 0, reviewId,
reviewId = '' initialLikes = 0
} = Astro.props; } = Astro.props;
// Форматируем дату // Форматируем дату
@ -32,14 +34,41 @@ const formatDate = (dateStr: string) => {
year: 'numeric' year: 'numeric'
}); });
}; };
// Цвета для градиентов аватаров
const gradientColors = {
'bg-gradient-1': 'from-purple-500 to-pink-500',
'bg-gradient-2': 'from-blue-500 to-cyan-500',
'bg-gradient-3': 'from-green-500 to-emerald-500',
'bg-gradient-4': 'from-orange-500 to-red-500',
'bg-gradient-5': 'from-indigo-500 to-purple-500',
'bg-gradient-6': 'from-rose-500 to-orange-500',
};
--- ---
<article class="review-card animate-on-scroll" data-animation="fade-up"> <article class="review-card animate-on-scroll" data-animation="fade-up" data-review-id={reviewId}>
<!-- Декоративный элемент -->
<div class="card-decoration"></div>
<!-- Кавычки -->
<div class="quote-icon">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M14.017 21v-7.391c0-5.704 3.731-9.57 8.983-10.609l.995 2.151c-2.432.917-3.995 3.638-3.995 5.849h4v10h-9.983zm-14.017 0v-7.391c0-5.704 3.748-9.57 9-10.609l.996 2.151c-2.433.917-3.996 3.638-3.996 5.849h3.983v10h-9.983z" />
</svg>
</div>
<!-- Шапка карточки --> <!-- Шапка карточки -->
<div class="review-header"> <div class="review-header">
<div class="author-info"> <div class="author-info">
<div class={`avatar ${color}`}> <div class="avatar-wrapper">
<span>{initial}</span> <div class={`avatar ${color} ${gradientColors[color] || ''}`}>
<span>{initial}</span>
</div>
<div class="avatar-badge">
<svg viewBox="0 0 20 20" fill="currentColor">
<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>
</div>
</div> </div>
<div class="author-details"> <div class="author-details">
<h3 class="author-name">{name}</h3> <h3 class="author-name">{name}</h3>
@ -53,67 +82,103 @@ const formatDate = (dateStr: string) => {
<div class="review-rating"> <div class="review-rating">
<div class="rating-stars-display"> <div class="rating-stars-display">
{[1, 2, 3, 4, 5].map((star) => ( {[1, 2, 3, 4, 5].map((star) => (
<svg <svg
class={`star ${star <= rating ? 'filled' : ''}`} class={`star ${star <= rating ? 'filled' : ''}`}
viewBox="0 0 24 24" viewBox="0 0 24 24"
fill={star <= rating ? 'currentColor' : 'none'} fill={star <= rating ? 'currentColor' : 'none'}
stroke="currentColor" stroke="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" /> <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> </svg>
))} ))}
</div> </div>
<span class="rating-value">{rating}.0</span>
</div> </div>
<!-- Текст отзыва --> <!-- Текст отзыва -->
<div class="review-text"> <div class="review-text">
<p>{text}</p> <p>"{text}"</p>
</div> </div>
<!-- Блок голосования --> <!-- Нижняя панель с действиями -->
<div class="voting-section" data-review-id={reviewId}> <div class="review-footer">
<button <button class="like-button" data-vote="likes">
type="button" <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="vote-btn vote-btn-up" <path d="M7 10v12"></path>
data-vote="likes" <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>
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> </svg>
<span class="votes-number">{votesCount}</span> <span>Полезно</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> </button>
<div class="share-button">
<span class="likes-count" data-likes-count>{initialLikes}</span>
</div>
<span class="auth-warning" data-auth-warning>Чтобы голосовать, нужно войти</span>
</div> </div>
</article> </article>
<style> <style>
.review-card { .review-card {
background: #ffffff; position: relative;
border-radius: 1rem; background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
border-radius: 1.5rem;
padding: 2rem; padding: 2rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); box-shadow: 0 20px 35px -10px rgba(0, 0, 0, 0.1);
border: 1px solid #e2e8f0; border: 1px solid rgba(212, 175, 55, 0.2);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 1.25rem; gap: 1.5rem;
overflow: hidden;
}
.review-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #d4af37, #fbbf24, #d4af37);
transform: scaleX(0);
transition: transform 0.4s ease;
}
.review-card:hover::before {
transform: scaleX(1);
} }
.review-card:hover { .review-card:hover {
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08); box-shadow: 0 25px 40px -12px rgba(0, 0, 0, 0.15);
border-color: #d4af37; border-color: rgba(212, 175, 55, 0.4);
transform: translateY(-4px); transform: translateY(-6px);
}
/* Декоративный элемент */
.card-decoration {
position: absolute;
top: 0;
right: 0;
width: 100px;
height: 100px;
background: radial-gradient(circle, rgba(212, 175, 55, 0.05) 0%, transparent 70%);
border-radius: 50%;
pointer-events: none;
}
/* Иконка кавычек */
.quote-icon {
position: absolute;
bottom: 1rem;
right: 1rem;
width: 3rem;
height: 3rem;
color: rgba(212, 175, 55, 0.1);
pointer-events: none;
}
.quote-icon svg {
width: 100%;
height: 100%;
} }
.review-header { .review-header {
@ -121,6 +186,8 @@ const formatDate = (dateStr: string) => {
justify-content: space-between; justify-content: space-between;
align-items: flex-start; align-items: flex-start;
gap: 1rem; gap: 1rem;
position: relative;
z-index: 1;
} }
.author-info { .author-info {
@ -129,16 +196,72 @@ const formatDate = (dateStr: string) => {
gap: 1rem; gap: 1rem;
} }
.avatar-wrapper {
position: relative;
}
.avatar { .avatar {
width: 3.5rem; width: 3.5rem;
height: 3.5rem; height: 3.5rem;
border-radius: 0.75rem; border-radius: 1rem;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-weight: 700; font-weight: 700;
font-size: 1.25rem; font-size: 1.25rem;
flex-shrink: 0; flex-shrink: 0;
position: relative;
transition: all 0.3s ease;
}
.review-card:hover .avatar {
transform: scale(1.05) rotate(2deg);
}
/* Цвета аватаров */
.bg-gradient-1 {
background: linear-gradient(135deg, #8b5cf6, #ec4899);
color: white;
}
.bg-gradient-2 {
background: linear-gradient(135deg, #3b82f6, #06b6d4);
color: white;
}
.bg-gradient-3 {
background: linear-gradient(135deg, #10b981, #059669);
color: white;
}
.bg-gradient-4 {
background: linear-gradient(135deg, #f59e0b, #ef4444);
color: white;
}
.bg-gradient-5 {
background: linear-gradient(135deg, #6366f1, #a855f7);
color: white;
}
.bg-gradient-6 {
background: linear-gradient(135deg, #f43f5e, #fb923c);
color: white;
}
.avatar-badge {
position: absolute;
bottom: -4px;
right: -4px;
width: 1rem;
height: 1rem;
background: #10b981;
border-radius: 50%;
border: 2px solid white;
display: flex;
align-items: center;
justify-content: center;
color: white;
}
.avatar-badge svg {
width: 0.75rem;
height: 0.75rem;
} }
.author-details { .author-details {
@ -149,166 +272,150 @@ const formatDate = (dateStr: string) => {
.author-name { .author-name {
color: #1e293b; color: #1e293b;
font-weight: 700; font-weight: 800;
font-size: 1.125rem; font-size: 1.125rem;
margin: 0; margin: 0;
background: linear-gradient(135deg, #1e293b, #334155);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
} }
.author-profession { .author-profession {
color: #64748b; color: #64748b;
font-size: 0.875rem; font-size: 0.875rem;
margin: 0; margin: 0;
font-weight: 500;
} }
.review-date { .review-date {
color: #94a3b8; color: #94a3b8;
font-size: 0.875rem; font-size: 0.75rem;
white-space: nowrap; white-space: nowrap;
font-weight: 500;
letter-spacing: 0.3px;
} }
.review-rating { .review-rating {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between;
padding: 0.5rem 0;
border-top: 1px solid #e2e8f0;
border-bottom: 1px solid #e2e8f0;
} }
.rating-stars-display { .rating-stars-display {
display: flex; display: flex;
gap: 0.125rem; gap: 0.25rem;
} }
.rating-stars-display .star { .rating-stars-display .star {
width: 1.25rem; width: 1.25rem;
height: 1.25rem; height: 1.25rem;
color: #d1d5db; color: #e2e8f0;
transition: all 0.2s ease;
} }
.rating-stars-display .star.filled { .rating-stars-display .star.filled {
color: #fbbf24; color: #fbbf24;
filter: drop-shadow(0 0 2px rgba(251, 191, 36, 0.3));
}
.rating-value {
font-weight: 700;
font-size: 0.875rem;
color: #d4af37;
background: rgba(212, 175, 55, 0.1);
padding: 0.25rem 0.5rem;
border-radius: 0.5rem;
} }
.review-text { .review-text {
color: #334155; color: #334155;
line-height: 1.7; line-height: 1.7;
font-size: 0.95rem; font-size: 0.95rem;
position: relative;
z-index: 1;
} }
.review-text p { .review-text p {
margin: 0; margin: 0;
font-style: italic;
} }
.voting-section { /* Нижняя панель */
margin-top: auto; .review-footer {
padding-top: 1.25rem;
border-top: 1px solid #e2e8f0;
display: flex; display: flex;
gap: 1rem; gap: 1rem;
justify-content: center; padding-top: 0.5rem;
padding-bottom: 1.5rem;
border-top: 1px solid #e2e8f0;
align-items: center;
position: relative;
} }
.vote-btn { .auth-warning {
display: inline-flex; font-size: 0.75rem;
color: #ef4444;
opacity: 0;
transition: opacity 0.3s ease;
position: absolute;
bottom: -3px;
left: 0;
}
.auth-warning.visible {
opacity: 1;
}
.like-button,
.share-button {
display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
padding: 0.625rem 1rem; padding: 0.5rem 1rem;
background: transparent;
border: 1px solid #e2e8f0; border: 1px solid #e2e8f0;
border-radius: 0.5rem; border-radius: 0.75rem;
background: #ffffff; color: #64748b;
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 500; font-weight: 500;
color: #64748b; cursor: pointer;
transition: all 0.2s ease;
} }
.vote-btn svg { .like-button svg,
width: 1.125rem; .share-button svg {
height: 1.125rem; width: 1rem;
height: 1rem;
} }
.vote-btn:hover { /* Стили для кнопки лайка с пальцем вверх */
border-color: #1e3050; .like-button:hover {
color: #1e3050; background: #f0fdf4;
background: #f8fafc; border-color: #22c55e;
color: #22c55e;
transform: translateY(-2px);
} }
.vote-btn.active { /* Анимация для пальца вверх при нажатии */
background: #1e3050; .like-button:active svg {
border-color: #1e3050; animation: thumbsUp 0.3s ease;
color: #ffffff;
} }
.vote-btn:disabled { @keyframes thumbsUp {
opacity: 0.5; 0% {
cursor: not-allowed; transform: scale(1);
}
.vote-label {
display: none;
}
@media (max-width: 640px) {
.voting-buttons {
flex-direction: column;
width: 100%;
} }
50% {
.vote-btn { transform: scale(1.3) rotate(-10deg);
width: 100%;
justify-content: center;
} }
100% {
.vote-label { transform: scale(1);
display: inline;
} }
} }
.icon {
width: 1.125rem;
height: 1.125rem;
}
.auth-prompt {
position: fixed;
bottom: 1rem;
left: 50%;
transform: translateX(-50%);
background: #1e293b;
color: #fff;
padding: 1rem 1.5rem;
border-radius: 0.5rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 1000;
animation: fadeInUp 0.3s ease;
}
.auth-prompt a {
color: #d4af37;
text-decoration: underline;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateX(-50%) translateY(1rem);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
.helpful-badge {
display: inline-flex;
align-items: center;
gap: 0.375rem;
color: #059669;
font-size: 0.875rem;
font-weight: 600;
background: rgba(5, 150, 105, 0.1);
padding: 0.375rem 0.75rem;
border-radius: 0.5rem;
}
/* Анимации */ /* Анимации */
.animate-on-scroll { .animate-on-scroll {
opacity: 0; opacity: 0;
@ -318,7 +425,7 @@ const formatDate = (dateStr: string) => {
[data-animation="fade-up"] { [data-animation="fade-up"] {
transform: translateY(30px); transform: translateY(30px);
transition: opacity 0.7s cubic-bezier(0.4, 0, 0.2, 1), transition: opacity 0.7s cubic-bezier(0.4, 0, 0.2, 1),
transform 0.7s cubic-bezier(0.4, 0, 0.2, 1); transform 0.7s cubic-bezier(0.4, 0, 0.2, 1);
} }
.animate-on-scroll.is-visible { .animate-on-scroll.is-visible {
@ -334,22 +441,6 @@ const formatDate = (dateStr: string) => {
} }
} }
@media (max-width: 640px) {
.voting-buttons {
flex-direction: column;
width: 100%;
}
.vote-btn {
width: 100%;
justify-content: center;
}
.vote-label {
display: inline;
}
}
@media (max-width: 640px) { @media (max-width: 640px) {
.review-card { .review-card {
padding: 1.5rem; padding: 1.5rem;
@ -369,139 +460,114 @@ const formatDate = (dateStr: string) => {
.review-rating { .review-rating {
justify-content: center; justify-content: center;
gap: 1rem;
} }
.voting-section { .review-footer {
align-items: center; justify-content: center;
} }
.voting-stats { .quote-icon {
flex-direction: column; display: none;
gap: 0.5rem;
} }
} }
</style> </style>
<script> <script>
function showAuthPrompt(section: Element) { import { pb } from '../../lib/pb';
const votingSection = section as HTMLElement;
let authNote = votingSection.querySelector('.voting-auth-note'); console.log('[ReviewCard] Script loaded');
if (!authNote) {
authNote = document.createElement('p'); document.querySelectorAll('.review-card').forEach((card) => {
authNote.className = 'voting-auth-note'; const reviewId = (card as HTMLElement).dataset.reviewId;
authNote.style.cssText = 'color: #dc2626 !important; font-size: 0.7rem !important; font-style: italic; margin: 0;'; const likeBtn = card.querySelector('[data-vote="likes"]') as HTMLButtonElement;
authNote.innerHTML = 'Чтобы голосовать, <a href="/auth/sign-in">войдите</a> или <a href="/auth/sign-up">зарегистрируйтесь</a>'; const likesCount = card.querySelector('[data-likes-count]');
votingSection.insertBefore(authNote, votingSection.querySelector('.voting-buttons'));
setTimeout(() => authNote?.remove(), 3000); console.log('[ReviewCard] reviewId:', reviewId, 'likeBtn:', likeBtn, 'likesCount:', likesCount);
if (!reviewId) {
console.error('[ReviewCard] No reviewId found!');
return;
} }
}
document.addEventListener('DOMContentLoaded', () => { async function loadVotes() {
const votingSections = document.querySelectorAll('.voting-section'); console.log('[ReviewCard] Loading votes for:', reviewId);
if (!pb.authStore.isValid) {
votingSections.forEach(section => { console.log('[ReviewCard] Not logged in, keeping initialLikes:', initialLikes);
const reviewId = section.getAttribute('data-review-id'); if (likesCount) likesCount.textContent = initialLikes.toString();
const buttons = section.querySelectorAll('.vote-btn'); likeBtn?.classList.remove('active');
return;
buttons.forEach(btn => { }
btn.addEventListener('click', async () => { try {
const voteType = btn.getAttribute('data-vote'); const response = await fetch(`/api/reviews/vote?review_id=${reviewId}`, {
credentials: 'include',
if (!reviewId) {
showAuthPrompt(section);
return;
}
buttons.forEach(b => (b as HTMLButtonElement).disabled = true);
try {
const response = await fetch('/api/reviews/vote', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ review_id: reviewId, vote_type: voteType })
});
if (response.status === 401) {
showAuthPrompt(section);
return;
}
if (!response.ok) {
return;
}
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);
} finally {
buttons.forEach(b => (b as HTMLButtonElement).disabled = false);
}
}); });
}); console.log('[ReviewCard] loadVotes response:', response.status);
if (response.ok) {
const data = await response.json();
console.log('[ReviewCard] Votes data:', data);
if (likesCount) likesCount.textContent = data.likes.toString();
if (data.userVote === 'likes') {
likeBtn?.classList.add('active');
}
}
} catch (e) {
console.error('[ReviewCard] Error loading votes:', e);
}
}
loadVotes();
window.addEventListener('storage', (e) => {
if (e.key === 'pb_auth') {
loadVotes();
}
}); });
});
document.addEventListener('astro:page-load', () => { likeBtn?.addEventListener('click', async () => {
const votingSections = document.querySelectorAll('.voting-section'); console.log('[ReviewCard] Like button clicked, auth:', pb.authStore.isValid);
const warningEl = card.querySelector('[data-auth-warning]') as HTMLElement;
if (!pb.authStore.isValid) {
console.log('[ReviewCard] Not authorized, showing warning');
warningEl?.classList.add('visible');
setTimeout(() => {
warningEl?.classList.remove('visible');
}, 3000);
return;
}
votingSections.forEach(section => { try {
const buttons = section.querySelectorAll('.vote-btn'); console.log('[ReviewCard] Sending vote for:', reviewId);
const response = await fetch('/api/reviews/vote', {
buttons.forEach(btn => { method: 'POST',
btn.addEventListener('click', async () => { headers: { 'Content-Type': 'application/json' },
const voteType = btn.getAttribute('data-vote'); body: JSON.stringify({ review_id: reviewId, vote_type: 'likes' }),
const reviewId = section.getAttribute('data-review-id'); credentials: 'include',
if (!reviewId) {
showAuthPrompt(section);
return;
}
buttons.forEach(b => (b as HTMLButtonElement).disabled = true);
try {
const response = await fetch('/api/reviews/vote', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ review_id: reviewId, vote_type: voteType })
});
if (response.status === 401) {
showAuthPrompt(section);
return;
}
if (!response.ok) {
const errorText = await response.text();
console.error('[Vote JS] Error:', errorText);
return;
}
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);
} finally {
buttons.forEach(b => (b as HTMLButtonElement).disabled = false);
}
}); });
});
console.log('[ReviewCard] Vote response:', response.status);
if (response.ok) {
const data = await response.json();
console.log('[ReviewCard] Vote result:', data);
if (likesCount) likesCount.textContent = data.likes.toString();
if (data.userVote === 'likes') {
likeBtn?.classList.add('active');
} else {
likeBtn?.classList.remove('active');
}
} else if (response.status === 401) {
const warningEl = card.querySelector('[data-auth-warning]') as HTMLElement;
warningEl?.classList.add('visible');
setTimeout(() => {
warningEl?.classList.remove('visible');
}, 3000);
} else {
const error = await response.text();
console.error('[ReviewCard] Vote error:', error);
}
} catch (e) {
console.error('[ReviewCard] Error voting:', e);
}
}); });
}); });
</script> </script>

View file

@ -115,7 +115,6 @@ const getAvatarInfo = (name: string) => {
initial={avatarInfo.initial} initial={avatarInfo.initial}
color={avatarInfo.color} color={avatarInfo.color}
date={review.created} date={review.created}
votesCount={review.votesCount || 0}
reviewId={review.id} reviewId={review.id}
/> />
); );

View file

@ -115,16 +115,21 @@ export const POST: APIRoute = async ({ request, cookies }) => {
const votesRes = await fetch( const votesRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${review_id}")`, `${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${review_id}")`,
{} { headers: { 'Authorization': `Bearer ${token}` } }
); );
console.log('[ReviewVote API] Votes response:', votesRes.status);
let likes = 0; let likes = 0;
let dislikes = 0; let dislikes = 0;
if (votesRes.ok) { if (votesRes.ok) {
const votesData = await votesRes.json(); const votesData = await votesRes.json();
console.log('[ReviewVote API] Votes data:', JSON.stringify(votesData));
likes = votesData.items?.filter((v: any) => v.vote_type === 'likes').length || 0; likes = votesData.items?.filter((v: any) => v.vote_type === 'likes').length || 0;
dislikes = votesData.items?.filter((v: any) => v.vote_type === 'dislikes').length || 0; dislikes = votesData.items?.filter((v: any) => v.vote_type === 'dislikes').length || 0;
} else {
const errorText = await votesRes.text();
console.error('[ReviewVote API] Votes error:', errorText);
} }
return new Response( return new Response(
@ -152,16 +157,19 @@ export const GET: APIRoute = async ({ url, cookies }) => {
); );
} }
const authHeaders = token ? { 'Authorization': `Bearer ${token}` } : {};
const votesRes = await fetch( const votesRes = await fetch(
`${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${reviewId}")`, `${POCKETBASE_URL}/api/collections/review_votes/records?filter=(review="${reviewId}")`,
{} { headers: authHeaders }
); );
console.log('[ReviewVote API GET] Votes response:', votesRes.status);
let likes = 0; let likes = 0;
let dislikes = 0; let dislikes = 0;
if (votesRes.ok) { if (votesRes.ok) {
const votesData = await votesRes.json(); const votesData = await votesRes.json();
console.log('[ReviewVote API GET] Votes data:', JSON.stringify(votesData));
likes = votesData.items?.filter((v: any) => v.vote_type === 'likes').length || 0; likes = votesData.items?.filter((v: any) => v.vote_type === 'likes').length || 0;
dislikes = votesData.items?.filter((v: any) => v.vote_type === 'dislikes').length || 0; dislikes = votesData.items?.filter((v: any) => v.vote_type === 'dislikes').length || 0;
} }