ghost-portal/packages/ui-params/src/Param/Tuple.tsx
Jaco Greeff a8ed300dc4
Small init changes (static state) (#663)
* Small init changes (static state)

* Hide vanity on empty accounts

* Require accounts for apps, cleanup needsApi/needsCalls

* Display InputAddress when disable (but no options)

* Filter toolbox based on accounts

* Accounts gated via app, don't display add

* Cleanup linting

* Validation display & clear on settings types

* Split save for developer & general

* Add Reset button to dev settings
2019-01-31 18:02:47 +01:00

104 lines
2.5 KiB
TypeScript

// Copyright 2017-2019 @polkadot/ui-app 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 { TypeDef } from '@polkadot/types/codec';
import { Props, RawParam } from '../types';
import React from 'react';
import { isUndefined } from '@polkadot/util';
import Bare from './Bare';
import findComponent from './findComponent';
type State = {
Components: Array<React.ComponentType<Props>>,
sub: Array<string>,
subTypes: Array<TypeDef>,
type?: string,
values: Array<RawParam>
};
export default class Tuple extends React.PureComponent<Props, State> {
state: State = {
Components: [],
sub: [],
subTypes: [],
values: []
};
static getDerivedStateFromProps ({ defaultValue: { value }, type: { sub, type } }: Props, prevState: State): Partial<State> | null {
if (type === prevState.type) {
return null;
}
const subTypes = sub && Array.isArray(sub)
? sub
: [];
const values = (value as Array<any>).map((value) =>
isUndefined(value) || isUndefined(value.isValid)
? {
isValid: !isUndefined(value),
value
}
: value
);
return {
Components: subTypes.map((type) => findComponent(type)),
sub: subTypes.map(({ type }) => type),
subTypes,
type,
values
};
}
render () {
const { className, isDisabled, style, withLabel } = this.props;
const { Components, sub, subTypes, values } = this.state;
return (
<Bare
className={className}
style={style}
>
{Components.map((Component, index) => (
<Component
defaultValue={values[index] || {}}
isDisabled={isDisabled}
key={index}
label={sub[index]}
onChange={this.onChange(index)}
type={subTypes[index]}
withLabel={withLabel}
/>
))}
</Bare>
);
}
private onChange = (index: number) => {
const { onChange } = this.props;
return (value: RawParam): void => {
let isValid = value.isValid;
const values = this.state.values.map((svalue, sindex) => {
if (sindex === index) {
return value;
}
isValid = isValid && svalue.isValid;
return svalue;
});
this.setState({ values }, () => {
onChange && onChange({
isValid,
value: values.map(({ value }) => value)
});
});
};
}
}