almeira-web/src/components/publications/PostCard.tsx
Carlos (Almeira) 3647602413 feat: complete rx editor, media library grid, UX logic, and XSS protection
- Added @tiptap/extension-youtube and extension-image
- Added MediaGridSelector component with robust grid UI and inline uploads
- Integrated MediaGridSelector into PublicationLayout for featured images
- Integrated inline image module in RichTextEditor linked to MediaGridSelector
- Rendered date conditionally on PostCard and disabled bubble propagation
- Added isomorphic-dompurify to mitigate XSS in the public article viewer
2026-03-28 14:34:04 -05:00

211 lines
8.0 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,
globalSettings,
}) => {
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;
const handleCardClick = (e: React.MouseEvent) => {
if ((e.target as HTMLElement).closest('button, a, [role="button"]')) return;
// Single click: abre vista de detalle
window.open(`/${post.slug || post.$id}`, '_blank');
};
const handleCardDoubleClick = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if ((e.target as HTMLElement).closest('button, a, [role="button"]')) return;
// Double click: abre edición si es admin/editor
if (userRole === 'admin' || userRole === 'editor') {
onEdit?.(post);
}
};
const showDate = globalSettings?.show_news_date !== false;
return (
<article
onClick={handleCardClick}
onDoubleClick={handleCardDoubleClick}
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 cursor-pointer"
aria-label={`Publicación: ${safeTitle}`}
>
{/* Tooltip instructivo para admins */}
{(userRole === 'admin' || userRole === 'editor') && (
<div className="absolute -top-10 left-1/2 -translate-x-1/2 bg-slate-800 text-white text-[10px] py-1 px-3 rounded-full opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 pointer-events-none shadow-xl border border-slate-700">
Doble click para editar
</div>
)}
{/* 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>
</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 */}
{showDate && (
<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;