Additional func. component conversions (#1659)

* Additional func. component conversions

* rendering function cleanups (pre-convert)

* Additional

* Forks to functional
This commit is contained in:
Jaco Greeff 2019-09-26 16:16:07 +02:00 committed by GitHub
parent 5485b7d700
commit f5b0247270
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 512 additions and 720 deletions

View File

@ -6,7 +6,7 @@ import { ContractABIFnArg } from '@polkadot/api-contract/types';
import { TypeDef } from '@polkadot/types/types';
import { RawParams } from '@polkadot/react-params/types';
import React from 'react';
import React, { useEffect, useState } from 'react';
import UIParams from '@polkadot/react-params';
import { getTypeDef } from '@polkadot/types';
@ -22,47 +22,34 @@ interface ParamDef {
type: TypeDef;
}
interface State {
params: ParamDef[];
}
export default function Params ({ isDisabled, onChange, onEnter, params: propParams }: Props): React.ReactElement<Props> | null {
const [params, setParams] = useState<ParamDef[]>([]);
export default class Params extends React.PureComponent<Props, State> {
public state: State = { params: [] };
public static getDerivedStateFromProps ({ params }: Props): State | null {
if (!params) {
return { params: [] };
useEffect((): void => {
if (propParams) {
setParams(
propParams.map(({ name, type }): ParamDef => ({
name,
type: getTypeDef(type, name)
}))
);
}
}, [propParams]);
return {
params: params.map(({ name, type }): ParamDef => ({
name,
type: getTypeDef(type, name)
}))
};
if (!params.length) {
return null;
}
public render (): React.ReactNode {
const { isDisabled, onEnter } = this.props;
const { params } = this.state;
if (!params.length) {
return null;
}
return (
<UIParams
isDisabled={isDisabled}
onChange={this.onChange}
onEnter={onEnter}
params={params}
/>
);
}
private onChange = (values: RawParams): void => {
const { onChange } = this.props;
const _onChange = (values: RawParams): void => {
onChange(values.map(({ value }): any => value));
}
};
return (
<UIParams
isDisabled={isDisabled}
onChange={_onChange}
onEnter={onEnter}
params={params}
/>
);
}

View File

@ -7,9 +7,9 @@ import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import { Header } from '@polkadot/types/interfaces';
import React from 'react';
import React, { useContext, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { withApi, withMulti } from '@polkadot/react-api';
import { ApiContext } from '@polkadot/react-api';
import { CardSummary, IdentityIcon, SummaryBox } from '@polkadot/react-components';
import { formatNumber } from '@polkadot/util';
@ -39,12 +39,6 @@ interface Props extends ApiProps, I18nProps {
newHead?: Header;
}
interface State {
numBlocks: number;
numForks: number;
tree?: Link;
}
type UnsubFn = () => void;
interface Col {
@ -151,24 +145,23 @@ function renderCol ({ author, hash, isEmpty, isFinalized, parent, width }: Col,
colSpan={width}
key={`${hash}:${index}:${width}`}
>
{
isEmpty
? <div className='empty' />
: (
<>
{author && (
<IdentityIcon
className='author'
size={28}
value={author}
/>
)}
<div className='contents'>
<div className='hash'>{hash}</div>
<div className='parent'>{parent}</div>
</div>
</>
)
{isEmpty
? <div className='empty' />
: (
<>
{author && (
<IdentityIcon
className='author'
size={28}
value={author}
/>
)}
<div className='contents'>
<div className='hash'>{hash}</div>
<div className='parent'>{parent}</div>
</div>
</>
)
}
</td>
);
@ -210,146 +203,32 @@ function renderRows (rows: Row[]): React.ReactNode[] {
});
}
class Forks extends React.PureComponent<Props, State> {
public state: State = {
numBlocks: 0,
numForks: 0
};
function Forks ({ className, t }: Props): React.ReactElement<Props> | null {
const { api } = useContext(ApiContext);
const [tree, setTree] = useState<Link | null>(null);
const childrenRef = useRef<Map<string, string[]>>(new Map([['root', []]]));
const countRef = useRef({ numBlocks: 0, numForks: 0 });
const headersRef = useRef<Map<string, LinkHeader>>(new Map());
const firstNumRef = useRef('');
private _children: Map<string, string[]> = new Map([['root', []]]);
private _headers: Map<string, LinkHeader> = new Map();
private _firstNum = '';
private _subFinHead: UnsubFn | null = null;
private _subNewHead: UnsubFn | null = null;
// mark as finalized, working down for parents as well
private finalize (hash: string): void {
const hdr = this._headers.get(hash);
const _finalize = (hash: string): void => {
const hdr = headersRef.current.get(hash);
if (hdr && !hdr.isFinalized) {
hdr.isFinalized = true;
this.finalize(hdr.parent);
_finalize(hdr.parent);
}
}
// callback for the subscribe finalized sub
private addFinalized = (header: Header): void => {
this.finalize(header.hash.toHex());
}
// callback for the subscribe headers sub
private addHeader = (header: Header): void => {
const { api } = this.props;
// formatted block info
const bn = formatNumber(header.number);
const hash = header.hash.toHex();
const parent = header.parentHash.toHex();
let isFork = false;
// if this the first one?
if (!this._firstNum) {
this._firstNum = bn;
}
if (!this._headers.has(hash)) {
// if this is the first, add to the root entry
if (this._firstNum === bn) {
(this._children.get('root') as any[]).push(hash);
}
// add to the header map
// also for HeaderExtended header.author ? header.author.toString() : null
this._headers.set(hash, createHdr(bn, hash, parent, null));
// check to see if the children already has a entry
if (this._children.has(parent)) {
isFork = true;
(this._children.get(parent) as any[]).push(hash);
} else {
this._children.set(parent, [hash]);
}
// if we don't have the parent of this one, retrieve it
if (!this._headers.has(parent)) {
// just make sure we are not first in the list, we don't want to full chain
if (this._firstNum !== bn) {
console.warn(`Retrieving missing header ${header.parentHash.toHex()}`);
api.rpc.chain.getHeader(header.parentHash).then(this.addHeader);
// catch the refresh on the result
return;
}
}
// do the magic, extract the info into something useful and add to state
this.setState(({ numBlocks, numForks }): State => ({
numBlocks: numBlocks + 1,
numForks: numForks + (isFork ? 1 : 0),
tree: this.generateTree()
}));
}
}
// on mount, create the subscriptions for heads & finalized
public async componentDidMount (): Promise<void> {
const { api } = this.props;
this._subFinHead = await api.rpc.chain.subscribeFinalizedHeads(this.addFinalized);
this._subNewHead = await api.rpc.chain.subscribeNewHeads(this.addHeader);
}
// unsubscribe when we are unmounting
public componentWillUnmount (): void {
if (this._subFinHead) {
this._subFinHead();
}
if (this._subNewHead) {
this._subNewHead();
}
}
// render the acual component
public render (): React.ReactNode {
const { className, t } = this.props;
const { numBlocks, numForks, tree } = this.state;
if (!tree) {
return null;
}
return (
<div className={className}>
<SummaryBox>
<section>
<CardSummary label={t('blocks')}>{formatNumber(numBlocks)}</CardSummary>
<CardSummary label={t('forks')}>{formatNumber(numForks)}</CardSummary>
</section>
</SummaryBox>
<table>
<tbody>
{renderRows(createRows(tree.arr))}
</tbody>
</table>
</div>
);
}
};
// adds children for a specific header, retrieving based on matching parent
private addChildren (base: LinkHeader, children: LinkArray): LinkArray {
const hdrs = (this._children.get(base.hash) || [])
.map((hash): LinkHeader | null => this._headers.get(hash) || null)
const _addChildren = (base: LinkHeader, children: LinkArray): LinkArray => {
const hdrs = (childrenRef.current.get(base.hash) || [])
.map((hash): LinkHeader | null => headersRef.current.get(hash) || null)
.filter((hdr): boolean => !!hdr) as LinkHeader[];
hdrs.forEach((hdr): void => {
children.push({ arr: this.addChildren(hdr, []), hdr });
children.push({ arr: _addChildren(hdr, []), hdr });
});
// caclulate the max height/width for this entry
@ -368,16 +247,16 @@ class Forks extends React.PureComponent<Props, State> {
});
return children;
}
};
// create a tree list from the available headers
private generateTree (): Link {
const _generateTree = (): Link => {
const root = createLink();
// add all the root entries first, we iterate from these
// We add the root entry explicitly, it exists as per init
(this._children.get('root') as string[]).forEach((hash): void => {
const hdr = this._headers.get(hash);
(childrenRef.current.get('root') as string[]).forEach((hash): void => {
const hdr = headersRef.current.get(hash);
// if this fails, well, we have a bigger issue :(
if (hdr) {
@ -387,7 +266,7 @@ class Forks extends React.PureComponent<Props, State> {
// iterate through, adding the children for each of the root nodes
root.arr.forEach(({ arr, hdr }): void => {
this.addChildren(hdr, arr);
_addChildren(hdr, arr);
});
// align the columns with empty spacers - this aids in display
@ -397,11 +276,107 @@ class Forks extends React.PureComponent<Props, State> {
root.hdr.width = calcWidth(root.arr);
return root;
};
useEffect((): () => void => {
let _subFinHead: UnsubFn | null = null;
let _subNewHead: UnsubFn | null = null;
// callback when finalized
const _newFinalized = (header: Header): void => {
_finalize(header.hash.toHex());
};
// callback for the subscribe headers sub
const _newHeader = (header: Header): void => {
// formatted block info
const bn = formatNumber(header.number);
const hash = header.hash.toHex();
const parent = header.parentHash.toHex();
let isFork = false;
// if this the first one?
if (!firstNumRef.current) {
firstNumRef.current = bn;
}
if (!headersRef.current.has(hash)) {
// if this is the first, add to the root entry
if (firstNumRef.current === bn) {
(childrenRef.current.get('root') as any[]).push(hash);
}
// add to the header map
// also for HeaderExtended header.author ? header.author.toString() : null
headersRef.current.set(hash, createHdr(bn, hash, parent, null));
// check to see if the children already has a entry
if (childrenRef.current.has(parent)) {
isFork = true;
(childrenRef.current.get(parent) as any[]).push(hash);
} else {
childrenRef.current.set(parent, [hash]);
}
// if we don't have the parent of this one, retrieve it
if (!headersRef.current.has(parent)) {
// just make sure we are not first in the list, we don't want to full chain
if (firstNumRef.current !== bn) {
console.warn(`Retrieving missing header ${header.parentHash.toHex()}`);
api.rpc.chain.getHeader(header.parentHash).then(_newHeader);
// catch the refresh on the result
return;
}
}
// update our counters
countRef.current.numBlocks++;
if (isFork) {
countRef.current.numForks++;
}
// do the magic, extract the info into something useful and add to state
setTree(_generateTree());
}
};
(async (): Promise<void> => {
_subFinHead = await api.rpc.chain.subscribeFinalizedHeads(_newFinalized);
_subNewHead = await api.rpc.chain.subscribeNewHeads(_newHeader);
})();
return (): void => {
_subFinHead && _subFinHead();
_subNewHead && _subNewHead();
};
}, []);
if (!tree) {
return null;
}
return (
<div className={className}>
<SummaryBox>
<section>
<CardSummary label={t('blocks')}>{formatNumber(countRef.current.numBlocks)}</CardSummary>
<CardSummary label={t('forks')}>{formatNumber(countRef.current.numForks)}</CardSummary>
</section>
</SummaryBox>
<table>
<tbody>
{renderRows(createRows(tree.arr))}
</tbody>
</table>
</div>
);
}
export default withMulti(
styled(Forks as React.ComponentClass<Props>)`
export default translate(
styled(Forks)`
margin-bottom: 1.5rem;
table {
@ -498,7 +473,5 @@ export default withMulti(
}
}
}
`,
translate,
withApi
`
);

View File

@ -2,17 +2,16 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ApiProps } from '@polkadot/react-api/types';
import { I18nProps } from '@polkadot/react-components/types';
import React from 'react';
import React, { useContext, useState } from 'react';
import { Button, InputAddress, Input, Modal, TxButton } from '@polkadot/react-components';
import { withApi, withMulti } from '@polkadot/react-api';
import { ApiContext } from '@polkadot/react-api';
import ValidationSessionKey from './InputValidationSessionKey';
import translate from '../../translate';
interface Props extends I18nProps, ApiProps {
interface Props extends I18nProps {
controllerId: string;
isOpen: boolean;
onClose: () => void;
@ -20,159 +19,99 @@ interface Props extends I18nProps, ApiProps {
stashId: string;
}
interface State {
// TODO remove once we drop v1 support
ed25519: string | null;
ed25519Error: string | null;
keys: string | null;
}
const EMPTY_PROOF = new Uint8Array();
class SetSessionKey extends React.PureComponent<Props, State> {
public state: State;
function SetSessionKey ({ controllerId, isOpen, onClose, sessionIds, stashId, t }: Props): React.ReactElement<Props> | null {
const { isSubstrateV2 } = useContext(ApiContext);
const [ed25519, setEd25519] = useState<string | null>(null);
const [ed25519Error, setEd25519Error] = useState<string | null>(sessionIds[0] || controllerId);
const [keys, setKeys] = useState<string | null>(null);
public constructor (props: Props) {
super(props);
this.state = {
ed25519: props.sessionIds[0] || props.controllerId,
ed25519Error: null,
keys: null
};
if (!isOpen) {
return null;
}
public render (): React.ReactNode {
const { controllerId, isOpen, isSubstrateV2, onClose, t } = this.props;
const { ed25519, ed25519Error, keys } = this.state;
const hasError = isSubstrateV2
? !keys
: (!ed25519 || !!ed25519Error);
if (!isOpen) {
return null;
}
const hasError = isSubstrateV2
? !keys
: (!ed25519 || !!ed25519Error);
return (
<Modal
className='staking--SetSessionAccount'
dimmer='inverted'
open
size='small'
>
{this.renderContent()}
<Modal.Actions>
<Button.Group>
<Button
isNegative
onClick={onClose}
label={t('Cancel')}
icon='cancel'
/>
<Button.Or />
<TxButton
accountId={controllerId}
isDisabled={hasError}
isPrimary
label={t('Set Session Key')}
icon='sign-in'
onClick={onClose}
params={
isSubstrateV2
? [keys, new Uint8Array()]
: [ed25519]
}
tx={
isSubstrateV2
? 'session.setKeys'
: 'session.setKey'
}
/>
</Button.Group>
</Modal.Actions>
</Modal>
);
}
private renderContent (): React.ReactNode {
const { controllerId, isSubstrateV2, t } = this.props;
return (
<>
<Modal.Header>
{t('Set Session Key')}
</Modal.Header>
<Modal.Content className='ui--signer-Signer-Content'>
<InputAddress
className='medium'
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
{
isSubstrateV2
? this.renderV2Keys()
: this.renderV1Keys()
}
</Modal.Content>
</>
);
}
private renderV1Keys (): React.ReactNode {
const { controllerId, stashId, t } = this.props;
const { ed25519 } = this.state;
return (
<>
return (
<Modal
className='staking--SetSessionAccount'
dimmer='inverted'
open
size='small'
>
<Modal.Header>
{t('Set Session Key')}
</Modal.Header>
<Modal.Content className='ui--signer-Signer-Content'>
<InputAddress
className='medium'
help={t('Changing the key only takes effect at the start of the next session. If validating, it must be an ed25519 key.')}
label={t('Session key (ed25519)')}
onChange={this.onChangeEd25519}
value={ed25519}
defaultValue={controllerId}
isDisabled
label={t('controller account')}
/>
<ValidationSessionKey
controllerId={controllerId}
onError={this.onSessionErrorEd25519}
sessionId={ed25519}
stashId={stashId}
/>
</>
);
}
private renderV2Keys (): React.ReactNode {
const { t } = this.props;
const { keys } = this.state;
return (
<>
<Input
className='medium'
help={t('Changing the key only takes effect at the start of the next session. The input here is generates from the author_rotateKeys command')}
isError={!keys}
label={t('Keys from rotateKeys')}
onChange={this.onChangeKeys}
/>
</>
);
}
private onChangeEd25519 = (ed25519: string | null): void => {
this.setState({ ed25519 });
}
private onChangeKeys = (keys: string): void => {
this.setState({ keys: keys || null });
}
private onSessionErrorEd25519 = (ed25519Error: string | null): void => {
this.setState({ ed25519Error });
}
{isSubstrateV2
? (
<Input
className='medium'
help={t('Changing the key only takes effect at the start of the next session. The input here is generates from the author_rotateKeys command')}
isError={!keys}
label={t('Keys from rotateKeys')}
onChange={setKeys}
/>
)
: (
<>
<InputAddress
className='medium'
help={t('Changing the key only takes effect at the start of the next session. If validating, it must be an ed25519 key.')}
label={t('Session key (ed25519)')}
onChange={setEd25519}
value={ed25519}
/>
<ValidationSessionKey
controllerId={controllerId}
onError={setEd25519Error}
sessionId={ed25519}
stashId={stashId}
/>
</>
)
}
</Modal.Content>
<Modal.Actions>
<Button.Group>
<Button
isNegative
onClick={onClose}
label={t('Cancel')}
icon='cancel'
/>
<Button.Or />
<TxButton
accountId={controllerId}
isDisabled={hasError}
isPrimary
label={t('Set Session Key')}
icon='sign-in'
onClick={onClose}
params={
isSubstrateV2
? [keys, EMPTY_PROOF]
: [ed25519]
}
tx={
isSubstrateV2
? 'session.setKeys'
: 'session.setKey'
}
/>
</Button.Group>
</Modal.Actions>
</Modal>
);
}
export default withMulti(
SetSessionKey,
translate,
withApi
);
export default translate(SetSessionKey);

View File

@ -4,7 +4,7 @@
import { Props } from '../types';
import React from 'react';
import React, { useEffect, useState } from 'react';
import { Compact } from '@polkadot/types';
import { Input } from '@polkadot/react-components';
import { hexToU8a, u8aConcat } from '@polkadot/util';
@ -16,98 +16,67 @@ interface StateParam {
u8a: Uint8Array;
}
interface State {
key: StateParam;
value: StateParam;
}
export function createParam (hex: string, length = -1): StateParam {
let u8a;
export default class KeyValue extends React.PureComponent<Props, State> {
public state: State = {
key: {
isValid: false,
u8a: new Uint8Array([])
},
value: {
isValid: false,
u8a: new Uint8Array([])
}
try {
u8a = hexToU8a(hex);
} catch (error) {
u8a = new Uint8Array([]);
}
const isValid = length !== -1
? u8a.length === length
: u8a.length !== 0;
return {
isValid,
u8a: Compact.addLengthPrefix(u8a)
};
public render (): React.ReactNode {
const { className, isDisabled, label, onEnter, style, withLabel } = this.props;
const { key, value } = this.state;
return (
<Bare
className={className}
style={style}
>
<Input
className='medium'
isDisabled={isDisabled}
isError={!key.isValid}
label={label}
onChange={this.onChangeKey}
placeholder='0x...'
type='text'
withLabel={withLabel}
/>
<Input
className='medium'
isDisabled={isDisabled}
isError={!value.isValid}
onChange={this.onChangeValue}
onEnter={onEnter}
placeholder='0x...'
type='text'
withLabel={withLabel}
/>
</Bare>
);
}
public static createParam (hex: string, length = -1): StateParam {
let u8a;
try {
u8a = hexToU8a(hex);
} catch (error) {
u8a = new Uint8Array([]);
}
const isValid = length !== -1
? u8a.length === length
: u8a.length !== 0;
return {
isValid,
u8a: Compact.addLengthPrefix(u8a)
};
}
private nextState (newState: Partial<State>): void {
this.setState(
(prevState: State, { onChange }: Props): State => {
const { key = prevState.key, value = prevState.value } = newState;
onChange && onChange({
isValid: key.isValid && value.isValid,
value: u8aConcat(
key.u8a,
value.u8a
)
});
return newState as State;
}
);
}
private onChangeKey = (key: string): void => {
this.nextState({ key: KeyValue.createParam(key) });
}
private onChangeValue = (value: string): void => {
this.nextState({ value: KeyValue.createParam(value) });
}
}
export default function KeyValue ({ className, isDisabled, label, onChange, onEnter, style, withLabel }: Props): React.ReactElement<Props> {
const [key, setKey] = useState<StateParam>({ isValid: false, u8a: new Uint8Array([]) });
const [value, setValue] = useState<StateParam>({ isValid: false, u8a: new Uint8Array([]) });
useEffect((): void => {
onChange && onChange({
isValid: key.isValid && value.isValid,
value: u8aConcat(
key.u8a,
value.u8a
)
});
}, [key, value]);
const _onChangeKey = (key: string): void => setKey(createParam(key));
const _onChangeValue = (value: string): void => setValue(createParam(value));
return (
<Bare
className={className}
style={style}
>
<Input
className='medium'
isDisabled={isDisabled}
isError={!key.isValid}
label={label}
onChange={_onChangeKey}
placeholder='0x...'
type='text'
withLabel={withLabel}
/>
<Input
className='medium'
isDisabled={isDisabled}
isError={!value.isValid}
onChange={_onChangeValue}
onEnter={onEnter}
placeholder='0x...'
type='text'
withLabel={withLabel}
/>
</Bare>
);
}

View File

@ -5,7 +5,7 @@
import { KeyValue as Pair } from '@polkadot/types/interfaces';
import { Props as BaseProps, RawParam } from '../types';
import React from 'react';
import React, { useState } from 'react';
import { WithTranslation } from 'react-i18next';
import { Vec } from '@polkadot/types';
import translate from '@polkadot/react-components/translate';
@ -14,14 +14,10 @@ import { assert, isHex, u8aToHex, u8aToString } from '@polkadot/util';
import Base from './Base';
import Bytes from './Bytes';
import File from './File';
import KeyValue from './KeyValue';
import { createParam } from './KeyValue';
interface Props extends BaseProps, WithTranslation {}
interface State {
placeholder?: string;
}
interface Parsed {
isValid: boolean;
value: [Uint8Array, Uint8Array][];
@ -32,43 +28,36 @@ const BYTES_TYPE = {
info: 0
};
class KeyValueArray extends React.PureComponent<Props, State> {
private placeholderEmpty: string;
const EMPTY_PLACEHOLDER = 'click to select or drag and drop JSON key/value (hex-encoded) file';
public constructor (props: Props) {
super(props);
function parseFile (raw: Uint8Array): Parsed {
const json = JSON.parse(u8aToString(raw));
const keys = Object.keys(json);
let isValid = keys.length !== 0;
const value = keys.map((key): [Uint8Array, Uint8Array] => {
const value = json[key];
this.placeholderEmpty = props.t('click to select or drag and drop JSON key/value (hex-encoded) file');
this.state = {
placeholder: this.placeholderEmpty
};
}
assert(isHex(key) && isHex(value), `Non-hex key/value pair found in ${key.toString()} => ${value.toString()}`);
public render (): React.ReactNode {
const { className, isDisabled, isError, label, style, withLabel } = this.props;
const { placeholder } = this.state;
const encKey = createParam(key);
const encValue = createParam(value);
if (isDisabled) {
return this.renderReadOnly();
}
isValid = isValid && encKey.isValid && encValue.isValid;
return (
<File
className={className}
isDisabled={isDisabled}
isError={isError}
label={label}
onChange={this.onChange}
placeholder={placeholder}
style={style}
withLabel={withLabel}
/>
);
}
return [encKey.u8a, encValue.u8a];
});
private renderReadOnly (): React.ReactNode {
const { className, defaultValue: { value }, label, onEnter, style } = this.props;
const pairs = value as Vec<Pair>;
return {
isValid,
value
};
}
function KeyValueArray ({ className, defaultValue, isDisabled, isError, label, onChange, onEnter, style, t, withLabel }: Props): React.ReactElement<Props> {
const [placeholder, setPlaceholder] = useState(t(EMPTY_PLACEHOLDER));
if (isDisabled) {
const pairs = defaultValue.value as Vec<Pair>;
return (
<>
@ -101,53 +90,38 @@ class KeyValueArray extends React.PureComponent<Props, State> {
);
}
private onChange = (raw: Uint8Array): void => {
const { onChange, t } = this.props;
const _onChange = (raw: Uint8Array): void => {
let encoded: Parsed = { isValid: false, value: [] };
try {
encoded = this.parseFile(raw);
encoded = parseFile(raw);
this.setState({
placeholder: t('{{count}} key/value pairs encoded for submission', {
replace: {
count: encoded.value.length
}
})
});
setPlaceholder(t('{{count}} key/value pairs encoded for submission', {
replace: {
count: encoded.value.length
}
}));
} catch (error) {
console.error('Error converting json k/v', error);
this.setState({
placeholder: this.placeholderEmpty
});
setPlaceholder(t(EMPTY_PLACEHOLDER));
}
onChange && onChange(encoded);
}
};
private parseFile (raw: Uint8Array): Parsed {
const json = JSON.parse(u8aToString(raw));
const keys = Object.keys(json);
let isValid = keys.length !== 0;
const value = keys.map((key): [Uint8Array, Uint8Array] => {
const value = json[key];
assert(isHex(key) && isHex(value), `Non-hex key/value pair found in ${key.toString()} => ${value.toString()}`);
const encKey = KeyValue.createParam(key);
const encValue = KeyValue.createParam(value);
isValid = isValid && encKey.isValid && encValue.isValid;
return [encKey.u8a, encValue.u8a];
});
return {
isValid,
value
};
}
return (
<File
className={className}
isDisabled={isDisabled}
isError={isError}
label={label}
onChange={_onChange}
placeholder={placeholder}
style={style}
withLabel={withLabel}
/>
);
}
export default translate(KeyValueArray);

View File

@ -6,7 +6,7 @@ import { WithTranslation } from 'react-i18next';
import { TypeDef } from '@polkadot/types/types';
import { Props as BareProps, RawParam } from '../types';
import React from 'react';
import React, { useEffect, useState } from 'react';
import { Button } from '@polkadot/react-components';
import translate from '@polkadot/react-components/translate';
import { isUndefined } from '@polkadot/util';
@ -17,157 +17,113 @@ import findComponent from './findComponent';
interface Props extends BareProps, WithTranslation {}
interface State {
Component: React.ComponentType<BareProps> | null;
type?: string;
values: RawParam[];
}
function Vector ({ className, defaultValue, isDisabled = false, label, onChange, onEnter, style, t, type, withLabel }: Props): React.ReactElement<Props> | null {
const [Component, setComponent] = useState<React.ComponentType<BareProps> | null>(null);
const [stateType, setStateType] = useState<string | null>(null);
const [values, setValues] = useState<RawParam[]>([]);
class Vector extends React.PureComponent<Props, State> {
public state: State = {
Component: null,
values: []
useEffect((): void => {
const value = defaultValue.value || [];
if (stateType === type.type) {
return;
}
setStateType(type.type);
setComponent((): React.ComponentType<BareProps> => findComponent(type.sub as TypeDef));
setValues(
isDisabled || values.length === 0
? value.map((value: any): RawParam => (
isUndefined(value) || isUndefined(value.isValid)
? {
isValid: !isUndefined(value),
value
}
: value
))
: values
);
}, [type]);
useEffect((): void => {
onChange && onChange({
isValid: values.reduce((result: boolean, { isValid }): boolean => result && isValid, true),
value: values.map(({ value }): any => value)
});
}, [values]);
if (!Component) {
return null;
}
const subType = type.sub as TypeDef;
const _rowAdd = (): void => {
const value = getInitValue(subType);
setValues([...values, {
isValid: !isUndefined(value),
value
}]);
};
const _rowRemove = (): void => {
setValues(values.slice(0, values.length - 1));
};
public static getDerivedStateFromProps ({ defaultValue: { value = [] }, isDisabled, type: { sub, type } }: Props, prevState: State): Partial<State> | null {
if (type === prevState.type) {
return null;
}
const values: RawParam[] = isDisabled || prevState.values.length === 0
? value.map((value: any): RawParam => (
isUndefined(value) || isUndefined(value.isValid)
? {
isValid: !isUndefined(value),
value
}
: value
))
: prevState.values;
return {
Component: findComponent(sub as TypeDef),
type,
values
};
}
public render (): React.ReactNode {
const { className, isDisabled, label, onEnter, style, type, withLabel } = this.props;
const { Component, values } = this.state;
const subType = type.sub as TypeDef;
if (!Component) {
return null;
}
return (
<Base
className={className}
label={label}
style={style}
withLabel={withLabel}
>
{values.map((value, index): React.ReactNode => (
this.isParamHidden(index)
? null
: (
<Component
defaultValue={value}
isDisabled={isDisabled}
isOptional={false}
key={index}
label={`${index}: ${subType.type}`}
onChange={this.onChange(index)}
onEnter={onEnter}
type={subType}
withLabel={withLabel}
/>
)
))}
{this.renderButtons()}
</Base>
);
}
private renderButtons (): React.ReactNode {
const { isDisabled, t } = this.props;
const { values } = this.state;
if (isDisabled) {
return null;
}
return (
<div className='ui--Param-Vector-buttons'>
<Button
isPrimary
onClick={this.rowAdd}
label={t('Add item')}
icon='add'
/>
<Button
isDisabled={values.length === 1}
isNegative
onClick={this.rowRemove}
label={t('Remove item')}
icon='minus'
/>
</div>
);
}
private isParamHidden = (index: number): boolean => {
const { isDisabled, type } = this.props;
const { values } = this.state;
if (type.type === 'Vec<bool>' && isDisabled && values[index].value === false) {
return true;
}
return false;
}
private onChange = (index: number): (value: RawParam) => void => {
return (value: RawParam): void => {
this.setState(
({ values }: State): Pick<State, never> => ({
values: values.map((svalue, sindex): RawParam =>
(sindex === index)
? value
: svalue
return (
<Base
className={className}
label={label}
style={style}
withLabel={withLabel}
>
{values.map((value, index): React.ReactNode => (
// FIXME? This doesn't look quite right - this means that any bool would disappear
// when set to false? At the very least need an explanation here
type.type === 'Vec<bool>' && isDisabled && values[index].value === false
? null
: (
<Component
defaultValue={value}
isDisabled={isDisabled}
isOptional={false}
key={index}
label={`${index}: ${subType.type}`}
onChange={
(value: RawParam): void =>
setValues(
values.map((svalue, sindex): RawParam =>
(sindex === index)
? value
: svalue
)
)
}
onEnter={onEnter}
type={subType}
withLabel={withLabel}
/>
)
}),
(): void => {
const { values } = this.state;
const { onChange } = this.props;
onChange && onChange({
isValid: values.reduce((result: boolean, { isValid }): boolean => result && isValid, true),
value: values.map(({ value }): any => value)
});
}
);
};
}
private rowAdd = (): void => {
this.setState(({ values }: State, { type: { sub } }: Props): Pick<State, never> => {
const value = getInitValue(sub as TypeDef);
return {
values: values.concat({
isValid: !isUndefined(value),
value
})
};
});
}
private rowRemove = (): void => {
this.setState(({ values }: State): Pick<State, never> => ({
values: values.slice(0, values.length - 1)
}));
}
))}
{!isDisabled && (
<div className='ui--Param-Vector-buttons'>
<Button
isPrimary
onClick={_rowAdd}
label={t('Add item')}
icon='add'
/>
<Button
isDisabled={values.length === 1}
isNegative
onClick={_rowRemove}
label={t('Remove item')}
icon='minus'
/>
</div>
)}
</Base>
);
}
export default translate(Vector);

View File

@ -35,6 +35,8 @@ interface State {
values?: RawParams;
}
const DISABLED_OPTIONAL = { isValid: true, value: undefined };
class Params extends React.PureComponent<Props, State> {
public state: State;
@ -104,7 +106,8 @@ class Params extends React.PureComponent<Props, State> {
}
public render (): React.ReactNode {
const { className, params, style } = this.props;
const { className, isDisabled, onEnter, overrides, params, style } = this.props;
const { handlersChange = [], handlersOption = [], optional = [], values = this.props.values } = this.state;
if (!params || params.length === 0) {
return null;
@ -116,63 +119,54 @@ class Params extends React.PureComponent<Props, State> {
style={style}
>
<div className='ui--Params-Content'>
{params.map(this.renderComponent)}
{params.map(({ isOptional = false, name, type }: ParamDef, index: number): React.ReactNode => {
if (!values || values.length === 0) {
return null;
}
const isDisabledOptional = isOptional && !optional[index];
const key = `${name}:${type}:${index}`;
return (
<div
className='ui--Param-composite'
key={key}
>
<Param
defaultValue={
isDisabledOptional
? DISABLED_OPTIONAL
: values[index]
}
isDisabled={isDisabled || isDisabledOptional}
isOptional={isOptional}
key={`input:${key}`}
name={name}
onChange={handlersChange[index]}
onEnter={onEnter}
overrides={overrides}
type={type}
/>
{isOptional && (
<Toggle
className='ui--Param-overlay'
key={`option:${key}`}
label={
optional[index]
? 'include option'
: 'exclude option'
}
onChange={handlersOption[index]}
/>
)}
</div>
);
})}
</div>
</div>
);
}
private renderComponent = ({ isOptional = false, name, type }: ParamDef, index: number): React.ReactNode => {
const { isDisabled, onEnter, overrides } = this.props;
const { handlersChange = [], handlersOption = [], optional = [], values = this.props.values } = this.state;
const key = `${name}:${type}:${index}`;
if (!values || values.length === 0) {
return null;
}
const isDisabledOptional = isOptional && !optional[index];
return (
<div
className='ui--Param-composite'
key={key}
>
<Param
defaultValue={
isDisabledOptional
? { isValid: true, value: undefined }
: values[index]
}
isDisabled={isDisabled || isDisabledOptional}
isOptional={isOptional}
key={`input:${key}`}
name={name}
onChange={handlersChange[index]}
onEnter={onEnter}
overrides={overrides}
type={type}
/>
{
isOptional
? (
<Toggle
className='ui--Param-overlay'
key={`option:${key}`}
label={
optional[index]
? 'include option'
: 'exclude option'
}
onChange={handlersOption[index]}
/>
)
: null
}
</div>
);
}
private extractValues (): RawParam[] {
const { optional, values } = this.state;
const { isDisabled } = this.props;