gitscope
← marzneshin / v0.1.4 / app/dashboard/src/components/json-editor/index.tsx
https://dev.kronoz.win/r/marzneshin.git
app/dashboard/src/components/json-editor/index.tsx · TypeScript
Blame Raw
 1import { Box, useColorMode } from '@chakra-ui/react';
 2import JSONEditor, { JSONEditorMode, JSONEditorOptions } from 'jsoneditor';
 3import 'jsoneditor/dist/jsoneditor.css';
 4import { forwardRef, useEffect, useRef } from 'react';
 5import './styles.css';
 6import './themes.js';
 7
 8export type JSONEditorProps = {
 9  onChange: (value: string) => void;
10  json: any;
11  mode?: JSONEditorMode;
12};
13export const JsonEditor = forwardRef<HTMLDivElement, JSONEditorProps>(
14  ({ json, onChange, mode = 'code' }, ref) => {
15    const { colorMode } = useColorMode();
16    const options: JSONEditorOptions = {
17      mode,
18      onChangeText: onChange,
19      statusBar: false,
20      mainMenuBar: false,
21      theme: colorMode === 'dark' ? 'ace/theme/nord_dark' : 'ace/theme/dawn',
22    };
23
24    const jsonEditorContainer = useRef<HTMLDivElement>(null);
25    const jsonEditorRef = useRef<JSONEditor | null>(null);
26
27    useEffect(() => {
28      jsonEditorRef.current = new JSONEditor(
29        jsonEditorContainer.current!,
30        options
31      );
32
33      return () => {
34        if (jsonEditorRef.current) jsonEditorRef.current.destroy();
35      };
36    }, []);
37
38    useEffect(() => {
39      if (jsonEditorRef.current) jsonEditorRef.current.update(json);
40    }, [json]);
41
42    return (
43      <Box
44        ref={ref}
45        border="1px solid"
46        borderColor="gray.300"
47        _dark={{
48          borderColor: 'gray.500',
49        }}
50        borderRadius={5}
51        h="full"
52      >
53        <Box height="full" ref={jsonEditorContainer} />
54      </Box>
55    );
56  }
57);