feat(resenas): media en la cabecera, formulario bajo la barra y cajón solo de reseñas
- LocalCard: las estrellas de la media van arriba a la derecha, a la altura del título; el formulario de reseña se monta DEBAJO de la barra y solo al pulsar «Comentar», que queda en estado activo (aria-pressed). - ResenasLocal pasa a ser presentacional: el cajón animado revela SOLO el resto de reseñas y el control de ampliar/plegar es de ancho completo y va debajo de ellas (Ver las N reseñas / Ver menos). - Nuevo hook useResenas (dueño único del estado: lista, total, media, reseña propia, envío, borrado, reporte, error) y nuevo FormularioResena controlado. Desaparece el ref imperativo comentar(). - Tarjetas de comentario con padding uniforme y texto sin margen interno. - StarRating exporta TAMANO_ESTRELLAS (14) y lo usan media, tarjetas e input: un único tamaño. - Botones con hover/activo a superficie completa por clases CSS (.btn-hover, .btn-hover.activo, .btn-sobre-tarjeta, .btn-primario, .btn-verde); se retiran los background inline que anulaban el hover. 164/164 tests y build en verde.
This commit is contained in:
+20
@@ -47,6 +47,26 @@
|
|||||||
/* Foco visible en la barra de filtros: sus controles comparten inputStyle,
|
/* Foco visible en la barra de filtros: sus controles comparten inputStyle,
|
||||||
que anula el outline del navegador (el resto de botones lo conservan). */
|
que anula el outline del navegador (el resto de botones lo conservan). */
|
||||||
.barra-filtros :focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
.barra-filtros :focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
||||||
|
/* Respuesta visual de los botones de la tarjeta y las reseñas: el fondo
|
||||||
|
cubre TODA la superficie del botón (no solo el icono). Los botones sin
|
||||||
|
color propio usan .btn-hover; los que llevan color fijo, su clase. */
|
||||||
|
.btn-hover { background: transparent; transition: background-color 0.15s ease, color 0.15s ease; }
|
||||||
|
.btn-hover:not(:disabled):hover { background: var(--color-background-secondary); }
|
||||||
|
.btn-hover:not(:disabled):active { background: var(--color-border-tertiary); }
|
||||||
|
.btn-hover.activo { background: #FDEDEC; color: #8B0000; }
|
||||||
|
.btn-hover.activo:not(:disabled):hover { background: #FADBD8; }
|
||||||
|
.btn-hover.activo:not(:disabled):active { background: #F5B7B1; }
|
||||||
|
/* Botones que viven sobre una superficie secundaria (tarjetas de reseña):
|
||||||
|
el hover usa un tono más oscuro para que el cambio se note. */
|
||||||
|
.btn-hover.btn-sobre-tarjeta:not(:disabled):hover { background: var(--color-border-tertiary); }
|
||||||
|
.btn-hover.btn-sobre-tarjeta:not(:disabled):active { background: var(--color-border-secondary); }
|
||||||
|
.btn-primario { background: #8B0000; color: #ffffff; transition: background-color 0.15s ease; }
|
||||||
|
.btn-primario:not(:disabled):hover { background: #A31212; }
|
||||||
|
.btn-primario:not(:disabled):active { background: #7A0C0C; }
|
||||||
|
.btn-primario:disabled { background: var(--color-background-secondary); color: var(--color-text-tertiary); }
|
||||||
|
.btn-verde { background: #1E8449; color: #ffffff; transition: background-color 0.15s ease; }
|
||||||
|
.btn-verde:not(:disabled):hover { background: #229954; }
|
||||||
|
.btn-verde:not(:disabled):active { background: #196F3D; }
|
||||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import StarRating, { TAMANO_ESTRELLAS } from "./StarRating.jsx";
|
||||||
|
|
||||||
|
const MAX_COMENTARIO = 500;
|
||||||
|
|
||||||
|
// Formulario de reseña (anónima), controlado desde `useResenas` y montado por
|
||||||
|
// LocalCard DEBAJO de la barra de acciones: aparece solo al pulsar "Comentar".
|
||||||
|
// Estrellas y textarea reflejan el estado del hook, así que publicar deja el
|
||||||
|
// formulario en modo "Actualizar" sin lógica extra.
|
||||||
|
export default function FormularioResena({
|
||||||
|
puntuacion, setPuntuacion,
|
||||||
|
comentario, setComentario,
|
||||||
|
tienePropia, enviando, error,
|
||||||
|
onEnviar, onCerrar,
|
||||||
|
}) {
|
||||||
|
const contenedorRef = useRef(null);
|
||||||
|
|
||||||
|
// Al abrirse, el foco va a la primera estrella (como antes al expandir).
|
||||||
|
useEffect(() => {
|
||||||
|
contenedorRef.current?.querySelector("button")?.focus();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const puedePublicar = puntuacion >= 1 && !enviando;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={contenedorRef}
|
||||||
|
style={{
|
||||||
|
borderTop: "0.5px solid var(--color-border-tertiary)", paddingTop: 8,
|
||||||
|
display: "flex", flexDirection: "column", gap: 8,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p style={{ margin: 0, fontSize: 12, fontWeight: 500 }}>
|
||||||
|
{tienePropia ? "Tu reseña (anónima) — edítala o bórrala desde su tarjeta" : "Deja tu reseña (anónima)"}
|
||||||
|
</p>
|
||||||
|
{/* Las estrellas usan lineHeight 0 (caja de línea de altura 0: el glifo
|
||||||
|
desborda y se solapa con el título). El wrapper con lineHeight normal
|
||||||
|
aporta el soporte de línea que falta. */}
|
||||||
|
<div style={{ lineHeight: "22px" }}>
|
||||||
|
<StarRating value={puntuacion} onChange={setPuntuacion} size={TAMANO_ESTRELLAS} />
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
value={comentario}
|
||||||
|
onChange={(e) => setComentario(e.target.value)}
|
||||||
|
maxLength={MAX_COMENTARIO}
|
||||||
|
rows={2}
|
||||||
|
placeholder="Comentario opcional (máx. 500 caracteres)…"
|
||||||
|
aria-label="Comentario de la reseña"
|
||||||
|
style={{
|
||||||
|
fontSize: 12, padding: "5px 8px", borderRadius: "var(--border-radius-md)",
|
||||||
|
border: "0.5px solid var(--color-border-secondary)",
|
||||||
|
background: "var(--color-background-primary)", color: "var(--color-text-primary)",
|
||||||
|
resize: "vertical", fontFamily: "inherit",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{error && (
|
||||||
|
<p role="alert" style={{ margin: 0, fontSize: 12, color: "#922B21" }}>
|
||||||
|
<i className="ti ti-alert-triangle" aria-hidden="true"></i> {error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-primario"
|
||||||
|
onClick={onEnviar}
|
||||||
|
disabled={!puedePublicar}
|
||||||
|
style={{
|
||||||
|
fontSize: 12, border: "none", borderRadius: "var(--border-radius-md)",
|
||||||
|
padding: "5px 12px", cursor: puedePublicar ? "pointer" : "not-allowed", fontWeight: 500,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{enviando ? "Guardando…" : tienePropia ? "Actualizar" : "Publicar"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-hover"
|
||||||
|
onClick={onCerrar}
|
||||||
|
style={{
|
||||||
|
fontSize: 12, border: "0.5px solid var(--color-border-secondary)",
|
||||||
|
borderRadius: "var(--border-radius-md)", padding: "5px 12px", cursor: "pointer",
|
||||||
|
color: "var(--color-text-secondary)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Cerrar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { useRef, useState } from "react";
|
import { useState } from "react";
|
||||||
import CategoriaBadge from "./CategoriaBadge.jsx";
|
import CategoriaBadge from "./CategoriaBadge.jsx";
|
||||||
import ResenasLocal from "./ResenasLocal.jsx";
|
import ResenasLocal from "./ResenasLocal.jsx";
|
||||||
|
import FormularioResena from "./FormularioResena.jsx";
|
||||||
import ReportarLocal from "./ReportarLocal.jsx";
|
import ReportarLocal from "./ReportarLocal.jsx";
|
||||||
|
import StarRating, { TAMANO_ESTRELLAS } from "./StarRating.jsx";
|
||||||
import Toast from "./Toast.jsx";
|
import Toast from "./Toast.jsx";
|
||||||
import useFavoritos from "../hooks/useFavoritos.js";
|
import useFavoritos from "../hooks/useFavoritos.js";
|
||||||
|
import useResenas from "../hooks/useResenas.js";
|
||||||
import useToast from "../hooks/useToast.js";
|
import useToast from "../hooks/useToast.js";
|
||||||
import { confirmarLocal } from "../firebase.js";
|
import { confirmarLocal } from "../firebase.js";
|
||||||
import { enlaceGoogleMapsDesdeLocal, enlaceWazeDesdeLocal, formatearDistancia } from "../utils/geo.js";
|
import { enlaceGoogleMapsDesdeLocal, enlaceWazeDesdeLocal, formatearDistancia } from "../utils/geo.js";
|
||||||
@@ -26,16 +29,19 @@ function mesesDesde(fecha) {
|
|||||||
|
|
||||||
const botonBarra = (activo) => ({
|
const botonBarra = (activo) => ({
|
||||||
flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 2,
|
flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 2,
|
||||||
background: "none", border: "none", padding: "6px 2px 2px", cursor: "pointer",
|
border: "none", padding: "6px 2px 4px", cursor: "pointer",
|
||||||
|
borderRadius: "var(--border-radius-md)",
|
||||||
fontSize: 11, fontWeight: 500, lineHeight: 1.2,
|
fontSize: 11, fontWeight: 500, lineHeight: 1.2,
|
||||||
color: activo ? "#8B0000" : "var(--color-text-secondary)",
|
color: activo ? "#8B0000" : "var(--color-text-secondary)",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Tarjeta de local (rediseño de usabilidad): cabecera limpia (nombre y
|
// Tarjeta de local (rediseño de usabilidad): cabecera con nombre, provincia y
|
||||||
// provincia), categoría, dirección y enlaces; la DESCRIPCIÓN del local en
|
// las estrellas de la media arriba a la derecha a la altura del título;
|
||||||
// bloque propio ENCIMA de la sección de reseñas (vista previa de 2 + detalle
|
// categoría, dirección y enlaces; la DESCRIPCIÓN del local en bloque propio
|
||||||
// en `ResenasLocal`); fecha en pequeñito y, como pie, la barra inferior de
|
// ENCIMA de la sección de reseñas; fecha en pequeñito y, como pie, la barra
|
||||||
// acciones a ancho completo: Comentar · Reportar · Marcar · Compartir.
|
// inferior de acciones a ancho completo: Comentar · Reportar · Marcar ·
|
||||||
|
// Compartir. El formulario de reseña se monta DEBAJO de la barra cuando el
|
||||||
|
// usuario pulsa «Comentar» (que queda en estado activo).
|
||||||
export default function LocalCard({ local, distanciaKm }) {
|
export default function LocalCard({ local, distanciaKm }) {
|
||||||
const { esFavorito, alternarFavorito } = useFavoritos();
|
const { esFavorito, alternarFavorito } = useFavoritos();
|
||||||
const { toast, mostrarToast } = useToast();
|
const { toast, mostrarToast } = useToast();
|
||||||
@@ -43,7 +49,12 @@ export default function LocalCard({ local, distanciaKm }) {
|
|||||||
const [confirmado, setConfirmado] = useState(false);
|
const [confirmado, setConfirmado] = useState(false);
|
||||||
const [fechaConfirmacion, setFechaConfirmacion] = useState(local.fechaConfirmacion || local.fecha);
|
const [fechaConfirmacion, setFechaConfirmacion] = useState(local.fechaConfirmacion || local.fecha);
|
||||||
const [reportando, setReportando] = useState(false);
|
const [reportando, setReportando] = useState(false);
|
||||||
const resenasRef = useRef(null);
|
const [comentando, setComentando] = useState(false);
|
||||||
|
const {
|
||||||
|
resenas, cargando, total, media, reportada,
|
||||||
|
tienePropia, puntuacion, setPuntuacion, comentario, setComentario,
|
||||||
|
enviando, error, enviar, borrarPropia, reportar,
|
||||||
|
} = useResenas(local.id, { totalInicial: local.totalResenas || 0, mediaInicial: local.puntuacion || 0 });
|
||||||
|
|
||||||
const gmUrl = local.enlaceGoogleMaps || enlaceGoogleMapsDesdeLocal(local);
|
const gmUrl = local.enlaceGoogleMaps || enlaceGoogleMapsDesdeLocal(local);
|
||||||
const wazeUrl = enlaceWazeDesdeLocal(local);
|
const wazeUrl = enlaceWazeDesdeLocal(local);
|
||||||
@@ -92,13 +103,19 @@ export default function LocalCard({ local, distanciaKm }) {
|
|||||||
onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--color-border-secondary)"; }}
|
onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--color-border-secondary)"; }}
|
||||||
onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--color-border-tertiary)"; }}
|
onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--color-border-tertiary)"; }}
|
||||||
>
|
>
|
||||||
{/* Cabecera: solo nombre y provincia (las acciones viven en la barra inferior) */}
|
{/* Cabecera: nombre, provincia y las estrellas de la media arriba a la
|
||||||
<div>
|
derecha, a la altura del título */}
|
||||||
<p style={{ fontWeight: 500, fontSize: 16, margin: 0 }}>{local.nombre}</p>
|
<div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
|
||||||
<p style={{ fontSize: 13, color: "var(--color-text-secondary)", margin: "2px 0 0" }}>
|
<div style={{ minWidth: 0 }}>
|
||||||
{local.provincia}
|
<p style={{ fontWeight: 500, fontSize: 16, margin: 0 }}>{local.nombre}</p>
|
||||||
{distanciaKm != null && <span style={{ color: "var(--color-text-tertiary)" }}> · {formatearDistancia(distanciaKm)}</span>}
|
<p style={{ fontSize: 13, color: "var(--color-text-secondary)", margin: "2px 0 0" }}>
|
||||||
</p>
|
{local.provincia}
|
||||||
|
{distanciaKm != null && <span style={{ color: "var(--color-text-tertiary)" }}> · {formatearDistancia(distanciaKm)}</span>}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div style={{ flexShrink: 0, paddingTop: 2, lineHeight: 0 }}>
|
||||||
|
<StarRating value={media} readOnly size={TAMANO_ESTRELLAS} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CategoriaBadge categoria={local.categoria} subcategoria={local.subcategoria} />
|
<CategoriaBadge categoria={local.categoria} subcategoria={local.subcategoria} />
|
||||||
@@ -141,12 +158,15 @@ export default function LocalCard({ local, distanciaKm }) {
|
|||||||
<p style={{ fontSize: 13, color: "var(--color-text-secondary)", margin: 0, fontStyle: "italic" }}>"{local.descripcion}"</p>
|
<p style={{ fontSize: 13, color: "var(--color-text-secondary)", margin: 0, fontStyle: "italic" }}>"{local.descripcion}"</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Reseñas: vista previa de 2 + expansión animada (media y total aquí) */}
|
{/* Reseñas: vista previa + expansión animada solo del resto de reseñas
|
||||||
|
(la media va en la cabecera; el formulario, bajo la barra) */}
|
||||||
<ResenasLocal
|
<ResenasLocal
|
||||||
ref={resenasRef}
|
resenas={resenas}
|
||||||
localId={local.id}
|
cargando={cargando}
|
||||||
totalInicial={local.totalResenas || 0}
|
total={total}
|
||||||
mediaInicial={local.puntuacion || 0}
|
reportada={reportada}
|
||||||
|
onReportar={reportar}
|
||||||
|
onBorrar={borrarPropia}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{sinConfirmarReciente && !confirmado && (
|
{sinConfirmarReciente && !confirmado && (
|
||||||
@@ -154,8 +174,8 @@ export default function LocalCard({ local, distanciaKm }) {
|
|||||||
<span style={{ fontSize: 12, color: "#784212", display: "flex", alignItems: "center", gap: 5 }}>
|
<span style={{ fontSize: 12, color: "#784212", display: "flex", alignItems: "center", gap: 5 }}>
|
||||||
<i className="ti ti-clock-exclamation" aria-hidden="true"></i> Sin confirmar recientemente
|
<i className="ti ti-clock-exclamation" aria-hidden="true"></i> Sin confirmar recientemente
|
||||||
</span>
|
</span>
|
||||||
<button type="button" onClick={handleConfirmar} disabled={confirmando}
|
<button type="button" className="btn-verde" onClick={handleConfirmar} disabled={confirmando}
|
||||||
style={{ fontSize: 12, background: "#1E8449", color: "white", border: "none", borderRadius: "var(--border-radius-md)", padding: "4px 10px", cursor: "pointer", fontWeight: 500 }}>
|
style={{ fontSize: 12, border: "none", borderRadius: "var(--border-radius-md)", padding: "4px 10px", cursor: "pointer", fontWeight: 500 }}>
|
||||||
{confirmando ? "..." : "Sigue aquí ✅"}
|
{confirmando ? "..." : "Sigue aquí ✅"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -176,20 +196,31 @@ export default function LocalCard({ local, distanciaKm }) {
|
|||||||
|
|
||||||
{/* Barra inferior de acciones: cubre todo el pie de la tarjeta */}
|
{/* Barra inferior de acciones: cubre todo el pie de la tarjeta */}
|
||||||
<div style={{ display: "flex", gap: 2, marginTop: 2, paddingTop: 6, borderTop: "0.5px solid var(--color-border-tertiary)", flexWrap: "wrap" }}>
|
<div style={{ display: "flex", gap: 2, marginTop: 2, paddingTop: 6, borderTop: "0.5px solid var(--color-border-tertiary)", flexWrap: "wrap" }}>
|
||||||
<button type="button" onClick={() => resenasRef.current?.comentar()} style={botonBarra(false)}>
|
<button type="button" onClick={() => setComentando((v) => !v)} aria-pressed={comentando}
|
||||||
|
className={`btn-hover${comentando ? " activo" : ""}`} style={botonBarra(comentando)}>
|
||||||
<i className="ti ti-message-dots" aria-hidden="true" style={{ fontSize: 18 }}></i> Comentar
|
<i className="ti ti-message-dots" aria-hidden="true" style={{ fontSize: 18 }}></i> Comentar
|
||||||
</button>
|
</button>
|
||||||
<button type="button" onClick={() => setReportando(true)} style={botonBarra(false)}>
|
<button type="button" className="btn-hover" onClick={() => setReportando(true)} style={botonBarra(false)}>
|
||||||
<i className="ti ti-flag" aria-hidden="true" style={{ fontSize: 18 }}></i> Reportar
|
<i className="ti ti-flag" aria-hidden="true" style={{ fontSize: 18 }}></i> Reportar
|
||||||
</button>
|
</button>
|
||||||
<button type="button" onClick={handleAlternarFavorito} aria-pressed={favorito} style={botonBarra(favorito)}>
|
<button type="button" className={`btn-hover${favorito ? " activo" : ""}`} onClick={handleAlternarFavorito} aria-pressed={favorito} style={botonBarra(favorito)}>
|
||||||
<i className={`ti ${favorito ? "ti-heart-filled" : "ti-heart"}`} aria-hidden="true" style={{ fontSize: 18 }}></i> {favorito ? "Marcado" : "Marcar"}
|
<i className={`ti ${favorito ? "ti-heart-filled" : "ti-heart"}`} aria-hidden="true" style={{ fontSize: 18 }}></i> {favorito ? "Marcado" : "Marcar"}
|
||||||
</button>
|
</button>
|
||||||
<button type="button" onClick={compartir} style={botonBarra(false)}>
|
<button type="button" className="btn-hover" onClick={compartir} style={botonBarra(false)}>
|
||||||
<i className="ti ti-share-2" aria-hidden="true" style={{ fontSize: 18 }}></i> Compartir
|
<i className="ti ti-share-2" aria-hidden="true" style={{ fontSize: 18 }}></i> Compartir
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Formulario de reseña: DEBAJO de la barra y solo con «Comentar» */}
|
||||||
|
{comentando && (
|
||||||
|
<FormularioResena
|
||||||
|
puntuacion={puntuacion} setPuntuacion={setPuntuacion}
|
||||||
|
comentario={comentario} setComentario={setComentario}
|
||||||
|
tienePropia={tienePropia} enviando={enviando} error={error}
|
||||||
|
onEnviar={enviar} onCerrar={() => setComentando(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<Toast toast={toast} />
|
<Toast toast={toast} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
+58
-220
@@ -1,9 +1,6 @@
|
|||||||
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
|
import { useState } from "react";
|
||||||
import StarRating from "./StarRating.jsx";
|
import StarRating, { TAMANO_ESTRELLAS } from "./StarRating.jsx";
|
||||||
import { borrarResena, enviarResena, listarResenas, reportarLocal } from "../firebase.js";
|
|
||||||
import { obtenerDeviceId } from "../utils/dispositivo.js";
|
|
||||||
|
|
||||||
const MAX_COMENTARIO = 500;
|
|
||||||
// Reseñas visibles sin expandir (en fila, ocupando el ancho) y duración de
|
// Reseñas visibles sin expandir (en fila, ocupando el ancho) y duración de
|
||||||
// la animación de revelado (ms), sincronizada con la transición CSS.
|
// la animación de revelado (ms), sincronizada con la transición CSS.
|
||||||
const VISTA_PREVIA = 3;
|
const VISTA_PREVIA = 3;
|
||||||
@@ -21,7 +18,6 @@ function formatearFechaCorta(fecha) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const accionTarjeta = {
|
const accionTarjeta = {
|
||||||
background: "none",
|
|
||||||
border: "0.5px solid var(--color-border-secondary)",
|
border: "0.5px solid var(--color-border-secondary)",
|
||||||
borderRadius: "var(--border-radius-md)",
|
borderRadius: "var(--border-radius-md)",
|
||||||
padding: "2px 6px",
|
padding: "2px 6px",
|
||||||
@@ -32,23 +28,24 @@ const accionTarjeta = {
|
|||||||
|
|
||||||
// Tarjeta de reseña (celda del grid): estrellas, comentario acotado a 3
|
// Tarjeta de reseña (celda del grid): estrellas, comentario acotado a 3
|
||||||
// líneas, autor anónimo con huella + fecha corta y acciones por tarjeta —
|
// líneas, autor anónimo con huella + fecha corta y acciones por tarjeta —
|
||||||
// "Borrar" solo en las propias, "Reportar" solo en las ajenas.
|
// "Borrar" solo en las propias, "Reportar" solo en las ajenas. El padding es
|
||||||
|
// uniforme (12) y el texto no lleva margen propio para alinearse con el resto.
|
||||||
function Reseña({ r, reportada, onReportar, onBorrar }) {
|
function Reseña({ r, reportada, onReportar, onBorrar }) {
|
||||||
const autor = `Anónimo ${r.huella} · ${formatearFechaCorta(r.fecha)}${r.fechaEdicion ? " · ed." : ""}`;
|
const autor = `Anónimo ${r.huella} · ${formatearFechaCorta(r.fecha)}${r.fechaEdicion ? " · ed." : ""}`;
|
||||||
return (
|
return (
|
||||||
<div style={{
|
<div style={{
|
||||||
background: "var(--color-background-secondary)",
|
background: "var(--color-background-secondary)",
|
||||||
borderRadius: "var(--border-radius-md)",
|
borderRadius: "var(--border-radius-md)",
|
||||||
padding: "12px 12px 8px",
|
padding: 12,
|
||||||
display: "flex", flexDirection: "column", gap: 10, minWidth: 0,
|
display: "flex", flexDirection: "column", gap: 10, minWidth: 0,
|
||||||
border: r.esPropia ? "0.5px solid var(--color-border-secondary)" : "none",
|
border: r.esPropia ? "0.5px solid var(--color-border-secondary)" : "none",
|
||||||
}}>
|
}}>
|
||||||
<StarRating value={r.puntuacion} readOnly size={12} />
|
<StarRating value={r.puntuacion} readOnly size={TAMANO_ESTRELLAS} />
|
||||||
{r.comentario && (
|
{r.comentario && (
|
||||||
<p
|
<p
|
||||||
title={r.comentario}
|
title={r.comentario}
|
||||||
style={{
|
style={{
|
||||||
margin: 10, fontSize: 12, color: "var(--color-text-secondary)",
|
margin: 0, fontSize: 12, color: "var(--color-text-secondary)",
|
||||||
display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden",
|
display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -61,11 +58,11 @@ function Reseña({ r, reportada, onReportar, onBorrar }) {
|
|||||||
</span>
|
</span>
|
||||||
<span style={{ display: "flex", gap: 4, flexShrink: 0 }}>
|
<span style={{ display: "flex", gap: 4, flexShrink: 0 }}>
|
||||||
{r.esPropia ? (
|
{r.esPropia ? (
|
||||||
<button type="button" onClick={() => onBorrar(r)} style={{ ...accionTarjeta, color: "#922B21" }}>Borrar</button>
|
<button type="button" className="btn-hover btn-sobre-tarjeta" onClick={() => onBorrar(r)} style={{ ...accionTarjeta, color: "#922B21" }}>Borrar</button>
|
||||||
) : reportada === r.id ? (
|
) : reportada === r.id ? (
|
||||||
<span style={{ fontSize: 10, color: "#1E8449" }}>✅</span>
|
<span style={{ fontSize: 10, color: "#1E8449" }}>✅</span>
|
||||||
) : (
|
) : (
|
||||||
<button type="button" onClick={() => onReportar(r)} style={accionTarjeta}>Reportar</button>
|
<button type="button" className="btn-hover btn-sobre-tarjeta" onClick={() => onReportar(r)} style={accionTarjeta}>Reportar</button>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -74,139 +71,37 @@ function Reseña({ r, reportada, onReportar, onBorrar }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sección de reseñas de la tarjeta del local (issue #6 + rediseño de
|
// Sección de reseñas de la tarjeta del local (issue #6 + rediseño de
|
||||||
// usabilidad, iteración 2): carga al montar y muestra VISTA_PREVIA reseñas
|
// usabilidad): componente de presentación. Recibe las reseñas y el total del
|
||||||
// en fila ocupando el ancho; la cabecera "★ media · Reseñas (N)" alterna con
|
// hook `useResenas` (la media vive en la cabecera de la tarjeta) y muestra la
|
||||||
// una animación (grid-template-rows 0fr→1fr) que revela el resto en el mismo
|
// vista previa en fila; el cajón animado revela SOLO el resto de reseñas, con
|
||||||
// grid y el formulario inline PLANO (sin caja propia). Cierre por tres vías:
|
// el control de ampliar/plegar a ancho completo y debajo de ellas. El
|
||||||
// cabecera, "Comentar" (toggle, desde la barra de la tarjeta) y "Cerrar" en
|
// formulario de reseña no forma parte de esta sección (vive bajo la barra de
|
||||||
// el formulario. Identidad anónima con huella corta por local.
|
// acciones de la tarjeta).
|
||||||
const ResenasLocal = forwardRef(function ResenasLocal({ localId, totalInicial = 0, mediaInicial = 0 }, ref) {
|
export default function ResenasLocal({ resenas, cargando, total = 0, reportada, onReportar, onBorrar }) {
|
||||||
const [abierto, setAbierto] = useState(false);
|
const [abierto, setAbierto] = useState(false);
|
||||||
const [resenas, setResenas] = useState(null); // null = aún sin cargar
|
|
||||||
const [cargando, setCargando] = useState(false);
|
|
||||||
const [total, setTotal] = useState(totalInicial);
|
|
||||||
const [media, setMedia] = useState(mediaInicial);
|
|
||||||
const [tienePropia, setTienePropia] = useState(false);
|
|
||||||
const [puntuacion, setPuntuacion] = useState(0);
|
|
||||||
const [comentario, setComentario] = useState("");
|
|
||||||
const [enviando, setEnviando] = useState(false);
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
const [reportada, setReportada] = useState(null);
|
|
||||||
const formRef = useRef(null);
|
|
||||||
|
|
||||||
const cargar = async () => {
|
|
||||||
setCargando(true);
|
|
||||||
setError("");
|
|
||||||
try {
|
|
||||||
const datos = await listarResenas(localId, obtenerDeviceId());
|
|
||||||
setResenas(datos.resenas || []);
|
|
||||||
setTotal(datos.total || 0);
|
|
||||||
const propia = (datos.resenas || []).find((r) => r.esPropia);
|
|
||||||
setTienePropia(!!propia);
|
|
||||||
setPuntuacion(propia?.puntuacion || 0);
|
|
||||||
setComentario(propia?.comentario || "");
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
setError("No se pudieron cargar las reseñas.");
|
|
||||||
}
|
|
||||||
setCargando(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
// La vista previa debe existir sin interacción: carga al montar la tarjeta.
|
|
||||||
// Se refresca al expandir y tras cada escritura.
|
|
||||||
useEffect(() => { cargar(); /* eslint-disable-line react-hooks/exhaustive-deps */ }, []);
|
|
||||||
|
|
||||||
const expandir = (conFoco = false) => {
|
|
||||||
setAbierto(true);
|
|
||||||
if (conFoco) {
|
|
||||||
// Espera al fin de la transición para no pelearse con la animación.
|
|
||||||
setTimeout(() => {
|
|
||||||
formRef.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
|
||||||
formRef.current?.querySelector("button")?.focus();
|
|
||||||
}, DURACION_TRANSICION + 30);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// API imperativa para la barra de acciones de la tarjeta: ALTERNA (abre con
|
|
||||||
// foco / cierra). El cierre también está en la cabecera y en "Cerrar".
|
|
||||||
useImperativeHandle(ref, () => ({
|
|
||||||
comentar: () => (abierto ? setAbierto(false) : expandir(true)),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const alternar = () => {
|
|
||||||
if (abierto) {
|
|
||||||
setAbierto(false);
|
|
||||||
} else {
|
|
||||||
expandir(false);
|
|
||||||
if (resenas === null && !cargando) cargar();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const enviar = async () => {
|
|
||||||
if (puntuacion < 1) return;
|
|
||||||
setEnviando(true);
|
|
||||||
setError("");
|
|
||||||
try {
|
|
||||||
const datos = await enviarResena(localId, {
|
|
||||||
deviceId: obtenerDeviceId(),
|
|
||||||
puntuacion,
|
|
||||||
comentario: comentario.trim(),
|
|
||||||
});
|
|
||||||
setMedia(datos.media ?? media);
|
|
||||||
setTienePropia(true);
|
|
||||||
await cargar();
|
|
||||||
} catch (e) {
|
|
||||||
setError(e.message || "No se pudo guardar la reseña.");
|
|
||||||
}
|
|
||||||
setEnviando(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Borrado desde la propia tarjeta de reseña (solo propias).
|
|
||||||
const borrarPropia = async () => {
|
|
||||||
setEnviando(true);
|
|
||||||
setError("");
|
|
||||||
try {
|
|
||||||
const datos = await borrarResena(localId, obtenerDeviceId());
|
|
||||||
setMedia(datos.media ?? media);
|
|
||||||
setTienePropia(false);
|
|
||||||
setPuntuacion(0);
|
|
||||||
setComentario("");
|
|
||||||
await cargar();
|
|
||||||
} catch (e) {
|
|
||||||
setError(e.message || "No se pudo borrar la reseña.");
|
|
||||||
}
|
|
||||||
setEnviando(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const reportar = async (resena) => {
|
|
||||||
try {
|
|
||||||
await reportarLocal(localId, "inapropiado", "", resena.id);
|
|
||||||
setReportada(resena.id);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const lista = resenas || [];
|
const lista = resenas || [];
|
||||||
// La vista previa son siempre las primeras VISTA_PREVIA; el resto vive
|
// La vista previa son siempre las primeras VISTA_PREVIA; el resto vive
|
||||||
// dentro de la zona animada (se revela al expandir, sin duplicar render).
|
// dentro de la zona animada (se revela al expandir, sin duplicar render).
|
||||||
const visibles = lista.slice(0, VISTA_PREVIA);
|
const visibles = lista.slice(0, VISTA_PREVIA);
|
||||||
const resto = lista.slice(VISTA_PREVIA);
|
const resto = lista.slice(VISTA_PREVIA);
|
||||||
|
const puedeDesplegar = resto.length > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||||
{/* Cabecera plegable: media + número de reseñas */}
|
{/* Cabecera plegable: solo el total (la media está en la tarjeta) */}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={alternar}
|
className="btn-hover"
|
||||||
|
onClick={() => setAbierto((v) => !v)}
|
||||||
aria-expanded={abierto}
|
aria-expanded={abierto}
|
||||||
style={{
|
style={{
|
||||||
display: "flex", alignItems: "center", gap: 8, width: "fit-content",
|
display: "flex", alignItems: "center", gap: 4, width: "fit-content",
|
||||||
background: "none", border: "none", padding: 0, cursor: "pointer",
|
border: "none", padding: "2px 6px", marginLeft: -6,
|
||||||
|
borderRadius: "var(--border-radius-md)", cursor: "pointer",
|
||||||
fontSize: 12, color: "var(--color-text-secondary)",
|
fontSize: 12, color: "var(--color-text-secondary)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<StarRating value={media} readOnly size={14} />
|
|
||||||
<span>
|
<span>
|
||||||
Reseñas ({total})
|
Reseñas ({total})
|
||||||
<i
|
<i
|
||||||
@@ -226,105 +121,48 @@ const ResenasLocal = forwardRef(function ResenasLocal({ localId, totalInicial =
|
|||||||
Aún no hay reseñas. ¡Sé el primero!
|
Aún no hay reseñas. ¡Sé el primero!
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<div style={gridResenas} aria-label="Vista previa de reseñas">
|
<div style={gridResenas} aria-label="Reseñas del local">
|
||||||
{visibles.map((r) => <Reseña key={r.id} r={r} reportada={reportada} onReportar={reportar} onBorrar={borrarPropia} />)}
|
{visibles.map((r) => <Reseña key={r.id} r={r} reportada={reportada} onReportar={onReportar} onBorrar={onBorrar} />)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Pista de expansión cuando hay más reseñas que la vista previa */}
|
{/* Zona animada: SOLO el resto de reseñas. La altura anima de 0fr a
|
||||||
{!abierto && total > VISTA_PREVIA && (
|
1fr; el contenido permanece montado para que la transición sea
|
||||||
<button
|
fluida y se oculta del árbol accesible plegado. */}
|
||||||
type="button"
|
{puedeDesplegar && (
|
||||||
onClick={() => expandir(false)}
|
<div
|
||||||
|
aria-hidden={!abierto}
|
||||||
style={{
|
style={{
|
||||||
background: "none", border: "none", padding: 0, width: "fit-content",
|
display: "grid",
|
||||||
fontSize: 12, color: "#8B0000", cursor: "pointer", fontWeight: 500,
|
gridTemplateRows: abierto ? "1fr" : "0fr",
|
||||||
|
transition: `grid-template-rows ${DURACION_TRANSICION}ms ease`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Ver las {total} reseñas <i className="ti ti-chevron-down" aria-hidden="true"></i>
|
<div style={{ overflow: "hidden" }}>
|
||||||
</button>
|
<div style={{ ...gridResenas, paddingTop: abierto ? 8 : 0 }}>
|
||||||
)}
|
{resto.map((r) => <Reseña key={r.id} r={r} reportada={reportada} onReportar={onReportar} onBorrar={onBorrar} />)}
|
||||||
|
|
||||||
{/* Zona animada: resto de reseñas (mismo grid) + formulario plano. La
|
|
||||||
altura anima de 0fr a 1fr; el contenido permanece montado para que
|
|
||||||
la transición sea fluida y se oculta del árbol accesible plegado. */}
|
|
||||||
<div
|
|
||||||
aria-hidden={!abierto}
|
|
||||||
style={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateRows: abierto ? "1fr" : "0fr",
|
|
||||||
transition: `grid-template-rows ${DURACION_TRANSICION}ms ease`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div style={{ overflow: "hidden" }}>
|
|
||||||
<div style={{ display: "flex", flexDirection: "column", gap: 8, paddingTop: abierto ? 8 : 0 }}>
|
|
||||||
{resto.length > 0 && (
|
|
||||||
<div style={gridResenas}>
|
|
||||||
{resto.map((r) => <Reseña key={r.id} r={r} reportada={reportada} onReportar={reportar} onBorrar={borrarPropia} />)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Formulario inline PLANO (sin caja): solo un borde que lo separa */}
|
|
||||||
<div ref={formRef} style={{ paddingTop: 8, borderTop: "0.5px solid var(--color-border-tertiary)", display: "flex", flexDirection: "column", gap: 8 }}>
|
|
||||||
<p style={{ margin: 0, fontSize: 12, fontWeight: 500 }}>
|
|
||||||
{tienePropia ? "Tu reseña (anónima) — edítala o bórrala desde su tarjeta" : "Deja tu reseña (anónima)"}
|
|
||||||
</p>
|
|
||||||
{/* Las estrellas usan lineHeight 0 (caja de línea de altura 0:
|
|
||||||
el glifo desborda y se solapa con el título). El wrapper con
|
|
||||||
lineHeight normal aporta el soporte de línea que falta. */}
|
|
||||||
<div style={{ lineHeight: "26px" }}>
|
|
||||||
<StarRating value={puntuacion} onChange={setPuntuacion} size={20} />
|
|
||||||
</div>
|
|
||||||
<textarea
|
|
||||||
value={comentario}
|
|
||||||
onChange={(e) => setComentario(e.target.value)}
|
|
||||||
maxLength={MAX_COMENTARIO}
|
|
||||||
rows={2}
|
|
||||||
placeholder="Comentario opcional (máx. 500 caracteres)…"
|
|
||||||
aria-label="Comentario de la reseña"
|
|
||||||
style={{
|
|
||||||
fontSize: 12, padding: "5px 8px", borderRadius: "var(--border-radius-md)",
|
|
||||||
border: "0.5px solid var(--color-border-secondary)",
|
|
||||||
background: "var(--color-background-primary)", color: "var(--color-text-primary)",
|
|
||||||
resize: "vertical", fontFamily: "inherit",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{error && (
|
|
||||||
<p role="alert" style={{ margin: 0, fontSize: 12, color: "#922B21" }}>
|
|
||||||
<i className="ti ti-alert-triangle" aria-hidden="true"></i> {error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
<div style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={enviar}
|
|
||||||
disabled={puntuacion < 1 || enviando}
|
|
||||||
style={{
|
|
||||||
fontSize: 12, background: puntuacion >= 1 ? "#8B0000" : "var(--color-background-secondary)",
|
|
||||||
color: puntuacion >= 1 ? "white" : "var(--color-text-tertiary)",
|
|
||||||
border: "none", borderRadius: "var(--border-radius-md)", padding: "5px 12px",
|
|
||||||
cursor: puntuacion >= 1 && !enviando ? "pointer" : "not-allowed", fontWeight: 500,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{enviando ? "Guardando…" : tienePropia ? "Actualizar" : "Publicar"}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setAbierto(false)}
|
|
||||||
style={{
|
|
||||||
fontSize: 12, background: "none", border: "0.5px solid var(--color-border-secondary)",
|
|
||||||
borderRadius: "var(--border-radius-md)", padding: "5px 12px", cursor: "pointer",
|
|
||||||
color: "var(--color-text-secondary)",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Cerrar
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
|
|
||||||
|
{/* Control de expansión: debajo de las reseñas y a ancho completo */}
|
||||||
|
{puedeDesplegar && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-hover"
|
||||||
|
onClick={() => setAbierto((v) => !v)}
|
||||||
|
aria-expanded={abierto}
|
||||||
|
style={{
|
||||||
|
width: "100%", border: "0.5px solid var(--color-border-tertiary)",
|
||||||
|
borderRadius: "var(--border-radius-md)", padding: "6px 10px", fontSize: 12,
|
||||||
|
color: "#8B0000", cursor: "pointer", fontWeight: 500,
|
||||||
|
display: "flex", alignItems: "center", justifyContent: "center", gap: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{abierto ? "Ver menos" : `Ver las ${total} reseñas`}
|
||||||
|
<i className={`ti ${abierto ? "ti-chevron-up" : "ti-chevron-down"}`} aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
});
|
}
|
||||||
|
|
||||||
export default ResenasLocal;
|
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ import { useState } from "react";
|
|||||||
|
|
||||||
const ESTRELLAS = [1, 2, 3, 4, 5];
|
const ESTRELLAS = [1, 2, 3, 4, 5];
|
||||||
|
|
||||||
|
// Tamaño único de las estrellas de la tarjeta (media, tarjetas de reseña e
|
||||||
|
// input de valoración): evita que cada punto de uso elija el suyo.
|
||||||
|
export const TAMANO_ESTRELLAS = 14;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Muestra siempre 5 estrellas (usando el font icon de Tabler ya cargado en
|
* Muestra siempre 5 estrellas (usando el font icon de Tabler ya cargado en
|
||||||
* index.html, para no depender de una fuente/librería extra). Si no hay
|
* index.html, para no depender de una fuente/librería extra). Si no hay
|
||||||
@@ -13,7 +17,7 @@ const ESTRELLAS = [1, 2, 3, 4, 5];
|
|||||||
* - Modo edición (onChange): botones reales con role="radio" para que sea
|
* - Modo edición (onChange): botones reales con role="radio" para que sea
|
||||||
* utilizable con teclado y tenga foco visible.
|
* utilizable con teclado y tenga foco visible.
|
||||||
*/
|
*/
|
||||||
export default function StarRating({ value = 0, onChange, readOnly = false, size = 20 }) {
|
export default function StarRating({ value = 0, onChange, readOnly = false, size = TAMANO_ESTRELLAS }) {
|
||||||
const [valorHover, setValorHover] = useState(0);
|
const [valorHover, setValorHover] = useState(0);
|
||||||
const esInteractivo = !readOnly && typeof onChange === "function";
|
const esInteractivo = !readOnly && typeof onChange === "function";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { borrarResena, enviarResena, listarResenas, reportarLocal } from "../firebase.js";
|
||||||
|
import { obtenerDeviceId } from "../utils/dispositivo.js";
|
||||||
|
|
||||||
|
// Dueño único del estado de reseñas de un local: lista, total, media, la
|
||||||
|
// reseña propia (para precargar el formulario) y las acciones de escritura.
|
||||||
|
// Lo consume LocalCard y reparte los datos a ResenasLocal (lista desplegable)
|
||||||
|
// y a FormularioResena (formulario bajo la barra de acciones).
|
||||||
|
//
|
||||||
|
// La media no viene en el listado (`GET .../resenas` devuelve `{resenas,total}`);
|
||||||
|
// se toma de `mediaInicial` (la del local) y de la respuesta de cada escritura.
|
||||||
|
export default function useResenas(localId, { totalInicial = 0, mediaInicial = 0 } = {}) {
|
||||||
|
const [resenas, setResenas] = useState(null); // null = aún sin cargar
|
||||||
|
const [cargando, setCargando] = useState(false);
|
||||||
|
const [total, setTotal] = useState(totalInicial);
|
||||||
|
const [media, setMedia] = useState(mediaInicial);
|
||||||
|
const [tienePropia, setTienePropia] = useState(false);
|
||||||
|
const [puntuacion, setPuntuacion] = useState(0);
|
||||||
|
const [comentario, setComentario] = useState("");
|
||||||
|
const [enviando, setEnviando] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [reportada, setReportada] = useState(null);
|
||||||
|
|
||||||
|
const cargar = useCallback(async () => {
|
||||||
|
setCargando(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const datos = await listarResenas(localId, obtenerDeviceId());
|
||||||
|
const lista = datos.resenas || [];
|
||||||
|
setResenas(lista);
|
||||||
|
setTotal(datos.total ?? lista.length);
|
||||||
|
const propia = lista.find((r) => r.esPropia);
|
||||||
|
setTienePropia(!!propia);
|
||||||
|
setPuntuacion(propia?.puntuacion || 0);
|
||||||
|
setComentario(propia?.comentario || "");
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setError("No se pudieron cargar las reseñas.");
|
||||||
|
}
|
||||||
|
setCargando(false);
|
||||||
|
}, [localId]);
|
||||||
|
|
||||||
|
// La vista previa debe existir sin interacción: carga al montar la tarjeta.
|
||||||
|
useEffect(() => { cargar(); }, [cargar]);
|
||||||
|
|
||||||
|
const enviar = async () => {
|
||||||
|
if (puntuacion < 1) return;
|
||||||
|
setEnviando(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const datos = await enviarResena(localId, {
|
||||||
|
deviceId: obtenerDeviceId(),
|
||||||
|
puntuacion,
|
||||||
|
comentario: comentario.trim(),
|
||||||
|
});
|
||||||
|
setTienePropia(true);
|
||||||
|
if (typeof datos.media === "number") setMedia(datos.media);
|
||||||
|
await cargar();
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.message || "No se pudo guardar la reseña.");
|
||||||
|
}
|
||||||
|
setEnviando(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const borrarPropia = async () => {
|
||||||
|
setEnviando(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const datos = await borrarResena(localId, obtenerDeviceId());
|
||||||
|
if (typeof datos.media === "number") setMedia(datos.media);
|
||||||
|
await cargar();
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.message || "No se pudo borrar la reseña.");
|
||||||
|
}
|
||||||
|
setEnviando(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const reportar = async (resena) => {
|
||||||
|
try {
|
||||||
|
await reportarLocal(localId, "inapropiado", "", resena.id);
|
||||||
|
setReportada(resena.id);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
resenas, cargando, total, media, reportada,
|
||||||
|
tienePropia, puntuacion, setPuntuacion, comentario, setComentario,
|
||||||
|
enviando, error,
|
||||||
|
enviar, borrarPropia, reportar, cargar,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
|
||||||
|
import FormularioResena from "../../src/components/FormularioResena.jsx";
|
||||||
|
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
function renderFormulario(over = {}) {
|
||||||
|
const props = {
|
||||||
|
puntuacion: 0, setPuntuacion: vi.fn(),
|
||||||
|
comentario: "", setComentario: vi.fn(),
|
||||||
|
tienePropia: false, enviando: false, error: "",
|
||||||
|
onEnviar: vi.fn(), onCerrar: vi.fn(),
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
render(<FormularioResena {...props} />);
|
||||||
|
return props;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("FormularioResena (presentación)", () => {
|
||||||
|
it("estrellas 1–5, comentario, Publicar y Cerrar; el foco arranca en la primera estrella", () => {
|
||||||
|
renderFormulario();
|
||||||
|
|
||||||
|
expect(screen.getByRole("radiogroup", { name: /selecciona una puntuación/i })).toBeTruthy();
|
||||||
|
expect(screen.getAllByRole("radio")).toHaveLength(5);
|
||||||
|
expect(screen.getByLabelText(/comentario de la reseña/i)).toBeTruthy();
|
||||||
|
expect(screen.getByRole("button", { name: /publicar/i })).toBeTruthy();
|
||||||
|
expect(document.activeElement?.getAttribute("aria-label")).toMatch(/1 estrella/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Publicar está deshabilitado sin puntuación y se habilita con 1 o más", () => {
|
||||||
|
renderFormulario({ puntuacion: 0 });
|
||||||
|
expect(screen.getByRole("button", { name: /publicar/i }).disabled).toBe(true);
|
||||||
|
cleanup();
|
||||||
|
|
||||||
|
renderFormulario({ puntuacion: 3 });
|
||||||
|
expect(screen.getByRole("button", { name: /publicar/i }).disabled).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("con reseña propia muestra Actualizar y el aviso de edición", () => {
|
||||||
|
renderFormulario({ tienePropia: true, puntuacion: 5, comentario: "Mi favorito" });
|
||||||
|
|
||||||
|
expect(screen.getByText(/tu reseña \(anónima\)/i)).toBeTruthy();
|
||||||
|
expect(screen.getByRole("button", { name: /actualizar/i })).toBeTruthy();
|
||||||
|
expect(screen.getByLabelText(/comentario de la reseña/i).value).toBe("Mi favorito");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("los cambios de estrellas y comentario se notifican al dueño del estado", () => {
|
||||||
|
const props = renderFormulario();
|
||||||
|
fireEvent.click(screen.getByRole("radio", { name: "4 estrellas" }));
|
||||||
|
expect(props.setPuntuacion).toHaveBeenCalledWith(4);
|
||||||
|
fireEvent.change(screen.getByLabelText(/comentario de la reseña/i), { target: { value: "Buen sitio" } });
|
||||||
|
expect(props.setComentario).toHaveBeenCalledWith("Buen sitio");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("el error del servidor se muestra como aviso y Cerrar delega en el padre", () => {
|
||||||
|
const props = renderFormulario({ error: "El comentario contiene palabras no permitidas" });
|
||||||
|
|
||||||
|
expect(screen.getByRole("alert").textContent).toMatch(/no permitidas/i);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /cerrar/i }));
|
||||||
|
expect(props.onCerrar).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("enviar delega en el padre (y bloquea mientras guarda)", () => {
|
||||||
|
const props = renderFormulario({ puntuacion: 2, enviando: true });
|
||||||
|
|
||||||
|
const publicar = screen.getByRole("button", { name: /guardando/i });
|
||||||
|
expect(publicar.disabled).toBe(true);
|
||||||
|
cleanup();
|
||||||
|
|
||||||
|
const props2 = renderFormulario({ puntuacion: 2 });
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /publicar/i }));
|
||||||
|
expect(props2.onEnviar).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
// @vitest-environment jsdom
|
// @vitest-environment jsdom
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||||
|
|
||||||
// Mock del cliente API: LocalCard importa confirmarLocal vía firebase.js y
|
// Mock del cliente API: LocalCard importa confirmarLocal vía firebase.js y el
|
||||||
// ResenasLocal importa las funciones de reseñas por la misma vía.
|
// hook useResenas, las funciones de reseñas por la misma vía.
|
||||||
vi.mock("../../src/api.js", () => ({
|
vi.mock("../../src/api.js", () => ({
|
||||||
confirmarLocal: vi.fn(),
|
confirmarLocal: vi.fn(),
|
||||||
listarResenas: vi.fn(async () => ({ resenas: [], total: 0 })),
|
listarResenas: vi.fn(async () => ({ resenas: [], total: 0 })),
|
||||||
@@ -13,6 +13,7 @@ vi.mock("../../src/api.js", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
import LocalCard from "../../src/components/LocalCard.jsx";
|
import LocalCard from "../../src/components/LocalCard.jsx";
|
||||||
|
import { enviarResena, listarResenas } from "../../src/api.js";
|
||||||
|
|
||||||
beforeEach(() => { vi.clearAllMocks(); localStorage.clear(); });
|
beforeEach(() => { vi.clearAllMocks(); localStorage.clear(); });
|
||||||
afterEach(cleanup);
|
afterEach(cleanup);
|
||||||
@@ -24,6 +25,17 @@ const LOCAL = {
|
|||||||
fecha: "2026-10-01T10:00:00.000Z",
|
fecha: "2026-10-01T10:00:00.000Z",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const ISO = "2026-10-11T10:00:00.000Z";
|
||||||
|
const resena = (id, huella, puntuacion, comentario) => ({ id, huella, puntuacion, comentario, fecha: ISO, fechaEdicion: null, esPropia: false });
|
||||||
|
const CUATRO = [
|
||||||
|
resena("r1", "#111111", 5, "Uno"),
|
||||||
|
resena("r2", "#222222", 4, "Dos"),
|
||||||
|
resena("r3", "#333333", 3, "Tres"),
|
||||||
|
resena("r4", "#444444", 2, "Cuatro"),
|
||||||
|
];
|
||||||
|
|
||||||
|
const boton = (nombre) => screen.getByRole("button", { name: nombre });
|
||||||
|
|
||||||
describe("LocalCard (rediseño de usabilidad)", () => {
|
describe("LocalCard (rediseño de usabilidad)", () => {
|
||||||
it("la descripción va en bloque propio ENCIMA de la sección de reseñas", () => {
|
it("la descripción va en bloque propio ENCIMA de la sección de reseñas", () => {
|
||||||
render(<LocalCard local={LOCAL} />);
|
render(<LocalCard local={LOCAL} />);
|
||||||
@@ -43,6 +55,20 @@ describe("LocalCard (rediseño de usabilidad)", () => {
|
|||||||
expect(screen.getByText(/^publicado /i)).toBeTruthy();
|
expect(screen.getByText(/^publicado /i)).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("la media va arriba a la derecha de la cabecera, a la altura del título", () => {
|
||||||
|
render(<LocalCard local={LOCAL} />);
|
||||||
|
const estrellas = screen.getByRole("img", { name: /valoración: 4 de 5 estrellas/i });
|
||||||
|
const titulo = screen.getByText("Bar Prueba");
|
||||||
|
|
||||||
|
// mismo bloque de cabecera, después del nombre
|
||||||
|
const filaCabecera = titulo.closest("div").parentElement;
|
||||||
|
expect(filaCabecera.contains(estrellas)).toBe(true);
|
||||||
|
expect(titulo.compareDocumentPosition(estrellas) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||||
|
expect(filaCabecera.style.alignItems).toBe("flex-start");
|
||||||
|
// y no está en la sección de reseñas
|
||||||
|
expect(within(screen.getByRole("button", { name: /reseñas \(2\)/i })).queryByRole("img")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it("Marcar alterna el favorito (aria-pressed + persistencia)", () => {
|
it("Marcar alterna el favorito (aria-pressed + persistencia)", () => {
|
||||||
render(<LocalCard local={LOCAL} />);
|
render(<LocalCard local={LOCAL} />);
|
||||||
const marcar = screen.getByRole("button", { name: /^marcar$/i });
|
const marcar = screen.getByRole("button", { name: /^marcar$/i });
|
||||||
@@ -59,25 +85,79 @@ describe("LocalCard (rediseño de usabilidad)", () => {
|
|||||||
|
|
||||||
it("Reportar abre el formulario controlado encima de la barra; Cancelar lo cierra", () => {
|
it("Reportar abre el formulario controlado encima de la barra; Cancelar lo cierra", () => {
|
||||||
render(<LocalCard local={LOCAL} />);
|
render(<LocalCard local={LOCAL} />);
|
||||||
fireEvent.click(screen.getByRole("button", { name: /^reportar$/i }));
|
fireEvent.click(boton(/^reportar$/i));
|
||||||
expect(screen.getByText(/¿Qué está mal con este local\?/i)).toBeTruthy();
|
expect(screen.getByText(/¿Qué está mal con este local\?/i)).toBeTruthy();
|
||||||
|
|
||||||
fireEvent.click(screen.getByRole("button", { name: /cancelar/i }));
|
fireEvent.click(boton(/cancelar/i));
|
||||||
expect(screen.queryByText(/¿Qué está mal/i)).toBeNull();
|
expect(screen.queryByText(/¿Qué está mal/i)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Comentar expande la sección de reseñas y enfoca el formulario", async () => {
|
it("Comentar abre el formulario DEBAJO de la barra y el botón queda activo", async () => {
|
||||||
render(<LocalCard local={LOCAL} />);
|
render(<LocalCard local={LOCAL} />);
|
||||||
fireEvent.click(screen.getByRole("button", { name: /^comentar$/i }));
|
const comentar = boton(/^comentar$/i);
|
||||||
|
expect(comentar.getAttribute("aria-pressed")).toBe("false");
|
||||||
|
expect(screen.queryByLabelText(/comentario de la reseña/i)).toBeNull();
|
||||||
|
|
||||||
await waitFor(() => expect(screen.getByRole("button", { name: /publicar/i })).toBeTruthy(), { timeout: 3000 });
|
fireEvent.click(comentar);
|
||||||
|
const textarea = await screen.findByLabelText(/comentario de la reseña/i);
|
||||||
|
expect(screen.getByText(/deja tu reseña/i)).toBeTruthy();
|
||||||
|
|
||||||
|
// debajo de los botones: el formulario va después de la barra
|
||||||
|
const barra = comentar.parentElement;
|
||||||
|
expect(barra.compareDocumentPosition(textarea.closest("div")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||||
|
|
||||||
|
expect(comentar.getAttribute("aria-pressed")).toBe("true");
|
||||||
|
expect(comentar.className).toMatch(/activo/);
|
||||||
await waitFor(
|
await waitFor(
|
||||||
() => expect(document.activeElement?.getAttribute("aria-label")).toMatch(/1 estrella/),
|
() => expect(document.activeElement?.getAttribute("aria-label")).toMatch(/1 estrella/),
|
||||||
{ timeout: 3000 },
|
{ timeout: 3000 },
|
||||||
);
|
);
|
||||||
|
|
||||||
// Comentar ALTERNA: la segunda pulsación cierra la sección
|
// el botón activo se apaga al cerrar desde «Cerrar»
|
||||||
fireEvent.click(screen.getByRole("button", { name: /^comentar$/i }));
|
fireEvent.click(boton(/cerrar/i));
|
||||||
await waitFor(() => expect(screen.queryByRole("button", { name: /publicar/i })).toBeNull());
|
expect(screen.queryByLabelText(/comentario de la reseña/i)).toBeNull();
|
||||||
|
expect(boton(/^comentar$/i).getAttribute("aria-pressed")).toBe("false");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("expandir las reseñas no abre el formulario (solo amplía reseñas)", async () => {
|
||||||
|
listarResenas.mockResolvedValueOnce({ resenas: CUATRO, total: 4 });
|
||||||
|
render(<LocalCard local={LOCAL} />);
|
||||||
|
await screen.findByText("Uno");
|
||||||
|
|
||||||
|
fireEvent.click(await screen.findByRole("button", { name: /ver las 4 reseñas/i }));
|
||||||
|
expect(await screen.findByText("Cuatro")).toBeTruthy();
|
||||||
|
expect(screen.queryByLabelText(/comentario de la reseña/i)).toBeNull();
|
||||||
|
expect(screen.getByRole("button", { name: /ver menos/i })).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("publicar desde el formulario envía la reseña y refresca la tarjeta", async () => {
|
||||||
|
enviarResena.mockResolvedValue({ ok: true, media: 5, total: 1 });
|
||||||
|
render(<LocalCard local={LOCAL} />);
|
||||||
|
|
||||||
|
fireEvent.click(boton(/^comentar$/i));
|
||||||
|
await screen.findByRole("radio", { name: "5 estrellas" });
|
||||||
|
fireEvent.click(screen.getByRole("radio", { name: "5 estrellas" }));
|
||||||
|
fireEvent.click(boton(/publicar/i));
|
||||||
|
|
||||||
|
await waitFor(() => expect(enviarResena).toHaveBeenCalledWith("loc-1", {
|
||||||
|
deviceId: expect.any(String),
|
||||||
|
puntuacion: 5,
|
||||||
|
comentario: "",
|
||||||
|
}));
|
||||||
|
// la media de la cabecera se actualiza con la respuesta
|
||||||
|
await waitFor(() => expect(screen.getByRole("img", { name: /valoración: 5 de 5 estrellas/i })).toBeTruthy());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("los botones llevan hover a superficie completa (clase btn-hover / activo)", () => {
|
||||||
|
render(<LocalCard local={LOCAL} />);
|
||||||
|
const barra = boton(/^comentar$/i).parentElement;
|
||||||
|
for (const b of barra.querySelectorAll("button")) expect(b.className).toMatch(/btn-hover/);
|
||||||
|
|
||||||
|
fireEvent.click(boton(/^marcar$/i));
|
||||||
|
expect(boton(/marcado/i).className).toMatch(/activo/);
|
||||||
|
|
||||||
|
fireEvent.click(boton(/^comentar$/i));
|
||||||
|
expect(boton(/publicar/i).className).toMatch(/btn-primario/);
|
||||||
|
expect(boton(/cerrar/i).className).toMatch(/btn-hover/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,164 +1,109 @@
|
|||||||
// @vitest-environment jsdom
|
// @vitest-environment jsdom
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||||
|
|
||||||
// Mock del cliente API (firebase.js re-exporta api.js: el mock intercepta la
|
|
||||||
// resolución del módulo y cubre ambas vías).
|
|
||||||
vi.mock("../../src/api.js", () => ({
|
|
||||||
listarResenas: vi.fn(),
|
|
||||||
enviarResena: vi.fn(),
|
|
||||||
borrarResena: vi.fn(),
|
|
||||||
reportarLocal: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { createRef } from "react";
|
|
||||||
import ResenasLocal from "../../src/components/ResenasLocal.jsx";
|
import ResenasLocal from "../../src/components/ResenasLocal.jsx";
|
||||||
import { borrarResena, enviarResena, listarResenas, reportarLocal } from "../../src/api.js";
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
localStorage.clear();
|
|
||||||
});
|
|
||||||
afterEach(cleanup);
|
afterEach(cleanup);
|
||||||
|
|
||||||
const ISO = "2026-10-11T10:00:00.000Z";
|
const ISO = "2026-10-11T10:00:00.000Z";
|
||||||
const reseña = (id, huella, puntuacion, comentario, extra = {}) => ({
|
const resena = (id, huella, puntuacion, comentario, extra = {}) => ({
|
||||||
id, huella, puntuacion, comentario, fecha: ISO, fechaEdicion: null, esPropia: false, ...extra,
|
id, huella, puntuacion, comentario, fecha: ISO, fechaEdicion: null, esPropia: false, ...extra,
|
||||||
});
|
});
|
||||||
const CUATRO = [
|
const CUATRO = [
|
||||||
reseña("r1", "#111111", 5, "Uno"),
|
resena("r1", "#111111", 5, "Uno"),
|
||||||
reseña("r2", "#222222", 4, "Dos"),
|
resena("r2", "#222222", 4, "Dos"),
|
||||||
reseña("r3", "#333333", 3, "Tres"),
|
resena("r3", "#333333", 3, "Tres"),
|
||||||
reseña("r4", "#444444", 2, "Cuatro"),
|
resena("r4", "#444444", 2, "Cuatro"),
|
||||||
];
|
];
|
||||||
const PROPIA = reseña("r9", "#999999", 5, "Mi favorito", { esPropia: true });
|
const PROPIA = resena("r9", "#999999", 5, "Mi favorito", { esPropia: true });
|
||||||
|
|
||||||
const cabecera = () => screen.getByRole("button", { name: /reseñas \(\d+\)/i });
|
const cabecera = () => screen.getByRole("button", { name: /reseñas \(\d+\)/i });
|
||||||
|
const botonAmpliar = () => screen.getByRole("button", { name: /ver las \d+ reseñas/i });
|
||||||
|
|
||||||
describe("ResenasLocal (grid + cierre por tres vías)", () => {
|
describe("ResenasLocal (presentación)", () => {
|
||||||
it("carga al montar y muestra 3 en fila; la 4ª y el formulario quedan plegados", async () => {
|
it("vista previa de 3 en fila, sin estrellas de media y sin formulario", () => {
|
||||||
listarResenas.mockResolvedValue({ resenas: CUATRO, total: 4 });
|
render(<ResenasLocal resenas={CUATRO} total={4} />);
|
||||||
render(<ResenasLocal localId="loc-1" totalInicial={4} mediaInicial={4} />);
|
|
||||||
|
|
||||||
await waitFor(() => expect(listarResenas).toHaveBeenCalledWith("loc-1", expect.any(String)));
|
const previa = screen.getByLabelText(/reseñas del local/i);
|
||||||
expect(await screen.findByText("Uno")).toBeTruthy();
|
expect(within(previa).getByText("Uno")).toBeTruthy();
|
||||||
expect(screen.getByText("Dos")).toBeTruthy();
|
expect(within(previa).getByText("Tres")).toBeTruthy();
|
||||||
expect(screen.getByText("Tres")).toBeTruthy();
|
// la 4ª vive en el cajón plegado
|
||||||
|
|
||||||
// la vista previa contiene solo las 3 primeras
|
|
||||||
const previa = screen.getByLabelText(/vista previa de reseñas/i);
|
|
||||||
expect(within(previa).queryByText("Cuatro")).toBeNull();
|
expect(within(previa).queryByText("Cuatro")).toBeNull();
|
||||||
// pista y formulario plegado (aria-hidden excluye los roles)
|
// la media NO está en la sección (vive en la cabecera de la tarjeta)
|
||||||
expect(screen.getByRole("button", { name: /ver las 4 reseñas/i })).toBeTruthy();
|
expect(within(cabecera()).queryByRole("img")).toBeNull();
|
||||||
expect(screen.queryByRole("button", { name: /publicar/i })).toBeNull();
|
// no hay formulario de reseña
|
||||||
|
expect(screen.queryByRole("radio")).toBeNull();
|
||||||
|
expect(screen.queryByLabelText(/comentario de la reseña/i)).toBeNull();
|
||||||
expect(cabecera().getAttribute("aria-expanded")).toBe("false");
|
expect(cabecera().getAttribute("aria-expanded")).toBe("false");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("expandir revela el resto en el mismo grid y el formulario; la cabecera vuelve a cerrar", async () => {
|
it("el control de ampliar va debajo de las reseñas y a ancho completo", () => {
|
||||||
listarResenas.mockResolvedValue({ resenas: CUATRO, total: 4 });
|
render(<ResenasLocal resenas={CUATRO} total={4} />);
|
||||||
render(<ResenasLocal localId="loc-1" />);
|
|
||||||
await screen.findByText("Uno");
|
const boton = botonAmpliar();
|
||||||
|
const previa = screen.getByLabelText(/reseñas del local/i);
|
||||||
|
expect(previa.compareDocumentPosition(boton) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||||
|
expect(boton.style.width).toBe("100%");
|
||||||
|
expect(boton.getAttribute("aria-expanded")).toBe("false");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("expandir revela SOLO el resto de reseñas (sin formulario) y pasa a «Ver menos»", () => {
|
||||||
|
render(<ResenasLocal resenas={CUATRO} total={4} />);
|
||||||
|
|
||||||
|
fireEvent.click(botonAmpliar());
|
||||||
|
expect(screen.getByText("Cuatro")).toBeTruthy();
|
||||||
|
expect(screen.queryByRole("radio")).toBeNull();
|
||||||
|
expect(screen.queryByLabelText(/comentario de la reseña/i)).toBeNull();
|
||||||
|
expect(screen.getByRole("button", { name: /ver menos/i })).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("la cabecera también alterna el plegado", () => {
|
||||||
|
render(<ResenasLocal resenas={CUATRO} total={4} />);
|
||||||
|
|
||||||
fireEvent.click(cabecera());
|
fireEvent.click(cabecera());
|
||||||
expect(await screen.findByText("Cuatro")).toBeTruthy();
|
|
||||||
expect(screen.getByRole("button", { name: /publicar/i })).toBeTruthy();
|
|
||||||
expect(screen.getByRole("button", { name: /cerrar/i })).toBeTruthy();
|
|
||||||
expect(screen.queryByRole("button", { name: /ver las 4 reseñas/i })).toBeNull();
|
|
||||||
expect(cabecera().getAttribute("aria-expanded")).toBe("true");
|
expect(cabecera().getAttribute("aria-expanded")).toBe("true");
|
||||||
|
expect(screen.getByRole("button", { name: /ver menos/i })).toBeTruthy();
|
||||||
|
|
||||||
// cierre vía cabecera
|
|
||||||
fireEvent.click(cabecera());
|
fireEvent.click(cabecera());
|
||||||
expect(cabecera().getAttribute("aria-expanded")).toBe("false");
|
expect(cabecera().getAttribute("aria-expanded")).toBe("false");
|
||||||
expect(screen.queryByRole("button", { name: /publicar/i })).toBeNull();
|
expect(screen.getByRole("button", { name: /ver las 4 reseñas/i })).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("el botón Cerrar del formulario pliega la sección", async () => {
|
it("sin reseñas que desplegar no aparece el control de ancho completo", () => {
|
||||||
listarResenas.mockResolvedValue({ resenas: CUATRO, total: 4 });
|
render(<ResenasLocal resenas={CUATRO.slice(0, 3)} total={3} />);
|
||||||
render(<ResenasLocal localId="loc-1" />);
|
expect(screen.queryByRole("button", { name: /ver las 3 reseñas/i })).toBeNull();
|
||||||
await screen.findByText("Uno");
|
expect(screen.queryByRole("button", { name: /ver menos/i })).toBeNull();
|
||||||
|
|
||||||
fireEvent.click(cabecera());
|
|
||||||
fireEvent.click(await screen.findByRole("button", { name: /cerrar/i }));
|
|
||||||
expect(cabecera().getAttribute("aria-expanded")).toBe("false");
|
|
||||||
expect(screen.queryByRole("button", { name: /publicar/i })).toBeNull();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("comentar() (barra de acciones) alterna: abre con foco y vuelve a cerrar", async () => {
|
it("la reseña propia ofrece Borrar y la ajena Reportar (o el ✅ si ya se reportó)", () => {
|
||||||
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
const onBorrar = vi.fn();
|
||||||
const ref = createRef();
|
const onReportar = vi.fn();
|
||||||
render(<ResenasLocal ref={ref} localId="loc-1" />);
|
render(<ResenasLocal resenas={[PROPIA, CUATRO[0]]} total={2} onBorrar={onBorrar} onReportar={onReportar} />);
|
||||||
await waitFor(() => expect(listarResenas).toHaveBeenCalled());
|
|
||||||
|
|
||||||
act(() => ref.current.comentar());
|
const previa = screen.getByLabelText(/reseñas del local/i);
|
||||||
await waitFor(() => expect(screen.getByRole("button", { name: /publicar/i })).toBeTruthy(), { timeout: 3000 });
|
const tarjetaPropia = within(previa).getByText("Mi favorito").closest("div");
|
||||||
await waitFor(
|
expect(within(tarjetaPropia).getByText(/^tú$/i)).toBeTruthy();
|
||||||
() => expect(document.activeElement?.getAttribute("aria-label")).toMatch(/1 estrella/),
|
fireEvent.click(within(tarjetaPropia).getByRole("button", { name: /borrar/i }));
|
||||||
{ timeout: 3000 },
|
expect(onBorrar).toHaveBeenCalledWith(PROPIA);
|
||||||
);
|
|
||||||
|
|
||||||
act(() => ref.current.comentar());
|
const tarjetaAjena = within(previa).getByText("Uno").closest("div");
|
||||||
await waitFor(() => expect(screen.queryByRole("button", { name: /publicar/i })).toBeNull());
|
fireEvent.click(within(tarjetaAjena).getByRole("button", { name: /reportar/i }));
|
||||||
});
|
expect(onReportar).toHaveBeenCalledWith(CUATRO[0]);
|
||||||
|
cleanup();
|
||||||
it("elegir estrellas y publicar llama a enviarResena con el deviceId", async () => {
|
|
||||||
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
|
||||||
enviarResena.mockResolvedValue({ ok: true, media: 4, total: 1 });
|
|
||||||
render(<ResenasLocal localId="loc-1" />);
|
|
||||||
await screen.findByText(/aún no hay reseñas/i);
|
|
||||||
|
|
||||||
fireEvent.click(cabecera());
|
|
||||||
fireEvent.click(await screen.findByRole("radio", { name: "4 estrellas" }));
|
|
||||||
fireEvent.change(screen.getByLabelText(/comentario de la reseña/i), { target: { value: "Muy bien" } });
|
|
||||||
fireEvent.click(screen.getByRole("button", { name: /publicar/i }));
|
|
||||||
|
|
||||||
await waitFor(() => expect(enviarResena).toHaveBeenCalledWith("loc-1", {
|
|
||||||
deviceId: expect.any(String),
|
|
||||||
puntuacion: 4,
|
|
||||||
comentario: "Muy bien",
|
|
||||||
}));
|
|
||||||
expect(localStorage.getItem("localesp_device_id")).toMatch(/./);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("la propia aparece como «Tú» con botón Borrar en su tarjeta; el formulario se precarga (Actualizar)", async () => {
|
|
||||||
listarResenas.mockResolvedValue({ resenas: [PROPIA], total: 1 });
|
|
||||||
borrarResena.mockResolvedValue({ ok: true, media: 0, total: 0 });
|
|
||||||
render(<ResenasLocal localId="loc-1" totalInicial={1} mediaInicial={5} />);
|
|
||||||
const previa = screen.getByLabelText(/vista previa de reseñas/i);
|
|
||||||
await waitFor(() => expect(within(previa).getByText("Mi favorito")).toBeTruthy());
|
|
||||||
|
|
||||||
// tarjeta propia en la vista previa: etiqueta «Tú» + Borrar (sin Reportar)
|
|
||||||
const tarjeta = within(previa).getByText("Mi favorito").closest("div");
|
|
||||||
expect(within(tarjeta).getByText(/^tú$/i)).toBeTruthy();
|
|
||||||
fireEvent.click(within(tarjeta).getByRole("button", { name: /borrar/i }));
|
|
||||||
await waitFor(() => expect(borrarResena).toHaveBeenCalledWith("loc-1", expect.any(String)));
|
|
||||||
|
|
||||||
// el formulario expandido sigue precargando la propia (Actualizar)
|
|
||||||
fireEvent.click(cabecera());
|
|
||||||
expect(await screen.findByRole("button", { name: /actualizar/i })).toBeTruthy();
|
|
||||||
expect(screen.getByLabelText(/comentario de la reseña/i).value).toBe("Mi favorito");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("las reseñas ajenas tienen botón Reportar por tarjeta y queda marcada", async () => {
|
|
||||||
listarResenas.mockResolvedValue({ resenas: [CUATRO[0]], total: 1 });
|
|
||||||
reportarLocal.mockResolvedValue({ ok: true });
|
|
||||||
render(<ResenasLocal localId="loc-1" />);
|
|
||||||
await screen.findByText("Uno");
|
|
||||||
|
|
||||||
|
render(<ResenasLocal resenas={[CUATRO[0]]} total={1} reportada="r1" />);
|
||||||
const tarjeta = screen.getByText("Uno").closest("div");
|
const tarjeta = screen.getByText("Uno").closest("div");
|
||||||
fireEvent.click(within(tarjeta).getByRole("button", { name: /reportar/i }));
|
expect(within(tarjeta).getByText("✅")).toBeTruthy();
|
||||||
await waitFor(() => expect(reportarLocal).toHaveBeenCalledWith("loc-1", "inapropiado", "", "r1"));
|
expect(within(tarjeta).queryByRole("button", { name: /reportar/i })).toBeNull();
|
||||||
await waitFor(() => expect(within(tarjeta).getByText("✅")).toBeTruthy());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("errores del servidor (palabras no permitidas, 429) se muestran como aviso", async () => {
|
it("estados de carga y sin reseñas", () => {
|
||||||
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
render(<ResenasLocal resenas={null} cargando total={0} />);
|
||||||
enviarResena.mockRejectedValue(new Error("El comentario contiene palabras no permitidas"));
|
expect(screen.getByText(/cargando reseñas/i)).toBeTruthy();
|
||||||
render(<ResenasLocal localId="loc-1" />);
|
cleanup();
|
||||||
await screen.findByText(/aún no hay reseñas/i);
|
|
||||||
|
|
||||||
fireEvent.click(cabecera());
|
render(<ResenasLocal resenas={[]} total={0} />);
|
||||||
fireEvent.click(await screen.findByRole("radio", { name: "3 estrellas" }));
|
expect(screen.getByText(/aún no hay reseñas/i)).toBeTruthy();
|
||||||
fireEvent.click(screen.getByRole("button", { name: /publicar/i }));
|
|
||||||
expect((await screen.findByRole("alert")).textContent).toMatch(/no permitidas/i);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
|
||||||
|
|
||||||
|
// Mock del cliente API (firebase.js re-exporta api.js: el mock intercepta la
|
||||||
|
// resolución del módulo y cubre ambas vías).
|
||||||
|
vi.mock("../../src/api.js", () => ({
|
||||||
|
listarResenas: vi.fn(),
|
||||||
|
enviarResena: vi.fn(),
|
||||||
|
borrarResena: vi.fn(),
|
||||||
|
reportarLocal: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import useResenas from "../../src/hooks/useResenas.js";
|
||||||
|
import { borrarResena, enviarResena, listarResenas, reportarLocal } from "../../src/api.js";
|
||||||
|
|
||||||
|
const ISO = "2026-10-11T10:00:00.000Z";
|
||||||
|
const PROPIA = { id: "r9", huella: "#999999", puntuacion: 5, comentario: "Mi favorito", fecha: ISO, fechaEdicion: null, esPropia: true };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
describe("useResenas (dueño único del estado de reseñas)", () => {
|
||||||
|
it("carga al montar y precarga la reseña propia", async () => {
|
||||||
|
listarResenas.mockResolvedValue({ resenas: [PROPIA], total: 1 });
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1", { totalInicial: 1, mediaInicial: 4 }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(result.current.resenas).not.toBeNull());
|
||||||
|
expect(listarResenas).toHaveBeenCalledWith("loc-1", expect.any(String));
|
||||||
|
expect(result.current.cargando).toBe(false);
|
||||||
|
expect(result.current.total).toBe(1);
|
||||||
|
// La media la aporta el local (el listado no la devuelve)
|
||||||
|
expect(result.current.media).toBe(4);
|
||||||
|
expect(result.current.tienePropia).toBe(true);
|
||||||
|
expect(result.current.puntuacion).toBe(5);
|
||||||
|
expect(result.current.comentario).toBe("Mi favorito");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("enviar manda el deviceId y refresca lista, media y total", async () => {
|
||||||
|
listarResenas
|
||||||
|
.mockResolvedValueOnce({ resenas: [], total: 0 })
|
||||||
|
.mockResolvedValueOnce({ resenas: [PROPIA], total: 1 });
|
||||||
|
enviarResena.mockResolvedValue({ ok: true, media: 4, total: 1 });
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1"));
|
||||||
|
await waitFor(() => expect(result.current.resenas).toEqual([]));
|
||||||
|
|
||||||
|
act(() => { result.current.setPuntuacion(4); result.current.setComentario("Muy bien"); });
|
||||||
|
await act(async () => { await result.current.enviar(); });
|
||||||
|
|
||||||
|
expect(enviarResena).toHaveBeenCalledWith("loc-1", {
|
||||||
|
deviceId: expect.any(String),
|
||||||
|
puntuacion: 4,
|
||||||
|
comentario: "Muy bien",
|
||||||
|
});
|
||||||
|
expect(result.current.media).toBe(4);
|
||||||
|
expect(result.current.total).toBe(1);
|
||||||
|
expect(result.current.tienePropia).toBe(true);
|
||||||
|
expect(listarResenas).toHaveBeenCalledTimes(2);
|
||||||
|
expect(localStorage.getItem("localesp_device_id")).toMatch(/./);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sin puntuación no envía", async () => {
|
||||||
|
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1"));
|
||||||
|
await waitFor(() => expect(result.current.resenas).toEqual([]));
|
||||||
|
|
||||||
|
await act(async () => { await result.current.enviar(); });
|
||||||
|
expect(enviarResena).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("el error del servidor se expone como mensaje", async () => {
|
||||||
|
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
||||||
|
enviarResena.mockRejectedValue(new Error("El comentario contiene palabras no permitidas"));
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1"));
|
||||||
|
await waitFor(() => expect(result.current.resenas).toEqual([]));
|
||||||
|
act(() => result.current.setPuntuacion(3));
|
||||||
|
await act(async () => { await result.current.enviar(); });
|
||||||
|
|
||||||
|
expect(result.current.error).toMatch(/no permitidas/i);
|
||||||
|
expect(result.current.enviando).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("borrar la propia recalcula la media y limpia el formulario", async () => {
|
||||||
|
listarResenas
|
||||||
|
.mockResolvedValueOnce({ resenas: [PROPIA], total: 1 })
|
||||||
|
.mockResolvedValueOnce({ resenas: [], total: 0 });
|
||||||
|
borrarResena.mockResolvedValue({ ok: true, media: 0, total: 0 });
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1", { totalInicial: 1, mediaInicial: 5 }));
|
||||||
|
await waitFor(() => expect(result.current.tienePropia).toBe(true));
|
||||||
|
|
||||||
|
await act(async () => { await result.current.borrarPropia(); });
|
||||||
|
expect(borrarResena).toHaveBeenCalledWith("loc-1", expect.any(String));
|
||||||
|
expect(result.current.media).toBe(0);
|
||||||
|
expect(result.current.tienePropia).toBe(false);
|
||||||
|
expect(result.current.puntuacion).toBe(0);
|
||||||
|
expect(result.current.comentario).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reportar marca la reseña reportada", async () => {
|
||||||
|
listarResenas.mockResolvedValue({ resenas: [{ id: "r1", huella: "#111", puntuacion: 5, comentario: "Uno", fecha: ISO, esPropia: false }], total: 1 });
|
||||||
|
reportarLocal.mockResolvedValue({ ok: true });
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1"));
|
||||||
|
await waitFor(() => expect(result.current.resenas?.length).toBe(1));
|
||||||
|
await act(async () => { await result.current.reportar(result.current.resenas[0]); });
|
||||||
|
|
||||||
|
expect(reportarLocal).toHaveBeenCalledWith("loc-1", "inapropiado", "", "r1");
|
||||||
|
expect(result.current.reportada).toBe("r1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("si falla la carga lo avisa y deja de cargar", async () => {
|
||||||
|
listarResenas.mockRejectedValue(new Error("boom"));
|
||||||
|
const { result } = renderHook(() => useResenas("loc-1"));
|
||||||
|
|
||||||
|
await waitFor(() => expect(result.current.error).toMatch(/no se pudieron cargar/i));
|
||||||
|
expect(result.current.cargando).toBe(false);
|
||||||
|
expect(result.current.resenas).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user