1<script>
2  import { codeStore, updateCode } from '../code-store.js';
3  import { codeErrorStore } from '../error-store.js';
4  import { onMount } from 'svelte';
5  import mermaid from '@mermaid';
6  import Error from './Error.svelte';
7  import { getResizeHandler, initEditor } from './editor-utils';
8  import * as monaco from 'monaco-editor';
9  import { watchResize } from 'svelte-watch-resize';
10
11  let edit;
12
13  const decArr = [];
14  let editorElem = null;
15  let resizeHandler = () => {};
16  const handleCodeUpdate = (updatedCode, updateEditor) => {
17    try {
18      mermaid.parse(updatedCode);
19      if (edit) {
20        if (updateEditor) {
21          edit.setValue(updatedCode);
22        }
23        decArr.forEach((decor) => {
24          edit.deltaDecorations(decor, []);
25        });
26      }
27      updateCode(updatedCode, false);
28      codeErrorStore.set(undefined);
29    } catch (e) {
30      codeErrorStore.set('Syntax Error');
31      console.log('Error in parsed', e.hash);
32      const l = e.hash.line;
33      decArr.push(
34        edit.deltaDecorations(
35          [],
36          [
37            {
38              range: new monaco.Range(
39                e.hash.loc.first_line,
40                e.hash.loc.last_line,
41                e.hash.loc.first_column,
42                e.hash.loc.last_column
43              ),
44              options: { inlineClassName: 'myInlineDecoration' },
45            },
46          ]
47        )
48      );
49    }
50  };
51
52  const unsubscribe = codeStore.subscribe((state) => {
53    if (state.updateEditor) {
54      handleCodeUpdate(state.code, true);
55    }
56  });
57
58  onMount(async () => {
59    initEditor(monaco);
60    editorElem = document.getElementById('editor');
61    edit = monaco.editor.create(editorElem, {
62      value: '',
63      theme: 'myCoolTheme',
64      language: 'mermaid',
65    });
66    resizeHandler = getResizeHandler(edit);
67    edit.onDidChangeModelContent(function (e) {
68      handleCodeUpdate(edit.getValue(), false);
69    });
70
71    initEditor(monaco);
72  });
73</script>
74
75<style>
76  #editor {
77    width: 100%;
78    height: 400px;
79    max-height: 300px;
80    flex: 1;
81  }
82</style>
83
84<div id="editor-container">
85  <div id="editor" use:watchResize={resizeHandler} />
86  <Error errorStore={codeErrorStore} />
87</div>
88