feat: Implement post deletion functionality across feeds and profiles, and refactor PostCard component into a shared module.

This commit is contained in:
Christopher
2026-01-22 19:26:47 -08:00
parent 66cd763c30
commit a6e0ef2278
6 changed files with 69 additions and 114 deletions
+11
View File
@@ -110,6 +110,16 @@ export default function ProfilePage() {
router.push(`/${post.author.handle}/posts/${post.id}`); router.push(`/${post.author.handle}/posts/${post.id}`);
}; };
const handleDelete = (postId: string) => {
setPosts(prev => prev.filter(p => p.id !== postId));
if (user && isOwnProfile) {
setUser({
...user,
postsCount: (user.postsCount || 0) - 1
});
}
};
useEffect(() => { useEffect(() => {
if (user && currentUser?.handle === user.handle) { if (user && currentUser?.handle === user.handle) {
setProfileForm({ setProfileForm({
@@ -582,6 +592,7 @@ export default function ProfilePage() {
onLike={handleLike} onLike={handleLike}
onRepost={handleRepost} onRepost={handleRepost}
onComment={handleComment} onComment={handleComment}
onDelete={handleDelete}
/> />
)) ))
) )
+13
View File
@@ -68,6 +68,17 @@ export default function PostDetailPage() {
await fetch(`/api/posts/${postId}/repost`, { method }); await fetch(`/api/posts/${postId}/repost`, { method });
}; };
const handleDelete = (postId: string) => {
if (postId === id) {
router.push(`/${handle}`);
} else {
setReplies(prev => prev.filter(r => r.id !== postId));
if (post) {
setPost({ ...post, repliesCount: Math.max(0, post.repliesCount - 1) });
}
}
};
if (loading) { if (loading) {
return ( return (
<div style={{ padding: '48px', textAlign: 'center', color: 'var(--foreground-tertiary)' }}> <div style={{ padding: '48px', textAlign: 'center', color: 'var(--foreground-tertiary)' }}>
@@ -113,6 +124,7 @@ export default function PostDetailPage() {
isDetail isDetail
onLike={handleLike} onLike={handleLike}
onRepost={handleRepost} onRepost={handleRepost}
onDelete={handleDelete}
onComment={() => { onComment={() => {
const composer = document.querySelector('.compose-input') as HTMLTextAreaElement; const composer = document.querySelector('.compose-input') as HTMLTextAreaElement;
composer?.focus(); composer?.focus();
@@ -137,6 +149,7 @@ export default function PostDetailPage() {
post={reply} post={reply}
onLike={handleLike} onLike={handleLike}
onRepost={handleRepost} onRepost={handleRepost}
onDelete={handleDelete}
onComment={(p) => { onComment={(p) => {
// In detail view, commenting on a reply should probably just focus the main composer // In detail view, commenting on a reply should probably just focus the main composer
// but we could also implement nested replies later. // but we could also implement nested replies later.
+10 -2
View File
@@ -113,6 +113,14 @@ export default function ExplorePage() {
await fetch(`/api/posts/${postId}/repost`, { method }); await fetch(`/api/posts/${postId}/repost`, { method });
}; };
const handleDelete = (postId: string) => {
setTrendingPosts(prev => prev.filter(p => p.id !== postId));
setSearchResults(prev => ({
...prev,
posts: prev.posts.filter(p => p.id !== postId)
}));
};
return ( return (
<div className="explore-page"> <div className="explore-page">
<header className="explore-header"> <header className="explore-header">
@@ -166,7 +174,7 @@ export default function ExplorePage() {
) : ( ) : (
<div className="explore-posts"> <div className="explore-posts">
{trendingPosts.map((post) => ( {trendingPosts.map((post) => (
<PostCard key={post.id} post={post} onLike={handleLike} onRepost={handleRepost} /> <PostCard key={post.id} post={post} onLike={handleLike} onRepost={handleRepost} onDelete={handleDelete} />
))} ))}
</div> </div>
) )
@@ -209,7 +217,7 @@ export default function ExplorePage() {
<h2>Posts</h2> <h2>Posts</h2>
<div className="explore-posts"> <div className="explore-posts">
{searchResults.posts.map((post) => ( {searchResults.posts.map((post) => (
<PostCard key={post.id} post={post} onLike={handleLike} onRepost={handleRepost} /> <PostCard key={post.id} post={post} onLike={handleLike} onRepost={handleRepost} onDelete={handleDelete} />
))} ))}
</div> </div>
</div> </div>
+5
View File
@@ -83,6 +83,10 @@ export default function Home() {
await fetch(`/api/posts/${postId}/repost`, { method }); await fetch(`/api/posts/${postId}/repost`, { method });
}; };
const handleDelete = (postId: string) => {
setPosts(prev => prev.filter(p => p.id !== postId));
};
return ( return (
<> <>
<header style={{ <header style={{
@@ -157,6 +161,7 @@ export default function Home() {
post={post} post={post}
onLike={handleLike} onLike={handleLike}
onRepost={handleRepost} onRepost={handleRepost}
onDelete={handleDelete}
onComment={(p) => { onComment={(p) => {
setReplyingTo(p); setReplyingTo(p);
window.scrollTo({ top: 0, behavior: 'smooth' }); window.scrollTo({ top: 0, behavior: 'smooth' });
+25 -107
View File
@@ -4,6 +4,8 @@ import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { useSearchParams, useRouter } from 'next/navigation'; import { useSearchParams, useRouter } from 'next/navigation';
import { formatFullHandle } from '@/lib/utils/handle'; import { formatFullHandle } from '@/lib/utils/handle';
import { PostCard } from '@/components/PostCard';
import { Post } from '@/lib/types';
interface User { interface User {
id: string; id: string;
@@ -15,22 +17,7 @@ interface User {
isRemote?: boolean; isRemote?: boolean;
} }
interface MediaItem {
id: string;
url: string;
altText?: string | null;
}
interface Post {
id: string;
content: string;
createdAt: string;
likesCount: number;
repostsCount: number;
repliesCount: number;
author: User;
media?: MediaItem[];
}
// Icons // Icons
const SearchIcon = () => ( const SearchIcon = () => (
@@ -116,98 +103,7 @@ function UserCard({ user }: { user: User }) {
); );
} }
function PostCard({ post }: { post: Post }) {
const [liked, setLiked] = useState(false);
const [reporting, setReporting] = useState(false);
const formatTime = (dateStr: string) => {
const date = new Date(dateStr);
const now = new Date();
const diff = now.getTime() - date.getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (minutes < 1) return 'now';
if (minutes < 60) return `${minutes}m`;
if (hours < 24) return `${hours}h`;
if (days < 7) return `${days}d`;
return date.toLocaleDateString();
};
return (
<article className="post">
<div className="post-header">
<div className="avatar">
{post.author?.avatarUrl ? (
<img src={post.author.avatarUrl} alt={post.author.displayName} />
) : (
(post.author?.displayName || post.author?.handle || '?').charAt(0).toUpperCase()
)}
</div>
<div className="post-author">
<Link href={`/@${post.author?.handle}`} className="post-handle">
{post.author?.displayName || post.author?.handle}
</Link>
<span className="post-time">{formatFullHandle(post.author?.handle || '')} · {formatTime(post.createdAt)}</span>
</div>
</div>
<div className="post-content">{post.content}</div>
{post.media && post.media.length > 0 && (
<div className="post-media-grid">
{post.media.map((item) => (
<div className="post-media-item" key={item.id}>
<img src={item.url} alt={item.altText || 'Post media'} loading="lazy" />
</div>
))}
</div>
)}
<div className="post-actions">
<button className="post-action">
<MessageIcon />
<span>{post.repliesCount || ''}</span>
</button>
<button className="post-action">
<RepeatIcon />
<span>{post.repostsCount || ''}</span>
</button>
<button className={`post-action ${liked ? 'liked' : ''}`} onClick={() => setLiked(!liked)}>
<HeartIcon filled={liked} />
<span>{post.likesCount + (liked ? 1 : 0) || ''}</span>
</button>
<button className="post-action" onClick={async () => {
if (reporting) return;
const reason = window.prompt('Why are you reporting this post?');
if (!reason) return;
setReporting(true);
try {
const res = await fetch('/api/reports', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetType: 'post', targetId: post.id, reason }),
});
if (!res.ok) {
if (res.status === 401) {
alert('Please log in to report.');
} else {
alert('Report failed. Please try again.');
}
} else {
alert('Report submitted. Thank you.');
}
} catch {
alert('Report failed. Please try again.');
} finally {
setReporting(false);
}
}} disabled={reporting}>
<FlagIcon />
<span>{reporting ? '...' : ''}</span>
</button>
</div>
</article>
);
}
export default function SearchPage() { export default function SearchPage() {
const router = useRouter(); const router = useRouter();
@@ -261,6 +157,20 @@ export default function SearchPage() {
} }
}; };
const handleLike = async (postId: string, currentLiked: boolean) => {
const method = currentLiked ? 'DELETE' : 'POST';
await fetch(`/api/posts/${postId}/like`, { method });
};
const handleRepost = async (postId: string, currentReposted: boolean) => {
const method = currentReposted ? 'DELETE' : 'POST';
await fetch(`/api/posts/${postId}/repost`, { method });
};
const handleDelete = (postId: string) => {
setPosts(prev => prev.filter(p => p.id !== postId));
};
return ( return (
<div style={{ maxWidth: '600px', margin: '0 auto', minHeight: '100vh' }}> <div style={{ maxWidth: '600px', margin: '0 auto', minHeight: '100vh' }}>
{/* Header */} {/* Header */}
@@ -368,7 +278,15 @@ export default function SearchPage() {
Posts Posts
</div> </div>
)} )}
{posts.map(post => <PostCard key={post.id} post={post} />)} {posts.map(post => (
<PostCard
key={post.id}
post={post}
onLike={handleLike}
onRepost={handleRepost}
onDelete={handleDelete}
/>
))}
</div> </div>
)} )}
</> </>
+5 -5
View File
@@ -62,17 +62,17 @@ export function Sidebar() {
</nav> </nav>
{user && ( {user && (
<div style={{ marginTop: 'auto', paddingTop: '16px' }}> <div style={{ marginTop: 'auto', paddingTop: '16px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}> <div style={{ display: 'flex', alignItems: 'center', gap: '12px', minWidth: 0 }}>
<div className="avatar avatar-sm"> <div className="avatar avatar-sm" style={{ flexShrink: 0 }}>
{user.avatarUrl ? ( {user.avatarUrl ? (
<img src={user.avatarUrl} alt={user.displayName} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> <img src={user.avatarUrl} alt={user.displayName} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : ( ) : (
(user.displayName?.charAt(0) || user.handle.charAt(0)).toUpperCase() (user.displayName?.charAt(0) || user.handle.charAt(0)).toUpperCase()
)} )}
</div> </div>
<div> <div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: '14px' }}>{user.displayName}</div> <div style={{ fontWeight: 600, fontSize: '14px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.displayName}</div>
<div style={{ color: 'var(--foreground-tertiary)', fontSize: '13px' }}>{formatFullHandle(user.handle)}</div> <div style={{ color: 'var(--foreground-tertiary)', fontSize: '13px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{formatFullHandle(user.handle)}</div>
</div> </div>
</div> </div>
</div> </div>