Merge pull request #6622 from BlueWallet/walletslistcallback

REF: WalletsList useCallback
This commit is contained in:
GLaDOS 2024-05-27 19:50:28 +00:00 committed by GitHub
commit e3c1240a77
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -151,69 +151,75 @@ const WalletsList: React.FC = () => {
walletsCount.current = wallets.length; walletsCount.current = wallets.length;
}, [wallets]); }, [wallets]);
const verifyBalance = () => { const verifyBalance = useCallback(() => {
if (getBalance() !== 0) { if (getBalance() !== 0) {
A(A.ENUM.GOT_NONZERO_BALANCE); A(A.ENUM.GOT_NONZERO_BALANCE);
} else { } else {
A(A.ENUM.GOT_ZERO_BALANCE); A(A.ENUM.GOT_ZERO_BALANCE);
} }
}; }, [getBalance]);
/** /**
* Forcefully fetches TXs and balance for ALL wallets. * Forcefully fetches TXs and balance for ALL wallets.
* Triggered manually by user on pull-to-refresh. * Triggered manually by user on pull-to-refresh.
*/ */
const refreshTransactions = async (showLoadingIndicator = true, showUpdateStatusIndicator = false) => { const refreshTransactions = useCallback(
if (isElectrumDisabled) { async (showLoadingIndicator = true, showUpdateStatusIndicator = false) => {
dispatch({ type: ActionTypes.SET_LOADING, payload: false }); if (isElectrumDisabled) {
return; dispatch({ type: ActionTypes.SET_LOADING, payload: false });
} return;
dispatch({ type: ActionTypes.SET_LOADING, payload: showLoadingIndicator }); }
refreshAllWalletTransactions(undefined, showUpdateStatusIndicator).finally(() => { dispatch({ type: ActionTypes.SET_LOADING, payload: showLoadingIndicator });
dispatch({ type: ActionTypes.SET_LOADING, payload: false }); refreshAllWalletTransactions(undefined, showUpdateStatusIndicator).finally(() => {
}); dispatch({ type: ActionTypes.SET_LOADING, payload: false });
}; });
},
[isElectrumDisabled, refreshAllWalletTransactions],
);
useEffect(() => { useEffect(() => {
refreshTransactions(false, true); refreshTransactions(false, true);
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // call refreshTransactions() only once, when screen mounts }, []);
const handleClick = (item?: TWallet) => { const handleClick = useCallback(
if (item?.getID) { (item?: TWallet) => {
const walletID = item.getID(); if (item?.getID) {
navigate('WalletTransactions', { const walletID = item.getID();
walletID, navigate('WalletTransactions', {
walletType: item.type, walletID,
}); walletType: item.type,
} else { });
navigate('AddWalletRoot'); } else {
} navigate('AddWalletRoot');
};
const setIsLoading = (value: boolean) => {
dispatch({ type: ActionTypes.SET_LOADING, payload: value });
};
const onSnapToItem = (e: { nativeEvent: { contentOffset: any } }) => {
if (!isFocused) return;
const contentOffset = e.nativeEvent.contentOffset;
const index = Math.ceil(contentOffset.x / width);
if (currentWalletIndex.current !== index) {
console.log('onSnapToItem', wallets.length === index ? 'NewWallet/Importing card' : index);
if (wallets[index] && (wallets[index].timeToRefreshBalance() || wallets[index].timeToRefreshTransaction())) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh either balance or transactions. refetching both');
refreshAllWalletTransactions(index, false).finally(() => setIsLoading(false));
} }
currentWalletIndex.current = index; },
} else { [navigate],
console.log('onSnapToItem did not change. Most likely momentum stopped at the same index it started.'); );
}
};
const renderListHeaderComponent = () => { const setIsLoading = useCallback((value: boolean) => {
dispatch({ type: ActionTypes.SET_LOADING, payload: value });
}, []);
const onSnapToItem = useCallback(
(e: { nativeEvent: { contentOffset: any } }) => {
if (!isFocused) return;
const contentOffset = e.nativeEvent.contentOffset;
const index = Math.ceil(contentOffset.x / width);
if (currentWalletIndex.current !== index) {
console.debug('onSnapToItem', wallets.length === index ? 'NewWallet/Importing card' : index);
if (wallets[index] && (wallets[index].timeToRefreshBalance() || wallets[index].timeToRefreshTransaction())) {
refreshAllWalletTransactions(index, false).finally(() => setIsLoading(false));
}
currentWalletIndex.current = index;
}
},
[isFocused, refreshAllWalletTransactions, setIsLoading, wallets, width],
);
const renderListHeaderComponent = useCallback(() => {
return ( return (
<View style={[styles.listHeaderBack, stylesHook.listHeaderBack]}> <View style={[styles.listHeaderBack, stylesHook.listHeaderBack]}>
<Text textBreakStrategy="simple" style={[styles.listHeaderText, stylesHook.listHeaderText]}> <Text textBreakStrategy="simple" style={[styles.listHeaderText, stylesHook.listHeaderText]}>
@ -221,28 +227,29 @@ const WalletsList: React.FC = () => {
</Text> </Text>
</View> </View>
); );
}; }, [stylesHook.listHeaderBack, stylesHook.listHeaderText]);
const handleLongPress = () => { const handleLongPress = useCallback(() => {
if (wallets.length > 1) { if (wallets.length > 1) {
navigate('ReorderWallets'); navigate('ReorderWallets');
} else { } else {
triggerHapticFeedback(HapticFeedbackTypes.NotificationError); triggerHapticFeedback(HapticFeedbackTypes.NotificationError);
} }
}; }, [navigate, wallets.length]);
const renderTransactionListsRow = (item: ExtendedTransaction) => { const renderTransactionListsRow = useCallback(
return ( (item: ExtendedTransaction) => (
<View style={styles.transaction}> <View style={styles.transaction}>
<TransactionListItem item={item} itemPriceUnit={item.walletPreferredBalanceUnit} walletID={item.walletID} /> <TransactionListItem item={item} itemPriceUnit={item.walletPreferredBalanceUnit} walletID={item.walletID} />
</View> </View>
); ),
}; [],
);
const renderWalletsCarousel = () => { const renderWalletsCarousel = useCallback(() => {
return ( return (
<WalletsCarousel <WalletsCarousel
// @ts-ignore: Convert to TS later // @ts-ignore: Fix later
data={wallets.concat(false)} data={wallets.concat(false)}
extraData={[wallets]} extraData={[wallets]}
onPress={handleClick} onPress={handleClick}
@ -254,49 +261,58 @@ const WalletsList: React.FC = () => {
scrollEnabled={isFocused} scrollEnabled={isFocused}
/> />
); );
}; }, [handleClick, handleLongPress, isFocused, onSnapToItem, wallets]);
const renderSectionItem = (item: { section: any; item: ExtendedTransaction }) => { const renderSectionItem = useCallback(
switch (item.section.key) { (item: { section: any; item: ExtendedTransaction }) => {
case WalletsListSections.CAROUSEL: switch (item.section.key) {
return isLargeScreen ? null : renderWalletsCarousel(); case WalletsListSections.CAROUSEL:
case WalletsListSections.TRANSACTIONS: return isLargeScreen ? null : renderWalletsCarousel();
return renderTransactionListsRow(item.item); case WalletsListSections.TRANSACTIONS:
default: return renderTransactionListsRow(item.item);
return null; default:
}
};
const renderSectionHeader = (section: { section: { key: any } }) => {
switch (section.section.key) {
case WalletsListSections.CAROUSEL:
return isLargeScreen ? null : <Header leftText={loc.wallets.list_title} onNewWalletPress={() => navigate('AddWalletRoot')} />;
case WalletsListSections.TRANSACTIONS:
return renderListHeaderComponent();
default:
return null;
}
};
const renderSectionFooter = (section: { section: { key: any } }) => {
switch (section.section.key) {
case WalletsListSections.TRANSACTIONS:
if (dataSource.length === 0 && !isLoading) {
return (
<View style={styles.footerRoot} testID="NoTransactionsMessage">
<Text style={styles.footerEmpty}>{loc.wallets.list_empty_txs1}</Text>
<Text style={styles.footerStart}>{loc.wallets.list_empty_txs2}</Text>
</View>
);
} else {
return null; return null;
} }
default: },
return null; [isLargeScreen, renderTransactionListsRow, renderWalletsCarousel],
} );
};
const renderScanButton = () => { const renderSectionHeader = useCallback(
(section: { section: { key: any } }) => {
switch (section.section.key) {
case WalletsListSections.CAROUSEL:
return isLargeScreen ? null : <Header leftText={loc.wallets.list_title} onNewWalletPress={() => navigate('AddWalletRoot')} />;
case WalletsListSections.TRANSACTIONS:
return renderListHeaderComponent();
default:
return null;
}
},
[isLargeScreen, navigate, renderListHeaderComponent],
);
const renderSectionFooter = useCallback(
(section: { section: { key: any } }) => {
switch (section.section.key) {
case WalletsListSections.TRANSACTIONS:
if (dataSource.length === 0 && !isLoading) {
return (
<View style={styles.footerRoot} testID="NoTransactionsMessage">
<Text style={styles.footerEmpty}>{loc.wallets.list_empty_txs1}</Text>
<Text style={styles.footerStart}>{loc.wallets.list_empty_txs2}</Text>
</View>
);
} else {
return null;
}
default:
return null;
}
},
[dataSource.length, isLoading],
);
const renderScanButton = useCallback(() => {
if (wallets.length > 0) { if (wallets.length > 0) {
return ( return (
<FContainer ref={walletActionButtonsRef.current}> <FContainer ref={walletActionButtonsRef.current}>
@ -311,30 +327,35 @@ const WalletsList: React.FC = () => {
} else { } else {
return null; return null;
} }
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [scanImage, wallets.length]);
const sectionListKeyExtractor = (item: any, index: any) => { const sectionListKeyExtractor = (item: any, index: any) => {
return `${item}${index}}`; return `${item}${index}}`;
}; };
const onScanButtonPressed = () => { const onScanButtonPressed = useCallback(() => {
scanQrHelper(routeName).then(onBarScanned); scanQrHelper(routeName).then(onBarScanned);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onBarScanned = (value: any) => { const onBarScanned = useCallback(
if (!value) return; (value: any) => {
DeeplinkSchemaMatch.navigationRouteFor({ url: value }, completionValue => { if (!value) return;
triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess); DeeplinkSchemaMatch.navigationRouteFor({ url: value }, completionValue => {
// @ts-ignore: Fix later triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess);
navigate(...completionValue); // @ts-ignore: for now
}); navigate(...completionValue);
}; });
},
[navigate],
);
const copyFromClipboard = async () => { const copyFromClipboard = useCallback(async () => {
onBarScanned(await BlueClipboard().getClipboardContent()); onBarScanned(await BlueClipboard().getClipboardContent());
}; }, [onBarScanned]);
const sendButtonLongPress = async () => { const sendButtonLongPress = useCallback(async () => {
const isClipboardEmpty = (await BlueClipboard().getClipboardContent()).trim().length === 0; const isClipboardEmpty = (await BlueClipboard().getClipboardContent()).trim().length === 0;
const options = [loc._.cancel, loc.wallets.list_long_choose, loc.wallets.list_long_scan]; const options = [loc._.cancel, loc.wallets.list_long_choose, loc.wallets.list_long_scan];
@ -358,7 +379,6 @@ const WalletsList: React.FC = () => {
fs.showImagePickerAndReadImage() fs.showImagePickerAndReadImage()
.then(onBarScanned) .then(onBarScanned)
.catch(error => { .catch(error => {
console.log(error);
triggerHapticFeedback(HapticFeedbackTypes.NotificationError); triggerHapticFeedback(HapticFeedbackTypes.NotificationError);
presentAlert({ title: loc.errors.error, message: error.message }); presentAlert({ title: loc.errors.error, message: error.message });
}); });
@ -373,12 +393,13 @@ const WalletsList: React.FC = () => {
break; break;
} }
}); });
}; }, [copyFromClipboard, onBarScanned, routeName]);
const onRefresh = () => { const onRefresh = useCallback(() => {
refreshTransactions(true, false); refreshTransactions(true, false);
}; // Optimized for Mac option doesn't like RN Refresh component. Menu Elements now handles it for macOS
// Optimized for Mac option doesn't like RN Refresh component. Menu Elements now handles it for macOS }, [refreshTransactions]);
const refreshProps = isDesktop || isElectrumDisabled ? {} : { refreshing: isLoading, onRefresh }; const refreshProps = isDesktop || isElectrumDisabled ? {} : { refreshing: isLoading, onRefresh };
const sections: SectionData[] = [ const sections: SectionData[] = [
@ -401,6 +422,9 @@ const WalletsList: React.FC = () => {
contentInset={styles.scrollContent} contentInset={styles.scrollContent}
renderSectionFooter={renderSectionFooter} renderSectionFooter={renderSectionFooter}
sections={sections} sections={sections}
windowSize={21}
maxToRenderPerBatch={10}
updateCellsBatchingPeriod={50}
/> />
{renderScanButton()} {renderScanButton()}
</View> </View>