import React from 'react'; import translate from 'translations'; import { Token } from 'types/network'; import { walletTypes } from 'features/wallet'; import { AddCustomTokenForm } from './AddCustomTokenForm'; import TokenRow from './TokenRow'; interface Props { allTokens: Token[]; tokenBalances: walletTypes.TokenBalance[]; hasSavedWalletTokens: boolean; scanWalletForTokens(): any; setWalletTokens(tokens: string[]): any; onAddCustomToken(token: Token): any; onRemoveCustomToken(symbol: string): any; } interface TrackedTokens { [symbol: string]: boolean; } interface State { trackedTokens: TrackedTokens; showCustomTokenForm: boolean; } export default class TokenBalances extends React.PureComponent { public state: State = { trackedTokens: {}, showCustomTokenForm: false }; public UNSAFE_componentWillReceiveProps(nextProps: Props) { if (nextProps.tokenBalances !== this.props.tokenBalances) { const trackedTokens = nextProps.tokenBalances.reduce((prev, t) => { prev[t.symbol] = !t.balance.isZero() || t.custom; return prev; }, {}); this.setState({ trackedTokens }); } } public render() { const { allTokens, tokenBalances, hasSavedWalletTokens } = this.props; const { showCustomTokenForm, trackedTokens } = this.state; let bottom; let help; if (tokenBalances.length && !hasSavedWalletTokens && !this.onlyCustomTokens()) { help = translate('SELECT_WHICH_TOKENS'); bottom = (

{translate('PROMPT_ADD_CUSTOM_TKN')}

); } else if (showCustomTokenForm) { bottom = (
); } else { bottom = (
); } return (
{help &&

{help}

} {tokenBalances.length ? ( {tokenBalances.map( token => token ? ( ) : null )}
) : (
{translate('SCAN_TOKENS_FAIL_NO_TOKENS')}
)} {bottom}
); } private toggleTrack = (symbol: string) => { this.setState({ trackedTokens: { ...this.state.trackedTokens, [symbol]: !this.state.trackedTokens[symbol] } }); }; private toggleShowCustomTokenForm = () => { this.setState({ showCustomTokenForm: !this.state.showCustomTokenForm }); }; /** * * @description Checks if all currently tracked tokens are custom * @private * @returns * @memberof TokenBalances */ private onlyCustomTokens() { const tokenMap = this.props.tokenBalances.reduce<{ [key: string]: walletTypes.TokenBalance }>( (acc, cur) => ({ ...acc, [cur.symbol]: cur }), {} ); return Object.keys(this.state.trackedTokens).reduce( (prev, tokenName) => tokenMap[tokenName].custom && prev, true ); } private addCustomToken = (token: Token) => { this.props.onAddCustomToken(token); this.setState({ showCustomTokenForm: false }); }; private handleSetWalletTokens = () => { const { trackedTokens } = this.state; const desiredTokens = Object.keys(trackedTokens).filter(t => trackedTokens[t]); this.props.setWalletTokens(desiredTokens); }; }