<script lang="ts">
    import * as monaco from "monaco-editor";
    import { onMount } from "svelte";
    import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker";
    import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker";
    import defaultEnv from "./defaultEnv.d.ts?raw";
    import { code } from "./code";

    let divEl: HTMLDivElement = null;
    let editor: monaco.editor.IStandaloneCodeEditor;

    onMount(async () => {
        // @ts-ignore
        self.MonacoEnvironment = {
            getWorker: function (_moduleId: any, label: string) {
                if (label === "typescript" || label === "javascript") {
                    return new tsWorker();
                }
                return new editorWorker();
            },
        };

        editor = monaco.editor.create(divEl, {
            value: $code,
            language: "typescript",
            automaticLayout: true,
        });

        let lib =
            monaco.languages.typescript.typescriptDefaults.addExtraLib(
                defaultEnv
            );

        editor.onKeyUp((_e) => ($code = editor.getValue()));

        return () => {
            lib.dispose();
            editor.dispose();
        };
    });
</script>

<div class="parent">
    <div class="editor" bind:this={divEl} />
</div>

<style lang="scss">
    .parent {
        flex-grow: 1;
    }

    .editor {
        height: 100%;
    }
</style>
