'use client'; // 用户主页:资料卡 + 该用户的帖子列表 import { useEffect, useState, useCallback, useRef } from 'react'; import { API } from '@/lib/api'; import { useApp } from './AppProvider'; import { Icon } from './Icons'; import { useOpenPrivateChat } from './chat/ChatManager'; import { renderMarkdown } from '@/lib/markdown'; import { useTranslation } from 'react-i18next'; function avatar(username, size = 128) { return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') + '&background=6366f1&color=fff&size=' + size; } export default function UserProfile({ username, initialUser = null, initialPosts = null }) { const { currentUser, openPost } = useApp(); const { t, i18n } = useTranslation(); const openPrivateChat = useOpenPrivateChat(); const [user, setUser] = useState(initialUser); const [posts, setPosts] = useState(initialPosts || []); const [error, setError] = useState(null); const postsRef = useRef(null); const load = useCallback(async () => { setError(null); try { const u = await API.getUserProfile(username); if (u.error || !u.id) { setError(u.error || '用户不存在'); return; } setUser(u); const result = await API.getPosts('latest', u.id); setPosts(result.data || []); } catch (err) { setError(err.message || '加载失败'); } }, [username]); useEffect(() => { setUser(initialUser); setPosts(initialPosts || []); load(); }, [initialPosts, initialUser, load]); useEffect(() => { const contents = postsRef.current?.querySelectorAll('.user-post-preview') || []; contents.forEach((element) => { element.classList.toggle('has-fade', element.scrollHeight > element.clientHeight + 4); }); }, [posts]); if (error) { return (
加载失败:{error}
); } if (!user) { return
加载中...
; } return (

用户主页

{user.username

{user.username}

{user.id && (

{user.bio || '这个人很懒,什么都没写'}

{currentUser && currentUser.username !== user.username && ( )}
加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'} 发了 {posts.length} 个帖子 {user.role === 'admin' && 管理员}
)}
{user.id && (

发布的帖子

{posts.length === 0 ? (
还没有发帖
) : ( posts.map((p) => { const time = p.created_at ? new Date(p.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : ''; return (
openPost(p.id, event.currentTarget, p, { view: 'user', username: user.username, user, posts, scrollTop: document.getElementById('pageUser')?.scrollTop || 0, })} > {p.is_pinned && (
{t('feed.pinned')}
)}
{user.username} {time} {p.edited_at && ( {t('feed.deleted')} )}
{p.title || t('feed.noTitle')}
{p.images && p.images.length > 0 && (
{p.images.map((image, index) => ( ))}
)}
{p.reply_count || 0}
); }) )}
)}
); }