almeira-web/src/components/publications/PostCard.tsx
Carlos (Almeira) dda9ae0f4a feat: implement robust publications module with real-time validation and state management
- Refactor dashboard entity pages to support dynamic publications management.
- Add Publications Module with Atomic Design components (PostCard, PublicationsList, FormSection).
- Implement Zod-based real-time validation for publication forms.
- Manage state using Zustand for optimistic UI and in-place relations.
- Add RBAC protection with PermissionGuard and server-side API validation.
- Fix: Resolve TypeScript type error in AdWrappers.tsx to ensure successful build.
- Add ToastProvider and ErrorBoundary for improved user experience.
- Update dependencies for publications logic.
2026-03-28 08:47:40 -05:00

196 lines
7.5 KiB
TypeScript

'use client';
/**
* @file PostCard.tsx
* @description Pure presentation component for displaying a Post in the dashboard.
*
* - Receives all data via props (no internal data fetching).
* - Uses `PermissionGuard` to conditionally show edit/delete controls.
* - XSS-safe: all text content uses textContent rendering (no dangerouslySetInnerHTML).
* - The `onEdit` callback is injected by the parent — this component stays pure.
*/
import React from 'react';
import Link from 'next/link';
import { Edit2, Trash2, Eye, Calendar, Tag } from 'lucide-react';
import { Post, PostCardProps, UserRole } from '@/types/publications';
import PermissionGuard from './PermissionGuard';
import { decodeHtmlEntities } from '@/lib/utils';
/** Derives a plain text excerpt from raw HTML content — XSS safe */
function getPlainTextExcerpt(html: string, maxLength = 120): string {
// Remove all HTML tags using regex (safe for server, no DOM parsing needed)
const plain = html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
return plain.length > maxLength ? plain.substring(0, maxLength) + '…' : plain;
}
/** Resolves the image URL from a Post's imagen_destacada_id (string or MediaItem object) */
function resolveImageUrl(
post: Post,
endpoint: string,
projectId: string
): string | null {
if (post.og_image_url) return post.og_image_url;
if (!post.imagen_destacada_id) return null;
if (typeof post.imagen_destacada_id === 'object') {
const { bucket_id, file_id } = post.imagen_destacada_id;
return `${endpoint}/storage/buckets/${bucket_id}/files/${file_id}/preview?project=${projectId}&width=600&height=400&quality=80`;
}
// Fallback: just an ID, use default 'media' bucket
return `${endpoint}/storage/buckets/media/files/${post.imagen_destacada_id}/preview?project=${projectId}&width=600&height=400&quality=80`;
}
/** Maps PostStatus to a visual badge style */
const statusBadge: Record<string, { label: string; className: string }> = {
Publicado: { label: 'Publicado', className: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30' },
Borrador: { label: 'Borrador', className: 'bg-slate-500/10 text-slate-400 border-slate-500/30' },
Pendiente: { label: 'Pendiente', className: 'bg-amber-500/10 text-amber-400 border-amber-500/30' },
Archivado: { label: 'Archivado', className: 'bg-red-500/10 text-red-400 border-red-500/30' },
};
/**
* PostCard — Dashboard card for a single Post.
*/
export const PostCard: React.FC<PostCardProps> = ({
post,
userRole,
onEdit,
onDelete,
appwriteEndpoint,
appwriteProjectId,
}) => {
const imageUrl = resolveImageUrl(post, appwriteEndpoint, appwriteProjectId);
// Safe text rendering — no raw HTML
const safeTitle = decodeHtmlEntities(post.titulo);
const safeExcerpt = getPlainTextExcerpt(post.resumen_redes || post.contenido || '');
const badge = statusBadge[post.estado] ?? statusBadge['Borrador'];
const fechaFormatted = new Date(post.fecha_publicacion || post.$createdAt).toLocaleDateString(
'es-CO',
{ day: '2-digit', month: 'short', year: 'numeric' }
);
const postType =
typeof post.tipo_publicacion_id === 'object'
? post.tipo_publicacion_id.descripcion
: post.tipo_publicacion_id;
return (
<article
className="group relative flex flex-col bg-slate-900/60 border border-white/8 rounded-2xl overflow-hidden transition-all duration-300 hover:border-cyan-500/40 hover:shadow-[0_8px_30px_rgba(6,182,212,0.1)] hover:-translate-y-1"
aria-label={`Publicación: ${safeTitle}`}
>
{/* Imagen Destacada */}
<div className="relative aspect-[16/9] bg-slate-800 overflow-hidden">
{imageUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={imageUrl}
alt={safeTitle}
className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-slate-800 to-slate-900">
<Tag size={32} className="text-slate-700" />
</div>
)}
{/* Estado Badge */}
<div className="absolute top-3 left-3">
<span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[10px] font-black uppercase tracking-widest border ${badge.className}`}>
{badge.label}
</span>
</div>
{/* Edit Overlay — solo visible si el usuario tiene permisos */}
<PermissionGuard allowedRoles={['editor', 'admin']} userRole={userRole}>
<div
className="absolute inset-0 bg-slate-950/70 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center gap-3 cursor-pointer"
onClick={() => onEdit?.(post)}
role="button"
aria-label={`Editar: ${safeTitle}`}
>
<span className="flex items-center gap-2 bg-cyan-500 text-slate-950 font-black text-xs px-4 py-2 rounded-full uppercase tracking-widest shadow-lg">
<Edit2 size={14} />
Editar
</span>
</div>
</PermissionGuard>
</div>
{/* Contenido */}
<div className="flex flex-col flex-1 p-5">
{/* Tipo de publicación */}
{postType && (
<span className="text-[10px] font-black uppercase tracking-widest text-cyan-500 mb-2">
{postType}
</span>
)}
{/* Título — safe text */}
<h3 className="text-base font-bold text-white leading-snug mb-2 line-clamp-2">
{safeTitle}
</h3>
{/* Resumen — safe, no HTML */}
<p className="text-slate-400 text-sm leading-relaxed line-clamp-3 flex-1">
{safeExcerpt}
</p>
{/* Footer */}
<div className="mt-4 pt-4 border-t border-white/8 flex items-center justify-between gap-2">
{/* Fecha */}
<div className="flex items-center gap-1.5 text-slate-500 text-xs font-medium">
<Calendar size={12} />
<span>{fechaFormatted}</span>
</div>
{/* Acciones */}
<div className="flex items-center gap-1">
{/* Ver publicación (siempre visible) */}
<Link
href={`/${post.slug || post.$id}`}
target="_blank"
className="p-2 rounded-lg text-slate-500 hover:text-cyan-400 hover:bg-cyan-500/10 transition-all"
aria-label="Ver publicación"
>
<Eye size={15} />
</Link>
{/* Editar — solo para editor/admin */}
<PermissionGuard allowedRoles={['editor', 'admin']} userRole={userRole}>
<button
type="button"
onClick={() => onEdit?.(post)}
className="p-2 rounded-lg text-slate-500 hover:text-cyan-400 hover:bg-cyan-500/10 transition-all"
aria-label="Editar publicación"
>
<Edit2 size={15} />
</button>
</PermissionGuard>
{/* Eliminar — solo para admin */}
<PermissionGuard allowedRoles={['admin']} userRole={userRole}>
<button
type="button"
onClick={() => onDelete?.(post.$id)}
className="p-2 rounded-lg text-slate-500 hover:text-red-400 hover:bg-red-500/10 transition-all"
aria-label="Eliminar publicación"
>
<Trash2 size={15} />
</button>
</PermissionGuard>
</div>
</div>
</div>
</article>
);
};
export default PostCard;