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

@@ -0,0 +1,101 @@
import { NativeModules, NativeEventEmitter, EmitterSubscription } from 'react-native';
import { createWaterRecordAction } from '@/store/waterSlice';
import { store } from '@/store';
import { WaterRecordSource } from './waterRecords';
// Native Module 接口定义
interface WaterRecordManagerInterface {
addWaterRecord(amount: number): Promise<{
success: boolean;
amount: number;
newTotal: number;
}>;
}
// 获取原生模块
const WaterRecordManager: WaterRecordManagerInterface = NativeModules.WaterRecordManager;
// 创建事件发射器
const waterRecordEventEmitter = NativeModules.WaterRecordManager
? new NativeEventEmitter(NativeModules.WaterRecordManager)
: null;
// 事件监听器引用
let eventSubscription: EmitterSubscription | null = null;
// 事件数据接口
interface WaterRecordEventData {
amount: number;
recordedAt: string;
source: string;
}
// 初始化事件监听器
export function initializeWaterRecordBridge(): void {
if (!waterRecordEventEmitter) {
console.warn('WaterRecordManager 原生模块不可用,跳过事件监听器初始化');
return;
}
if (eventSubscription) {
// 如果已经初始化,先清理
eventSubscription.remove();
}
// 监听来自原生模块的事件
eventSubscription = waterRecordEventEmitter.addListener(
'WaterRecordAdded',
(eventData: WaterRecordEventData) => {
console.log('收到来自 Swift 的喝水记录事件:', eventData);
// 通过 Redux 创建喝水记录
store.dispatch(createWaterRecordAction({
amount: eventData.amount,
recordedAt: eventData.recordedAt,
source: WaterRecordSource.Auto, // 标记为自动添加
}));
}
);
console.log('WaterRecordBridge 初始化完成');
}
// 清理事件监听器
export function cleanupWaterRecordBridge(): void {
if (eventSubscription) {
eventSubscription.remove();
eventSubscription = null;
}
}
// 供原生代码调用的添加喝水记录方法
export async function addWaterRecordFromNative(amount: number): Promise<{
success: boolean;
amount: number;
newTotal: number;
}> {
try {
if (!WaterRecordManager) {
throw new Error('WaterRecordManager 原生模块不可用');
}
const result = await WaterRecordManager.addWaterRecord(amount);
console.log('通过 Bridge 添加喝水记录成功:', result);
return result;
} catch (error) {
console.error('通过 Bridge 添加喝水记录失败:', error);
throw error;
}
}
// 检查原生模块是否可用
export function isWaterRecordBridgeAvailable(): boolean {
return WaterRecordManager && typeof WaterRecordManager.addWaterRecord === 'function';
}
export default {
initializeWaterRecordBridge,
cleanupWaterRecordBridge,
addWaterRecordFromNative,
isWaterRecordBridgeAvailable,
};