feat(pagination): implement cursor-based pagination across the app
Add useCursorPagination hook and update multiple screens and services to use cursor-based pagination for better performance and consistency. - Add useCursorPagination hook with deduplication and caching support - Add cursor pagination types to infrastructure layer - Refactor HomeScreen, PostDetailScreen, SearchScreen for posts/comments - Refactor GroupMembersScreen, JoinGroupScreen for groups/members - Refactor MessageListScreen, NotificationsScreen for messages - Update post, message, group, comment, notification services with cursor endpoints - Add CursorPaginationRequest/Response DTOs - Remove deprecated OPTIMIZATION_DESIGN.md documentation
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
* GroupMembersScreen 群成员管理界面
|
||||
* 显示群成员列表,支持管理员管理成员
|
||||
* 支持响应式网格布局
|
||||
* 使用游标分页
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
@@ -27,6 +28,7 @@ import { groupService } from '../../services/groupService';
|
||||
import { groupManager } from '../../stores/groupManager';
|
||||
import { Avatar, Text, Button, Loading, EmptyState, Divider, ResponsiveContainer } from '../../components/common';
|
||||
import { useResponsive, useBreakpointGTE } from '../../hooks/useResponsive';
|
||||
import { useCursorPagination } from '../../hooks/useCursorPagination';
|
||||
import {
|
||||
GroupMemberResponse,
|
||||
GroupRole,
|
||||
@@ -68,12 +70,34 @@ const GroupMembersScreen: React.FC = () => {
|
||||
return GRID_CONFIG.mobile;
|
||||
}, [width]);
|
||||
|
||||
// 成员列表状态
|
||||
const [members, setMembers] = useState<GroupMemberResponse[]>([]);
|
||||
// 使用游标分页 Hook 管理成员列表
|
||||
const {
|
||||
items: members,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
hasMore,
|
||||
loadMore,
|
||||
refresh,
|
||||
error,
|
||||
} = useCursorPagination(
|
||||
async ({ cursor, pageSize }) => {
|
||||
return await groupService.getGroupMembersCursor(groupId, {
|
||||
cursor,
|
||||
page_size: pageSize,
|
||||
});
|
||||
},
|
||||
{ pageSize: 50 }
|
||||
);
|
||||
|
||||
// 本地成员状态(用于乐观更新)
|
||||
const [localMembers, setLocalMembers] = useState<GroupMemberResponse[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
|
||||
// 同步分页数据到本地状态
|
||||
useEffect(() => {
|
||||
setLocalMembers(members);
|
||||
setLoading(false);
|
||||
}, [members]);
|
||||
|
||||
// 当前用户的成员信息
|
||||
const [currentMember, setCurrentMember] = useState<GroupMemberResponse | null>(null);
|
||||
@@ -91,65 +115,31 @@ const GroupMembersScreen: React.FC = () => {
|
||||
const isOwner = currentMember?.role === 'owner';
|
||||
const isAdmin = currentMember?.role === 'admin' || isOwner;
|
||||
|
||||
// 加载成员列表
|
||||
const loadMembers = useCallback(
|
||||
async (
|
||||
pageNum: number = 1,
|
||||
refresh: boolean = false,
|
||||
forceRefresh: boolean = false
|
||||
) => {
|
||||
if (!hasMore && !refresh) return;
|
||||
|
||||
try {
|
||||
const response = await groupManager.getMembers(groupId, pageNum, 50, forceRefresh);
|
||||
|
||||
if (refresh) {
|
||||
setMembers(response.list);
|
||||
setPage(1);
|
||||
} else {
|
||||
setMembers(prev => [...prev, ...response.list]);
|
||||
}
|
||||
|
||||
setHasMore(response.list.length === 50);
|
||||
|
||||
// 查找当前用户的成员信息
|
||||
const myMember = response.list.find(m => m.user_id === currentUser?.id);
|
||||
if (myMember) {
|
||||
setCurrentMember(myMember);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载成员列表失败:', error);
|
||||
// 查找当前用户的成员信息
|
||||
useEffect(() => {
|
||||
const myMember = localMembers.find(m => m.user_id === currentUser?.id);
|
||||
if (myMember) {
|
||||
setCurrentMember(myMember);
|
||||
}
|
||||
}, [localMembers, currentUser]);
|
||||
|
||||
// 下拉刷新
|
||||
const onRefresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
await refresh();
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}, [groupId, currentUser, hasMore]);
|
||||
}, [refresh]);
|
||||
|
||||
// 初始加载
|
||||
useEffect(() => {
|
||||
loadMembers(1, true, true);
|
||||
refresh();
|
||||
}, [groupId]);
|
||||
|
||||
// 下拉刷新
|
||||
const onRefresh = useCallback(() => {
|
||||
setRefreshing(true);
|
||||
setHasMore(true);
|
||||
loadMembers(1, true, true);
|
||||
}, [loadMembers]);
|
||||
|
||||
// 加载更多
|
||||
const loadMore = useCallback(() => {
|
||||
if (!loading && hasMore) {
|
||||
const nextPage = page + 1;
|
||||
setPage(nextPage);
|
||||
loadMembers(nextPage);
|
||||
}
|
||||
}, [loading, hasMore, page, loadMembers]);
|
||||
|
||||
// 按角色分组
|
||||
const groupMembers = useCallback((): MemberGroup[] => {
|
||||
const owners = members.filter(m => m.role === 'owner');
|
||||
const admins = members.filter(m => m.role === 'admin');
|
||||
const normalMembers = members.filter(m => m.role === 'member');
|
||||
const owners = localMembers.filter(m => m.role === 'owner');
|
||||
const admins = localMembers.filter(m => m.role === 'admin');
|
||||
const normalMembers = localMembers.filter(m => m.role === 'member');
|
||||
|
||||
const groups: MemberGroup[] = [];
|
||||
|
||||
@@ -164,7 +154,7 @@ const GroupMembersScreen: React.FC = () => {
|
||||
}
|
||||
|
||||
return groups;
|
||||
}, [members]);
|
||||
}, [localMembers]);
|
||||
|
||||
// 打开操作菜单
|
||||
const openActionModal = (member: GroupMemberResponse) => {
|
||||
@@ -203,7 +193,7 @@ const GroupMembersScreen: React.FC = () => {
|
||||
});
|
||||
|
||||
// 更新本地数据
|
||||
setMembers(prev => prev.map(m => {
|
||||
setLocalMembers(prev => prev.map(m => {
|
||||
if (m.user_id === selectedMember.user_id) {
|
||||
return { ...m, role: newRole };
|
||||
}
|
||||
@@ -245,14 +235,14 @@ const GroupMembersScreen: React.FC = () => {
|
||||
await groupService.muteMember(groupId, selectedMember.user_id, newMuted ? -1 : 0);
|
||||
|
||||
// 更新本地数据
|
||||
setMembers(prev => prev.map(m => {
|
||||
setLocalMembers(prev => prev.map(m => {
|
||||
if (m.user_id === selectedMember.user_id) {
|
||||
return { ...m, muted: newMuted };
|
||||
}
|
||||
return m;
|
||||
}));
|
||||
// 强制刷新远端状态,避免命中旧缓存导致解禁后仍显示禁言
|
||||
await loadMembers(1, true, true);
|
||||
await refresh();
|
||||
|
||||
setActionModalVisible(false);
|
||||
Alert.alert('成功', `已${actionText}`);
|
||||
@@ -286,7 +276,7 @@ const GroupMembersScreen: React.FC = () => {
|
||||
await groupService.removeMember(groupId, selectedMember.user_id);
|
||||
|
||||
// 更新本地数据
|
||||
setMembers(prev => prev.filter(m => m.user_id !== selectedMember.user_id));
|
||||
setLocalMembers(prev => prev.filter(m => m.user_id !== selectedMember.user_id));
|
||||
|
||||
setActionModalVisible(false);
|
||||
Alert.alert('成功', '已移除成员');
|
||||
@@ -320,7 +310,7 @@ const GroupMembersScreen: React.FC = () => {
|
||||
});
|
||||
|
||||
// 更新本地数据
|
||||
setMembers(prev => prev.map(m => {
|
||||
setLocalMembers(prev => prev.map(m => {
|
||||
if (m.user_id === selectedMember.user_id) {
|
||||
return { ...m, nickname: newNickname.trim() };
|
||||
}
|
||||
@@ -422,7 +412,7 @@ const GroupMembersScreen: React.FC = () => {
|
||||
|
||||
// 渲染空状态
|
||||
const renderEmpty = () => {
|
||||
if (loading) return <Loading />;
|
||||
if (loading || isLoading) return <Loading />;
|
||||
|
||||
return (
|
||||
<EmptyState
|
||||
@@ -589,7 +579,7 @@ const GroupMembersScreen: React.FC = () => {
|
||||
keyExtractor={(item) => item.title}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={refreshing}
|
||||
refreshing={isRefreshing}
|
||||
onRefresh={onRefresh}
|
||||
colors={[colors.primary.main]}
|
||||
tintColor={colors.primary.main}
|
||||
@@ -598,6 +588,23 @@ const GroupMembersScreen: React.FC = () => {
|
||||
onEndReached={loadMore}
|
||||
onEndReachedThreshold={0.3}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListFooterComponent={
|
||||
isLoading ? (
|
||||
<View style={styles.loadingFooter}>
|
||||
<Loading size="sm" />
|
||||
</View>
|
||||
) : hasMore ? (
|
||||
<TouchableOpacity style={styles.loadMoreBtn} onPress={loadMore}>
|
||||
<Text variant="caption" color={colors.primary.main}>
|
||||
加载更多成员
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
) : localMembers.length > 0 ? (
|
||||
<Text variant="caption" color={colors.text.hint} style={styles.noMoreText}>
|
||||
没有更多成员了
|
||||
</Text>
|
||||
) : null
|
||||
}
|
||||
renderItem={({ item: group }) => (
|
||||
<View style={styles.section}>
|
||||
{renderSectionHeader(group.title, group.data.length)}
|
||||
@@ -724,6 +731,19 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
marginHorizontal: spacing.xs,
|
||||
},
|
||||
// 分页加载样式
|
||||
loadingFooter: {
|
||||
paddingVertical: spacing.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
loadMoreBtn: {
|
||||
paddingVertical: spacing.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
noMoreText: {
|
||||
textAlign: 'center',
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
});
|
||||
|
||||
export default GroupMembersScreen;
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, StyleSheet, TextInput, TouchableOpacity, Alert, ActivityIndicator, Clipboard } from 'react-native';
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import {
|
||||
View,
|
||||
StyleSheet,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
Alert,
|
||||
ActivityIndicator,
|
||||
Clipboard,
|
||||
FlatList,
|
||||
RefreshControl,
|
||||
} from 'react-native';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
|
||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||
@@ -11,6 +21,8 @@ import { groupService } from '../../services/groupService';
|
||||
import { groupManager } from '../../stores/groupManager';
|
||||
import { RootStackParamList } from '../../navigation/types';
|
||||
import { GroupResponse, JoinType } from '../../types/dto';
|
||||
import { useCursorPagination } from '../../hooks/useCursorPagination';
|
||||
import { EmptyState } from '../../components/common';
|
||||
|
||||
type NavigationProp = NativeStackNavigationProp<RootStackParamList>;
|
||||
|
||||
@@ -18,10 +30,29 @@ const JoinGroupScreen: React.FC = () => {
|
||||
const navigation = useNavigation<NavigationProp>();
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [joining, setJoining] = useState(false);
|
||||
const [group, setGroup] = useState<GroupResponse | null>(null);
|
||||
const [joiningGroupId, setJoiningGroupId] = useState<string | null>(null);
|
||||
const [searchedGroup, setSearchedGroup] = useState<GroupResponse | null>(null);
|
||||
const [searched, setSearched] = useState(false);
|
||||
|
||||
// 使用游标分页 Hook 管理群组列表
|
||||
const {
|
||||
items: groups,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
hasMore,
|
||||
loadMore,
|
||||
refresh,
|
||||
error,
|
||||
} = useCursorPagination(
|
||||
async ({ cursor, pageSize }) => {
|
||||
return await groupService.getGroupsCursor({
|
||||
cursor,
|
||||
page_size: pageSize,
|
||||
});
|
||||
},
|
||||
{ pageSize: 20 }
|
||||
);
|
||||
|
||||
const getJoinTypeText = (joinType: JoinType) => {
|
||||
if (joinType === 0) return '允许加入';
|
||||
if (joinType === 1) return '需要审批';
|
||||
@@ -39,9 +70,9 @@ const JoinGroupScreen: React.FC = () => {
|
||||
setSearched(true);
|
||||
try {
|
||||
const result = await groupManager.getGroup(trimmed, true);
|
||||
setGroup(result);
|
||||
setSearchedGroup(result);
|
||||
} catch (error: any) {
|
||||
setGroup(null);
|
||||
setSearchedGroup(null);
|
||||
const message = error?.response?.data?.message || error?.message || '';
|
||||
if (String(message).includes('不存在') || error?.response?.status === 404) {
|
||||
Alert.alert('未找到', '未搜索到该群聊,请确认群ID是否正确');
|
||||
@@ -53,9 +84,9 @@ const JoinGroupScreen: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleJoin = async () => {
|
||||
const handleJoin = async (group: GroupResponse) => {
|
||||
if (!group?.id) return;
|
||||
setJoining(true);
|
||||
setJoiningGroupId(String(group.id));
|
||||
try {
|
||||
await groupService.joinGroup(group.id);
|
||||
Alert.alert('成功', '操作已提交', [
|
||||
@@ -71,13 +102,12 @@ const JoinGroupScreen: React.FC = () => {
|
||||
'操作失败,请稍后重试';
|
||||
Alert.alert('操作失败', String(message));
|
||||
} finally {
|
||||
setJoining(false);
|
||||
setJoiningGroupId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCopyGroupId = () => {
|
||||
if (!group?.id) return;
|
||||
Clipboard.setString(String(group.id));
|
||||
const handleCopyGroupId = (groupId: string | number) => {
|
||||
Clipboard.setString(String(groupId));
|
||||
Alert.alert('已复制', '群号已复制到剪贴板');
|
||||
};
|
||||
|
||||
@@ -87,6 +117,99 @@ const JoinGroupScreen: React.FC = () => {
|
||||
return `${raw.slice(0, 6)}...${raw.slice(-4)}`;
|
||||
};
|
||||
|
||||
const renderGroupItem = ({ item: group }: { item: GroupResponse }) => {
|
||||
const isJoining = joiningGroupId === String(group.id);
|
||||
|
||||
return (
|
||||
<View style={styles.groupCard}>
|
||||
<View style={styles.groupHeader}>
|
||||
<Avatar source={group.avatar} size={52} name={group.name} />
|
||||
<View style={styles.groupMeta}>
|
||||
<Text variant="body" style={styles.groupName} numberOfLines={1}>
|
||||
{group.name}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
{!!group.description && (
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.groupDesc}>
|
||||
{group.description}
|
||||
</Text>
|
||||
)}
|
||||
<View style={styles.groupInfoRow}>
|
||||
<Text variant="caption" color={colors.text.secondary}>
|
||||
成员 {group.member_count}/{group.max_members}
|
||||
</Text>
|
||||
<Text variant="caption" color={colors.text.secondary}>
|
||||
{getJoinTypeText(group.join_type)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.groupNoRow}>
|
||||
<Text variant="caption" color={colors.text.secondary}>
|
||||
群号:{formatGroupNo(group.id)}
|
||||
</Text>
|
||||
<TouchableOpacity style={styles.copyBtn} onPress={() => handleCopyGroupId(group.id)}>
|
||||
<MaterialCommunityIcons name="content-copy" size={14} color={colors.primary.main} />
|
||||
<Text variant="caption" color={colors.primary.main} style={styles.copyBtnText}>
|
||||
复制
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
style={[styles.submitBtn, isJoining && styles.submitBtnDisabled]}
|
||||
onPress={() => handleJoin(group)}
|
||||
disabled={isJoining}
|
||||
>
|
||||
{isJoining ? (
|
||||
<ActivityIndicator color="#fff" />
|
||||
) : (
|
||||
<>
|
||||
<MaterialCommunityIcons name="send-outline" size={18} color="#fff" />
|
||||
<Text variant="body" color="#fff" style={styles.submitText}>
|
||||
申请入群
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
const renderEmptyList = () => {
|
||||
if (isLoading) return null;
|
||||
return (
|
||||
<EmptyState
|
||||
title="暂无群组"
|
||||
description="还没有可加入的群组"
|
||||
icon="account-group-outline"
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const renderSearchResult = () => {
|
||||
if (!searched) return null;
|
||||
|
||||
if (searchedGroup) {
|
||||
return (
|
||||
<View style={styles.searchResultSection}>
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.sectionTitle}>
|
||||
搜索结果
|
||||
</Text>
|
||||
{renderGroupItem({ item: searchedGroup })}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!searching) {
|
||||
return (
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.emptyText}>
|
||||
暂无搜索结果,请检查群ID后重试
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.heroCard}>
|
||||
@@ -100,23 +223,25 @@ const JoinGroupScreen: React.FC = () => {
|
||||
</View>
|
||||
|
||||
<View style={styles.formCard}>
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.label}>搜索群聊(群ID)</Text>
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.label}>
|
||||
搜索群聊(群ID)
|
||||
</Text>
|
||||
<View style={styles.searchRow}>
|
||||
<TextInput
|
||||
value={keyword}
|
||||
onChangeText={setKeyword}
|
||||
placeholder="例如:7391234567890"
|
||||
placeholderTextColor={colors.text.hint}
|
||||
placeholder="例如:7391234567890"
|
||||
placeholderTextColor={colors.text.hint}
|
||||
style={styles.input}
|
||||
editable={!searching && !joining}
|
||||
autoCapitalize="none"
|
||||
cursorColor={colors.primary.main}
|
||||
selectionColor={`${colors.primary.main}40`}
|
||||
editable={!searching && !joiningGroupId}
|
||||
autoCapitalize="none"
|
||||
cursorColor={colors.primary.main}
|
||||
selectionColor={`${colors.primary.main}40`}
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={[styles.searchBtn, (!keyword.trim() || searching || joining) && styles.submitBtnDisabled]}
|
||||
style={[styles.searchBtn, (!keyword.trim() || searching || !!joiningGroupId) && styles.submitBtnDisabled]}
|
||||
onPress={handleSearch}
|
||||
disabled={!keyword.trim() || searching || joining}
|
||||
disabled={!keyword.trim() || searching || !!joiningGroupId}
|
||||
>
|
||||
{searching ? (
|
||||
<ActivityIndicator color="#fff" />
|
||||
@@ -126,58 +251,49 @@ const JoinGroupScreen: React.FC = () => {
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{group && (
|
||||
<View style={styles.groupCard}>
|
||||
<View style={styles.groupHeader}>
|
||||
<Avatar source={group.avatar} size={52} name={group.name} />
|
||||
<View style={styles.groupMeta}>
|
||||
<Text variant="body" style={styles.groupName} numberOfLines={1}>{group.name}</Text>
|
||||
</View>
|
||||
</View>
|
||||
{!!group.description && (
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.groupDesc}>
|
||||
{group.description}
|
||||
</Text>
|
||||
)}
|
||||
<View style={styles.groupInfoRow}>
|
||||
<Text variant="caption" color={colors.text.secondary}>
|
||||
成员 {group.member_count}/{group.max_members}
|
||||
</Text>
|
||||
<Text variant="caption" color={colors.text.secondary}>
|
||||
{getJoinTypeText(group.join_type)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.groupNoRow}>
|
||||
<Text variant="caption" color={colors.text.secondary}>
|
||||
群号:{formatGroupNo(group.id)}
|
||||
</Text>
|
||||
<TouchableOpacity style={styles.copyBtn} onPress={handleCopyGroupId}>
|
||||
<MaterialCommunityIcons name="content-copy" size={14} color={colors.primary.main} />
|
||||
<Text variant="caption" color={colors.primary.main} style={styles.copyBtnText}>复制</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
style={[styles.submitBtn, joining && styles.submitBtnDisabled]}
|
||||
onPress={handleJoin}
|
||||
disabled={joining}
|
||||
>
|
||||
{joining ? (
|
||||
<ActivityIndicator color="#fff" />
|
||||
) : (
|
||||
<>
|
||||
<MaterialCommunityIcons name="send-outline" size={18} color="#fff" />
|
||||
<Text variant="body" color="#fff" style={styles.submitText}>申请入群</Text>
|
||||
</>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
{/* 搜索结果 */}
|
||||
{renderSearchResult()}
|
||||
|
||||
{searched && !group && !searching && (
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.emptyText}>
|
||||
暂无搜索结果,请检查群ID后重试
|
||||
{/* 群组列表 */}
|
||||
<View style={styles.listSection}>
|
||||
<Text variant="caption" color={colors.text.secondary} style={styles.sectionTitle}>
|
||||
推荐群组
|
||||
</Text>
|
||||
)}
|
||||
<FlatList
|
||||
data={groups}
|
||||
renderItem={renderGroupItem}
|
||||
keyExtractor={(item) => String(item.id)}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={isRefreshing}
|
||||
onRefresh={refresh}
|
||||
colors={[colors.primary.main]}
|
||||
tintColor={colors.primary.main}
|
||||
/>
|
||||
}
|
||||
onEndReached={loadMore}
|
||||
onEndReachedThreshold={0.3}
|
||||
ListEmptyComponent={renderEmptyList}
|
||||
ListFooterComponent={
|
||||
isLoading ? (
|
||||
<View style={styles.loadingFooter}>
|
||||
<ActivityIndicator color={colors.primary.main} />
|
||||
</View>
|
||||
) : hasMore ? (
|
||||
<TouchableOpacity style={styles.loadMoreBtn} onPress={loadMore}>
|
||||
<Text variant="caption" color={colors.primary.main}>
|
||||
加载更多
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
) : groups.length > 0 ? (
|
||||
<Text variant="caption" color={colors.text.hint} style={styles.noMoreText}>
|
||||
没有更多群组了
|
||||
</Text>
|
||||
) : null
|
||||
}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -214,6 +330,7 @@ const styles = StyleSheet.create({
|
||||
backgroundColor: colors.background.paper,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.lg,
|
||||
flex: 1,
|
||||
},
|
||||
label: {
|
||||
marginBottom: spacing.xs,
|
||||
@@ -242,12 +359,23 @@ const styles = StyleSheet.create({
|
||||
justifyContent: 'center',
|
||||
marginLeft: spacing.sm,
|
||||
},
|
||||
searchResultSection: {
|
||||
marginBottom: spacing.lg,
|
||||
},
|
||||
sectionTitle: {
|
||||
marginBottom: spacing.sm,
|
||||
fontWeight: '600',
|
||||
},
|
||||
listSection: {
|
||||
flex: 1,
|
||||
},
|
||||
groupCard: {
|
||||
borderWidth: 1,
|
||||
borderColor: colors.divider,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.background.default,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
groupHeader: {
|
||||
flexDirection: 'row',
|
||||
@@ -259,6 +387,7 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
groupName: {
|
||||
marginBottom: spacing.xs,
|
||||
fontWeight: '600',
|
||||
},
|
||||
groupDesc: {
|
||||
marginTop: spacing.sm,
|
||||
@@ -303,6 +432,19 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
emptyText: {
|
||||
marginTop: spacing.sm,
|
||||
textAlign: 'center',
|
||||
},
|
||||
loadingFooter: {
|
||||
paddingVertical: spacing.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
loadMoreBtn: {
|
||||
paddingVertical: spacing.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
noMoreText: {
|
||||
textAlign: 'center',
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -30,12 +30,13 @@ import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
|
||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||
import { colors, spacing, fontSizes, shadows, borderRadius } from '../../theme';
|
||||
import { ConversationResponse, UserDTO, MessageResponse, extractTextFromSegments, extractTextFromSegmentsAsync, MessageSegment } from '../../types/dto';
|
||||
import { authService } from '../../services';
|
||||
import { authService, messageService } from '../../services';
|
||||
import { useUserStore, useAuthStore } from '../../stores';
|
||||
// 【新架构】使用MessageManager hooks
|
||||
import { useMessageList, messageManager, useMessageListRefresh, useCreateConversation } from '../../stores';
|
||||
import { messageManager, useMessageListRefresh, useCreateConversation, useUnreadCount, useMarkAsRead } from '../../stores';
|
||||
import { Avatar, Text, EmptyState, ResponsiveContainer } from '../../components/common';
|
||||
import { useResponsive, useBreakpointGTE } from '../../hooks/useResponsive';
|
||||
import { useCursorPagination } from '../../hooks/useCursorPagination';
|
||||
import { RootStackParamList, MessageStackParamList } from '../../navigation/types';
|
||||
import { getUserCache } from '../../services/database';
|
||||
// 导入 EmbeddedChat 组件用于桌面端双栏布局
|
||||
@@ -160,22 +161,43 @@ export const MessageListScreen: React.FC = () => {
|
||||
const { isDesktop, isTablet, width } = useResponsive();
|
||||
const isWideScreen = useBreakpointGTE('lg');
|
||||
|
||||
// 【新架构】使用MessageManager的hook获取数据
|
||||
// 【游标分页】使用 useCursorPagination hook 获取会话列表
|
||||
const {
|
||||
conversations,
|
||||
items: conversations,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
hasMore,
|
||||
loadMore,
|
||||
refresh,
|
||||
totalUnreadCount,
|
||||
systemUnreadCount,
|
||||
markAllAsRead,
|
||||
isMarking,
|
||||
} = useMessageList();
|
||||
error: paginationError,
|
||||
} = useCursorPagination(
|
||||
async ({ cursor, pageSize }) => {
|
||||
return await messageService.getConversationsCursor({
|
||||
cursor,
|
||||
page_size: pageSize,
|
||||
});
|
||||
},
|
||||
{ pageSize: 20 }
|
||||
);
|
||||
|
||||
// 使用 MessageManager 获取未读数和系统通知数
|
||||
const { totalUnreadCount, systemUnreadCount } = useUnreadCount();
|
||||
const { markAllAsRead, isMarking } = useMarkAsRead(null);
|
||||
|
||||
// 【新架构】使用MessageManager的hook创建会话
|
||||
const { createConversation } = useCreateConversation();
|
||||
|
||||
// 本地刷新状态(仅用于下拉刷新的UI显示)
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
// 上拉加载更多
|
||||
const onEndReached = useCallback(async () => {
|
||||
if (isLoading || loadingMore || !hasMore) return;
|
||||
setLoadingMore(true);
|
||||
await loadMore();
|
||||
setLoadingMore(false);
|
||||
}, [isLoading, loadingMore, hasMore, loadMore]);
|
||||
|
||||
// 搜索相关状态
|
||||
const [isSearchMode, setIsSearchMode] = useState(false);
|
||||
@@ -885,7 +907,7 @@ export const MessageListScreen: React.FC = () => {
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
|
||||
{isLoading ? (
|
||||
{isLoading && conversations.length === 0 ? (
|
||||
<View style={styles.loadingContainer}>
|
||||
<ActivityIndicator size="large" color={colors.primary.main} />
|
||||
</View>
|
||||
@@ -901,6 +923,8 @@ export const MessageListScreen: React.FC = () => {
|
||||
]}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListEmptyComponent={renderEmpty}
|
||||
onEndReached={onEndReached}
|
||||
onEndReachedThreshold={0.5}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={refreshing}
|
||||
@@ -909,6 +933,14 @@ export const MessageListScreen: React.FC = () => {
|
||||
tintColor={colors.primary.main}
|
||||
/>
|
||||
}
|
||||
ListFooterComponent={
|
||||
loadingMore ? (
|
||||
<View style={styles.loadingMoreContainer}>
|
||||
<ActivityIndicator size="small" color={colors.primary.main} />
|
||||
<Text style={styles.loadingMoreText}>加载中...</Text>
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
@@ -1261,6 +1293,17 @@ const styles = StyleSheet.create({
|
||||
alignItems: 'center',
|
||||
paddingVertical: spacing.xl * 2,
|
||||
},
|
||||
loadingMoreContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
loadingMoreText: {
|
||||
marginLeft: spacing.sm,
|
||||
fontSize: 14,
|
||||
color: '#999',
|
||||
},
|
||||
searchModeContainer: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAFAFA',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 通知页 NotificationsScreen
|
||||
* 胡萝卜BBS - 系统消息列表
|
||||
* 使用新的系统消息API
|
||||
* 【游标分页】使用 messageService.getSystemMessagesCursor
|
||||
* 支持响应式布局
|
||||
*/
|
||||
|
||||
@@ -26,6 +26,7 @@ import { messageService } from '../../services/messageService';
|
||||
import { commentService } from '../../services/commentService';
|
||||
import { SystemMessageItem } from '../../components/business';
|
||||
import { Text, EmptyState, ResponsiveContainer } from '../../components/common';
|
||||
import { useCursorPagination } from '../../hooks/useCursorPagination';
|
||||
import { RootStackParamList } from '../../navigation/types';
|
||||
import { useMessageManagerSystemUnreadCount, useUserStore } from '../../stores';
|
||||
|
||||
@@ -70,14 +71,32 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
// Web端使用更大的容器宽度
|
||||
const containerMaxWidth = isDesktop ? 1200 : isTablet ? 1000 : 900;
|
||||
|
||||
const [messages, setMessages] = useState<SystemMessageResponse[]>([]);
|
||||
const [activeType, setActiveType] = useState('all');
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [unreadCount, setUnreadCount] = useState(0);
|
||||
|
||||
// 【游标分页】使用 useCursorPagination hook 获取系统消息列表
|
||||
const {
|
||||
items: messages,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
hasMore,
|
||||
loadMore,
|
||||
refresh,
|
||||
error: paginationError,
|
||||
} = useCursorPagination(
|
||||
async ({ cursor, pageSize }) => {
|
||||
return await messageService.getSystemMessagesCursor({
|
||||
cursor,
|
||||
page_size: pageSize,
|
||||
});
|
||||
},
|
||||
{ pageSize: 20 }
|
||||
);
|
||||
|
||||
// 本地刷新状态(仅用于下拉刷新的UI显示)
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
// 同一 flag 只要有人审批过,就将待处理消息同步展示为已处理状态
|
||||
const displayMessages = useMemo(() => {
|
||||
const reviewedByFlag = new Map<string, SystemMessageResponse>();
|
||||
@@ -116,21 +135,6 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
});
|
||||
}, [messages]);
|
||||
|
||||
// 获取系统消息数据
|
||||
const fetchMessages = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await messageService.getSystemMessages(50, 1);
|
||||
// 添加防御性检查,确保 messages 数组存在
|
||||
setMessages(response.messages || []);
|
||||
setHasMore(response.has_more ?? false);
|
||||
} catch (error) {
|
||||
console.error('获取系统消息失败:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 获取未读数
|
||||
const fetchUnreadCount = useCallback(async () => {
|
||||
try {
|
||||
@@ -145,27 +149,25 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
const handleMarkAllRead = useCallback(async () => {
|
||||
try {
|
||||
await messageService.markAllSystemMessagesRead();
|
||||
setMessages(prev => prev.map(m => ({ ...m, is_read: true })));
|
||||
// 刷新消息列表
|
||||
await refresh();
|
||||
setUnreadCount(0);
|
||||
setSystemUnreadCount(0);
|
||||
// 同步更新全局 TabBar 红点
|
||||
fetchMessageUnreadCount();
|
||||
// 刷新消息列表
|
||||
fetchMessages();
|
||||
} catch (error) {
|
||||
console.error('一键已读失败:', error);
|
||||
}
|
||||
}, [fetchMessages, fetchMessageUnreadCount, setSystemUnreadCount]);
|
||||
}, [refresh, fetchMessageUnreadCount, setSystemUnreadCount]);
|
||||
|
||||
// 页面加载和获得焦点时刷新,并自动标记所有消息为已读
|
||||
useEffect(() => {
|
||||
if (isFocused) {
|
||||
fetchMessages();
|
||||
fetchUnreadCount();
|
||||
// 进入界面自动标记所有消息为已读
|
||||
handleMarkAllRead();
|
||||
}
|
||||
}, [isFocused, fetchMessages, fetchUnreadCount, handleMarkAllRead]);
|
||||
}, [isFocused, fetchUnreadCount, handleMarkAllRead]);
|
||||
|
||||
// 屏幕失去焦点时,如果有 onBack 回调则调用它(用于内嵌模式)
|
||||
useEffect(() => {
|
||||
@@ -190,29 +192,17 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
// 下拉刷新
|
||||
const onRefresh = useCallback(async () => {
|
||||
setRefreshing(true);
|
||||
await Promise.all([fetchMessages(), fetchUnreadCount()]);
|
||||
await Promise.all([refresh(), fetchUnreadCount()]);
|
||||
setRefreshing(false);
|
||||
}, [fetchMessages, fetchUnreadCount]);
|
||||
}, [refresh, fetchUnreadCount]);
|
||||
|
||||
// 加载更多
|
||||
const loadMore = useCallback(async () => {
|
||||
if (loadingMore || !hasMore || messages.length === 0) return;
|
||||
|
||||
try {
|
||||
setLoadingMore(true);
|
||||
// 使用时间戳或seq作为游标分页(后端使用page分页)
|
||||
const nextPage = Math.floor((messages.length / 20)) + 1;
|
||||
const response = await messageService.getSystemMessages(20, nextPage);
|
||||
// 添加防御性检查
|
||||
const newMessages = response.messages || [];
|
||||
setMessages(prev => [...prev, ...newMessages]);
|
||||
setHasMore(response.has_more ?? false);
|
||||
} catch (error) {
|
||||
console.error('加载更多失败:', error);
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}, [loadingMore, hasMore, messages]);
|
||||
const onEndReached = useCallback(async () => {
|
||||
if (isLoading || loadingMore || !hasMore) return;
|
||||
setLoadingMore(true);
|
||||
await loadMore();
|
||||
setLoadingMore(false);
|
||||
}, [isLoading, loadingMore, hasMore, loadMore]);
|
||||
|
||||
// 标记单条消息已读并处理导航
|
||||
const extractPostIdFromActionUrl = (actionUrl?: string): string | null => {
|
||||
@@ -262,9 +252,7 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
const messageId = String(message.id);
|
||||
const wasUnread = message.is_read !== true;
|
||||
await messageService.markSystemMessageRead(messageId);
|
||||
setMessages(prev =>
|
||||
prev.map(m => (String(m.id) === messageId ? { ...m, is_read: true } : m))
|
||||
);
|
||||
// 【游标分页】不再直接修改 messages 状态,而是通过刷新获取最新数据
|
||||
if (wasUnread) {
|
||||
setUnreadCount(prev => Math.max(0, prev - 1));
|
||||
decrementSystemUnreadCount(1);
|
||||
@@ -431,7 +419,7 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
</View>
|
||||
|
||||
{/* 消息列表 */}
|
||||
{loading ? (
|
||||
{isLoading && messages.length === 0 ? (
|
||||
<View style={styles.loadingContainer}>
|
||||
<ActivityIndicator size="large" color={colors.primary.main} />
|
||||
</View>
|
||||
@@ -444,7 +432,7 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListEmptyComponent={renderEmpty}
|
||||
ListFooterComponent={renderFooter}
|
||||
onEndReached={loadMore}
|
||||
onEndReached={onEndReached}
|
||||
onEndReachedThreshold={0.3}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
@@ -505,7 +493,7 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
</View>
|
||||
|
||||
{/* 消息列表 */}
|
||||
{loading ? (
|
||||
{isLoading && messages.length === 0 ? (
|
||||
<View style={styles.loadingContainer}>
|
||||
<ActivityIndicator size="large" color={colors.primary.main} />
|
||||
</View>
|
||||
@@ -518,7 +506,7 @@ export const NotificationsScreen: React.FC<{ onBack?: () => void }> = ({ onBack
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListEmptyComponent={renderEmpty}
|
||||
ListFooterComponent={renderFooter}
|
||||
onEndReached={loadMore}
|
||||
onEndReached={onEndReached}
|
||||
onEndReachedThreshold={0.3}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
|
||||
Reference in New Issue
Block a user