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

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;
}
};