Add multi-address selection component (#2028)

This commit is contained in:
Jaco Greeff 2019-12-10 16:20:14 +01:00 committed by GitHub
parent d1c8cffaa1
commit ef388226b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 286 additions and 209 deletions

View File

@ -10,81 +10,28 @@ import { ComponentProps } from './types';
import BN from 'bn.js';
import React from 'react';
import { withApi } from '@polkadot/react-api';
import styled from 'styled-components';
import { AddressMini, Button, Toggle } from '@polkadot/react-components';
import { AddressMulti, Button } from '@polkadot/react-components';
import TxModal, { TxModalState, TxModalProps } from '@polkadot/react-components/TxModal';
import translate from '../translate';
import VoteValue from './VoteValue';
type VoteType = 'member' | 'runnerup' | 'candidate';
interface Props extends ApiProps, ComponentProps, TxModalProps {}
interface State extends TxModalState {
votes: Record<string, boolean>;
votes: string[];
voteValue: BN;
}
// const MAX_VOTES = 16;
const Candidates = styled.div`
display: flex;
flex-wrap: wrap;
justify-content: center;
.candidate {
border: 1px solid #eee;
border-radius: 0.25rem;
margin: 0.25rem;
padding: 0 0.5rem 0.25rem;
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
right: 0;
border-color: transparent;
border-style: solid;
border-radius: 0.25em;
border-width: 0.25em;
}
&.isAye {
background: #fff;
border-color: #ccc;
}
&.member::after {
border-color: green;
}
&.runnerup::after {
border-color: steelblue;
}
.ui--AddressMini-icon {
z-index: 1;
}
.candidate-right {
text-align: right;
}
}
`;
const MAX_VOTES = 16;
class Vote extends TxModal<Props, State> {
public static emptyApprovals (length: number): boolean[] {
return [...new Array(length).keys()].map((): boolean => false);
}
constructor (props: Props) {
super(props);
this.defaultState = {
...this.defaultState,
votes: {},
votes: [],
voteValue: new BN(0)
};
@ -107,20 +54,13 @@ class Vote extends TxModal<Props, State> {
protected txParams = (): [boolean[] | null, VoteIndex, BN | null] | [string[], BN] => {
const { votes, voteValue } = this.state;
return [
Object
.entries(votes)
.filter(([, vote]): boolean => vote)
.map(([accountId]): string => accountId),
voteValue
];
return [votes, voteValue];
}
protected isDisabled = (): boolean => {
const { accountId, votes } = this.state;
const hasApprovals = Object.values(votes).some((vote): boolean => vote);
return !accountId || !hasApprovals;
return !accountId || votes.length === 0;
}
protected renderTrigger = (): React.ReactNode => {
@ -144,11 +84,10 @@ class Vote extends TxModal<Props, State> {
protected renderContent = (): React.ReactNode => {
const { electionsInfo: { candidates, members, runnersUp }, t } = this.props;
const { accountId, votes } = this.state;
const _candidates = candidates.map((accountId): [AccountId, VoteType] => [accountId, 'candidate']);
const available = members
.map(([accountId]): [AccountId, VoteType] => [accountId, 'member'])
.concat(runnersUp.map(([accountId]): [AccountId, VoteType] => [accountId, 'runnerup']))
.concat(_candidates);
.map(([accountId]): string => accountId.toString())
.concat(runnersUp.map(([accountId]): string => accountId.toString()))
.concat(candidates.map((accountId): string => accountId.toString()));
return (
<>
@ -156,32 +95,14 @@ class Vote extends TxModal<Props, State> {
accountId={accountId}
onChange={this.setVoteValue}
/>
<Candidates>
{available.map(([accountId, type]): React.ReactNode => {
const key = accountId.toString();
const isAye = votes[key] || false;
return (
<AddressMini
className={`candidate ${isAye ? 'isAye' : 'isNay'} ${type}`}
key={key}
value={key}
>
<div className='candidate-right'>
<Toggle
label={
isAye
? t('Aye')
: t('Nay')
}
onChange={this.onChangeVote(key)}
value={isAye}
/>
</div>
</AddressMini>
);
})}
</Candidates>
<AddressMulti
available={available}
help={t('Filter available candidates based on name, address or short account index.')}
label={t('filter candidates')}
maxCount={MAX_VOTES}
onChange={this.onChangeVotes}
value={votes}
/>
</>
);
}
@ -199,22 +120,14 @@ class Vote extends TxModal<Props, State> {
(api.query.electionsPhragmen || api.query.elections)
.votesOf<[AccountId[]] & Codec>(accountId)
.then(([existingVotes]): void => {
existingVotes.forEach((accountId): void => {
this.onChangeVote(accountId.toString())(true);
});
this.setState({ votes: existingVotes.map((accountId): string => accountId.toString()) });
});
}
}
private onChangeVote = (accountId: string): (isChecked: boolean) => void =>
(isChecked: boolean): void => {
this.setState(({ votes }: State): Pick<State, never> => ({
votes: {
...votes,
[accountId]: isChecked
}
}));
}
private onChangeVotes = (votes: string[]): void => {
this.setState({ votes });
}
}
export default translate(withApi(Vote));

View File

@ -2,12 +2,12 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DerivedStakingOverview } from '@polkadot/api-derive/types';
import { I18nProps } from '@polkadot/react-components/types';
import { KeyringSectionOption } from '@polkadot/ui-keyring/options/types';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { AddressMini, Button, InputAddress, Modal, Toggle, TxButton } from '@polkadot/react-components';
import { AddressMulti, Button, InputAddress, Modal, TxButton } from '@polkadot/react-components';
import { useFavorites } from '@polkadot/react-hooks';
import { STORE_FAVS_BASE } from '../../constants';
@ -15,59 +15,47 @@ import translate from '../../translate';
interface Props extends I18nProps {
controllerId: string;
next: string[];
nominees?: string[];
onClose: () => void;
stakingOverview?: DerivedStakingOverview;
stashId: string;
stashOptions: KeyringSectionOption[];
}
// We only allow a maximum of 16 nominees, negative to slice
const MAX_NOMINEES = -16;
const MAX_NOMINEES = 16;
function Nominate ({ className, controllerId, nominees, onClose, stashId, stashOptions, t }: Props): React.ReactElement<Props> | null {
function Nominate ({ className, controllerId, nominees, onClose, next, stakingOverview, stashId, t }: Props): React.ReactElement<Props> | null {
const [favorites] = useFavorites(STORE_FAVS_BASE);
const [next, setNext] = useState<string[] | undefined>();
const [{ options, shortlist }, setShortlist] = useState<{ options: KeyringSectionOption[]; shortlist: string[] }>({ options: [], shortlist: [] });
const [validators, setValidators] = useState<string[]>([]);
const [selection, setSelection] = useState<string[]>([]);
const [available, setAvailable] = useState<string[]>([]);
useEffect((): void => {
if (!next && nominees) {
setNext(nominees);
if (!selection.length && nominees) {
setSelection(nominees);
}
}, [next, nominees]);
}, [selection, nominees]);
useEffect((): void => {
if (nominees) {
const _favorites = favorites.filter((accountId): boolean =>
stashOptions.some(({ value }): boolean => value === accountId)
);
const shortlist = [
// ensure that the favorite is included in the list of stashes
..._favorites,
// make sure the nominee is not in our favorites already
...nominees.filter((accountId): boolean => !_favorites.includes(accountId))
];
setShortlist({
options: stashOptions.filter(({ value }): boolean => !shortlist.includes(value as string)),
shortlist
});
if (stakingOverview) {
setValidators((stakingOverview.currentElected || []).map((acc): string => acc.toString()));
}
}, [favorites, nominees, stashOptions]);
}, [stakingOverview]);
const _onChangeNominees = (_nominees: string[]): void => {
const newNominees = _nominees.slice(MAX_NOMINEES);
useEffect((): void => {
const shortlist = [
// ensure that the favorite is included in the list of stashes
...favorites.filter((acc): boolean => validators.includes(acc) || next.includes(acc)),
// make sure the nominee is not in our favorites already
...(nominees || []).filter((acc): boolean => !favorites.includes(acc))
];
if (JSON.stringify(newNominees) !== JSON.stringify(nominees)) {
setNext(newNominees);
}
};
const _onToggleNominee = (nominee: string): void =>
setNext(
(next || []).includes(nominee)
? (next || []).filter((accountId): boolean => accountId !== nominee)
: [...(next || []), nominee].slice(MAX_NOMINEES)
);
setAvailable([
...shortlist,
...validators.filter((acc): boolean => !shortlist.includes(acc)),
...next.filter((acc): boolean => !shortlist.includes(acc))
]);
}, [favorites, next, nominees, validators]);
return (
<Modal
@ -88,46 +76,15 @@ function Nominate ({ className, controllerId, nominees, onClose, stashId, stashO
isDisabled
label={t('stash account')}
/>
<InputAddress
<AddressMulti
available={available}
className='medium'
help={t('Stash accounts that are to be nominated. Block rewards are split between validators and nominators. Only 16 nominees will be taken into account.')}
isInput={false}
isMultiple
label={t('nominate the following addresses')}
onChangeMulti={_onChangeNominees}
options={options}
placeholder={t('select accounts(s) nominate')}
type='account'
value={next || []}
help={t('Filter available candidates based on name, address or short account index.')}
label={t('filter candidates')}
maxCount={MAX_NOMINEES}
onChange={setSelection}
value={selection}
/>
{shortlist.length !== 0 && (
<div className='shortlist'>
{shortlist.map((address): React.ReactNode => {
const isAye = next?.includes(address);
const _onChange = (): void => _onToggleNominee(address);
return (
<AddressMini
className={`candidate ${isAye ? 'isAye' : 'isNay'}`}
key={address}
value={address}
>
<div className='candidate-right'>
<Toggle
label={
isAye
? t('Aye')
: t('Nay')
}
onChange={_onChange}
value={isAye}
/>
</div>
</AddressMini>
);
})}
</div>
)}
</Modal.Content>
<Modal.Actions>
<Button.Group>
@ -140,10 +97,10 @@ function Nominate ({ className, controllerId, nominees, onClose, stashId, stashO
<Button.Or />
<TxButton
accountId={controllerId}
isDisabled={!next || next.length === 0}
isDisabled={!selection.length}
isPrimary
onClick={onClose}
params={[next]}
params={[selection]}
label={t('Nominate')}
icon='hand paper outline'
tx='staking.nominate'

View File

@ -3,11 +3,10 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DerivedBalances, DerivedStakingAccount, DerivedHeartbeats } from '@polkadot/api-derive/types';
import { DerivedBalances, DerivedStakingAccount, DerivedStakingOverview, DerivedHeartbeats } from '@polkadot/api-derive/types';
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import { AccountId, Exposure, StakingLedger, ValidatorPrefs } from '@polkadot/types/interfaces';
import { KeyringSectionOption } from '@polkadot/ui-keyring/options/types';
import React from 'react';
import styled from 'styled-components';
@ -30,10 +29,11 @@ interface Props extends ApiProps, I18nProps {
balances_all?: DerivedBalances;
className?: string;
isOwnStash: boolean;
next: string[];
recentlyOnline?: DerivedHeartbeats;
staking_account?: DerivedStakingAccount;
stakingOverview?: DerivedStakingOverview;
stashId: string;
stashOptions: KeyringSectionOption[];
}
interface State {
@ -235,7 +235,7 @@ class Account extends React.PureComponent<Props, State> {
}
private renderNominate (): React.ReactNode {
const { stashId, stashOptions } = this.props;
const { next, stakingOverview, stashId } = this.props;
const { controllerId, isNominateOpen, nominees } = this.state;
if (!isNominateOpen || !stashId || !controllerId) {
@ -245,10 +245,11 @@ class Account extends React.PureComponent<Props, State> {
return (
<Nominate
controllerId={controllerId}
next={next}
nominees={nominees}
onClose={this.toggleNominate}
stakingOverview={stakingOverview}
stashId={stashId}
stashOptions={stashOptions}
/>
);
}

View File

@ -2,18 +2,15 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DerivedHeartbeats } from '@polkadot/api-derive/types';
import { DerivedHeartbeats, DerivedStakingOverview } from '@polkadot/api-derive/types';
import { I18nProps } from '@polkadot/react-components/types';
import { KeyringSectionOption } from '@polkadot/ui-keyring/options/types';
import { AccountId, StakingLedger } from '@polkadot/types/interfaces';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Button, CardGrid } from '@polkadot/react-components';
import { useCall, useApi, useAccounts } from '@polkadot/react-hooks';
import { AccountName } from '@polkadot/react-query';
import { Option } from '@polkadot/types';
import createOption from '@polkadot/ui-keyring/options/item';
import Account from './Account';
import StartStaking from './NewStake';
@ -23,6 +20,8 @@ interface Props extends I18nProps {
allStashes: string[];
isVisible: boolean;
recentlyOnline?: DerivedHeartbeats;
next: string[];
stakingOverview?: DerivedStakingOverview;
}
function getStashes (allAccounts: string[], queryBonded?: Option<AccountId>[], queryLedger?: Option<StakingLedger>[]): [string, boolean][] | null {
@ -47,22 +46,13 @@ function getStashes (allAccounts: string[], queryBonded?: Option<AccountId>[], q
return result;
}
function Actions ({ allStashes, className, isVisible, recentlyOnline, t }: Props): React.ReactElement<Props> {
function Actions ({ allStashes, className, isVisible, next, recentlyOnline, stakingOverview, t }: Props): React.ReactElement<Props> {
const { api } = useApi();
const { allAccounts } = useAccounts();
const queryBonded = useCall<Option<AccountId>[]>(api.query.staking.bonded.multi as any, [allAccounts]);
const queryLedger = useCall<Option<StakingLedger>[]>(api.query.staking.ledger.multi as any, [allAccounts]);
const [isNewStakeOpen, setIsNewStateOpen] = useState(false);
const [foundStashes, setFoundStashes] = useState<[string, boolean][] | null>(null);
const [stashOptions, setStashOptions] = useState<KeyringSectionOption[]>([]);
useEffect((): void => {
setStashOptions(
allStashes.map((stashId): KeyringSectionOption =>
createOption(stashId, (<AccountName params={stashId} />) as any)
)
);
}, [allStashes]);
useEffect((): void => {
setFoundStashes(getStashes(allAccounts, queryBonded, queryLedger));
@ -89,15 +79,16 @@ function Actions ({ allStashes, className, isVisible, recentlyOnline, t }: Props
{isNewStakeOpen && (
<StartStaking onClose={_toggleNewStake} />
)}
{foundStashes && foundStashes.map(([stashId, isOwnStash], index): React.ReactNode => (
{foundStashes?.map(([stashId, isOwnStash], index): React.ReactNode => (
stashId && (
<Account
allStashes={allStashes}
isOwnStash={isOwnStash}
key={index}
next={next}
recentlyOnline={recentlyOnline}
stakingOverview={stakingOverview}
stashId={stashId}
stashOptions={stashOptions}
/>
)
))}

View File

@ -121,6 +121,8 @@ function App ({ basePath, className, t }: Props): React.ReactElement<Props> {
allStashes={allStashes}
isVisible={pathname === `${basePath}/actions`}
recentlyOnline={recentlyOnline}
next={next}
stakingOverview={stakingOverview}
/>
<Overview
hasQueries={hasQueries}

View File

@ -0,0 +1,96 @@
// Copyright 2017-2019 @polkadot/react-components authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { I18nProps } from './types';
import React, { useState } from 'react';
import styled from 'styled-components';
import { useDebounce } from '@polkadot/react-hooks';
import translate from './translate';
import AddressToggle from './AddressToggle';
import Input from './Input';
interface Props extends I18nProps {
available: string[];
className?: string;
help: React.ReactNode;
label: React.ReactNode;
maxCount: number;
onChange: (values: string[]) => void;
value: string[];
}
function AddressMulti ({ available, className, help, label, maxCount, onChange, t, value }: Props): React.ReactElement<Props> {
const [_filter, setFilter] = useState<string>('');
const filter = useDebounce(_filter);
const _onClick = (key: string): (isChecked: boolean) => void =>
(isChecked: boolean): void => {
let newValues = value.filter((address): boolean => address !== key);
if (isChecked) {
newValues = [key].concat(newValues).slice(0, maxCount);
}
onChange(newValues);
};
return (
<div className={`ui--AddressMulti ${className}`}>
<Input
autoFocus
className='ui--AddressMulti-input'
help={help}
label={label}
onChange={setFilter}
placeholder={t('partial name, address or account index')}
value={_filter}
/>
<div className='ui--AddressMulti-container'>
{available.map((key): React.ReactNode => (
<AddressToggle
address={key}
filter={filter}
key={key}
onChange={_onClick(key)}
value={value.includes(key)}
/>
))}
</div>
</div>
);
}
export default translate(
styled(AddressMulti)`
.ui--AddressMulti-input {
.ui.input {
margin-bottom: 0rem;
input {
border-bottom-width: 0px;
border-bottom-right-radius: 0px;
border-bottom-left-radius: 0px;
}
}
}
.ui--AddressMulti-container {
background: white;
border: 1px solid rgba(34,36,38,.15);
border-top-width: 0px;
border-radius: 0 0 0.25rem 0.25rem;
margin-left: 2rem;
max-height: 15rem;
overflow-y: scroll;
padding: 0.25rem 0.5rem;
display: flex;
flex-wrap: wrap;
justify-content: center;
.ui--AddressToggle {}
}
`
);

View File

@ -0,0 +1,115 @@
// Copyright 2017-2019 @polkadot/react-components authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { DeriveAccountInfo } from '@polkadot/api-derive/types';
import { I18nProps } from './types';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { getAddressName } from './util';
import translate from './translate';
import AddressMini from './AddressMini';
import Toggle from './Toggle';
interface Props extends I18nProps {
address: string;
className?: string;
filter?: string;
onChange?: (isChecked: boolean) => void;
value: boolean;
}
function AddressToggle ({ address, className, filter, onChange, value }: Props): React.ReactElement<Props> | null {
const { api } = useApi();
const info = useCall<DeriveAccountInfo>(api.derive.accounts.info as any, [address]);
const [isFiltered, setIsFiltered] = useState(false);
useEffect((): void => {
const [,, extracted] = getAddressName(address);
let isFiltered = true;
if (!filter || address.includes(filter) || extracted.toLowerCase().includes(filter)) {
isFiltered = false;
} else if (info) {
const { accountId, accountIndex, nickname } = info;
if (accountId?.toString().includes(filter) || accountIndex?.toString().includes(filter) || nickname?.toLowerCase().includes(filter)) {
isFiltered = false;
}
}
setIsFiltered(isFiltered);
}, [filter, info, value]);
if (isFiltered) {
return null;
}
const _onClick = (): void => onChange && onChange(!value);
return (
<div
className={`ui--AddressToggle ${className} ${value ? 'isAye' : 'isNay'}`}
onClick={_onClick}
>
<AddressMini
className='ui--AddressToggle-address'
value={address}
/>
<div className='ui--AddressToggle-toggle'>
<Toggle
label=''
onChange={onChange}
value={value}
/>
</div>
</div>
);
}
export default translate(
styled(AddressToggle)`
align-items: flex-start;
border: 1px solid transparent; /* #eee */
border-radius: 0.25rem;
cursor: pointer;
display: flex;
justify-content: space-between;
margin: 0.125rem;
padding: 0.125rem 0.25rem;
text-align: left;
vertical-align: middle;
white-space: nowrap;
.ui--AddressToggle-address {
filter: grayscale(100%);
opacity: 0.5;
}
&:hover {
border-color: #ccc;
}
&.isAye {
.ui--AddressToggle-address {
filter: none;
opacity: 1;
}
/* border-color: #ccc; */
}
.ui--AddressToggle-address,
.ui--AddressToggle-toggle {
flex: 1;
padding: 0;
}
.ui--AddressToggle-toggle {
margin-top: 0.1rem;
text-align: right;
}
`
);

View File

@ -6,8 +6,10 @@ export { default as ActionItem } from './ActionItem';
export { default as AddressCard } from './AddressCard';
export { default as AddressInfo } from './AddressInfo';
export { default as AddressMini } from './AddressMini';
export { default as AddressMulti } from './AddressMulti';
export { default as AddressRow } from './AddressRow';
export { default as AddressSmall } from './AddressSmall';
export { default as AddressToggle } from './AddressToggle';
export { default as Available } from './Available';
export { default as Badge } from './Badge';
export { default as Balance } from './Balance';