Complete eslint swap (#1407)

This commit is contained in:
Jaco Greeff 2019-07-16 11:56:40 +02:00 committed by GitHub
parent 1c57182b6d
commit 8bb35dd9ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
79 changed files with 300 additions and 251 deletions

View File

@ -25,8 +25,7 @@
"build": "NODE_ENV=production polkadot-dev-build-ts",
"check": "yarn lint",
"clean": "polkadot-dev-clean-build",
"lint": "tslint --project . && tsc --noEmit --pretty",
"lint:new": "eslint --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
"lint": "eslint --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
"postinstall": "polkadot-dev-yarn-only",
"test": "echo \"skipping tests\"",
"vanitygen": "node packages/app-accounts/scripts/vanitygen.js",

View File

@ -201,7 +201,7 @@ class VanityApp extends TxComponent<Props, State> {
}
this.setState(
({ keyCount, keyTime, matches, startAt }: State) => {
({ keyCount, keyTime, matches, startAt }: State): Pick<State, never> => {
let newKeyCount = keyCount;
let newKeyTime = keyTime;
const newMatches = results
@ -279,7 +279,7 @@ class VanityApp extends TxComponent<Props, State> {
private onRemove = (address: string): void => {
this.setState(
({ matches }: State) => ({
({ matches }: State): Pick<State, never> => ({
matches: matches.filter((item): boolean =>
item.address !== address
)
@ -289,7 +289,7 @@ class VanityApp extends TxComponent<Props, State> {
private toggleStart = (): void => {
this.setState(
({ isRunning, keyCount, keyTime, startAt }: State) => {
({ isRunning, keyCount, keyTime, startAt }: State): Pick<State, never> => {
this._isActive = !isRunning;
return {

View File

@ -8,7 +8,7 @@ import generate from './generate';
export default function generator (options: GeneratorOptions): GeneratorResult {
const { match, runs = 10, withCase = false } = options;
const test = (withCase ? match : match.toLowerCase()).split(',').map((c) => c.split(''));
const test = (withCase ? match : match.toLowerCase()).split(',').map((c): string[] => c.split(''));
const startAt = Date.now();
const found: GeneratorMatches = [];

View File

@ -112,6 +112,10 @@ class ABI extends React.PureComponent<Props, State> {
const { help, isDisabled, label, onRemove } = this.props;
const { contractAbi } = this.state;
if (!contractAbi) {
return null;
}
return (
<Labelled
label={label}
@ -119,7 +123,7 @@ class ABI extends React.PureComponent<Props, State> {
withLabel={!!label}
>
<Messages
contractAbi={contractAbi!}
contractAbi={contractAbi}
onRemove={onRemove || this.onRemove}
isLabelled={!!label}
isRemovable={!isDisabled}

View File

@ -32,6 +32,8 @@ export interface ContractModalState {
}
class ContractModal<P extends ContractModalProps, S extends ContractModalState> extends TxComponent<P, S> {
// horrible :(
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
protected defaultState: S = {
accountId: null,
gasLimit: new BN(0),
@ -47,7 +49,8 @@ class ContractModal<P extends ContractModalProps, S extends ContractModalState>
protected isContract?: boolean;
public componentWillReceiveProps ({ isOpen }: P, _: S): void {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public componentWillReceiveProps ({ isOpen }: P, prevState: S): void {
if (isOpen && !this.props.isOpen && !this.state.isBusy) {
this.reset();
}
@ -78,9 +81,9 @@ class ContractModal<P extends ContractModalProps, S extends ContractModalState>
protected headerText: string = '';
protected renderContent: () => React.ReactNode | null = () => null;
protected renderContent: () => React.ReactNode | null = (): React.ReactNode => null;
protected renderButtons: () => React.ReactNode | null = () => null;
protected renderButtons: () => React.ReactNode | null = (): React.ReactNode => null;
protected renderInputAbi (): React.ReactNode {
const { t } = this.props;

View File

@ -3,6 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { AppProps, I18nProps } from '@polkadot/ui-app/types';
import { TabItem } from '@polkadot/ui-app/Tabs';
import { ComponentProps, LocationProps } from './types';
import React from 'react';
@ -81,7 +82,7 @@ class App extends React.PureComponent<Props, State> {
name: 'contracts',
text: 'Contracts'
}
].map((tab) => ({ ...tab, text: t(tab.text) }))
].map((tab): TabItem => ({ ...tab, text: t(tab.text) }))
}
/>
</header>

View File

@ -24,7 +24,7 @@ interface State extends TxModalState {
}
class Propose extends TxModal<Props, State> {
constructor (props: Props) {
public constructor (props: Props) {
super(props);
this.defaultState = {

View File

@ -11,13 +11,13 @@ import { formatNumber } from '@polkadot/util';
import translate from '../translate';
type Props = I18nProps & {
address: string,
block: BN
};
interface Props extends I18nProps {
address: string;
block: BN;
}
class Member extends React.PureComponent<Props> {
render () {
public render (): React.ReactNode {
const { address, block, t } = this.props;
return (

View File

@ -4,26 +4,29 @@
import { ElectionsInfo } from './types';
import BN from 'bn.js';
import React from 'react';
import { Button } from '@polkadot/ui-app';
import TxModal, { TxModalState, TxModalProps } from '@polkadot/ui-app/TxModal';
import translate from '../translate';
type Props = TxModalProps & {
electionsInfo: ElectionsInfo
};
interface Props extends TxModalProps {
electionsInfo: ElectionsInfo;
}
type State = TxModalState;
class SubmitCandidacy extends TxModal<Props, State> {
headerText = () => this.props.t('Submit your council candidacy');
protected headerText = (): string => this.props.t('Submit your council candidacy');
accountLabel = () => this.props.t('Candidate account');
accountHelp = () => this.props.t('This account will be nominated to fill the council slot you specify.');
protected accountLabel = (): string => this.props.t('Candidate account');
txMethod = () => 'elections.submitCandidacy';
txParams = () => {
protected accountHelp = (): string => this.props.t('This account will be nominated to fill the council slot you specify.');
protected txMethod = (): string => 'elections.submitCandidacy';
protected txParams = (): [BN] => {
const { electionsInfo: { candidateCount } } = this.props;
return [
@ -31,13 +34,13 @@ class SubmitCandidacy extends TxModal<Props, State> {
];
}
isDisabled = () => {
protected isDisabled = (): boolean => {
const { accountId } = this.state;
return !accountId;
}
renderTrigger = () => {
protected renderTrigger = (): React.ReactNode => {
const { t } = this.props;
return (

View File

@ -40,8 +40,8 @@ class Summary extends React.PureComponent<Props> {
<section>
<CardSummary label={t('term duration')}>
{formatNumber(termDuration)}
</CardSummary>
{formatNumber(termDuration)}
</CardSummary>
</section>
</SummaryBox>
);

View File

@ -15,12 +15,12 @@ import translate from './translate';
type Props = AppProps & BareProps & I18nProps;
type State = {
tabs: Array<TabItem>
};
interface State {
tabs: TabItem[];
}
class App extends React.PureComponent<Props, State> {
constructor (props: Props) {
public constructor (props: Props) {
super(props);
const { t } = props;
@ -40,7 +40,7 @@ class App extends React.PureComponent<Props, State> {
};
}
render () {
public render (): React.ReactNode {
const { basePath } = this.props;
const { tabs } = this.state;

View File

@ -4,9 +4,7 @@
import React from 'react';
interface Props {}
export default class Spacer extends React.PureComponent<Props> {
export default class Spacer extends React.PureComponent<{}> {
public render (): React.ReactNode {
return (
<div />

View File

@ -44,7 +44,7 @@ class App extends React.PureComponent<Props, State> {
);
}
private renderEntry (route: Route) {
private renderEntry (route: Route): React.ReactNode {
return (
<Entry
key={route.name}
@ -57,7 +57,7 @@ class App extends React.PureComponent<Props, State> {
// the entries of an equal width. So here we add a non-content spacers at the end that just
// ensures flex has enough items to render something usable to the user. Since we don't
// quite know how many items per row, we just render a bunch, n === routes.length
private renderSpacer (route: Route, index: number) {
private renderSpacer (route: Route, index: number): React.ReactNode {
return (
<Spacer key={index} />
);

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-democracy authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -44,7 +45,7 @@ class ProposalDisplay extends React.PureComponent<Props> {
);
}
private renderInfo () {
private renderInfo (): React.ReactNode {
const { democracy_depositOf, t } = this.props;
if (!democracy_depositOf) {
@ -56,7 +57,7 @@ class ProposalDisplay extends React.PureComponent<Props> {
return (
<div>
<Labelled label={t('depositors')}>
{addresses.map((address, index) => (
{addresses.map((address, index): React.ReactNode => (
<InputAddress
isDisabled
key={`${index}:${address}`}
@ -79,7 +80,7 @@ export default withMulti(
withCalls<Props>(
['query.democracy.depositOf', {
paramName: 'idNumber',
transform: (value: Option<Tuple>) =>
transform: (value: Option<Tuple>): Tuple | null =>
value.unwrapOr(null)
}]
)

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-democracy authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -39,10 +40,10 @@ class Proposals extends React.PureComponent<Props> {
);
}
private renderProposals () {
private renderProposals (): React.ReactNode {
const { democracy_publicProps = [] } = this.props;
return democracy_publicProps.map(([idNumber, proposal]) => (
return democracy_publicProps.map(([idNumber, proposal]): React.ReactNode => (
<ProposalDisplay
idNumber={idNumber}
key={idNumber.toString()}

View File

@ -6,7 +6,6 @@
import { DerivedReferendumVote } from '@polkadot/api-derive/types';
import { I18nProps } from '@polkadot/ui-app/types';
import { ReferendumInfoExtended } from '@polkadot/api-derive/type';
import { RawParam } from '@polkadot/ui-params/types';
import BN from 'bn.js';
import React from 'react';
@ -58,7 +57,7 @@ class Referendum extends React.PureComponent<Props, State> {
return null;
}
const newState: State = democracy_referendumVotesFor.reduce((state, { balance, vote }) => {
const newState: State = democracy_referendumVotesFor.reduce((state, { balance, vote }): State => {
if (vote.isAye) {
state.voteCountAye++;
state.votedAye = state.votedAye.add(balance);
@ -111,7 +110,7 @@ class Referendum extends React.PureComponent<Props, State> {
);
}
private renderInfo () {
private renderInfo (): React.ReactNode {
const { chain_bestNumber, democracy_publicDelay, t, value: { end, threshold } } = this.props;
if (!chain_bestNumber) {
@ -140,7 +139,7 @@ class Referendum extends React.PureComponent<Props, State> {
</Static>
<VoteThreshold
isDisabled
defaultValue={{ value: threshold } as RawParam}
defaultValue={{ isValid: true, value: threshold }}
label={t('vote threshold')}
name='voteThreshold'
type={{
@ -152,7 +151,7 @@ class Referendum extends React.PureComponent<Props, State> {
);
}
private renderResults () {
private renderResults (): React.ReactNode {
const { voteCount, voteCountAye, voteCountNay, votedAye, votedNay, votedTotal } = this.state;
if (voteCount === 0 || votedTotal.eqn(0)) {

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-democracy authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -31,13 +32,13 @@ class Referendums extends React.PureComponent<Props> {
);
}
private renderReferendums () {
private renderReferendums (): React.ReactNode {
const { democracy_referendums = [] } = this.props;
const referendums = democracy_referendums
.filter((opt) => opt.isSome)
.map((opt) => opt.unwrap());
.filter((opt): boolean => opt.isSome)
.map((opt): ReferendumInfoExtended => opt.unwrap());
return referendums.map((referendum) => (
return referendums.map((referendum): React.ReactNode => (
<Referendum
idNumber={referendum.index}
key={referendum.index.toString()}

View File

@ -52,7 +52,7 @@ class Seconding extends React.PureComponent<Props, State> {
);
}
private renderModal () {
private renderModal (): React.ReactNode {
const { depositors, proposalId, t } = this.props;
const { accountId, isSecondingOpen } = this.state;
@ -60,7 +60,7 @@ class Seconding extends React.PureComponent<Props, State> {
return null;
}
const isDepositor = !!depositors.find((depositor) => depositor.eq(accountId));
const isDepositor = !!depositors.find((depositor): boolean => depositor.eq(accountId));
return (
<Modal

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-democracy authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@ -80,7 +80,7 @@ class Propose extends TxComponent<Props, State> {
);
}
private nextState (newState: State): void {
private nextState (newState: Partial<State>): void {
this.setState(
(prevState: State): State => {
const { accountId = prevState.accountId, method = prevState.method, value = prevState.value } = newState;
@ -97,7 +97,7 @@ class Propose extends TxComponent<Props, State> {
}
private onChangeAccount = (accountId: string): void => {
this.nextState({ accountId } as State);
this.nextState({ accountId });
}
private onChangeExtrinsic = (method: Method): void => {
@ -105,14 +105,14 @@ class Propose extends TxComponent<Props, State> {
return;
}
this.nextState({ method } as State);
this.nextState({ method });
}
private onChangeValue = (value?: BN): void => {
this.nextState({ value } as State);
this.nextState({ value });
}
private onSubmitProposal = () => {
private onSubmitProposal = (): void => {
const { history, basePath } = this.props;
history.push(basePath);

View File

@ -7,7 +7,7 @@ import { TabItem } from '@polkadot/ui-app/Tabs';
import React from 'react';
import { Route, Switch } from 'react-router';
import { HelpOverlay,Tabs } from '@polkadot/ui-app';
import { HelpOverlay, Tabs } from '@polkadot/ui-app';
import uiSettings from '@polkadot/ui-settings';
import basicMd from './md/basic.md';
@ -60,7 +60,10 @@ class App extends React.PureComponent<Props, State> {
/>
</header>
<Switch>
<Route path={`${basePath}/propose`} render={() => <Propose basePath={basePath} />} />
<Route
path={`${basePath}/propose`}
render={(): React.ReactNode => <Propose basePath={basePath} />}
/>
<Route component={Overview} />
</Switch>
</main>

View File

@ -37,8 +37,8 @@ export default class BlockHeader extends React.PureComponent<Props> {
<div className='header'>
<div className='number'>{
withLink
? <Link to={`/explorer/query/${hashHex}`}>{textNumber}</Link>
: textNumber
? <Link to={`/explorer/query/${hashHex}`}>{textNumber}</Link>
: textNumber
}&nbsp;</div>
<div className='hash'>{hashHex}</div>
<div className='author ui--media-small'>{
@ -62,7 +62,7 @@ export default class BlockHeader extends React.PureComponent<Props> {
);
}
private renderDetails ({ blockNumber, extrinsicsRoot, parentHash, stateRoot }: HeaderExtended) {
private renderDetails ({ blockNumber, extrinsicsRoot, parentHash, stateRoot }: HeaderExtended): React.ReactNode {
const parentHex = parentHash.toHex();
return (

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-explorer authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@ -23,7 +23,7 @@ class Events extends React.PureComponent<Props> {
return null;
}
const events = value.map((record, index) => ({
const events = value.map((record, index): { key: string; record: EventRecord } => ({
key: `${index}`, record
}));

View File

@ -33,14 +33,14 @@ class Extrinsics extends React.PureComponent<Props> {
);
}
private renderContent () {
private renderContent (): React.ReactNode {
const { value = [] } = this.props;
return (value || []).map(this.renderExtrinsic);
}
// FIXME This is _very_ similar to what we have in democracy/Item
private renderExtrinsic = (extrinsic: Extrinsic, index: number) => {
private renderExtrinsic = (extrinsic: Extrinsic, index: number): React.ReactNode => {
const { blockNumber, t } = this.props;
const { meta, method, section } = Method.findFunction(extrinsic.callIndex);
@ -90,7 +90,7 @@ class Extrinsics extends React.PureComponent<Props> {
);
}
private renderSigner (extrinsic: Extrinsic) {
private renderSigner (extrinsic: Extrinsic): React.ReactNode {
const { t } = this.props;
if (!extrinsic.signature.isSigned) {

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-explorer authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -39,12 +40,11 @@ class Entry extends React.Component<Props, State> {
return {
value
} as State;
};
}
shouldComponentUpdate (nextProps: Props) {
return this.props.match !== nextProps.match ||
!this.state.value;
public shouldComponentUpdate (nextProps: Props): boolean {
return this.props.match !== nextProps.match || !this.state.value;
}
public render (): React.ReactNode {

View File

@ -30,7 +30,7 @@ class Summary extends React.PureComponent<Props, State> {
return null;
}
const bestPeer = info.peers.sort((a, b) => b.bestNumber.cmp(a.bestNumber))[0];
const bestPeer = info.peers.sort((a, b): number => b.bestNumber.cmp(a.bestNumber))[0];
return {
peerBest: bestPeer

View File

@ -56,7 +56,7 @@ class Query extends TxComponent<Props, State> {
);
}
private setHash = (value: string) => {
private setHash = (value: string): void => {
this.setState(
this.stateFromValue(value)
);

View File

@ -11,7 +11,7 @@ import { BestFinalized, BestNumber, TimeNow, TimePeriod, TotalIssuance } from '@
import SummarySession from './SummarySession';
import translate from './translate';
interface Props extends I18nProps {}
type Props = I18nProps;
class Summary extends React.PureComponent<Props> {
public render (): React.ReactNode {

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-explorer authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -28,15 +29,15 @@ class SummarySession extends React.PureComponent<Props> {
);
}
private renderEra () {
private renderEra (): React.ReactNode {
const { session_info, t, withEra = true } = this.props;
if (!withEra || ! session_info) {
if (!withEra || !session_info) {
return null;
}
return session_info.sessionLength.gtn(0)
? (
? (
<CardSummary
label={t('era')}
progress={{
@ -52,7 +53,7 @@ class SummarySession extends React.PureComponent<Props> {
);
}
private renderSession () {
private renderSession (): React.ReactNode {
const { session_info, t, withSession = true } = this.props;
if (!withSession || !session_info) {
@ -60,7 +61,7 @@ class SummarySession extends React.PureComponent<Props> {
}
return session_info.sessionLength.gtn(0)
? (
? (
<CardSummary
label={t('session')}
progress={{

View File

@ -72,10 +72,10 @@ class ExplorerApp extends React.Component<Props, State> {
}
const recentEvents = system_events
.filter(({ event }) => event.section !== 'system')
.map((record, index) => ({ key: `${Date.now()}-${index}`, record }))
.filter(({ event }): boolean => event.section !== 'system')
.map((record, index): { key: string; record: EventRecord } => ({ key: `${Date.now()}-${index}`, record }))
.concat(prevState.recentEvents)
.filter((_, index) => index < MAX_ITEMS);
.filter((_, index): boolean => index < MAX_ITEMS);
return {
items: prevState.items,
@ -110,7 +110,7 @@ class ExplorerApp extends React.Component<Props, State> {
);
}
private renderMain = () => {
private renderMain = (): JSX.Element => {
const { recentEvents } = this.state;
return (

View File

@ -125,31 +125,31 @@ class ActionButtons extends React.PureComponent<Props, State> {
private generateLink = (): void => {
const { generateLink, t } = this.props;
this.setState({ shareText: t('Copied to clipboard') } as State);
this.setState({ shareText: t('Copied to clipboard') });
generateLink();
}
private onShareClose = (): void => {
this.setState({ shareText: this.props.t('Generate link to share code example') } as State);
this.setState({ shareText: this.props.t('Generate link to share code example') });
}
private onChangeName = (snippetName: string): void => {
this.setState({ snippetName } as State);
this.setState({ snippetName });
}
private saveSnippet = (): void => {
const { state: { snippetName }, props: { saveSnippet } } = this;
saveSnippet(snippetName);
this.setState({ snippetName: '', isOpen: false } as State);
this.setState({ snippetName: '', isOpen: false });
}
private onPopupOpen = (): void => {
this.setState({ isOpen: true, snippetName: this.props.snippetName || '' } as State);
this.setState({ isOpen: true, snippetName: this.props.snippetName || '' });
}
private onPopupClose = (): void => {
this.setState({ snippetName: '', isOpen: false } as State);
this.setState({ snippetName: '', isOpen: false });
}
}

View File

@ -105,15 +105,15 @@ class Playground extends React.PureComponent<Props, State> {
? [sharedExample, ...customExamples, ...this.snippets]
: [...customExamples, ...this.snippets];
const selected = options.find(option => option.value === localData.selectedValue);
const selected = options.find((option): boolean => option.value === localData.selectedValue);
this.setState((prevState: State): Pick<State, never> => ({
this.setState({
customExamples,
isCustomExample: (selected && selected.type === 'custom') || false,
options,
selected: sharedExample || selected || this.snippets[0],
sharedExample
}));
});
}
public render (): React.ReactNode {
@ -194,9 +194,10 @@ class Playground extends React.PureComponent<Props, State> {
// as we have in the editor view (TODO: Make the console.error here actually return the full stack)
const exec = `(async ({${Object.keys(this.injected).join(',')}}) => { try { ${code} \n } catch (error) { console.error(error); } })(injected);`;
// eslint-disable-next-line no-new-func
new Function('injected', exec)(this.injected);
this.setState({ isRunning: true } as State);
this.setState({ isRunning: true });
}
private stopJs = (): void => {
@ -207,13 +208,13 @@ class Playground extends React.PureComponent<Props, State> {
this.injected.api.disconnect();
this.injected = null;
this.setState({ isRunning: false } as State);
this.setState({ isRunning: false });
}
private selectExample = (value: string) => {
private selectExample = (value: string): void => {
if (value.length) {
const { options } = this.state;
const option = options.find(option => option.value === value);
const option = options.find((option): boolean => option.value === value);
if (option) {
localStorage.setItem(STORE_SELECTED, value);
@ -247,27 +248,27 @@ class Playground extends React.PureComponent<Props, State> {
localStorage.setItem(STORE_EXAMPLES, JSON.stringify([snapshot, ...customExamples]));
this.setState((prevState: State): State => ({
this.setState((prevState: State): Pick<State, never> => ({
...prevState,
customExamples: [snapshot, ...prevState.customExamples],
isCustomExample: true,
options,
selected: snapshot,
sharedExample: type === 'shared' ? undefined : prevState.sharedExample
}) as State);
}));
}
private removeSnippet = (): void => {
const { customExamples, selected } = this.state;
const filtered = customExamples.filter((value) => value.value !== selected.value);
const filtered = customExamples.filter((value): boolean => value.value !== selected.value);
const nextOptions = [...filtered, ...this.snippets];
this.setState((prevState: State): State => ({
this.setState((prevState: State): Pick<State, never> => ({
...prevState,
customExamples: filtered,
isCustomExample: nextOptions[0].type === 'custom' || false,
options: prevState.sharedExample ? [prevState.sharedExample, ...nextOptions] : nextOptions
}) as State);
}));
this.selectExample(nextOptions[0].value);
localStorage.setItem(STORE_EXAMPLES, JSON.stringify(filtered));
@ -275,10 +276,10 @@ class Playground extends React.PureComponent<Props, State> {
private onEdit = (code: string): void => {
if (code !== this.state.selected.code) {
this.setState((prevState: State): State => ({
this.setState((prevState: State): Pick<State, never> => ({
selected: { ...prevState.selected, code },
isCustomExample: false
} as State));
}));
}
}
@ -286,9 +287,9 @@ class Playground extends React.PureComponent<Props, State> {
this.setState({ logs: [] });
}
private hookConsole = (type: LogType) => {
private hookConsole = (type: LogType): (...args: any[]) => void => {
return (...args: any[]): void => {
this.setState(({ logs }: State) => {
this.setState(({ logs }: State): Pick<State, never> => {
logs.push({ args, type });
return { logs: logs.slice(0) };
@ -296,20 +297,20 @@ class Playground extends React.PureComponent<Props, State> {
};
}
private decodeBase64 = (base64: string) => {
const sharedExample = {
private decodeBase64 = (base64: string): Snippet => {
const sharedExample: Snippet = {
code: '',
label: { basic: true, children: 'URL', size: 'tiny' },
text: 'Shared code example (unsaved)',
type: 'shared',
value: `custom-${Date.now()}`
} as Snippet;
};
try {
const compStr = atob(base64);
const compU8a = new Uint8Array(compStr.length);
compU8a.forEach((_, i) => {
compU8a.forEach((_, i): void => {
compU8a[i] = compStr.charCodeAt(i);
});
@ -335,7 +336,7 @@ class Playground extends React.PureComponent<Props, State> {
const u8a = util.stringToU8a(code);
const compU8a = snappy.compress(u8a);
const compStr = compU8a.reduce((str: string, ch: number) => {
const compStr = compU8a.reduce((str: string, ch: number): string => {
return str + String.fromCharCode(ch);
}, '');
@ -356,14 +357,14 @@ class Playground extends React.PureComponent<Props, State> {
private copyToClipboard = (link: string): void => {
// See https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f
const el = document.createElement('textarea');
el.value = link;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const existingSelection = document.getSelection()!;
const existingSelection = document.getSelection();
const selected = existingSelection && existingSelection.rangeCount > 0
? existingSelection.getRangeAt(0)
: undefined;
@ -372,7 +373,7 @@ class Playground extends React.PureComponent<Props, State> {
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
if (existingSelection && selected) {
existingSelection.removeAllRanges();
existingSelection.addRange(selected);
}

View File

@ -4,7 +4,11 @@
import { StrictLabelProps } from 'semantic-ui-react/dist/commonjs/elements/Label';
export const STORE_EXAMPLES: string = 'polkadot-app-js-examples';
export const STORE_SELECTED: string = 'polkadot-app-js-selected';
export const STORE_EXAMPLES = 'polkadot-app-js-examples';
export const STORE_SELECTED = 'polkadot-app-js-selected';
export const CUSTOM_LABEL: StrictLabelProps = { color: 'orange', children: 'Custom', size: 'tiny' };
export const CUSTOM_LABEL: StrictLabelProps = {
color: 'orange',
children: 'Custom',
size: 'tiny'
};

View File

@ -1,6 +1,6 @@
// Copyright 2017-2019 @polkadot/app-js authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// Copyright 2017-2019 @polkadot/app-js authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
export default function makeWrapper (isDevelopment: boolean): string {
const args = `api, hashing, ${isDevelopment ? 'keyring, ' : ''}types, util`;

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-parachains authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -66,7 +67,7 @@ export default withMulti(
withCalls<Props>(
['query.parachains.heads', {
paramName: 'paraId',
transform: (heads: Option<Bytes>) =>
transform: (heads: Option<Bytes>): string | null =>
heads.isSome ? heads.unwrap().toHex() : null
}],
['query.parachains.relayDispatchQueueSize', { paramName: 'paraId' }]

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-parachains authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -27,7 +28,7 @@ class Parachains extends React.PureComponent<Props> {
>
{
parachains_parachains.length
? parachains_parachains.map((paraId) =>
? parachains_parachains.map((paraId): React.ReactNode =>
<Parachain key={paraId.toString()} paraId={paraId} />
)
: null

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-parachains authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@ -105,7 +105,7 @@ class Developer extends React.PureComponent<Props, State> {
});
}
private onChangeTypes = (data: Uint8Array) => {
private onChangeTypes = (data: Uint8Array): void => {
const code = u8aToString(data);
try {
@ -121,7 +121,6 @@ class Developer extends React.PureComponent<Props, State> {
types: Object.keys(types).length === 0 ? {} : types,
typesPlaceholder
});
} catch (error) {
console.error('Error registering types:', error);
@ -141,20 +140,20 @@ class Developer extends React.PureComponent<Props, State> {
throw Error(this.props.t('This is not a valid JSON object.'));
}
this.setState((prevState: State) => ({
this.setState((prevState: State): Pick<State, never> => ({
...prevState,
code,
isJsonValid: true
}) as State);
}));
this.onChangeTypes(stringToU8a(code));
} catch (e) {
this.setState((prevState: State) => ({
this.setState((prevState: State): Pick<State, never> => ({
...prevState,
code,
isJsonValid: false,
typesPlaceholder: e.message
}) as State);
}));
}
}
@ -171,15 +170,14 @@ class Developer extends React.PureComponent<Props, State> {
this.props.onStatusChange({
status: 'success',
action: t('Your custom types have been added')
} as ActionStatus);
});
} catch (e) {
console.error(e);
this.setState({ isTypesValid: false });
this.props.onStatusChange({
status: 'error',
action: t(`Error saving your custom types. ${e}`)
} as ActionStatus);
});
}
}
}

View File

@ -126,7 +126,7 @@ class General extends React.PureComponent<Props, State> {
}
private onChangeApiUrl = (apiUrl: string): void => {
this.setState(({ settings }: State) => ({
this.setState(({ settings }: State): Pick<State, never> => ({
isUrlValid: this.isValidUrl(apiUrl),
settings: {
...settings,
@ -136,7 +136,7 @@ class General extends React.PureComponent<Props, State> {
}
private onChangeUiMode = (uiMode: string): void => {
this.setState(({ settings }: State) => ({
this.setState(({ settings }: State): Pick<State, never> => ({
settings: {
...settings,
uiMode
@ -145,7 +145,7 @@ class General extends React.PureComponent<Props, State> {
}
private onChangeUiTheme = (uiTheme: string): void => {
this.setState(({ settings }: State) => ({
this.setState(({ settings }: State): Pick<State, never> => ({
settings: {
...settings,
uiTheme
@ -154,7 +154,7 @@ class General extends React.PureComponent<Props, State> {
}
private onChangeCustom = (isCustomNode: boolean): void => {
this.setState(({ settings }: State) => ({
this.setState(({ settings }: State): Pick<State, never> => ({
isCustomNode,
isUrlValid: true,
settings: {

View File

@ -67,10 +67,10 @@ class App extends React.PureComponent<Props, State> {
);
}
private DeveloperWithStatus = () => {
private DeveloperWithStatus = (): React.ReactNode => {
return (
<Developer
onStatusChange={() => this.props.onStatusChange}
onStatusChange={this.props.onStatusChange}
{...this.props}
/>
);

View File

@ -30,7 +30,7 @@ class ValidateController extends React.PureComponent<Props, State> {
};
public static getDerivedStateFromProps ({ accountId, bondedId, controllerId, defaultController, onError, stashId, t }: Props, prevState: State): State {
const error = (() => {
const error = ((): string | null => {
if (defaultController === controllerId) {
// don't show an error if the selected controller is the default
// this applies when changing controller
@ -76,7 +76,7 @@ export default translate(
['query.staking.bonded', {
paramName: 'controllerId',
propName: 'bondedId',
transform: (value: Option<AccountId>) => {
transform: (value: Option<AccountId>): string | null => {
const extracted = value.unwrapOr(null);
return extracted
@ -87,7 +87,7 @@ export default translate(
['query.staking.ledger', {
paramName: 'controllerId',
propName: 'stashId',
transform: (value: Option<StakingLedger>) => {
transform: (value: Option<StakingLedger>): string | null => {
const extracted = value.unwrapOr({ stash: null }).stash;
return extracted

View File

@ -111,7 +111,7 @@ class Nominate extends React.PureComponent<Props, State> {
);
}
private onChangeNominees = (nominees: string[]) => {
private onChangeNominees = (nominees: string[]): void => {
this.setState({ nominees });
}
}

View File

@ -70,7 +70,7 @@ class SetControllerAccount extends TxComponent<Props, State> {
);
}
private renderContent () {
private renderContent (): React.ReactNode {
const { defaultControllerId, stashId, t } = this.props;
const { controllerId, controllerError } = this.state;
@ -108,7 +108,7 @@ class SetControllerAccount extends TxComponent<Props, State> {
);
}
private renderSessionAccountWarning () {
private renderSessionAccountWarning (): React.ReactNode {
const { isValidating = false, t } = this.props;
if (!isValidating) {
@ -124,11 +124,12 @@ class SetControllerAccount extends TxComponent<Props, State> {
</article>
);
}
private onChangeController = (controllerId: string) => {
private onChangeController = (controllerId: string): void => {
this.setState({ controllerId });
}
private onControllerError = (controllerError: string | null) => {
private onControllerError = (controllerError: string | null): void => {
this.setState({ controllerError });
}
}

View File

@ -67,7 +67,7 @@ class SetRewardDestination extends TxComponent<Props, State> {
);
}
private renderContent () {
private renderContent (): React.ReactNode {
const { controllerId, defaultDestination, t } = this.props;
const { destination } = this.state;
@ -98,7 +98,7 @@ class SetRewardDestination extends TxComponent<Props, State> {
);
}
private onChangeDestination = (destination: number) => {
private onChangeDestination = (destination: number): void => {
this.setState({ destination });
}
}

View File

@ -77,7 +77,7 @@ class Validate extends TxComponent<Props, State> {
);
}
private renderButtons () {
private renderButtons (): React.ReactNode {
const { controllerId, onClose, t, validatorPrefs } = this.props;
const { unstakeThreshold, unstakeThresholdError, validatorPayment } = this.state;
const isChangingPrefs = validatorPrefs && !!validatorPrefs.unstakeThreshold;
@ -109,7 +109,7 @@ class Validate extends TxComponent<Props, State> {
);
}
private renderContent () {
private renderContent (): React.ReactNode {
const { controllerId, stashId, t, validatorPrefs } = this.props;
const { unstakeThreshold, unstakeThresholdError, validatorPayment } = this.state;
const defaultValue = validatorPrefs && validatorPrefs.unstakeThreshold && validatorPrefs.unstakeThreshold.toBn();
@ -170,19 +170,19 @@ class Validate extends TxComponent<Props, State> {
);
}
private onChangePayment = (validatorPayment?: BN) => {
private onChangePayment = (validatorPayment?: BN): void => {
if (validatorPayment) {
this.setState({ validatorPayment });
}
}
private onChangeThreshold = (unstakeThreshold?: BN) => {
private onChangeThreshold = (unstakeThreshold?: BN): void => {
if (unstakeThreshold) {
this.setState({ unstakeThreshold });
}
}
private onUnstakeThresholdError = (unstakeThresholdError: string | null) => {
private onUnstakeThresholdError = (unstakeThresholdError: string | null): void => {
this.setState({ unstakeThresholdError });
}
}

View File

@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
export const rewardDestinationOptions = [
{ text: 'Stash account (increase the amount at stake)', value: 0 },
{ text: 'Stash account (do not increase the amount at stake)', value: 1 },
{ text: 'Controller account', value: 2 }
{ text: 'Stash account (increase the amount at stake)', value: 0 },
{ text: 'Stash account (do not increase the amount at stake)', value: 1 },
{ text: 'Controller account', value: 2 }
];

View File

@ -23,8 +23,8 @@ interface Props extends I18nProps {
}
interface State {
inputs: React.ReactNode[];
Component: React.ComponentType<{}>;
inputs?: React.ReactNode[];
Component?: React.ComponentType<{}>;
spread: Record<number, boolean>;
}
@ -37,13 +37,13 @@ interface CacheInstance {
const cache: CacheInstance[] = [];
class Query extends React.PureComponent<Props, State> {
public state: State = { spread: {} } as State;
public state: State = { spread: {} };
public static getCachedComponent (query: QueryTypes): CacheInstance {
const { id, key, params = [] } = query as StorageModuleQuery;
if (!cache[id]) {
const values: any[] = params.map(({ value }) => value);
const values: any[] = params.map(({ value }): any => value);
const type = key.creator.meta
? key.creator.meta.type.toString()
: 'Data';
@ -57,7 +57,7 @@ class Query extends React.PureComponent<Props, State> {
});
const Component = renderHelper(
// By default we render a simple div node component with the query results in it
(value: any) => valueToText(type, value, true, true),
(value: any): React.ReactNode => valueToText(type, value, true, true),
defaultProps
);
cache[query.id] = Query.createComponent(type, Component, defaultProps, renderHelper);
@ -66,24 +66,24 @@ class Query extends React.PureComponent<Props, State> {
return cache[id];
}
public static createComponent (type: string, Component: React.ComponentType<any>, defaultProps: DefaultProps, renderHelper: ComponentRenderer) {
public static createComponent (type: string, Component: React.ComponentType<any>, defaultProps: DefaultProps, renderHelper: ComponentRenderer): { Component: React.ComponentType<any>; render: (createComponent: RenderFn) => React.ComponentType<any>; refresh: (swallowErrors: boolean, contentShorten: boolean) => React.ComponentType<any> } {
return {
Component,
// In order to replace the default component during runtime we can provide a RenderFn to create a new 'plugged' component
render: (createComponent: RenderFn) => {
render: (createComponent: RenderFn): React.ComponentType<any> => {
return renderHelper(createComponent, defaultProps);
},
// In order to modify the parameters which are used to render the default component, we can use this method
refresh: (swallowErrors: boolean, contentShorten: boolean) => {
refresh: (swallowErrors: boolean, contentShorten: boolean): React.ComponentType<any> => {
return renderHelper(
(value: any) => valueToText(type, value, swallowErrors, contentShorten),
(value: any): React.ReactNode => valueToText(type, value, swallowErrors, contentShorten),
defaultProps
);
}
};
}
public static getDerivedStateFromProps ({ value }: Props) {
public static getDerivedStateFromProps ({ value }: Props): Pick<State, never> {
const Component = Query.getCachedComponent(value).Component;
const inputs: React.ReactNode[] = isU8a(value.key)
? []
@ -99,7 +99,7 @@ class Query extends React.PureComponent<Props, State> {
return {
Component,
inputs
} as State;
};
}
public render (): React.ReactNode {
@ -114,6 +114,10 @@ class Query extends React.PureComponent<Props, State> {
: key.creator.meta.type.toString()
);
if (!Component) {
return null;
}
return (
<div className={`storage--Query storage--actionrow ${className}`}>
<div className='storage--actionrow-value'>
@ -136,7 +140,7 @@ class Query extends React.PureComponent<Props, State> {
);
}
private renderButtons () {
private renderButtons (): React.ReactNode {
const { id, key } = this.props.value as StorageModuleQuery;
const buttons = [
@ -181,8 +185,8 @@ class Query extends React.PureComponent<Props, State> {
return `${key.creator.section}.${key.creator.method}`;
}
private spreadHandler (id: number) {
return () => {
private spreadHandler (id: number): () => void {
return (): void => {
const { spread } = this.state;
cache[id].Component = cache[id].refresh(true, !!spread[id]);

View File

@ -78,7 +78,7 @@ class Modules extends TxComponent<Props, State> {
);
}
private nextState (newState: State): void {
private nextState (newState: Partial<State>): void {
this.setState(
(prevState: State): Pick<State, never> => {
const { key = prevState.key, values = prevState.values } = newState;
@ -125,7 +125,7 @@ class Modules extends TxComponent<Props, State> {
}
private onChangeParams = (values: RawParams = []): void => {
this.nextState({ values } as State);
this.nextState({ values });
}
}

View File

@ -66,7 +66,7 @@ class Selection extends React.PureComponent<Props, State> {
);
}
private renderComponent (Component: React.ComponentType<ComponentProps>) {
private renderComponent (Component: React.ComponentType<ComponentProps>): () => React.ReactNode {
return (): React.ReactNode => {
return (
<Component onAdd={this.onAdd} />
@ -74,7 +74,7 @@ class Selection extends React.PureComponent<Props, State> {
};
}
private onAdd = (query: ParitalQueryTypes) => {
private onAdd = (query: ParitalQueryTypes): void => {
const { onAdd } = this.props;
onAdd({

View File

@ -78,7 +78,7 @@ class App extends React.PureComponent<Props, State> {
);
}
private renderComponent (Component: React.ComponentType<ComponentProps>) {
private renderComponent (Component: React.ComponentType<ComponentProps>): () => React.ReactNode {
return (): React.ReactNode => {
const { allAccounts = {}, sudo_key: sudoKey = '' } = this.props;
const { isMine } = this.state;
@ -99,7 +99,10 @@ export default withMulti(
translate,
withApi,
withCalls<Props>(
['query.sudo.key', { transform: key => key.toString() }]
['query.sudo.key', {
transform: (key): string =>
key.toString()
}]
),
withObservable(accountObservable.subject, { propName: 'allAccounts' })
);

View File

@ -84,7 +84,7 @@ class Hash extends React.PureComponent<Props, State> {
);
}
onChangeData = (data: string): void => {
private onChangeData = (data: string): void => {
const isHexData = isHex(data);
const hash = blake2AsHex(
isHexData

View File

@ -77,19 +77,19 @@ class Account extends React.PureComponent<Props, State> {
);
}
onChangeAccount = (accountId: string): void => {
private onChangeAccount = (accountId: string): void => {
const { onChange } = this.props;
this.setState({ accountId }, () =>
this.setState({ accountId }, (): void =>
onChange(accountId, this.state.accountNonce)
);
}
onChangeNonce = (_accountNonce: BN): void => {
private onChangeNonce = (_accountNonce: BN): void => {
const { onChange } = this.props;
const accountNonce = _accountNonce || new BN(0);
this.setState({ accountNonce }, () =>
this.setState({ accountNonce }, (): void =>
onChange(this.state.accountId, accountNonce)
);
}

View File

@ -29,7 +29,7 @@ export default class Results extends React.PureComponent<Props> {
return (
<section className='rpc--Results'>
{filtered.map(({ error, id, result, rpc: { section, method } }) => (
{filtered.map(({ error, id, result, rpc: { section, method } }): React.ReactNode => (
<Output
isError={!!error}
key={id}

View File

@ -9,7 +9,7 @@ import { QueueTxRpcAdd } from '@polkadot/ui-app/Status/types';
import React from 'react';
import rpc from '@polkadot/jsonrpc';
import { getTypeDef } from '@polkadot/types';
import { TypeDef, getTypeDef } from '@polkadot/types';
import { Button, InputRpc, TxComponent } from '@polkadot/ui-app';
import Params from '@polkadot/ui-params';
@ -39,7 +39,7 @@ class Selection extends TxComponent<Props, State> {
public render (): React.ReactNode {
const { t } = this.props;
const { isValid, rpc } = this.state;
const params = rpc.params.map(({ name, type }) => ({
const params = rpc.params.map(({ name, type }): { name: string; type: TypeDef } => ({
name,
type: getTypeDef(type)
}));
@ -71,7 +71,7 @@ class Selection extends TxComponent<Props, State> {
);
}
private nextState (newState: State): void {
private nextState (newState: Partial<State>): void {
this.setState(
(prevState: State): State => {
const { rpc = prevState.rpc, accountId = prevState.accountId, values = prevState.values } = newState;
@ -92,11 +92,11 @@ class Selection extends TxComponent<Props, State> {
this.nextState({
rpc,
values: [] as RawParam[]
} as State);
});
}
private onChangeValues = (values: RawParam[]): void => {
this.nextState({ values } as State);
this.nextState({ values });
}
private onSubmit = (): void => {
@ -106,9 +106,7 @@ class Selection extends TxComponent<Props, State> {
queueRpc({
accountId,
rpc,
values: values.map(({ value }) =>
value
)
values: values.map(({ value }): any => value)
});
}
}

View File

@ -8,7 +8,7 @@ import { KeyringPair } from '@polkadot/keyring/types';
import React from 'react';
import styled from 'styled-components';
import { withMulti } from '@polkadot/ui-api';
import { Button , Input, InputAddress, Output, Static } from '@polkadot/ui-app';
import { Button, Input, InputAddress, Output, Static } from '@polkadot/ui-app';
import keyring from '@polkadot/ui-keyring';
import { hexToU8a, isHex, stringToU8a, u8aToHex } from '@polkadot/util';
@ -175,7 +175,7 @@ class Sign extends React.PureComponent<Props, State> {
);
}
private nextState = (newState: State): void => {
private nextState = (newState: Partial<State>): void => {
this.setState(
(prevState: State): State => {
const { currentPair = prevState.currentPair, data = prevState.data, isHexData = prevState.isHexData, isUnlockVisible = prevState.isUnlockVisible } = newState;
@ -204,24 +204,24 @@ class Sign extends React.PureComponent<Props, State> {
);
}
toggleUnlock = (): void => {
private toggleUnlock = (): void => {
const { isUnlockVisible } = this.state;
this.nextState({
isUnlockVisible: !isUnlockVisible
} as State);
});
}
onChangeAccount = (accountId: string): void => {
private onChangeAccount = (accountId: string): void => {
const currentPair = keyring.getPair(accountId);
this.nextState({ currentPair } as State);
this.nextState({ currentPair });
}
onChangeData = (data: string): void => {
private onChangeData = (data: string): void => {
const isHexData = isHex(data);
this.nextState({ data, isHexData } as State);
this.nextState({ data, isHexData });
}
}

View File

@ -56,7 +56,7 @@ class Unlock extends TxComponent<Props, State> {
);
}
private renderActions () {
private renderActions (): React.ReactNode {
const { t } = this.props;
return (
@ -79,7 +79,7 @@ class Unlock extends TxComponent<Props, State> {
);
}
private renderContent () {
private renderContent (): React.ReactNode {
const { t } = this.props;
const { address, password, unlockError } = this.state;

View File

@ -102,7 +102,7 @@ class Verify extends React.PureComponent<Props, State> {
);
}
private renderAddress () {
private renderAddress (): React.ReactNode {
const { t } = this.props;
const { defaultPublicKey, isValidAddress } = this.state;
@ -121,7 +121,7 @@ class Verify extends React.PureComponent<Props, State> {
);
}
private renderSignature () {
private renderSignature (): React.ReactNode {
const { t } = this.props;
const { isValid, isValidSignature, signature } = this.state;
@ -146,9 +146,9 @@ class Verify extends React.PureComponent<Props, State> {
);
}
private nextState (newState: State): void {
private nextState (newState: Partial<State>): void {
this.setState(
(prevState: State): State => {
(prevState: State): Pick<State, never> => {
const { isHexData = prevState.isHexData, isValidAddress = prevState.isValidAddress, isValidSignature = prevState.isValidSignature, currentPublicKey = prevState.currentPublicKey, data = prevState.data, signature = prevState.signature } = newState;
let cryptoType: CryptoTypes = 'unknown';
let isValid = isValidAddress && isValidSignature;
@ -192,7 +192,7 @@ class Verify extends React.PureComponent<Props, State> {
currentPublicKey,
data,
signature
} as State;
};
}
);
}
@ -200,13 +200,13 @@ class Verify extends React.PureComponent<Props, State> {
private onChangeData = (data: string): void => {
const isHexData = isHex(data);
this.nextState({ data, isHexData } as State);
this.nextState({ data, isHexData });
}
private onChangeSignature = (signature: string): void => {
const isValidSignature = isHex(signature) && signature.length === 130;
this.nextState({ signature, isValidSignature } as State);
this.nextState({ signature, isValidSignature });
}
private onChangeAddress = (accountId: string): void => {
@ -220,7 +220,7 @@ class Verify extends React.PureComponent<Props, State> {
const isValidAddress = currentPublicKey && currentPublicKey.length === 32;
this.nextState({ currentPublicKey, isValidAddress } as State);
this.nextState({ currentPublicKey, isValidAddress });
}
}

View File

@ -43,7 +43,7 @@ class ProposalDisplay extends React.PureComponent<Props, State> {
}
}
componentWillReceiveProps ({ proposal }: Props) {
public componentWillReceiveProps ({ proposal }: Props): void {
const { onPopulate } = this.props;
if (proposal && !this.props.proposal) {
@ -72,7 +72,7 @@ class ProposalDisplay extends React.PureComponent<Props, State> {
);
}
private renderAccessory () {
private renderAccessory (): React.ReactNode {
const { allAccounts, isApproved, onRespond, proposal, proposalId, t } = this.props;
if (isApproved) {
@ -115,7 +115,7 @@ export default withMulti(
['query.treasury.proposals', {
paramName: 'proposalId',
propName: 'proposal',
transform: (value: Option<TreasuryProposalType>) =>
transform: (value: Option<TreasuryProposalType>): TreasuryProposalType | null =>
value.unwrapOr(null)
}]
),

View File

@ -116,4 +116,4 @@ const Proposals = withMulti(
);
export default Proposals;
export const Approvals = () => <Proposals isApprovals />;
export const Approvals = (): JSX.Element => <Proposals isApprovals />;

View File

@ -23,11 +23,11 @@ class Propose extends TxModal<Props, State> {
value: new BN(0)
};
headerText = () => this.props.t('Submit a spend proposal');
protected headerText = (): string => this.props.t('Submit a spend proposal');
txMethod = () => 'treasury.proposeSpend';
protected txMethod = (): string => 'treasury.proposeSpend';
txParams = () => {
protected txParams = (): (string | BN | undefined)[] => {
const { beneficiary, value } = this.state;
return [
@ -84,26 +84,26 @@ class Propose extends TxModal<Props, State> {
);
}
private nextState (newState: State): void {
private nextState (newState: Partial<State>): void {
this.setState(
(prevState: State): State => {
(prevState: State): Pick<State, never> => {
const { accountId = prevState.accountId, beneficiary = prevState.beneficiary, value = prevState.value } = newState;
return {
accountId,
beneficiary,
value
} as State;
};
}
);
}
private onChangeBeneficiary = (beneficiary: string): void => {
this.nextState({ beneficiary } as State);
this.nextState({ beneficiary });
}
private onChangeValue = (value?: BN): void => {
this.nextState({ value } as State);
this.nextState({ value });
}
}

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/camelcase */
// Copyright 2017-2019 @polkadot/app-democracy authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@ -37,12 +38,11 @@ class Summary extends React.PureComponent<Props> {
</section>
<section>
<CardSummary label={t('pot')}>
{
value
? `${formatBalance(value, false)}${treasury_pot.gtn(0) ? formatBalance.calcSi(value).value : ''}`
: '-'
{
value
? `${formatBalance(value, false)}${treasury_pot.gtn(0) ? formatBalance.calcSi(value).value : ''}`
: '-'
}
</CardSummary>
</section>
</SummaryBox>

View File

@ -56,7 +56,7 @@ class App extends React.PureComponent<Props, State> {
/>
</header>
<Switch>
{/*<Route path={`${basePath}/settings`} component={Settings} />*/}
{/* <Route path={`${basePath}/settings`} component={Settings} /> */}
<Route component={Overview} />
</Switch>
</main>

View File

@ -65,7 +65,9 @@ const routes: Routes = appSettings.uiMode === 'light'
template
);
export default ({
const setup: Routing = {
default: 'explorer',
routes
} as Routing);
};
export default setup;

View File

@ -28,10 +28,10 @@ interface Props extends I18nProps {
let prevEventHash: string;
class Status extends React.PureComponent<Props> {
public componentDidUpdate ({ optionsAll = { account: [] as any[] } as KeyringOptions, queueAction, system_events, t }: Props): void {
public componentDidUpdate ({ optionsAll, queueAction, system_events, t }: Props): void {
const eventHash = xxhashAsHex(stringToU8a(JSON.stringify(system_events || [])));
if (eventHash === prevEventHash) {
if (!optionsAll || eventHash === prevEventHash) {
return;
}

View File

@ -61,7 +61,7 @@ class Accounts extends React.PureComponent<Props, State> {
icon='users'
>
<Trans i18nKey='noAccounts'>
You don't have any accounts. Some features are currently hidden and will only become available once you have accounts.
You don&apos;t have any accounts. Some features are currently hidden and will only become available once you have accounts.
{' '}
<Link
to = {{ pathname: '/accounts', state: { isCreateOpen: true } }}

View File

@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable @typescript-eslint/no-var-requires */
// Copyright 2017-2019 @polkadot/apps authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@ -32,6 +32,14 @@ interface State extends ApiProps {
chain?: string | null;
}
interface InjectedAccountExt {
address: string;
meta: {
name: string;
source: string;
};
}
export { api };
const injectedPromise = web3Enable('polkadot-js/apps');
@ -105,8 +113,8 @@ export default class Api extends React.PureComponent<Props, State> {
? value.toString()
: null;
const isDevelopment = isTestChain(chain);
const injectedAccounts = await web3Accounts().then((accounts) =>
accounts.map(({ address, meta }) => ({
const injectedAccounts = await web3Accounts().then((accounts): InjectedAccountExt[] =>
accounts.map(({ address, meta }): InjectedAccountExt => ({
address,
meta: {
...meta,

View File

@ -13,6 +13,7 @@ interface Props<T> extends BaseProps<T> {
callResult?: T;
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export default function withCallDiv<T> (endpoint: string, options: Options = {}) {
return (render: (value?: T) => React.ReactNode, defaultProps: DefaultProps = {}): React.ComponentType<any> => {
class Inner extends React.PureComponent<Props<T>> {

View File

@ -4,6 +4,7 @@
// import { I18nProps } from '@polkadot/ui-app/types';
// @ts-ignore This line needed for the styled export... don't ask why
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import BN from 'bn.js';
import React from 'react';
import styled from 'styled-components';

View File

@ -27,6 +27,15 @@ interface State {
valuesStr?: string;
}
interface Config {
labels: string[];
datasets: {
data: number[];
backgroundColor: string[];
hoverBackgroundColor: string[];
}[];
}
const alphaColor = (hexColor: string): string =>
ChartJs.helpers.color(hexColor).alpha(0.65).rgbString();
@ -40,7 +49,7 @@ export default class ChartHorizBar extends React.PureComponent<Props, State> {
return null;
}
const chartData = values.reduce((data, { colors: [normalColor = '#00f', hoverColor], label, value }) => {
const chartData = values.reduce((data, { colors: [normalColor = '#00f', hoverColor], label, value }): Config => {
const dataset = data.datasets[0];
dataset.backgroundColor.push(alphaColor(normalColor));

View File

@ -42,6 +42,7 @@ export default class Collection<P extends CollectionProps, S extends CollectionS
public constructor (props: P) {
super(props);
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
this.state = {
isEmpty: Collection.isEmpty(props.children)
} as S;

View File

@ -104,11 +104,11 @@ class InputAddress extends React.PureComponent<Props, State> {
}
}
public static readOptions () {
public static readOptions (): Record<string, any> {
return store.get(STORAGE_KEY) || { defaults: {} };
}
public static getLastValue (type: KeyringOption$Type = DEFAULT_TYPE) {
public static getLastValue (type: KeyringOption$Type = DEFAULT_TYPE): any {
const options = InputAddress.readOptions();
return options.defaults[type];

View File

@ -31,8 +31,8 @@ type Props = ApiProps & I18nProps & {
};
interface State {
optionsMethod: DropdownOptions;
optionsSection: DropdownOptions;
optionsMethod?: DropdownOptions;
optionsSection?: DropdownOptions;
value: MethodFunction;
}
@ -44,7 +44,7 @@ class InputExtrinsic extends React.PureComponent<Props, State> {
this.state = {
value: this.props.defaultValue
} as State;
};
}
public static getDerivedStateFromProps ({ api }: Props, { value }: State): Pick<State, never> {
@ -72,14 +72,14 @@ class InputExtrinsic extends React.PureComponent<Props, State> {
<SelectSection
className='small'
onChange={this.onSectionChange}
options={optionsSection}
options={optionsSection || []}
value={value}
/>
<SelectMethod
api={api}
className='large'
onChange={this.onKeyChange}
options={optionsMethod}
options={optionsMethod || []}
value={value}
/>
</div>

View File

@ -91,7 +91,7 @@ class InputRpc extends React.PureComponent<Props, State> {
return;
}
this.setState({ value: newValue }, () =>
this.setState({ value: newValue }, (): void =>
onChange && onChange(newValue)
);
}
@ -106,7 +106,7 @@ class InputRpc extends React.PureComponent<Props, State> {
const optionsMethod = methodOptions(newSection);
const newValue = map[newSection].methods[optionsMethod[0].value];
this.setState({ optionsMethod }, () =>
this.setState({ optionsMethod }, (): void =>
this.onMethodChange(newValue)
);
}

View File

@ -10,7 +10,7 @@ export default function createOptions (): DropdownOptions {
return Object
.keys(map)
.sort()
.map((name) => ({
.map((name): { text: string; value: string } => ({
text: name,
value: name
}));

View File

@ -92,7 +92,7 @@ class InputStorage extends React.PureComponent<Props, State> {
return;
}
this.setState({ value: newValue }, () =>
this.setState({ value: newValue }, (): void =>
onChange && onChange(newValue)
);
}
@ -108,7 +108,7 @@ class InputStorage extends React.PureComponent<Props, State> {
const optionsMethod = keyOptions(api, newSection);
const newValue = api.query[newSection][optionsMethod[0].value];
this.setState({ optionsMethod }, () =>
this.setState({ optionsMethod }, (): void =>
this.onKeyChange(newValue)
);
}

View File

@ -10,8 +10,8 @@ export default function createOptions (api: ApiPromise): DropdownOptions {
return Object
.keys(api.query)
.sort()
.filter((name) => Object.keys(api.query[name]).length)
.map((name) => ({
.filter((name): number => Object.keys(api.query[name]).length)
.map((name): { text: string; value: string } => ({
text: name,
value: name
}));

View File

@ -1,3 +0,0 @@
{
"extends": "@polkadot/dev-react/config/tslint"
}