import{LitElement as e,html as t,css as n}from"../../../../lit/index.js";class MonacoElement extends e{static get styles(){return[n`
        :host {
          display: block;
        }
        iframe {
          border: none;
          width: 100%;
          height: 100%;
          padding: 0;
          margin: 0;
          resize: vertical;
        }
      `]}constructor(){super(),this.windowControllers=new AbortController,this.iframe=null,this.value="",this.fontSize=16,this.wordWrap=!1,this.tabSize=2,this.readOnly=!1,this.eventTypes={ready:"ready",focus:"focus",blur:"blur",valueChanged:"valueChanged",languageChanged:"languageChanged",themeChanged:"themeChanged"},this.language="javascript",this.theme="vs-dark",this.libPath="node_modules/monaco-editor/min/vs",this.autofocus=!1,this.hideLineNumbers=!1,this.editorReference=this.generateUUID()}render(){return t` <iframe
      id="iframe"
      frameborder="0"
      aria-label="Code editor"
    ></iframe>`}static get properties(){return{value:{type:String},fontSize:{type:Number,attribute:"font-size"},wordWrap:{type:Boolean,attribute:"word-wrap"},readOnly:{type:Boolean,attribute:"read-only"},uniqueKey:{type:String,attribute:"unique-key"},eventTypes:{type:Object},language:{type:String},theme:{type:String},libPath:{type:String,attribute:"lib-path"},editorReference:{type:String,reflect:!0,attribute:"editor-reference"},autofocus:{type:Boolean,reflect:!0},hideLineNumbers:{type:Boolean,attribute:"hide-line-numbers"},tabSize:{type:Number,attribute:"tab-size"}}}generateUUID(){return"ss-s-s-s-sss".replace(/s/g,this._uuidPart)}_uuidPart(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}get document(){if(this.iframe&&this.iframe.contentWindow)return this.iframe.contentWindow.document}updated(e){e.forEach(((e,t)=>{"value"==t&&this.monacoValueChanged(this[t]),"language"==t&&this.monacoLanguageChanged(this[t]),"theme"==t&&this.monacoThemeChanged(this[t])}))}firstUpdated(e){super.firstUpdated(e),this.__init||setTimeout((()=>{this.initIFrame()}),500)}connectedCallback(){super.connectedCallback(),this.__init||this.initIFrame(),globalThis.addEventListener("message",(e=>{this.handleMessage(e)}),{signal:this.windowControllers.signal})}disconnectedCallback(){this.windowControllers.abort(),this.__init=!1,super.disconnectedCallback()}initIFrame(){if(this.iframe=this.shadowRoot.querySelector("#iframe"),this.document&&!this.__init){this.__init=!0;const t=globalThis.document.createElement("div");t.id="container",this.document.body.appendChild(t);var e=`\n  var eventTypes = {\n    ready: 'ready',\n    focus: 'focus',\n    blur: "blur",\n    valueChanged: 'valueChanged',\n    languageChanged: 'languageChanged',\n    themeChanged: 'themeChanged',\n  };\n\n  class MonacoEditor {\n    constructor(editorReference) {\n      this._editorReference_ = editorReference;\n      this.language = 'javascript';\n      this.value = '';\n      this.editor = null;\n      this.setupEventListener('message', this.handleMessage.bind(this));\n      this.setupEditor();\n    }\n\n    setupEditor() {\n      require.config({ paths: { vs: '${this.libPath}' } });\n      require(['vs/editor/editor.main'], () => {\n        this.editor = monaco.editor.create(globalThis.document.getElementById('container'), {\n          value: this.value,\n          language: '${this.language}',\n          scrollBeyondLastLine: false,\n          automaticLayout: true,\n          ${this.hideLineNumbers?"lineNumbers: 'false',":""}\n          fontSize: ${this.fontSize},\n          wordWrap: ${this.wordWrap},\n          readOnly: ${this.readOnly},\n          automaticLayout: true,\n          minimap: {\n            enabled: true\n          },\n          tabSize: ${this.tabSize},\n          autoIndent: true,\n        });\n        const model = this.editor.getModel();\n        model.onDidChangeContent(() => {\n          const value = model.getValue();\n          this.onValueChanged(value);\n        });\n        this.ready();\n      });\n    }\n\n    ready() {\n      setTimeout(root => {\n        this.postMessage(eventTypes.ready, null);\n        if(${this.autofocus}) this.editor.focus();\n        this.setupEventListener(\n          eventTypes.valueChanged,\n          this.onValueChanged.bind(this)\n        );\n        this.editor.onDidFocusEditorText(e=>{\n          this.postMessage(eventTypes.focus, null);\n        });\n        this.editor.onDidBlurEditorText(e=>{\n          this.postMessage(eventTypes.blur, null);\n        });\n        this.editor.onDidFocusEditorWidget(e=>{\n          this.postMessage(eventTypes.focus, null);\n        });\n        this.editor.onDidBlurEditorWidget(e=>{\n          this.postMessage(eventTypes.blur, null);\n        });\n      }, 100);\n    }\n\n    _handleMessage(data) {\n      switch (data.event) {\n        case eventTypes.valueChanged:\n          this.onInputValueChanged(data.payload);\n          break;\n        case eventTypes.languageChanged:\n          this.onLanguageChanged(data.payload);\n          break;\n        case eventTypes.themeChanged:\n          this.onThemeChanged(data.payload);\n          break;\n        default:\n          break;\n      }\n    }\n\n    handleMessage(message) {\n      try {\n        const data = JSON.parse(message.data);\n        this._handleMessage(data);\n      } catch (error) {\n        console.warn(error);\n        return;\n      }\n    }\n\n    postMessage(event, payload) {\n      var msg = {\n        event: event,\n        payload: payload,\n        editorReference: this._editorReference_\n      }\n      globalThis.parent.postMessage(msg, globalThis.parent.location.href);\n    }\n\n    setupEventListener(type, callback) {\n      globalThis.addEventListener(type, data => {\n        callback(data);\n      });\n    }\n\n    onInputValueChanged(newValue) {\n      if (newValue !== this.value) {\n        this.value = newValue;\n        this.editor.getModel().setValue(newValue);\n        this.postMessage(eventTypes.valueChanged, newValue);\n      }\n    } \n\n    onValueChanged(newValue) {\n      if (newValue !== this.value) {\n        this.value = newValue;\n        this.postMessage(eventTypes.valueChanged, newValue);\n      }\n    }\n\n    onLanguageChanged(newLang) {\n      monaco.editor.setModelLanguage(this.editor.getModel(), newLang);\n    }\n\n    onThemeChanged(newValue) {\n      monaco.editor.setTheme(newValue);\n    }\n  }\n\n  new MonacoEditor("${this.editorReference}");`;this.insertScriptElement({src:`${this.libPath}/loader.js`,onload:()=>{this.insertScriptElement({text:e}),this.insertStyle()}})}this.autofocus&&this.iframe&&this.iframe.focus()}handleMessage(e){try{let t=e.data;"string"==typeof e.data&&(t=JSON.parse(e.data)),this._handleMessage(t)}catch(e){return void console.warn("[monaco-element] Error while parsing message:",e)}}_handleMessage(e){if(e.editorReference===this.editorReference)if(e.event===this.eventTypes.valueChanged){const t=new CustomEvent("value-changed",{bubbles:!0,cancelable:!0,detail:e.payload});this.dispatchEvent(t)}else e.event===this.eventTypes.ready?this.onIFrameReady():e.event===this.eventTypes.focus?this.onIFrameFocus():e.event===this.eventTypes.blur&&this.onIFrameBlur()}onIFrameFocus(){this.dispatchEvent(new CustomEvent("code-editor-focus",{bubbles:!0,composed:!0,cancelable:!0,detail:!0}))}onIFrameBlur(){this.dispatchEvent(new CustomEvent("code-editor-blur",{bubbles:!0,composed:!0,cancelable:!0,detail:!0}))}onIFrameReady(){this.monacoValueChanged(this.value),this.monacoLanguageChanged(this.language),this.monacoThemeChanged(this.theme),setTimeout((()=>{this.dispatchEvent(new CustomEvent("monaco-element-ready",{bubbles:!0,composed:!0,cancelable:!0,detail:!0}))}),10)}monacoValueChanged(e){this.postMessage(this.eventTypes.valueChanged,e)}monacoLanguageChanged(e){this.postMessage(this.eventTypes.languageChanged,e)}monacoThemeChanged(e){this.postMessage(this.eventTypes.themeChanged,e)}postMessage(e,t){this.iframe&&null!=this.iframe.contentWindow&&this.iframe.contentWindow.postMessage(JSON.stringify({event:e,payload:t}),globalThis.location.href)}insertScriptElement({src:e,text:t,onload:n}){var a=this.document.createElement("script");e&&(a.src=e),t&&(a.text=t),n&&(a.onload=n),this.document.head.appendChild(a)}insertStyle(){var e="\n    body {\n      height: 100vh;\n      overflow: hidden;\n      margin: 0;\n    }    \n    #container {\n      width: 100%;\n      height: 100%;\n    }\n    .debug-red {\n      background : red;\n    }\n    .debug-green {\n      background : green;\n    }\n    html,body {\n      margin : 0px;\n    }";const t=this.document.head,n=this.document.createElement("style");n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(this.document.createTextNode(e)),t.appendChild(n)}}customElements.define("monaco-element",MonacoElement);export{MonacoElement};globalThis.MonacoData=globalThis.MonacoData||{};