index.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import React from 'react';
  2. import { Context } from './context';
  3. import ConfigureButton from './button';
  4. import ConfigureSelect from './select';
  5. import ConfigureMcp from './mcp';
  6. import ConfigureRadioButton from './radioButton';
  7. class Configure extends React.Component<any, any> {
  8. static contextType = Context;
  9. static Button = ConfigureButton;
  10. static Select = ConfigureSelect;
  11. static Mcp = ConfigureMcp;
  12. static RadioButton = ConfigureRadioButton;
  13. constructor(props: any) {
  14. super(props);
  15. this.state = {
  16. value: props.value || props.defaultValue,
  17. };
  18. this._contextValue = {
  19. value: this.state.value,
  20. onChange: this.onChange,
  21. onRemove: this.onRemove,
  22. };
  23. }
  24. _contextValue: any;
  25. onChange = (obj: any, init = false) => {
  26. this.setState((s: any) => {
  27. const { value } = s;
  28. const newValue = { ...value, ...obj };
  29. const { onChange } = this.props;
  30. !init && onChange?.(newValue, obj);
  31. return { value: newValue };
  32. });
  33. }
  34. onRemove = (field: string) => {
  35. this.setState((s: any) => {
  36. const { value = {} } = s;
  37. const newValue = {};
  38. Object.keys(value).forEach((key: string) => {
  39. if (key !== field) {
  40. newValue[key] = value[key];
  41. }
  42. });
  43. const { onChange } = this.props;
  44. onChange?.(newValue);
  45. return { value: newValue };
  46. });
  47. }
  48. getConfigureValue = () => {
  49. return this.state.value;
  50. }
  51. getContextValue = () => {
  52. if (!this._contextValue ||
  53. this._contextValue.value !== this.state.value ||
  54. this._contextValue.onChange !== this.onChange ||
  55. this._contextValue.onRemove !== this.onRemove
  56. ) {
  57. this._contextValue = {
  58. value: this.state.value,
  59. onChange: this.onChange,
  60. onRemove: this.onRemove,
  61. };
  62. }
  63. return this._contextValue;
  64. }
  65. render() {
  66. const { children } = this.props;
  67. return (
  68. <Context.Provider value={this.getContextValue()} >
  69. {children}
  70. </Context.Provider>
  71. );
  72. }
  73. }
  74. export default Configure;