feat(onboarding): 添加新用户引导流程

实现了完整的应用引导功能,包括:
- 新增引导页面UI,包含健康数据追踪、轻断食计划和健康挑战三个介绍页面
- 添加引导状态持久化存储,使用AsyncStorage管理用户完成状态
- 修改应用启动逻辑,根据引导状态决定跳转到主页或引导页
- 在开发者选项中添加重置引导状态功能,方便测试
- 更新路由配置和存储键常量,统一管理引导相关配置
This commit is contained in:
richarjiang
2025-11-06 15:22:31 +08:00
parent 9b1a40cea3
commit a228280ca4
10 changed files with 323 additions and 16 deletions

View File

@@ -319,6 +319,7 @@ export default function RootLayout() {
<ToastProvider> <ToastProvider>
<ThemeProvider value={DefaultTheme}> <ThemeProvider value={DefaultTheme}>
<Stack screenOptions={{ headerShown: false }}> <Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="onboarding" />
<Stack.Screen name="(tabs)" /> <Stack.Screen name="(tabs)" />
<Stack.Screen name="challenge" options={{ headerShown: false }} /> <Stack.Screen name="challenge" options={{ headerShown: false }} />
<Stack.Screen name="training-plan" options={{ headerShown: false }} /> <Stack.Screen name="training-plan" options={{ headerShown: false }} />

View File

@@ -1,14 +1,26 @@
import { ROUTES } from '@/constants/Routes'; import { ROUTES } from '@/constants/Routes';
import { STORAGE_KEYS } from '@/services/api';
import AsyncStorage from '@/utils/kvStore';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import React from 'react'; import React from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { Alert, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
export default function DeveloperScreen() { export default function DeveloperScreen() {
const router = useRouter(); const router = useRouter();
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
const resetOnboardingStatus = async () => {
try {
await AsyncStorage.removeItem(STORAGE_KEYS.onboardingCompleted);
Alert.alert('成功', '引导状态已重置,下次启动应用将重新显示引导页面');
} catch (error) {
console.error('重置引导状态失败:', error);
Alert.alert('错误', '重置引导状态失败,请重试');
}
};
const developerItems = [ const developerItems = [
{ {
title: '日志', title: '日志',
@@ -16,6 +28,12 @@ export default function DeveloperScreen() {
icon: 'document-text-outline', icon: 'document-text-outline',
onPress: () => router.push(ROUTES.DEVELOPER_LOGS), onPress: () => router.push(ROUTES.DEVELOPER_LOGS),
}, },
{
title: '重置引导状态',
subtitle: '清除 onboarding 缓存,下次启动将重新显示引导页面',
icon: 'refresh-outline',
onPress: resetOnboardingStatus,
},
]; ];
return ( return (

View File

@@ -6,8 +6,9 @@ import { preloadUserData } from '@/store/userSlice';
import { router } from 'expo-router'; import { router } from 'expo-router';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native'; import { ActivityIndicator, View } from 'react-native';
import AsyncStorage from '@/utils/kvStore';
const ONBOARDING_COMPLETED_KEY = '@onboarding_completed'; import { STORAGE_KEYS } from '@/services/api';
const ONBOARDING_COMPLETED_KEY = STORAGE_KEYS.onboardingCompleted;
export default function SplashScreen() { export default function SplashScreen() {
const backgroundColor = useThemeColor({}, 'background'); const backgroundColor = useThemeColor({}, 'background');
@@ -32,15 +33,13 @@ export default function SplashScreen() {
console.warn('推送通知初始化失败,但不影响应用正常使用:', error); console.warn('推送通知初始化失败,但不影响应用正常使用:', error);
}); });
// const onboardingCompleted = await AsyncStorage.getItem(ONBOARDING_COMPLETED_KEY); const onboardingCompleted = await AsyncStorage.getItem(ONBOARDING_COMPLETED_KEY);
// if (onboardingCompleted === 'true') { if (onboardingCompleted === 'true') {
// router.replace('/(tabs)'); router.replace(ROUTES.TAB_STATISTICS);
// } else { } else {
// router.replace('/onboarding'); router.replace(ROUTES.ONBOARDING);
// } }
// setIsLoading(false);
router.replace(ROUTES.TAB_STATISTICS);
} catch (error) { } catch (error) {
console.error('检查引导状态或预加载用户数据失败:', error); console.error('检查引导状态或预加载用户数据失败:', error);
// 如果出现错误,仍然进入应用,但可能会有状态更新 // 如果出现错误,仍然进入应用,但可能会有状态更新

287
app/onboarding.tsx Normal file
View File

@@ -0,0 +1,287 @@
import { GlassView, isLiquidGlassAvailable } from 'expo-glass-effect';
import { LinearGradient } from 'expo-linear-gradient';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
Animated,
Easing,
FlatList,
Image,
ImageSourcePropType,
NativeScrollEvent,
NativeSyntheticEvent,
Pressable,
StyleSheet,
Text,
TouchableOpacity,
View,
useWindowDimensions,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { palette } from '@/constants/Colors';
import { ROUTES } from '@/constants/Routes';
import { STORAGE_KEYS } from '@/services/api';
import AsyncStorage from '@/utils/kvStore';
const ONBOARDING_COMPLETED_KEY = STORAGE_KEYS.onboardingCompleted;
type OnboardingSlide = {
key: string;
title: string;
description: string;
image: ImageSourcePropType;
};
const SLIDES: OnboardingSlide[] = [
{
key: 'statistics',
title: '全方位健康数据追踪',
description: '实时监测步数、心率、睡眠等多维度健康指标,助你全面了解身体状况。',
image: require('@/assets/images/onboarding/statistic.png'),
},
{
key: 'insights',
title: '科学轻断食计划',
description: '个性化断食方案,智能提醒与进度追踪,助你改善代谢,科学控脂。',
image: require('@/assets/images/onboarding/fasting.jpg'),
},
{
key: 'support',
title: '健康挑战赛',
description: '参与精选健康挑战,与好友一起打卡,保持每日运动动力。',
image: require('@/assets/images/onboarding/challange.jpg'),
},
];
export default function OnboardingScreen() {
const router = useRouter();
const { width } = useWindowDimensions();
const [currentIndex, setCurrentIndex] = useState(0);
const listRef = useRef<FlatList<OnboardingSlide>>(null);
const indicatorAnim = useRef(SLIDES.map((_, index) => new Animated.Value(index === 0 ? 1 : 0))).current;
const glassAvailable = isLiquidGlassAvailable();
useEffect(() => {
indicatorAnim.forEach((anim, index) => {
Animated.timing(anim, {
toValue: index === currentIndex ? 1 : 0,
duration: 250,
easing: Easing.out(Easing.quad),
useNativeDriver: false,
}).start();
});
}, [currentIndex, indicatorAnim]);
const updateIndexFromScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
const offsetX = event.nativeEvent.contentOffset.x;
const nextIndex = Math.round(offsetX / width);
if (!Number.isNaN(nextIndex) && nextIndex !== currentIndex) {
setCurrentIndex(nextIndex);
}
},
[currentIndex, width],
);
const completeOnboarding = useCallback(async () => {
await AsyncStorage.setItem(ONBOARDING_COMPLETED_KEY, 'true');
router.replace(ROUTES.TAB_STATISTICS);
}, [router]);
const handleSkip = useCallback(() => {
completeOnboarding();
}, [completeOnboarding]);
const handleNext = useCallback(() => {
if (currentIndex < SLIDES.length - 1) {
const nextIndex = currentIndex + 1;
listRef.current?.scrollToOffset({ offset: nextIndex * width, animated: true });
setCurrentIndex(nextIndex);
return;
}
completeOnboarding();
}, [completeOnboarding, currentIndex, width]);
const renderSlide = useCallback(
({ item }: { item: OnboardingSlide }) => (
<View style={[styles.slide, { width }]}>
<Image source={item.image} style={styles.slideImage} />
</View>
),
[width],
);
const currentSlide = SLIDES[currentIndex];
return (
<SafeAreaView style={styles.safeArea}>
<StatusBar style="dark" />
<View style={styles.header}>
<Pressable onPress={handleSkip} hitSlop={12}>
<Text style={styles.skipText}></Text>
</Pressable>
</View>
<View style={styles.carouselContainer}>
<FlatList
ref={listRef}
data={SLIDES}
horizontal
keyExtractor={(item) => item.key}
pagingEnabled
decelerationRate="fast"
bounces={false}
showsHorizontalScrollIndicator={false}
renderItem={renderSlide}
onMomentumScrollEnd={updateIndexFromScroll}
/>
</View>
<View style={styles.body}>
<View style={styles.indicatorContainer}>
{SLIDES.map((slide, index) => {
const animatedStyle = {
width: indicatorAnim[index].interpolate({
inputRange: [0, 1],
outputRange: [8, 24],
}),
backgroundColor: indicatorAnim[index].interpolate({
inputRange: [0, 1],
outputRange: ['#D8D8D8', '#0066FF'],
}),
};
return <Animated.View key={slide.key} style={[styles.indicatorDot, animatedStyle]} />;
})}
</View>
<View style={styles.textContainer}>
<Text style={styles.title}>{currentSlide.title}</Text>
<Text style={styles.description}>{currentSlide.description}</Text>
</View>
<TouchableOpacity style={styles.primaryButtonWrapper} onPress={handleNext} activeOpacity={0.9}>
{glassAvailable ? (
<GlassView
style={styles.primaryButtonGlass}
glassEffectStyle="regular"
tintColor="rgba(122, 90, 248, 0.25)"
isInteractive
>
<LinearGradient
colors={[palette.purple[600], palette.purple[400]]}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
style={styles.primaryButtonGradient}
/>
<Text style={styles.primaryButtonText}>
{currentIndex === SLIDES.length - 1 ? '开始使用' : '下一步'}
</Text>
</GlassView>
) : (
<LinearGradient
colors={[palette.purple[600], palette.purple[400]]}
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 1 }}
style={[styles.primaryButtonGlass, styles.primaryButtonFallback]}
>
<Text style={styles.primaryButtonText}>{currentIndex === SLIDES.length - 1 ? '开始使用' : '下一步'}</Text>
</LinearGradient>
)}
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#FFFFFF',
},
header: {
alignItems: 'flex-end',
paddingHorizontal: 24,
paddingTop: 12,
},
skipText: {
fontSize: 16,
color: '#666C7A',
fontWeight: '500',
},
carouselContainer: {
flex: 1,
marginTop: 20,
alignItems: 'center',
justifyContent: 'center',
},
slide: {
height: 'auto',
justifyContent: 'center',
alignItems: 'center',
},
slideImage: {
width: '85%',
height: '100%',
resizeMode: 'cover',
},
body: {
paddingHorizontal: 24,
paddingBottom: 24,
},
indicatorContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginVertical: 24,
gap: 10,
},
indicatorDot: {
height: 8,
borderRadius: 4,
},
textContainer: {
alignItems: 'center',
marginBottom: 32,
},
title: {
fontSize: 24,
color: '#222532',
fontWeight: '700',
textAlign: 'center',
marginBottom: 12,
},
description: {
fontSize: 16,
color: '#5C6373',
textAlign: 'center',
lineHeight: 22,
paddingHorizontal: 8,
},
primaryButtonWrapper: {
marginTop: 16,
},
primaryButtonGlass: {
borderRadius: 24,
paddingVertical: 16,
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
shadowColor: palette.purple[600],
shadowOffset: { width: 0, height: 8 },
shadowOpacity: 0.35,
shadowRadius: 16,
elevation: 6,
},
primaryButtonFallback: {
borderRadius: 24,
},
primaryButtonGradient: {
...StyleSheet.absoluteFillObject,
},
primaryButtonText: {
color: '#FFFFFF',
fontSize: 18,
fontWeight: '600',
},
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

View File

@@ -57,6 +57,9 @@ export const ROUTES = {
// 轻断食相关 // 轻断食相关
FASTING_PLAN_DETAIL: '/fasting', FASTING_PLAN_DETAIL: '/fasting',
// 新用户引导
ONBOARDING: '/onboarding',
// 目标管理路由 (已移至tab中) // 目标管理路由 (已移至tab中)
// GOAL_MANAGEMENT: '/goal-management', // GOAL_MANAGEMENT: '/goal-management',

View File

@@ -5,7 +5,7 @@ import { Alert } from 'react-native';
import { ROUTES } from '@/constants/Routes'; import { ROUTES } from '@/constants/Routes';
import { useAppDispatch, useAppSelector } from '@/hooks/redux'; import { useAppDispatch, useAppSelector } from '@/hooks/redux';
import { api } from '@/services/api'; import { STORAGE_KEYS, api } from '@/services/api';
import { logout as logoutAction } from '@/store/userSlice'; import { logout as logoutAction } from '@/store/userSlice';
type RedirectParams = Record<string, string | number | boolean | undefined>; type RedirectParams = Record<string, string | number | boolean | undefined>;
@@ -99,7 +99,7 @@ export function useAuthGuard() {
await api.delete('/api/users/delete-account'); await api.delete('/api/users/delete-account');
// 清除额外的本地数据 // 清除额外的本地数据
await AsyncStorage.multiRemove(['@user_personal_info', '@onboarding_completed']); await AsyncStorage.multiRemove(['@user_personal_info', STORAGE_KEYS.onboardingCompleted]);
// 执行退出登录逻辑 // 执行退出登录逻辑
await dispatch(logoutAction()).unwrap(); await dispatch(logoutAction()).unwrap();
@@ -149,4 +149,3 @@ export function useAuthGuard() {
} as const; } as const;
} }

View File

@@ -84,6 +84,7 @@ export const STORAGE_KEYS = {
authToken: '@auth_token', authToken: '@auth_token',
userProfile: '@user_profile', userProfile: '@user_profile',
privacyAgreed: '@privacy_agreed', privacyAgreed: '@privacy_agreed',
onboardingCompleted: '@onboarding_completed',
} as const; } as const;
@@ -231,4 +232,3 @@ export async function postTextStream(path: string, body: any, callbacks: TextStr
return { abort, requestId }; return { abort, requestId };
} }