feat: 新增饮水记录功能,支持快速添加饮水量和用户偏好设置

This commit is contained in:
richarjiang
2025-09-02 17:12:38 +08:00
parent 85a3c742df
commit ac748dc339
5 changed files with 612 additions and 210 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -1,8 +1,13 @@
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { useWaterDataByDate } from '@/hooks/useWaterData'; import { useWaterDataByDate } from '@/hooks/useWaterData';
import { getQuickWaterAmount, setQuickWaterAmount } from '@/utils/userPreferences';
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import React, { useState } from 'react'; import { Image } from 'expo-image';
import React, { useEffect, useState } from 'react';
import { import {
Alert,
KeyboardAvoidingView, KeyboardAvoidingView,
Modal, Modal,
Platform, Platform,
@@ -13,6 +18,7 @@ import {
TouchableOpacity, TouchableOpacity,
View, View,
} from 'react-native'; } from 'react-native';
import { Swipeable } from 'react-native-gesture-handler';
interface AddWaterModalProps { interface AddWaterModalProps {
visible: boolean; visible: boolean;
@@ -20,34 +26,22 @@ interface AddWaterModalProps {
selectedDate?: string; // 新增:选中的日期,格式为 YYYY-MM-DD selectedDate?: string; // 新增:选中的日期,格式为 YYYY-MM-DD
} }
interface TabButtonProps {
title: string;
isActive: boolean;
onPress: () => void;
}
const TabButton: React.FC<TabButtonProps> = ({ title, isActive, onPress }) => (
<TouchableOpacity
style={[styles.tabButton, isActive && styles.activeTabButton]}
onPress={onPress}
>
<Text style={[styles.tabButtonText, isActive && styles.activeTabButtonText]}>
{title}
</Text>
</TouchableOpacity>
);
const AddWaterModal: React.FC<AddWaterModalProps> = ({ visible, onClose, selectedDate }) => { const AddWaterModal: React.FC<AddWaterModalProps> = ({ visible, onClose, selectedDate }) => {
const [activeTab, setActiveTab] = useState<'add' | 'goal'>('add'); const theme = (useColorScheme() ?? 'light') as 'light' | 'dark';
const colorTokens = Colors[theme];
const [activeTab, setActiveTab] = useState<'manage' | 'records'>('manage');
const [waterAmount, setWaterAmount] = useState<string>('250'); const [waterAmount, setWaterAmount] = useState<string>('250');
const [note, setNote] = useState<string>(''); const [note, setNote] = useState<string>('');
const [dailyGoal, setDailyGoal] = useState<string>('2000'); const [dailyGoal, setDailyGoal] = useState<string>('2000');
const [quickAddAmount, setQuickAddAmount] = useState<string>('250'); // 快速添加默认值
// 使用新的 hook 来处理指定日期的饮水数据 // 使用新的 hook 来处理指定日期的饮水数据
const { addWaterRecord, updateWaterGoal } = useWaterDataByDate(selectedDate); const { waterRecords, dailyWaterGoal, addWaterRecord, updateWaterGoal, removeWaterRecord } = useWaterDataByDate(selectedDate);
const quickAmounts = [100, 150, 200, 250, 300, 350, 400, 500]; const quickAmounts = [100, 150, 200, 250, 300, 350, 400, 500];
const goalPresets = [1500, 2000, 2500, 3000, 3500, 4000]; const goalPresets = [1500, 2000, 2500, 3000, 3500, 4000];
const quickAddPresets = [100, 150, 200, 250, 300, 350, 400, 500]; // 快速添加默认值选项
const handleAddWater = async () => { const handleAddWater = async () => {
const amount = parseInt(waterAmount); const amount = parseInt(waterAmount);
@@ -75,79 +69,122 @@ const AddWaterModal: React.FC<AddWaterModalProps> = ({ visible, onClose, selecte
} }
}; };
const renderAddRecordTab = () => ( // 处理保存所有设置(饮水目标 + 快速添加默认值)
<View style={styles.tabContent}> const handleSaveSettings = async () => {
<Text style={styles.sectionTitle}> (ml)</Text> const goal = parseInt(dailyGoal);
<TextInput const amount = parseInt(quickAddAmount);
style={styles.input}
value={waterAmount}
onChangeText={setWaterAmount}
keyboardType="numeric"
placeholder="请输入饮水量"
placeholderTextColor="#999"
/>
<Text style={styles.sectionTitle}></Text> let hasError = false;
<ScrollView
horizontal // 验证饮水目标
showsHorizontalScrollIndicator={false} if (goal < 500 || goal > 10000) {
style={styles.quickAmountsContainer} Alert.alert('输入错误', '每日饮水目标应在500ml到10000ml之间');
return;
}
// 验证快速添加默认值
if (amount < 50 || amount > 1000) {
Alert.alert('输入错误', '快速添加默认值应在50ml到1000ml之间');
return;
}
try {
// 保存饮水目标
const goalSuccess = await updateWaterGoal(goal);
if (!goalSuccess) {
hasError = true;
}
// 保存快速添加默认值
await setQuickWaterAmount(amount);
if (!hasError) {
onClose();
}
} catch (error) {
Alert.alert('设置失败', '无法保存设置,请重试');
}
};
// 删除饮水记录
const handleDeleteRecord = async (recordId: string) => {
await removeWaterRecord(recordId);
};
// 加载用户偏好设置和当前饮水目标
useEffect(() => {
const loadUserPreferences = async () => {
try {
const amount = await getQuickWaterAmount();
setQuickAddAmount(amount.toString());
// 设置当前的饮水目标
if (dailyWaterGoal) {
setDailyGoal(dailyWaterGoal.toString());
}
} catch (error) {
console.error('加载用户偏好设置失败:', error);
}
};
if (visible) {
loadUserPreferences();
}
}, [visible, dailyWaterGoal]);
// 渲染Tab切换器 - 参照营养记录页面的实现
const renderTabToggle = () => (
<View style={[styles.tabContainer, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
<TouchableOpacity
style={[
styles.tabButton,
activeTab === 'manage' && { backgroundColor: colorTokens.primary }
]}
onPress={() => setActiveTab('manage')}
> >
<View style={styles.quickAmountsWrapper}> <Text style={[
{quickAmounts.map((amount) => ( styles.tabButtonText,
<TouchableOpacity { color: activeTab === 'manage' ? colorTokens.onPrimary : colorTokens.textSecondary }
key={amount} ]}>
style={[
styles.quickAmountButton, </Text>
parseInt(waterAmount) === amount && styles.quickAmountButtonActive </TouchableOpacity>
]} <TouchableOpacity
onPress={() => setWaterAmount(amount.toString())} style={[
> styles.tabButton,
<Text style={[ activeTab === 'records' && { backgroundColor: colorTokens.primary }
styles.quickAmountText, ]}
parseInt(waterAmount) === amount && styles.quickAmountTextActive onPress={() => setActiveTab('records')}
]}> >
{amount}ml <Text style={[
</Text> styles.tabButtonText,
</TouchableOpacity> { color: activeTab === 'records' ? colorTokens.onPrimary : colorTokens.textSecondary }
))} ]}>
</View>
</ScrollView> </Text>
</TouchableOpacity>
<Text style={styles.sectionTitle}> ()</Text>
<TextInput
style={[styles.input, styles.remarkInput]}
value={note}
onChangeText={setNote}
placeholder="添加备注..."
placeholderTextColor="#999"
multiline
/>
<View style={styles.buttonContainer}>
<TouchableOpacity style={[styles.button, styles.cancelButton]} onPress={onClose}>
<Text style={styles.cancelButtonText}></Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.confirmButton]} onPress={handleAddWater}>
<Text style={styles.confirmButtonText}></Text>
</TouchableOpacity>
</View>
</View> </View>
); );
const renderGoalTab = () => ( // 合并后的管理Tab包含添加记录和设置目标
const renderManageTab = () => (
<View style={styles.tabContent}> <View style={styles.tabContent}>
<Text style={styles.sectionTitle}> (ml)</Text> {/* 设置目标部分 */}
<Text style={[styles.sectionTitle, { color: colorTokens.text }]}> (ml)</Text>
<TextInput <TextInput
style={styles.input} style={[styles.input, {
borderColor: colorTokens.border,
backgroundColor: colorTokens.pageBackgroundEmphasis,
color: colorTokens.text
}]}
value={dailyGoal} value={dailyGoal}
onChangeText={setDailyGoal} onChangeText={setDailyGoal}
keyboardType="numeric" keyboardType="numeric"
placeholder="请输入每日饮水目标" placeholder="请输入每日饮水目标"
placeholderTextColor="#999" placeholderTextColor={colorTokens.textSecondary}
/> />
<Text style={styles.sectionTitle}></Text> <Text style={[styles.sectionTitle, { color: colorTokens.text }]}></Text>
<ScrollView <ScrollView
horizontal horizontal
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
@@ -159,13 +196,20 @@ const AddWaterModal: React.FC<AddWaterModalProps> = ({ visible, onClose, selecte
key={goal} key={goal}
style={[ style={[
styles.quickAmountButton, styles.quickAmountButton,
parseInt(dailyGoal) === goal && styles.quickAmountButtonActive {
borderColor: colorTokens.border,
backgroundColor: colorTokens.pageBackgroundEmphasis
},
parseInt(dailyGoal) === goal && {
backgroundColor: colorTokens.primary,
borderColor: colorTokens.primary
}
]} ]}
onPress={() => setDailyGoal(goal.toString())} onPress={() => setDailyGoal(goal.toString())}
> >
<Text style={[ <Text style={[
styles.quickAmountText, styles.quickAmountText,
parseInt(dailyGoal) === goal && styles.quickAmountTextActive { color: parseInt(dailyGoal) === goal ? colorTokens.onPrimary : colorTokens.textSecondary }
]}> ]}>
{goal}ml {goal}ml
</Text> </Text>
@@ -174,20 +218,195 @@ const AddWaterModal: React.FC<AddWaterModalProps> = ({ visible, onClose, selecte
</View> </View>
</ScrollView> </ScrollView>
{/* 快速添加默认值设置部分 */}
<Text style={[styles.sectionTitle, { color: colorTokens.text, marginTop: 20 }]}> (ml)</Text>
<Text style={[styles.sectionSubtitle, { color: colorTokens.textSecondary, marginBottom: 12 }]}>
"+"
</Text>
<TextInput
style={[styles.input, {
borderColor: colorTokens.border,
backgroundColor: colorTokens.pageBackgroundEmphasis,
color: colorTokens.text
}]}
value={quickAddAmount}
onChangeText={setQuickAddAmount}
keyboardType="numeric"
placeholder="请输入快速添加默认值"
placeholderTextColor={colorTokens.textSecondary}
/>
<Text style={[styles.sectionTitle, { color: colorTokens.text }]}></Text>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
style={styles.quickAmountsContainer}
>
<View style={styles.quickAmountsWrapper}>
{quickAddPresets.map((amount) => (
<TouchableOpacity
key={amount}
style={[
styles.quickAmountButton,
{
borderColor: colorTokens.border,
backgroundColor: colorTokens.pageBackgroundEmphasis
},
parseInt(quickAddAmount) === amount && {
backgroundColor: colorTokens.primary,
borderColor: colorTokens.primary
}
]}
onPress={() => setQuickAddAmount(amount.toString())}
>
<Text style={[
styles.quickAmountText,
{ color: parseInt(quickAddAmount) === amount ? colorTokens.onPrimary : colorTokens.textSecondary }
]}>
{amount}ml
</Text>
</TouchableOpacity>
))}
</View>
</ScrollView>
<View style={styles.buttonContainer}> <View style={styles.buttonContainer}>
<TouchableOpacity style={[styles.button, styles.cancelButton]} onPress={onClose}> <TouchableOpacity
<Text style={styles.cancelButtonText}></Text> style={[styles.button, styles.cancelButton, {
backgroundColor: colorTokens.pageBackgroundEmphasis,
}]}
onPress={onClose}
>
<Text style={[styles.cancelButtonText, { color: colorTokens.textSecondary }]}></Text>
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.confirmButton]} onPress={handleUpdateGoal}> <TouchableOpacity
<Text style={styles.confirmButtonText}></Text> style={[styles.button, styles.confirmButton, { backgroundColor: colorTokens.primary }]}
onPress={handleSaveSettings}
>
<Text style={[styles.confirmButtonText, { color: colorTokens.onPrimary }]}></Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
</View> </View>
); );
// 新增:饮水记录卡片组件
const WaterRecordCard = ({ record, onDelete }: { record: any; onDelete: () => void }) => {
const swipeableRef = React.useRef<Swipeable>(null);
// 处理删除操作
const handleDelete = () => {
Alert.alert(
'确认删除',
'确定要删除这条饮水记录吗?此操作无法撤销。',
[
{
text: '取消',
style: 'cancel',
},
{
text: '删除',
style: 'destructive',
onPress: () => {
onDelete();
swipeableRef.current?.close();
},
},
]
);
};
// 渲染右侧删除按钮
const renderRightActions = () => {
return (
<TouchableOpacity
style={styles.deleteSwipeButton}
onPress={handleDelete}
activeOpacity={0.8}
>
<Ionicons name="trash" size={20} color="#FFFFFF" />
<Text style={styles.deleteSwipeButtonText}></Text>
</TouchableOpacity>
);
};
return (
<View style={styles.recordCardContainer}>
<Swipeable
ref={swipeableRef}
renderRightActions={renderRightActions}
rightThreshold={40}
overshootRight={false}
>
<View style={[styles.recordCard, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
<View style={styles.recordMainContent}>
<View style={[styles.recordIconContainer, { backgroundColor: colorTokens.background }]}>
<Image
source={require('@/assets/images/icons/IconGlass.png')}
style={styles.recordIcon}
/>
</View>
<View style={styles.recordInfo}>
<Text style={[styles.recordLabel, { color: colorTokens.text }]}></Text>
<View style={styles.recordTimeContainer}>
<Ionicons name="time-outline" size={14} color={colorTokens.textSecondary} />
<Text style={[styles.recordTimeText, { color: colorTokens.textSecondary }]}>
{dayjs(record.recordedAt || record.createdAt).format('HH:mm')}
</Text>
</View>
</View>
<View style={styles.recordAmountContainer}>
<Text style={[styles.recordAmount, { color: colorTokens.text }]}>{record.amount}ml</Text>
</View>
</View>
{record.note && (
<Text style={[styles.recordNote, { color: colorTokens.textSecondary }]}>{record.note}</Text>
)}
</View>
</Swipeable>
</View>
);
};
// 新增饮水记录Tab内容
const renderRecordsTab = () => (
<View style={styles.tabContent}>
<Text style={[styles.sectionTitle, { color: colorTokens.text }]}>
{selectedDate ? dayjs(selectedDate).format('MM月DD日') : '今日'}
</Text>
{waterRecords && waterRecords.length > 0 ? (
<View style={styles.recordsList}>
{waterRecords.map((record) => (
<WaterRecordCard
key={record.id}
record={record}
onDelete={() => handleDeleteRecord(record.id)}
/>
))}
{/* 总计显示 */}
<View style={[styles.recordsSummary, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
<Text style={[styles.summaryText, { color: colorTokens.text }]}>
{waterRecords.reduce((sum, record) => sum + record.amount, 0)}ml
</Text>
<Text style={[styles.summaryGoal, { color: colorTokens.textSecondary }]}>
{dailyWaterGoal}ml
</Text>
</View>
</View>
) : (
<View style={styles.noRecordsContainer}>
<Ionicons name="water-outline" size={48} color={colorTokens.textSecondary} />
<Text style={[styles.noRecordsText, { color: colorTokens.textSecondary }]}></Text>
<Text style={[styles.noRecordsSubText, { color: colorTokens.textSecondary }]}>"添加记录"</Text>
</View>
)}
</View>
);
return ( return (
<Modal <Modal
animationType="slide" animationType="fade"
transparent={true} transparent={true}
visible={visible} visible={visible}
onRequestClose={onClose} onRequestClose={onClose}
@@ -196,29 +415,18 @@ const AddWaterModal: React.FC<AddWaterModalProps> = ({ visible, onClose, selecte
style={styles.centeredView} style={styles.centeredView}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
> >
<View style={styles.modalView}> <View style={[styles.modalView, { backgroundColor: colorTokens.background }]}>
<View style={styles.header}> <View style={styles.header}>
<Text style={styles.modalTitle}></Text> <Text style={[styles.modalTitle, { color: colorTokens.text }]}></Text>
<TouchableOpacity style={styles.closeButton} onPress={onClose}> <TouchableOpacity style={styles.closeButton} onPress={onClose}>
<Ionicons name="close" size={24} color="#666" /> <Ionicons name="close" size={18} color={colorTokens.textSecondary} />
</TouchableOpacity> </TouchableOpacity>
</View> </View>
<View style={styles.tabContainer}> {renderTabToggle()}
<TabButton
title="添加记录"
isActive={activeTab === 'add'}
onPress={() => setActiveTab('add')}
/>
<TabButton
title="设置目标"
isActive={activeTab === 'goal'}
onPress={() => setActiveTab('goal')}
/>
</View>
<ScrollView style={styles.contentScrollView}> <ScrollView style={styles.contentScrollView}>
{activeTab === 'add' ? renderAddRecordTab() : renderGoalTab()} {activeTab === 'manage' ? renderManageTab() : renderRecordsTab()}
</ScrollView> </ScrollView>
</View> </View>
</KeyboardAvoidingView> </KeyboardAvoidingView>
@@ -235,19 +443,20 @@ const styles = StyleSheet.create({
}, },
modalView: { modalView: {
width: '90%', width: '90%',
maxWidth: 350, maxWidth: 400,
maxHeight: '80%', height: 650, // 固定高度
backgroundColor: 'white', borderRadius: 24,
borderRadius: 20, paddingTop: 24,
padding: 20, paddingHorizontal: 20,
shadowColor: '#000', paddingBottom: 20,
shadowColor: '#000000',
shadowOffset: { shadowOffset: {
width: 0, width: 0,
height: 2, height: 8,
}, },
shadowOpacity: 0.25, shadowOpacity: 0.12,
shadowRadius: 4, shadowRadius: 20,
elevation: 5, elevation: 8,
}, },
header: { header: {
flexDirection: 'row', flexDirection: 'row',
@@ -256,59 +465,55 @@ const styles = StyleSheet.create({
marginBottom: 20, marginBottom: 20,
}, },
modalTitle: { modalTitle: {
fontSize: 20, fontSize: 16,
fontWeight: 'bold', fontWeight: '600',
color: '#333', letterSpacing: -0.5,
}, },
closeButton: { closeButton: {
padding: 5, padding: 5,
}, },
tabContainer: { tabContainer: {
flexDirection: 'row', flexDirection: 'row',
marginBottom: 20, borderRadius: 20,
borderRadius: 10, padding: 2,
backgroundColor: '#f5f5f5', marginBottom: 24,
padding: 4,
}, },
tabButton: { tabButton: {
flex: 1, paddingHorizontal: 16,
paddingVertical: 10, paddingVertical: 8,
borderRadius: 18,
minWidth: 80,
alignItems: 'center', alignItems: 'center',
borderRadius: 8, flex: 1,
},
activeTabButton: {
backgroundColor: '#007AFF',
}, },
tabButtonText: { tabButtonText: {
fontSize: 14, fontSize: 14,
color: '#666',
fontWeight: '500',
},
activeTabButtonText: {
color: 'white',
fontWeight: '600', fontWeight: '600',
}, },
contentScrollView: { contentScrollView: {
maxHeight: 400, flex: 1,
}, },
tabContent: { tabContent: {
paddingVertical: 10, paddingVertical: 10,
}, },
sectionTitle: { sectionTitle: {
fontSize: 16, fontSize: 14,
fontWeight: '600', fontWeight: '500',
color: '#333', marginBottom: 12,
marginBottom: 10, letterSpacing: -0.3,
},
sectionSubtitle: {
fontSize: 14,
fontWeight: '400',
lineHeight: 18,
}, },
input: { input: {
borderWidth: 1, borderRadius: 12,
borderColor: '#e0e0e0', paddingHorizontal: 16,
borderRadius: 10, paddingVertical: 14,
paddingHorizontal: 15,
paddingVertical: 12,
fontSize: 16, fontSize: 16,
color: '#333', fontWeight: '500',
marginBottom: 15, marginBottom: 16,
}, },
remarkInput: { remarkInput: {
height: 80, height: 80,
@@ -324,27 +529,20 @@ const styles = StyleSheet.create({
}, },
quickAmountButton: { quickAmountButton: {
paddingHorizontal: 20, paddingHorizontal: 20,
paddingVertical: 10, paddingVertical: 8,
borderRadius: 20, borderRadius: 20,
borderWidth: 1, minWidth: 70,
borderColor: '#e0e0e0',
backgroundColor: '#f9f9f9',
minWidth: 60,
alignItems: 'center', alignItems: 'center',
}, shadowColor: '#000',
quickAmountButtonActive: { shadowOffset: { width: 0, height: 1 },
backgroundColor: '#007AFF', shadowOpacity: 0.05,
borderColor: '#007AFF', shadowRadius: 2,
elevation: 1,
}, },
quickAmountText: { quickAmountText: {
fontSize: 14, fontSize: 15,
color: '#666',
fontWeight: '500', fontWeight: '500',
}, },
quickAmountTextActive: {
color: 'white',
fontWeight: '600',
},
buttonContainer: { buttonContainer: {
flexDirection: 'row', flexDirection: 'row',
gap: 10, gap: 10,
@@ -352,25 +550,134 @@ const styles = StyleSheet.create({
}, },
button: { button: {
flex: 1, flex: 1,
paddingVertical: 12, paddingVertical: 14,
borderRadius: 10, borderRadius: 12,
alignItems: 'center', alignItems: 'center',
}, },
cancelButton: { cancelButton: {
backgroundColor: '#f5f5f5',
}, },
confirmButton: { confirmButton: {
backgroundColor: '#007AFF', shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 3,
}, },
cancelButtonText: { cancelButtonText: {
fontSize: 16, fontSize: 16,
color: '#666', fontWeight: '600',
fontWeight: '500',
}, },
confirmButtonText: { confirmButtonText: {
fontSize: 16, fontSize: 16,
color: 'white', fontWeight: '700',
},
// 饮水记录相关样式
recordsList: {
gap: 12,
},
recordCardContainer: {
// iOS 阴影效果
shadowColor: '#000000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.08,
shadowRadius: 4,
// Android 阴影效果
elevation: 2,
},
recordCard: {
borderRadius: 12,
padding: 10,
},
recordMainContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
recordIconContainer: {
width: 40,
height: 40,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
},
recordIcon: {
width: 20,
height: 20,
},
recordInfo: {
flex: 1,
marginLeft: 12,
},
recordLabel: {
fontSize: 16,
fontWeight: '600', fontWeight: '600',
marginBottom: 8,
},
recordTimeContainer: {
flexDirection: 'row',
alignItems: 'center',
gap: 4,
},
recordAmountContainer: {
alignItems: 'flex-end',
},
recordAmount: {
fontSize: 14,
fontWeight: '500',
},
deleteSwipeButton: {
backgroundColor: '#EF4444',
justifyContent: 'center',
alignItems: 'center',
width: 80,
borderRadius: 12,
marginLeft: 8,
},
deleteSwipeButtonText: {
color: '#FFFFFF',
fontSize: 12,
fontWeight: '600',
marginTop: 4,
},
recordTimeText: {
fontSize: 12,
fontWeight: '400',
},
recordNote: {
marginTop: 8,
fontSize: 14,
fontStyle: 'italic',
lineHeight: 20,
},
recordsSummary: {
marginTop: 20,
padding: 16,
borderRadius: 12,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
summaryText: {
fontSize: 12,
fontWeight: '500',
},
summaryGoal: {
fontSize: 12,
fontWeight: '500',
},
noRecordsContainer: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 40,
gap: 12,
},
noRecordsText: {
fontSize: 16,
fontWeight: '600',
},
noRecordsSubText: {
fontSize: 14,
textAlign: 'center',
}, },
}); });

View File

@@ -18,15 +18,26 @@ export function AnimatedNumber({
resetToken, resetToken,
}: AnimatedNumberProps) { }: AnimatedNumberProps) {
const opacity = useRef(new Animated.Value(1)).current; const opacity = useRef(new Animated.Value(1)).current;
const [display, setDisplay] = useState<string>('0'); const [display, setDisplay] = useState<string>(() =>
const [currentValue, setCurrentValue] = useState(0); format ? format(value) : `${Math.round(value)}`
);
const [currentValue, setCurrentValue] = useState(value);
const [lastResetToken, setLastResetToken] = useState(resetToken);
const [isAnimating, setIsAnimating] = useState(false);
useEffect(() => { useEffect(() => {
// 如果值没有变化,不执行动画 // 检查是否需要触发动画
if (value === currentValue && resetToken === undefined) { const valueChanged = value !== currentValue;
const resetTokenChanged = resetToken !== lastResetToken;
// 如果值没有变化且resetToken也没有变化或者正在动画中则不执行新动画
if ((!valueChanged && !resetTokenChanged) || isAnimating) {
return; return;
} }
// 标记开始动画
setIsAnimating(true);
// 停止当前动画 // 停止当前动画
opacity.stopAnimation(() => { opacity.stopAnimation(() => {
// 创建优雅的透明度变化动画 // 创建优雅的透明度变化动画
@@ -48,22 +59,17 @@ export function AnimatedNumber({
fadeOut.start(() => { fadeOut.start(() => {
// 更新当前值和显示 // 更新当前值和显示
setCurrentValue(value); setCurrentValue(value);
setLastResetToken(resetToken);
setDisplay(format ? format(value) : `${Math.round(value)}`); setDisplay(format ? format(value) : `${Math.round(value)}`);
// 然后淡入新数字 // 然后淡入新数字
fadeIn.start(); fadeIn.start(() => {
// 动画完成,标记结束
setIsAnimating(false);
});
}); });
}); });
// eslint-disable-next-line react-hooks/exhaustive-deps }, [value, resetToken, currentValue, lastResetToken, isAnimating, durationMs, format]);
}, [value, resetToken]);
// 初始化显示值
useEffect(() => {
if (currentValue !== value) {
setCurrentValue(value);
setDisplay(format ? format(value) : `${Math.round(value)}`);
}
}, [value, format, currentValue]);
return ( return (
<Animated.Text <Animated.Text

View File

@@ -1,4 +1,5 @@
import { useWaterDataByDate } from '@/hooks/useWaterData'; import { useWaterDataByDate } from '@/hooks/useWaterData';
import { getQuickWaterAmount } from '@/utils/userPreferences';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import React, { useEffect, useMemo, useState } from 'react'; import React, { useEffect, useMemo, useState } from 'react';
import { import {
@@ -10,6 +11,7 @@ import {
ViewStyle ViewStyle
} from 'react-native'; } from 'react-native';
import AddWaterModal from './AddWaterModal'; import AddWaterModal from './AddWaterModal';
import { AnimatedNumber } from './AnimatedNumber';
interface WaterIntakeCardProps { interface WaterIntakeCardProps {
style?: ViewStyle; style?: ViewStyle;
@@ -22,6 +24,7 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
}) => { }) => {
const { waterStats, dailyWaterGoal, waterRecords, addWaterRecord } = useWaterDataByDate(selectedDate); const { waterStats, dailyWaterGoal, waterRecords, addWaterRecord } = useWaterDataByDate(selectedDate);
const [isModalVisible, setIsModalVisible] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false);
const [quickWaterAmount, setQuickWaterAmount] = useState(150); // 默认值,将从用户偏好中加载
// 计算当前饮水量和目标 // 计算当前饮水量和目标
const currentIntake = waterStats?.totalAmount || 0; const currentIntake = waterStats?.totalAmount || 0;
@@ -64,9 +67,23 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
})); }));
}, [waterRecords]); }, [waterRecords]);
// 获取当前小时 - 只有当选中的是今天时才显示当前小时 // 判断是否是今天
const isToday = selectedDate === dayjs().format('YYYY-MM-DD') || !selectedDate; const isToday = selectedDate === dayjs().format('YYYY-MM-DD') || !selectedDate;
const currentHour = isToday ? new Date().getHours() : -1; // 如果不是今天,设为-1表示没有当前小时
// 加载用户偏好的快速添加饮水默认值
useEffect(() => {
const loadQuickWaterAmount = async () => {
try {
const amount = await getQuickWaterAmount();
setQuickWaterAmount(amount);
} catch (error) {
console.error('加载快速添加饮水默认值失败:', error);
// 保持默认值 250ml
}
};
loadQuickWaterAmount();
}, []);
// 触发柱体动画 // 触发柱体动画
useEffect(() => { useEffect(() => {
@@ -96,8 +113,8 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
// 处理添加喝水 - 右上角按钮直接添加 // 处理添加喝水 - 右上角按钮直接添加
const handleQuickAddWater = async () => { const handleQuickAddWater = async () => {
// 默认添加250ml水 // 使用用户配置的快速添加饮水量
const waterAmount = 250; const waterAmount = quickWaterAmount;
// 如果有选中日期,则为该日期添加记录;否则为今天添加记录 // 如果有选中日期,则为该日期添加记录;否则为今天添加记录
const recordedAt = selectedDate ? dayjs(selectedDate).toISOString() : dayjs().toISOString(); const recordedAt = selectedDate ? dayjs(selectedDate).toISOString() : dayjs().toISOString();
await addWaterRecord(waterAmount, recordedAt); await addWaterRecord(waterAmount, recordedAt);
@@ -109,8 +126,16 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
}; };
// 处理关闭弹窗 // 处理关闭弹窗
const handleCloseModal = () => { const handleCloseModal = async () => {
setIsModalVisible(false); setIsModalVisible(false);
// 弹窗关闭后重新加载快速添加默认值,以防用户修改了设置
try {
const amount = await getQuickWaterAmount();
setQuickWaterAmount(amount);
} catch (error) {
console.error('刷新快速添加默认值失败:', error);
}
}; };
return ( return (
@@ -123,9 +148,11 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
{/* 标题和加号按钮 */} {/* 标题和加号按钮 */}
<View style={styles.header}> <View style={styles.header}>
<Text style={styles.title}></Text> <Text style={styles.title}></Text>
<TouchableOpacity style={styles.addButton} onPress={handleQuickAddWater}> {isToday && (
<Text style={styles.addButtonText}>+</Text> <TouchableOpacity style={styles.addButton} onPress={handleQuickAddWater}>
</TouchableOpacity> <Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
)}
</View> </View>
{/* 柱状图 */} {/* 柱状图 */}
@@ -133,9 +160,8 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
<View style={styles.chartWrapper}> <View style={styles.chartWrapper}>
<View style={styles.chartArea}> <View style={styles.chartArea}>
{chartData.map((data, index) => { {chartData.map((data, index) => {
// 判断是否是当前小时或者有活动的小时 // 判断是否有活动的小时
const isActive = data.amount > 0; const isActive = data.amount > 0;
const isCurrent = isToday && index <= currentHour;
// 动画变换高度从0到目标高度 // 动画变换高度从0到目标高度
const animatedHeight = animatedValues[index].interpolate({ const animatedHeight = animatedValues[index].interpolate({
@@ -184,22 +210,21 @@ const WaterIntakeCard: React.FC<WaterIntakeCardProps> = ({
{/* 饮水量显示 */} {/* 饮水量显示 */}
<View style={styles.statsContainer}> <View style={styles.statsContainer}>
<Text style={styles.currentIntake}> {currentIntake !== null ? (
{currentIntake !== null ? `${currentIntake}ml` : '——'} <AnimatedNumber
</Text> value={currentIntake}
style={styles.currentIntake}
format={(value) => `${Math.round(value)}ml`}
resetToken={selectedDate}
/>
) : (
<Text style={styles.currentIntake}></Text>
)}
<Text style={styles.targetIntake}> <Text style={styles.targetIntake}>
/ {targetIntake}ml / {targetIntake}ml
</Text> </Text>
</View> </View>
{/* 完成率显示 */}
{waterStats && (
<View style={styles.completionContainer}>
<Text style={styles.completionText}>
{Math.round(waterStats.completionRate)}%
</Text>
</View>
)}
</TouchableOpacity> </TouchableOpacity>
{/* 配置饮水弹窗 */} {/* 配置饮水弹窗 */}
@@ -233,6 +258,7 @@ const styles = StyleSheet.create({
justifyContent: 'space-between', justifyContent: 'space-between',
alignItems: 'center', alignItems: 'center',
marginBottom: 4, marginBottom: 4,
minHeight: 22,
}, },
title: { title: {
fontSize: 14, fontSize: 14,
@@ -298,15 +324,6 @@ const styles = StyleSheet.create({
color: '#6B7280', color: '#6B7280',
marginLeft: 4, marginLeft: 4,
}, },
completionContainer: {
alignItems: 'flex-start',
marginTop: 2,
},
completionText: {
fontSize: 12,
color: '#10B981',
fontWeight: '500',
},
}); });
export default WaterIntakeCard; export default WaterIntakeCard;

72
utils/userPreferences.ts Normal file
View File

@@ -0,0 +1,72 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
// 用户偏好设置的存储键
const PREFERENCES_KEYS = {
QUICK_WATER_AMOUNT: 'user_preference_quick_water_amount',
} as const;
// 用户偏好设置接口
export interface UserPreferences {
quickWaterAmount: number;
}
// 默认的用户偏好设置
const DEFAULT_PREFERENCES: UserPreferences = {
quickWaterAmount: 150, // 默认快速添加饮水量为 250ml
};
/**
* 获取用户偏好设置
*/
export const getUserPreferences = async (): Promise<UserPreferences> => {
try {
const quickWaterAmount = await AsyncStorage.getItem(PREFERENCES_KEYS.QUICK_WATER_AMOUNT);
return {
quickWaterAmount: quickWaterAmount ? parseInt(quickWaterAmount, 10) : DEFAULT_PREFERENCES.quickWaterAmount,
};
} catch (error) {
console.error('获取用户偏好设置失败:', error);
return DEFAULT_PREFERENCES;
}
};
/**
* 设置快速添加饮水的默认值
* @param amount 饮水量(毫升)
*/
export const setQuickWaterAmount = async (amount: number): Promise<void> => {
try {
// 确保值在合理范围内50ml - 1000ml
const validAmount = Math.max(50, Math.min(1000, amount));
await AsyncStorage.setItem(PREFERENCES_KEYS.QUICK_WATER_AMOUNT, validAmount.toString());
} catch (error) {
console.error('设置快速添加饮水默认值失败:', error);
throw error;
}
};
/**
* 获取快速添加饮水的默认值
*/
export const getQuickWaterAmount = async (): Promise<number> => {
try {
const amount = await AsyncStorage.getItem(PREFERENCES_KEYS.QUICK_WATER_AMOUNT);
return amount ? parseInt(amount, 10) : DEFAULT_PREFERENCES.quickWaterAmount;
} catch (error) {
console.error('获取快速添加饮水默认值失败:', error);
return DEFAULT_PREFERENCES.quickWaterAmount;
}
};
/**
* 重置所有用户偏好设置为默认值
*/
export const resetUserPreferences = async (): Promise<void> => {
try {
await AsyncStorage.removeItem(PREFERENCES_KEYS.QUICK_WATER_AMOUNT);
} catch (error) {
console.error('重置用户偏好设置失败:', error);
throw error;
}
};