deploy-branch / deploy (push) Successful in 2m43s
deploy-branch / teardown (push) Skipped
tests / Unitarias + componente + build (pull_request) Failing after 3m3s
tests / Integración (Nominatim real, opt-in) (pull_request) Skipped
tests / Unitarias + componente + build (push) Failing after 3m5s
tests / Integración (Nominatim real, opt-in) (push) Skipped
- 15px → 12px 12px 8px (punto medio tras el ajuste manual a 15) - el formulario delinea las estrellas con un soporte de línea (lineHeight 26px): con lineHeight 0 la caja mide 0 y el glifo se solapaba con 'Deja tu reseña'; además gap 6→8
331 lines
13 KiB
React
331 lines
13 KiB
React
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
|
|
import StarRating 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
|
|
// la animación de revelado (ms), sincronizada con la transición CSS.
|
|
const VISTA_PREVIA = 3;
|
|
const DURACION_TRANSICION = 350;
|
|
|
|
const gridResenas = {
|
|
display: "grid",
|
|
gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))",
|
|
gap: 6,
|
|
};
|
|
|
|
function formatearFechaCorta(fecha) {
|
|
const d = new Date(fecha);
|
|
return Number.isNaN(d.getTime()) ? "" : d.toLocaleDateString("es-ES", { day: "numeric", month: "short" });
|
|
}
|
|
|
|
const accionTarjeta = {
|
|
background: "none",
|
|
border: "0.5px solid var(--color-border-secondary)",
|
|
borderRadius: "var(--border-radius-md)",
|
|
padding: "2px 6px",
|
|
fontSize: 10,
|
|
cursor: "pointer",
|
|
color: "var(--color-text-secondary)",
|
|
};
|
|
|
|
// 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 —
|
|
// "Borrar" solo en las propias, "Reportar" solo en las ajenas.
|
|
function Reseña({ r, reportada, onReportar, onBorrar }) {
|
|
const autor = `Anónimo ${r.huella} · ${formatearFechaCorta(r.fecha)}${r.fechaEdicion ? " · ed." : ""}`;
|
|
return (
|
|
<div style={{
|
|
background: "var(--color-background-secondary)",
|
|
borderRadius: "var(--border-radius-md)",
|
|
padding: "12px 12px 8px",
|
|
display: "flex", flexDirection: "column", gap: 10, minWidth: 0,
|
|
border: r.esPropia ? "0.5px solid var(--color-border-secondary)" : "none",
|
|
}}>
|
|
<StarRating value={r.puntuacion} readOnly size={12} />
|
|
{r.comentario && (
|
|
<p
|
|
title={r.comentario}
|
|
style={{
|
|
margin: 10, fontSize: 12, color: "var(--color-text-secondary)",
|
|
display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden",
|
|
}}
|
|
>
|
|
{r.comentario}
|
|
</p>
|
|
)}
|
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 4, marginTop: "auto", flexWrap: "wrap" }}>
|
|
<span title={autor} style={{ fontSize: 10, color: "var(--color-text-tertiary)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", minWidth: 0 }}>
|
|
{r.esPropia ? "Tú" : `Anónimo ${r.huella}`}
|
|
</span>
|
|
<span style={{ display: "flex", gap: 4, flexShrink: 0 }}>
|
|
{r.esPropia ? (
|
|
<button type="button" onClick={() => onBorrar(r)} style={{ ...accionTarjeta, color: "#922B21" }}>Borrar</button>
|
|
) : reportada === r.id ? (
|
|
<span style={{ fontSize: 10, color: "#1E8449" }}>✅</span>
|
|
) : (
|
|
<button type="button" onClick={() => onReportar(r)} style={accionTarjeta}>Reportar</button>
|
|
)}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// 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
|
|
// en fila ocupando el ancho; la cabecera "★ media · Reseñas (N)" alterna con
|
|
// una animación (grid-template-rows 0fr→1fr) que revela el resto en el mismo
|
|
// grid y el formulario inline PLANO (sin caja propia). Cierre por tres vías:
|
|
// cabecera, "Comentar" (toggle, desde la barra de la tarjeta) y "Cerrar" en
|
|
// el formulario. Identidad anónima con huella corta por local.
|
|
const ResenasLocal = forwardRef(function ResenasLocal({ localId, totalInicial = 0, mediaInicial = 0 }, ref) {
|
|
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 || [];
|
|
// La vista previa son siempre las primeras VISTA_PREVIA; el resto vive
|
|
// dentro de la zona animada (se revela al expandir, sin duplicar render).
|
|
const visibles = lista.slice(0, VISTA_PREVIA);
|
|
const resto = lista.slice(VISTA_PREVIA);
|
|
|
|
return (
|
|
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
|
{/* Cabecera plegable: media + número de reseñas */}
|
|
<button
|
|
type="button"
|
|
onClick={alternar}
|
|
aria-expanded={abierto}
|
|
style={{
|
|
display: "flex", alignItems: "center", gap: 8, width: "fit-content",
|
|
background: "none", border: "none", padding: 0, cursor: "pointer",
|
|
fontSize: 12, color: "var(--color-text-secondary)",
|
|
}}
|
|
>
|
|
<StarRating value={media} readOnly size={14} />
|
|
<span>
|
|
Reseñas ({total})
|
|
<i
|
|
className={`ti ${abierto ? "ti-chevron-up" : "ti-chevron-down"}`}
|
|
aria-hidden="true"
|
|
style={{ fontSize: 14, marginLeft: 4, color: "var(--color-text-tertiary)" }}
|
|
/>
|
|
</span>
|
|
</button>
|
|
|
|
{/* Vista previa: siempre a la vista, en fila ocupando el ancho */}
|
|
{cargando && resenas === null && (
|
|
<p style={{ fontSize: 12, color: "var(--color-text-tertiary)", margin: 0 }}>Cargando reseñas…</p>
|
|
)}
|
|
{resenas !== null && lista.length === 0 && (
|
|
<p style={{ fontSize: 12, color: "var(--color-text-tertiary)", margin: 0 }}>
|
|
Aún no hay reseñas. ¡Sé el primero!
|
|
</p>
|
|
)}
|
|
<div style={gridResenas} aria-label="Vista previa de reseñas">
|
|
{visibles.map((r) => <Reseña key={r.id} r={r} reportada={reportada} onReportar={reportar} onBorrar={borrarPropia} />)}
|
|
</div>
|
|
|
|
{/* Pista de expansión cuando hay más reseñas que la vista previa */}
|
|
{!abierto && total > VISTA_PREVIA && (
|
|
<button
|
|
type="button"
|
|
onClick={() => expandir(false)}
|
|
style={{
|
|
background: "none", border: "none", padding: 0, width: "fit-content",
|
|
fontSize: 12, color: "#8B0000", cursor: "pointer", fontWeight: 500,
|
|
}}
|
|
>
|
|
Ver las {total} reseñas <i className="ti ti-chevron-down" aria-hidden="true"></i>
|
|
</button>
|
|
)}
|
|
|
|
{/* 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>
|
|
);
|
|
});
|
|
|
|
export default ResenasLocal;
|