Store data in a better format

This commit is contained in:
Neil Brommer 2017-12-27 15:27:08 -08:00
parent bd20c403b3
commit 45f33631e9
5 changed files with 175 additions and 196 deletions

View file

@ -7,7 +7,7 @@ $(document).ready(function () {
for (let group of bookmarkList) {
if (group != null)
combo.append($("<option>").attr({ "value": group.title })
combo.append($("<option>").attr({ "value": group.groupIndex })
.text(group.title));
}
@ -30,48 +30,30 @@ function addNewBookmark(e) {
if (bkmkGroup == "--") { // create a new group
var newGroupName = $("#newBookMarkGroupNew").val();
var newGroup = {
"title": newGroupName,
"bookmarks": [ { "name": bkmkName, "address": bkmkAddress } ]
};
var openDBRequest = window.indexedDB.open("bookmarks", dbVersion + 1);
openDBRequest.onupgradeneeded = function (e) {
var db = e.target.result;
dbVersion++;
if (db.objectStoreNames.contains(newGroup.title)) {
window.alert("The group already exists");
return;
}
var objStore = db.createObjectStore(newGroup.title, { autoIncrement: true });
objStore.createIndex("name", "name", { unique: false });
objStore.createIndex("address", "address", { unique: false });
var bookmarks = newGroup.bookmarks;
for (var i = 0; i < bookmarks.length; i++) {
var bkmk = bookmarks[i];
objStore.add({ "name": bkmk.name, "address": bkmk.address }, i);
}
}
var openDBRequest = window.indexedDB.open("bookmarks");
openDBRequest.onsuccess = function (e) {
var db = e.target.result;
var groupsStore = db.transaction("Groups", "readwrite").objectStore("Groups");
var indexStore = db.transaction(["groupIndexes"], "readwrite")
.objectStore("groupIndexes");
groupsStore.getAll().onsuccess = function (evt) {
// find the largest index and use that +1
var groups = evt.target.result;
indexStore.getAll().onsuccess = function (evt) {
var items = evt.target.result;
var largest = 0;
for (let item of items) {
if (item.groupIndex >= largest)
largest = item.groupIndex + 1;
var largest = -1;
for (var group of groups) {
if (group.groupIndex > largest)
largest = group.groupIndex;
}
indexStore.add({ "title": newGroup.title, "groupIndex": largest });
bookmarkList[largest] = newGroup;
var newGroup = {
groupIndex: largest + 1,
title: newGroupName,
bookmarks: [ { name: bkmkName, address: bkmkAddress } ]
};
groupsStore.add(newGroup);
// don't need to add to bookmarkList because loadBookmarks is
// being called
db.close();
loadBookmarks();
@ -84,22 +66,21 @@ function addNewBookmark(e) {
var openDBRequest = window.indexedDB.open("bookmarks");
openDBRequest.onsuccess = function (e) {
var db = e.target.result;
var newItem = { "name": bkmkName, "address": bkmkAddress };
db.transaction([bkmkGroup], "readwrite")
.objectStore(bkmkGroup)
.add(newItem);
var groupsStore = db.transaction("Groups", "readwrite").objectStore("Groups");
for (let group of bookmarkList) {
if (group.title == bkmkGroup) {
group.bookmarks.push(newItem);
break;
}
var groupReq = groupsStore.get(parseInt(bkmkGroup));
groupReq.onsuccess = function (evt) {
var group = groupReq.result;
var newItem = { "name": bkmkName, "address": bkmkAddress };
group.bookmarks.push(newItem);
groupsStore.put(group);
db.close();
loadBookmarks();
$(".modal").modal("hide");
}
db.close();
loadBookmarks();
$(".modal").modal("hide");
}
openDBRequest.onerror = function (e) { console.log(e); }

View file

@ -36,47 +36,59 @@ function toggleEditing (e) {
function deleteBookmark(e) {
var item = $(this);
var group = item.data("group");
var key = item.data("key");
var key = item.data("key");
var groupIndex = item.data("group-index");
var bookmarkItem = $("#" + group + "-" + key);
var openDBRequest = window.indexedDB.open("bookmarks");
openDBRequest.onsuccess = function (e) {
var db = e.target.result;
var deleteRequest = db.transaction(group, "readwrite").objectStore(group).delete(key);
deleteRequest.onsuccess = function (evt) {
$("#" + group + "-" + key).remove();
var groupsStore = db.transaction("Groups", "readwrite").objectStore("Groups");
groupsStore.get(groupIndex).onsuccess = function (getEvt) {
var groupData = getEvt.target.result;
// remove the bookmark from the group object
var bookmarkData = {name: bookmarkItem.data("name"), address: bookmarkItem.data("address")};
groupData.bookmarks = groupData.bookmarks.filter(function (item) {
if (item.name != bookmarkData.name && item.address != bookmarkData.address)
return true;
return false;
});
// no need to provide key since keyPath is set
groupsStore.put(groupData);
bookmarkItem.remove();
}
}
openDBRequest.onerror = function (evt) {
console.log("Error", evt);
window.alert("There was an error deleting the bookmark");
}
}
function deleteGroup(e) {
var group = $(this); // the delete group button
var groupName = group.data("group");
var groupIndex = group.data("group");
var openDBRequest = window.indexedDB.open("bookmarks", dbVersion + 1);
var openDBRequest = window.indexedDB.open("bookmarks");
openDBRequest.onupgradeneeded = function (e) {
var db = e.target.result;
dbVersion++;
openDBRequest.onsuccess = function (dbe) {
var db = dbe.target.result;
var deleteRequest = db.deleteObjectStore(groupName);
}
openDBRequest.onsuccess = function (e) {
var db = e.target.result;
var indexStore = db.transaction("groupIndexes", "readwrite").objectStore("groupIndexes");
indexStore.delete(groupName).onsuccess = function (evt) {
$("#group-" + groupName.replace(" ", "-")).parent().remove();
};
var groupsStore = db.transaction("Groups", "readwrite").objectStore("Groups");
var delReq = groupsStore.delete(groupIndex);
delReq.onsuccess = function (dele) {
$("#group-" + groupIndex).remove();
}
}
openDBRequest.onerror = function (e) {
console.error(e);
window.alert("There was an error deleting the group");
}
}

View file

@ -1,11 +1,5 @@
$(document).ready(function () {
$("#importExportModal").on("shown.bs.modal", function () {
var data = JSON.stringify(bookmarkList, null, 4);
if (data != null)
$("#exportText").text(data);
else
$("#exportText").text("[]");
});
$("#importExportModal").on("shown.bs.modal", showBookmarkData);
$("#btnImportDialog").click(importBookmarks);
@ -14,6 +8,22 @@ $(document).ready(function () {
});
});
function showBookmarkData() {
var openDBRequest = window.indexedDB.open("bookmarks");
openDBRequest.onsuccess = function (e) {
var db = e.target.result;
db.transaction("Groups").objectStore("Groups").getAllKeys().onsuccess = function (evt) {
var data = JSON.stringify(bookmarkList, null, 4);
if (data != null)
$("#exportText").text(data);
else
$("#exportText").text("[]");
}
}
}
function importBookmarks() {
try {
var newData = $.parseJSON($("#importText").val());
@ -23,10 +33,9 @@ function importBookmarks() {
return;
}
if (verifyBookmarks(newData)) {
if (validateBookmarks(newData)) {
$("#btnImportDialog").prop("disabled", true);
setList(newData);
$("#importExportModal").modal("hide");
} else {
window.alert("Invalid Format");
}
@ -36,38 +45,32 @@ function setList(data) {
// empty the DB and fill it with the new data
bookmarkList = data;
try {
indexedDB.deleteDatabase("bookmarks");
} catch (err) {
// it's OK if the DB doesn't exist
if (err.name != "NotFoundError") {
console.error(err);
return;
}
}
var openDBRequest = window.indexedDB.open("bookmarks", 1);
var openDBRequest = window.indexedDB.open("bookmarks");
openDBRequest.onsuccess = function (e) {
dbVersion = db.version;
db = e.target.result;
var groupStore = db.transaction("Groups", "readwrite").objectStore("Groups");
groupStore.clear();
// create the object stores
for (group of data) {
groupStore.add(group);
}
$("#importExportModal").modal("hide");
$("#btnImportDialog").prop("disabled", false);
db.close();
loadBookmarks();
}
openDBRequest.onerror = function (err) { console.error(err); }
openDBRequest.onupgradeneeded = function (e) {
db = e.target.result;
var groupStore = initDB(db);
// create the object stores
for (var i = 0; i < data.length; i++) {
addGroup(data[i], groupStore, db, i);
}
}
}
function verifyBookmarks(bookmarks) {
function validateBookmarks(bookmarks) {
var indexes = [];
if (!Array.isArray(bookmarks))
return false;
@ -80,6 +83,14 @@ function verifyBookmarks(bookmarks) {
if (item.title == null || typeof item.title != "string")
return false;
if (item.groupIndex == null || typeof item.groupIndex != "number")
return false;
if (arrayContains(indexes, item.groupIndex))
return false;
indexes.push(item.groupIndex);
for (var j = 0; j < item.bookmarks.length; j++) {
var bkmk = item.bookmarks[j];
@ -96,3 +107,12 @@ function verifyBookmarks(bookmarks) {
return true;
}
function arrayContains(array, searchFor) {
for (item of array) {
if (item == searchFor)
return true;
}
return false;
}

View file

@ -9,31 +9,30 @@ function loadBookmarks() {
openDBRequest.onsuccess = function (dbEvt) {
db = dbEvt.target.result;
dbVersion = db.version;
bookmarkList = [];
db.transaction(["groupIndexes"], "readonly")
.objectStore("groupIndexes")
.getAll()
.onsuccess = function (indexEvt) {
var indexes = indexEvt.target.result;
indexes.sort(function (a, b) {
return a.groupIndex - b.groupIndex;
});
db.transaction(["Groups"], "readonly").objectStore("Groups").getAll().onsuccess = function (groupsEvt) {
var groups = groupsEvt.target.result;
groups.sort(function (a, b) {
return a.groupIndex - b.groupIndex;
});
// use a placholder because getting the group info is async
// and groups could finish loading in a different order
var cardList = $("#cardList");
for (var i = 0; i < indexes.length; i++) {
$("<div>").attr("id", "group-" + indexes[i].groupIndex).appendTo(cardList);
}
for (let item of indexes) {
buildGroup(item, $("#group-" + item.groupIndex));
}
db.close();
// use a placholder
var cardList = $("#cardList");
for (let groupData of groups) {
$("<div>").attr("id", "group-" + groupData.groupIndex)
.addClass("bookmarkGroupContainer")
.appendTo(cardList);
}
;
bookmarkList = [];
for (let groupData of groups) {
buildGroup(groupData, $("#group-" + groupData.groupIndex));
bookmarkList.push(groupData);
}
db.close();
};
}
openDBRequest.onerror = function (e) { console.log(e); }
@ -43,81 +42,55 @@ function loadBookmarks() {
console.log("Creating database");
db = e.target.result;
var data = window.localStorage.getItem("bookmarks");
if (data != null) {
console.log("Importing data from old version");
data = JSON.parse(data);
db.close();
setList(data);
window.localStorage.removeItem("bookmarks");
} else {
var groupStore = initDB(db);
var groupStore = db.createObjectStore("Groups", {keyPath: "groupIndex"});
groupStore.createIndex("groupIndex", "groupIndex", {unique: true});
groupStore.createIndex("title", "title", {unique: false});
groupStore.createIndex("bookmarks", "bookmarks", {unique: false});
// add example bookmarks
var exBookmarks = db.createObjectStore("Examples", { autoIncrement: true });
exBookmarks.createIndex("name", "name", { unique: false });
exBookmarks.createIndex("address", "address", { unique: false });
groupStore.add({ "title": "Examples", "groupIndex": 0 });
var groupData = {
groupIndex: 0,
title: "Examples",
bookmarks: [
{
"name": "Github",
"address": "https://github.com/"
},
{
"name": "This project on Github",
"address": "https://github.com/NeilBrommer/NewTabPage"
}
]
};
exBookmarks.add({
"name": "Github",
"address": "https://github.com/"
});
exBookmarks.add({
"name": "This project on Github",
"address": "https://github.com/NeilBrommer/NewTabPage"
});
exBookmarks.add({
"name": "Hacker News",
"address": "https://news.ycombinator.com/"
});
exBookmarks.add({
"name": "reddit",
"address": "https://www.reddit.com/"
});
groupStore.add(groupData);
$("#aboutModal").modal("show");
}
$("#aboutModal").modal("show");
}
}
function buildGroup(groupInfo, placeholder) {
var groupTransaction = db.transaction([groupInfo.title], "readonly");
var groupStore = groupTransaction.objectStore(groupInfo.title);
var groupRequest = groupStore.getAll();
groupRequest.onsuccess = function (e) {
var bookmarks = e.target.result;
var keyRequest = groupStore.getAllKeys();
keyRequest.onsuccess = function (evt) {
var keys = evt.target.result;
for (var i = 0; i < bookmarks.length; i++) {
bookmarks[i].key = keys[i];
}
bookmarkList[groupInfo.groupIndex] = {
"title": groupInfo.title,
"bookmarks": bookmarks
};
buildCard(groupInfo.title, bookmarks).appendTo(placeholder);
}
}
buildCard(groupInfo.title, groupInfo.groupIndex, groupInfo.bookmarks).appendTo(placeholder);
}
function buildCard(title, itemList) {
function buildCard(title, groupIndex, itemList) {
var card = $("<div>");
card.attr({
"id": "group-" + title.replace(" ", "-"),
"class": "card"
"id": "group-" + groupIndex,
"class": "card",
"data-group-name": title,
"data-group-index": groupIndex
});
var cardHead = $("<div>");
cardHead.addClass("card-header");
cardHead.text(title);
var btnDrag = $("<span>").addClass("mr-2 start-hidden dragGroupHandle")
.append($("<span>").addClass("fas fa-bars"));
var btnDel = $("<span>")
.attr("data-group", title)
.attr("data-group", groupIndex)
.addClass("btnDelGroup far fa-trash-alt float-right mt-1 start-hidden text-danger clickable");
btnDel.appendTo(cardHead);
btnDrag.prependTo(cardHead);
card.append(cardHead);
var cardList = $("<div>");
@ -126,35 +99,29 @@ function buildCard(title, itemList) {
for (var i = 0; i < itemList.length; i++) {
var item = itemList[i];
// the fa span gets replaced with an svg element, which causes problems
// with using it as a drag handle, so wrap it in the drag element
var handle = $("<span>").addClass("mr-2 start-hidden dragHandle")
.append($("<span>").addClass("fas fa-bars"));
var del = $("<span>")
.attr({"data-group": title, "data-key": item.key})
.attr({"data-group": title, "data-group-index": groupIndex, "data-key": i})
.addClass("btnDel far fa-trash-alt float-right mt-1 start-hidden text-danger");
del.css("cursor: pointer;");
$("<a>")
.attr({
"id": title + "-" + item.key,
"id": title + "-" + i,
"class": "list-group-item list-group-item-action bookmark",
"href": item.address,
"data-name": item.name,
"data-address": item.address
})
.text(item.name)
.prepend(handle)
.append(del)
.appendTo(cardList);
}
return card;
}
function addGroup(group, groupStore, db, index) {
var objStore = db.createObjectStore(group.title, { autoIncrement: true });
objStore.createIndex("name", "name", { unique: false });
objStore.createIndex("address", "address", { unique: false });
groupStore.add({ "title": group.title, "groupIndex": index });
var bookmarks = group.bookmarks;
for (var i = 0; i < bookmarks.length; i++) {
var bkmk = bookmarks[i];
objStore.add({ "name": bkmk.name, "address": bkmk.address }, i);
}
}

View file

@ -1,6 +1,5 @@
// use this when making changes so that there is no need to parse the page
var bookmarkList;
var dbVersion;
var backgroundList = ["img/1.png", "img/2.png", "img/3.png", "img/4.png",
"img/5.png", "img/6.png", "img/7.png", "img/8.png"];