REF: Wallet details uses Hooks

This commit is contained in:
marcosrdz 2020-08-08 21:04:11 -04:00 committed by Overtorment
parent 309218c86a
commit 75f52e421e

View File

@ -1,7 +1,6 @@
/* global alert */
import React, { Component } from 'react';
import React, { useEffect, useState, useCallback } from 'react';
import {
ActivityIndicator,
View,
Text,
TextInput,
@ -16,8 +15,7 @@ import {
StyleSheet,
StatusBar,
} from 'react-native';
import { SecondButton, SafeBlueArea, BlueCard, BlueSpacing20, BlueNavigationStyle, BlueText } from '../../BlueComponents';
import PropTypes from 'prop-types';
import { SecondButton, SafeBlueArea, BlueCard, BlueSpacing20, BlueNavigationStyle, BlueText, BlueLoadingHook } from '../../BlueComponents';
import { LightningCustodianWallet } from '../../class/wallets/lightning-custodian-wallet';
import { HDLegacyBreadwalletWallet } from '../../class/wallets/hd-legacy-breadwallet-wallet';
import { HDLegacyP2PKHWallet } from '../../class/wallets/hd-legacy-p2pkh-wallet';
@ -27,7 +25,7 @@ import Biometric from '../../class/biometrics';
import { HDSegwitBech32Wallet, SegwitP2SHWallet, LegacyWallet, SegwitBech32Wallet, WatchOnlyWallet } from '../../class';
import { ScrollView } from 'react-native-gesture-handler';
import loc from '../../loc';
import { BlueCurrentTheme } from '../../components/themes';
import { useTheme, useRoute, useNavigation } from '@react-navigation/native';
const EV = require('../../blue_modules/events');
const prompt = require('../../blue_modules/prompt');
const BlueApp = require('../../BlueApp');
@ -45,37 +43,28 @@ const styles = StyleSheet.create({
justifyContent: 'center',
alignItems: 'center',
},
saveText: {
color: BlueCurrentTheme.colors.outputValue,
},
address: {
alignItems: 'center',
flex: 1,
},
textLabel1: {
color: BlueCurrentTheme.colors.feeText,
fontWeight: '500',
fontSize: 14,
marginVertical: 12,
},
textLabel2: {
color: BlueCurrentTheme.colors.feeText,
fontWeight: '500',
fontSize: 14,
marginVertical: 16,
},
textValue: {
color: BlueCurrentTheme.colors.outputValue,
fontWeight: '500',
fontSize: 14,
},
input: {
flexDirection: 'row',
borderColor: BlueCurrentTheme.colors.formBorder,
borderBottomColor: BlueCurrentTheme.colors.formBorder,
borderWidth: 1,
borderBottomWidth: 0.5,
backgroundColor: BlueCurrentTheme.colors.inputBackgroundColor,
minHeight: 44,
height: 44,
alignItems: 'center',
@ -102,92 +91,103 @@ const styles = StyleSheet.create({
},
});
export default class WalletDetails extends Component {
constructor(props) {
super(props);
const WalletDetails = () => {
const { wallet } = useRoute().params;
const [isLoading, setIsLoading] = useState(true);
const [walletName, setWalletName] = useState(wallet.getLabel());
const [useWithHardwareWallet, setUseWithHardwareWallet] = useState(wallet.useWithHardwareWalletEnabled());
const [hideTransactionsInWalletsList, setHideTransactionsInWalletsList] = useState(!wallet.getHideTransactionsInWalletsList());
const { setParams, goBack, navigate, popToTop } = useNavigation();
const { colors } = useTheme();
const stylesHook = StyleSheet.create({
textLabel1: {
color: colors.feeText,
},
textLabel2: {
color: colors.feeText,
},
saveText: {
color: colors.outputValue,
},
textValue: {
color: colors.outputValue,
},
input: {
borderColor: colors.formBorder,
borderBottomColor: colors.formBorder,
const wallet = props.route.params.wallet;
const isLoading = true;
this.state = {
isLoading,
walletName: wallet.getLabel(),
wallet,
useWithHardwareWallet: wallet.useWithHardwareWalletEnabled(),
};
this.props.navigation.setParams({ isLoading, saveAction: () => this.setLabel() });
}
backgroundColor: colors.inputBackgroundColor,
},
});
componentDidMount() {
console.log('wallets/details componentDidMount');
this.setState({
isLoading: false,
});
this.props.navigation.setParams({ isLoading: false, saveAction: () => this.setLabel() });
}
setLabel() {
this.props.navigation.setParams({ isLoading: true });
this.setState({ isLoading: true }, async () => {
if (this.state.walletName.trim().length > 0) {
this.state.wallet.setLabel(this.state.walletName);
const setLabel = useCallback(async () => {
setParams({ isLoading: true });
setIsLoading(true);
if (walletName.trim().length > 0) {
wallet.setLabel(walletName);
if (wallet.type === WatchOnlyWallet.type && wallet.getSecret().startsWith('zpub')) {
wallet.setUseWithHardwareWalletEnabled(useWithHardwareWallet);
}
await BlueApp.saveToDisk();
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED);
alert(loc.wallets.details_wallet_updated);
this.props.navigation.goBack(null);
});
}
wallet.setHideTransactionsInWalletsList(!hideTransactionsInWalletsList);
}
setParams({ wallet });
await BlueApp.saveToDisk();
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED);
alert(loc.wallets.details_wallet_updated);
goBack();
}, [goBack, hideTransactionsInWalletsList, setParams, useWithHardwareWallet, wallet, walletName]);
async presentWalletHasBalanceAlert() {
useEffect(() => {
setParams({ isLoading, saveAction: setLabel, saveTextStyle: stylesHook.saveText });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoading, colors.outputValue, setLabel]);
useEffect(() => {
setIsLoading(false);
}, []);
const presentWalletHasBalanceAlert = useCallback(async () => {
ReactNativeHapticFeedback.trigger('notificationWarning', { ignoreAndroidSystemSettings: false });
const walletBalanceConfirmation = await prompt(
loc.wallets.details_del_wb,
loc.formatString(loc.wallets.details_del_wb_q, { balance: this.state.wallet.getBalance() }),
loc.formatString(loc.wallets.details_del_wb_q, { balance: wallet.getBalance() }),
true,
'plain-text',
);
if (Number(walletBalanceConfirmation) === this.state.wallet.getBalance()) {
this.props.navigation.setParams({ isLoading: true });
this.setState({ isLoading: true }, async () => {
notifications.unsubscribe(this.state.wallet.getAllExternalAddresses(), [], []);
BlueApp.deleteWallet(this.state.wallet);
ReactNativeHapticFeedback.trigger('notificationSuccess', { ignoreAndroidSystemSettings: false });
await BlueApp.saveToDisk();
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED);
EV(EV.enum.WALLETS_COUNT_CHANGED);
this.props.navigation.popToTop();
});
if (Number(walletBalanceConfirmation) === wallet.getBalance()) {
setParams({ isLoading: true });
setIsLoading(true);
notifications.unsubscribe(wallet.getAllExternalAddresses(), [], []);
BlueApp.deleteWallet(wallet);
ReactNativeHapticFeedback.trigger('notificationSuccess', { ignoreAndroidSystemSettings: false });
await BlueApp.saveToDisk();
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED);
EV(EV.enum.WALLETS_COUNT_CHANGED);
popToTop();
} else {
ReactNativeHapticFeedback.trigger('notificationError', { ignoreAndroidSystemSettings: false });
this.setState({ isLoading: false }, async () => {
alert(loc.wallets.details_del_wb_err);
});
setIsLoading(false);
alert(loc.wallets.details_del_wb_err);
}
}
}, [popToTop, setParams, wallet]);
async onUseWithHardwareWalletSwitch(value) {
this.setState((state, props) => {
const wallet = state.wallet;
wallet.setUseWithHardwareWalletEnabled(value);
return { useWithHardwareWallet: !!value, wallet };
});
}
onHideTransactionsInWalletsListSwitch = value => {
this.setState(state => {
const wallet = state.wallet;
wallet.setHideTransactionsInWalletsList(!value);
return { wallet };
const navigateToWalletExport = () => {
navigate('WalletExport', {
wallet,
});
};
const navigateToXPub = () =>
navigate('WalletXpub', {
secret: wallet.getSecret(),
});
renderMarketplaceButton = () => {
const renderMarketplaceButton = () => {
return Platform.select({
android: (
<SecondButton
onPress={() =>
this.props.navigation.navigate('Marketplace', {
fromWallet: this.state.wallet,
navigate('Marketplace', {
fromWallet: wallet,
})
}
title={loc.wallets.details_marketplace}
@ -204,188 +204,168 @@ export default class WalletDetails extends Component {
});
};
render() {
if (this.state.isLoading) {
return (
<View style={styles.root}>
<ActivityIndicator />
</View>
);
}
const navigateToBroadcast = () => {
navigate('Broadcast');
};
return (
<SafeBlueArea style={styles.root}>
<StatusBar barStyle="default" />
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<ScrollView contentContainerStyle={styles.scrollViewContent}>
<BlueCard style={styles.address}>
{(() => {
if (
[LegacyWallet.type, SegwitBech32Wallet.type, SegwitP2SHWallet.type].includes(this.state.wallet.type) ||
(this.state.wallet.type === WatchOnlyWallet.type && !this.state.wallet.isHd())
) {
return (
<>
<Text style={styles.textLabel1}>{loc.wallets.details_address.toLowerCase()}</Text>
<Text style={styles.textValue}>{this.state.wallet.getAddress()}</Text>
</>
);
}
})()}
<Text style={styles.textLabel2}>{loc.wallets.add_wallet_name.toLowerCase()}</Text>
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'position' : null}>
<View style={styles.input}>
<TextInput
placeholder={loc.send.details_note_placeholder}
value={this.state.walletName}
onChangeText={text => {
this.setState({ walletName: text });
}}
onBlur={() => {
if (this.state.walletName.trim().length === 0) {
const walletLabel = this.state.wallet.getLabel();
this.setState({ walletName: walletLabel });
}
}}
numberOfLines={1}
placeholderTextColor="#81868e"
style={styles.inputText}
editable={!this.state.isLoading}
underlineColorAndroid="transparent"
/>
</View>
</KeyboardAvoidingView>
<BlueSpacing20 />
<Text style={styles.textLabel1}>{loc.wallets.details_type.toLowerCase()}</Text>
<Text style={styles.textValue}>{this.state.wallet.typeReadable}</Text>
{this.state.wallet.type === LightningCustodianWallet.type && (
const walletNameTextInputOnBlur = () => {
if (walletName.trim().length === 0) {
const walletLabel = wallet.getLabel();
setWalletName(walletLabel);
}
};
const handleDeleteButtonTapped = () => {
ReactNativeHapticFeedback.trigger('notificationWarning', { ignoreAndroidSystemSettings: false });
Alert.alert(
loc.wallets.details_delete_wallet,
loc.wallets.details_are_you_sure,
[
{
text: loc.wallets.details_yes_delete,
onPress: async () => {
const isBiometricsEnabled = await Biometric.isBiometricUseCapableAndEnabled();
if (isBiometricsEnabled) {
if (!(await Biometric.unlockWithBiometrics())) {
return;
}
}
if (wallet.getBalance() > 0 && wallet.allowSend()) {
presentWalletHasBalanceAlert();
} else {
setParams({ isLoading: true });
setIsLoading(true);
notifications.unsubscribe(wallet.getAllExternalAddresses(), [], []);
BlueApp.deleteWallet(wallet);
ReactNativeHapticFeedback.trigger('notificationSuccess', { ignoreAndroidSystemSettings: false });
await BlueApp.saveToDisk();
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED);
EV(EV.enum.WALLETS_COUNT_CHANGED);
popToTop();
}
},
style: 'destructive',
},
{ text: loc.wallets.details_no_cancel, onPress: () => {}, style: 'cancel' },
],
{ cancelable: false },
);
};
return isLoading ? (
<View style={styles.root}>
<BlueLoadingHook />
</View>
) : (
<SafeBlueArea style={styles.root}>
<StatusBar barStyle="default" />
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<ScrollView contentContainerStyle={styles.scrollViewContent}>
<BlueCard style={styles.address}>
{(() => {
if (
[LegacyWallet.type, SegwitBech32Wallet.type, SegwitP2SHWallet.type].includes(wallet.type) ||
(wallet.type === WatchOnlyWallet.type && !wallet.isHd())
) {
return (
<>
<Text style={[styles.textLabel1, stylesHook.textLabel1]}>{loc.wallets.details_address.toLowerCase()}</Text>
<Text style={[styles.textValue, stylesHook.textValue]}>{wallet.getAddress()}</Text>
</>
);
}
})()}
<Text style={[styles.textLabel2, stylesHook.textLabel2]}>{loc.wallets.add_wallet_name.toLowerCase()}</Text>
<KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'position' : null}>
<View style={[styles.input, stylesHook.input]}>
<TextInput
placeholder={loc.send.details_note_placeholder}
value={walletName}
onChangeText={setWalletName}
onBlur={walletNameTextInputOnBlur}
numberOfLines={1}
placeholderTextColor="#81868e"
style={styles.inputText}
editable={!isLoading}
underlineColorAndroid="transparent"
/>
</View>
</KeyboardAvoidingView>
<BlueSpacing20 />
<Text style={[styles.textLabel1, stylesHook.textLabel1]}>{loc.wallets.details_type.toLowerCase()}</Text>
<Text style={[styles.textValue, stylesHook.textValue]}>{wallet.typeReadable}</Text>
{wallet.type === LightningCustodianWallet.type && (
<>
<Text style={[styles.textLabel1, stylesHook.textLabel1]}>{loc.wallets.details_connected_to.toLowerCase()}</Text>
<BlueText>{wallet.getBaseURI()}</BlueText>
</>
)}
<>
<Text style={[styles.textLabel2, stylesHook.textLabel2]}>{loc.transactions.list_title.toLowerCase()}</Text>
<View style={styles.hardware}>
<BlueText>{loc.wallets.details_display}</BlueText>
<Switch value={hideTransactionsInWalletsList} onValueChange={setHideTransactionsInWalletsList} />
</View>
</>
<>
<Text style={[styles.textLabel2, stylesHook.textLabel2]}>{loc.transactions.transactions_count.toLowerCase()}</Text>
<BlueText>{wallet.getTransactions().length}</BlueText>
</>
<View>
{wallet.type === WatchOnlyWallet.type && wallet.getSecret().startsWith('zpub') && (
<>
<Text style={styles.textLabel1}>{loc.wallets.details_connected_to.toLowerCase()}</Text>
<BlueText>{this.state.wallet.getBaseURI()}</BlueText>
<Text style={[styles.textLabel2, stylesHook.textLabel2]}>{loc.wallets.details_advanced.toLowerCase()}</Text>
<View style={styles.hardware}>
<BlueText>{loc.wallets.details_use_with_hardware_wallet}</BlueText>
<Switch value={useWithHardwareWallet} onValueChange={setUseWithHardwareWallet} />
</View>
<>
<Text style={[styles.textLabel1, stylesHook.textLabel1]}>{loc.wallets.details_master_fingerprint.toLowerCase()}</Text>
<Text style={[styles.textValue, stylesHook.textValue]}>{wallet.getMasterFingerprintHex()}</Text>
</>
<BlueSpacing20 />
</>
)}
<>
<Text style={styles.textLabel2}>{loc.transactions.list_title.toLowerCase()}</Text>
<View style={styles.hardware}>
<BlueText>{loc.wallets.details_display}</BlueText>
<Switch
value={!this.state.wallet.getHideTransactionsInWalletsList()}
onValueChange={this.onHideTransactionsInWalletsListSwitch}
/>
</View>
</>
<>
<Text style={styles.textLabel2}>{loc.transactions.transactions_count.toLowerCase()}</Text>
<BlueText>{this.state.wallet.getTransactions().length}</BlueText>
</>
<View>
<BlueSpacing20 />
{this.state.wallet.type === WatchOnlyWallet.type && this.state.wallet.getSecret().startsWith('zpub') && (
<>
<Text style={styles.textLabel2}>{loc.wallets.details_advanced.toLowerCase()}</Text>
<View style={styles.hardware}>
<BlueText>{loc.wallets.details_use_with_hardware_wallet}</BlueText>
<Switch value={this.state.useWithHardwareWallet} onValueChange={value => this.onUseWithHardwareWalletSwitch(value)} />
</View>
<>
<Text style={styles.textLabel1}>{loc.wallets.details_master_fingerprint.toLowerCase()}</Text>
<Text style={styles.textValue}>{this.state.wallet.getMasterFingerprintHex()}</Text>
</>
<BlueSpacing20 />
</>
)}
<BlueSpacing20 />
<SecondButton
onPress={() =>
this.props.navigation.navigate('WalletExport', {
wallet: this.state.wallet,
})
}
title={loc.wallets.details_export_backup}
/>
<SecondButton onPress={navigateToWalletExport} title={loc.wallets.details_export_backup} />
<BlueSpacing20 />
<BlueSpacing20 />
{(this.state.wallet.type === HDLegacyBreadwalletWallet.type ||
this.state.wallet.type === HDLegacyP2PKHWallet.type ||
this.state.wallet.type === HDSegwitBech32Wallet.type ||
this.state.wallet.type === HDSegwitP2SHWallet.type) && (
<>
<SecondButton
onPress={() =>
this.props.navigation.navigate('WalletXpub', {
secret: this.state.wallet.getSecret(),
})
}
title={loc.wallets.details_show_xpub}
/>
{(wallet.type === HDLegacyBreadwalletWallet.type ||
wallet.type === HDLegacyP2PKHWallet.type ||
wallet.type === HDSegwitBech32Wallet.type ||
wallet.type === HDSegwitP2SHWallet.type) && (
<>
<SecondButton onPress={navigateToXPub} title={loc.wallets.details_show_xpub} />
<BlueSpacing20 />
{this.renderMarketplaceButton()}
</>
)}
{this.state.wallet.type !== LightningCustodianWallet.type && (
<>
<BlueSpacing20 />
<SecondButton onPress={() => this.props.navigation.navigate('Broadcast')} title={loc.settings.network_broadcast} />
</>
)}
<BlueSpacing20 />
<TouchableOpacity
style={styles.center}
onPress={() => {
ReactNativeHapticFeedback.trigger('notificationWarning', { ignoreAndroidSystemSettings: false });
Alert.alert(
loc.wallets.details_delete_wallet,
loc.wallets.details_are_you_sure,
[
{
text: loc.wallets.details_yes_delete,
onPress: async () => {
const isBiometricsEnabled = await Biometric.isBiometricUseCapableAndEnabled();
<BlueSpacing20 />
{renderMarketplaceButton()}
</>
)}
{wallet.type !== LightningCustodianWallet.type && (
<>
<BlueSpacing20 />
<SecondButton onPress={navigateToBroadcast} title={loc.settings.network_broadcast} />
</>
)}
<BlueSpacing20 />
<BlueSpacing20 />
<TouchableOpacity style={styles.center} onPress={handleDeleteButtonTapped}>
<Text style={styles.delete}>{loc.wallets.details_delete}</Text>
</TouchableOpacity>
</View>
</BlueCard>
</ScrollView>
</TouchableWithoutFeedback>
</SafeBlueArea>
);
};
if (isBiometricsEnabled) {
if (!(await Biometric.unlockWithBiometrics())) {
return;
}
}
if (this.state.wallet.getBalance() > 0 && this.state.wallet.allowSend()) {
this.presentWalletHasBalanceAlert();
} else {
this.props.navigation.setParams({ isLoading: true });
this.setState({ isLoading: true }, async () => {
notifications.unsubscribe(this.state.wallet.getAllExternalAddresses(), [], []);
BlueApp.deleteWallet(this.state.wallet);
ReactNativeHapticFeedback.trigger('notificationSuccess', { ignoreAndroidSystemSettings: false });
await BlueApp.saveToDisk();
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED);
EV(EV.enum.WALLETS_COUNT_CHANGED);
this.props.navigation.popToTop();
});
}
},
style: 'destructive',
},
{ text: loc.wallets.details_no_cancel, onPress: () => {}, style: 'cancel' },
],
{ cancelable: false },
);
}}
>
<Text style={styles.delete}>{loc.wallets.details_delete}</Text>
</TouchableOpacity>
</View>
</BlueCard>
</ScrollView>
</TouchableWithoutFeedback>
</SafeBlueArea>
);
}
}
WalletDetails.navigationOptions = ({ navigation, route }) => ({
WalletDetails.navigationOptions = ({ route }) => ({
...BlueNavigationStyle(),
title: loc.wallets.details_title,
headerTitle: loc.wallets.details_title,
headerRight: () => (
<TouchableOpacity
disabled={route.params.isLoading === true}
@ -396,24 +376,9 @@ WalletDetails.navigationOptions = ({ navigation, route }) => ({
}
}}
>
<Text style={styles.saveText}>{loc.wallets.details_save}</Text>
<Text style={route.params.saveTextStyle}>{loc.wallets.details_save}</Text>
</TouchableOpacity>
),
});
WalletDetails.propTypes = {
navigation: PropTypes.shape({
state: PropTypes.shape({
params: PropTypes.shape({
secret: PropTypes.string,
}),
}),
navigate: PropTypes.func,
goBack: PropTypes.func,
popToTop: PropTypes.func,
setParams: PropTypes.func,
}),
route: PropTypes.shape({
params: PropTypes.object,
}),
};
export default WalletDetails;