feat: animate user profile transitions

This commit is contained in:
lezi-fun committed 2026-08-12 10:24:20 +08:00
1 parent 8e67e82eb0
commit bbf3262aff
6 files changed
+467 -63

No files matched your search

+91 -7
View File
@@ -15,7 +15,7 @@ const POST_TRANSITION_PARTS = [
['.post-content', 'post-body'],
['.post-images', 'post-feed-media'],
['.post-pin-state', 'post-pin-state'],
['.post-edited-state', 'post-edited-state'],
['.post-edited-label', 'post-edited-label'],
['.post-actions', 'post-feed-actions'],
];
@@ -129,6 +129,7 @@ export default function AppProvider({ children, cachedName = '' }) {
const [currentPostId, setCurrentPostId] = useState(null);
const [currentPostPreview, setCurrentPostPreview] = useState(null);
const [currentUsername, setCurrentUsername] = useState(null);
const [currentUserPreview, setCurrentUserPreview] = useState(null);
const [currentPageName, setCurrentPageName] = useState(null);
const [sort, setSort] = useState('latest');
const [refreshKey, setRefreshKey] = useState(0);
@@ -273,15 +274,19 @@ export default function AppProvider({ children, cachedName = '' }) {
if (page === 'feed') {
url.searchParams.delete('page');
url.searchParams.delete('post');
url.searchParams.delete('user');
} else {
url.searchParams.set('page', page);
url.searchParams.delete('post');
url.searchParams.delete('user');
}
const commitNavigation = (refreshFeed = true) => {
window.history.pushState({ page }, '', url);
setView(page);
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentUsername(null);
setCurrentUserPreview(null);
if (refreshFeed) refresh();
};
@@ -291,6 +296,48 @@ export default function AppProvider({ children, cachedName = '' }) {
return;
}
if (view === 'user') {
const root = document.documentElement;
const sourceAvatar = document.querySelector('#pageUser .user-profile-avatar');
const sourceName = document.querySelector('#pageUser .user-profile-name');
const findTargetCard = () => {
if (currentUserPreview?.sourcePostId) {
const exact = Array.from(document.querySelectorAll('[data-post-id]')).find(
(element) => element.dataset.postId === String(currentUserPreview.sourcePostId)
);
if (exact) return exact;
}
return Array.from(document.querySelectorAll('[data-username]')).find(
(element) => element.dataset.username === String(currentUsername || '')
) || null;
};
let targetCard = findTargetCard();
if (sourceAvatar && sourceName && targetCard) {
let targetAvatar = null;
let targetName = null;
root.classList.add('user-view-transition', 'returning-user-home');
const transition = document.startViewTransition(() => {
flushSync(() => commitNavigation(false));
targetCard = findTargetCard();
targetAvatar = targetCard?.querySelector('.post-avatar') || null;
targetName = targetCard?.querySelector('.post-username') || null;
if (targetAvatar) targetAvatar.style.viewTransitionName = 'user-avatar';
if (targetName) targetName.style.viewTransitionName = 'user-name';
});
const clearTargetNames = () => {
if (targetAvatar) targetAvatar.style.viewTransitionName = '';
if (targetName) targetName.style.viewTransitionName = '';
};
transition.ready.then(clearTargetNames, clearTargetNames);
transition.finished.finally(() => {
root.classList.remove('user-view-transition', 'returning-user-home');
refresh();
});
return;
}
}
let targetCard = currentPostId
? Array.from(document.querySelectorAll('[data-post-id]')).find((element) => element.dataset.postId === String(currentPostId))
: null;
@@ -331,7 +378,7 @@ export default function AppProvider({ children, cachedName = '' }) {
document.documentElement.classList.remove('home-view-transition', 'returning-home');
refresh();
});
}, [currentPostId, refresh, view]);
}, [currentPostId, currentUsername, currentUserPreview, refresh, view]);
const openPost = useCallback((postId, sourceElement = null, preview = null) => {
const url = new URL(window.location);
@@ -343,6 +390,7 @@ export default function AppProvider({ children, cachedName = '' }) {
setView('post');
setCurrentPostId(postId);
setCurrentPostPreview(preview);
setCurrentUserPreview(null);
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
@@ -380,14 +428,47 @@ export default function AppProvider({ children, cachedName = '' }) {
});
}, []);
const openUser = useCallback((username) => {
const openUser = useCallback((username, source = null, preview = null) => {
const url = new URL(window.location);
url.searchParams.set('user', username);
url.searchParams.delete('page');
url.searchParams.delete('post');
window.history.pushState({ page: 'user', username }, '', url);
setView('user');
setCurrentUsername(username);
const commitNavigation = () => {
window.history.pushState({ page: 'user', username }, '', url);
setView('user');
setCurrentUsername(username);
setCurrentUserPreview(preview || { username });
setCurrentPostId(null);
setCurrentPostPreview(null);
};
const avatarElement = source?.avatarElement;
const nameElement = source?.nameElement;
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (!avatarElement || !nameElement || !document.startViewTransition || reduceMotion) {
commitNavigation();
return;
}
const root = document.documentElement;
root.classList.remove('user-transition-settled');
root.classList.add('user-view-transition');
avatarElement.style.viewTransitionName = 'user-avatar';
nameElement.style.viewTransitionName = 'user-name';
const transition = document.startViewTransition(() => {
flushSync(commitNavigation);
});
const clearSourceNames = () => {
avatarElement.style.viewTransitionName = '';
nameElement.style.viewTransitionName = '';
};
transition.ready.then(clearSourceNames, clearSourceNames);
transition.finished.finally(() => {
root.classList.remove('user-view-transition');
root.classList.add('user-transition-settled');
window.setTimeout(() => root.classList.remove('user-transition-settled'), 320);
});
}, []);
const openCustomPage = useCallback((pageName) => {
@@ -398,6 +479,7 @@ export default function AppProvider({ children, cachedName = '' }) {
window.history.pushState({ page: 'custom', pageName }, '', url);
setView('custom');
setCurrentPageName(pageName);
setCurrentUserPreview(null);
}, []);
// 浏览器前进后退
@@ -411,6 +493,7 @@ export default function AppProvider({ children, cachedName = '' }) {
} else if (state.username) {
setView('user');
setCurrentUsername(state.username);
setCurrentUserPreview(null);
} else if (state.pageName) {
setView('custom');
setCurrentPageName(state.pageName);
@@ -419,6 +502,7 @@ export default function AppProvider({ children, cachedName = '' }) {
setCurrentPostId(null);
setCurrentPostPreview(null);
setCurrentUsername(null);
setCurrentUserPreview(null);
setCurrentPageName(null);
}
};
@@ -461,7 +545,7 @@ export default function AppProvider({ children, cachedName = '' }) {
theme, toggleTheme,
view, navigate,
currentPostId, currentPostPreview, openPost,
currentUsername, openUser,
currentUsername, currentUserPreview, openUser,
currentPageName, openCustomPage,
sort, setSort,
refreshKey, refresh,
+37 -4
View File
@@ -107,6 +107,23 @@ export default function Feed({ onOpenModal, onReport }) {
}
};
const handleOpenUser = (event, post) => {
event.stopPropagation();
const header = event.currentTarget.closest('.post-header');
openUser(
post.username,
{
avatarElement: header?.querySelector('.post-avatar'),
nameElement: header?.querySelector('.post-username'),
},
{
username: post.username,
avatar_url: post.avatar_url || avatar(post.username),
sourcePostId: post.id,
}
);
};
return (
<main id="feed">
<div className="feed-header">
@@ -137,23 +154,39 @@ export default function Feed({ onOpenModal, onReport }) {
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" data-post-id={p.id} style={{ cursor: 'pointer' }}
<div key={p.id} className="post-card" data-post-id={p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
onClick={(e) => openPost(p.id, e.currentTarget, p)}>
{p.is_pinned && (
<div className="post-pin-state" style={{ width: 'fit-content', display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}><Icon name="pin" size={12} /> {t('feed.pinned')}</div>
)}
<div className="post-header">
<img src={p.avatar_url || avatar(p.username)} className="post-avatar" alt="" />
<img
src={p.avatar_url || avatar(p.username)}
className="post-avatar"
alt={p.username || t('feed.anonymous')}
role="button"
tabIndex={0}
style={{ cursor: 'pointer' }}
onClick={(e) => handleOpenUser(e, p)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleOpenUser(e, p);
}
}}
/>
<span
className="post-username"
style={{ cursor: 'pointer', color: 'var(--primary)' }}
onClick={(e) => { e.stopPropagation(); openUser(p.username); }}
onClick={(e) => handleOpenUser(e, p)}
>
{p.username || t('feed.anonymous')}
</span>
<span className="post-time">{time}</span>
{p.edited_at && (
<span className="post-edited-state" style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>{t('feed.deleted')}</span>
<span className="post-edited-state" style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>
<span className="post-edited-label">{t('feed.deleted')}</span>
</span>
)}
</div>
<div className="post-title">{p.title || t('feed.noTitle')}</div>
+6 -1
View File
@@ -10,6 +10,7 @@ import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
import { useToast } from './Toast';
import { useTranslation } from 'react-i18next';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
@@ -18,6 +19,7 @@ function avatar(username) {
export default function PostDetail({ postId, initialPost = null }) {
const { currentUser, navigate, openUser, refreshKey } = useApp();
const { t, i18n } = useTranslation();
const { toast, confirmAction } = useToast();
const [post, setPost] = useState(initialPost);
const [error, setError] = useState(null);
@@ -156,7 +158,10 @@ export default function PostDetail({ postId, initialPost = null }) {
<span className="post-time">{time}</span>
{post.edited_at && (
<span className="post-edited-state" style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
(已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
<span className="post-edited-label">{t('feed.deleted')}</span>
<span className="post-edited-detail">
{' '}{new Date(post.edited_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN')}
</span>
</span>
)}
{post.is_pinned && (
+51 -39
View File
@@ -12,10 +12,10 @@ function avatar(username, size = 128) {
'&background=6366f1&color=fff&size=' + size;
}
export default function UserProfile({ username }) {
export default function UserProfile({ username, initialUser = null }) {
const { currentUser, openPost } = useApp();
const openPrivateChat = useOpenPrivateChat();
const [user, setUser] = useState(null);
const [user, setUser] = useState(initialUser);
const [posts, setPosts] = useState([]);
const [error, setError] = useState(null);
@@ -35,60 +35,72 @@ export default function UserProfile({ username }) {
}
}, [username]);
useEffect(() => { load(); }, [load]);
useEffect(() => {
setUser(initialUser);
setPosts([]);
load();
}, [initialUser, load]);
if (error) {
return (
<div className="page-slide active">
<div id="pageUser" className="page-slide active">
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
</div>
);
}
if (!user) {
return <div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>;
return <div id="pageUser" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>;
}
return (
<div className="page-slide active">
<div id="pageUser" className="page-slide active">
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<h2><Icon name="users" size={20} /> 用户主页</h2>
</div>
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
<img src={user.avatar_url || avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
<h2 style={{ margin: '16px 0 4px', fontSize: 24 }}>{user.username}</h2>
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
{currentUser && currentUser.id !== user.id && (
<button
className="btn-primary"
style={{ marginTop: 12, padding: '8px 20px' }}
onClick={() => openPrivateChat(user.id, user.username)}
>
<Icon name="message" size={14} /> 发私信
</button>
)}
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}><Icon name="shield" size={14} /> 管理员</span>}
<div id="userProfileContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
<div className="user-profile-card" style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
<img className="user-profile-avatar" src={user.avatar_url || avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt={user.username || ''} />
<h2 className="user-profile-name" style={{ margin: '16px 0 4px', fontSize: 24, color: 'var(--text)' }}>{user.username}</h2>
{user.id && (
<div className="user-profile-details">
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
{currentUser && currentUser.username !== user.username && (
<button
className="btn-primary"
style={{ marginTop: 12, padding: '8px 20px' }}
onClick={() => openPrivateChat(user.id, user.username)}
>
<Icon name="message" size={14} /> 发私信
</button>
)}
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}><Icon name="shield" size={14} /> 管理员</span>}
</div>
</div>
)}
</div>
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}><Icon name="file" size={18} /> 发布的帖子</h3>
{posts.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={(e) => openPost(p.id, e.currentTarget, p)}>
<div className="post-title" style={{ fontSize: 16, fontWeight: 600 }}>{p.title || '无标题'}</div>
<div className="post-content" style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
{user.id && (
<div className="user-profile-posts">
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}><Icon name="file" size={18} /> 发布的帖子</h3>
{posts.length === 0 ? (
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</div>
) : (
posts.map((p) => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
return (
<div key={p.id} className="post-card" style={{ cursor: 'pointer' }} onClick={(e) => openPost(p.id, e.currentTarget, p)}>
<div className="post-title" style={{ fontSize: 16, fontWeight: 600 }}>{p.title || '无标题'}</div>
<div className="post-content" style={{ fontSize: 14, color: 'var(--text-secondary)' }}>
{(p.content || '').substring(0, 100)}{(p.content || '').length > 100 ? '...' : ''}
</div>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 8 }}>{time}</div>
</div>
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 8 }}>{time}</div>
</div>
);
})
);
})
)}
</div>
)}
</div>
</div>