index.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import React from "react";
  2. import styled from "styled-components";
  3. import Editor from "@monaco-editor/react";
  4. import parseJson from "parse-json";
  5. import { loader } from "@monaco-editor/react";
  6. import { ErrorContainer } from "src/components/ErrorContainer/ErrorContainer";
  7. import useConfig from "src/hooks/store/useConfig";
  8. import { Loading } from "src/components/Loading";
  9. import { CarbonAds } from "src/components/CarbonAds";
  10. loader.config({
  11. paths: {
  12. vs: "https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs",
  13. },
  14. });
  15. const StyledEditorWrapper = styled.div`
  16. display: flex;
  17. flex-direction: column;
  18. height: 100%;
  19. overflow: auto;
  20. user-select: none;
  21. `;
  22. const editorOptions = {
  23. formatOnPaste: true,
  24. minimap: {
  25. enabled: false,
  26. },
  27. };
  28. const StyledWrapper = styled.div`
  29. display: grid;
  30. height: calc(100vh - 36px);
  31. grid-template-columns: 100%;
  32. grid-template-rows: minmax(0, 1fr);
  33. `;
  34. export const JsonEditor: React.FC = () => {
  35. const json = useConfig((state) => state.json);
  36. const lightmode = useConfig((state) => state.settings.lightmode);
  37. const updateJson = useConfig((state) => state.updateJson);
  38. const [value, setValue] = React.useState("");
  39. const [error, setError] = React.useState({
  40. message: "",
  41. isExpanded: true,
  42. });
  43. const editorTheme = React.useMemo(
  44. () => (lightmode ? "light" : "vs-dark"),
  45. [lightmode]
  46. );
  47. React.useEffect(() => {
  48. setValue(JSON.stringify(JSON.parse(json), null, 2));
  49. }, [json]);
  50. React.useEffect(() => {
  51. const formatTimer = setTimeout(() => {
  52. try {
  53. if (!value) {
  54. setError((err) => ({ ...err, message: "" }));
  55. return updateJson("[]");
  56. }
  57. parseJson(value);
  58. updateJson(value);
  59. setError((err) => ({ ...err, message: "" }));
  60. } catch (jsonError: any) {
  61. setError((err) => ({ ...err, message: jsonError.message }));
  62. }
  63. }, 1500);
  64. return () => clearTimeout(formatTimer);
  65. }, [value, updateJson]);
  66. return (
  67. <StyledEditorWrapper>
  68. <ErrorContainer error={error} setError={setError} />
  69. <StyledWrapper>
  70. <Editor
  71. height="100%"
  72. defaultLanguage="json"
  73. value={value}
  74. theme={editorTheme}
  75. options={editorOptions}
  76. loading={<Loading message="Loading Editor..." />}
  77. onChange={(value) => setValue(value as string)}
  78. />
  79. <CarbonAds editor />
  80. </StyledWrapper>
  81. </StyledEditorWrapper>
  82. );
  83. };