From f5b02472708366744b835c8080d3407d7761b0df Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Thu, 26 Sep 2019 16:16:07 +0200 Subject: [PATCH] Additional func. component conversions (#1659) * Additional func. component conversions * rendering function cleanups (pre-convert) * Additional * Forks to functional --- packages/app-contracts/src/Params.tsx | 63 ++-- packages/app-explorer/src/Forks.tsx | 303 ++++++++---------- .../src/Actions/Account/SetSessionAccount.tsx | 239 +++++--------- packages/react-params/src/Param/KeyValue.tsx | 155 ++++----- .../react-params/src/Param/KeyValueArray.tsx | 120 +++---- packages/react-params/src/Param/Vector.tsx | 252 ++++++--------- packages/react-params/src/index.tsx | 100 +++--- 7 files changed, 512 insertions(+), 720 deletions(-) diff --git a/packages/app-contracts/src/Params.tsx b/packages/app-contracts/src/Params.tsx index 6e2731713a..1031061d77 100644 --- a/packages/app-contracts/src/Params.tsx +++ b/packages/app-contracts/src/Params.tsx @@ -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 | null { + const [params, setParams] = useState([]); -export default class Params extends React.PureComponent { - 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 ( - - ); - } - - private onChange = (values: RawParams): void => { - const { onChange } = this.props; - + const _onChange = (values: RawParams): void => { onChange(values.map(({ value }): any => value)); - } + }; + + return ( + + ); } diff --git a/packages/app-explorer/src/Forks.tsx b/packages/app-explorer/src/Forks.tsx index c052cd0558..c1ecce814c 100644 --- a/packages/app-explorer/src/Forks.tsx +++ b/packages/app-explorer/src/Forks.tsx @@ -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 - ?
- : ( - <> - {author && ( - - )} -
-
{hash}
-
{parent}
-
- - ) + {isEmpty + ?
+ : ( + <> + {author && ( + + )} +
+
{hash}
+
{parent}
+
+ + ) } ); @@ -210,146 +203,32 @@ function renderRows (rows: Row[]): React.ReactNode[] { }); } -class Forks extends React.PureComponent { - public state: State = { - numBlocks: 0, - numForks: 0 - }; +function Forks ({ className, t }: Props): React.ReactElement | null { + const { api } = useContext(ApiContext); + const [tree, setTree] = useState(null); + const childrenRef = useRef>(new Map([['root', []]])); + const countRef = useRef({ numBlocks: 0, numForks: 0 }); + const headersRef = useRef>(new Map()); + const firstNumRef = useRef(''); - private _children: Map = new Map([['root', []]]); - - private _headers: Map = 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 { - 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 ( -
- -
- {formatNumber(numBlocks)} - {formatNumber(numForks)} -
-
- - - {renderRows(createRows(tree.arr))} - -
-
- ); - } + }; // 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 { }); 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 { // 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 { 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 => { + _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 ( +
+ +
+ {formatNumber(countRef.current.numBlocks)} + {formatNumber(countRef.current.numForks)} +
+
+ + + {renderRows(createRows(tree.arr))} + +
+
+ ); } -export default withMulti( - styled(Forks as React.ComponentClass)` +export default translate( + styled(Forks)` margin-bottom: 1.5rem; table { @@ -498,7 +473,5 @@ export default withMulti( } } } - `, - translate, - withApi + ` ); diff --git a/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx b/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx index 2b4bcd23ed..fe918c0745 100644 --- a/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx +++ b/packages/app-staking/src/Actions/Account/SetSessionAccount.tsx @@ -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 { - public state: State; +function SetSessionKey ({ controllerId, isOpen, onClose, sessionIds, stashId, t }: Props): React.ReactElement | null { + const { isSubstrateV2 } = useContext(ApiContext); + const [ed25519, setEd25519] = useState(null); + const [ed25519Error, setEd25519Error] = useState(sessionIds[0] || controllerId); + const [keys, setKeys] = useState(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 ( - - {this.renderContent()} - - -
- ); - } - - private isParamHidden = (index: number): boolean => { - const { isDisabled, type } = this.props; - const { values } = this.state; - - if (type.type === 'Vec' && 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 => ({ - values: values.map((svalue, sindex): RawParam => - (sindex === index) - ? value - : svalue + return ( + + {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' && isDisabled && values[index].value === false + ? null + : ( + + 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 => { - const value = getInitValue(sub as TypeDef); - - return { - values: values.concat({ - isValid: !isUndefined(value), - value - }) - }; - }); - } - - private rowRemove = (): void => { - this.setState(({ values }: State): Pick => ({ - values: values.slice(0, values.length - 1) - })); - } + ))} + {!isDisabled && ( +
+
+ )} + + ); } export default translate(Vector); diff --git a/packages/react-params/src/index.tsx b/packages/react-params/src/index.tsx index fdc400837e..ca72afc903 100644 --- a/packages/react-params/src/index.tsx +++ b/packages/react-params/src/index.tsx @@ -35,6 +35,8 @@ interface State { values?: RawParams; } +const DISABLED_OPTIONAL = { isValid: true, value: undefined }; + class Params extends React.PureComponent { public state: State; @@ -104,7 +106,8 @@ class Params extends React.PureComponent { } 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 { style={style} >
- {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 ( +
+ + {isOptional && ( + + )} +
+ ); + })}
); } - 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 ( -
- - { - isOptional - ? ( - - ) - : null - } -
- ); - } - private extractValues (): RawParam[] { const { optional, values } = this.state; const { isDisabled } = this.props;