feat(Notification): implement notification preferences management and enhance notification handling
- Introduced a new service for managing notification preferences, including push notifications, sound, and vibration settings. - Updated the notification handling logic to respect user preferences, ensuring notifications are displayed according to user settings. - Refactored the App and various screens to integrate the new notification preferences, improving user experience and consistency. - Enhanced the HomeScreen and NotificationSettingsScreen to load and update notification settings seamlessly. - Implemented a mechanism to hide the bottom tab bar based on scroll events, improving navigation usability.
This commit is contained in:
@@ -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,19 +15,19 @@ 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;
|
||||||
|
|
||||||
return (
|
const isHomeStackRoute = pathname === '/home' || pathname.startsWith('/home/');
|
||||||
<Tabs
|
|
||||||
screenOptions={{
|
const tabBarStyle = useMemo(() => {
|
||||||
headerShown: false,
|
if (hideTabBar) {
|
||||||
tabBarActiveTintColor: colors.primary.main,
|
return { display: 'none' as const, height: 0, overflow: 'hidden' as const };
|
||||||
tabBarInactiveTintColor: colors.text.secondary,
|
}
|
||||||
tabBarStyle: hideTabBar
|
const visibleStyle = {
|
||||||
? { display: 'none', height: 0, overflow: 'hidden' }
|
position: 'absolute' as const,
|
||||||
: {
|
|
||||||
position: 'absolute',
|
|
||||||
left: 0,
|
left: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
marginHorizontal: TAB_BAR_MARGIN,
|
marginHorizontal: TAB_BAR_MARGIN,
|
||||||
@@ -38,7 +39,26 @@ export default function TabsLayout() {
|
|||||||
borderTopWidth: 0,
|
borderTopWidth: 0,
|
||||||
elevation: 100,
|
elevation: 100,
|
||||||
zIndex: 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 (
|
||||||
|
<Tabs
|
||||||
|
screenOptions={{
|
||||||
|
headerShown: false,
|
||||||
|
tabBarActiveTintColor: colors.primary.main,
|
||||||
|
tabBarInactiveTintColor: colors.text.secondary,
|
||||||
|
tabBarStyle,
|
||||||
tabBarItemStyle: {
|
tabBarItemStyle: {
|
||||||
borderRadius: 16,
|
borderRadius: 16,
|
||||||
marginHorizontal: 2,
|
marginHorizontal: 2,
|
||||||
@@ -62,13 +82,12 @@ export default function TabsLayout() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Tabs.Screen
|
<Tabs.Screen
|
||||||
name="messages"
|
name="apps"
|
||||||
options={{
|
options={{
|
||||||
title: '消息',
|
title: '应用',
|
||||||
tabBarBadge: unreadCount > 0 ? (unreadCount > 99 ? 99 : unreadCount) : undefined,
|
|
||||||
tabBarIcon: ({ color, focused }) => (
|
tabBarIcon: ({ color, focused }) => (
|
||||||
<MaterialCommunityIcons
|
<MaterialCommunityIcons
|
||||||
name={focused ? 'message-text' : 'message-text-outline'}
|
name={focused ? 'view-grid' : 'view-grid-outline'}
|
||||||
size={focused ? 24 : 22}
|
size={focused ? 24 : 22}
|
||||||
color={color}
|
color={color}
|
||||||
/>
|
/>
|
||||||
@@ -76,12 +95,13 @@ export default function TabsLayout() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Tabs.Screen
|
<Tabs.Screen
|
||||||
name="apps"
|
name="messages"
|
||||||
options={{
|
options={{
|
||||||
title: '应用',
|
title: '消息',
|
||||||
|
tabBarBadge: unreadCount > 0 ? (unreadCount > 99 ? 99 : unreadCount) : undefined,
|
||||||
tabBarIcon: ({ color, focused }) => (
|
tabBarIcon: ({ color, focused }) => (
|
||||||
<MaterialCommunityIcons
|
<MaterialCommunityIcons
|
||||||
name={focused ? 'view-grid' : 'view-grid-outline'}
|
name={focused ? 'message-text' : 'message-text-outline'}
|
||||||
size={focused ? 24 : 22}
|
size={focused ? 24 : 22}
|
||||||
color={color}
|
color={color}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -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');
|
||||||
|
|||||||
@@ -23,8 +23,8 @@ 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: 'MessageTab', label: '消息', href: '/messages', icon: 'message-text', iconOutline: 'message-text-outline' },
|
|
||||||
{ name: 'AppsTab', label: '应用', href: '/apps', icon: 'view-grid', iconOutline: 'view-grid-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: 'ProfileTab', label: '我的', href: '/profile', icon: 'account', iconOutline: 'account-outline' },
|
{ name: 'ProfileTab', label: '我的', href: '/profile', icon: 'account', iconOutline: 'account-outline' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -346,14 +346,6 @@ const PostCardInner: React.FC<PostCardProps> = (normalizedProps) => {
|
|||||||
{!showGrid && (
|
{!showGrid && (
|
||||||
<View style={styles.metaRow}>
|
<View style={styles.metaRow}>
|
||||||
<PostCardRelativeTime createdAt={post.created_at} style={styles.timeText} />
|
<PostCardRelativeTime createdAt={post.created_at} style={styles.timeText} />
|
||||||
{!!post.channel?.name && (
|
|
||||||
<View style={styles.channelTag}>
|
|
||||||
<MaterialCommunityIcons name="tag-outline" size={11} color={colors.primary.main} />
|
|
||||||
<Text style={styles.channelTagText} numberOfLines={1}>
|
|
||||||
{post.channel.name}
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
)}
|
|
||||||
{post.is_pinned && (
|
{post.is_pinned && (
|
||||||
<View style={styles.pinnedTag}>
|
<View style={styles.pinnedTag}>
|
||||||
<MaterialCommunityIcons name="pin" size={10} color={colors.warning.main} />
|
<MaterialCommunityIcons name="pin" size={10} color={colors.warning.main} />
|
||||||
@@ -402,10 +394,20 @@ const PostCardInner: React.FC<PostCardProps> = (normalizedProps) => {
|
|||||||
{renderTopComment()}
|
{renderTopComment()}
|
||||||
|
|
||||||
<View style={styles.actions}>
|
<View style={styles.actions}>
|
||||||
|
<View style={styles.actionsLeading}>
|
||||||
<View style={styles.viewsWrap}>
|
<View style={styles.viewsWrap}>
|
||||||
<MaterialCommunityIcons name="eye-outline" size={16} color={colors.text.hint} />
|
<MaterialCommunityIcons name="eye-outline" size={16} color={colors.text.hint} />
|
||||||
<Text style={styles.viewsText}>{post.views_count || 0}</Text>
|
<Text style={styles.viewsText}>{post.views_count || 0}</Text>
|
||||||
</View>
|
</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 style={styles.actionButtons}>
|
<View style={styles.actionButtons}>
|
||||||
<TouchableOpacity style={styles.actionBtn} onPress={handleLike}>
|
<TouchableOpacity style={styles.actionBtn} onPress={handleLike}>
|
||||||
<MaterialCommunityIcons
|
<MaterialCommunityIcons
|
||||||
@@ -571,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,
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
|||||||
@@ -1,25 +1,23 @@
|
|||||||
/**
|
/**
|
||||||
* 应用中心:聚合站内轻应用入口
|
* 应用中心:与首页顶栏、个人主页帖子卡片同一套圆角 / 阴影 / 主色体系
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { useCallback, useMemo, useState } from 'react';
|
import React, { useCallback } from 'react';
|
||||||
import { View, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
|
import { View, StyleSheet, ScrollView, TouchableOpacity, StatusBar } from 'react-native';
|
||||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||||
import { StatusBar } from 'expo-status-bar';
|
|
||||||
import { useRouter } from 'expo-router';
|
import { useRouter } from 'expo-router';
|
||||||
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
import { MaterialCommunityIcons } from '@expo/vector-icons';
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
|
||||||
|
|
||||||
import { colors, spacing, fontSizes, borderRadius, shadows } from '../../theme';
|
import { colors, spacing, fontSizes, borderRadius, shadows } from '../../theme';
|
||||||
import * as hrefs from '../../navigation/hrefs';
|
import * as hrefs from '../../navigation/hrefs';
|
||||||
import { Text, ResponsiveContainer } from '../../components/common';
|
import { Text, ResponsiveContainer } from '../../components/common';
|
||||||
import { useResponsive } from '../../hooks/useResponsive';
|
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks/useResponsive';
|
||||||
|
|
||||||
type AppItem = {
|
type AppItem = {
|
||||||
id: string;
|
id: string;
|
||||||
title: string;
|
title: string;
|
||||||
subtitle: string;
|
subtitle: string;
|
||||||
icon: React.ComponentProps<typeof MaterialCommunityIcons>['name'];
|
icon: React.ComponentProps<typeof MaterialCommunityIcons>['name'];
|
||||||
gradient: readonly [string, string, ...string[]];
|
|
||||||
href: string;
|
href: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -27,28 +25,32 @@ const APP_ENTRIES: AppItem[] = [
|
|||||||
{
|
{
|
||||||
id: 'schedule',
|
id: 'schedule',
|
||||||
title: '课表',
|
title: '课表',
|
||||||
subtitle: '周视图 · 教务同步',
|
subtitle: '周课表、教务同步与课程管理',
|
||||||
icon: 'calendar-week',
|
icon: 'calendar-week',
|
||||||
gradient: [colors.primary.main, colors.primary.light],
|
|
||||||
href: hrefs.hrefSchedule(),
|
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 = () => {
|
export const AppsScreen: React.FC = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const insets = useSafeAreaInsets();
|
const insets = useSafeAreaInsets();
|
||||||
const { isMobile, isTablet, width } = useResponsive();
|
const { isMobile } = useResponsive();
|
||||||
|
/** 与 MessageListScreen 顶栏宽屏 padding 一致 */
|
||||||
const columns = useMemo(() => {
|
const isWideScreen = useBreakpointGTE('lg');
|
||||||
if (width >= 900) return 4;
|
const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });
|
||||||
if (isTablet || width >= 600) return 3;
|
|
||||||
return 2;
|
|
||||||
}, [isTablet, width]);
|
|
||||||
|
|
||||||
const gap = spacing.md;
|
|
||||||
const [gridWidth, setGridWidth] = useState(0);
|
|
||||||
const cardWidth =
|
|
||||||
gridWidth > 0 ? (gridWidth - gap * (columns - 1)) / columns : undefined;
|
|
||||||
|
|
||||||
const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];
|
const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];
|
||||||
|
|
||||||
@@ -59,74 +61,82 @@ export const AppsScreen: React.FC = () => {
|
|||||||
[router]
|
[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 (
|
return (
|
||||||
<SafeAreaView style={styles.safe} edges={['top']}>
|
<SafeAreaView style={styles.container} edges={['top', 'bottom']}>
|
||||||
<StatusBar style="dark" />
|
<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
|
<ScrollView
|
||||||
style={styles.scroll}
|
style={styles.scroll}
|
||||||
contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset }]}
|
contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset }]}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
>
|
>
|
||||||
<ResponsiveContainer maxWidth={960}>
|
{renderTiles()}
|
||||||
<LinearGradient
|
|
||||||
colors={[`${colors.primary.main}18`, `${colors.primary.light}10`, 'transparent']}
|
|
||||||
start={{ x: 0, y: 0 }}
|
|
||||||
end={{ x: 1, y: 1 }}
|
|
||||||
style={styles.hero}
|
|
||||||
>
|
|
||||||
<View style={styles.heroIconWrap}>
|
|
||||||
<LinearGradient
|
|
||||||
colors={[colors.primary.main, colors.primary.light]}
|
|
||||||
style={styles.heroIconGradient}
|
|
||||||
start={{ x: 0, y: 0 }}
|
|
||||||
end={{ x: 1, y: 1 }}
|
|
||||||
>
|
|
||||||
<MaterialCommunityIcons name="apps" size={28} color={colors.primary.contrast} />
|
|
||||||
</LinearGradient>
|
|
||||||
</View>
|
|
||||||
<Text style={styles.heroTitle}>应用</Text>
|
|
||||||
<Text style={styles.heroSubtitle}>学习与生活常用工具,持续扩充中</Text>
|
|
||||||
</LinearGradient>
|
|
||||||
|
|
||||||
<Text style={styles.sectionLabel}>全部应用</Text>
|
|
||||||
<View
|
|
||||||
style={[styles.grid, { gap }]}
|
|
||||||
onLayout={e => setGridWidth(e.nativeEvent.layout.width)}
|
|
||||||
>
|
|
||||||
{APP_ENTRIES.map(item => (
|
|
||||||
<TouchableOpacity
|
|
||||||
key={item.id}
|
|
||||||
style={[styles.card, cardWidth != null ? { width: cardWidth } : styles.cardFlex, shadows.md]}
|
|
||||||
onPress={() => onOpenApp(item.href)}
|
|
||||||
activeOpacity={0.88}
|
|
||||||
>
|
|
||||||
<LinearGradient
|
|
||||||
colors={item.gradient}
|
|
||||||
start={{ x: 0, y: 0 }}
|
|
||||||
end={{ x: 1, y: 1 }}
|
|
||||||
style={styles.cardIconRing}
|
|
||||||
>
|
|
||||||
<View style={styles.cardIconInner}>
|
|
||||||
<MaterialCommunityIcons name={item.icon} size={26} color={colors.primary.main} />
|
|
||||||
</View>
|
|
||||||
</LinearGradient>
|
|
||||||
<Text style={styles.cardTitle} numberOfLines={1}>
|
|
||||||
{item.title}
|
|
||||||
</Text>
|
|
||||||
<Text style={styles.cardSubtitle} numberOfLines={2}>
|
|
||||||
{item.subtitle}
|
|
||||||
</Text>
|
|
||||||
<View style={styles.cardFooter}>
|
|
||||||
<Text style={styles.cardAction}>打开</Text>
|
|
||||||
<MaterialCommunityIcons name="chevron-right" size={18} color={colors.primary.main} />
|
|
||||||
</View>
|
|
||||||
</TouchableOpacity>
|
|
||||||
))}
|
|
||||||
</View>
|
|
||||||
|
|
||||||
<Text style={styles.hint}>更多应用敬请期待</Text>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
) : (
|
||||||
|
<ScrollView
|
||||||
|
style={styles.scroll}
|
||||||
|
contentContainerStyle={[
|
||||||
|
styles.scrollContent,
|
||||||
|
{ paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding },
|
||||||
|
]}
|
||||||
|
showsVerticalScrollIndicator={false}
|
||||||
|
>
|
||||||
|
{renderTiles()}
|
||||||
|
</ScrollView>
|
||||||
|
)}
|
||||||
</SafeAreaView>
|
</SafeAreaView>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -134,115 +144,92 @@ export const AppsScreen: React.FC = () => {
|
|||||||
export default AppsScreen;
|
export default AppsScreen;
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
safe: {
|
container: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
backgroundColor: colors.background.default,
|
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: {
|
scroll: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
|
backgroundColor: '#FAFAFA',
|
||||||
},
|
},
|
||||||
scrollContent: {
|
scrollContent: {
|
||||||
paddingTop: spacing.md,
|
paddingTop: spacing.md,
|
||||||
|
flexGrow: 1,
|
||||||
|
backgroundColor: '#FAFAFA',
|
||||||
|
},
|
||||||
|
appCardInner: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
paddingVertical: spacing.lg,
|
||||||
paddingHorizontal: spacing.lg,
|
paddingHorizontal: spacing.lg,
|
||||||
},
|
},
|
||||||
hero: {
|
/** 与首页发帖 FAB 同主色实心圆 */
|
||||||
borderRadius: borderRadius['2xl'],
|
appIconCircle: {
|
||||||
paddingVertical: spacing['2xl'],
|
|
||||||
paddingHorizontal: spacing.xl,
|
|
||||||
marginBottom: spacing['2xl'],
|
|
||||||
overflow: 'hidden',
|
|
||||||
},
|
|
||||||
heroIconWrap: {
|
|
||||||
marginBottom: spacing.md,
|
|
||||||
},
|
|
||||||
heroIconGradient: {
|
|
||||||
width: 52,
|
width: 52,
|
||||||
height: 52,
|
height: 52,
|
||||||
borderRadius: borderRadius.xl,
|
borderRadius: borderRadius.full,
|
||||||
alignItems: 'center',
|
backgroundColor: colors.primary.main,
|
||||||
justifyContent: 'center',
|
|
||||||
...shadows.md,
|
|
||||||
},
|
|
||||||
heroTitle: {
|
|
||||||
fontSize: fontSizes['3xl'],
|
|
||||||
fontWeight: '800',
|
|
||||||
color: colors.text.primary,
|
|
||||||
letterSpacing: -0.5,
|
|
||||||
},
|
|
||||||
heroSubtitle: {
|
|
||||||
marginTop: spacing.xs,
|
|
||||||
fontSize: fontSizes.sm,
|
|
||||||
color: colors.text.secondary,
|
|
||||||
lineHeight: 20,
|
|
||||||
maxWidth: 320,
|
|
||||||
},
|
|
||||||
sectionLabel: {
|
|
||||||
fontSize: fontSizes.xs,
|
|
||||||
fontWeight: '700',
|
|
||||||
color: colors.text.secondary,
|
|
||||||
textTransform: 'uppercase',
|
|
||||||
letterSpacing: 1.2,
|
|
||||||
marginBottom: spacing.md,
|
|
||||||
marginLeft: 2,
|
|
||||||
},
|
|
||||||
grid: {
|
|
||||||
flexDirection: 'row',
|
|
||||||
flexWrap: 'wrap',
|
|
||||||
width: '100%',
|
|
||||||
},
|
|
||||||
cardFlex: {
|
|
||||||
flex: 1,
|
|
||||||
minWidth: 140,
|
|
||||||
maxWidth: '100%',
|
|
||||||
},
|
|
||||||
card: {
|
|
||||||
backgroundColor: colors.background.paper,
|
|
||||||
borderRadius: borderRadius.xl,
|
|
||||||
padding: spacing.lg,
|
|
||||||
borderWidth: 1,
|
|
||||||
borderColor: `${colors.divider}99`,
|
|
||||||
},
|
|
||||||
cardIconRing: {
|
|
||||||
width: 52,
|
|
||||||
height: 52,
|
|
||||||
borderRadius: borderRadius.lg,
|
|
||||||
padding: 2,
|
|
||||||
marginBottom: spacing.md,
|
|
||||||
alignSelf: 'flex-start',
|
|
||||||
},
|
|
||||||
cardIconInner: {
|
|
||||||
flex: 1,
|
|
||||||
borderRadius: borderRadius.md,
|
|
||||||
backgroundColor: colors.background.paper,
|
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent: 'center',
|
justifyContent: 'center',
|
||||||
},
|
},
|
||||||
cardTitle: {
|
appCardText: {
|
||||||
fontSize: fontSizes.lg,
|
flex: 1,
|
||||||
|
marginLeft: spacing.md,
|
||||||
|
marginRight: spacing.sm,
|
||||||
|
},
|
||||||
|
appTitle: {
|
||||||
fontWeight: '700',
|
fontWeight: '700',
|
||||||
color: colors.text.primary,
|
fontSize: fontSizes.md + 1,
|
||||||
},
|
},
|
||||||
cardSubtitle: {
|
appSubtitle: {
|
||||||
marginTop: spacing.xs,
|
marginTop: 4,
|
||||||
fontSize: fontSizes.sm,
|
|
||||||
color: colors.text.secondary,
|
|
||||||
lineHeight: 18,
|
|
||||||
minHeight: 36,
|
|
||||||
},
|
},
|
||||||
cardFooter: {
|
footer: {
|
||||||
flexDirection: 'row',
|
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
marginTop: spacing.md,
|
paddingTop: spacing.xl,
|
||||||
},
|
paddingBottom: spacing.md,
|
||||||
cardAction: {
|
|
||||||
fontSize: fontSizes.sm,
|
|
||||||
fontWeight: '600',
|
|
||||||
color: colors.primary.main,
|
|
||||||
},
|
|
||||||
hint: {
|
|
||||||
marginTop: spacing['3xl'],
|
|
||||||
textAlign: 'center',
|
|
||||||
fontSize: fontSizes.sm,
|
|
||||||
color: colors.text.hint,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -21,12 +21,12 @@ import {
|
|||||||
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';
|
||||||
@@ -47,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';
|
||||||
@@ -93,6 +97,65 @@ 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 capsuleHScrollRef = useRef<ScrollView | null>(null);
|
||||||
const capsuleScrollXRef = useRef(0);
|
const capsuleScrollXRef = useRef(0);
|
||||||
@@ -133,6 +196,11 @@ 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(() => {
|
useLayoutEffect(() => {
|
||||||
if (!isLatestTab) return;
|
if (!isLatestTab) return;
|
||||||
restoreCapsuleStripScroll();
|
restoreCapsuleStripScroll();
|
||||||
@@ -183,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(
|
||||||
|
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||||
|
handleHomeVerticalScroll(event);
|
||||||
const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
|
const { layoutMeasurement, contentOffset, contentSize } = event.nativeEvent;
|
||||||
const scrollY = contentOffset.y;
|
const scrollY = contentOffset.y;
|
||||||
const visibleHeight = layoutMeasurement.height;
|
const visibleHeight = layoutMeasurement.height;
|
||||||
const contentHeight = contentSize.height;
|
const contentHeight = contentSize.height;
|
||||||
|
|
||||||
// 当滚动到距离底部 200px 时触发加载更多
|
|
||||||
if (scrollY + visibleHeight >= contentHeight - 200) {
|
if (scrollY + visibleHeight >= contentHeight - 200) {
|
||||||
loadMore();
|
loadMore();
|
||||||
}
|
}
|
||||||
}, [loadMore]);
|
},
|
||||||
|
[handleHomeVerticalScroll, loadMore]
|
||||||
|
);
|
||||||
|
|
||||||
// 刷新方法 - 先获取正确类型的帖子,再刷新
|
// 刷新方法 - 先获取正确类型的帖子,再刷新
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
@@ -227,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]);
|
||||||
@@ -281,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 = () => {
|
||||||
@@ -639,7 +715,7 @@ export const HomeScreen: React.FC = () => {
|
|||||||
}
|
}
|
||||||
]}
|
]}
|
||||||
showsVerticalScrollIndicator={false}
|
showsVerticalScrollIndicator={false}
|
||||||
scrollEventThrottle={100}
|
scrollEventThrottle={16}
|
||||||
onScroll={handleGridScroll}
|
onScroll={handleGridScroll}
|
||||||
refreshControl={
|
refreshControl={
|
||||||
<RefreshControl
|
<RefreshControl
|
||||||
@@ -734,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}
|
||||||
@@ -783,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
|
||||||
@@ -874,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 },
|
||||||
@@ -882,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,
|
||||||
|
|||||||
@@ -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,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -20,22 +20,50 @@ 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) {
|
||||||
*/
|
|
||||||
export const initDatabase = async (userId?: string): Promise<void> => {
|
|
||||||
try {
|
try {
|
||||||
|
await db.closeAsync();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[Database] 关闭数据库失败:', error);
|
||||||
|
}
|
||||||
|
db = null;
|
||||||
|
currentDbUserId = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
async function initDatabaseUnlocked(userId?: string): Promise<void> {
|
||||||
// 如果指定了用户ID,使用用户专属数据库
|
// 如果指定了用户ID,使用用户专属数据库
|
||||||
// 否则使用默认数据库(兼容旧版本)
|
// 否则使用默认数据库(兼容旧版本)
|
||||||
const dbName = userId ? `carrot_bbs_${userId}.db` : 'carrot_bbs.db';
|
const dbName = userId ? `carrot_bbs_${userId}.db` : 'carrot_bbs.db';
|
||||||
|
|
||||||
// 如果存在旧的数据库连接且用户ID变化,需要关闭旧连接
|
// 如果存在旧的数据库连接且用户ID变化,需要关闭旧连接
|
||||||
if (db && currentDbUserId !== userId) {
|
if (db && currentDbUserId !== userId) {
|
||||||
await closeDatabase();
|
await closeDatabaseUnlocked();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果已经打开了正确的数据库,直接返回
|
// 如果已经打开了正确的数据库,直接返回
|
||||||
@@ -43,7 +71,10 @@ export const initDatabase = async (userId?: string): Promise<void> => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
db = await SQLite.openDatabaseAsync(dbName);
|
let opened: SQLite.SQLiteDatabase | null = null;
|
||||||
|
try {
|
||||||
|
opened = await SQLite.openDatabaseAsync(dbName);
|
||||||
|
db = opened;
|
||||||
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,29 +276,36 @@ 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 {
|
try {
|
||||||
|
const database = await getDb();
|
||||||
return await operation(database);
|
return await operation(database);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isRecoverableDbError(error)) {
|
if (!isRecoverableDbError(error)) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
console.error('数据库读取异常,尝试重连后重试:', error);
|
console.error('数据库读取异常,尝试重连后重试:', error);
|
||||||
database = await recoverDbConnection();
|
await reconnectDatabaseUnlocked();
|
||||||
return operation(database);
|
const database = await getDb();
|
||||||
|
return await operation(database);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const enqueueWrite = async <T>(operation: () => Promise<T>): Promise<T> => {
|
const enqueueWrite = async <T>(operation: () => Promise<T>): Promise<T> => {
|
||||||
const wrappedOperation = async () => {
|
const wrappedOperation = async () => {
|
||||||
|
return withDbOpenCloseLock(async () => {
|
||||||
try {
|
try {
|
||||||
return await operation();
|
return await operation();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -267,9 +313,10 @@ const enqueueWrite = async <T>(operation: () => Promise<T>): Promise<T> => {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
console.error('数据库写入异常,尝试重连后重试:', error);
|
console.error('数据库写入异常,尝试重连后重试:', error);
|
||||||
await recoverDbConnection();
|
await reconnectDatabaseUnlocked();
|
||||||
return operation();
|
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,8 +628,7 @@ 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 ?
|
||||||
@@ -596,12 +636,12 @@ export const searchMessages = async (keyword: string): Promise<CachedMessage[]>
|
|||||||
LIMIT 50`,
|
LIMIT 50`,
|
||||||
[`%${keyword}%`]
|
[`%${keyword}%`]
|
||||||
);
|
);
|
||||||
|
|
||||||
return result.map(msg => ({
|
return result.map(msg => ({
|
||||||
...msg,
|
...msg,
|
||||||
isRead: msg.isRead === 1,
|
isRead: msg.isRead === 1,
|
||||||
segments: msg.segments ? JSON.parse(msg.segments) : undefined,
|
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 }>(
|
const convCount = await database.getFirstAsync<{ count: number }>(
|
||||||
`SELECT COUNT(*) as count FROM conversations`
|
`SELECT COUNT(*) as count FROM conversations`
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
totalMessages: msgCount?.count || 0,
|
totalMessages: msgCount?.count || 0,
|
||||||
totalConversations: convCount?.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);
|
||||||
|
if (getNotificationPreferencesSync().pushEnabled) {
|
||||||
vibrateOnMessage('notification').catch(() => {});
|
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,
|
||||||
|
|||||||
Reference in New Issue
Block a user