feat: 完善饮水 widget

This commit is contained in:
richarjiang
2025-09-09 14:26:16 +08:00
parent cacfde064f
commit e56ebe3636
13 changed files with 984 additions and 62 deletions

View File

@@ -12,6 +12,8 @@ import {
} from '@/store/waterSlice';
import { Toast } from '@/utils/toast.utils';
import { saveWaterIntakeToHealthKit, deleteWaterIntakeFromHealthKit } from '@/utils/health';
import { syncWaterDataToWidget, refreshWidget } from '@/utils/widgetDataSync';
import { getQuickWaterAmount } from '@/utils/userPreferences';
import dayjs from 'dayjs';
import { useCallback, useEffect, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
@@ -101,6 +103,25 @@ export const useWaterData = () => {
// 重新获取今日统计
dispatch(fetchTodayWaterStats());
// 同步数据到Widget
try {
const newCurrentIntake = (todayStats?.totalAmount || 0) + amount;
const quickAddAmount = await getQuickWaterAmount();
await syncWaterDataToWidget({
currentIntake: newCurrentIntake,
dailyGoal: dailyWaterGoal || 2000,
quickAddAmount,
});
// 刷新Widget
await refreshWidget();
} catch (widgetError) {
console.error('Widget 同步错误:', widgetError);
// Widget 同步失败不影响主要功能
}
return true;
} catch (error: any) {
console.error('添加喝水记录失败:', error);
@@ -200,6 +221,20 @@ export const useWaterData = () => {
const updateWaterGoal = useCallback(async (goal: number) => {
try {
await dispatch(updateWaterGoalAction(goal)).unwrap();
// 同步目标到Widget
try {
const quickAddAmount = await getQuickWaterAmount();
await syncWaterDataToWidget({
dailyGoal: goal,
currentIntake: todayStats?.totalAmount || 0,
quickAddAmount,
});
await refreshWidget();
} catch (widgetError) {
console.error('Widget 目标同步错误:', widgetError);
}
return true;
} catch (error: any) {
console.error('更新喝水目标失败:', error);
@@ -212,7 +247,7 @@ export const useWaterData = () => {
Toast.error(errorMessage);
return false;
}
}, [dispatch]);
}, [dispatch, todayStats]);
// 计算总喝水量
const getTotalAmount = useCallback((records: any[]) => {
@@ -249,6 +284,26 @@ export const useWaterData = () => {
loadTodayData();
}, [loadTodayData]);
// 同步初始数据到Widget
useEffect(() => {
const syncInitialDataToWidget = async () => {
if (todayStats && dailyWaterGoal) {
try {
const quickAddAmount = await getQuickWaterAmount();
await syncWaterDataToWidget({
currentIntake: todayStats.totalAmount,
dailyGoal: dailyWaterGoal,
quickAddAmount,
});
} catch (error) {
console.error('初始Widget数据同步失败:', error);
}
}
};
syncInitialDataToWidget();
}, [todayStats, dailyWaterGoal]);
return {
// 数据
todayStats,