✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML and CSV into interactive graphs.
import React, { useCallback } from "react";
import { LoadingOverlay } from "@mantine/core";
import styled from "styled-components";
import Editor, { type EditorProps, loader, type OnMount, useMonaco } from "@monaco-editor/react";
import useConfig from "../../store/useConfig";
import useFile from "../../store/useFile";
loader.config({
paths: {
vs: "https://unpkg.com/[email protected]/min/vs",
},
});
const editorOptions: EditorProps["options"] = {
tabSize: 2,
formatOnType: true,
minimap: { enabled: false },
stickyScroll: { enabled: false },
scrollBeyondLastLine: false,
placeholder: "Start typing...",
};
const TextEditor = () => {
const monaco = useMonaco();
const contents = useFile(state => state.contents);
const setContents = useFile(state => state.setContents);
const setError = useFile(state => state.setError);
const jsonSchema = useFile(state => state.jsonSchema);
const getHasChanges = useFile(state => state.getHasChanges);
const theme = useConfig(state => (state.darkmodeEnabled ? "vs-dark" : "light"));
const fileType = useFile(state => state.format);
const jsonDefaults = (monaco?.languages as any)?.json?.jsonDefaults as
{ setDiagnosticsOptions: (options: unknown) => void } | undefined;
React.useEffect(() => {
if (!jsonDefaults) return;
jsonDefaults.setDiagnosticsOptions({
validate: true,
allowComments: true,
enableSchemaRequest: true,
...(jsonSchema && {
schemas: [
{
uri: "http://myserver/foo-schema.json",
fileMatch: ["*"],
schema: jsonSchema,
},
],
}),
});
}, [jsonDefaults, jsonSchema]);
React.useEffect(() => {
const beforeunload = (e: BeforeUnloadEvent) => {
if (getHasChanges()) {
const confirmationMessage =
"Unsaved changes, if you leave before saving your changes will be lost";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage;
}
};
window.addEventListener("beforeunload", beforeunload);
return () => {
window.removeEventListener("beforeunload", beforeunload);
};
}, [getHasChanges]);
const handleMount: OnMount = useCallback(editor => {
editor.onDidPaste(() => {
editor.getAction("editor.action.formatDocument")?.run();
});
}, []);
return (
<StyledEditorWrapper>
<StyledWrapper>
<Editor
height="100%"
language={fileType}
theme={theme}
value={contents}
options={editorOptions}
onMount={handleMount}
onValidate={errors => setError(errors[0]?.message || "")}
onChange={contents => setContents({ contents, skipUpdate: true })}
loading={<LoadingOverlay visible />}
/>
</StyledWrapper>
</StyledEditorWrapper>
);
};
export default TextEditor;
const StyledEditorWrapper = styled.div`
display: flex;
flex-direction: column;
height: 100%;
user-select: none;
`;
const StyledWrapper = styled.div`
display: grid;
height: 100%;
grid-template-columns: 100%;
grid-template-rows: minmax(0, 1fr);
`;