Compare commits
2 Commits
c12b98e293
...
583ac64dfd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
583ac64dfd | ||
|
|
cedb8284ba |
@@ -1,11 +1,12 @@
|
|||||||
|
import { useMemo } from 'react';
|
||||||
import { Platform, useWindowDimensions } from 'react-native';
|
import { Platform, useWindowDimensions } from 'react-native';
|
||||||
import { Tabs } from 'expo-router';
|
import { Tabs, usePathname } from 'expo-router';
|
||||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||||
|
|
||||||
import { colors, shadows } from '../../../src/theme';
|
import { colors, shadows } from '../../../src/theme';
|
||||||
import { BREAKPOINTS } from '../../../src/hooks/useResponsive';
|
import { BREAKPOINTS } from '../../../src/hooks/useResponsive';
|
||||||
import { useTotalUnreadCount } from '../../../src/stores';
|
import { useHomeTabBarVisibilityStore, useTotalUnreadCount } from '../../../src/stores';
|
||||||
|
|
||||||
const TAB_BAR_HEIGHT = 56;
|
const TAB_BAR_HEIGHT = 56;
|
||||||
const TAB_BAR_FLOATING_MARGIN = 12;
|
const TAB_BAR_FLOATING_MARGIN = 12;
|
||||||
@@ -14,31 +15,50 @@ const TAB_BAR_MARGIN = 20;
|
|||||||
export default function TabsLayout() {
|
export default function TabsLayout() {
|
||||||
const { width } = useWindowDimensions();
|
const { width } = useWindowDimensions();
|
||||||
const insets = useSafeAreaInsets();
|
const insets = useSafeAreaInsets();
|
||||||
|
const pathname = usePathname();
|
||||||
const unreadCount = useTotalUnreadCount();
|
const unreadCount = useTotalUnreadCount();
|
||||||
|
const scrollHideTabBar = useHomeTabBarVisibilityStore((s) => s.bottomTabBarHiddenByScroll);
|
||||||
const hideTabBar = Platform.OS === 'web' && width >= BREAKPOINTS.desktop;
|
const hideTabBar = Platform.OS === 'web' && width >= BREAKPOINTS.desktop;
|
||||||
|
|
||||||
|
const isHomeStackRoute = pathname === '/home' || pathname.startsWith('/home/');
|
||||||
|
|
||||||
|
const tabBarStyle = useMemo(() => {
|
||||||
|
if (hideTabBar) {
|
||||||
|
return { display: 'none' as const, height: 0, overflow: 'hidden' as const };
|
||||||
|
}
|
||||||
|
const visibleStyle = {
|
||||||
|
position: 'absolute' as const,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
marginHorizontal: TAB_BAR_MARGIN,
|
||||||
|
bottom: TAB_BAR_FLOATING_MARGIN + insets.bottom,
|
||||||
|
height: TAB_BAR_HEIGHT,
|
||||||
|
borderRadius: 22,
|
||||||
|
backgroundColor: colors.background.paper,
|
||||||
|
...shadows.lg,
|
||||||
|
borderTopWidth: 0,
|
||||||
|
elevation: 100,
|
||||||
|
zIndex: 100,
|
||||||
|
};
|
||||||
|
if (isHomeStackRoute && scrollHideTabBar) {
|
||||||
|
return {
|
||||||
|
...visibleStyle,
|
||||||
|
display: 'none' as const,
|
||||||
|
height: 0,
|
||||||
|
opacity: 0,
|
||||||
|
overflow: 'hidden' as const,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return visibleStyle;
|
||||||
|
}, [hideTabBar, insets.bottom, isHomeStackRoute, scrollHideTabBar]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Tabs
|
<Tabs
|
||||||
screenOptions={{
|
screenOptions={{
|
||||||
headerShown: false,
|
headerShown: false,
|
||||||
tabBarActiveTintColor: colors.primary.main,
|
tabBarActiveTintColor: colors.primary.main,
|
||||||
tabBarInactiveTintColor: colors.text.secondary,
|
tabBarInactiveTintColor: colors.text.secondary,
|
||||||
tabBarStyle: hideTabBar
|
tabBarStyle,
|
||||||
? { display: 'none', height: 0, overflow: 'hidden' }
|
|
||||||
: {
|
|
||||||
position: 'absolute',
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
marginHorizontal: TAB_BAR_MARGIN,
|
|
||||||
bottom: TAB_BAR_FLOATING_MARGIN + insets.bottom,
|
|
||||||
height: TAB_BAR_HEIGHT,
|
|
||||||
borderRadius: 22,
|
|
||||||
backgroundColor: colors.background.paper,
|
|
||||||
...shadows.lg,
|
|
||||||
borderTopWidth: 0,
|
|
||||||
elevation: 100,
|
|
||||||
zIndex: 100,
|
|
||||||
},
|
|
||||||
tabBarItemStyle: {
|
tabBarItemStyle: {
|
||||||
borderRadius: 16,
|
borderRadius: 16,
|
||||||
marginHorizontal: 2,
|
marginHorizontal: 2,
|
||||||
@@ -62,11 +82,15 @@ export default function TabsLayout() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Tabs.Screen
|
<Tabs.Screen
|
||||||
name="schedule"
|
name="apps"
|
||||||
options={{
|
options={{
|
||||||
title: '课表',
|
title: '应用',
|
||||||
tabBarIcon: ({ color, focused }) => (
|
tabBarIcon: ({ color, focused }) => (
|
||||||
<MaterialCommunityIcons name="calendar-today" size={focused ? 24 : 22} color={color} />
|
<MaterialCommunityIcons
|
||||||
|
name={focused ? 'view-grid' : 'view-grid-outline'}
|
||||||
|
size={focused ? 24 : 22}
|
||||||
|
color={color}
|
||||||
|
/>
|
||||||
),
|
),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
5
app/(app)/(tabs)/apps/_layout.tsx
Normal file
5
app/(app)/(tabs)/apps/_layout.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { Stack } from 'expo-router';
|
||||||
|
|
||||||
|
export default function AppsStackLayout() {
|
||||||
|
return <Stack screenOptions={{ headerShown: false }} />;
|
||||||
|
}
|
||||||
5
app/(app)/(tabs)/apps/index.tsx
Normal file
5
app/(app)/(tabs)/apps/index.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { AppsScreen } from '../../../../src/screens/apps';
|
||||||
|
|
||||||
|
export default function AppsRoute() {
|
||||||
|
return <AppsScreen />;
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { CourseDetailScreen } from '../../../../src/screens/schedule';
|
import { CourseDetailScreen } from '../../../../../src/screens/schedule';
|
||||||
|
|
||||||
export default function CourseDetailRoute() {
|
export default function CourseDetailRoute() {
|
||||||
return <CourseDetailScreen />;
|
return <CourseDetailScreen />;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ScheduleScreen } from '../../../../src/screens/schedule';
|
import { ScheduleScreen } from '../../../../../src/screens/schedule';
|
||||||
|
|
||||||
export default function ScheduleRoute() {
|
export default function ScheduleRoute() {
|
||||||
return <ScheduleScreen />;
|
return <ScheduleScreen />;
|
||||||
@@ -8,6 +8,7 @@ import { PaperProvider } from 'react-native-paper';
|
|||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
import * as Notifications from 'expo-notifications';
|
import * as Notifications from 'expo-notifications';
|
||||||
|
|
||||||
|
import { registerNotificationPresentationHandler } from '../src/services/notificationPreferences';
|
||||||
import { paperTheme } from '../src/theme';
|
import { paperTheme } from '../src/theme';
|
||||||
import { AppBackButton } from '../src/components/common';
|
import { AppBackButton } from '../src/components/common';
|
||||||
import AppPromptBar from '../src/components/common/AppPromptBar';
|
import AppPromptBar from '../src/components/common/AppPromptBar';
|
||||||
@@ -16,15 +17,7 @@ import { installAlertOverride } from '../src/services/alertOverride';
|
|||||||
import { useAuthStore } from '../src/stores';
|
import { useAuthStore } from '../src/stores';
|
||||||
import { colors } from '../src/theme';
|
import { colors } from '../src/theme';
|
||||||
|
|
||||||
Notifications.setNotificationHandler({
|
registerNotificationPresentationHandler();
|
||||||
handleNotification: async () => ({
|
|
||||||
shouldShowAlert: true,
|
|
||||||
shouldPlaySound: true,
|
|
||||||
shouldSetBadge: true,
|
|
||||||
shouldShowBanner: true,
|
|
||||||
shouldShowList: true,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
@@ -78,6 +71,8 @@ function NotificationBootstrap() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const initNotifications = async () => {
|
const initNotifications = async () => {
|
||||||
|
const { loadNotificationPreferences } = await import('../src/services/notificationPreferences');
|
||||||
|
await loadNotificationPreferences();
|
||||||
const { systemNotificationService } = await import('../src/services/systemNotificationService');
|
const { systemNotificationService } = await import('../src/services/systemNotificationService');
|
||||||
await systemNotificationService.initialize();
|
await systemNotificationService.initialize();
|
||||||
const { initBackgroundService } = await import('../src/services/backgroundService');
|
const { initBackgroundService } = await import('../src/services/backgroundService');
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import { colors, shadows } from '../theme';
|
|||||||
import { useTotalUnreadCount } from '../stores';
|
import { useTotalUnreadCount } from '../stores';
|
||||||
import { AppRouteStack } from './AppRouteStack';
|
import { AppRouteStack } from './AppRouteStack';
|
||||||
|
|
||||||
type TabName = 'HomeTab' | 'MessageTab' | 'ScheduleTab' | 'ProfileTab';
|
type TabName = 'HomeTab' | 'MessageTab' | 'AppsTab' | 'ProfileTab';
|
||||||
|
|
||||||
const SIDEBAR_WIDTH_DESKTOP = 240;
|
const SIDEBAR_WIDTH_DESKTOP = 240;
|
||||||
const SIDEBAR_WIDTH_TABLET = 200;
|
const SIDEBAR_WIDTH_TABLET = 200;
|
||||||
@@ -23,14 +23,14 @@ const SIDEBAR_COLLAPSED_WIDTH = 72;
|
|||||||
|
|
||||||
const NAV_ITEMS: { name: TabName; label: string; href: string; icon: string; iconOutline: string }[] = [
|
const NAV_ITEMS: { name: TabName; label: string; href: string; icon: string; iconOutline: string }[] = [
|
||||||
{ name: 'HomeTab', label: '首页', href: '/home', icon: 'home', iconOutline: 'home-outline' },
|
{ name: 'HomeTab', label: '首页', href: '/home', icon: 'home', iconOutline: 'home-outline' },
|
||||||
|
{ name: 'AppsTab', label: '应用', href: '/apps', icon: 'view-grid', iconOutline: 'view-grid-outline' },
|
||||||
{ name: 'MessageTab', label: '消息', href: '/messages', icon: 'message-text', iconOutline: 'message-text-outline' },
|
{ name: 'MessageTab', label: '消息', href: '/messages', icon: 'message-text', iconOutline: 'message-text-outline' },
|
||||||
{ name: 'ScheduleTab', label: '课表', href: '/schedule', icon: 'calendar-today', iconOutline: 'calendar-today' },
|
|
||||||
{ name: 'ProfileTab', label: '我的', href: '/profile', icon: 'account', iconOutline: 'account-outline' },
|
{ name: 'ProfileTab', label: '我的', href: '/profile', icon: 'account', iconOutline: 'account-outline' },
|
||||||
];
|
];
|
||||||
|
|
||||||
function pathToTab(pathname: string): TabName {
|
function pathToTab(pathname: string): TabName {
|
||||||
if (pathname.startsWith('/messages')) return 'MessageTab';
|
if (pathname.startsWith('/messages')) return 'MessageTab';
|
||||||
if (pathname.startsWith('/schedule')) return 'ScheduleTab';
|
if (pathname.startsWith('/apps')) return 'AppsTab';
|
||||||
if (pathname.startsWith('/profile')) return 'ProfileTab';
|
if (pathname.startsWith('/profile')) return 'ProfileTab';
|
||||||
if (pathname.startsWith('/home')) return 'HomeTab';
|
if (pathname.startsWith('/home')) return 'HomeTab';
|
||||||
return 'HomeTab';
|
return 'HomeTab';
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
/**
|
/**
|
||||||
* CommentItem 评论项组件 - QQ频道风格
|
* CommentItem 评论项组件 - 小红书 / 贴吧式平铺列表
|
||||||
* 支持嵌套回复显示、楼层号、身份标识、删除评论、图片显示
|
* 支持嵌套回复显示、楼层号、身份标识、删除评论、图片显示
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { View, TouchableOpacity, StyleSheet, Alert, Dimensions } from 'react-native';
|
import { View, TouchableOpacity, StyleSheet, Alert } from 'react-native';
|
||||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
import { formatDistanceToNow } from 'date-fns';
|
import { formatDistanceToNow } from 'date-fns';
|
||||||
import { zhCN } from 'date-fns/locale';
|
import { zhCN } from 'date-fns/locale';
|
||||||
@@ -14,8 +14,6 @@ import Text from '../common/Text';
|
|||||||
import Avatar from '../common/Avatar';
|
import Avatar from '../common/Avatar';
|
||||||
import { CompactImageGrid, ImageGridItem } from '../common';
|
import { CompactImageGrid, ImageGridItem } from '../common';
|
||||||
|
|
||||||
const { width: screenWidth } = Dimensions.get('window');
|
|
||||||
|
|
||||||
interface CommentItemProps {
|
interface CommentItemProps {
|
||||||
comment: Comment;
|
comment: Comment;
|
||||||
onUserPress: () => void;
|
onUserPress: () => void;
|
||||||
@@ -181,11 +179,9 @@ const CommentItem: React.FC<CommentItemProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.floorTag}>
|
<Text variant="caption" color={colors.text.hint} style={styles.floorPlain}>
|
||||||
<Text variant="caption" color={colors.text.hint} style={styles.floorText}>
|
{getFloorText(floorNumber)}
|
||||||
{getFloorText(floorNumber)}
|
</Text>
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -276,8 +272,9 @@ const CommentItem: React.FC<CommentItemProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.subRepliesContainer}>
|
<View style={styles.subRepliesContainer}>
|
||||||
{comment.replies.map((reply) => {
|
{comment.replies.map((reply, replyIndex) => {
|
||||||
const replyAuthorId = reply.author?.id || '';
|
const replyAuthorId = reply.author?.id || '';
|
||||||
|
const isLastReply = replyIndex === comment.replies!.length - 1;
|
||||||
// 根据 target_id 获取被回复的用户昵称
|
// 根据 target_id 获取被回复的用户昵称
|
||||||
const targetId = reply.target_id;
|
const targetId = reply.target_id;
|
||||||
const targetNickname = targetId ? getTargetUserNickname(targetId) : null;
|
const targetNickname = targetId ? getTargetUserNickname(targetId) : null;
|
||||||
@@ -287,7 +284,7 @@ const CommentItem: React.FC<CommentItemProps> = ({
|
|||||||
return (
|
return (
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
key={reply.id}
|
key={reply.id}
|
||||||
style={styles.subReplyItem}
|
style={[styles.subReplyItem, isLastReply && styles.subReplyItemLast]}
|
||||||
onPress={() => onReplyPress?.(reply)}
|
onPress={() => onReplyPress?.(reply)}
|
||||||
activeOpacity={0.7}
|
activeOpacity={0.7}
|
||||||
>
|
>
|
||||||
@@ -320,7 +317,7 @@ const CommentItem: React.FC<CommentItemProps> = ({
|
|||||||
</View>
|
</View>
|
||||||
{/* 显示回复内容(如果有文字) */}
|
{/* 显示回复内容(如果有文字) */}
|
||||||
{reply.content ? (
|
{reply.content ? (
|
||||||
<Text variant="caption" color={colors.text.secondary} numberOfLines={2}>
|
<Text variant="body" color={colors.text.primary} style={styles.subReplyBody}>
|
||||||
{reply.content}
|
{reply.content}
|
||||||
</Text>
|
</Text>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -375,11 +372,11 @@ const CommentItem: React.FC<CommentItemProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.container}>
|
<View style={styles.container}>
|
||||||
{/* 用户头像 */}
|
{/* 用户头像 - 略大便于点击,与正文左对齐 */}
|
||||||
<TouchableOpacity onPress={onUserPress}>
|
<TouchableOpacity onPress={onUserPress} activeOpacity={0.7}>
|
||||||
<Avatar
|
<Avatar
|
||||||
source={comment.author?.avatar}
|
source={comment.author?.avatar}
|
||||||
size={36}
|
size={40}
|
||||||
name={comment.author?.nickname}
|
name={comment.author?.nickname}
|
||||||
/>
|
/>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
@@ -389,12 +386,13 @@ const CommentItem: React.FC<CommentItemProps> = ({
|
|||||||
{/* 用户信息行 - QQ频道风格 */}
|
{/* 用户信息行 - QQ频道风格 */}
|
||||||
<View style={styles.header}>
|
<View style={styles.header}>
|
||||||
<View style={styles.userInfo}>
|
<View style={styles.userInfo}>
|
||||||
<TouchableOpacity onPress={onUserPress}>
|
<TouchableOpacity onPress={onUserPress} activeOpacity={0.7}>
|
||||||
<Text variant="body" style={styles.username}>
|
<Text variant="body" style={styles.username} numberOfLines={1}>
|
||||||
{comment.author?.nickname}
|
{comment.author?.nickname || '用户'}
|
||||||
</Text>
|
</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
{renderBadges()}
|
{renderBadges()}
|
||||||
|
<Text style={styles.metaDot}>·</Text>
|
||||||
<Text variant="caption" color={colors.text.hint} style={styles.timeText}>
|
<Text variant="caption" color={colors.text.hint} style={styles.timeText}>
|
||||||
{formatTime(comment.created_at || '')}
|
{formatTime(comment.created_at || '')}
|
||||||
</Text>
|
</Text>
|
||||||
@@ -477,31 +475,35 @@ const styles = StyleSheet.create({
|
|||||||
container: {
|
container: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
paddingTop: spacing.md,
|
paddingTop: spacing.md,
|
||||||
paddingBottom: spacing.xs,
|
paddingBottom: spacing.md,
|
||||||
paddingHorizontal: spacing.lg,
|
paddingHorizontal: spacing.md,
|
||||||
backgroundColor: 'transparent',
|
backgroundColor: colors.background.paper,
|
||||||
|
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||||
|
borderBottomColor: colors.divider,
|
||||||
},
|
},
|
||||||
content: {
|
content: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
marginLeft: spacing.sm,
|
marginLeft: spacing.sm,
|
||||||
backgroundColor: colors.background.paper,
|
minWidth: 0,
|
||||||
borderRadius: borderRadius.lg,
|
|
||||||
borderWidth: StyleSheet.hairlineWidth,
|
|
||||||
borderColor: colors.divider,
|
|
||||||
paddingHorizontal: spacing.md,
|
|
||||||
paddingVertical: spacing.sm,
|
|
||||||
},
|
},
|
||||||
header: {
|
header: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
justifyContent: 'space-between',
|
justifyContent: 'space-between',
|
||||||
alignItems: 'flex-start',
|
alignItems: 'center',
|
||||||
marginBottom: spacing.sm,
|
marginBottom: spacing.xs,
|
||||||
|
gap: spacing.xs,
|
||||||
},
|
},
|
||||||
userInfo: {
|
userInfo: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
flexWrap: 'wrap',
|
flexWrap: 'wrap',
|
||||||
flex: 1,
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
metaDot: {
|
||||||
|
fontSize: fontSizes.xs,
|
||||||
|
color: colors.text.hint,
|
||||||
|
marginHorizontal: 2,
|
||||||
},
|
},
|
||||||
username: {
|
username: {
|
||||||
fontWeight: '600',
|
fontWeight: '600',
|
||||||
@@ -537,42 +539,35 @@ const styles = StyleSheet.create({
|
|||||||
},
|
},
|
||||||
timeText: {
|
timeText: {
|
||||||
fontSize: fontSizes.xs,
|
fontSize: fontSizes.xs,
|
||||||
|
flexShrink: 0,
|
||||||
},
|
},
|
||||||
floorTag: {
|
floorPlain: {
|
||||||
backgroundColor: colors.background.default,
|
|
||||||
paddingHorizontal: spacing.xs,
|
|
||||||
paddingVertical: 2,
|
|
||||||
borderRadius: 999,
|
|
||||||
borderWidth: StyleSheet.hairlineWidth,
|
|
||||||
borderColor: colors.divider,
|
|
||||||
},
|
|
||||||
floorText: {
|
|
||||||
fontSize: fontSizes.xs,
|
fontSize: fontSizes.xs,
|
||||||
|
flexShrink: 0,
|
||||||
},
|
},
|
||||||
replyReference: {
|
replyReference: {
|
||||||
marginBottom: spacing.xs,
|
marginBottom: spacing.xs,
|
||||||
},
|
},
|
||||||
commentContent: {
|
commentContent: {
|
||||||
marginBottom: spacing.sm,
|
marginBottom: spacing.xs,
|
||||||
},
|
},
|
||||||
text: {
|
text: {
|
||||||
lineHeight: 20,
|
lineHeight: 22,
|
||||||
fontSize: fontSizes.md,
|
fontSize: fontSizes.md,
|
||||||
|
color: colors.text.primary,
|
||||||
},
|
},
|
||||||
actions: {
|
actions: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
|
marginTop: spacing.xs,
|
||||||
|
flexWrap: 'wrap',
|
||||||
},
|
},
|
||||||
actionButton: {
|
actionButton: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
marginRight: spacing.sm,
|
marginRight: spacing.lg,
|
||||||
paddingHorizontal: spacing.sm,
|
paddingVertical: 4,
|
||||||
paddingVertical: 5,
|
paddingRight: spacing.xs,
|
||||||
borderRadius: 999,
|
|
||||||
backgroundColor: colors.background.default,
|
|
||||||
borderWidth: StyleSheet.hairlineWidth,
|
|
||||||
borderColor: colors.divider,
|
|
||||||
},
|
},
|
||||||
actionText: {
|
actionText: {
|
||||||
marginLeft: 4,
|
marginLeft: 4,
|
||||||
@@ -580,16 +575,25 @@ const styles = StyleSheet.create({
|
|||||||
},
|
},
|
||||||
subRepliesContainer: {
|
subRepliesContainer: {
|
||||||
marginTop: spacing.sm,
|
marginTop: spacing.sm,
|
||||||
|
marginLeft: 0,
|
||||||
|
paddingLeft: spacing.sm,
|
||||||
|
paddingVertical: spacing.xs,
|
||||||
|
borderLeftWidth: 2,
|
||||||
|
borderLeftColor: colors.divider,
|
||||||
backgroundColor: colors.background.default,
|
backgroundColor: colors.background.default,
|
||||||
borderRadius: borderRadius.lg,
|
|
||||||
borderWidth: StyleSheet.hairlineWidth,
|
|
||||||
borderColor: colors.divider,
|
|
||||||
padding: spacing.sm,
|
|
||||||
},
|
},
|
||||||
subReplyItem: {
|
subReplyItem: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'flex-start',
|
alignItems: 'flex-start',
|
||||||
marginBottom: spacing.sm,
|
marginBottom: spacing.md,
|
||||||
|
},
|
||||||
|
subReplyItemLast: {
|
||||||
|
marginBottom: 0,
|
||||||
|
},
|
||||||
|
subReplyBody: {
|
||||||
|
fontSize: fontSizes.sm,
|
||||||
|
lineHeight: 20,
|
||||||
|
marginTop: 2,
|
||||||
},
|
},
|
||||||
subReplyContent: {
|
subReplyContent: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
|
|||||||
@@ -63,6 +63,11 @@ function topCommentSignature(tc: PostCardProps['post']['top_comment']): string {
|
|||||||
return [tc.id, tc.content ?? '', tc.author?.id ?? ''].join('\u001f');
|
return [tc.id, tc.content ?? '', tc.author?.id ?? ''].join('\u001f');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function channelSignature(ch: PostCardProps['post']['channel']): string {
|
||||||
|
if (!ch) return '';
|
||||||
|
return [ch.id, ch.name ?? ''].join('\u001f');
|
||||||
|
}
|
||||||
|
|
||||||
function featuresComparable(f: PostCardProps['features']): string {
|
function featuresComparable(f: PostCardProps['features']): string {
|
||||||
if (f == null) return '';
|
if (f == null) return '';
|
||||||
if (typeof f === 'string') return f;
|
if (typeof f === 'string') return f;
|
||||||
@@ -103,6 +108,7 @@ function arePostCardPropsEqual(prev: PostCardProps, next: PostCardProps): boolea
|
|||||||
if (authorSignature(a.author) !== authorSignature(b.author)) return false;
|
if (authorSignature(a.author) !== authorSignature(b.author)) return false;
|
||||||
if (imagesSignature(a.images) !== imagesSignature(b.images)) return false;
|
if (imagesSignature(a.images) !== imagesSignature(b.images)) return false;
|
||||||
if (topCommentSignature(a.top_comment) !== topCommentSignature(b.top_comment)) return false;
|
if (topCommentSignature(a.top_comment) !== topCommentSignature(b.top_comment)) return false;
|
||||||
|
if (channelSignature(a.channel) !== channelSignature(b.channel)) return false;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -302,6 +308,15 @@ const PostCardInner: React.FC<PostCardProps> = (normalizedProps) => {
|
|||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{!!post.channel?.name && (
|
||||||
|
<View style={styles.gridChannelRow}>
|
||||||
|
<MaterialCommunityIcons name="tag-outline" size={12} color={colors.text.hint} />
|
||||||
|
<Text style={styles.gridChannelText} numberOfLines={1}>
|
||||||
|
{post.channel.name}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
|
||||||
<View style={styles.gridFooter}>
|
<View style={styles.gridFooter}>
|
||||||
<TouchableOpacity onPress={handleUserPress} style={styles.gridUserArea}>
|
<TouchableOpacity onPress={handleUserPress} style={styles.gridUserArea}>
|
||||||
<Avatar source={author?.avatar} size={20} name={author?.nickname || '匿名用户'} />
|
<Avatar source={author?.avatar} size={20} name={author?.nickname || '匿名用户'} />
|
||||||
@@ -379,9 +394,19 @@ const PostCardInner: React.FC<PostCardProps> = (normalizedProps) => {
|
|||||||
{renderTopComment()}
|
{renderTopComment()}
|
||||||
|
|
||||||
<View style={styles.actions}>
|
<View style={styles.actions}>
|
||||||
<View style={styles.viewsWrap}>
|
<View style={styles.actionsLeading}>
|
||||||
<MaterialCommunityIcons name="eye-outline" size={16} color={colors.text.hint} />
|
<View style={styles.viewsWrap}>
|
||||||
<Text style={styles.viewsText}>{post.views_count || 0}</Text>
|
<MaterialCommunityIcons name="eye-outline" size={16} color={colors.text.hint} />
|
||||||
|
<Text style={styles.viewsText}>{post.views_count || 0}</Text>
|
||||||
|
</View>
|
||||||
|
{!!post.channel?.name && (
|
||||||
|
<View style={[styles.channelTag, styles.channelTagAfterViews]}>
|
||||||
|
<MaterialCommunityIcons name="tag-outline" size={11} color={colors.primary.main} />
|
||||||
|
<Text style={styles.channelTagText} numberOfLines={1}>
|
||||||
|
{post.channel.name}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
<View style={styles.actionButtons}>
|
<View style={styles.actionButtons}>
|
||||||
<TouchableOpacity style={styles.actionBtn} onPress={handleLike}>
|
<TouchableOpacity style={styles.actionBtn} onPress={handleLike}>
|
||||||
@@ -459,6 +484,23 @@ const styles = StyleSheet.create({
|
|||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
gap: 6,
|
gap: 6,
|
||||||
marginTop: 2,
|
marginTop: 2,
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
},
|
||||||
|
channelTag: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
maxWidth: 140,
|
||||||
|
paddingHorizontal: 6,
|
||||||
|
paddingVertical: 2,
|
||||||
|
borderRadius: borderRadius.sm,
|
||||||
|
backgroundColor: `${colors.primary.main}12`,
|
||||||
|
gap: 4,
|
||||||
|
},
|
||||||
|
channelTagText: {
|
||||||
|
fontSize: fontSizes.xs,
|
||||||
|
color: colors.primary.main,
|
||||||
|
fontWeight: '600',
|
||||||
|
flexShrink: 1,
|
||||||
},
|
},
|
||||||
pinnedTag: {
|
pinnedTag: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
@@ -531,9 +573,22 @@ const styles = StyleSheet.create({
|
|||||||
justifyContent: 'space-between',
|
justifyContent: 'space-between',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
},
|
},
|
||||||
|
actionsLeading: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
marginRight: spacing.sm,
|
||||||
|
gap: spacing.sm,
|
||||||
|
},
|
||||||
|
channelTagAfterViews: {
|
||||||
|
maxWidth: 130,
|
||||||
|
flexShrink: 1,
|
||||||
|
},
|
||||||
viewsWrap: {
|
viewsWrap: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
|
flexShrink: 0,
|
||||||
},
|
},
|
||||||
viewsText: {
|
viewsText: {
|
||||||
color: colors.text.hint,
|
color: colors.text.hint,
|
||||||
@@ -606,6 +661,21 @@ const styles = StyleSheet.create({
|
|||||||
paddingTop: 8,
|
paddingTop: 8,
|
||||||
minHeight: 44,
|
minHeight: 44,
|
||||||
},
|
},
|
||||||
|
gridChannelRow: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 4,
|
||||||
|
paddingHorizontal: 8,
|
||||||
|
paddingTop: 4,
|
||||||
|
paddingBottom: 2,
|
||||||
|
},
|
||||||
|
gridChannelText: {
|
||||||
|
fontSize: fontSizes.xs,
|
||||||
|
color: colors.text.secondary,
|
||||||
|
fontWeight: '600',
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
gridFooter: {
|
gridFooter: {
|
||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { ReactNode } from 'react';
|
import React, { ReactNode } from 'react';
|
||||||
import { View, TouchableOpacity, StyleSheet, ScrollView, Animated } from 'react-native';
|
import { View, TouchableOpacity, StyleSheet, ScrollView, Animated, ViewStyle, StyleProp } from 'react-native';
|
||||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
import { colors, spacing, fontSizes, borderRadius } from '../../theme';
|
import { colors, spacing, fontSizes, borderRadius } from '../../theme';
|
||||||
import Text from '../common/Text';
|
import Text from '../common/Text';
|
||||||
@@ -20,6 +20,8 @@ interface TabBarProps {
|
|||||||
rightContent?: ReactNode;
|
rightContent?: ReactNode;
|
||||||
variant?: TabBarVariant;
|
variant?: TabBarVariant;
|
||||||
icons?: string[];
|
icons?: string[];
|
||||||
|
/** 合并到最外层容器,用于按页面微调外边距等 */
|
||||||
|
style?: StyleProp<ViewStyle>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TabBar: React.FC<TabBarProps> = ({
|
const TabBar: React.FC<TabBarProps> = ({
|
||||||
@@ -30,6 +32,7 @@ const TabBar: React.FC<TabBarProps> = ({
|
|||||||
rightContent,
|
rightContent,
|
||||||
variant = 'default',
|
variant = 'default',
|
||||||
icons,
|
icons,
|
||||||
|
style,
|
||||||
}) => {
|
}) => {
|
||||||
const renderTabs = () => {
|
const renderTabs = () => {
|
||||||
return tabs.map((tab, index) => {
|
return tabs.map((tab, index) => {
|
||||||
@@ -157,7 +160,7 @@ const TabBar: React.FC<TabBarProps> = ({
|
|||||||
|
|
||||||
if (scrollable) {
|
if (scrollable) {
|
||||||
return (
|
return (
|
||||||
<View style={getContainerStyle()}>
|
<View style={[getContainerStyle(), style]}>
|
||||||
<ScrollView
|
<ScrollView
|
||||||
horizontal
|
horizontal
|
||||||
showsHorizontalScrollIndicator={false}
|
showsHorizontalScrollIndicator={false}
|
||||||
@@ -171,7 +174,7 @@ const TabBar: React.FC<TabBarProps> = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={getContainerStyle()}>
|
<View style={[getContainerStyle(), style]}>
|
||||||
{renderTabs()}
|
{renderTabs()}
|
||||||
{rightContent && <View style={styles.rightContent}>{rightContent}</View>}
|
{rightContent && <View style={styles.rightContent}>{rightContent}</View>}
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ export interface Post {
|
|||||||
status: PostStatus;
|
status: PostStatus;
|
||||||
/** 所属频道ID */
|
/** 所属频道ID */
|
||||||
channelId?: string;
|
channelId?: string;
|
||||||
|
/** 频道摘要(列表 API 填充,供 PostCard 等展示) */
|
||||||
|
channel?: { id: string; name: string } | null;
|
||||||
/** 标签列表 */
|
/** 标签列表 */
|
||||||
tags: string[];
|
tags: string[];
|
||||||
/** 创建时间 */
|
/** 创建时间 */
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ export class PostMapper {
|
|||||||
isTop: response.is_pinned || false,
|
isTop: response.is_pinned || false,
|
||||||
status: (response.status || 'published') as 'published' | 'draft' | 'deleted',
|
status: (response.status || 'published') as 'published' | 'draft' | 'deleted',
|
||||||
channelId: response.channel_id,
|
channelId: response.channel_id,
|
||||||
|
channel:
|
||||||
|
response.channel && response.channel.id
|
||||||
|
? { id: String(response.channel.id), name: String(response.channel.name || '') }
|
||||||
|
: undefined,
|
||||||
tags: [],
|
tags: [],
|
||||||
createdAt: new Date(response.created_at || Date.now()),
|
createdAt: new Date(response.created_at || Date.now()),
|
||||||
// 空字符串/缺省时用 created_at,避免误用 Date.now() 导致全部显示「刚修改」
|
// 空字符串/缺省时用 created_at,避免误用 Date.now() 导致全部显示「刚修改」
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ export interface PostModel {
|
|||||||
isTop: boolean;
|
isTop: boolean;
|
||||||
status: 'published' | 'draft' | 'deleted';
|
status: 'published' | 'draft' | 'deleted';
|
||||||
channelId?: string;
|
channelId?: string;
|
||||||
|
/** 频道展示用(与 PostDTO.channel 一致) */
|
||||||
|
channel?: { id: string; name: string } | null;
|
||||||
tags?: string[];
|
tags?: string[];
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ interface PostApiResponse {
|
|||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
content_edited_at?: string;
|
content_edited_at?: string;
|
||||||
|
channel?: { id: string; name: string } | null;
|
||||||
author?: {
|
author?: {
|
||||||
id: number;
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
@@ -125,6 +126,7 @@ export class PostRepository implements IPostRepository {
|
|||||||
isPinned: model.isTop,
|
isPinned: model.isTop,
|
||||||
status: model.status,
|
status: model.status,
|
||||||
channelId: model.channelId,
|
channelId: model.channelId,
|
||||||
|
channel: model.channel,
|
||||||
tags: model.tags || [],
|
tags: model.tags || [],
|
||||||
createdAt: model.createdAt.toISOString(),
|
createdAt: model.createdAt.toISOString(),
|
||||||
updatedAt: model.updatedAt.toISOString(),
|
updatedAt: model.updatedAt.toISOString(),
|
||||||
|
|||||||
@@ -29,12 +29,16 @@ export function hrefNotifications(): string {
|
|||||||
return '/messages/notifications';
|
return '/messages/notifications';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function hrefApps(): string {
|
||||||
|
return '/apps';
|
||||||
|
}
|
||||||
|
|
||||||
export function hrefSchedule(): string {
|
export function hrefSchedule(): string {
|
||||||
return '/schedule';
|
return '/apps/schedule';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hrefScheduleCourse(courseId: string): string {
|
export function hrefScheduleCourse(courseId: string): string {
|
||||||
return `/schedule/course?courseId=${encodeURIComponent(courseId)}`;
|
return `/apps/schedule/course?courseId=${encodeURIComponent(courseId)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hrefProfileSettings(): string {
|
export function hrefProfileSettings(): string {
|
||||||
|
|||||||
235
src/screens/apps/AppsScreen.tsx
Normal file
235
src/screens/apps/AppsScreen.tsx
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
/**
|
||||||
|
* 应用中心:与首页顶栏、个人主页帖子卡片同一套圆角 / 阴影 / 主色体系
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React, { useCallback } from 'react';
|
||||||
|
import { View, StyleSheet, ScrollView, TouchableOpacity, StatusBar } from 'react-native';
|
||||||
|
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||||
|
import { useRouter } from 'expo-router';
|
||||||
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
|
|
||||||
|
import { colors, spacing, fontSizes, borderRadius, shadows } from '../../theme';
|
||||||
|
import * as hrefs from '../../navigation/hrefs';
|
||||||
|
import { Text, ResponsiveContainer } from '../../components/common';
|
||||||
|
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks/useResponsive';
|
||||||
|
|
||||||
|
type AppItem = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
icon: React.ComponentProps<typeof MaterialCommunityIcons>['name'];
|
||||||
|
href: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const APP_ENTRIES: AppItem[] = [
|
||||||
|
{
|
||||||
|
id: 'schedule',
|
||||||
|
title: '课表',
|
||||||
|
subtitle: '周课表、教务同步与课程管理',
|
||||||
|
icon: 'calendar-week',
|
||||||
|
href: hrefs.hrefSchedule(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 与个人主页 PostCard 外层 `postWrapper` 一致 */
|
||||||
|
const postCardShell = {
|
||||||
|
marginBottom: spacing.md,
|
||||||
|
backgroundColor: colors.background.paper,
|
||||||
|
borderRadius: 16,
|
||||||
|
overflow: 'hidden' as const,
|
||||||
|
shadowColor: '#000',
|
||||||
|
shadowOffset: { width: 0, height: 2 },
|
||||||
|
shadowOpacity: 0.06,
|
||||||
|
shadowRadius: 8,
|
||||||
|
elevation: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AppsScreen: React.FC = () => {
|
||||||
|
const router = useRouter();
|
||||||
|
const insets = useSafeAreaInsets();
|
||||||
|
const { isMobile } = useResponsive();
|
||||||
|
/** 与 MessageListScreen 顶栏宽屏 padding 一致 */
|
||||||
|
const isWideScreen = useBreakpointGTE('lg');
|
||||||
|
const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });
|
||||||
|
|
||||||
|
const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];
|
||||||
|
|
||||||
|
const onOpenApp = useCallback(
|
||||||
|
(href: string) => {
|
||||||
|
router.push(href);
|
||||||
|
},
|
||||||
|
[router]
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderTiles = () => (
|
||||||
|
<>
|
||||||
|
<Text variant="caption" color={colors.text.secondary} style={styles.pageSubtitle}>
|
||||||
|
与社区账号打通的轻应用入口
|
||||||
|
</Text>
|
||||||
|
{APP_ENTRIES.map(item => (
|
||||||
|
<TouchableOpacity
|
||||||
|
key={item.id}
|
||||||
|
style={postCardShell}
|
||||||
|
onPress={() => onOpenApp(item.href)}
|
||||||
|
activeOpacity={0.88}
|
||||||
|
>
|
||||||
|
<View style={styles.appCardInner}>
|
||||||
|
<View style={styles.appIconCircle}>
|
||||||
|
<MaterialCommunityIcons name={item.icon} size={26} color={colors.primary.contrast} />
|
||||||
|
</View>
|
||||||
|
<View style={styles.appCardText}>
|
||||||
|
<Text variant="body" color={colors.text.primary} style={styles.appTitle}>
|
||||||
|
{item.title}
|
||||||
|
</Text>
|
||||||
|
<Text variant="caption" color={colors.text.secondary} style={styles.appSubtitle}>
|
||||||
|
{item.subtitle}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<MaterialCommunityIcons name="chevron-right" size={22} color={colors.primary.main} />
|
||||||
|
</View>
|
||||||
|
</TouchableOpacity>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<View style={styles.footer}>
|
||||||
|
<Text variant="caption" color={colors.text.hint}>
|
||||||
|
更多应用陆续上线
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SafeAreaView style={styles.container} edges={['top', 'bottom']}>
|
||||||
|
<StatusBar barStyle="dark-content" backgroundColor="#FAFAFA" />
|
||||||
|
|
||||||
|
{/* 与 MessageListScreen 顶栏同一结构 / 样式 */}
|
||||||
|
<View style={[styles.msgHeader, isWideScreen && styles.msgHeaderWide]}>
|
||||||
|
<View style={styles.msgHeaderLeft} />
|
||||||
|
<View style={styles.msgHeaderCenter}>
|
||||||
|
<Text style={[styles.msgHeaderTitle, ...(isWideScreen ? [styles.msgHeaderTitleWide] : [])]}>
|
||||||
|
应用
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
<View style={styles.msgHeaderRight}>
|
||||||
|
<View style={styles.msgHeaderRightSpacer} />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{isWideScreen ? (
|
||||||
|
<ResponsiveContainer maxWidth={720}>
|
||||||
|
<ScrollView
|
||||||
|
style={styles.scroll}
|
||||||
|
contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset }]}
|
||||||
|
showsVerticalScrollIndicator={false}
|
||||||
|
>
|
||||||
|
{renderTiles()}
|
||||||
|
</ScrollView>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<ScrollView
|
||||||
|
style={styles.scroll}
|
||||||
|
contentContainerStyle={[
|
||||||
|
styles.scrollContent,
|
||||||
|
{ paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding },
|
||||||
|
]}
|
||||||
|
showsVerticalScrollIndicator={false}
|
||||||
|
>
|
||||||
|
{renderTiles()}
|
||||||
|
</ScrollView>
|
||||||
|
)}
|
||||||
|
</SafeAreaView>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AppsScreen;
|
||||||
|
|
||||||
|
const styles = StyleSheet.create({
|
||||||
|
container: {
|
||||||
|
flex: 1,
|
||||||
|
backgroundColor: colors.background.default,
|
||||||
|
},
|
||||||
|
msgHeader: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
paddingHorizontal: spacing.md,
|
||||||
|
paddingVertical: spacing.md,
|
||||||
|
backgroundColor: '#FAFAFA',
|
||||||
|
...shadows.sm,
|
||||||
|
},
|
||||||
|
msgHeaderWide: {
|
||||||
|
paddingHorizontal: spacing.lg,
|
||||||
|
paddingVertical: spacing.lg,
|
||||||
|
},
|
||||||
|
msgHeaderLeft: {
|
||||||
|
width: 44,
|
||||||
|
},
|
||||||
|
msgHeaderCenter: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: spacing.xs,
|
||||||
|
},
|
||||||
|
msgHeaderTitle: {
|
||||||
|
fontSize: 19,
|
||||||
|
fontWeight: '700',
|
||||||
|
color: '#333',
|
||||||
|
},
|
||||||
|
msgHeaderTitleWide: {
|
||||||
|
fontSize: 22,
|
||||||
|
},
|
||||||
|
msgHeaderRight: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
},
|
||||||
|
/** 与消息页「+」按钮同占位宽度,标题视觉居中 */
|
||||||
|
msgHeaderRightSpacer: {
|
||||||
|
width: 36,
|
||||||
|
height: 44,
|
||||||
|
},
|
||||||
|
pageSubtitle: {
|
||||||
|
marginBottom: spacing.md,
|
||||||
|
lineHeight: fontSizes.sm * 1.45,
|
||||||
|
},
|
||||||
|
/** 与消息列表区同色,避免顶栏阴影落在灰底上像一条线 */
|
||||||
|
scroll: {
|
||||||
|
flex: 1,
|
||||||
|
backgroundColor: '#FAFAFA',
|
||||||
|
},
|
||||||
|
scrollContent: {
|
||||||
|
paddingTop: spacing.md,
|
||||||
|
flexGrow: 1,
|
||||||
|
backgroundColor: '#FAFAFA',
|
||||||
|
},
|
||||||
|
appCardInner: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
paddingVertical: spacing.lg,
|
||||||
|
paddingHorizontal: spacing.lg,
|
||||||
|
},
|
||||||
|
/** 与首页发帖 FAB 同主色实心圆 */
|
||||||
|
appIconCircle: {
|
||||||
|
width: 52,
|
||||||
|
height: 52,
|
||||||
|
borderRadius: borderRadius.full,
|
||||||
|
backgroundColor: colors.primary.main,
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
},
|
||||||
|
appCardText: {
|
||||||
|
flex: 1,
|
||||||
|
marginLeft: spacing.md,
|
||||||
|
marginRight: spacing.sm,
|
||||||
|
},
|
||||||
|
appTitle: {
|
||||||
|
fontWeight: '700',
|
||||||
|
fontSize: fontSizes.md + 1,
|
||||||
|
},
|
||||||
|
appSubtitle: {
|
||||||
|
marginTop: 4,
|
||||||
|
},
|
||||||
|
footer: {
|
||||||
|
alignItems: 'center',
|
||||||
|
paddingTop: spacing.xl,
|
||||||
|
paddingBottom: spacing.md,
|
||||||
|
},
|
||||||
|
});
|
||||||
2
src/screens/apps/index.ts
Normal file
2
src/screens/apps/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { AppsScreen } from './AppsScreen';
|
||||||
|
export { default } from './AppsScreen';
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
* 支持列表和多列网格模式(响应式布局)
|
* 支持列表和多列网格模式(响应式布局)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
|
import React, { useState, useEffect, useLayoutEffect, useCallback, useMemo, useRef } from 'react';
|
||||||
import {
|
import {
|
||||||
View,
|
View,
|
||||||
FlatList,
|
FlatList,
|
||||||
@@ -15,17 +15,18 @@ import {
|
|||||||
StatusBar,
|
StatusBar,
|
||||||
TouchableOpacity,
|
TouchableOpacity,
|
||||||
NativeSyntheticEvent,
|
NativeSyntheticEvent,
|
||||||
|
NativeScrollEvent,
|
||||||
Alert,
|
Alert,
|
||||||
Clipboard,
|
Clipboard,
|
||||||
Modal,
|
Modal,
|
||||||
} from 'react-native';
|
} from 'react-native';
|
||||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||||
import { useRouter } from 'expo-router';
|
import { useRouter, useFocusEffect } from 'expo-router';
|
||||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
|
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
|
||||||
import { colors, spacing, borderRadius, shadows } from '../../theme';
|
import { colors, spacing, borderRadius, shadows } from '../../theme';
|
||||||
import { Post } from '../../types';
|
import { Post } from '../../types';
|
||||||
import { useUserStore } from '../../stores';
|
import { useUserStore, useHomeTabBarVisibilityStore } from '../../stores';
|
||||||
import { useCurrentUser } from '../../stores/authStore';
|
import { useCurrentUser } from '../../stores/authStore';
|
||||||
import { channelService, postService } from '../../services';
|
import { channelService, postService } from '../../services';
|
||||||
import { PostCard, TabBar, SearchBar } from '../../components/business';
|
import { PostCard, TabBar, SearchBar } from '../../components/business';
|
||||||
@@ -46,6 +47,10 @@ const SWIPE_COOLDOWN_MS = 300;
|
|||||||
const MOBILE_TAB_BAR_HEIGHT = 64;
|
const MOBILE_TAB_BAR_HEIGHT = 64;
|
||||||
const MOBILE_TAB_FLOATING_MARGIN = 12;
|
const MOBILE_TAB_FLOATING_MARGIN = 12;
|
||||||
const MOBILE_FAB_GAP = 12;
|
const MOBILE_FAB_GAP = 12;
|
||||||
|
/** 首页纵向滑动超过此阈值视为明确向下/向上划,用于隐藏或显示底部 Tab */
|
||||||
|
const TAB_BAR_SCROLL_DELTA_Y = 10;
|
||||||
|
/** 停止滑动多久后自动恢复底部 Tab */
|
||||||
|
const TAB_BAR_IDLE_RESTORE_MS = 2200;
|
||||||
|
|
||||||
type ViewMode = 'list' | 'grid';
|
type ViewMode = 'list' | 'grid';
|
||||||
type PostType = 'follow' | 'hot' | 'latest';
|
type PostType = 'follow' | 'hot' | 'latest';
|
||||||
@@ -92,6 +97,83 @@ export const HomeScreen: React.FC = () => {
|
|||||||
|
|
||||||
const isLoadingMoreRef = useRef(false);
|
const isLoadingMoreRef = useRef(false);
|
||||||
|
|
||||||
|
const setBottomTabBarHiddenByScroll = useHomeTabBarVisibilityStore((s) => s.setBottomTabBarHiddenByScroll);
|
||||||
|
const bottomTabBarHiddenByScroll = useHomeTabBarVisibilityStore((s) => s.bottomTabBarHiddenByScroll);
|
||||||
|
const homeListScrollYRef = useRef(0);
|
||||||
|
const tabBarIdleRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
const clearTabBarIdleRestoreTimer = useCallback(() => {
|
||||||
|
if (tabBarIdleRestoreTimerRef.current != null) {
|
||||||
|
clearTimeout(tabBarIdleRestoreTimerRef.current);
|
||||||
|
tabBarIdleRestoreTimerRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const scheduleTabBarIdleRestore = useCallback(() => {
|
||||||
|
clearTabBarIdleRestoreTimer();
|
||||||
|
tabBarIdleRestoreTimerRef.current = setTimeout(() => {
|
||||||
|
setBottomTabBarHiddenByScroll(false);
|
||||||
|
tabBarIdleRestoreTimerRef.current = null;
|
||||||
|
}, TAB_BAR_IDLE_RESTORE_MS);
|
||||||
|
}, [clearTabBarIdleRestoreTimer, setBottomTabBarHiddenByScroll]);
|
||||||
|
|
||||||
|
const handleHomeVerticalScroll = useCallback(
|
||||||
|
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||||
|
const y = event.nativeEvent.contentOffset.y;
|
||||||
|
const dy = y - homeListScrollYRef.current;
|
||||||
|
homeListScrollYRef.current = y;
|
||||||
|
|
||||||
|
scheduleTabBarIdleRestore();
|
||||||
|
|
||||||
|
if (y <= 0) {
|
||||||
|
setBottomTabBarHiddenByScroll(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dy > TAB_BAR_SCROLL_DELTA_Y) {
|
||||||
|
setBottomTabBarHiddenByScroll(true);
|
||||||
|
} else if (dy < -TAB_BAR_SCROLL_DELTA_Y) {
|
||||||
|
setBottomTabBarHiddenByScroll(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[scheduleTabBarIdleRestore, setBottomTabBarHiddenByScroll]
|
||||||
|
);
|
||||||
|
|
||||||
|
useFocusEffect(
|
||||||
|
useCallback(() => {
|
||||||
|
return () => {
|
||||||
|
clearTabBarIdleRestoreTimer();
|
||||||
|
homeListScrollYRef.current = 0;
|
||||||
|
setBottomTabBarHiddenByScroll(false);
|
||||||
|
};
|
||||||
|
}, [clearTabBarIdleRestoreTimer, setBottomTabBarHiddenByScroll])
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (showSearch) {
|
||||||
|
clearTabBarIdleRestoreTimer();
|
||||||
|
setBottomTabBarHiddenByScroll(false);
|
||||||
|
}
|
||||||
|
}, [showSearch, clearTabBarIdleRestoreTimer, setBottomTabBarHiddenByScroll]);
|
||||||
|
|
||||||
|
/** 横向胶囊条滚动位置:切换频道刷新列表时不重置 */
|
||||||
|
const capsuleHScrollRef = useRef<ScrollView | null>(null);
|
||||||
|
const capsuleScrollXRef = useRef(0);
|
||||||
|
|
||||||
|
const restoreCapsuleStripScroll = useCallback(() => {
|
||||||
|
const x = capsuleScrollXRef.current;
|
||||||
|
if (x <= 0) return;
|
||||||
|
const scroll = () => capsuleHScrollRef.current?.scrollTo({ x, animated: false });
|
||||||
|
scroll();
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
requestAnimationFrame(scroll);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const onCapsuleHorizontalScroll = useCallback((e: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||||
|
capsuleScrollXRef.current = e.nativeEvent.contentOffset.x;
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 构建一个以 postId 为 key 的 map,用于快速查找
|
// 构建一个以 postId 为 key 的 map,用于快速查找
|
||||||
const postsMap = useMemo(() => {
|
const postsMap = useMemo(() => {
|
||||||
const map = new Map<string, Post>();
|
const map = new Map<string, Post>();
|
||||||
@@ -114,6 +196,16 @@ export const HomeScreen: React.FC = () => {
|
|||||||
const isLatestTab = activeIndex === 1;
|
const isLatestTab = activeIndex === 1;
|
||||||
const currentChannelId = isLatestTab && activeCapsuleId ? activeCapsuleId : undefined;
|
const currentChannelId = isLatestTab && activeCapsuleId ? activeCapsuleId : undefined;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
homeListScrollYRef.current = 0;
|
||||||
|
setBottomTabBarHiddenByScroll(false);
|
||||||
|
}, [activeIndex, currentChannelId, viewMode, setBottomTabBarHiddenByScroll]);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!isLatestTab) return;
|
||||||
|
restoreCapsuleStripScroll();
|
||||||
|
}, [isLatestTab, activeCapsuleId, latestCapsules.length, restoreCapsuleStripScroll]);
|
||||||
|
|
||||||
// 使用差异更新 Hook 获取帖子列表
|
// 使用差异更新 Hook 获取帖子列表
|
||||||
const listKey = useMemo(
|
const listKey = useMemo(
|
||||||
() => `home_${getPostType()}_${currentChannelId || 'all'}`,
|
() => `home_${getPostType()}_${currentChannelId || 'all'}`,
|
||||||
@@ -159,18 +251,21 @@ export const HomeScreen: React.FC = () => {
|
|||||||
}
|
}
|
||||||
}, [posts.length, listKey, hasMore, isLoadingMore]);
|
}, [posts.length, listKey, hasMore, isLoadingMore]);
|
||||||
|
|
||||||
// 网格模式滚动处理 - 检测是否滚动到底部
|
// 网格模式滚动处理 - 检测是否滚动到底部 + 底部 Tab 显隐
|
||||||
const handleGridScroll = useCallback((event: any) => {
|
const handleGridScroll = useCallback(
|
||||||
const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
|
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||||
const scrollY = contentOffset.y;
|
handleHomeVerticalScroll(event);
|
||||||
const visibleHeight = layoutMeasurement.height;
|
const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
|
||||||
const contentHeight = contentSize.height;
|
const scrollY = contentOffset.y;
|
||||||
|
const visibleHeight = layoutMeasurement.height;
|
||||||
// 当滚动到距离底部 200px 时触发加载更多
|
const contentHeight = contentSize.height;
|
||||||
if (scrollY + visibleHeight >= contentHeight - 200) {
|
|
||||||
loadMore();
|
if (scrollY + visibleHeight >= contentHeight - 200) {
|
||||||
}
|
loadMore();
|
||||||
}, [loadMore]);
|
}
|
||||||
|
},
|
||||||
|
[handleHomeVerticalScroll, loadMore]
|
||||||
|
);
|
||||||
|
|
||||||
// 刷新方法 - 先获取正确类型的帖子,再刷新
|
// 刷新方法 - 先获取正确类型的帖子,再刷新
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
@@ -203,10 +298,13 @@ export const HomeScreen: React.FC = () => {
|
|||||||
return posts.map(post => {
|
return posts.map(post => {
|
||||||
const storePost = postsMap.get(post.id);
|
const storePost = postsMap.get(post.id);
|
||||||
if (storePost) {
|
if (storePost) {
|
||||||
// 如果 store 中有这个帖子,使用 store 的最新状态
|
// store 同步点赞等状态;channel 等列表专用字段在 store 里常缺失,从列表帖合并
|
||||||
return storePost;
|
return {
|
||||||
|
...post,
|
||||||
|
...storePost,
|
||||||
|
channel: storePost.channel ?? post.channel,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
// 如果 store 中没有这个帖子,使用原始数据
|
|
||||||
return post;
|
return post;
|
||||||
});
|
});
|
||||||
}, [posts, postsMap]);
|
}, [posts, postsMap]);
|
||||||
@@ -257,10 +355,12 @@ export const HomeScreen: React.FC = () => {
|
|||||||
if (!isMobile) {
|
if (!isMobile) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
if (bottomTabBarHiddenByScroll) {
|
||||||
|
return MOBILE_TAB_FLOATING_MARGIN + MOBILE_FAB_GAP + insets.bottom;
|
||||||
|
}
|
||||||
// TabBar 悬浮在底部,发帖按钮需要在 TabBar 上方
|
// TabBar 悬浮在底部,发帖按钮需要在 TabBar 上方
|
||||||
// TabBar 高度 64 + TabBar 浮动间距 12 + 按钮与 TabBar 间距 16
|
|
||||||
return MOBILE_TAB_BAR_HEIGHT + MOBILE_TAB_FLOATING_MARGIN * 2 + MOBILE_FAB_GAP + insets.bottom;
|
return MOBILE_TAB_BAR_HEIGHT + MOBILE_TAB_FLOATING_MARGIN * 2 + MOBILE_FAB_GAP + insets.bottom;
|
||||||
}, [isMobile, insets.bottom]);
|
}, [isMobile, insets.bottom, bottomTabBarHiddenByScroll]);
|
||||||
|
|
||||||
// 切换视图模式
|
// 切换视图模式
|
||||||
const toggleViewMode = () => {
|
const toggleViewMode = () => {
|
||||||
@@ -453,7 +553,15 @@ export const HomeScreen: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={[styles.capsuleWrapper, { paddingHorizontal: responsivePadding }]}>
|
<View style={[styles.capsuleWrapper, { paddingHorizontal: responsivePadding }]}>
|
||||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.capsuleList}>
|
<ScrollView
|
||||||
|
ref={capsuleHScrollRef}
|
||||||
|
horizontal
|
||||||
|
showsHorizontalScrollIndicator={false}
|
||||||
|
contentContainerStyle={styles.capsuleList}
|
||||||
|
onScroll={onCapsuleHorizontalScroll}
|
||||||
|
scrollEventThrottle={16}
|
||||||
|
onContentSizeChange={restoreCapsuleStripScroll}
|
||||||
|
>
|
||||||
{latestCapsules.map((item) => {
|
{latestCapsules.map((item) => {
|
||||||
const isActive = item.id === activeCapsuleId;
|
const isActive = item.id === activeCapsuleId;
|
||||||
return (
|
return (
|
||||||
@@ -607,7 +715,7 @@ export const HomeScreen: React.FC = () => {
|
|||||||
}
|
}
|
||||||
]}
|
]}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
scrollEventThrottle={100}
|
scrollEventThrottle={16}
|
||||||
onScroll={handleGridScroll}
|
onScroll={handleGridScroll}
|
||||||
refreshControl={
|
refreshControl={
|
||||||
<RefreshControl
|
<RefreshControl
|
||||||
@@ -702,6 +810,7 @@ export const HomeScreen: React.FC = () => {
|
|||||||
}
|
}
|
||||||
onEndReached={loadMore}
|
onEndReached={loadMore}
|
||||||
onEndReachedThreshold={0.3}
|
onEndReachedThreshold={0.3}
|
||||||
|
onScroll={handleHomeVerticalScroll}
|
||||||
scrollEventThrottle={16}
|
scrollEventThrottle={16}
|
||||||
ListEmptyComponent={renderEmpty}
|
ListEmptyComponent={renderEmpty}
|
||||||
ListFooterComponent={isLoadingMore ? <Loading size="sm" /> : null}
|
ListFooterComponent={isLoadingMore ? <Loading size="sm" /> : null}
|
||||||
@@ -751,6 +860,7 @@ export const HomeScreen: React.FC = () => {
|
|||||||
activeIndex={activeIndex}
|
activeIndex={activeIndex}
|
||||||
onTabChange={changeTab}
|
onTabChange={changeTab}
|
||||||
variant="modern"
|
variant="modern"
|
||||||
|
style={styles.homeTabBar}
|
||||||
rightContent={
|
rightContent={
|
||||||
<TouchableOpacity onPress={toggleViewMode} style={styles.viewToggleBtn}>
|
<TouchableOpacity onPress={toggleViewMode} style={styles.viewToggleBtn}>
|
||||||
<MaterialCommunityIcons
|
<MaterialCommunityIcons
|
||||||
@@ -842,7 +952,8 @@ const styles = StyleSheet.create({
|
|||||||
backgroundColor: colors.background.paper,
|
backgroundColor: colors.background.paper,
|
||||||
},
|
},
|
||||||
searchWrapper: {
|
searchWrapper: {
|
||||||
paddingBottom: spacing.sm,
|
paddingTop: spacing.lg,
|
||||||
|
paddingBottom: spacing.xs,
|
||||||
// 移除阴影效果
|
// 移除阴影效果
|
||||||
shadowColor: 'transparent',
|
shadowColor: 'transparent',
|
||||||
shadowOffset: { width: 0, height: 0 },
|
shadowOffset: { width: 0, height: 0 },
|
||||||
@@ -850,6 +961,10 @@ const styles = StyleSheet.create({
|
|||||||
shadowRadius: 0,
|
shadowRadius: 0,
|
||||||
elevation: 0,
|
elevation: 0,
|
||||||
},
|
},
|
||||||
|
homeTabBar: {
|
||||||
|
marginTop: 0,
|
||||||
|
marginBottom: spacing.sm,
|
||||||
|
},
|
||||||
viewToggleBtn: {
|
viewToggleBtn: {
|
||||||
width: 44,
|
width: 44,
|
||||||
height: 44,
|
height: 44,
|
||||||
|
|||||||
@@ -2054,30 +2054,23 @@ const styles = StyleSheet.create({
|
|||||||
paddingVertical: spacing.xs,
|
paddingVertical: spacing.xs,
|
||||||
borderRadius: borderRadius.md,
|
borderRadius: borderRadius.md,
|
||||||
},
|
},
|
||||||
// 空评论状态样式
|
// 空评论状态样式(与平铺评论区一致,无卡片气泡)
|
||||||
emptyCommentsContainer: {
|
emptyCommentsContainer: {
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent: 'center',
|
justifyContent: 'center',
|
||||||
marginHorizontal: spacing.lg,
|
marginHorizontal: spacing.md,
|
||||||
marginTop: spacing.lg,
|
marginTop: spacing.md,
|
||||||
marginBottom: spacing.md,
|
marginBottom: spacing.lg,
|
||||||
paddingVertical: spacing.xl + spacing.md,
|
paddingVertical: spacing.xl,
|
||||||
paddingHorizontal: spacing.lg,
|
paddingHorizontal: spacing.md,
|
||||||
borderRadius: borderRadius.lg,
|
|
||||||
backgroundColor: colors.background.paper,
|
|
||||||
borderWidth: StyleSheet.hairlineWidth,
|
|
||||||
borderColor: colors.divider,
|
|
||||||
},
|
},
|
||||||
emptyCommentsIconWrapper: {
|
emptyCommentsIconWrapper: {
|
||||||
width: 44,
|
width: 40,
|
||||||
height: 44,
|
height: 40,
|
||||||
borderRadius: 22,
|
|
||||||
backgroundColor: colors.background.default,
|
|
||||||
borderWidth: StyleSheet.hairlineWidth,
|
|
||||||
borderColor: colors.divider,
|
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent: 'center',
|
justifyContent: 'center',
|
||||||
marginBottom: spacing.sm,
|
marginBottom: spacing.sm,
|
||||||
|
opacity: 0.85,
|
||||||
},
|
},
|
||||||
emptyCommentsTitle: {
|
emptyCommentsTitle: {
|
||||||
fontSize: fontSizes.md,
|
fontSize: fontSizes.md,
|
||||||
|
|||||||
@@ -575,11 +575,7 @@ const styles = StyleSheet.create({
|
|||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
},
|
},
|
||||||
coverEditOverlay: {
|
coverEditOverlay: {
|
||||||
position: 'absolute',
|
...StyleSheet.absoluteFillObject,
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
height: '60%',
|
|
||||||
backgroundColor: 'rgba(0, 0, 0, 0.3)',
|
backgroundColor: 'rgba(0, 0, 0, 0.3)',
|
||||||
justifyContent: 'center',
|
justifyContent: 'center',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
|
|||||||
@@ -13,14 +13,16 @@ import {
|
|||||||
} from 'react-native';
|
} from 'react-native';
|
||||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
|
||||||
import { colors, spacing, fontSizes, borderRadius } from '../../theme';
|
import { colors, spacing, fontSizes, borderRadius } from '../../theme';
|
||||||
import { Text, ResponsiveContainer } from '../../components/common';
|
import { Text, ResponsiveContainer } from '../../components/common';
|
||||||
import { setVibrationEnabled } from '../../services/backgroundService';
|
import {
|
||||||
|
loadNotificationPreferences,
|
||||||
|
setPushNotificationsPreference,
|
||||||
|
setSoundPreference,
|
||||||
|
setVibrationPreference,
|
||||||
|
} from '../../services/notificationPreferences';
|
||||||
import { useResponsive } from '../../hooks';
|
import { useResponsive } from '../../hooks';
|
||||||
|
|
||||||
const VIBRATION_ENABLED_KEY = 'vibration_enabled';
|
|
||||||
|
|
||||||
interface NotificationSettingItem {
|
interface NotificationSettingItem {
|
||||||
key: string;
|
key: string;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -40,34 +42,48 @@ export const NotificationSettingsScreen: React.FC = () => {
|
|||||||
// 底部间距,避免被 TabBar 遮挡
|
// 底部间距,避免被 TabBar 遮挡
|
||||||
const scrollBottomInset = isMobile ? 64 + 24 + insets.bottom + spacing.md : spacing.md;
|
const scrollBottomInset = isMobile ? 64 + 24 + insets.bottom + spacing.md : spacing.md;
|
||||||
|
|
||||||
// 加载设置
|
// 加载设置(与启动时 hydrate 一致,避免从其它入口进页时 UI 与内存不一致)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadSettings = async () => {
|
const loadSettings = async () => {
|
||||||
try {
|
try {
|
||||||
const vibrationStored = await AsyncStorage.getItem(VIBRATION_ENABLED_KEY);
|
const prefs = await loadNotificationPreferences();
|
||||||
if (vibrationStored !== null) {
|
setVibrationEnabledState(prefs.vibrationEnabled);
|
||||||
const enabled = JSON.parse(vibrationStored);
|
setPushEnabled(prefs.pushEnabled);
|
||||||
setVibrationEnabledState(enabled);
|
setSoundEnabled(prefs.soundEnabled);
|
||||||
setVibrationEnabled(enabled);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('加载震动设置失败:', error);
|
console.error('加载通知设置失败:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
loadSettings();
|
loadSettings();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 切换震动
|
|
||||||
const toggleVibration = async (value: boolean) => {
|
const toggleVibration = async (value: boolean) => {
|
||||||
try {
|
try {
|
||||||
setVibrationEnabledState(value);
|
setVibrationEnabledState(value);
|
||||||
setVibrationEnabled(value);
|
await setVibrationPreference(value);
|
||||||
await AsyncStorage.setItem(VIBRATION_ENABLED_KEY, JSON.stringify(value));
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('保存震动设置失败:', error);
|
console.error('保存震动设置失败:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const togglePush = async (value: boolean) => {
|
||||||
|
try {
|
||||||
|
setPushEnabled(value);
|
||||||
|
await setPushNotificationsPreference(value);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('保存推送开关失败:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleSound = async (value: boolean) => {
|
||||||
|
try {
|
||||||
|
setSoundEnabled(value);
|
||||||
|
await setSoundPreference(value);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('保存提示音设置失败:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const settings: NotificationSettingItem[] = [
|
const settings: NotificationSettingItem[] = [
|
||||||
{
|
{
|
||||||
key: 'push',
|
key: 'push',
|
||||||
@@ -75,7 +91,7 @@ export const NotificationSettingsScreen: React.FC = () => {
|
|||||||
subtitle: '接收新消息、点赞、评论等推送',
|
subtitle: '接收新消息、点赞、评论等推送',
|
||||||
icon: 'bell-outline',
|
icon: 'bell-outline',
|
||||||
value: pushEnabled,
|
value: pushEnabled,
|
||||||
onValueChange: setPushEnabled,
|
onValueChange: togglePush,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'vibration',
|
key: 'vibration',
|
||||||
@@ -91,7 +107,7 @@ export const NotificationSettingsScreen: React.FC = () => {
|
|||||||
subtitle: '收到新消息时播放提示音',
|
subtitle: '收到新消息时播放提示音',
|
||||||
icon: 'volume-high',
|
icon: 'volume-high',
|
||||||
value: soundEnabled,
|
value: soundEnabled,
|
||||||
onValueChange: setSoundEnabled,
|
onValueChange: toggleSound,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -379,6 +379,16 @@ export const ScheduleScreen: React.FC = () => {
|
|||||||
// 渲染周选择器
|
// 渲染周选择器
|
||||||
const renderWeekSelector = () => (
|
const renderWeekSelector = () => (
|
||||||
<View style={styles.weekSelector}>
|
<View style={styles.weekSelector}>
|
||||||
|
{router.canGoBack() ? (
|
||||||
|
<TouchableOpacity
|
||||||
|
style={styles.weekBarIconButton}
|
||||||
|
onPress={() => router.back()}
|
||||||
|
accessibilityRole="button"
|
||||||
|
accessibilityLabel="返回"
|
||||||
|
>
|
||||||
|
<MaterialCommunityIcons name="chevron-left" size={28} color="#FFFFFF" />
|
||||||
|
</TouchableOpacity>
|
||||||
|
) : null}
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
style={styles.settingsButton}
|
style={styles.settingsButton}
|
||||||
onPress={() => setIsSettingsModalVisible(true)}
|
onPress={() => setIsSettingsModalVisible(true)}
|
||||||
@@ -1066,6 +1076,13 @@ const styles = StyleSheet.create({
|
|||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
},
|
},
|
||||||
|
weekBarIconButton: {
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
justifyContent: 'center',
|
||||||
|
alignItems: 'center',
|
||||||
|
marginLeft: spacing.sm,
|
||||||
|
},
|
||||||
settingsButton: {
|
settingsButton: {
|
||||||
width: 40,
|
width: 40,
|
||||||
height: 40,
|
height: 40,
|
||||||
|
|||||||
@@ -20,30 +20,61 @@ let writeQueue: Promise<void> = Promise.resolve();
|
|||||||
// 当前数据库对应的用户ID
|
// 当前数据库对应的用户ID
|
||||||
let currentDbUserId: string | null = null;
|
let currentDbUserId: string | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 串行化 open/close,避免并发 initDatabase(如 React Strict Mode 双次 effect、登录与冷启动校验交错)
|
||||||
|
* 导致后完成的 open 覆盖先完成的连接,进而在 Android 上出现 NativeDatabase.execAsync NPE。
|
||||||
|
*/
|
||||||
|
let dbOpenCloseMutex: Promise<void> = Promise.resolve();
|
||||||
|
|
||||||
|
async function withDbOpenCloseLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||||
|
const previous = dbOpenCloseMutex;
|
||||||
|
let release!: () => void;
|
||||||
|
dbOpenCloseMutex = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await previous;
|
||||||
|
return await fn();
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 数据库版本,用于迁移
|
// 数据库版本,用于迁移
|
||||||
const DB_VERSION = 2;
|
const DB_VERSION = 2;
|
||||||
|
|
||||||
/**
|
/** 关闭连接(须在已持有 dbOpenCloseMutex 时调用,或作为 withDbOpenCloseLock 内的实现) */
|
||||||
* 初始化用户数据库
|
const closeDatabaseUnlocked = async (): Promise<void> => {
|
||||||
* @param userId 用户ID,用于创建用户专属数据库文件
|
if (db) {
|
||||||
*/
|
try {
|
||||||
export const initDatabase = async (userId?: string): Promise<void> => {
|
await db.closeAsync();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Database] 关闭数据库失败:', error);
|
||||||
|
}
|
||||||
|
db = null;
|
||||||
|
currentDbUserId = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
async function initDatabaseUnlocked(userId?: string): Promise<void> {
|
||||||
|
// 如果指定了用户ID,使用用户专属数据库
|
||||||
|
// 否则使用默认数据库(兼容旧版本)
|
||||||
|
const dbName = userId ? `carrot_bbs_${userId}.db` : 'carrot_bbs.db';
|
||||||
|
|
||||||
|
// 如果存在旧的数据库连接且用户ID变化,需要关闭旧连接
|
||||||
|
if (db && currentDbUserId !== userId) {
|
||||||
|
await closeDatabaseUnlocked();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果已经打开了正确的数据库,直接返回
|
||||||
|
if (db && currentDbUserId === userId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let opened: SQLite.SQLiteDatabase | null = null;
|
||||||
try {
|
try {
|
||||||
// 如果指定了用户ID,使用用户专属数据库
|
opened = await SQLite.openDatabaseAsync(dbName);
|
||||||
// 否则使用默认数据库(兼容旧版本)
|
db = opened;
|
||||||
const dbName = userId ? `carrot_bbs_${userId}.db` : 'carrot_bbs.db';
|
|
||||||
|
|
||||||
// 如果存在旧的数据库连接且用户ID变化,需要关闭旧连接
|
|
||||||
if (db && currentDbUserId !== userId) {
|
|
||||||
await closeDatabase();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果已经打开了正确的数据库,直接返回
|
|
||||||
if (db && currentDbUserId === userId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
db = await SQLite.openDatabaseAsync(dbName);
|
|
||||||
currentDbUserId = userId || null;
|
currentDbUserId = userId || null;
|
||||||
|
|
||||||
// 创建消息表(包含新字段 seq, status, segments)
|
// 创建消息表(包含新字段 seq, status, segments)
|
||||||
@@ -149,26 +180,34 @@ export const initDatabase = async (userId?: string): Promise<void> => {
|
|||||||
await db.execAsync(`
|
await db.execAsync(`
|
||||||
CREATE INDEX IF NOT EXISTS idx_messages_conversation_seq ON messages(conversationId, seq);
|
CREATE INDEX IF NOT EXISTS idx_messages_conversation_seq ON messages(conversationId, seq);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('数据库初始化失败:', error);
|
console.error('数据库初始化失败:', error);
|
||||||
|
try {
|
||||||
|
if (opened && opened === db) {
|
||||||
|
await opened.closeAsync();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
db = null;
|
||||||
|
currentDbUserId = null;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化用户数据库
|
||||||
|
* @param userId 用户ID,用于创建用户专属数据库文件
|
||||||
|
*/
|
||||||
|
export const initDatabase = async (userId?: string): Promise<void> => {
|
||||||
|
return withDbOpenCloseLock(() => initDatabaseUnlocked(userId));
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 关闭数据库连接
|
* 关闭数据库连接
|
||||||
*/
|
*/
|
||||||
export const closeDatabase = async (): Promise<void> => {
|
export const closeDatabase = async (): Promise<void> => {
|
||||||
if (db) {
|
return withDbOpenCloseLock(() => closeDatabaseUnlocked());
|
||||||
try {
|
|
||||||
await db.closeAsync();
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[Database] 关闭数据库失败:', error);
|
|
||||||
}
|
|
||||||
db = null;
|
|
||||||
currentDbUserId = null;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -237,39 +276,47 @@ const isRecoverableDbError = (error: unknown): boolean => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const recoverDbConnection = async (): Promise<SQLite.SQLiteDatabase> => {
|
/** 在已持有 dbOpenCloseMutex 时重建连接(禁止在持有 SQLiteDatabase 期间 await 会抢锁的 recoverDbConnection) */
|
||||||
// 清理当前引用,随后用当前用户上下文重建连接
|
const reconnectDatabaseUnlocked = async (): Promise<void> => {
|
||||||
db = null;
|
await closeDatabaseUnlocked();
|
||||||
await initDatabase(currentDbUserId || undefined);
|
await initDatabaseUnlocked(currentDbUserId || undefined);
|
||||||
return getDb();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读路径与 init/close/recover 共用同一把锁,避免:
|
||||||
|
* 线程 A 持有 database 引用执行 prepareAsync 时,线程 B 的 recover 关闭连接导致 NPE。
|
||||||
|
*/
|
||||||
const withDbRead = async <T>(operation: (database: SQLite.SQLiteDatabase) => Promise<T>): Promise<T> => {
|
const withDbRead = async <T>(operation: (database: SQLite.SQLiteDatabase) => Promise<T>): Promise<T> => {
|
||||||
let database = await getDb();
|
return withDbOpenCloseLock(async () => {
|
||||||
try {
|
|
||||||
return await operation(database);
|
|
||||||
} catch (error) {
|
|
||||||
if (!isRecoverableDbError(error)) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
console.error('数据库读取异常,尝试重连后重试:', error);
|
|
||||||
database = await recoverDbConnection();
|
|
||||||
return operation(database);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const enqueueWrite = async <T>(operation: () => Promise<T>): Promise<T> => {
|
|
||||||
const wrappedOperation = async () => {
|
|
||||||
try {
|
try {
|
||||||
return await operation();
|
const database = await getDb();
|
||||||
|
return await operation(database);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isRecoverableDbError(error)) {
|
if (!isRecoverableDbError(error)) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
console.error('数据库写入异常,尝试重连后重试:', error);
|
console.error('数据库读取异常,尝试重连后重试:', error);
|
||||||
await recoverDbConnection();
|
await reconnectDatabaseUnlocked();
|
||||||
return operation();
|
const database = await getDb();
|
||||||
|
return await operation(database);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const enqueueWrite = async <T>(operation: () => Promise<T>): Promise<T> => {
|
||||||
|
const wrappedOperation = async () => {
|
||||||
|
return withDbOpenCloseLock(async () => {
|
||||||
|
try {
|
||||||
|
return await operation();
|
||||||
|
} catch (error) {
|
||||||
|
if (!isRecoverableDbError(error)) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
console.error('数据库写入异常,尝试重连后重试:', error);
|
||||||
|
await reconnectDatabaseUnlocked();
|
||||||
|
return await operation();
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
const queued = writeQueue.then(wrappedOperation, wrappedOperation);
|
const queued = writeQueue.then(wrappedOperation, wrappedOperation);
|
||||||
writeQueue = queued.then(() => undefined, () => undefined);
|
writeQueue = queued.then(() => undefined, () => undefined);
|
||||||
@@ -411,26 +458,24 @@ export const getMessagesBeforeSeq = async (conversationId: string, beforeSeq: nu
|
|||||||
|
|
||||||
// 获取本地消息数量(用于判断是否还有更多历史)
|
// 获取本地消息数量(用于判断是否还有更多历史)
|
||||||
export const getLocalMessageCountBeforeSeq = async (conversationId: string, beforeSeq: number): Promise<number> => {
|
export const getLocalMessageCountBeforeSeq = async (conversationId: string, beforeSeq: number): Promise<number> => {
|
||||||
const database = await getDb();
|
return withDbRead(async (database) => {
|
||||||
|
const result = await database.getFirstAsync<{ count: number }>(
|
||||||
const result = await database.getFirstAsync<{ count: number }>(
|
`SELECT COUNT(*) as count FROM messages WHERE conversationId = ? AND seq < ?`,
|
||||||
`SELECT COUNT(*) as count FROM messages WHERE conversationId = ? AND seq < ?`,
|
[conversationId, beforeSeq]
|
||||||
[conversationId, beforeSeq]
|
);
|
||||||
);
|
return result?.count || 0;
|
||||||
|
});
|
||||||
return result?.count || 0;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 获取消息数量
|
// 获取消息数量
|
||||||
export const getMessageCount = async (conversationId: string): Promise<number> => {
|
export const getMessageCount = async (conversationId: string): Promise<number> => {
|
||||||
const database = await getDb();
|
return withDbRead(async (database) => {
|
||||||
|
const result = await database.getFirstAsync<{ count: number }>(
|
||||||
const result = await database.getFirstAsync<{ count: number }>(
|
`SELECT COUNT(*) as count FROM messages WHERE conversationId = ?`,
|
||||||
`SELECT COUNT(*) as count FROM messages WHERE conversationId = ?`,
|
[conversationId]
|
||||||
[conversationId]
|
);
|
||||||
);
|
return result?.count || 0;
|
||||||
|
});
|
||||||
return result?.count || 0;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 标记消息为已读
|
// 标记消息为已读
|
||||||
@@ -532,13 +577,9 @@ export const saveConversation = async (conversation: {
|
|||||||
|
|
||||||
// 获取所有会话
|
// 获取所有会话
|
||||||
export const getAllConversations = async (): Promise<any[]> => {
|
export const getAllConversations = async (): Promise<any[]> => {
|
||||||
const database = await getDb();
|
return withDbRead(async (database) => {
|
||||||
|
return database.getAllAsync<any>(`SELECT * FROM conversations ORDER BY updatedAt DESC`);
|
||||||
const result = await database.getAllAsync<any>(
|
});
|
||||||
`SELECT * FROM conversations ORDER BY updatedAt DESC`
|
|
||||||
);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 更新会话未读数
|
// 更新会话未读数
|
||||||
@@ -587,21 +628,20 @@ export const deleteConversation = async (conversationId: string): Promise<void>
|
|||||||
|
|
||||||
// 搜索消息
|
// 搜索消息
|
||||||
export const searchMessages = async (keyword: string): Promise<CachedMessage[]> => {
|
export const searchMessages = async (keyword: string): Promise<CachedMessage[]> => {
|
||||||
const database = await getDb();
|
return withDbRead(async (database) => {
|
||||||
|
const result = await database.getAllAsync<any>(
|
||||||
const result = await database.getAllAsync<any>(
|
`SELECT * FROM messages
|
||||||
`SELECT * FROM messages
|
WHERE content LIKE ?
|
||||||
WHERE content LIKE ?
|
ORDER BY createdAt DESC
|
||||||
ORDER BY createdAt DESC
|
LIMIT 50`,
|
||||||
LIMIT 50`,
|
[`%${keyword}%`]
|
||||||
[`%${keyword}%`]
|
);
|
||||||
);
|
return result.map(msg => ({
|
||||||
|
...msg,
|
||||||
return result.map(msg => ({
|
isRead: msg.isRead === 1,
|
||||||
...msg,
|
segments: msg.segments ? JSON.parse(msg.segments) : undefined,
|
||||||
isRead: msg.isRead === 1,
|
}));
|
||||||
segments: msg.segments ? JSON.parse(msg.segments) : undefined,
|
});
|
||||||
}));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ==================== 工具函数 ====================
|
// ==================== 工具函数 ====================
|
||||||
@@ -611,20 +651,18 @@ export const getDatabaseStats = async (): Promise<{
|
|||||||
totalMessages: number;
|
totalMessages: number;
|
||||||
totalConversations: number;
|
totalConversations: number;
|
||||||
}> => {
|
}> => {
|
||||||
const database = await getDb();
|
return withDbRead(async (database) => {
|
||||||
|
const msgCount = await database.getFirstAsync<{ count: number }>(
|
||||||
const msgCount = await database.getFirstAsync<{ count: number }>(
|
`SELECT COUNT(*) as count FROM messages`
|
||||||
`SELECT COUNT(*) as count FROM messages`
|
);
|
||||||
);
|
const convCount = await database.getFirstAsync<{ count: number }>(
|
||||||
|
`SELECT COUNT(*) as count FROM conversations`
|
||||||
const convCount = await database.getFirstAsync<{ count: number }>(
|
);
|
||||||
`SELECT COUNT(*) as count FROM conversations`
|
return {
|
||||||
);
|
totalMessages: msgCount?.count || 0,
|
||||||
|
totalConversations: convCount?.count || 0,
|
||||||
return {
|
};
|
||||||
totalMessages: msgCount?.count || 0,
|
});
|
||||||
totalConversations: convCount?.count || 0,
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 清空所有数据(用于调试或用户退出登录)
|
// 清空所有数据(用于调试或用户退出登录)
|
||||||
@@ -689,12 +727,13 @@ export const getUserCache = async (userId: string): Promise<UserDTO | null> => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const getLatestUserCache = async (): Promise<UserDTO | null> => {
|
export const getLatestUserCache = async (): Promise<UserDTO | null> => {
|
||||||
const database = await getDb();
|
return withDbRead(async (database) => {
|
||||||
const row = await database.getFirstAsync<{ data: string }>(
|
const row = await database.getFirstAsync<{ data: string }>(
|
||||||
`SELECT data FROM users ORDER BY updatedAt DESC LIMIT 1`
|
`SELECT data FROM users ORDER BY updatedAt DESC LIMIT 1`
|
||||||
);
|
);
|
||||||
if (!row?.data) return null;
|
if (!row?.data) return null;
|
||||||
return safeParseJson<UserDTO>(row.data);
|
return safeParseJson<UserDTO>(row.data);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const saveCurrentUserCache = async (user: UserDTO): Promise<void> => {
|
export const saveCurrentUserCache = async (user: UserDTO): Promise<void> => {
|
||||||
|
|||||||
94
src/services/notificationPreferences.ts
Normal file
94
src/services/notificationPreferences.ts
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
/**
|
||||||
|
* 通知相关本地偏好(推送开关、提示音、震动)
|
||||||
|
* 启动时 loadNotificationPreferences 会同步到内存,供 SSE / 系统通知 / Handler 读取
|
||||||
|
*/
|
||||||
|
|
||||||
|
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||||
|
import * as Notifications from 'expo-notifications';
|
||||||
|
import { setVibrationEnabled } from './messageVibrationService';
|
||||||
|
|
||||||
|
export const NOTIFICATION_PREF_KEYS = {
|
||||||
|
/** 与历史版本保持一致 */
|
||||||
|
vibration: 'vibration_enabled',
|
||||||
|
push: 'notification_push_enabled',
|
||||||
|
sound: 'notification_sound_enabled',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type NotificationPrefs = {
|
||||||
|
pushEnabled: boolean;
|
||||||
|
soundEnabled: boolean;
|
||||||
|
vibrationEnabled: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaults: NotificationPrefs = {
|
||||||
|
pushEnabled: true,
|
||||||
|
soundEnabled: true,
|
||||||
|
vibrationEnabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
let cached: NotificationPrefs = { ...defaults };
|
||||||
|
|
||||||
|
export function getNotificationPreferencesSync(): NotificationPrefs {
|
||||||
|
return { ...cached };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBool(raw: string | null, fallback: boolean): boolean {
|
||||||
|
if (raw === null) return fallback;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as boolean;
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 应用启动时调用:从 AsyncStorage 恢复并写入震动服务内存态 */
|
||||||
|
export async function loadNotificationPreferences(): Promise<NotificationPrefs> {
|
||||||
|
try {
|
||||||
|
const [vibrationRaw, pushRaw, soundRaw] = await Promise.all([
|
||||||
|
AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.vibration),
|
||||||
|
AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.push),
|
||||||
|
AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.sound),
|
||||||
|
]);
|
||||||
|
cached = {
|
||||||
|
vibrationEnabled: parseBool(vibrationRaw, defaults.vibrationEnabled),
|
||||||
|
pushEnabled: parseBool(pushRaw, defaults.pushEnabled),
|
||||||
|
soundEnabled: parseBool(soundRaw, defaults.soundEnabled),
|
||||||
|
};
|
||||||
|
setVibrationEnabled(cached.vibrationEnabled);
|
||||||
|
return { ...cached };
|
||||||
|
} catch {
|
||||||
|
return { ...cached };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setVibrationPreference(enabled: boolean): Promise<void> {
|
||||||
|
cached.vibrationEnabled = enabled;
|
||||||
|
setVibrationEnabled(enabled);
|
||||||
|
await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.vibration, JSON.stringify(enabled));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setPushNotificationsPreference(enabled: boolean): Promise<void> {
|
||||||
|
cached.pushEnabled = enabled;
|
||||||
|
await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.push, JSON.stringify(enabled));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setSoundPreference(enabled: boolean): Promise<void> {
|
||||||
|
cached.soundEnabled = enabled;
|
||||||
|
await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.sound, JSON.stringify(enabled));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 注册 expo-notifications 展示策略(读取内存缓存,切换开关后立即生效) */
|
||||||
|
export function registerNotificationPresentationHandler(): void {
|
||||||
|
Notifications.setNotificationHandler({
|
||||||
|
handleNotification: async () => {
|
||||||
|
const p = getNotificationPreferencesSync();
|
||||||
|
return {
|
||||||
|
shouldShowAlert: p.pushEnabled,
|
||||||
|
shouldPlaySound: p.soundEnabled,
|
||||||
|
shouldSetBadge: true,
|
||||||
|
shouldShowBanner: p.pushEnabled,
|
||||||
|
shouldShowList: p.pushEnabled,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import EventSource from 'react-native-sse';
|
|||||||
import { api, SSE_URL } from './api';
|
import { api, SSE_URL } from './api';
|
||||||
import { MessageCategory, SystemMessageType, SystemMessageExtraData, MessageSegment } from '../types/dto';
|
import { MessageCategory, SystemMessageType, SystemMessageExtraData, MessageSegment } from '../types/dto';
|
||||||
import { systemNotificationService } from './systemNotificationService';
|
import { systemNotificationService } from './systemNotificationService';
|
||||||
|
import { getNotificationPreferencesSync } from './notificationPreferences';
|
||||||
import { vibrateOnMessage } from './messageVibrationService';
|
import { vibrateOnMessage } from './messageVibrationService';
|
||||||
|
|
||||||
export type WSMessageType =
|
export type WSMessageType =
|
||||||
@@ -384,7 +385,9 @@ class SSEService {
|
|||||||
created_at: payload.created_at || new Date().toISOString(),
|
created_at: payload.created_at || new Date().toISOString(),
|
||||||
};
|
};
|
||||||
this.emit('notification', m);
|
this.emit('notification', m);
|
||||||
vibrateOnMessage('notification').catch(() => {});
|
if (getNotificationPreferencesSync().pushEnabled) {
|
||||||
|
vibrateOnMessage('notification').catch(() => {});
|
||||||
|
}
|
||||||
systemNotificationService.handleWSMessage(m as any).catch(() => {});
|
systemNotificationService.handleWSMessage(m as any).catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import * as Notifications from 'expo-notifications';
|
|||||||
import { Platform, AppState, AppStateStatus } from 'react-native';
|
import { Platform, AppState, AppStateStatus } from 'react-native';
|
||||||
import type { WSChatMessage, WSNotificationMessage, WSAnnouncementMessage } from './sseService';
|
import type { WSChatMessage, WSNotificationMessage, WSAnnouncementMessage } from './sseService';
|
||||||
import { extractTextFromSegments } from '../types/dto';
|
import { extractTextFromSegments } from '../types/dto';
|
||||||
|
import { getNotificationPreferencesSync } from './notificationPreferences';
|
||||||
|
|
||||||
// 通知渠道配置
|
// 通知渠道配置
|
||||||
const CHANNEL_ID = 'default';
|
const CHANNEL_ID = 'default';
|
||||||
@@ -71,17 +72,6 @@ class SystemNotificationService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置 notification handler,确保前台也能显示通知、播放声音和震动
|
|
||||||
Notifications.setNotificationHandler({
|
|
||||||
handleNotification: async () => ({
|
|
||||||
shouldShowAlert: true,
|
|
||||||
shouldPlaySound: true,
|
|
||||||
shouldSetBadge: true,
|
|
||||||
shouldShowBanner: true,
|
|
||||||
shouldShowList: true,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (Platform.OS === 'android') {
|
if (Platform.OS === 'android') {
|
||||||
await Notifications.setNotificationChannelAsync(CHANNEL_ID, {
|
await Notifications.setNotificationChannelAsync(CHANNEL_ID, {
|
||||||
name: CHANNEL_NAME,
|
name: CHANNEL_NAME,
|
||||||
@@ -120,15 +110,16 @@ class SystemNotificationService {
|
|||||||
// 使用 scheduleNotificationAsync 立即显示通知
|
// 使用 scheduleNotificationAsync 立即显示通知
|
||||||
// 配合 setNotificationHandler 确保前台也能显示
|
// 配合 setNotificationHandler 确保前台也能显示
|
||||||
|
|
||||||
|
const { vibrationEnabled } = getNotificationPreferencesSync();
|
||||||
// 构建通知内容
|
// 构建通知内容
|
||||||
const content: Notifications.NotificationContentInput = {
|
const content: Notifications.NotificationContentInput = {
|
||||||
title: options.title,
|
title: options.title,
|
||||||
body: options.body,
|
body: options.body,
|
||||||
data: options.data as Record<string, string | number | object> | undefined,
|
data: options.data as Record<string, string | number | object> | undefined,
|
||||||
// 显式设置震动(仅 Android 生效)
|
// 显式设置震动(仅 Android 生效,且尊重「消息震动」开关)
|
||||||
...(Platform.OS === 'android' ? {
|
...(Platform.OS === 'android' && vibrationEnabled
|
||||||
vibrationPattern: [0, 300, 200, 300],
|
? { vibrationPattern: [0, 300, 200, 300] }
|
||||||
} : {}),
|
: {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
const notificationId = await Notifications.scheduleNotificationAsync({
|
const notificationId = await Notifications.scheduleNotificationAsync({
|
||||||
@@ -179,6 +170,9 @@ class SystemNotificationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleWSMessage(message: WSChatMessage | WSNotificationMessage | WSAnnouncementMessage): Promise<void> {
|
async handleWSMessage(message: WSChatMessage | WSNotificationMessage | WSAnnouncementMessage): Promise<void> {
|
||||||
|
if (!getNotificationPreferencesSync().pushEnabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 仅在后台时显示通知,前台时不显示(用户正在使用应用,可以直接看到消息)
|
// 仅在后台时显示通知,前台时不显示(用户正在使用应用,可以直接看到消息)
|
||||||
if (this.currentAppState !== 'active') {
|
if (this.currentAppState !== 'active') {
|
||||||
// 判断是否是聊天消息(通过 segments 字段)
|
// 判断是否是聊天消息(通过 segments 字段)
|
||||||
|
|||||||
12
src/stores/homeTabBarVisibilityStore.ts
Normal file
12
src/stores/homeTabBarVisibilityStore.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { create } from 'zustand';
|
||||||
|
|
||||||
|
interface HomeTabBarVisibilityState {
|
||||||
|
/** 首页列表下滑时隐藏底部 Tab,上滑或闲置后恢复 */
|
||||||
|
bottomTabBarHiddenByScroll: boolean;
|
||||||
|
setBottomTabBarHiddenByScroll: (hidden: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useHomeTabBarVisibilityStore = create<HomeTabBarVisibilityState>((set) => ({
|
||||||
|
bottomTabBarHiddenByScroll: false,
|
||||||
|
setBottomTabBarHiddenByScroll: (hidden) => set({ bottomTabBarHiddenByScroll: hidden }),
|
||||||
|
}));
|
||||||
@@ -42,6 +42,9 @@ export { enrichGroupMembersWithUserProfiles } from './groupMemberProfileResolver
|
|||||||
export { postManager } from './postManager';
|
export { postManager } from './postManager';
|
||||||
export { groupManager } from './groupManager';
|
export { groupManager } from './groupManager';
|
||||||
export { userManager } from './userManager';
|
export { userManager } from './userManager';
|
||||||
|
export {
|
||||||
|
useHomeTabBarVisibilityStore,
|
||||||
|
} from './homeTabBarVisibilityStore';
|
||||||
export {
|
export {
|
||||||
useConversations as useMessageManagerConversations,
|
useConversations as useMessageManagerConversations,
|
||||||
useMessages,
|
useMessages,
|
||||||
|
|||||||
@@ -57,6 +57,12 @@ export interface PostImageDTO {
|
|||||||
height: number;
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 帖子所属频道(列表卡片展示) */
|
||||||
|
export interface PostChannelBriefDTO {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PostDTO {
|
export interface PostDTO {
|
||||||
id: string;
|
id: string;
|
||||||
user_id: string;
|
user_id: string;
|
||||||
@@ -81,6 +87,8 @@ export interface PostDTO {
|
|||||||
is_favorited: boolean;
|
is_favorited: boolean;
|
||||||
// 额外字段
|
// 额外字段
|
||||||
channel_id?: string;
|
channel_id?: string;
|
||||||
|
/** 频道摘要(与 channel_id 对应,服务端批量填充) */
|
||||||
|
channel?: PostChannelBriefDTO | null;
|
||||||
top_comment?: CommentDTO | null;
|
top_comment?: CommentDTO | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user