index.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2017-2020 @polkadot/react-components authors & contributors
  2. // This software may be modified and distributed under the terms
  3. // of the Apache-2.0 license. See the LICENSE file for details.
  4. // TODO: We have a lot shared between this and InputExtrinsic & InputStorage
  5. import { RpcMethod } from '@polkadot/jsonrpc/types';
  6. import { DropdownOptions } from '../util/types';
  7. import React, { useState } from 'react';
  8. import map from '@polkadot/jsonrpc';
  9. import { useApi } from '@polkadot/react-hooks';
  10. import LinkedWrapper from '../InputExtrinsic/LinkedWrapper';
  11. import SelectMethod from './SelectMethod';
  12. import SelectSection from './SelectSection';
  13. import methodOptions from './options/method';
  14. import sectionOptions from './options/section';
  15. interface Props {
  16. className?: string;
  17. defaultValue: RpcMethod;
  18. help?: React.ReactNode;
  19. isError?: boolean;
  20. label: React.ReactNode;
  21. onChange?: (value: RpcMethod) => void;
  22. style?: any;
  23. withLabel?: boolean;
  24. }
  25. function InputRpc ({ className, defaultValue, help, label, onChange, style, withLabel }: Props): React.ReactElement<Props> {
  26. const { api } = useApi();
  27. const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(methodOptions(api, defaultValue.section));
  28. const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
  29. const [value, setValue] = useState<RpcMethod>((): RpcMethod => defaultValue);
  30. const _onMethodChange = (newValue: RpcMethod): void => {
  31. if (value.section === newValue.section && value.method === newValue.method) {
  32. return;
  33. }
  34. // set via callback since the method is a function itself
  35. setValue((): RpcMethod => newValue);
  36. onChange && onChange(newValue);
  37. };
  38. const _onSectionChange = (section: string): void => {
  39. if (section === value.section) {
  40. return;
  41. }
  42. const optionsMethod = methodOptions(api, section);
  43. setOptionsMethod(optionsMethod);
  44. _onMethodChange(map[section].methods[optionsMethod[0].value]);
  45. };
  46. return (
  47. <LinkedWrapper
  48. className={className}
  49. help={help}
  50. label={label}
  51. style={style}
  52. withLabel={withLabel}
  53. >
  54. <SelectSection
  55. className='small'
  56. onChange={_onSectionChange}
  57. options={optionsSection}
  58. value={value}
  59. />
  60. <SelectMethod
  61. className='large'
  62. onChange={_onMethodChange}
  63. options={optionsMethod}
  64. value={value}
  65. />
  66. </LinkedWrapper>
  67. );
  68. }
  69. export default React.memo(InputRpc);