<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 TS from "typescript";
    import defaultCode from "./defaultCode.ts?raw";
    import defaultEnv from "./defaultEnv.d.ts?raw";
    import { code } from "./code";

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

    let value = defaultCode;
    $: $code = TS.transpile(value, { strict: true });

    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: value,
            language: "typescript",
        });

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

        editor.onKeyUp((_e) => (value = editor.getValue()));

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

<div bind:this={divEl} />

<style lang="scss">
    div {
        flex-grow: 1;
    }
</style>
