index.tsx 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { Input, Modal } from 'antd';
  2. import { FormOutlined } from '@ant-design/icons';
  3. import { useEffect, useState } from 'react';
  4. import MonacoEditor from 'react-monaco-editor';
  5. import { isObject } from 'lodash';
  6. type MetaDataJsonInputProps = {
  7. json: Record<string, any>;
  8. value?: string;
  9. onChange?: (value: string) => void;
  10. };
  11. export const MetaDataJsonHandle = (data: any): Record<string, any> => {
  12. const _JSON = {};
  13. if (isObject(data)) {
  14. const type = (data as any).valueType.type;
  15. const id = (data as any).id;
  16. switch (type) {
  17. case 'object':
  18. _JSON[id] = MetaDataJsonHandle((data as any)['json']['properties'][0]);
  19. break;
  20. case 'array':
  21. _JSON[id] = [];
  22. break;
  23. case 'int':
  24. case 'long':
  25. case 'float':
  26. case 'double':
  27. _JSON[id] = 0;
  28. break;
  29. case 'boolean':
  30. _JSON[id] = false;
  31. break;
  32. default:
  33. _JSON[id] = '';
  34. break;
  35. }
  36. }
  37. return _JSON;
  38. };
  39. export default (props: MetaDataJsonInputProps) => {
  40. const [value, setValue] = useState(props.value || '');
  41. const [visible, setVisible] = useState(false);
  42. const [monacoValue, setMonacoValue] = useState<string>('');
  43. const onChange = (data: string) => {
  44. if (props.onChange) {
  45. const newData = data.replace(/[ ]/g, '');
  46. props.onChange(newData);
  47. }
  48. };
  49. const editorDidMountHandle = (editor: any) => {
  50. editor.onDidContentSizeChange?.(() => {
  51. editor.getAction('editor.action.formatDocument').run();
  52. });
  53. };
  54. useEffect(() => {
  55. setValue(props.value || '');
  56. }, [props.value]);
  57. useEffect(() => {
  58. if (props.json) {
  59. const _json = MetaDataJsonHandle(props.json);
  60. onChange(JSON.stringify(_json));
  61. }
  62. }, [props.json]);
  63. return (
  64. <>
  65. <Input
  66. addonAfter={
  67. <FormOutlined
  68. onClick={() => {
  69. setMonacoValue(value);
  70. setVisible(true);
  71. }}
  72. />
  73. }
  74. value={value}
  75. onChange={(e) => {
  76. setValue(e.target.value);
  77. onChange(e.target.value);
  78. }}
  79. />
  80. <Modal
  81. visible={visible}
  82. title={'编辑'}
  83. onOk={() => {
  84. onChange(monacoValue);
  85. setVisible(false);
  86. }}
  87. onCancel={() => {
  88. setVisible(false);
  89. }}
  90. width={700}
  91. >
  92. <MonacoEditor
  93. width={'100%'}
  94. height={400}
  95. theme="vs-dark"
  96. language={'json'}
  97. value={monacoValue}
  98. onChange={(newValue) => {
  99. setMonacoValue(newValue);
  100. }}
  101. editorDidMount={editorDidMountHandle}
  102. />
  103. </Modal>
  104. </>
  105. );
  106. };