BlueWallet/hooks/useHandoffListener.ios.ts

69 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-11-14 20:42:56 -04:00
import { useEffect, useCallback } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';
import { useStorage } from '../hooks/context/useStorage';
import { useExtendedNavigation } from '../hooks/useExtendedNavigation';
import { HandOffActivityType } from '../components/types';
import { useSettings } from './context/useSettings';
interface UserActivityData {
activityType: HandOffActivityType;
userInfo: {
address?: string;
xpub?: string;
};
}
const EventEmitter = NativeModules.EventEmitter;
const eventEmitter = EventEmitter ? new NativeEventEmitter(EventEmitter) : null;
2024-11-14 20:42:56 -04:00
const useHandoffListener = () => {
const { walletsInitialized } = useStorage();
const { isHandOffUseEnabled } = useSettings();
const { navigate } = useExtendedNavigation();
const handleUserActivity = useCallback(
(data: UserActivityData) => {
2025-01-31 18:49:22 -04:00
if (!data || !data.activityType) {
console.debug(`Invalid handoff data received: ${data ? JSON.stringify(data) : 'No data provided'}`);
return;
}
2024-11-14 20:42:56 -04:00
const { activityType, userInfo } = data;
2025-01-31 18:49:22 -04:00
const modifiedUserInfo = { ...(userInfo || {}), type: activityType };
2024-11-15 19:58:11 -04:00
try {
2025-01-31 18:49:22 -04:00
if (activityType === HandOffActivityType.ReceiveOnchain && modifiedUserInfo.address) {
2024-11-15 19:58:11 -04:00
navigate('ReceiveDetailsRoot', {
screen: 'ReceiveDetails',
2025-01-31 18:49:22 -04:00
params: { address: modifiedUserInfo.address, type: activityType },
2024-11-15 19:58:11 -04:00
});
2025-01-31 18:49:22 -04:00
} else if (activityType === HandOffActivityType.Xpub && modifiedUserInfo.xpub) {
2024-11-15 19:58:11 -04:00
navigate('WalletXpubRoot', {
screen: 'WalletXpub',
2025-01-31 18:49:22 -04:00
params: { xpub: modifiedUserInfo.xpub, type: activityType },
2024-11-15 19:58:11 -04:00
});
} else {
2025-01-31 18:49:22 -04:00
console.debug(`Unhandled or incomplete activity type/data: ${activityType}`, modifiedUserInfo);
2024-11-15 19:58:11 -04:00
}
} catch (error) {
console.error('Error handling user activity:', error);
2024-11-14 20:42:56 -04:00
}
},
[navigate],
);
useEffect(() => {
if (!walletsInitialized || !isHandOffUseEnabled) return;
2024-11-15 19:58:11 -04:00
const activitySubscription = eventEmitter?.addListener('onUserActivityOpen', handleUserActivity);
2024-11-14 20:42:56 -04:00
EventEmitter.getMostRecentUserActivity?.()
.then(handleUserActivity)
2025-01-31 18:49:22 -04:00
.catch(() => console.debug('No valid user activity object received'));
2024-11-14 20:42:56 -04:00
return () => {
2024-11-15 19:58:11 -04:00
activitySubscription?.remove();
2024-11-14 20:42:56 -04:00
};
}, [walletsInitialized, isHandOffUseEnabled, handleUserActivity]);
};
2024-11-15 19:58:11 -04:00
export default useHandoffListener;