feat: 更新应用名称及图标,新增HRV数据管理,优化营养记录展示

This commit is contained in:
richarjiang
2025-08-19 19:13:02 +08:00
parent 260546ff46
commit 35cd320ea7
10 changed files with 643 additions and 564 deletions

View File

@@ -1,10 +1,10 @@
{ {
"expo": { "expo": {
"name": "Health Bot", "name": "Sealife",
"slug": "digital-pilates", "slug": "digital-pilates",
"version": "1.0.4", "version": "1.0.4",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/images/logo.png", "icon": "./assets/images/Sealife.jpeg",
"scheme": "digitalpilates", "scheme": "digitalpilates",
"userInterfaceStyle": "light", "userInterfaceStyle": "light",
"newArchEnabled": true, "newArchEnabled": true,
@@ -21,7 +21,7 @@
}, },
"android": { "android": {
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/images/logo.png", "foregroundImage": "./assets/images/Sealife.jpeg",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"edgeToEdgeEnabled": true, "edgeToEdgeEnabled": true,
@@ -30,14 +30,14 @@
"web": { "web": {
"bundler": "metro", "bundler": "metro",
"output": "static", "output": "static",
"favicon": "./assets/images/logo.png" "favicon": "./assets/images/Sealife.jpeg"
}, },
"plugins": [ "plugins": [
"expo-router", "expo-router",
[ [
"expo-splash-screen", "expo-splash-screen",
{ {
"image": "./assets/images/logo.png", "image": "./assets/images/Sealife.jpeg",
"imageWidth": 200, "imageWidth": 200,
"resizeMode": "contain", "resizeMode": "contain",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"

View File

@@ -172,7 +172,7 @@ export default function CoachScreen() {
const generateWelcomeMessage = useCallback(() => { const generateWelcomeMessage = useCallback(() => {
const hour = new Date().getHours(); const hour = new Date().getHours();
const name = userProfile?.name || '朋友'; const name = userProfile?.name || '朋友';
const botName = (params?.name || 'Health Bot').toString(); const botName = (params?.name || '海豹助手').toString();
// 时段问候 // 时段问候
let timeGreeting = ''; let timeGreeting = '';
@@ -197,7 +197,7 @@ export default function CoachScreen() {
messages: [ messages: [
`${timeGreeting}${name}!我是${botName},你的专属健康管理助手。新的一天开始了,让我们一起为你的健康目标努力吧!`, `${timeGreeting}${name}!我是${botName},你的专属健康管理助手。新的一天开始了,让我们一起为你的健康目标努力吧!`,
`${timeGreeting}!早晨是制定健康计划的最佳时机,我是${botName},可以帮你管理营养摄入、运动计划和生活作息。`, `${timeGreeting}!早晨是制定健康计划的最佳时机,我是${botName},可以帮你管理营养摄入、运动计划和生活作息。`,
`${timeGreeting}${name}!作为你的Health Bot,我很高兴能陪伴你的健康之旅。无论是饮食营养、健身锻炼还是生活管理,我都能为你提供专业建议。` `${timeGreeting}${name}!作为你的海豹助手,我很高兴能陪伴你的健康之旅。无论是饮食营养、健身锻炼还是生活管理,我都能为你提供专业建议。`
] ]
}, },
{ {
@@ -213,7 +213,7 @@ export default function CoachScreen() {
messages: [ messages: [
`${timeGreeting}${name}!午餐时间很关键呢,合理的营养搭配能为下午提供充足能量。我是${botName},可以为你分析饮食营养和热量管理。`, `${timeGreeting}${name}!午餐时间很关键呢,合理的营养搭配能为下午提供充足能量。我是${botName},可以为你分析饮食营养和热量管理。`,
`${timeGreeting}!忙碌的上午结束了,该关注一下身体需求啦。我是你的健康助手${botName},无论是饮食调整、运动安排还是休息建议,都可以找我。`, `${timeGreeting}!忙碌的上午结束了,该关注一下身体需求啦。我是你的健康助手${botName},无论是饮食调整、运动安排还是休息建议,都可以找我。`,
`${timeGreeting}${name}!午间是调整状态的好时机。作为你的Health Bot,我建议关注饮食均衡和适度放松~` `${timeGreeting}${name}!午间是调整状态的好时机。作为你的海豹助手,我建议关注饮食均衡和适度放松~`
] ]
}, },
{ {
@@ -229,7 +229,7 @@ export default function CoachScreen() {
messages: [ messages: [
`${timeGreeting}${name}!忙碌了一天,现在是时候关注身心平衡了。我是${botName},可以为你提供放松建议、营养补充和恢复方案。`, `${timeGreeting}${name}!忙碌了一天,现在是时候关注身心平衡了。我是${botName},可以为你提供放松建议、营养补充和恢复方案。`,
`${timeGreeting}!夜幕降临,这是一天中最适合总结和调整的时刻。我是你的健康伙伴${botName},让我们一起回顾今天的健康表现,规划明天的目标。`, `${timeGreeting}!夜幕降临,这是一天中最适合总结和调整的时刻。我是你的健康伙伴${botName},让我们一起回顾今天的健康表现,规划明天的目标。`,
`${timeGreeting}${name}!晚间时光属于你自己,也是关爱身体的珍贵时间。作为你的Health Bot,我想陪你聊聊如何更好地管理健康生活。` `${timeGreeting}${name}!晚间时光属于你自己,也是关爱身体的珍贵时间。作为你的海豹助手,我想陪你聊聊如何更好地管理健康生活。`
] ]
}, },
{ {
@@ -250,7 +250,7 @@ export default function CoachScreen() {
}, },
{ {
condition: () => userProfile && (!userProfile.pilatesPurposes || userProfile.pilatesPurposes.length === 0), condition: () => userProfile && (!userProfile.pilatesPurposes || userProfile.pilatesPurposes.length === 0),
message: `${timeGreeting}${name}!作为你的Health Bot,我想更好地了解你的健康需求。告诉我你希望在营养摄入、身材管理、健身锻炼或生活管理方面实现什么目标吧~` message: `${timeGreeting}${name}!作为你的海豹助手,我想更好地了解你的健康需求。告诉我你希望在营养摄入、身材管理、健身锻炼或生活管理方面实现什么目标吧~`
} }
]; ];
@@ -1233,7 +1233,7 @@ export default function CoachScreen() {
</TouchableOpacity> </TouchableOpacity>
</View> </View>
<Text style={{ color: '#687076', fontSize: 12 }}>Health Bot会根据您的饮食情况给出专业的营养建</Text> <Text style={{ color: '#687076', fontSize: 12 }}></Text>
</View> </View>
); );
} }
@@ -1275,7 +1275,7 @@ export default function CoachScreen() {
<Text style={{ color: '#192126', fontWeight: '700' }}></Text> <Text style={{ color: '#192126', fontWeight: '700' }}></Text>
</TouchableOpacity> </TouchableOpacity>
<Text style={{ color: '#687076', fontSize: 12 }}>Health Bot给出更精准的营养分析和建</Text> <Text style={{ color: '#687076', fontSize: 12 }}></Text>
</View> </View>
); );
} }

View File

@@ -30,6 +30,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
export default function ExploreScreen() { export default function ExploreScreen() {
const theme = (useColorScheme() ?? 'light') as 'light' | 'dark'; const theme = (useColorScheme() ?? 'light') as 'light' | 'dark';
const colorTokens = Colors[theme]; const colorTokens = Colors[theme];
const stepGoal = useAppSelector((s) => s.user.profile?.dailyStepsGoal) ?? 2000; const stepGoal = useAppSelector((s) => s.user.profile?.dailyStepsGoal) ?? 2000;
const userProfile = useAppSelector((s) => s.user.profile); const userProfile = useAppSelector((s) => s.user.profile);
@@ -68,6 +69,12 @@ export default function ExploreScreen() {
// HealthKit: 每次页面聚焦都拉取今日数据 // HealthKit: 每次页面聚焦都拉取今日数据
const [stepCount, setStepCount] = useState<number | null>(null); const [stepCount, setStepCount] = useState<number | null>(null);
const [activeCalories, setActiveCalories] = useState<number | null>(null); const [activeCalories, setActiveCalories] = useState<number | null>(null);
// 睡眠时长(分钟)
const [sleepDuration, setSleepDuration] = useState<number | null>(null);
// HRV数据
const [hrvValue, setHrvValue] = useState<number>(69);
const [hrvStatus, setHrvStatus] = useState<'放松' | '正常' | '紧张'>('正常');
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
// 用于触发动画重置的 token当日期或数据变化时更新 // 用于触发动画重置的 token当日期或数据变化时更新
const [animToken, setAnimToken] = useState(0); const [animToken, setAnimToken] = useState(0);
@@ -108,6 +115,21 @@ export default function ExploreScreen() {
if (latestRequestKeyRef.current === requestKey) { if (latestRequestKeyRef.current === requestKey) {
setStepCount(data.steps); setStepCount(data.steps);
setActiveCalories(Math.round(data.activeEnergyBurned)); setActiveCalories(Math.round(data.activeEnergyBurned));
setSleepDuration(data.sleepDuration);
// 模拟HRV数据实际应用中应从HealthKit获取
const simulatedHrv = Math.floor(Math.random() * 80) + 30; // 30-110ms范围
setHrvValue(simulatedHrv);
// 根据HRV值判断状态
if (simulatedHrv >= 70) {
setHrvStatus('放松');
} else if (simulatedHrv >= 40) {
setHrvStatus('正常');
} else {
setHrvStatus('紧张');
}
setAnimToken((t) => t + 1); setAnimToken((t) => t + 1);
} else { } else {
console.log('忽略过期健康数据请求结果key=', requestKey, '最新key=', latestRequestKeyRef.current); console.log('忽略过期健康数据请求结果key=', requestKey, '最新key=', latestRequestKeyRef.current);
@@ -187,6 +209,61 @@ export default function ExploreScreen() {
<Text style={styles.sectionTitle}></Text> <Text style={styles.sectionTitle}></Text>
<WeightHistoryCard /> <WeightHistoryCard />
{/* HRV压力监测卡片 */}
<View style={[styles.hrvCard, { backgroundColor: '#F0F7FF' }]}>
<View style={styles.hrvHeader}>
<View style={styles.hrvIconContainer}>
<Ionicons name="heart" size={24} color="#3B82F6" />
</View>
<Text style={styles.hrvTitle}></Text>
</View>
<View style={styles.hrvContent}>
<View style={styles.hrvValueContainer}>
<Text style={styles.hrvValue}>{hrvValue}</Text>
<Text style={styles.hrvUnit}></Text>
</View>
<View style={[styles.hrvStatus,
hrvStatus === '放松' ? { backgroundColor: '#DCFCE7' } :
hrvStatus === '正常' ? { backgroundColor: '#FEF3C7' } :
{ backgroundColor: '#FEE2E2' }
]}>
<Text style={[styles.hrvStatusText,
hrvStatus === '放松' ? { color: '#166534' } :
hrvStatus === '正常' ? { color: '#92400E' } :
{ color: '#991B1B' }
]}>{hrvStatus}</Text>
<Text style={styles.hrvEmoji}>
{hrvStatus === '放松' ? '😌' :
hrvStatus === '正常' ? '😊' :
'😰'}
</Text>
</View>
</View>
<View style={styles.hrvSliderContainer}>
<View style={styles.hrvSliderTrack}>
<View style={[styles.hrvSliderProgress, {
width: `${Math.min(100, Math.max(0, (hrvValue / 150) * 100))}%`,
backgroundColor: hrvStatus === '放松' ? '#10B981' :
hrvStatus === '正常' ? '#F59E0B' : '#EF4444'
}]} />
</View>
<View style={styles.hrvLabels}>
<Text style={styles.hrvLabel}></Text>
<Text style={styles.hrvLabel}></Text>
<Text style={styles.hrvLabel}></Text>
</View>
</View>
</View>
{/* 查看更多 */}
<View style={styles.viewMoreContainer}>
<Text style={styles.viewMoreText}></Text>
<Ionicons name="chevron-forward" size={16} color="#192126" style={styles.viewMoreIcon} />
</View>
{/* 标题与日期选择 */} {/* 标题与日期选择 */}
<Text style={styles.monthTitle}>{monthTitle}</Text> <Text style={styles.monthTitle}>{monthTitle}</Text>
<ScrollView <ScrollView
@@ -549,4 +626,114 @@ const styles = StyleSheet.create({
padding: 4, padding: 4,
marginLeft: 8, marginLeft: 8,
}, },
viewMoreContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 16,
},
viewMoreText: {
fontSize: 14,
color: '#192126',
},
viewMoreIcon: {
fontSize: 16,
color: '#192126',
marginLeft: 4,
},
hrvCard: {
backgroundColor: '#F0F7FF',
borderRadius: 22,
padding: 20,
marginBottom: 16,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.1,
shadowRadius: 8,
elevation: 5,
},
hrvHeader: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 16,
},
hrvIconContainer: {
width: 40,
height: 40,
borderRadius: 12,
backgroundColor: '#DBEAFE',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
},
hrvTitle: {
fontSize: 18,
fontWeight: '800',
color: '#1E293B',
},
hrvContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 20,
},
hrvValueContainer: {
flexDirection: 'row',
alignItems: 'baseline',
},
hrvValue: {
fontSize: 36,
fontWeight: '800',
color: '#1E293B',
marginRight: 4,
},
hrvUnit: {
fontSize: 16,
fontWeight: '600',
color: '#64748B',
},
hrvStatus: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#DCFCE7',
paddingHorizontal: 12,
paddingVertical: 6,
borderRadius: 20,
},
hrvStatusText: {
fontSize: 14,
fontWeight: '600',
color: '#166534',
marginRight: 4,
},
hrvEmoji: {
fontSize: 16,
},
hrvSliderContainer: {
marginTop: 8,
},
hrvSliderTrack: {
height: 8,
backgroundColor: '#E2E8F0',
borderRadius: 4,
marginBottom: 8,
overflow: 'hidden',
},
hrvSliderProgress: {
height: '100%',
backgroundColor: '#3B82F6',
borderRadius: 4,
},
hrvLabels: {
flexDirection: 'row',
justifyContent: 'space-between',
},
hrvLabel: {
fontSize: 12,
fontWeight: '500',
color: '#64748B',
},
}); });

View File

@@ -2,11 +2,9 @@ import { NutritionRecordCard } from '@/components/NutritionRecordCard';
import { HeaderBar } from '@/components/ui/HeaderBar'; import { HeaderBar } from '@/components/ui/HeaderBar';
import { Colors } from '@/constants/Colors'; import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme'; import { useColorScheme } from '@/hooks/useColorScheme';
import { DietRecord } from '@/services/dietRecords'; import { DietRecord, getDietRecords } from '@/services/dietRecords';
import { getMockDietRecords } from '@/services/mockDietRecords';
import { getMonthDaysZh, getMonthTitleZh, getTodayIndexInMonth } from '@/utils/date'; import { getMonthDaysZh, getMonthTitleZh, getTodayIndexInMonth } from '@/utils/date';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
// import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { router } from 'expo-router'; import { router } from 'expo-router';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
@@ -20,15 +18,12 @@ import {
TouchableOpacity, TouchableOpacity,
View View
} from 'react-native'; } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
type ViewMode = 'daily' | 'all'; type ViewMode = 'daily' | 'all';
export default function NutritionRecordsScreen() { export default function NutritionRecordsScreen() {
const theme = (useColorScheme() ?? 'light') as 'light' | 'dark'; const theme = (useColorScheme() ?? 'light') as 'light' | 'dark';
const colorTokens = Colors[theme]; const colorTokens = Colors[theme];
// const tabBarHeight = useBottomTabBarHeight();
const insets = useSafeAreaInsets();
// 日期相关状态 - 使用与统计页面相同的日期逻辑 // 日期相关状态 - 使用与统计页面相同的日期逻辑
const days = getMonthDaysZh(); const days = getMonthDaysZh();
@@ -83,24 +78,11 @@ export default function NutritionRecordsScreen() {
if (viewMode === 'daily') { if (viewMode === 'daily') {
// 按天查看时,获取选中日期的数据 // 按天查看时,获取选中日期的数据
const selectedDate = days[selectedIndex]?.date?.format('YYYY-MM-DD') ?? dayjs().format('YYYY-MM-DD'); startDate = days[selectedIndex]?.date.startOf('day').toISOString();
startDate = selectedDate; endDate = days[selectedIndex]?.date.endOf('day').toISOString();
endDate = selectedDate;
} }
// viewMode === 'all' 时不设置日期范围,获取所有数据
// 使用模拟数据进行测试 const data = await getDietRecords({
// const data = await getDietRecords({
// startDate,
// endDate,
// page: currentPage,
// limit: 10,
// });
// 模拟网络延迟
await new Promise(resolve => setTimeout(resolve, 800));
const data = getMockDietRecords({
startDate, startDate,
endDate, endDate,
page: currentPage, page: currentPage,
@@ -140,7 +122,7 @@ export default function NutritionRecordsScreen() {
// 渲染视图模式切换器 // 渲染视图模式切换器
const renderViewModeToggle = () => ( const renderViewModeToggle = () => (
<View style={[styles.viewModeContainer, { backgroundColor: colorTokens.surface }]}> <View style={[styles.viewModeContainer, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
<Text style={[styles.monthTitle, { color: colorTokens.text }]}>{monthTitle}</Text> <Text style={[styles.monthTitle, { color: colorTokens.text }]}>{monthTitle}</Text>
<View style={[styles.toggleContainer, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}> <View style={[styles.toggleContainer, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
<TouchableOpacity <TouchableOpacity
@@ -253,18 +235,32 @@ export default function NutritionRecordsScreen() {
const renderEmptyState = () => ( const renderEmptyState = () => (
<View style={styles.emptyContainer}> <View style={styles.emptyContainer}>
<Ionicons name="restaurant-outline" size={64} color={colorTokens.textSecondary} /> <View style={styles.emptyTimelineContainer}>
<Text style={[styles.emptyTitle, { color: colorTokens.text }]}> <View style={styles.emptyTimeline}>
{viewMode === 'daily' ? '今天还没有记录' : '暂无营养记录'} <View style={[styles.emptyTimelineDot, { backgroundColor: colorTokens.primary }]}>
</Text> <Ionicons name="add-outline" size={16} color="#FFFFFF" />
<Text style={[styles.emptySubtitle, { color: colorTokens.textSecondary }]}> </View>
{viewMode === 'daily' ? '点击右上角添加今日营养摄入' : '开始记录你的营养摄入吧'} </View>
</Text> <View style={styles.emptyContent}>
<Ionicons name="restaurant-outline" size={48} color={colorTokens.textSecondary} />
<Text style={[styles.emptyTitle, { color: colorTokens.text }]}>
{viewMode === 'daily' ? '今天还没有记录' : '暂无营养记录'}
</Text>
<Text style={[styles.emptySubtitle, { color: colorTokens.textSecondary }]}>
{viewMode === 'daily' ? '开始记录今日营养摄入' : '开始记录你的营养摄入吧'}
</Text>
</View>
</View>
</View> </View>
); );
const renderRecord = ({ item }: { item: DietRecord }) => ( const renderRecord = ({ item, index }: { item: DietRecord; index: number }) => (
<NutritionRecordCard record={item} /> <NutritionRecordCard
record={item}
showTimeline={true}
isFirst={index === 0}
isLast={index === records.length - 1}
/>
); );
const renderFooter = () => { const renderFooter = () => {
@@ -296,17 +292,6 @@ export default function NutritionRecordsScreen() {
<HeaderBar <HeaderBar
title="营养记录" title="营养记录"
onBack={() => router.back()} onBack={() => router.back()}
right={
<TouchableOpacity
style={[styles.addButton, { backgroundColor: colorTokens.primary }]}
onPress={() => {
// TODO: 跳转到添加营养记录页面
console.log('添加营养记录');
}}
>
<Ionicons name="add" size={20} color={colorTokens.onPrimary} />
</TouchableOpacity>
}
/> />
{renderViewModeToggle()} {renderViewModeToggle()}
@@ -322,11 +307,11 @@ export default function NutritionRecordsScreen() {
) : ( ) : (
<FlatList <FlatList
data={records} data={records}
renderItem={renderRecord} renderItem={({ item, index }) => renderRecord({ item, index })}
keyExtractor={(item) => item.id.toString()} keyExtractor={(item) => item.id.toString()}
contentContainerStyle={[ contentContainerStyle={[
styles.listContainer, styles.listContainer,
{ paddingBottom: 40 } { paddingBottom: 40, paddingTop: 16 }
]} ]}
showsVerticalScrollIndicator={false} showsVerticalScrollIndicator={false}
refreshControl={ refreshControl={
@@ -387,8 +372,8 @@ const styles = StyleSheet.create({
paddingVertical: 8, paddingVertical: 8,
}, },
dayPill: { dayPill: {
width: 68, width: 48,
height: 68, height: 48,
borderRadius: 34, borderRadius: 34,
marginRight: 12, marginRight: 12,
alignItems: 'center', alignItems: 'center',
@@ -434,18 +419,47 @@ const styles = StyleSheet.create({
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center', alignItems: 'center',
paddingVertical: 60, paddingVertical: 60,
paddingHorizontal: 16,
},
emptyTimelineContainer: {
flexDirection: 'row',
alignItems: 'center',
maxWidth: 320,
},
emptyTimeline: {
width: 64,
alignItems: 'center',
paddingTop: 8,
},
emptyTimelineDot: {
width: 32,
height: 32,
borderRadius: 16,
justifyContent: 'center',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
elevation: 2,
},
emptyContent: {
flex: 1,
alignItems: 'center',
marginLeft: 16,
}, },
emptyTitle: { emptyTitle: {
fontSize: 20, fontSize: 18,
fontWeight: '700', fontWeight: '700',
marginTop: 16, marginTop: 16,
marginBottom: 8, marginBottom: 8,
textAlign: 'center',
}, },
emptySubtitle: { emptySubtitle: {
fontSize: 16, fontSize: 14,
fontWeight: '500', fontWeight: '500',
textAlign: 'center', textAlign: 'center',
lineHeight: 22, lineHeight: 20,
}, },
footerContainer: { footerContainer: {
paddingVertical: 20, paddingVertical: 20,

BIN
assets/images/Sealife.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 298 KiB

View File

@@ -1,7 +1,6 @@
import { RadarChart } from '@/components/RadarChart';
import { ThemedText } from '@/components/ThemedText'; import { ThemedText } from '@/components/ThemedText';
import { useThemeColor } from '@/hooks/useThemeColor'; import { useThemeColor } from '@/hooks/useThemeColor';
import { DietRecord, calculateNutritionSummary, convertToRadarData } from '@/services/dietRecords'; import { DietRecord } from '@/services/dietRecords';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
@@ -10,17 +9,11 @@ import { Image, StyleSheet, TouchableOpacity, View } from 'react-native';
export type NutritionRecordCardProps = { export type NutritionRecordCardProps = {
record: DietRecord; record: DietRecord;
onPress?: () => void; onPress?: () => void;
showTimeline?: boolean;
isFirst?: boolean;
isLast?: boolean;
}; };
const NUTRITION_DIMENSIONS = [
{ key: 'calories', label: '热量' },
{ key: 'protein', label: '蛋白质' },
{ key: 'carbohydrate', label: '碳水' },
{ key: 'fat', label: '脂肪' },
{ key: 'fiber', label: '纤维' },
{ key: 'sodium', label: '钠' },
];
const MEAL_TYPE_LABELS = { const MEAL_TYPE_LABELS = {
breakfast: '早餐', breakfast: '早餐',
lunch: '午餐', lunch: '午餐',
@@ -45,55 +38,45 @@ const MEAL_TYPE_COLORS = {
other: '#9AA3AE', other: '#9AA3AE',
} as const; } as const;
export function NutritionRecordCard({ record, onPress }: NutritionRecordCardProps) { export function NutritionRecordCard({
record,
onPress,
showTimeline = false,
isFirst = false,
isLast = false
}: NutritionRecordCardProps) {
const surfaceColor = useThemeColor({}, 'surface'); const surfaceColor = useThemeColor({}, 'surface');
const textColor = useThemeColor({}, 'text'); const textColor = useThemeColor({}, 'text');
const textSecondaryColor = useThemeColor({}, 'textSecondary'); const textSecondaryColor = useThemeColor({}, 'textSecondary');
const primaryColor = useThemeColor({}, 'primary'); const primaryColor = useThemeColor({}, 'primary');
// 计算单条记录的营养摘要 // 营养数据统
const nutritionSummary = useMemo(() => {
return calculateNutritionSummary([record]);
}, [record]);
// 计算雷达图数据
const radarValues = useMemo(() => {
return convertToRadarData(nutritionSummary);
}, [nutritionSummary]);
// 营养维度数据
const nutritionStats = useMemo(() => { const nutritionStats = useMemo(() => {
return [ return [
{ {
label: '热量', label: '热量',
value: record.estimatedCalories ? `${Math.round(record.estimatedCalories)} 千卡` : '-', value: record.estimatedCalories ? `${Math.round(record.estimatedCalories)} 千卡` : '-',
icon: 'flame-outline' as const,
color: '#FF6B6B' color: '#FF6B6B'
}, },
{ {
label: '蛋白质', label: '蛋白质',
value: record.proteinGrams ? `${record.proteinGrams.toFixed(1)} g` : '-', value: record.proteinGrams ? `${record.proteinGrams.toFixed(1)} g` : '-',
icon: 'fitness-outline' as const,
color: '#4ECDC4' color: '#4ECDC4'
}, },
{ {
label: '碳水', label: '碳水',
value: record.carbohydrateGrams ? `${record.carbohydrateGrams.toFixed(1)} g` : '-', value: record.carbohydrateGrams ? `${record.carbohydrateGrams.toFixed(1)} g` : '-',
icon: 'leaf-outline' as const,
color: '#45B7D1' color: '#45B7D1'
}, },
{ {
label: '脂肪', label: '脂肪',
value: record.fatGrams ? `${record.fatGrams.toFixed(1)} g` : '-', value: record.fatGrams ? `${record.fatGrams.toFixed(1)} g` : '-',
icon: 'water-outline' as const,
color: '#FFA07A' color: '#FFA07A'
}, },
{
label: '纤维',
value: record.fiberGrams ? `${record.fiberGrams.toFixed(1)} g` : '-',
color: '#98D8C8'
},
{
label: '钠',
value: record.sodiumMg ? `${Math.round(record.sodiumMg)} mg` : '-',
color: '#F7DC6F'
},
]; ];
}, [record]); }, [record]);
@@ -102,170 +85,173 @@ export function NutritionRecordCard({ record, onPress }: NutritionRecordCardProp
const mealTypeLabel = MEAL_TYPE_LABELS[record.mealType]; const mealTypeLabel = MEAL_TYPE_LABELS[record.mealType];
return ( return (
<TouchableOpacity <View style={styles.timelineContainer}>
style={[styles.card, { backgroundColor: surfaceColor }]} {/* 时间轴 */}
onPress={onPress} {showTimeline && (
activeOpacity={0.8} <View style={styles.timelineColumn}>
> <View style={styles.timeContainer}>
{/* 卡片头部 */} <ThemedText style={[styles.timeText, { color: textSecondaryColor }]}>
<View style={styles.cardHeader}> {record.createdAt ? dayjs(record.createdAt).format('HH:mm') : '--:--'}
<View style={styles.mealInfo}>
<View style={[styles.mealTypeIndicator, { backgroundColor: mealTypeColor }]}>
<Ionicons name={mealTypeIcon as any} size={16} color="#FFFFFF" />
</View>
<View style={styles.mealDetails}>
<ThemedText style={[styles.mealType, { color: textColor }]}>
{mealTypeLabel}
</ThemedText>
<ThemedText style={[styles.mealTime, { color: textSecondaryColor }]}>
{record.mealTime ? dayjs(record.mealTime).format('HH:mm') : '时间未设置'}
</ThemedText> </ThemedText>
</View> </View>
</View> <View style={styles.timelineNode}>
<View style={[styles.timelineDot, { backgroundColor: mealTypeColor }]}>
<TouchableOpacity style={styles.moreButton}> <Ionicons name={mealTypeIcon as any} size={12} color="#FFFFFF" />
<Ionicons name="ellipsis-horizontal" size={20} color={textSecondaryColor} />
</TouchableOpacity>
</View>
{/* 食物信息 */}
<View style={styles.foodSection}>
<View style={[styles.foodImageContainer, !record.imageUrl && styles.foodImagePlaceholder]}>
{record.imageUrl ? (
<Image source={{ uri: record.imageUrl }} style={styles.foodImage} />
) : (
<Ionicons name="restaurant" size={24} color={textSecondaryColor} />
)}
</View>
<View style={styles.foodInfo}>
<ThemedText style={[styles.foodName, { color: textColor }]}>
{record.foodName}
</ThemedText>
{record.foodDescription && (
<ThemedText style={[styles.foodDescription, { color: textSecondaryColor }]}>
{record.foodDescription}
</ThemedText>
)}
{(record.weightGrams || record.portionDescription) && (
<ThemedText style={[styles.portionInfo, { color: textSecondaryColor }]}>
{record.weightGrams ? `${record.weightGrams}g` : ''}
{record.weightGrams && record.portionDescription ? ' • ' : ''}
{record.portionDescription || ''}
</ThemedText>
)}
</View>
</View>
{/* 营养分析区域 */}
<View style={styles.nutritionSection}>
<View style={styles.radarContainer}>
<RadarChart
categories={NUTRITION_DIMENSIONS}
values={radarValues}
size="small"
maxValue={5}
showLabels={false}
/>
</View>
<View style={styles.statsContainer}>
{nutritionStats.slice(0, 4).map((stat) => (
<View key={stat.label} style={styles.statItem}>
<View style={[styles.statDot, { backgroundColor: stat.color }]} />
<ThemedText style={[styles.statLabel, { color: textSecondaryColor }]}>
{stat.label}
</ThemedText>
<ThemedText style={[styles.statValue, { color: textColor }]}>
{stat.value}
</ThemedText>
</View> </View>
))} {!isLast && (
</View> <View style={[styles.timelineLine, { backgroundColor: textSecondaryColor }]} />
</View> )}
{/* 额外的营养信息 */}
<View style={styles.additionalStats}>
{nutritionStats.slice(4).map((stat) => (
<View key={stat.label} style={styles.additionalStatItem}>
<View style={[styles.statDot, { backgroundColor: stat.color }]} />
<ThemedText style={[styles.statLabel, { color: textSecondaryColor }]}>
{stat.label}
</ThemedText>
<ThemedText style={[styles.statValue, { color: textColor }]}>
{stat.value}
</ThemedText>
</View> </View>
))}
</View>
{/* 备注信息 */}
{record.notes && (
<View style={styles.notesSection}>
<ThemedText style={[styles.notesLabel, { color: textSecondaryColor }]}>
</ThemedText>
<ThemedText style={[styles.notesText, { color: textColor }]}>
{record.notes}
</ThemedText>
</View> </View>
)} )}
</TouchableOpacity>
{/* 卡片内容 */}
<TouchableOpacity
style={[
styles.card,
{ backgroundColor: surfaceColor },
showTimeline && styles.cardWithTimeline
]}
onPress={onPress}
activeOpacity={0.8}
>
{/* 主要内容区域 */}
<View style={styles.mainContent}>
{/* 左侧:食物图片 */}
<View style={[styles.foodImageContainer, !record.imageUrl && styles.foodImagePlaceholder]}>
{record.imageUrl ? (
<Image source={{ uri: record.imageUrl }} style={styles.foodImage} />
) : (
<Ionicons name="restaurant" size={32} color={textSecondaryColor} />
)}
</View>
{/* 右侧:食物信息 */}
<View style={styles.foodInfoContainer}>
{/* 餐次和操作按钮 */}
<View style={styles.headerRow}>
<View style={styles.mealTypeContainer}>
<View style={[styles.mealTypeBadge, { backgroundColor: `${mealTypeColor}15` }]}>
<ThemedText style={[styles.mealTypeText, { color: mealTypeColor }]}>
{mealTypeLabel}
</ThemedText>
</View>
{!showTimeline && (
<ThemedText style={[styles.mealTime, { color: textSecondaryColor }]}>
{record.mealTime ? dayjs(record.mealTime).format('HH:mm') : '时间未设置'}
</ThemedText>
)}
</View>
<TouchableOpacity style={styles.moreButton}>
<Ionicons name="ellipsis-horizontal" size={20} color={textSecondaryColor} />
</TouchableOpacity>
</View>
{/* 食物名称和分量 */}
<View style={styles.foodNameSection}>
<ThemedText style={[styles.foodName, { color: textColor }]}>
{record.foodName}
</ThemedText>
{(record.weightGrams || record.portionDescription) && (
<ThemedText style={[styles.portionInfo, { color: textSecondaryColor }]}>
{record.portionDescription || `${record.weightGrams}g`}
</ThemedText>
)}
</View>
{/* 营养信息网格 */}
<View style={styles.nutritionGrid}>
{nutritionStats.map((stat) => (
<View key={stat.label} style={styles.nutritionItem}>
<View style={styles.nutritionItemHeader}>
<Ionicons name={stat.icon} size={14} color={stat.color} />
<ThemedText style={[styles.nutritionLabel, { color: textSecondaryColor }]}>
{stat.label}
</ThemedText>
</View>
<ThemedText style={[styles.nutritionValue, { color: textColor }]}>
{stat.value}
</ThemedText>
</View>
))}
</View>
{/* 备注信息 */}
{record.notes && (
<View style={styles.notesSection}>
<ThemedText style={[styles.notesText, { color: textSecondaryColor }]}>
{record.notes}
</ThemedText>
</View>
)}
</View>
</View>
</TouchableOpacity>
</View>
); );
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
card: { timelineContainer: {
borderRadius: 22, flexDirection: 'row',
padding: 20,
marginBottom: 12, marginBottom: 12,
},
timelineColumn: {
width: 64,
alignItems: 'center',
paddingTop: 8,
},
timeContainer: {
marginBottom: 8,
},
timeText: {
fontSize: 12,
fontWeight: '600',
textAlign: 'center',
},
timelineNode: {
alignItems: 'center',
flex: 1,
},
timelineDot: {
width: 24,
height: 24,
borderRadius: 12,
justifyContent: 'center',
alignItems: 'center',
shadowColor: '#000', shadowColor: '#000',
shadowOffset: { width: 0, height: 2 }, shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.08, shadowOpacity: 0.1,
shadowRadius: 6, shadowRadius: 4,
elevation: 3, elevation: 2,
}, },
cardHeader: { timelineLine: {
width: 2,
flex: 1,
marginTop: 8,
opacity: 0.3,
},
card: {
flex: 1,
borderRadius: 16,
padding: 16,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.06,
shadowRadius: 8,
elevation: 2,
},
cardWithTimeline: {
marginLeft: 8,
},
mainContent: {
flexDirection: 'row', flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
},
mealInfo: {
flexDirection: 'row',
alignItems: 'center',
},
mealTypeIndicator: {
width: 36,
height: 36,
borderRadius: 18,
justifyContent: 'center',
alignItems: 'center',
marginRight: 12,
},
mealDetails: {
justifyContent: 'center',
},
mealType: {
fontSize: 16,
fontWeight: '700',
},
mealTime: {
fontSize: 13,
fontWeight: '500',
marginTop: 2,
},
moreButton: {
padding: 4,
},
foodSection: {
flexDirection: 'row',
marginBottom: 20,
}, },
foodImageContainer: { foodImageContainer: {
width: 60, width: 80,
height: 60, height: 80,
borderRadius: 12, borderRadius: 16,
marginRight: 12, marginRight: 16,
overflow: 'hidden', overflow: 'hidden',
}, },
foodImage: { foodImage: {
@@ -273,86 +259,88 @@ const styles = StyleSheet.create({
height: '100%', height: '100%',
}, },
foodImagePlaceholder: { foodImagePlaceholder: {
backgroundColor: '#F5F5F5', backgroundColor: '#F8F9FA',
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center', alignItems: 'center',
}, },
foodInfo: { foodInfoContainer: {
flex: 1, flex: 1,
justifyContent: 'center', },
headerRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: 8,
},
mealTypeContainer: {
flex: 1,
},
mealTypeBadge: {
alignSelf: 'flex-start',
paddingHorizontal: 8,
paddingVertical: 4,
borderRadius: 8,
marginBottom: 4,
},
mealTypeText: {
fontSize: 12,
fontWeight: '600',
},
mealTime: {
fontSize: 11,
fontWeight: '500',
},
moreButton: {
padding: 4,
marginLeft: 8,
},
foodNameSection: {
marginBottom: 12,
}, },
foodName: { foodName: {
fontSize: 18, fontSize: 18,
fontWeight: '700', fontWeight: '700',
marginBottom: 4, lineHeight: 24,
}, marginBottom: 2,
foodDescription: {
fontSize: 14,
fontWeight: '500',
lineHeight: 20,
marginBottom: 4,
}, },
portionInfo: { portionInfo: {
fontSize: 13,
fontWeight: '600',
},
nutritionSection: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 16,
},
radarContainer: {
marginRight: 16,
},
statsContainer: {
flex: 1,
},
statItem: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 12,
},
statDot: {
width: 8,
height: 8,
borderRadius: 4,
marginRight: 8,
},
statLabel: {
fontSize: 13,
fontWeight: '600',
flex: 1,
},
statValue: {
fontSize: 13,
fontWeight: '700',
},
additionalStats: {
flexDirection: 'row',
justifyContent: 'space-between',
marginBottom: 12,
},
additionalStatItem: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
notesSection: {
marginTop: 12,
paddingTop: 16,
borderTopWidth: 1,
borderTopColor: 'rgba(0,0,0,0.08)',
},
notesLabel: {
fontSize: 12,
fontWeight: '600',
marginBottom: 6,
textTransform: 'uppercase',
letterSpacing: 0.5,
},
notesText: {
fontSize: 14, fontSize: 14,
fontWeight: '500', fontWeight: '500',
lineHeight: 20, },
nutritionGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
marginBottom: 8,
},
nutritionItem: {
width: '50%',
marginBottom: 8,
paddingRight: 8,
},
nutritionItemHeader: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 2,
},
nutritionLabel: {
fontSize: 12,
fontWeight: '500',
marginLeft: 4,
},
nutritionValue: {
fontSize: 14,
fontWeight: '700',
},
notesSection: {
marginTop: 8,
paddingTop: 12,
borderTopWidth: 1,
borderTopColor: 'rgba(0,0,0,0.06)',
},
notesText: {
fontSize: 13,
fontWeight: '500',
lineHeight: 18,
fontStyle: 'italic',
}, },
}); });

View File

@@ -330,6 +330,7 @@
"FB_SONARKIT_ENABLED=1", "FB_SONARKIT_ENABLED=1",
); );
INFOPLIST_FILE = digitalpilates/Info.plist; INFOPLIST_FILE = digitalpilates/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Sealife;
IPHONEOS_DEPLOYMENT_TARGET = 15.1; IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = ( LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)", "$(inherited)",
@@ -367,6 +368,7 @@
DEVELOPMENT_TEAM = 756WVXJ6MT; DEVELOPMENT_TEAM = 756WVXJ6MT;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64;
INFOPLIST_FILE = digitalpilates/Info.plist; INFOPLIST_FILE = digitalpilates/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Sealife;
IPHONEOS_DEPLOYMENT_TARGET = 15.1; IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = ( LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)", "$(inherited)",
@@ -447,10 +449,7 @@
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\""; LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = YES; MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
OTHER_LDFLAGS = ( OTHER_LDFLAGS = "$(inherited) ";
"$(inherited)",
" ",
);
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native"; REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos; SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
@@ -505,10 +504,7 @@
); );
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\""; LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
OTHER_LDFLAGS = ( OTHER_LDFLAGS = "$(inherited) ";
"$(inherited)",
" ",
);
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native"; REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos; SDKROOT = iphoneos;
USE_HERMES = false; USE_HERMES = false;

View File

@@ -7,7 +7,7 @@
<key>CFBundleDevelopmentRegion</key> <key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string> <string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key> <key>CFBundleDisplayName</key>
<string>Health Bot</string> <string>Sealife</string>
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string> <string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>

View File

@@ -1,211 +0,0 @@
import dayjs from 'dayjs';
import { DietRecord } from './dietRecords';
// 模拟营养记录数据用于测试UI效果
export const mockDietRecords: DietRecord[] = [
// 今天的记录
{
id: 1,
mealType: 'breakfast',
foodName: '燕麦粥配蓝莓',
foodDescription: '有机燕麦片,新鲜蓝莓,低脂牛奶',
weightGrams: 300,
portionDescription: '1大碗',
estimatedCalories: 280,
proteinGrams: 12.5,
carbohydrateGrams: 45.2,
fatGrams: 6.8,
fiberGrams: 8.5,
sugarGrams: 15.3,
sodiumMg: 120,
source: 'manual',
mealTime: dayjs().hour(7).minute(30).toISOString(),
imageUrl: 'https://images.unsplash.com/photo-1511690743698-d9d85f2fbf38?w=300&h=300&fit=crop',
notes: '营养丰富的早餐,富含膳食纤维和抗氧化物质',
createdAt: dayjs().hour(7).minute(35).toISOString(),
updatedAt: dayjs().hour(7).minute(35).toISOString(),
},
{
id: 2,
mealType: 'lunch',
foodName: '鸡胸肉沙拉',
foodDescription: '烤鸡胸肉,混合蔬菜,橄榄油调味',
weightGrams: 250,
portionDescription: '1份',
estimatedCalories: 320,
proteinGrams: 35.6,
carbohydrateGrams: 8.4,
fatGrams: 15.2,
fiberGrams: 6.2,
sugarGrams: 5.8,
sodiumMg: 480,
source: 'manual',
mealTime: dayjs().hour(12).minute(15).toISOString(),
imageUrl: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=300&h=300&fit=crop',
notes: '高蛋白低碳水,适合健身人群',
createdAt: dayjs().hour(12).minute(20).toISOString(),
updatedAt: dayjs().hour(12).minute(20).toISOString(),
},
{
id: 3,
mealType: 'snack',
foodName: '混合坚果',
foodDescription: '杏仁,核桃,腰果混合装',
weightGrams: 30,
portionDescription: '1小包',
estimatedCalories: 180,
proteinGrams: 6.5,
carbohydrateGrams: 6.8,
fatGrams: 15.5,
fiberGrams: 3.2,
sugarGrams: 2.1,
sodiumMg: 5,
source: 'manual',
mealTime: dayjs().hour(15).minute(30).toISOString(),
notes: '健康的下午茶零食',
createdAt: dayjs().hour(15).minute(35).toISOString(),
updatedAt: dayjs().hour(15).minute(35).toISOString(),
},
{
id: 4,
mealType: 'dinner',
foodName: '三文鱼配蒸蔬菜',
foodDescription: '挪威三文鱼,西兰花,胡萝卜',
weightGrams: 350,
portionDescription: '1份',
estimatedCalories: 420,
proteinGrams: 42.3,
carbohydrateGrams: 12.5,
fatGrams: 22.8,
fiberGrams: 5.6,
sugarGrams: 8.2,
sodiumMg: 380,
source: 'vision',
mealTime: dayjs().hour(19).minute(0).toISOString(),
imageUrl: 'https://images.unsplash.com/photo-1467003909585-2f8a72700288?w=300&h=300&fit=crop',
notes: '富含Omega-3脂肪酸有益心血管健康',
createdAt: dayjs().hour(19).minute(10).toISOString(),
updatedAt: dayjs().hour(19).minute(10).toISOString(),
},
// 昨天的记录
{
id: 5,
mealType: 'breakfast',
foodName: '希腊酸奶杯',
foodDescription: '无糖希腊酸奶,草莓,燕麦片',
weightGrams: 200,
portionDescription: '1杯',
estimatedCalories: 220,
proteinGrams: 20.4,
carbohydrateGrams: 18.6,
fatGrams: 8.2,
fiberGrams: 4.1,
sugarGrams: 12.5,
sodiumMg: 85,
source: 'manual',
mealTime: dayjs().subtract(1, 'day').hour(8).minute(0).toISOString(),
imageUrl: 'https://images.unsplash.com/photo-1488477181946-6428a0291777?w=300&h=300&fit=crop',
notes: '高蛋白早餐,饱腹感强',
createdAt: dayjs().subtract(1, 'day').hour(8).minute(5).toISOString(),
updatedAt: dayjs().subtract(1, 'day').hour(8).minute(5).toISOString(),
},
// 更多历史记录,用于测试分页
{
id: 6,
mealType: 'lunch',
foodName: '牛肉面',
foodDescription: '手拉面条,牛肉汤底,青菜',
weightGrams: 400,
portionDescription: '1碗',
estimatedCalories: 580,
proteinGrams: 28.0,
carbohydrateGrams: 65.0,
fatGrams: 18.5,
fiberGrams: 4.8,
sugarGrams: 6.2,
sodiumMg: 1200,
source: 'manual',
mealTime: dayjs().subtract(2, 'day').hour(13).minute(0).toISOString(),
notes: '传统中式午餐',
createdAt: dayjs().subtract(2, 'day').hour(13).minute(10).toISOString(),
updatedAt: dayjs().subtract(2, 'day').hour(13).minute(10).toISOString(),
},
{
id: 7,
mealType: 'breakfast',
foodName: '全麦吐司配牛油果',
foodDescription: '全麦面包,新鲜牛油果,煎蛋',
weightGrams: 180,
portionDescription: '2片吐司',
estimatedCalories: 350,
proteinGrams: 15.2,
carbohydrateGrams: 28.5,
fatGrams: 22.0,
fiberGrams: 8.0,
sugarGrams: 3.5,
sodiumMg: 220,
source: 'manual',
mealTime: dayjs().subtract(3, 'day').hour(8).minute(30).toISOString(),
imageUrl: 'https://images.unsplash.com/photo-1541519227354-08fa5d50c44d?w=300&h=300&fit=crop',
notes: '健康脂肪和蛋白质的完美组合',
createdAt: dayjs().subtract(3, 'day').hour(8).minute(35).toISOString(),
updatedAt: dayjs().subtract(3, 'day').hour(8).minute(35).toISOString(),
},
{
id: 8,
mealType: 'dinner',
foodName: '蒸蛋羹',
foodDescription: '鸡蛋,温水,少许盐',
weightGrams: 150,
portionDescription: '1小碗',
estimatedCalories: 140,
proteinGrams: 12.0,
carbohydrateGrams: 1.0,
fatGrams: 10.0,
fiberGrams: 0,
sugarGrams: 1.0,
sodiumMg: 180,
source: 'manual',
mealTime: dayjs().subtract(4, 'day').hour(18).minute(45).toISOString(),
notes: '清淡易消化的晚餐',
createdAt: dayjs().subtract(4, 'day').hour(19).minute(0).toISOString(),
updatedAt: dayjs().subtract(4, 'day').hour(19).minute(0).toISOString(),
},
];
// 模拟API响应支持分页和日期过滤
export function getMockDietRecords({
startDate,
endDate,
page = 1,
limit = 10,
}: {
startDate?: string;
endDate?: string;
page?: number;
limit?: number;
} = {}) {
let filteredRecords = mockDietRecords;
// 如果有日期范围,则过滤
if (startDate && endDate) {
filteredRecords = mockDietRecords.filter(record => {
const recordDate = dayjs(record.mealTime).format('YYYY-MM-DD');
return recordDate >= startDate && recordDate <= endDate;
});
}
// 分页
const startIndex = (page - 1) * limit;
const endIndex = startIndex + limit;
const paginatedRecords = filteredRecords.slice(startIndex, endIndex);
return {
records: paginatedRecords,
total: filteredRecords.length,
page,
limit,
};
}

View File

@@ -6,6 +6,8 @@ const PERMISSIONS: HealthKitPermissions = {
read: [ read: [
AppleHealthKit.Constants.Permissions.StepCount, AppleHealthKit.Constants.Permissions.StepCount,
AppleHealthKit.Constants.Permissions.ActiveEnergyBurned, AppleHealthKit.Constants.Permissions.ActiveEnergyBurned,
AppleHealthKit.Constants.Permissions.SleepAnalysis,
AppleHealthKit.Constants.Permissions.HeartRateVariability,
], ],
write: [], write: [],
}, },
@@ -14,6 +16,8 @@ const PERMISSIONS: HealthKitPermissions = {
export type TodayHealthData = { export type TodayHealthData = {
steps: number; steps: number;
activeEnergyBurned: number; // kilocalories activeEnergyBurned: number; // kilocalories
sleepDuration: number; // 睡眠时长(分钟)
hrv: number | null; // 心率变异性 (ms)
}; };
export async function ensureHealthPermissions(): Promise<boolean> { export async function ensureHealthPermissions(): Promise<boolean> {
@@ -46,46 +50,147 @@ export async function fetchHealthDataForDate(date: Date): Promise<TodayHealthDat
const end = new Date(date); const end = new Date(date);
end.setHours(23, 59, 59, 999); end.setHours(23, 59, 59, 999);
const options = { startDate: start.toISOString(), endDate: end.toISOString() } as any; const options = {
startDate: start.toISOString(),
endDate: end.toISOString()
} as any;
console.log('查询选项:', options); console.log('查询选项:', options);
const steps = await new Promise<number>((resolve) => { // 并行获取所有健康数据
AppleHealthKit.getStepCount(options, (err, res) => { const [steps, calories, sleepDuration, hrv] = await Promise.all([
if (err) { // 获取步数
console.error('获取步数失败:', err); new Promise<number>((resolve) => {
return resolve(0); AppleHealthKit.getStepCount(options, (err, res) => {
} if (err) {
if (!res) { console.error('获取步数失败:', err);
console.warn('步数数据为空'); return resolve(0);
return resolve(0); }
} if (!res) {
console.log('步数数据:', res); console.warn('步数数据为空');
resolve(res.value || 0); return resolve(0);
}); }
}); console.log('步数数据:', res);
resolve(res.value || 0);
});
}),
const calories = await new Promise<number>((resolve) => { // 获取消耗卡路里
AppleHealthKit.getActiveEnergyBurned(options, (err, res) => { new Promise<number>((resolve) => {
if (err) { AppleHealthKit.getActiveEnergyBurned(options, (err, res) => {
console.error('获取消耗卡路里失败:', err); if (err) {
return resolve(0); console.error('获取消耗卡路里失败:', err);
} return resolve(0);
if (!res || !Array.isArray(res) || res.length === 0) { }
console.warn('卡路里数据为空或格式错误'); if (!res || !Array.isArray(res) || res.length === 0) {
return resolve(0); console.warn('卡路里数据为空或格式错误');
} return resolve(0);
console.log('卡路里数据:', res); }
// 求和该日内的所有记录(单位:千卡) console.log('卡路里数据:', res);
const total = res.reduce((acc: number, item: any) => acc + (item?.value || 0), 0); // 求和该日内的所有记录(单位:千卡)
resolve(total); const total = res.reduce((acc: number, item: any) => acc + (item?.value || 0), 0);
}); resolve(total);
}); });
}),
console.log('指定日期健康数据获取完成:', { steps, calories }); // 获取睡眠时长
return { steps, activeEnergyBurned: calories }; new Promise<number>((resolve) => {
AppleHealthKit.getSleepSamples(options, (err, res) => {
if (err) {
console.error('获取睡眠数据失败:', err);
return resolve(0);
}
if (!res || !Array.isArray(res) || res.length === 0) {
console.warn('睡眠数据为空或格式错误');
return resolve(0);
}
console.log('睡眠数据:', res);
// 计算总睡眠时间(单位:分钟)
let totalSleepDuration = 0;
res.forEach((sample: any) => {
if (sample && sample.startDate && sample.endDate) {
const startTime = new Date(sample.startDate).getTime();
const endTime = new Date(sample.endDate).getTime();
const durationMinutes = (endTime - startTime) / (1000 * 60);
totalSleepDuration += durationMinutes;
}
});
resolve(totalSleepDuration);
});
}),
// 获取HRV数据
new Promise<number | null>((resolve) => {
AppleHealthKit.getHeartRateVariabilitySamples(options, (err, res) => {
if (err) {
console.error('获取HRV数据失败:', err);
return resolve(null);
}
if (!res || !Array.isArray(res) || res.length === 0) {
console.warn('HRV数据为空或格式错误');
return resolve(null);
}
console.log('HRV数据:', res);
// 获取最新的HRV值
const latestHrv = res[res.length - 1];
if (latestHrv && latestHrv.value) {
resolve(latestHrv.value);
} else {
resolve(null);
}
});
})
]);
console.log('指定日期健康数据获取完成:', { steps, calories, sleepDuration, hrv });
return { steps, activeEnergyBurned: calories, sleepDuration, hrv };
} }
export async function fetchTodayHealthData(): Promise<TodayHealthData> { export async function fetchTodayHealthData(): Promise<TodayHealthData> {
return fetchHealthDataForDate(new Date()); return fetchHealthDataForDate(new Date());
} }
// 新增专门获取HRV数据的函数
export async function fetchHRVForDate(date: Date): Promise<number | null> {
console.log('开始获取指定日期HRV数据...', date);
const start = new Date(date);
start.setHours(0, 0, 0, 0);
const end = new Date(date);
end.setHours(23, 59, 59, 999);
const options = {
startDate: start.toISOString(),
endDate: end.toISOString()
} as any;
return new Promise<number | null>((resolve) => {
AppleHealthKit.getHeartRateVariabilitySamples(options, (err, res) => {
if (err) {
console.error('获取HRV数据失败:', err);
return resolve(null);
}
if (!res || !Array.isArray(res) || res.length === 0) {
console.warn('HRV数据为空或格式错误');
return resolve(null);
}
console.log('HRV数据:', res);
// 获取最新的HRV值
const latestHrv = res[res.length - 1];
if (latestHrv && latestHrv.value) {
resolve(latestHrv.value);
} else {
resolve(null);
}
});
});
}
// 新增获取今日HRV数据
export async function fetchTodayHRV(): Promise<number | null> {
return fetchHRVForDate(new Date());
}