thestrukture/IDE

View on GitHub
tmpl/js.tmpl

Summary

Maintainability
Test Coverage
    <!-- jQuery first, then Bootstrap JS. -->
    <!-- Modal -->
<div class="modal fade" id="accountJoin" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="exampleModalLabel"></h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Welcome to the Strukture! To get started enter a username that will be used for chat.</p>
        <hr>
        <p><input type="text" class="form-control username-input" name="" placeholder="username"></p>
      </div>
      <div class="modal-footer">
  
        <button type="button" onclick="saveProfile()" class="btn btn-primary">Save</button>
      </div>
    </div>
  </div>
</div>


    <script src="/dist/jquery.js"></script>
    <script src="/dist/bootstrap.js" ></script>
    <script type="text/javascript" src="/dist/havok.js"></script>
    <script src="/dist/jstree.min.js"></script>
    <script src="/dist/jquery.toolbar.js"></script>
    <script src="/ajax-loading.js"></script>
    <script type="text/javascript">
        var __loading = $.loading()
    </script>
    <script type="text/javascript" src="dist/jquery.terminal-0.10.8.min.js"></script>
     <script type="text/javascript" src="dist/unix_formatting.js"></script>
    <script src="/dist/src/ace.js"></script>
    <script src="/dist/src/ext-language_tools.js"></script>
    <script src="dist/sweetalert.min.js"></script>
    <script type="text/javascript" src="/dist/hotkeys.js"></script>
    <script type="text/javascript" src="/dist/jquery.ui.position.js"></script>
    <script type="text/javascript" src="/dist/jquery.contextMenu.js"></script>
    <script type="text/javascript">
    var working = false;
    var editors = {};
    var kanbanBoards = {};
    var editorPaths = {};

    var termsize = 0;

    var dirHandle;

    async function uploadDirectory(project){

      dirHandle = await window.showDirectoryPicker();

      iterateOver(dirHandle, project)
    }

    const headers = {
            "accept": "*/*",
            "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "x-requested-with": "XMLHttpRequest"
    }

    async function iterateOver(dirHandle, project, path = "/"){

      var it = dirHandle.entries()
      var next = await it.next()

      while(!next.done){

        const [name, handler] = next.value

         if (handler.kind === 'directory') {
              // run directory code
              let newPath = path == "/"  ? path + name  : path + "/" +  name
              //mkdir
              await fetch("http://localhost:8884/api/act", {
                headers,
                "referrer": "http://localhost:8884/",
                "referrerPolicy": "strict-origin-when-cross-origin",
                "body": `type=60&pkg=${project}&prefix=${path}&path=${name}&basesix=&fmode=dir`,
                "method": "POST",
                "mode": "cors",
                "credentials": "include"
              });

              await iterateOver(handler, project, newPath)

         } else  {

            // write file
            
              
          await fetch("http://localhost:8884/api/act", {
             headers,
            "referrer": "http://localhost:8884/",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": `type=60&pkg=${project}&prefix=${path}&path=${name}&basesix=&fmode=touch`,
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
          });

          fileData = await handler.getFile();
          let text = await fileData.text()


          await fetch("http://localhost:8884/api/put", {
            headers,
            "referrer": "http://localhost:8884/",
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": `type=30&target=${path}/${name}&pkg=${project}&data=${encodeURIComponent(text)}`,
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
          });

          

           
          

         }


        next = await it.next()
      }

      $(".modal .close").click()
      updateTree()
    }

    window.debugFn = (cmd) => {
      socketTerminal.send(cmd + " \n");
    }

    try {
      if(!window.localStorage["chatName"]){

        $("#accountJoin").modal('show');
      }

      if(!window.localStorage["struktureid"]){
        window.localStorage.struktureid = `${makeid()}-${makeid()}-${(new Date()).getTime()}`;
      }

    } catch(e) {

    } 
        /*
        Plugin format :
        name : "Name"
        show: function(code)
        exec : function(code,editor)
        */
      $trukture = {
      addPlugin:function(plugin){
          $trukture.plugins.push(plugin)
      },
      exec: function(cmd,callback){
              //console call here
              $.ajax({url:"/api/console",type:"POST",data:{command:cmd},success:function(html){
                  if (html.includes("Error::")){
                      callback(false, html)
                  } else {
                callback(html)
                 }
          },error:function(e){
               callback(false, e.responseText);
           }})
      },
      FindPlugin : function(name){
          for (var i = $trukture.plugins.length - 1; i >= 0; i--) {
             var plugin = $trukture.plugins[i];
             if ( plugin.name == name ) {
                 return plugin;
             }
         }
      },
      plugins:[]
      }

    function addBubble(message){
      //chatroom-thread
      let styles = "margin-bottom:5px;max-width:240px;";
      if(message.name == window.localStorage["chatName"]){
        styles +=  "margin-left:auto;";
      }

      $(".chat-thread").append(`<div class='list-group-item' style='${styles}'><h6>${message.name}<h6>
        <hr>
        <div>${message.message}</div><br>${ (new Date()).toLocaleString() }</div>` );

      var d = $('.chat-thread');
      d.scrollTop(d.prop("scrollHeight"));
    }



    function toggleChat(){
       if($(".chat-window").css("display") == "none" ){
          $(".chat-window").css("display", "block");
          return;
       } 

       $(".chat-window").css("display", "none");
    }

    function saveProfile(){
        let name = $(".username-input").val();
        window.localStorage["chatName"] = name;
        $("#accountJoin").modal('hide');
        sendMessage({message : window.localStorage["chatName"] + " has joined the chatroom." })
    }

     function sendMessage(obj){
        let payload = Object.assign(obj, { name : window.localStorage["chatName"]  });
        socket.send(JSON.stringify(payload));
      }

    function sendChat(){
      //chat-input
      if($(".chat-input").val() == "" )
        return;

      sendMessage({message : $(".chat-input").val() });
      $(".chat-input").val(""); 
    }

    $(".chat-input").keyup(function(e) {
     var code = e.keyCode ? e.keyCode : e.which;
     if (code == 13) {  // Enter keycode
        sendChat();
     }
  });

    function connectSocket(){
      window.socket = new WebSocket("ws://" + window.location.host + "/api/socket");


      socket.onclose = function(event) {
        console.log("WebSocket is closed now.");
        swal("Connection closed!", "Realtime functionality will not currently work, to restore it, please refresh the page.", "warning");
      };
      // Connection opened
      socket.addEventListener('open', function (event) {
          if(window.localStorage["chatName"])
             sendMessage({message : window.localStorage["chatName"] + " has joined the chatroom." })
      });

      // Listen for messages
      socket.addEventListener('message', function (event) {
          processMessage(JSON.parse(event.data) );
        });
    }

    function processMessage(data){
      //editor change
      if(data.editor && data.name != window.localStorage["chatName"]){
          if(editorPaths[data.path]){
          
              if( editorPaths[data.path].getValue() != data.editor){
                  let currentCursor =  editorPaths[data.path].getCursorPosition();
                  editorPaths[data.path].setValue(data.editor);
                  editorPaths[data.path].moveCursorToPosition(currentCursor);

              }

          }
      }

      //chat message
      if(data.message){
        addBubble(data);
      }
      //kanban change

      if(data.board && data.name){
        if(!kanbanBoards[data.board])
          return;

          console.log("Updating board");
          kanbanBoards[data.board]();
          data.message = data.name + " has updated " + data.board;
          addBubble(data);
      }
    }

    connectSocket();

      function handleClickStruk(plugin,txt,editorid,pkg){
          //console.log(plugin,txt,editorid)
          $trukture.exec("cd " + pkg,function(dud){})
          var plugin = $trukture.FindPlugin(plugin)
          var edt = editors[editorid];
          var execution = plugin.exec(txt,edt)

          if (typeof(execution) == "string") {
                  edt.insert( execution)    
          } 

      }

     function getItems(code){
         var codeedit = {
            "sep1": "---------"
         }

         for (var i = $trukture.plugins.length - 1; i >= 0; i--) {
             var plugin = $trukture.plugins[i];
             if ( plugin.show(code) ) {
                 codeedit[plugin.name] = {name: plugin.name}
             }
         }

         return codeedit
     }


     //add plugin go get github dep

   

    
    function addtermwidth(){
        if (termsize != 2){
          //below limit
          if(termsize == 0){
            termsize = 1;
              $(".terminal-side").css("width","50" + percentagetext)
          }
           else if(termsize == 1){
            termsize = 2;
              $(".terminal-side").css("width","95" + percentagetext)
          }
        }
    }

    function removePlugin(path){
        //
        $.ajax({url:"/api/delete", type:"POST", data:{type: "101",pkg:path} ,success:function(html){
            $("[data-plugin='" + path +"']").remove()
        },error:function(e){
            $(".plugin-list").html(e.responseText)

        } })
    }

    function GetPlugins(){
        //plugin-list
        $.ajax({url:"/api/new", type:"POST", data:{type: "101"} ,error:function(e){
            $(".plugin-list").html(e.responseText)
        } })
    }


    function CollapseGloj(){
        if($(".panel-k-left").css('display') == "none"){

          $(".right-bay").removeClass("side-bay")
          $(".left-bay").addClass("side-bay")
          $(".panel-k-left").css('display',"block");
          $(".panel-k-right").addClass("col-sm-9");
          $(".panel-k-right").removeClass("col-sm-12");
         $(".cps-side").html('<i class="fa fa-compress"></i> Hide')        
         // $(".recop").css("display","none");
        } else {
          $(".left-bay").removeClass("side-bay")
          $(".right-bay").addClass("side-bay")
          $(".panel-k-left").css('display',"none");
          $(".panel-k-right").removeClass("col-sm-9");
          $(".panel-k-right").addClass("col-sm-12");
         // $(".recop").css("display","block");
           $(".cps-side").html('<i class="fa fa-arrow-right"></i> Show')

        }
    }

    function redtermwidth(){
         if (termsize != 0){
          //below limit
          if(termsize == 1){
            termsize = 0;
              $(".terminal-side").css("width","320px")
          }
           else if(termsize == 2){
            termsize = 1;
              $(".terminal-side").css("width","50" + percentagetext)
          }
        }
    }

      var langTools = ace.require("ace/ext/language_tools");
      
      var autoCompleter = {
        identifierRegexps: [/[a-zA-Z_0-9]\.\s/],
        getCompletions: function(editor, session, pos, prefix, callback) {
         
           let pkg  =  $(".tabview.active").attr("pkg"),
           id = $(".tabview.active").attr("id");

           //console.log(session, pos, prefix)

           if(editor.custom){

              let latest = editor.getValue();
              let index = editor.session.doc.positionToIndex(editor.selection.getCursor()) ;
              let lastEntry;
              $.ajax(
              {
                url : "/api/complete",
                type : "POST",
                data : {
                  content : latest,
                  pref : index,
                  pkg,
                  gocode : "true",
                  id
                },
                success : function(html){
                  let completions = html ? html[1] : false;

                  if(completions && completions.length > 0){
                   
                    callback(null, completions.map(function(ea) {
                      
                      if(prefix[prefix.length - 1] === ".")
                        ea.package = prefix;

                      let ret = {caption: ea.name, value:prefix[prefix.length - 1] === "." ? ea.package + ea.name : ea.name, score: 0, meta: ea.type + " " + ea.class, trigger : true}

                      return ret
                    }));
                  } else {
                     callback(null, [])
                  } 
                }
              }
              )

              
           } 
        }
    }
    langTools.addCompleter(autoCompleter);

     function vetAndLint(id,pkg, path){
      resetVetter(id)
      let file = path

      let errors = []
        $.ajax({type : "POST", data : { 
          pkg 
        } ,url: "/api/govet", success:function(html){
          
          let cText = html.Text.split("\n")
         
          
          for(var i = 1; i < cText.length;i++){

            let line = cText[i]

            if ( line.includes(file) ){
              let lineParts = line.split(":")
              if( lineParts[2] ){
                let lastBit = lineParts[ lineParts.length - 1]
                
                errors.push({
                    row: parseInt(lineParts[1]) - 1,
                    column: 0,
                    text: lastBit, 
                    type: "warning" //This would give a red x on the gutter
                })
          

              }
            }
          }

          editors[id].getSession().setAnnotations(errors)
          
          

       } });


        $.ajax({type : "POST", data : { 
          pkg,
          path 
        },url: "/api/golint", success:function(html){
          
          let cText = html.Text.split("\n")
          
          
          for(var i = 0; i < cText.length;i++){

            let line = cText[i]

            if ( line.includes(file) ){
              let lineParts = line.split(":")
              if( lineParts[1] ){
                let lastBit = lineParts[ lineParts.length - 1]
                
                errors.push({
                    row: parseInt(lineParts[1]) - 1,
                    column: 0,
                    text: lastBit, 
                    type: "warning" //This would give a red x on the gutter
                })


              }
            }
          }
          
          editors[id].getSession().setAnnotations(errors)

       } });
    }

    function resetVetter(id){
      editors[id].getSession().clearAnnotations()
    }
      

    function ClearSideBay(){
      $(".side-bay").html("");
    }

    $('.side-bay').bind("DOMSubtreeModified",function(){

     if ($(".side-bay").height() == 0){
        $(".dimisser-btn").css('display','none')
     } else   $(".dimisser-btn").css('display','block');
     if($(".pop-box").css("display") != "none" ){
       $(".pop-box").scrollTop(1)
      }

    return false;
    });

    function toggleTerm(){
        if($(".terminal-side").hasClass('active')){
            $(".terminal-side").removeClass('active');
            $(".terminal-side").css('display','none');
        } else {
            $(".terminal-side").addClass('active');
            $(".terminal-side").css('display','block');
        }
    }
    $(document).bind("ajaxSend", function(){
    if($(".terminal-side").hasClass('active') && termx != null){
            termx("[[b;#00FF00;]Request sent > ]",{flush:false})
    }
 });

    $(document).bind('keydown', 'ctrl+s', function(){}); 
    $(document).bind('keydown', 'ctrl+i', toggleTerm); 
    $(document).bind('keydown', 'ctrl+m', CollapseGloj);
    $(document).bind('keydown', 'ctrl+n', function(){
         $(".footer-bay .modal").modal("hide")
         $(".new-package").click();
      });

    var working = false;
    var termx = null;
    let winDir;
    let comRan = 0
    let prevBuff = "";
    window.socketTerminal = new WebSocket("ws://" + window.location.host + "/api/terminal_realtime");

    function reset(){

         if(socketTerminal.readyState === 2 || socketTerminal.readyState === 3){
            
             window.socketTerminal = new WebSocket("ws://" + window.location.host + "/api/terminal_realtime");
             working = false;
             prevBuff = "";
             comRan = 0
             winDir = null
             $('#terminaldefault').terminal().set_prompt('user@Strutkure $')
             socketTerminal.addEventListener('message',  handleMsg);

        }
    }

      // Listen for messages
      socketTerminal.addEventListener('error', function (event) {

           reset()

      })
    
    function handleMsg(event) {
            let term =  $('#terminaldefault').terminal();
                      

            if(winDir == "await"){
                if(prevBuff == event.data) return
                let path = event.data.split("\n")
                winDir = path[path.length - 1]
            }

            if(!comRan && event.data.includes("globals.Windows user.")){        
                winDir = "await"
                let path = event.data.split("\n")

                if(path.length > 2){
                   winDir = path[path.length - 1]
                }
            }

            if (winDir && event.data.includes(winDir.replace(">", ""))){
                working = false;
                prevBuff = "";
                $(".next-dlv").css("display", "none")
                term.set_prompt(winDir)
                return
            }

            comRan++

            if(event.data.includes("bash") && event.data.includes("$") && event.data.length < 50){
                working = false;
                prevBuff = "";
                $(".next-dlv").css("display", "none")
                term.set_prompt('user@Strutkure $')
                return;
            } 

            if(event.data != prevBuff){
              term.echo(event.data);
              prevBuff = event.data;
            }

            if(working)
              term.set_prompt('>')

            if(event.data.includes("(dlv)") || (event.data.includes("Type 'help' for list of commands.") && window.$awaitDelve ) ){
              window.$startMap = true;
              term.set_prompt('>')
            }

            if(window.$awaitDelve && window.$startMap){
              var br = window.$breakpoints[ window.$arrayIndex ];
               term.echo(event.data);
              if(!br){
                $(".next-dlv").css("display", "block")
                delete window.$awaitDelve
                window.socketTerminal.send("continue \n");
              }
              else {

                window.socketTerminal.send(br + "\n");
                window.$arrayIndex++;
              }
              
              return
            }

          
    }
    socketTerminal.addEventListener('message',  handleMsg);

    $(".next-dlv").click(() => {
      socketTerminal.send("continue \n")    
    })

    $(".next-dlv").css("display", "none")

    jQuery(function($, undefined) {
    $('#terminaldefault').terminal(function(command, term) {
      termx = term.echo;
        
        if(winDir && command == "killnow") return reset()

        if (command !== '') {
            working = true;
            let cmC = command.trim()

            if(winDir){
              if(cmC[0] == "c" && cmC[1] == "d"){
                  winDir = "await"
                  prevBuff = command
              }
            }

            setTimeout(()=> {
               prevBuff = ""
               window.socketTerminal.send(command + "\n");
            }, 400)
           
        } 

        if(winDir){
          term.set_prompt(( working ? "": winDir  ) )
          return
        }
        term.set_prompt(( working ? "":'user@Strutkure $' ) )

    }, {
        greetings: 'Welcome to the Strukture v1.1\nA few notes :\nMake use of the kill command to stop a process.\n2.Command killnow will stop the current process.',
        name: 'struk_term',
        height: ($(".terminal-side").height() - 55),
        prompt: (working ? "":'user@Strutkure $'),
        completion : function (string, callback){
          console.log(string);
          return ["test", "foo","tt"];
        }
    });
});



    function SaveFile(editor, link,pkv){
      
        var payload = {type:"1",target:link,pkg:pkv};
        if ( link.includes("gosforceasapi/") ) {
            link_final = link.split("++()/")
            payload.target = link_final[0].replace("gosforceasapi/", "")
            payload.type = "13r";
        }
        payload["data"] = editors[editor].getValue();
      $.ajax({url:"/api/put", data: payload ,type:"POST",success:function(html){
        $(".side-bay").html(html);
      },error:function(e){
        $(".side-bay").html(e.responseText);
      }
    });
   }

  function resetTerminal(){
    let term =  $('#terminaldefault').terminal();
    term.exec([`killnow`]);
  }

  function SavePKG(typ, pkv,editor){
      
      var payload = {type:typ,pkg:pkv};
        payload["data"] = editors[editor].getValue();
      $.ajax({url:"/api/put", data: payload ,type:"POST",success:function(html){
        $(".side-bay").html(html);
      },error:function(e){
        $(".side-bay").html(e.responseText);
      }
    });
    }

      function BuildPKG( pkv){
        $(".side-bay").html("<h1 style='text-align:center;'><i class='fa fa-cog fa-spin'/></h1>")
        $(".side-bay").load("/api/build?pkg=" + pkv);
      }

      function ClearLogs( pkv){
        $(".side-bay").html("<h1 style='text-align:center;'><i class='fa fa-cog fa-spin'/></h1>")
        $(".side-bay").load("/api/empty?pkg=" + pkv);
      }

      function StartServer( pkv){
           $(".side-bay").html("<h1 style='text-align:center;'><i class='fa fa-cog fa-spin'/></h1>")
        $(".side-bay").load("/api/start?pkg=" + pkv);
      }

      function StopServer( pkv){
           $(".side-bay").html("<h1 style='text-align:center;'><i class='fa fa-cog fa-spin'/></h1>")
        $(".side-bay").load("/api/stop?pkg=" + pkv);
      }

      function SavePKGAndBuild(typ, pkv,editor){
      
      var payload = {type:typ,pkg:pkv};
        payload["data"] = editors[editor].getValue();
      $.ajax({url:"/api/put", data: payload ,type:"POST",success:function(html){
        $(".side-bay").load("/api/build?pkg=" + pkv);
      },error:function(e){
        $(".side-bay").load("/api/build?pkg=" + pkv);
      }
    });
    }

    function removeWelcome(){
      $.ajax({url:"/api/saw"})
      $(".welcome-card").remove();
    }
    function SearchEditor(editor){
       editors[editor].find("name=\"" + $(".sti[editor='" + editor + "']").val() + "\"",{
            backwards: true,
            wrap: false,
            caseSensitive: false,
            wholeWord: false,
            regExp: false
        });
        editors[editor].findNext();
        
    }

    function AddtoEd(typ, editor){
      if (typ == "struct"){
       editors[editor].gotoLine(editors[editor].session.getLength() );
       editors[editor].insert("&lt;struct name=\"" +  $(".sti[editor='" + editor + "']").val() + "\" &gt;\n//Add some attrs\n\n&lt;/struct&gt;\n\n");

       $(".sti[editor='" + editor + "']").val("");
      } else if (typ == "object") {
         editors[editor].gotoLine(editors[editor].session.getLength() );
       editors[editor].insert("&lt;object name=\"" +  $(".sti[editor='" + editor + "']").val() + "\" struct=\"\" &gt;\n\n&lt;/object&gt;\n\n");

       $(".sti[editor='" + editor + "']").val("");
      } else {
         editors[editor].gotoLine(editors[editor].session.getLength() );
       editors[editor].insert("&lt;method name=\"" +  $(".sti[editor='" + editor + "']").val() + "\" var=\"\" return=\"\"  &gt;\n\n&lt;/method&gt;\n\n");

       $(".sti[editor='" + editor + "']").val("");
      }
     
    }

    function buildFunction(package, name){
          swal("Hijacking terminal", "Building function. Please be patient, this will take some time.", "warning");

             if(!$(".terminal-side").hasClass('active')){
                $(".terminal-side").addClass('active');
                $(".terminal-side").css('display','block');
            }

            let term =  $('#terminaldefault').terminal();

            term.exec([`cd $GOPATH/src/${package}`]);

             setTimeout(function(){
                term.exec([`cd ${name} && dep init -gopath && rm ./Gopkg.* &&  cd ../ && faas-cli build -f ${name}.yml && rm -rf ./${name}/vendor`]);
             }, 1100);
    }

    function deployFunction(package, name){
          swal("Hijacking terminal", "Deploying function. Please be patient, this will take some time.", "warning");

             if(!$(".terminal-side").hasClass('active')){
                $(".terminal-side").addClass('active');
                $(".terminal-side").css('display','block');
            }

            let term =  $('#terminaldefault').terminal();

            term.exec([`cd $GOPATH/src/${package}`]);

             setTimeout(function(){
                term.exec([`faas-cli deploy -f ${name}.yml`]);
             }, 1100);
    }


       function SaveFileWeb(editor, link,pkv){
      
        var payload = {type:"3",target:link,pkg:pkv};
        payload["data"] = editors[editor].getValue();
      $.ajax({url:"/api/put", data: payload ,type:"POST",success:function(html){
        $(".side-bay").html(html);
      },error:function(e){
        $(".side-bay").html(e.responseText);
      }
    });
    }
      function SaveFileSrc(editor, link,pkv, custom_data = null){
      
        var payload = {type:"30",target:link,pkg:pkv};
        payload["data"] = custom_data ? custom_data : editors[editor].getValue();
      $.ajax({url:"/api/put", data: payload ,type:"POST",success:function(html){

        if(!custom_data)
          $(".side-bay").html(html);

        vetAndLint(editor,  pkv, link)
      },error:function(e){
        if(!custom_data)
          $(".side-bay").html(e.responseText);

        vetAndLint(editor, pkv, link)
      }
    });
    }

    $(function () { 
      $('#jstree').on('changed.jstree', function (e, data) {
        var node = data.instance.get_node(data.selected[0]).original;

        if(node){
          if(node.project)
            return;
        if(!working && node.type != "" ){
          working = true;
    $(".loader-prog").css("display","block");
          $.ajax({url:"/api/get",type:"POST",data:{space:node.appid,type:node.type,id:node.id}, error:function(e){
              working = false;
              $(".loader-prog").css("display","none");
              $(".ready-three").append($(e.responseText) );      
          } 
        });
        }
              //attempt request
          }
        }).jstree({
          'core' : {
            'data' : {
              'url' : function (node) {
                return '/api/get';
              },
              'type' : 'POST'
              ,
              'data' : function (node) {
                return node.id == "#" ? {'type' : '0'} : { 'id' : node.id, 'type' : node.type };
              }
            }
          },
          "plugins" : [ "contextmenu","state" ],
          "contextmenu": {
                 "select_node" : false ,
                  "items": function ($node) {
                      var menu = {};

                      if ($node.original.ctype){
                          menu["Create"] = {
                              "label": "Create",
                              "action": function (obj) {
                                 havop("/api/create?type=" + $node.original.ctype + "&pkg=" + $node.original.appid,".side-bay");
                              }
                          };
                        }

                      if ($node.original.dtype.includes("isDir=Yes")){

                         menu["Run"] = {
                              "label": "Open in terminal",
                              "action": function (obj) {
                               // isDirTerm
                               let parts = $node.original.dtype.split("path=")
                               
                               if( winDir ){
                                  winDir = ('src/' + $node.original.appid + "/" + parts[1]).split("/").join("\\") + ">"
                               }

                               socketTerminal.send('cd $GOPATH/src/' + $node.original.appid + "/" + parts[1] + "\n");

                               setTimeout(() => {

                                   if(!$(".terminal-side").hasClass('active')){
                                      $(".terminal-side").addClass('active');
                                      $(".terminal-side").css('display','block');
                                  }

                               }, 3000)
                              }
                          };

                          menu["Search"] = {
                              "label": "Search in folder",
                              "action": function (obj) {
                               // isDirTerm
                               let parts = $node.original.dtype.split("path=")
                               let id = $node.original.appid

                               if(working) return;
                               
                                working = true;
                                $(".loader-prog").css("display","block");
                                $.ajax({url:"/api/get",type:"POST",data:{pkg:id,type:"5505",path:parts[1]}, error:function(e){
                                    working = false;
                                    $(".loader-prog").css("display","none");
                                    $(".ready-three").append($(e.responseText) );
                                  
                                } 
                              });

                              }
                          };
                      }

                      if ($node.original.btype){


                         menu["Build"] = {
                              "label": "Build",
                              "action": function (obj) {
                                BuildPKG($node.original.appid);
                              }
                          };

                          menu["Start"] = {
                              "label": "Start/Reset",
                              "action": function (obj) {
                                StartServer($node.original.appid);
                              }
                          };
                          
                          menu["Stop"] = {
                              "label": "Stop",
                              "action": function (obj) {
                                StopServer($node.original.appid);
                              }
                          };

                          menu["Debug"] = {
                              "label": "Launch Delve",
                              "action": function (obj) {
                                
                                socketTerminal.send('cd $GOPATH/src/' + $node.original.appid + "\n");

           
                                setTimeout(() => {
                                  
                                    $.ajax({url:"/api/breakpoints", data: { id : $node.original.appid } ,type:"POST",success:function(html){
                                       completeDelvLaunch(html, $node.original.appid);
                                      },error:function(e){
                                        completeDelvLaunch(e.responseText, $node.original.appid);
                                      }
                                    });

                                 

                                }, 2000)
                              }
                          };

                          menu["DebugTest"] = {
                              "label": "Launch Delve (Test)",
                              "action": function (obj) {
                                
                                socketTerminal.send('cd $GOPATH/src/' + $node.original.appid + "\n");

           
                                setTimeout(() => {
                                  
                                    $.ajax({url:"/api/breakpoints", data: { id : $node.original.appid } ,type:"POST",success:function(html){
                                       completeDelvLaunch(html, $node.original.appid, true);
                                      },error:function(e){
                                        completeDelvLaunch(e.responseText, $node.original.appid, true);
                                      }
                                    });

                                 

                                }, 2000)
                              }
                          };
                      }

                      if ($node.original.mtype){
                          menu["Move"] = {
                              "label": "Move",
                              "action": function (obj) {
                                 havop("/api/create?type=" + $node.original.mtype + "&pkg=" + $node.original.appid,".side-bay");
                              }
                          };
                        }
                        if ($node.original.dtype){
                          menu["Delete"] = {
                              "label": "Delete",
                              "action": function (obj) {
                                 havop("/api/delete?type=" + $node.original.dtype + "&pkg=" + $node.original.appid,".side-bay");
                              }
                          };
                        }
                        /*  "Rename": {
                              "label": "Rename an employee",
                              "action": function (obj) {
                                  this.rename(obj);
                              }
                          },
                          "Delete": {
                              "label": "Delete an employee",
                              "action": function (obj) {
                                  this.remove(obj);
                              }
                          }
                      }; */

              

                      return menu;
                  }
              }
          });
    });


    function completeDelvLaunch(data, appid, test = false){
      var keys = Object.keys(data);
      var breakpoints = [];

      for (var i = keys.length - 1; i >= 0; i--) {
        var k = keys[i];
        var brs = JSON.parse(data[k]);
        if(k[0] == "/"){
          
          k = k.substr(1, k.length);
        }

  
        for(var v = 0; v < brs.length;v++){

          var ent = brs[v];

          if(ent){
            breakpoints.push(`break ${k.replace("-breakpoints", "")
            .replace("\\", "")}:${v + 1}`);
          }


        }

      }

      window.$awaitDelve = true;
      window.$breakpoints = breakpoints;
      window.$arrayIndex = 0;
      window.$startMap = false;

      setTimeout(() => {
        if(!test){
         socketTerminal.send('dlv debug --allow-non-terminal-interactive ' + appid + " \n");
         return;
        }

        socketTerminal.send('dlv test --allow-non-terminal-interactive ' + appid + " \n");

      }, 3500)
     

      if(!$(".terminal-side").hasClass('active')){
          $(".terminal-side").addClass('active');
          $(".terminal-side").css('display','block');
      }

     
    }

      function makeid()
      {
          var text = "";
          var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

          for( var i=0; i < 10; i++ )
              text += possible.charAt(Math.floor(Math.random() * possible.length));

          return text;
      }

    function hideAll(){
      $(".cbn").css('display','none');
    }

    function rmGroup(id){
      $("#" + id).remove();
    }

    function mready(id){ 
       let title = $("a[target='" + id + "'] .tab-name").html() ? $("a[target='" + id + "'] .tab-name").html()
       .split("<button")[0] : $("a[target='" + id + "'] .tab-name").html();
  
       $(".xtab").removeClass("active");
       $(".tabview").removeClass("active");
       $(".nav-link.xtab").removeClass("factive");
       $("a[target='" + id + "']").addClass("factive");
       $("title").html( title );
       $("#" + id).addClass("active");
    }

    function addTab(name, elementid){
      if(!editors["tabnames"]){
          editors["tabnames"] = ["tab","map"]
      }
      if (editors.tabnames.indexOf(name) != -1){
          var currentlink = $("a[data-name='" + name + "']");
          var currentid =  currentlink.attr("target");
           if (editors[currentid ]){
          delete editors[currentid];
          }
          if (editors[currentid + "c"]){
            delete editors[currentid + "c"]
          }
           $("#" + currentid ).remove()
          currentlink.attr("target", elementid)
         
         
          $(".xnavs").scrollLeft(currentlink.offset().left);
          currentlink.click();
          mready(elementid);

      } else {
       
        $(".xnavs").prepend('<li class="nav-item"><a data-name="' + name +'" class="nav-link xtab factive active" target="' + elementid + '" href="#" title="' + name + '"><span class="tab-name">' + name +'</span><button style="margin-left:15px;" type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></a></li>');
        $("a[target='" + elementid + "']").click(function(){
          //show tab 
          mready($(this).attr("target"));
          return false;
        });
        $("a[target='" + elementid + "'] .close").click(function(){
          //show tab 
          var elemid = $(this).parent().attr("target");
          var elemname = $(this).parent().attr("data-name");
          $(this).parents("li").remove();
          editors.tabnames.splice(editors.tabnames.indexOf(elemname),1)
          if (editors[elemid ]){
          delete editors[elemid];
          }
          if (editors[elemid + "c"]){
            delete editors[elemid + "c"]
          }
          $("#" + elemid).remove();
          return false;
        });
        mready(elementid);
        editors.tabnames.push(name)
      }
    }

    function updateTree(){
      $("#jstree").jstree('refresh')
    }
    </script>
        {{PluginJS}}