fix bug where new columns were not added to database immediately
[newtab.git] / admin.js
index 17fbdbd8172dda354a7ad3a4e4f01d8da0463b23..2b82da75484393dec8d2f4e1f971cadb297d34a3 100644 (file)
--- a/admin.js
+++ b/admin.js
 var mainlist;
-
-//chrome.tabs.create({ url: chrome.extension.getURL("newtab.html") });
-//window.close();
-
+var rmspan = ["<span class='remove' id='delete-", "'>–</span>"]
+var tick = "✔";
+var removebg = "#bf616a";
+var hovergrn = "#a3be8c";
+var hoverbg = "#434c5e";
+var hoverbg2 = "#848ead";
 document.addEventListener("DOMContentLoaded", function() {
-       chrome.storage.sync.get(
-{"lists": [
-    [
-        ["syncthing", "https://localhost:8384/"],
-        ["todoist", "http://todoist.com/"],
-        ["github", "https://github.com/"],
-        ["gmail", "http://mail.google.com/"],
-        ["drive", "http://drive.google.com/"]
-    ],
-    [
-        ["unixporn", "http://reddit.com/r/unixporn"],
-        ["news", "http://reddit.com/r/news"],
-        ["funny", "http://reddit.com/r/funny"],
-        ["linux", "http://reddit.com/r/linux"],
-        ["all", "http://reddit.com/r/all"]
-    ],
-    [
-        ["elementary", "https://elementary.io/"],
-        ["ubuntu", "https://www.ubuntu.com/"],
-        ["fedora", "https://getfedora.org/"],
-        ["mint", "https://linuxmint.com/"],
-        ["arch", "https://www.archlinux.org/"]
+  chrome.storage.sync.get(
+    {"lists": [
+      ["General",
+        ["Github", "https://github.com"],
+        ["Wikipedia", "https://en.wikipedia.org"],
+        ["Gmail", "https://mail.google.com"]
+      ],
+      ["Productivity",
+        ["Desmos", "https://www.desmos.com/calculator"],
+        ["Wolfram", "https://wolframalpha.com"],
+        ["Hacker News", "https://news.ycombinator.com"]
+      ],
+      ["Social",
+        ["Reddit", "https://www.reddit.com"],
+        ["YouTube", "https://youtube.com"],
+        ["Instagram", "https://instagram.com"]
+      ]
     ]
-],
-"l1name": "productivity",
-"l2name": "general",
-"l3name": "distros"},
-       userListsCallback);
+},
+    userListsCallback);
 });
 
+function columnToArray(list) {
+  var l = [];
+  var elem = list.getElementsByClassName("item");
+  for (var i = 0; i < elem.length; ++i) {
+    l[i] = [elem[i].innerText, elem[i].getAttribute("href")];
+  }
+  return l;
+}
+
 function listToArray(list) {
-       var l = [];
-       var elem = list.getElementsByTagName("li");
-       for (var i = 0; i < elem.length; ++i) {
-         l[i] = [elem[i].getElementsByTagName("a")[0].innerText, elem[i].getElementsByTagName("a")[0].getAttribute("href")];
-       }
-       return l;
+  var l = [];
+  console.log(list.getElementsByClassName('title')[0].getElementsByTagName("p")[0].textContent);
+  l[0] = list.getElementsByClassName('title')[0].getElementsByTagName("p")[0].textContent;
+  var elem = list.getElementsByTagName("li");
+  for (var i = 0; i < elem.length; ++i) {
+    l[i+1] = [elem[i].getElementsByTagName("a")[0].innerText, elem[i].getElementsByTagName("a")[0].getAttribute("href")];
+  }
+  return l;
 }
 
 var userListsCallback = function(lists) {
-       mainlist = [lists["l1name"],lists["l2name"],lists["l3name"]]
-       for(var i=0;i<lists["lists"].length;i++) {
-               var div = document.createElement("div");
-               div.setAttribute("class", "favorites-list users-list");
-               document.getElementById("links").appendChild(div);
-
-               var ul = document.createElement("ul");
-               ul.setAttribute("id", mainlist[i]);
-               div.appendChild(ul);
-
-               var title = document.createElement("div");
-               title.setAttribute("class", "title");
-               ul.appendChild(title);
-
-               var p = document.createElement("p");
-               p.innerText = mainlist[i];
-               title.appendChild(p);
-
-               title.insertAdjacentHTML("beforeend", "<span id='add-"+mainlist[i]+"'>+</span>");
-
-               var list = lists["lists"][i];
-               for(var j=0;j<lists["lists"][i].length;j++) {
-                       var li = document.createElement("li");
-                       li.setAttribute("id", mainlist[i]+"-"+j);
-                       var siteurl = list[j][1];
-                       var name = list[j][0];
-                       // ronmurphy change start
-                       var img = document.createElement("img");
-                                               img.className = "icon";
-                                               img.src = "http://www.google.com/s2/favicons?domain="+siteurl+"";
-                       li.insertAdjacentHTML("beforeend", "<a href="+siteurl+"> <img src="+img.src+" alt="+extractDomain(siteurl,1)+"/> "+name+"</a>");
-                       // ronmurphy end
-                       //li.insertAdjacentHTML("beforeend", "<a href="+siteurl+">"+name+"</a>");
-                       li.insertAdjacentHTML("beforeend", "<span id='delete-"+j+"-"+mainlist[i]+"'>-</span>");
-                       ul.appendChild(li);
-               }
-
-               var sortable = Sortable.create(ul, {
-                       group: "userlists",
-                       onUpdate: function (evt) {
-                               save();
-                       }
-               });
-       }
-
-       menu();
+  mainlist = []
+  for (let x of lists['lists']) {
+    mainlist.push(x[0]);
+  }
+  for(var i=0;i<lists["lists"].length;i++) {
+    document.getElementById('edit').addEventListener('click', edit, false);
+    document.getElementById('addcol').addEventListener('click', addCol, false);
+    var ul = document.createElement("ul");
+    ul.setAttribute("id", mainlist[i]);
+    ul.setAttribute('draggable', 'true');
+    ul.addEventListener('dragstart', dragStart, false);
+    ul.addEventListener('dragenter', dragEnter, false);
+    ul.addEventListener('dragover', dragOver, false);
+    ul.addEventListener('dragleave', dragLeave, false);
+    ul.addEventListener('drop', drop, false);
+    document.getElementById("links").appendChild(ul);
+
+    var grip = document.createElement("span");
+    grip.setAttribute("class", "grip");
+
+    var title = document.createElement("div");
+    title.setAttribute("class", "title");
+    title.appendChild(grip)
+    ul.appendChild(title);
+
+    var p = document.createElement("p");
+    p.innerText = mainlist[i];
+    title.appendChild(p);
+
+    title.insertAdjacentHTML("beforeend", "<span class='add' id='add-"+mainlist[i]+"'>+</span>");
+
+    var list = lists["lists"][i];
+    for(var j=1;j<lists["lists"][i].length;j++) {
+      var li = document.createElement("li");
+      li.setAttribute("id", mainlist[i]+"-"+j);
+      var siteurl = list[j][1];
+      var nme = list[j][0];
+      var img = document.createElement("img");
+      img.className = "icon";
+      img.src = "https://www.google.com/s2/favicons?domain="+siteurl+"";
+      li.insertAdjacentHTML("beforeend", "<a class='item' href="+siteurl+"><img src="+img.src+" alt="+extractDomain(siteurl,1)+"/> "+nme+"</a>");
+      li.insertAdjacentHTML("beforeend", rmspan[0] + j + "-" + mainlist[i] + rmspan[1]);
+      ul.appendChild(li);
+    }
+
+    new Sortable(ul, {
+      group: "userlists",
+      animation: 150,
+      onUpdate: function (evt) {
+        save();
+      }
+    });
+  }
+
+  menu();
 
 };
 
+function dragStart(e) {
+  dragSrcEl = this;
+  e.dataTransfer.effectAllowed = 'move';
+  e.dataTransfer.setData('text/html', this.innerHTML);
+}
+
+function dragOver(e) {
+  if (e.preventDefault) {
+    e.preventDefault();
+  }
+  e.dataTransfer.dropEffect = 'move';
+  return false;
+}
+
+function dragEnter(e) {
+  this.classList.add('over');
+}
+
+function dragLeave(e) {
+  this.classList.remove('over');
+}
+
+function drop(e) {
+  if (e.stopPropagation); {
+    e.stopPropagation();
+  }
+  if (dragSrcEl != this) {
+    dragSrcEl.innerHTML = this.innerHTML;
+    this.innerHTML = e.dataTransfer.getData('text/html');
+    save();
+  }
+  return false;
+}
+
+var dragSrcEl = null;
+
+document.onkeyup=function(e){
+  var e = e || window.event; // for IE to cover IEs window event-object
+  fields = document.getElementsByClassName("new");
+  if(e.which == 27 && fields != null) {
+    fields[fields.length-1].remove();
+    return false;
+  }
+  if(e.which == 13 && fields.length > 0) {
+    fields[fields.length-1].getElementsByClassName("save")[0].click();
+    return false;
+  }
+}
+
+var editMode = false;
+
+function edit() {
+  if (editMode == true) {
+    console.log("Exited edit mode");
+    closeEdit(this);
+    return 0;
+  }
+  console.log("Entered edit mode");
+  this.style.background = hovergrn;
+  this.innerText = tick;
+  addbtn = document.getElementById("addcol");
+  addbtn.style.display = "flex";
+  var cols = document.getElementsByTagName("ul");
+  for (let col of cols) {
+    title = col.getElementsByClassName("title")[0];
+    rmbutton = document.createElement("span"); 
+    rmbutton.setAttribute("class", "rmcol");
+    rmbutton.setAttribute("id", "rmcol-"+col.id);
+    rmbutton.innerText = "-";
+    rmbutton.addEventListener('click', function(event){
+      console.log("Deleting column " + this.parentNode.parentNode);
+      this.parentNode.parentNode.remove();
+      var index = mainlist.indexOf(this.parentNode.parentNode.id);
+      console.log("Found deleted node " + this.parentNode.parentNode.id + " at index " + index);
+      if (index > -1) {
+        mainlist.splice(index, 1);
+      }
+      save();
+    });
+    title.appendChild(rmbutton);
+    title.getElementsByClassName("add")[0].style.display = "flex";
+    title.getElementsByTagName("p")[0].style.width = "calc(100% - 90px)";
+  }
+  editMode = true;
+}
+
+function closeEdit(editbtn) {
+  editbtn.style.background = hoverbg;
+  editbtn.innerText = "e";
+  addbtn = document.getElementById("addcol");
+  addbtn.style.display = "none";
+  var cols = document.getElementsByTagName("ul");
+  for (let col of cols) {
+    rmbutton = col.getElementsByClassName("title")[0].getElementsByClassName("rmcol")[0];
+    rmbutton.remove();
+    title = col.getElementsByClassName("title")[0];
+    title.getElementsByClassName("add")[0].style.display = "";
+    title.getElementsByTagName("p")[0].style.width = "calc(100% - 45px)";
+  }
+  editMode = false;
+}
+
+function addCol() {
+  var ul = document.createElement("ul");
+  ul.setAttribute("id", "new");
+  ul.setAttribute('draggable', 'true');
+  ul.addEventListener('dragstart', dragStart, false);
+  ul.addEventListener('dragenter', dragEnter, false);
+  ul.addEventListener('dragover', dragOver, false);
+  ul.addEventListener('dragleave', dragLeave, false);
+  ul.addEventListener('drop', drop, false);
+  document.getElementById("links").appendChild(ul);
+
+  var grip = document.createElement("span");
+  grip.setAttribute("class", "grip");
+
+  var title = document.createElement("div");
+  title.setAttribute("class", "title");
+  title.appendChild(grip)
+  ul.appendChild(title);
+
+  var p = document.createElement("p");
+  p.innerText = "new";
+  title.appendChild(p);
+
+  title.insertAdjacentHTML("beforeend", "<span class='add' id='add-new'>+</span>");
+
+  rmbutton = document.createElement("span"); 
+  rmbutton.setAttribute("class", "rmcol");
+  rmbutton.setAttribute("id", "rmcol-new");
+  rmbutton.innerText = "-";
+  rmbutton.addEventListener('click', function(event){
+    console.log("Deleting column " + this.parentNode.parentNode);
+    this.parentNode.parentNode.remove();
+    var index = mainlist.indexOf(this.parentNode.parentNode.id);
+    console.log("Found deleted node " + this.parentNode.parentNode.id + " at index " + index);
+    if (index > -1) {
+      mainlist.splice(index, 1);
+    }
+    save();
+  });
+  title.appendChild(rmbutton);
+  title.getElementsByClassName("add")[0].style.display = "flex";
+  title.getElementsByTagName("p")[0].style.width = "calc(100% - 90px)";
+  
+  mainlist.push(["new"]);
+  save();
+  listen(title.getElementsByClassName("add")[0]);
+}
+
 function listen(li) {
-       li.addEventListener('click', function(event){
-               var r = event.target.id.split("-");
-               if (r[0] == "delete") {
-                       var el = document.getElementById(r[2]+"-"+r[1]);
-                       el.outerHTML = "";
-                       delete el;
-                       save();
-               } else {
-                       var ul = document.getElementById(r[1]);
-                       ul.insertAdjacentHTML("beforeend", "<div class='inp' id='div-"+listToArray(ul).length.toString()+"'><input style='width:35%' type='text' class='name' value='' placeholder='name'><input style='width:47%' type='text' class='url' value='' placeholder='url' id='form-"+listToArray(ul).length.toString()+"'><span id='input-"+listToArray(ul).length.toString()+"'>s</span></div>");
-                       var inp = document.getElementById("div-"+listToArray(ul).length.toString());
-                       var span = document.getElementById("input-"+listToArray(ul).length.toString());
-                       var form = document.getElementById("form-"+listToArray(ul).length.toString());
-
-                       form.addEventListener('keyup', function(event){
-                               if (event.keyCode == 13) {
-                                       span.click();
-                               }
-                       });
-
-                       span.addEventListener('click', function(event){
-                               inp.outerHTML = "";
-                               delete inp;
-
-                               if (inp.getElementsByClassName("name")[0].value != "" || inp.getElementsByClassName("url")[0].value != "") {
-                                       var li = document.createElement("li");
-                                       li.setAttribute("id",r[1]+"-"+listToArray(ul).length.toString());
-                                       //var splitted = splitHostname(inp.getElementsByClassName("url")[0].value); fix later
-                                       var siteurl = addhttp(inp.getElementsByClassName("url")[0].value);
-                                       var name = inp.getElementsByClassName("name")[0].value;
-
-                                       li.insertAdjacentHTML("beforeend", "<a href="+siteurl+">"+name+"</a>");
-                                       li.insertAdjacentHTML("beforeend", "<span id='delete-"+listToArray(ul).length.toString()+"-"+r[1]+"'>-</span>");
-                                       document.getElementById(r[1]).appendChild(li);
-                                       save();
-                                       listen(li);
-                               }
-                       });
-               }
-       }, false);
+  li.addEventListener('click', function(event){
+    var r = event.target.id.split("-");
+    if (r[0] == "delete") {
+      var el = document.getElementById(r[2]+"-"+r[1]);
+      el.outerHTML = "";
+      delete el;
+      save();
+    } else {
+      addItem(r, li);
+    }
+  }, false);
+}
+
+function addItem(caller, li) {
+      if (ul == null) {
+        var ul = li.parentNode.parentNode;
+        var id = ul.id;
+      }
+      else {
+        var ul = document.getElementById(caller[1]);
+        var id = caller[1];
+      }
+      
+      if (document.querySelectorAll("#"+id+" .new").length > 0) {
+        fields = document.querySelector("#"+id+" .new .name");
+        fields.focus(); 
+        return false;
+      }
+      var li = document.createElement("li");
+      li.setAttribute("class", "new");
+      li.insertAdjacentHTML("beforeend", "<span class='save' tabindex='3' id='input-"+columnToArray(li).length.toString()+"'>"+tick+"</span><input type='text' class='name' value='' placeholder='name' tabindex='1'><br /><input type='url' spellcheck=false class='url' value='' placeholder='url' tabindex='2' id='form-"+columnToArray(li).length.toString()+"'>");
+      ul.appendChild(li);
+      var span = document.getElementById("input-"+columnToArray(li).length.toString());
+      var form = document.getElementById("form-"+columnToArray(li).length.toString());
+      span.addEventListener('click', function(event){
+        var li = document.getElementsByClassName("new")[0]
+        var ul = li.parentNode;
+        if (li.getElementsByClassName("name")[0].value != "" && li.getElementsByClassName("url")[0].value != "" && li.getElementsByClassName("url")[0].validity.typeMismatch== false) {
+          var newli = document.createElement("li");
+          newli.setAttribute("id",caller[1]+"-"+columnToArray(ul).length.toString());
+          var siteurl = addhttp(li.getElementsByClassName("url")[0].value);
+          var nme = li.getElementsByClassName("name")[0].value;
+          li.remove()
+          delete li;
+
+          newli.insertAdjacentHTML("beforeend", "<a href="+siteurl+">"+nme+"</a>");
+          newli.insertAdjacentHTML("beforeend", rmspan[0]+columnToArray(ul).length.toString()+"-"+caller[1]+rmspan[1]);
+          document.getElementById(id).appendChild(newli);
+          save();
+          listen(newli);
+        }
+        else {
+          if (li.getElementsByClassName("name")[0].value == "" && li.getElementsByClassName("url")[0].value == "") {
+            console.log("No data supplied, deleting form");
+            this.parentNode.remove();
+          }
+          else {
+            console.log("Missing data, press Esc to delete form");
+          }
+        }
+      });
+      span.onmouseover = function() {
+        nme = document.getElementsByClassName("name")[0];
+        url = document.getElementsByClassName("url")[0];
+        if (nme.value === ''  || url.value === '' || url.validity.typeMismatch == true) {
+          this.style.background = removebg;
+        }
+        else {
+          this.style.background = hovergrn; 
+        }
+      };
+      span.onmouseout = function() {
+        this.style.background = hoverbg2;
+      };
+      fields = document.querySelector("#"+id+" .new .name");
+      fields.focus(); 
+
 }
 
 function menu() {
-       var allUserLi = document.querySelectorAll('.users-list > ul > li > span, .users-list > ul > .title > span');
+  var allUserLi = document.querySelectorAll('.remove, .add');
 
-       allUserLi.forEach(function(li, p_index){
-       listen(li);
-    });
+  allUserLi.forEach(function(li, p_index){
+    listen(li);
+  });
 }
 
 function save(l) {
-       var set = l || JSON.parse(JSON.stringify(mainlist));
-       d = []
-       d = set;
-       for (var i = 0; i < set.length; ++i) {
-               e = document.getElementById(set[i]);
-               d[i] = listToArray(e);
-       }
-       chrome.storage.sync.set( {"lists": d} );
+  console.log(mainlist);
+  var set = l || JSON.parse(JSON.stringify(mainlist));
+  d = []
+  d = set;
+  console.log("Saving settings");
+  for (var i = 0; i < set.length; ++i) {
+    d[i] = listToArray(document.getElementById(set[i]));
+  }
+  chrome.storage.sync.set( {"lists": d} );
 }