// 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>, sub: Array, subTypes: Array, type?: string, values: Array }; export default class Tuple extends React.PureComponent { state: State = { Components: [], sub: [], subTypes: [], values: [] }; static getDerivedStateFromProps ({ defaultValue: { value }, type: { sub, type } }: Props, prevState: State): Partial | null { if (type === prevState.type) { return null; } const subTypes = sub && Array.isArray(sub) ? sub : []; const values = (value as Array).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 ( {Components.map((Component, index) => ( ))} ); } 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) }); }); }; } }