BlueWallet/screen/wallets/list.js

453 lines
15 KiB
JavaScript
Raw Normal View History

2018-01-30 22:42:38 +00:00
import React, { Component } from 'react';
2019-12-27 18:53:34 -06:00
import {
View,
StatusBar,
TouchableOpacity,
Text,
StyleSheet,
FlatList,
InteractionManager,
RefreshControl,
ScrollView,
Alert,
} from 'react-native';
2019-02-16 20:22:14 -05:00
import { BlueLoading, SafeBlueArea, WalletsCarousel, BlueList, BlueHeaderDefaultMain, BlueTransactionListItem } from '../../BlueComponents';
import { Icon } from 'react-native-elements';
import { NavigationEvents } from 'react-navigation';
import ReactNativeHapticFeedback from 'react-native-haptic-feedback';
2018-03-18 02:48:23 +00:00
import PropTypes from 'prop-types';
2019-12-26 20:21:07 -06:00
import { PlaceholderWallet } from '../../class';
import WalletImport from '../../class/walletImport';
2020-03-24 22:23:58 -04:00
import ViewPager from '@react-native-community/viewpager';
import ScanQRCode from '../send/ScanQRCode';
2019-12-27 18:53:34 -06:00
import DeeplinkSchemaMatch from '../../class/deeplinkSchemaMatch';
2018-03-17 22:39:21 +02:00
let EV = require('../../events');
let A = require('../../analytics');
2018-03-18 02:48:23 +00:00
/** @type {AppStorage} */
let BlueApp = require('../../BlueApp');
2018-05-28 20:18:11 +01:00
let loc = require('../../loc');
let BlueElectrum = require('../../BlueElectrum');
2018-01-30 22:42:38 +00:00
export default class WalletsList extends Component {
walletsCarousel = React.createRef();
2020-03-24 22:23:58 -04:00
viewPagerRef = React.createRef();
2018-01-30 22:42:38 +00:00
constructor(props) {
super(props);
this.state = {
isLoading: true,
2019-02-16 20:22:14 -05:00
isFlatListRefreshControlHidden: true,
wallets: BlueApp.getWallets().concat(false),
lastSnappedTo: 0,
2019-12-28 10:22:43 -06:00
timeElpased: 0,
2020-01-08 04:29:51 -05:00
cameraPreviewIsPaused: true,
2020-03-24 23:08:48 -04:00
viewPagerIndex: 1,
2018-03-17 22:39:21 +02:00
};
EV(EV.enum.WALLETS_COUNT_CHANGED, () => this.redrawScreen(true));
// here, when we receive TRANSACTIONS_COUNT_CHANGED we do not query
// remote server, we just redraw the screen
EV(EV.enum.TRANSACTIONS_COUNT_CHANGED, this.redrawScreen);
2018-01-30 22:42:38 +00:00
}
componentDidMount() {
2019-02-16 20:22:14 -05:00
this.redrawScreen();
// the idea is that upon wallet launch we will refresh
// all balances and all transactions here:
InteractionManager.runAfterInteractions(async () => {
let noErr = true;
try {
await BlueElectrum.waitTillConnected();
let balanceStart = +new Date();
await BlueApp.fetchWalletBalances();
let balanceEnd = +new Date();
console.log('fetch all wallet balances took', (balanceEnd - balanceStart) / 1000, 'sec');
let start = +new Date();
await BlueApp.fetchWalletTransactions();
let end = +new Date();
console.log('fetch all wallet txs took', (end - start) / 1000, 'sec');
} catch (error) {
noErr = false;
2020-01-20 18:58:33 -05:00
console.log(error);
}
if (noErr) this.redrawScreen();
});
2019-12-28 10:22:43 -06:00
this.interval = setInterval(() => {
this.setState(prev => ({ timeElapsed: prev.timeElapsed + 1 }));
}, 60000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
2018-01-30 22:42:38 +00:00
2018-07-02 12:09:34 +01:00
/**
* Forcefully fetches TXs and balance for lastSnappedTo (i.e. current) wallet.
* Triggered manually by user on pull-to-refresh.
2018-07-02 12:09:34 +01:00
*/
2018-06-24 23:22:46 +01:00
refreshTransactions() {
2019-02-16 20:22:14 -05:00
if (!(this.lastSnappedTo < BlueApp.getWallets().length) && this.lastSnappedTo !== undefined) {
// last card, nop
console.log('last card, nop');
return;
}
2018-03-17 22:39:21 +02:00
this.setState(
2018-06-24 23:22:46 +01:00
{
isFlatListRefreshControlHidden: false,
2018-06-24 23:22:46 +01:00
},
2019-02-16 20:22:14 -05:00
() => {
InteractionManager.runAfterInteractions(async () => {
2018-06-24 23:22:46 +01:00
let noErr = true;
try {
2019-07-13 16:21:03 +01:00
await BlueElectrum.ping();
await BlueElectrum.waitTillConnected();
let balanceStart = +new Date();
2019-02-16 20:22:14 -05:00
await BlueApp.fetchWalletBalances(this.lastSnappedTo || 0);
let balanceEnd = +new Date();
console.log('fetch balance took', (balanceEnd - balanceStart) / 1000, 'sec');
let start = +new Date();
2019-02-16 20:22:14 -05:00
await BlueApp.fetchWalletTransactions(this.lastSnappedTo || 0);
let end = +new Date();
console.log('fetch tx took', (end - start) / 1000, 'sec');
2018-06-24 23:22:46 +01:00
} catch (err) {
noErr = false;
console.warn(err);
}
if (noErr) await BlueApp.saveToDisk(); // caching
2019-02-16 20:22:14 -05:00
this.redrawScreen();
});
2018-06-24 23:22:46 +01:00
},
);
}
redrawScreen = (scrollToEnd = false) => {
2019-02-16 20:22:14 -05:00
console.log('wallets/list redrawScreen()');
if (BlueApp.getBalance() !== 0) {
A(A.ENUM.GOT_NONZERO_BALANCE);
2019-11-28 23:16:04 +00:00
} else {
A(A.ENUM.GOT_ZERO_BALANCE);
}
2018-07-06 16:41:48 +01:00
const wallets = BlueApp.getWallets().concat(false);
if (scrollToEnd) {
scrollToEnd = wallets.length > this.state.wallets.length;
}
this.setState(
{
isLoading: false,
isFlatListRefreshControlHidden: true,
dataSource: BlueApp.getTransactions(null, 10),
wallets: BlueApp.getWallets().concat(false),
},
() => {
if (scrollToEnd) {
2019-12-26 20:21:07 -06:00
this.walletsCarousel.snapToItem(this.state.wallets.length - 2);
}
},
);
};
2018-06-24 23:22:46 +01:00
txMemo(hash) {
if (BlueApp.tx_metadata[hash] && BlueApp.tx_metadata[hash]['memo']) {
2018-06-28 02:43:28 +01:00
return BlueApp.tx_metadata[hash]['memo'];
2018-06-24 23:22:46 +01:00
}
return '';
}
2019-01-24 23:46:03 -05:00
handleClick(index) {
console.log('click', index);
2018-06-24 23:22:46 +01:00
let wallet = BlueApp.wallets[index];
if (wallet) {
2019-12-26 20:21:07 -06:00
if (wallet.type === PlaceholderWallet.type) {
Alert.alert(
loc.wallets.add.details,
'There was a problem importing this wallet.',
[
{
text: loc.wallets.details.delete,
onPress: () => {
WalletImport.removePlaceholderWallet();
EV(EV.enum.WALLETS_COUNT_CHANGED);
},
style: 'destructive',
},
{
text: 'Try Again',
onPress: () => {
this.props.navigation.navigate('ImportWallet', { label: wallet.getSecret() });
WalletImport.removePlaceholderWallet();
EV(EV.enum.WALLETS_COUNT_CHANGED);
},
style: 'default',
},
],
{ cancelable: false },
);
} else {
this.props.navigation.navigate('WalletTransactions', {
wallet: wallet,
key: `WalletTransactions-${wallet.getID()}`,
});
}
2018-06-24 23:22:46 +01:00
} else {
// if its out of index - this must be last card with incentive to create wallet
2019-12-26 20:21:07 -06:00
if (!BlueApp.getWallets().some(wallet => wallet.type === PlaceholderWallet.type)) {
this.props.navigation.navigate('AddWallet');
}
2018-06-24 23:22:46 +01:00
}
}
onSnapToItem(index) {
console.log('onSnapToItem', index);
this.lastSnappedTo = index;
this.setState({ lastSnappedTo: index });
2018-06-24 23:22:46 +01:00
if (index < BlueApp.getWallets().length) {
// not the last
2018-06-24 23:22:46 +01:00
}
2018-07-02 14:51:24 +01:00
2019-12-26 20:21:07 -06:00
if (this.state.wallets[index].type === PlaceholderWallet.type) {
return;
}
2018-07-02 14:51:24 +01:00
// now, lets try to fetch balance and txs for this wallet in case it has changed
this.lazyRefreshWallet(index);
}
/**
* Decides whether wallet with such index shoud be refreshed,
* refreshes if yes and redraws the screen
* @param index {Integer} Index of the wallet.
* @return {Promise.<void>}
*/
async lazyRefreshWallet(index) {
/** @type {Array.<AbstractWallet>} wallets */
let wallets = BlueApp.getWallets();
if (!wallets[index]) {
return;
}
2018-07-02 14:51:24 +01:00
let oldBalance = wallets[index].getBalance();
let noErr = true;
2018-07-14 21:32:36 +01:00
let didRefresh = false;
2018-07-02 14:51:24 +01:00
try {
2019-12-26 20:21:07 -06:00
if (wallets && wallets[index] && wallets[index].type !== PlaceholderWallet.type && wallets[index].timeToRefreshBalance()) {
2018-07-02 14:51:24 +01:00
console.log('snapped to, and now its time to refresh wallet #', index);
await wallets[index].fetchBalance();
2018-07-07 14:04:32 +01:00
if (oldBalance !== wallets[index].getBalance() || wallets[index].getUnconfirmedBalance() !== 0) {
console.log('balance changed, thus txs too');
2018-07-02 14:51:24 +01:00
// balance changed, thus txs too
await wallets[index].fetchTransactions();
2019-02-16 20:22:14 -05:00
this.redrawScreen();
2018-07-14 21:32:36 +01:00
didRefresh = true;
} else if (wallets[index].timeToRefreshTransaction()) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh TXs');
2018-07-14 21:32:36 +01:00
await wallets[index].fetchTransactions();
if (wallets[index].fetchPendingTransactions) {
await wallets[index].fetchPendingTransactions();
}
if (wallets[index].fetchUserInvoices) {
await wallets[index].fetchUserInvoices();
2019-06-01 21:45:01 +01:00
await wallets[index].fetchBalance(); // chances are, paid ln invoice was processed during `fetchUserInvoices()` call and altered user's balance, so its worth fetching balance again
}
2019-02-16 20:22:14 -05:00
this.redrawScreen();
2018-07-14 21:32:36 +01:00
didRefresh = true;
2018-07-03 21:11:02 +01:00
} else {
console.log('balance not changed');
2018-07-02 14:51:24 +01:00
}
}
} catch (Err) {
noErr = false;
console.warn(Err);
}
2018-07-14 21:32:36 +01:00
if (noErr && didRefresh) {
2018-07-02 14:51:24 +01:00
await BlueApp.saveToDisk(); // caching
}
2018-01-30 22:42:38 +00:00
}
_keyExtractor = (_item, index) => index.toString();
2018-09-18 03:24:42 -04:00
renderListHeaderComponent = () => {
return (
<View>
<Text
style={{
paddingLeft: 15,
fontWeight: 'bold',
fontSize: 24,
marginVertical: 8,
color: BlueApp.settings.foregroundColor,
}}
>
{loc.transactions.list.title}
</Text>
</View>
);
};
handleLongPress = () => {
2019-12-26 20:21:07 -06:00
if (BlueApp.getWallets().length > 1 && !BlueApp.getWallets().some(wallet => wallet.type === PlaceholderWallet.type)) {
this.props.navigation.navigate('ReorderWallets');
} else {
2019-05-03 13:36:11 +01:00
ReactNativeHapticFeedback.trigger('notificationError', { ignoreAndroidSystemSettings: false });
}
};
2020-03-24 23:11:28 -04:00
onPageSelected = e => {
const index = e.nativeEvent.position;
2019-12-27 18:53:34 -06:00
StatusBar.setBarStyle(index === 1 ? 'dark-content' : 'light-content');
2020-03-24 23:08:48 -04:00
this.setState({ cameraPreviewIsPaused: index === 1 || index === undefined, viewPagerIndex: index });
2019-12-27 18:53:34 -06:00
};
onBarScanned = value => {
DeeplinkSchemaMatch.navigationRouteFor({ url: value }, completionValue => {
ReactNativeHapticFeedback.trigger('impactLight', { ignoreAndroidSystemSettings: false });
this.props.navigation.navigate(completionValue);
});
};
2019-02-16 20:22:14 -05:00
_renderItem = data => {
return <BlueTransactionListItem item={data.item} itemPriceUnit={data.item.walletPreferredBalanceUnit} />;
};
2019-12-27 18:53:34 -06:00
renderNavigationHeader = () => {
return (
<View style={{ height: 44, alignItems: 'flex-end', justifyContent: 'center' }}>
<TouchableOpacity
testID="SettingsButton"
style={{ marginHorizontal: 16 }}
onPress={() => this.props.navigation.navigate('Settings')}
>
2019-12-27 18:53:34 -06:00
<Icon size={22} name="kebab-horizontal" type="octicon" color={BlueApp.settings.foregroundColor} />
</TouchableOpacity>
</View>
);
};
2018-01-30 22:42:38 +00:00
render() {
if (this.state.isLoading) {
2018-03-17 22:39:21 +02:00
return <BlueLoading />;
2018-01-30 22:42:38 +00:00
}
return (
2020-03-16 13:51:08 +00:00
<View style={{ flex: 1, backgroundColor: '#000000' }} testID="WalletsList" accessible>
2018-12-11 22:33:28 -05:00
<NavigationEvents
2019-12-27 18:53:34 -06:00
onDidFocus={() => {
2019-02-16 20:22:14 -05:00
this.redrawScreen();
2020-03-24 23:11:28 -04:00
this.setState({ cameraPreviewIsPaused: this.state.viewPagerIndex === 1 || this.viewPagerRef.current.index === undefined });
2018-12-11 22:33:28 -05:00
}}
2019-12-27 18:53:34 -06:00
onWillBlur={() => this.setState({ cameraPreviewIsPaused: true })}
2018-12-11 22:33:28 -05:00
/>
<ScrollView contentContainerStyle={{ flex: 1 }}>
2020-03-24 22:23:58 -04:00
<ViewPager
2019-12-27 18:53:34 -06:00
style={styles.wrapper}
2020-03-24 23:08:48 -04:00
onPageSelected={this.onPageSelected}
2020-03-24 22:23:58 -04:00
initialPage={1}
ref={this.viewPagerRef}
showPageIndicator={false}
2019-12-27 18:53:34 -06:00
>
<View style={styles.scanQRWrapper}>
<ScanQRCode
cameraPreviewIsPaused={this.state.cameraPreviewIsPaused}
onBarScanned={this.onBarScanned}
showCloseButton={false}
initialCameraStatusReady={false}
launchedBy={this.props.navigation.state.routeName}
/>
</View>
<SafeBlueArea>
<View style={styles.walletsListWrapper}>
{this.renderNavigationHeader()}
<ScrollView
refreshControl={
<RefreshControl onRefresh={() => this.refreshTransactions()} refreshing={!this.state.isFlatListRefreshControlHidden} />
}
>
<BlueHeaderDefaultMain
leftText={loc.wallets.list.title}
onNewWalletPress={
!BlueApp.getWallets().some(wallet => wallet.type === PlaceholderWallet.type)
? () => this.props.navigation.navigate('AddWallet')
: null
}
/>
<WalletsCarousel
removeClippedSubviews={false}
data={this.state.wallets}
handleClick={index => {
this.handleClick(index);
2018-10-10 20:36:32 +01:00
}}
2019-12-27 18:53:34 -06:00
handleLongPress={this.handleLongPress}
onSnapToItem={index => {
this.onSnapToItem(index);
2018-10-10 20:36:32 +01:00
}}
2019-12-27 18:53:34 -06:00
ref={c => (this.walletsCarousel = c)}
/>
<BlueList>
<FlatList
ListHeaderComponent={this.renderListHeaderComponent}
ListEmptyComponent={
<View style={{ top: 50, height: 100 }}>
<Text
style={{
fontSize: 18,
color: '#9aa0aa',
textAlign: 'center',
}}
>
{loc.wallets.list.empty_txs1}
</Text>
<Text
style={{
fontSize: 18,
color: '#9aa0aa',
textAlign: 'center',
}}
>
{loc.wallets.list.empty_txs2}
</Text>
</View>
}
data={this.state.dataSource}
extraData={this.state.dataSource}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
</BlueList>
</ScrollView>
</View>
</SafeBlueArea>
2020-03-24 22:23:58 -04:00
</ViewPager>
</ScrollView>
2019-12-27 18:53:34 -06:00
</View>
2018-01-30 22:42:38 +00:00
);
}
2018-03-17 22:39:21 +02:00
}
2018-03-18 02:48:23 +00:00
2019-12-27 18:53:34 -06:00
const styles = StyleSheet.create({
wrapper: {
backgroundColor: '#FFFFFF',
2020-03-24 22:23:58 -04:00
flex: 1,
2019-12-27 18:53:34 -06:00
},
walletsListWrapper: {
flex: 1,
backgroundColor: '#FFFFFF',
},
scanQRWrapper: {
flex: 1,
backgroundColor: '#000000',
},
});
2018-03-18 02:48:23 +00:00
WalletsList.propTypes = {
navigation: PropTypes.shape({
2019-12-27 18:53:34 -06:00
state: PropTypes.shape({
routeName: PropTypes.string,
}),
2018-03-18 02:48:23 +00:00
navigate: PropTypes.func,
}),
};