Replace TxComponent and TxModal (base) (#1951)

* essentials

* cleanup

* versions

* rv file

* useForm function refs

* restore button ref

* adjust TxModalNew

* refactor

* useTx

* arg

* rework

* linting

* restore changed comps
This commit is contained in:
Keith Ingram 2019-12-02 13:42:49 -08:00 committed by GitHub
parent cefafd9f9f
commit 9bc6194265
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 585 additions and 62 deletions

View File

@ -6,6 +6,8 @@ import { BareProps } from '../types';
export type Button$Sizes = 'mini' | 'tiny' | 'small' | 'medium' | 'large' | 'big' | 'huge' | 'massive';
export type Button$OnClick = () => void | Promise<void>;
export interface ButtonProps extends BareProps {
children?: React.ReactNode;
floated?: 'left' | 'right';
@ -20,7 +22,7 @@ export interface ButtonProps extends BareProps {
isPrimary?: boolean;
label?: React.ReactNode;
labelPosition?: 'left' | 'right';
onClick?: () => void | Promise<void>;
onClick?: Button$OnClick;
ref?: any;
size?: Button$Sizes;
tabIndex?: number;

View File

@ -23,6 +23,7 @@ interface Props extends BareProps {
label?: React.ReactNode;
onChange: (method?: Call) => void;
onEnter?: () => void;
onEscape?: () => void;
withLabel?: boolean;
}
@ -33,7 +34,7 @@ function getParams ({ meta }: CallFunction): { name: string; type: TypeDef }[] {
}));
}
export default function ExtrinsicDisplay ({ defaultValue, isDisabled, isError, isPrivate, label, onChange, onEnter, withLabel }: Props): React.ReactElement<Props> {
export default function ExtrinsicDisplay ({ defaultValue, isDisabled, isError, isPrivate, label, onChange, onEnter, onEscape, withLabel }: Props): React.ReactElement<Props> {
const [extrinsic, setCall] = useState<{ fn: CallFunction; params: { name: string; type: TypeDef }[] }>({ fn: defaultValue, params: getParams(defaultValue) });
const [values, setValues] = useState<RawParam[]>([]);
@ -82,6 +83,7 @@ export default function ExtrinsicDisplay ({ defaultValue, isDisabled, isError, i
key={`${section}.${method}:params` /* force re-render on change */}
onChange={setValues}
onEnter={onEnter}
onEscape={onEscape}
overrides={paramComponents}
params={params}
/>

View File

@ -31,6 +31,7 @@ interface Props extends BareProps {
min?: any;
name?: string;
onEnter?: () => void;
onEscape?: () => void;
onChange?: (value: string) => void;
onBlur?: () => void;
onKeyDown?: (event: React.KeyboardEvent<Element>) => void;
@ -86,7 +87,7 @@ const isSelectAll = (key: string, isPreKeyDown: boolean): boolean =>
let counter = 0;
export default function Input ({ autoFocus = false, children, className, defaultValue, help, icon, isEditable = false, isAction = false, isDisabled = false, isError = false, isHidden = false, isReadOnly = false, label, labelExtra, max, maxLength, min, name, onBlur, onChange, onEnter, onKeyDown, onKeyUp, onPaste, placeholder, style, tabIndex, type = 'text', value, withEllipsis, withLabel }: Props): React.ReactElement<Props> {
export default function Input ({ autoFocus = false, children, className, defaultValue, help, icon, isEditable = false, isAction = false, isDisabled = false, isError = false, isHidden = false, isReadOnly = false, label, labelExtra, max, maxLength, min, name, onBlur, onChange, onEnter, onEscape, onKeyDown, onKeyUp, onPaste, placeholder, style, tabIndex, type = 'text', value, withEllipsis, withLabel }: Props): React.ReactElement<Props> {
const [stateName] = useState(`in_${counter++}_at_${Date.now()}`);
const _onBlur = (): void => {
@ -105,6 +106,11 @@ export default function Input ({ autoFocus = false, children, className, default
(event.target as any).blur();
onEnter();
}
if (onEscape && event.keyCode === 27) {
(event.target as any).blur();
onEscape();
}
};
const _onPaste = (event: React.ClipboardEvent<HTMLInputElement>): void => {
onPaste && onPaste(event);

View File

@ -2,10 +2,32 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { KeyringSectionOption } from '@polkadot/ui-keyring/options/types';
import { KeyringSectionOption, KeyringOption$Type } from '@polkadot/ui-keyring/options/types';
import { BareProps } from '../types';
import React from 'react';
export interface InputAddressProps extends BareProps {
defaultValue?: Uint8Array | string | null;
help?: React.ReactNode;
hideAddress?: boolean;
isDisabled?: boolean;
isError?: boolean;
isInput?: boolean;
isMultiple?: boolean;
label?: React.ReactNode;
labelExtra?: React.ReactNode;
onChange?: (value: string | null) => void;
onChangeMulti?: (value: string[]) => void;
options?: KeyringSectionOption[];
optionsAll?: Record<string, Option[]>;
placeholder?: string;
type?: KeyringOption$Type;
value?: string | Uint8Array | string[] | null;
withEllipsis?: boolean;
withLabel?: boolean;
}
export interface Option extends KeyringSectionOption {
className?: string;
text: React.ReactNode;

View File

@ -18,9 +18,10 @@ interface Props extends BareProps {
label?: React.ReactNode;
onChange?: (address: string | null) => void;
onEnter?: () => void;
onEscape?: () => void;
}
function InputAddressSimple ({ children, className, defaultValue, help, label, onChange, onEnter }: Props): React.ReactElement<Props> {
function InputAddressSimple ({ children, className, defaultValue, help, label, onChange, onEnter, onEscape }: Props): React.ReactElement<Props> {
const [address, setAddress] = useState<string | null>(defaultValue || null);
const _onChange = (_address: string): void => {
@ -40,6 +41,7 @@ function InputAddressSimple ({ children, className, defaultValue, help, label, o
label={label}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
>
{children}
</Input>

View File

@ -23,6 +23,7 @@ interface Props extends BareProps {
maxValue?: BN;
onChange?: (value?: BN) => void;
onEnter?: () => void;
onEscape?: () => void;
placeholder?: string;
value?: BN | string;
withEllipsis?: boolean;
@ -32,7 +33,7 @@ interface Props extends BareProps {
const DEFAULT_BITLENGTH = BitLengthOption.CHAIN_SPEC as BitLength;
function InputBalance ({ autoFocus, className, defaultValue: inDefault, help, isDisabled, isError, isZeroable, label, labelExtra, maxValue, onChange, onEnter, placeholder, style, value, withEllipsis, withLabel, withMax }: Props): React.ReactElement<Props> {
function InputBalance ({ autoFocus, className, defaultValue: inDefault, help, isDisabled, isError, isZeroable, label, labelExtra, maxValue, onChange, onEnter, onEscape, placeholder, style, value, withEllipsis, withLabel, withMax }: Props): React.ReactElement<Props> {
const defaultValue = inDefault
? formatBalance(inDefault, { forceUnit: '-', withSi: false }).replace(',', isDisabled ? ',' : '')
: inDefault;
@ -53,6 +54,7 @@ function InputBalance ({ autoFocus, className, defaultValue: inDefault, help, is
maxValue={maxValue}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder={placeholder}
style={style}
value={value}

View File

@ -32,6 +32,7 @@ interface Props extends BareProps, ApiProps {
label?: any;
onChange?: (value?: BN) => void;
onEnter?: () => void;
onEscape?: () => void;
placeholder?: string;
stashId: string;
value?: BN | string;
@ -61,7 +62,7 @@ class InputBalanceBonded extends React.PureComponent<Props, State> {
}
public render (): React.ReactNode {
const { autoFocus, className, defaultValue, help, isDisabled, isError, isZeroable, label, onChange, onEnter, placeholder, style, value, withEllipsis, withLabel, withMax } = this.props;
const { autoFocus, className, defaultValue, help, isDisabled, isError, isZeroable, label, onChange, onEnter, onEscape, placeholder, style, value, withEllipsis, withLabel, withMax } = this.props;
const { maxBalance } = this.state;
return (
@ -79,6 +80,7 @@ class InputBalanceBonded extends React.PureComponent<Props, State> {
maxValue={maxBalance}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder={placeholder}
style={style}
value={value}

View File

@ -34,6 +34,7 @@ interface Props extends BareProps, I18nProps {
maxValue?: BN;
onChange?: (value?: BN) => void;
onEnter?: () => void;
onEscape?: () => void;
placeholder?: string;
value?: BN | string;
withEllipsis?: boolean;
@ -192,7 +193,7 @@ function isNewPropsValue (propsValue: BN | string, value: string, valueBn: BN):
}
function InputNumber (props: Props): React.ReactElement<Props> {
const { bitLength = DEFAULT_BITLENGTH, className, defaultValue = ZERO, help, isDecimal, isSi, isDisabled, isError = false, maxLength, maxValue, onChange, onEnter, placeholder, style, value: propsValue, t } = props;
const { bitLength = DEFAULT_BITLENGTH, className, defaultValue = ZERO, help, isDecimal, isSi, isDisabled, isError = false, maxLength, maxValue, onChange, onEnter, onEscape, placeholder, style, value: propsValue, t } = props;
const [si, setSi] = useState<SiDef | null>(isSi ? formatBalance.findSi('-') : null);
const [isPreKeyDown, setIsPreKeyDown] = useState(false);
@ -270,6 +271,7 @@ function InputNumber (props: Props): React.ReactElement<Props> {
maxLength={maxLength || maxValueLength}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
onKeyDown={_onKeyDown}
onKeyUp={_onKeyUp}
onPaste={_onPaste}

View File

@ -10,7 +10,7 @@ import { useApi } from '@polkadot/react-hooks';
import Extrinsic from './Extrinsic';
export default function Call ({ className, isDisabled, isError, label, onChange, onEnter, style, withLabel }: Props): React.ReactElement<Props> {
export default function Call ({ className, isDisabled, isError, label, onChange, onEnter, onEscape, style, withLabel }: Props): React.ReactElement<Props> {
const { api, apiDefaultTx } = useApi();
const defaultValue = ((): SubmittableExtrinsicFunction<'promise'> => {
@ -31,6 +31,7 @@ export default function Call ({ className, isDisabled, isError, label, onChange,
label={label}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
withLabel={withLabel}
/>

View File

@ -4,7 +4,7 @@
import { Call } from '@polkadot/types/interfaces';
import { CallFunction } from '@polkadot/types/types';
import { RawParamOnChange, RawParamOnEnter } from '@polkadot/react-params/types';
import { RawParamOnChange, RawParamOnEnter, RawParamOnEscape } from '@polkadot/react-params/types';
import { BareProps } from '../types';
import React from 'react';
@ -19,6 +19,7 @@ interface Props extends BareProps {
label: React.ReactNode;
onChange?: RawParamOnChange;
onEnter?: RawParamOnEnter;
onEscape?: RawParamOnEscape;
withLabel?: boolean;
}
@ -32,7 +33,7 @@ function onChange ({ onChange }: Props): (method?: Call) => void {
}
export default function ExtrinsicDisplay (props: Props): React.ReactElement<Props> {
const { className, defaultValue, isDisabled, isError, isPrivate, label, onEnter, style, withLabel } = props;
const { className, defaultValue, isDisabled, isError, isPrivate, label, onEnter, onEscape, style, withLabel } = props;
return (
<BaseExtrinsic
@ -44,6 +45,7 @@ export default function ExtrinsicDisplay (props: Props): React.ReactElement<Prop
label={label}
onChange={onChange(props)}
onEnter={onEnter}
onEscape={onEscape}
style={style}
withLabel={withLabel}
/>

View File

@ -28,7 +28,7 @@ function onChange ({ onChange }: Props): (_: RawParam) => void {
export default function ProposalDisplay (props: Props): React.ReactElement<Props> {
const { apiDefaultTxSudo } = useApi();
const { className, isDisabled, isError, label, onEnter, style, withLabel } = props;
const { className, isDisabled, isError, label, onEnter, onEscape, style, withLabel } = props;
return (
<ExtrinsicDisplay
@ -40,6 +40,7 @@ export default function ProposalDisplay (props: Props): React.ReactElement<Props
label={label}
onChange={onChange(props)}
onEnter={onEnter}
onEscape={onEscape}
style={style}
withLabel={withLabel}
/>

View File

@ -22,12 +22,13 @@ interface Props extends BareProps {
name?: string;
onChange: (value: string) => void;
onEnter?: () => void;
onEscape?: () => void;
tabIndex?: number;
value: any;
withLabel?: boolean;
}
export default function Password ({ autoFocus, children, className, defaultValue, help, isDisabled, isError, label, name, onChange, onEnter, style, tabIndex, value, withLabel }: Props): React.ReactElement<Props> {
export default function Password ({ autoFocus, children, className, defaultValue, help, isDisabled, isError, label, name, onChange, onEnter, onEscape, style, tabIndex, value, withLabel }: Props): React.ReactElement<Props> {
const [isVisible, setIsVisible] = useState(false);
const _toggleVisible = (): void => setIsVisible(!isVisible);
@ -46,6 +47,7 @@ export default function Password ({ autoFocus, children, className, defaultValue
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
tabIndex={tabIndex}
type={

View File

@ -3,51 +3,22 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { SubmittableExtrinsic } from '@polkadot/api/promise/types';
import { ApiProps } from '@polkadot/react-api/types';
import { assert, isFunction, isUndefined } from '@polkadot/util';
import { Index } from '@polkadot/types/interfaces';
import { IExtrinsic } from '@polkadot/types/types';
import { QueueTx, QueueTxExtrinsicAdd, TxCallback, TxFailedCallback } from './Status/types';
import { QueueTx, QueueTxExtrinsicAdd } from './Status/types';
import { TxButtonProps as Props } from './types';
import React from 'react';
import { SubmittableResult } from '@polkadot/api';
import { withApi } from '@polkadot/react-api';
import Button from './Button';
import { Button$Sizes } from './Button/types';
import { QueueConsumer } from './Status/Context';
type ConstructFn = () => any[];
interface InjectedProps {
queueExtrinsic: QueueTxExtrinsicAdd;
txqueue: QueueTx[];
}
interface Props extends ApiProps {
accountId?: string;
accountNonce?: Index;
className?: string;
extrinsic?: IExtrinsic | SubmittableExtrinsic;
icon: string;
iconSize?: Button$Sizes;
isBasic?: boolean;
isDisabled?: boolean;
isNegative?: boolean;
isPrimary?: boolean;
isUnsigned?: boolean;
label: React.ReactNode;
onClick?: () => any;
onFailed?: TxFailedCallback;
onStart?: () => void;
onSuccess?: TxCallback;
onUpdate?: TxCallback;
params?: any[] | ConstructFn;
tooltip?: string;
tx?: string;
withSpinner?: boolean;
}
type InnerProps = Props & InjectedProps;
interface State {
@ -61,7 +32,10 @@ class TxButtonInner extends React.PureComponent<InnerProps> {
};
public render (): React.ReactNode {
const { accountId, className, icon, iconSize, isBasic, isDisabled, isNegative, isPrimary, isUnsigned, label, tooltip } = this.props;
const { accountId, className, icon, iconSize, innerRef, isBasic, isDisabled, isNegative, isPrimary, isUnsigned, label, tooltip } = this.props;
assert(!!this.props.extrinsic || (!!this.props.params && !!this.props.tx), 'TxButton: Invalid extrinsic provided');
const { isSending } = this.state;
const needsAccount = isUnsigned
? false
@ -83,6 +57,7 @@ class TxButtonInner extends React.PureComponent<InnerProps> {
}
label={label}
onClick={this.send}
ref={innerRef}
size={iconSize}
/>
);
@ -146,14 +121,15 @@ class TxButton extends React.PureComponent<Props, State> {
protected button: any = React.createRef();
public render (): React.ReactNode {
const { innerRef, ...props } = this.props;
return (
<QueueConsumer>
{({ queueExtrinsic, txqueue }): React.ReactNode => (
<TxButtonInner
{...this.props}
{...props}
queueExtrinsic={queueExtrinsic}
txqueue={txqueue}
ref={this.button}
innerRef={innerRef}
/>
)}
</QueueConsumer>

View File

@ -0,0 +1,138 @@
// Copyright 2017-2019 @polkadot/app-contracts authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { TxModalProps as Props } from './types';
import React, { useState, useEffect } from 'react';
import { Button, InputAddress, Modal } from '@polkadot/react-components';
// import { useTx } from '@polkadot/react-hooks';
import { isUndefined } from '@polkadot/util';
import translate from './translate';
function TxModal<P extends Props> ({
t,
accountId,
onChangeAccountId,
sendTx,
isSending,
trigger: Trigger,
header = t('Submit signed extrinsic'),
content,
preContent,
isDisabled = false,
isSubmittable = true,
modalProps = {},
inputAddressExtra,
inputAddressLabel = t('using my account'),
inputAddressHelp = t('Select the account to use for this action.'),
inputAddressProps = {},
cancelButtonLabel = t('Cancel'),
submitButtonIcon = 'sign-in',
submitButtonLabel = t('Submit'),
submitButtonProps = {},
...props
}: P): React.ReactElement<P> | null {
const isControlled = !isUndefined(props.isOpen);
const [isOpen, setIsOpen] = useState(isControlled ? props.isOpen : false);
const onOpen = (): void => {
!isControlled && setIsOpen(true);
props.onOpen && props.onOpen();
};
const onClose = (): void => {
!isControlled && setIsOpen(false);
props.onClose && props.onClose();
};
// const onStart = (): void => {
// props.onSubmit && props.onSubmit();
// };
// const onFailed = (): void => {
// props.onFailed && props.onFailed();
// };
// const onSuccess = (): void => {
// !isControlled && setIsOpen(false);
// props.onSuccess && props.onSuccess();
// };
// const txState = useTx(
// txSource,
// {
// ...(props.accountId ? { accountId: props.accountId } : {}),
// onChangeAccountId: props.onChangeAccountId,
// onStart,
// onFailed,
// onSuccess
// }
// );
// const { accountId, onChangeAccountId, isSending, sendTx } = th
useEffect((): void => {
!isUndefined(props.isOpen) && setIsOpen(props.isOpen);
}, [props.isOpen]);
const allModalProps = {
className: ['ui--Modal', modalProps.className || ''].join(' '),
dimmer: 'inverted',
...modalProps,
onClose,
open: isOpen
};
return (
<>
{Trigger ? <Trigger onOpen={onOpen} /> : null}
<Modal {...allModalProps}>
<Modal.Header>
{header}
</Modal.Header>
<Modal.Content>
{preContent}
<InputAddress
defaultValue={accountId}
help={inputAddressHelp}
isDisabled={isDisabled || isSending}
isInput={false}
label={inputAddressLabel}
labelExtra={inputAddressExtra}
onChange={onChangeAccountId}
type='account'
{...inputAddressProps}
/>
{content}
</Modal.Content>
<Modal.Actions>
<Button.Group>
<Button
isNegative
onClick={onClose}
label={cancelButtonLabel}
icon='cancel'
/>
<Button.Or />
<Button
isLoading={isSending}
isDisabled={isDisabled || isSending || !accountId || !isSubmittable}
isPrimary
label={submitButtonLabel}
icon={submitButtonIcon}
onClick={sendTx}
{...submitButtonProps}
/>
</Button.Group>
</Modal.Actions>
</Modal>
</>
);
}
export default translate(TxModal);

View File

@ -80,6 +80,7 @@ export { default as TreasuryProposal } from './TreasuryProposal';
export { default as TxButton } from './TxButton';
export { default as TxComponent } from './TxComponent';
export { default as TxModal } from './TxModal';
export { default as TxModalNew } from './TxModalNew';
export { default as Voting } from './Voting';
export { default as media } from './media';

View File

@ -3,8 +3,16 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { WithTranslation } from 'react-i18next';
import { SubmittableExtrinsic } from '@polkadot/api/promise/types';
import { Abi } from '@polkadot/api-contract';
import { ActionStatus } from '@polkadot/react-components/Status/types';
import { InputAddressProps } from '@polkadot/react-components/InputAddress/types';
import { IExtrinsic } from '@polkadot/types/types';
import { ApiProps } from '@polkadot/react-api/types';
import { TxState } from '@polkadot/react-hooks/types';
import { Index } from '@polkadot/types/interfaces';
import { ButtonProps, Button$OnClick, Button$Sizes } from './Button/types';
import { TxCallback, TxFailedCallback } from './Status/types';
export interface BareProps {
className?: string;
@ -18,6 +26,117 @@ export interface AppProps {
export type I18nProps = BareProps & WithTranslation;
export type ButtonRef = React.RefObject<React.Component<ButtonProps>>;
// export type FormProps$Ref = React.MutableRefObject<Button$OnClick>;
export interface FormProps {
onCancel: Button$OnClick;
onSubmit: Button$OnClick;
}
// export interface FormProps$Hooks {
// onInputEnterKey: () => void;
// onInputEscapeKey: () => void;
// }
// export interface FormProps extends FormProps$Refs, FormProps$Hooks {}
export type ConstructTxFn = () => any[];
export type TxTrigger = React.ComponentType<TxTriggerProps>;
export interface TxTriggerProps {
onOpen: () => void;
}
export interface TxButtonInterface {
component?: {
current?: {
send: () => void;
};
};
}
export interface TxProps {
extrinsic?: IExtrinsic | SubmittableExtrinsic | null;
tx?: string;
params?: any[] | ConstructTxFn;
}
export interface TxButtonProps extends TxProps, ApiProps {
accountId?: string;
accountNonce?: Index;
className?: string;
icon: string;
iconSize?: Button$Sizes;
innerRef: ButtonRef;
isBasic?: boolean;
isDisabled?: boolean;
isNegative?: boolean;
isPrimary?: boolean;
isUnsigned?: boolean;
label: React.ReactNode;
onClick?: () => any;
onFailed?: TxFailedCallback;
onStart?: () => void;
onSuccess?: TxCallback;
onUpdate?: TxCallback;
tooltip?: string;
withSpinner?: boolean;
}
export interface TxButtonNewProps extends TxProps {
accountId?: StringOrNull;
accountNonce?: Index;
className?: string;
icon: string;
iconSize?: Button$Sizes;
isBasic?: boolean;
isDisabled?: boolean;
isNegative?: boolean;
isPrimary?: boolean;
isUnsigned?: boolean;
label: React.ReactNode;
onClick?: () => any;
onFailed?: TxFailedCallback;
onStart?: () => void;
onSuccess?: TxCallback;
onUpdate?: TxCallback;
tooltip?: string;
withSpinner?: boolean;
}
export interface TxModalProps extends I18nProps, TxState {
accountId?: StringOrNull;
header?: React.ReactNode;
isDisabled?: boolean;
isOpen?: boolean;
isUnsigned?: boolean;
isSubmittable?: boolean;
content: React.ReactNode;
preContent?: React.ReactNode;
trigger?: TxTrigger;
onSubmit?: () => void;
onOpen?: () => void;
onClose?: () => void;
onSuccess?: () => void;
onFailed?: () => void;
modalProps?: {
[index: string]: any;
};
contentClassName?: string;
inputAddressHelp?: React.ReactNode;
inputAddressExtra?: React.ReactNode;
inputAddressLabel?: React.ReactNode;
inputAddressProps?: Pick<InputAddressProps, never>;
cancelButtonLabel?: React.ReactNode;
cancelButtonProps?: Pick<ButtonProps, never>;
submitButtonIcon?: string;
submitButtonLabel?: React.ReactNode;
submitButtonProps?: Pick<TxButtonProps, never>;
}
export type BitLength = 8 | 16 | 32 | 64 | 128 | 256;
export type StringOrNull = string | null;

View File

@ -8,5 +8,8 @@ export { default as useAccounts } from './useAccounts';
export { default as useAddresses } from './useAddresses';
export { default as useApi } from './useApi';
export { default as useCacheKey } from './useCacheKey';
export { default as useForm } from './useForm';
export { default as useDebounce } from './useDebounce';
export { default as useFavorites } from './useFavorites';
export { default as usePassword } from './usePassword';
export { default as useTx } from './useTx';

View File

@ -0,0 +1,45 @@
// Copyright 2017-2019 @polkadot/react-components authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ConstructTxFn, StringOrNull } from '@polkadot/react-components/types';
import { AccountId, Balance, BlockNumber, Call, Hash, SessionIndex } from '@polkadot/types/interfaces';
import { IExtrinsic } from '@polkadot/types/types';
import { SubmittableExtrinsic } from '@polkadot/api/promise/types';
export type TxSources = SubmittableExtrinsic | IExtrinsic | Call | [string, any[] | ConstructTxFn] | null;
export interface Slash {
accountId: AccountId;
amount: Balance;
}
export interface SessionRewards {
blockHash: Hash;
blockNumber: BlockNumber;
isEventsEmpty: boolean;
reward: Balance;
sessionIndex: SessionIndex;
slashes: Slash[];
}
export interface ExtrinsicAndSenders {
extrinsic: SubmittableExtrinsic | null;
sendTx: () => void;
sendUnsigned: () => void;
}
export interface TxProps {
accountId?: StringOrNull;
onChangeAccountId?: (_: StringOrNull) => void;
onSuccess?: () => void;
onFailed?: () => void;
onStart?: () => void;
onUpdate?: () => void;
}
export interface TxState extends ExtrinsicAndSenders {
isSending: boolean;
accountId?: StringOrNull;
onChangeAccountId: (_: StringOrNull) => void;
}

View File

@ -0,0 +1,22 @@
// Copyright 2017-2019 @polkadot/react-hooks authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Button$OnClick } from '@polkadot/react-components/Button/types';
import { FormProps } from '@polkadot/react-components/types';
import { useRef } from 'react';
export default function useForm (onSubmit: () => void, onCancel: () => void = (): void => {}): FormProps {
const onCancelRef = useRef<Button$OnClick>(onCancel);
const onSubmitRef = useRef<Button$OnClick>(onSubmit);
return {
onCancel: (): void => {
onCancelRef.current && onCancelRef.current();
},
onSubmit: (): void => {
onSubmitRef.current && onSubmitRef.current();
}
};
}

View File

@ -0,0 +1,29 @@
// Copyright 2017-2019 @polkadot/react-hooks authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { useEffect, useState } from 'react';
import keyring from '@polkadot/ui-keyring';
interface PasswordProps {
password: string;
setPassword: React.Dispatch<string>;
isPasswordValid: boolean;
setIsPasswordValid: React.Dispatch<boolean>;
}
export default function usePassword (): PasswordProps {
const [password, setPassword] = useState('');
const [isPasswordValid, setIsPasswordValid] = useState(false);
useEffect((): void => {
setIsPasswordValid(keyring.isPassValid(password));
}, [password]);
return {
password,
setPassword,
isPasswordValid,
setIsPasswordValid
};
}

View File

@ -0,0 +1,124 @@
// Copyright 2017-2019 @polkadot/react-hooks authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { StringOrNull } from '@polkadot/react-components/types';
import { Call } from '@polkadot/types/interfaces';
import { ExtrinsicAndSenders, TxSources, TxProps, TxState } from './types';
import { useContext, useMemo, useState } from 'react';
import { ApiPromise } from '@polkadot/api';
import { StatusContext } from '@polkadot/react-components';
import { SubmittableExtrinsic } from '@polkadot/api/promise/types';
import { assert, isFunction } from '@polkadot/util';
import useApi from './useApi';
function getExtrinsic<T extends TxSources> (api: ApiPromise, tx: T): SubmittableExtrinsic | null {
if (!tx) {
return null;
}
if (Array.isArray(tx)) {
const [section, method] = tx[0].split('.');
assert(api.tx[section] && api.tx[section][method], `Unable to find api.tx.${section}.${method}`);
try {
return api.tx[section][method](...(
isFunction(tx[1])
? tx[1]()
: tx[1]
)) as any as SubmittableExtrinsic;
} catch (e) {
return null;
}
} else {
if ((tx as Call).callIndex) {
const fn = api.findCall(tx.callIndex);
return api.tx[fn.section][fn.method](...tx.args);
}
return tx as any as SubmittableExtrinsic;
}
}
export default function useTx<T extends TxSources> (source: T, { accountId: anAccountId, onChangeAccountId, onStart, onSuccess, onFailed, onUpdate }: TxProps = {}): TxState {
const { api } = useApi();
const { queueExtrinsic } = useContext(StatusContext);
const [accountId, setAccountId] = useState<StringOrNull>(anAccountId || null);
const [isSending, setIsSending] = useState(false);
const _onStart = useMemo(
(): () => void => (): void => {
setIsSending(true);
onStart && onStart();
},
[onStart]
);
const _onSuccess = useMemo(
(): () => void => (): void => {
setIsSending(false);
onSuccess && onSuccess();
},
[onSuccess]
);
const _onFailed = useMemo(
(): () => void => (): void => {
setIsSending(false);
onFailed && onFailed();
},
[onFailed]
);
const _onUpdate = useMemo(
(): () => void => (): void => {
setIsSending(false);
onUpdate && onUpdate();
},
[onUpdate]
);
function getExtrinsicAndSenders (api: ApiPromise, accountId: StringOrNull, tx: T): ExtrinsicAndSenders {
const extrinsic = getExtrinsic<T>(api, tx);
function _sendTx (isUnsigned?: boolean): void {
!!extrinsic && queueExtrinsic({
accountId,
extrinsic,
isUnsigned,
txFailedCb: _onFailed,
txStartCb: _onStart,
txSuccessCb: _onSuccess,
txUpdateCb: _onUpdate
});
}
return {
extrinsic,
sendTx: (): void => _sendTx(),
sendUnsigned: (): void => _sendTx(true)
};
}
const txAndSenders = useMemo<ExtrinsicAndSenders>(
(): ExtrinsicAndSenders => getExtrinsicAndSenders(api, accountId, source),
[accountId, source]
);
return {
...txAndSenders,
isSending,
accountId,
onChangeAccountId: (accountId: StringOrNull): void => {
setAccountId(accountId);
onChangeAccountId && onChangeAccountId(accountId);
}
};
}

View File

@ -10,7 +10,7 @@ import { InputBalance } from '@polkadot/react-components';
import Bare from './Bare';
export default function Balance ({ className, defaultValue: { value }, isDisabled, isError, label, onChange, onEnter, style, withLabel }: Props): React.ReactElement<Props> {
export default function Balance ({ className, defaultValue: { value }, isDisabled, isError, label, onChange, onEnter, onEscape, style, withLabel }: Props): React.ReactElement<Props> {
const defaultValue = new BN((value as BN || '0').toString()).toString(10);
const _onChange = (value?: BN): void =>
onChange && onChange({
@ -32,6 +32,7 @@ export default function Balance ({ className, defaultValue: { value }, isDisable
onChange={_onChange}
withEllipsis
onEnter={onEnter}
onEscape={onEscape}
withLabel={withLabel}
/>
</Bare>

View File

@ -42,7 +42,7 @@ function convertInput (value: string): [boolean, Uint8Array] {
return [value === '0x', new Uint8Array([])];
}
export default function BaseBytes ({ asHex, children, className, defaultValue: { value }, isDisabled, isError, label, length = -1, onChange, onEnter, size = 'full', style, validate = defaultValidate, withLabel, withLength }: Props): React.ReactElement<Props> {
export default function BaseBytes ({ asHex, children, className, defaultValue: { value }, isDisabled, isError, label, length = -1, onChange, onEnter, onEscape, size = 'full', style, validate = defaultValidate, withLabel, withLength }: Props): React.ReactElement<Props> {
const [isValid, setIsValid] = useState(false);
useEffect((): void => {
@ -102,6 +102,7 @@ export default function BaseBytes ({ asHex, children, className, defaultValue: {
label={label}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
placeholder='0x...'
type='text'
withEllipsis

View File

@ -11,7 +11,7 @@ import { Button } from '@polkadot/react-components';
import BaseBytes from './BaseBytes';
import File from './File';
export default function Bytes ({ className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, style, type, withLabel }: Props): React.ReactElement<Props> {
export default function Bytes ({ className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, onEscape, style, type, withLabel }: Props): React.ReactElement<Props> {
const [isFileDrop, setIsFileDrop] = useState(false);
const _toggleFile = (): void => setIsFileDrop(true);
@ -45,6 +45,7 @@ export default function Bytes ({ className, defaultValue, isDisabled, isError, l
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
withLabel={withLabel}

View File

@ -9,7 +9,7 @@ import React from 'react';
import Bytes from './Bytes';
import BytesFile from './File';
function renderDisabled ({ className, defaultValue, isError, label, onEnter, style, type, withLabel }: Props): React.ReactNode {
function renderDisabled ({ className, defaultValue, isError, label, onEnter, onEscape, style, type, withLabel }: Props): React.ReactNode {
return (
<Bytes
className={className}
@ -17,6 +17,7 @@ function renderDisabled ({ className, defaultValue, isError, label, onEnter, sty
isError={isError}
label={label}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
withLabel={withLabel}

View File

@ -21,7 +21,7 @@ function onChange ({ onChange }: Props): (_: string) => void {
}
export default function Data (props: Props): React.ReactElement<Props> {
const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, style, withLabel } = props;
const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, onEscape, style, withLabel } = props;
const defaultValue = value
? (value.toHex ? value.toHex() : value)
: '';
@ -39,6 +39,7 @@ export default function Data (props: Props): React.ReactElement<Props> {
label={label}
onChange={onChange(props)}
onEnter={onEnter}
onEscape={onEscape}
placeholder='Hex data'
type='text'
withLabel={withLabel}

View File

@ -8,7 +8,7 @@ import React from 'react';
import BaseBytes from './BaseBytes';
export default function Hash256 ({ className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, style, type, withLabel }: Props): React.ReactElement<Props> {
export default function Hash256 ({ className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, onEscape, style, type, withLabel }: Props): React.ReactElement<Props> {
return (
<BaseBytes
className={className}
@ -20,6 +20,7 @@ export default function Hash256 ({ className, defaultValue, isDisabled, isError,
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
withLabel={withLabel}

View File

@ -8,7 +8,7 @@ import React from 'react';
import BaseBytes from './BaseBytes';
export default function Hash512 ({ className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, style, type, withLabel }: Props): React.ReactElement<Props> {
export default function Hash512 ({ className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, onEscape, style, type, withLabel }: Props): React.ReactElement<Props> {
return (
<BaseBytes
className={className}
@ -20,6 +20,7 @@ export default function Hash512 ({ className, defaultValue, isDisabled, isError,
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
withLabel={withLabel}

View File

@ -53,7 +53,7 @@ function parseFile (raw: Uint8Array): Parsed {
};
}
function KeyValueArray ({ className, defaultValue, isDisabled, isError, label, onChange, onEnter, style, t, withLabel }: Props): React.ReactElement<Props> {
function KeyValueArray ({ className, defaultValue, isDisabled, isError, label, onChange, onEnter, onEscape, style, t, withLabel }: Props): React.ReactElement<Props> {
const [placeholder, setPlaceholder] = useState(t(EMPTY_PLACEHOLDER));
if (isDisabled) {
@ -80,6 +80,7 @@ function KeyValueArray ({ className, defaultValue, isDisabled, isError, label, o
label={keyHex}
name={keyHex}
onEnter={onEnter}
onEscape={onEscape}
type={BYTES_TYPE}
/>
);

View File

@ -34,7 +34,7 @@ function onChange ({ onChange }: Props): (_: RawParamOnChangeValue) => void {
}
export default function Code (props: Props): React.ReactNode {
const { className, defaultValue, isDisabled, isError, label, onEnter, style, type, withLabel } = props;
const { className, defaultValue, isDisabled, isError, label, onEnter, onEscape, style, type, withLabel } = props;
if (isDisabled) {
return (
@ -53,6 +53,7 @@ export default function Code (props: Props): React.ReactNode {
label={label}
onChange={onChange(props)}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
withLabel={withLabel}

View File

@ -15,7 +15,7 @@ import Param from './index';
interface Props extends CProps, I18nProps {}
function Option ({ className, defaultValue, isDisabled, name, onChange, onEnter, t, type: { sub } }: Props): React.ReactElement<Props> {
function Option ({ className, defaultValue, isDisabled, name, onChange, onEnter, onEscape, t, type: { sub } }: Props): React.ReactElement<Props> {
const [isActive, setIsActive] = useState(false);
useEffect((): void => {
@ -34,6 +34,7 @@ function Option ({ className, defaultValue, isDisabled, name, onChange, onEnter,
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
type={sub as TypeDef}
/>
{!isDisabled && (

View File

@ -21,7 +21,7 @@ function onChange ({ onChange }: Props): (_: string) => void {
}
export default function Text (props: Props): React.ReactNode {
const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, style, withLabel } = props;
const { className, defaultValue: { value }, isDisabled, isError, label, onEnter, onEscape, style, withLabel } = props;
const defaultValue = (value || '').toString();
return (
@ -37,6 +37,7 @@ export default function Text (props: Props): React.ReactNode {
label={label}
onChange={onChange(props)}
onEnter={onEnter}
onEscape={onEscape}
placeholder='<any string>'
type='text'
withLabel={withLabel}

View File

@ -15,7 +15,7 @@ interface Props extends BareProps {
}
export default function Unknown (props: Props): React.ReactElement<Props> {
const { className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, style, type } = props;
const { className, defaultValue, isDisabled, isError, label, name, onChange, onEnter, onEscape, style, type } = props;
if (isDisabled) {
return <Static {...props} />;
@ -33,6 +33,7 @@ export default function Unknown (props: Props): React.ReactElement<Props> {
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
withLength={false}

View File

@ -20,7 +20,7 @@ interface Props extends I18nProps, BaseProps {
overrides?: ComponentMap;
}
function Param ({ className, defaultValue, isDisabled, isOptional, name, onChange, onEnter, overrides, style, type }: Props): React.ReactElement<Props> | null {
function Param ({ className, defaultValue, isDisabled, isOptional, name, onChange, onEnter, onEscape, overrides, style, type }: Props): React.ReactElement<Props> | null {
const compRef = useRef<React.ComponentType<CProps> | null>(findComponent(type, overrides));
if (!compRef.current) {
@ -49,6 +49,7 @@ function Param ({ className, defaultValue, isDisabled, isOptional, name, onChang
name={name}
onChange={onChange}
onEnter={onEnter}
onEscape={onEscape}
style={style}
type={type}
/>

View File

@ -16,12 +16,13 @@ interface Props {
name?: string;
onChange: (index: number, value: RawParamOnChangeValue) => void;
onEnter?: () => void;
onEscape?: () => void;
overrides?: ComponentMap;
type: TypeDef;
values?: RawParams | null;
}
export default function ParamComp ({ defaultValue, index, isDisabled, name, onChange, onEnter, overrides, type }: Props): React.ReactElement<Props> {
export default function ParamComp ({ defaultValue, index, isDisabled, name, onChange, onEnter, onEscape, overrides, type }: Props): React.ReactElement<Props> {
const _onChange = (value: RawParamOnChangeValue): void =>
onChange(index, value);
@ -34,6 +35,7 @@ export default function ParamComp ({ defaultValue, index, isDisabled, name, onCh
name={name}
onChange={_onChange}
onEnter={onEnter}
onEscape={onEscape}
overrides={overrides}
type={type}
/>

View File

@ -19,6 +19,7 @@ interface Props extends I18nProps {
isDisabled?: boolean;
onChange?: (value: RawParams) => void;
onEnter?: () => void;
onEscape?: () => void;
overrides?: ComponentMap;
params: ParamDef[];
values?: RawParams | null;
@ -72,7 +73,7 @@ class Params extends React.PureComponent<Props, State> {
}
public render (): React.ReactNode {
const { className, isDisabled, overrides, params, style } = this.props;
const { className, isDisabled, onEnter, onEscape, overrides, params, style } = this.props;
const { values = this.props.values } = this.state;
if (!values || !values.length) {
@ -93,6 +94,8 @@ class Params extends React.PureComponent<Props, State> {
key={`${name}:${type}:${index}`}
name={name}
onChange={this.onChangeParam}
onEnter={onEnter}
onEscape={onEscape}
overrides={overrides}
type={type}
/>

View File

@ -24,6 +24,7 @@ export interface RawParamOnChangeValue {
}
export type RawParamOnChange = (value: RawParamOnChangeValue) => void;
export type RawParamOnEnter = () => void;
export type RawParamOnEscape = () => void;
export type RawParams = RawParam[];
@ -32,6 +33,7 @@ export interface BaseProps extends BareProps {
name?: string;
onChange?: RawParamOnChange;
onEnter?: RawParamOnEnter;
onEscape?: RawParamOnEscape;
type: TypeDef;
}