first refactor: load and save

This commit is contained in:
quenousimporte 2024-02-01 23:21:05 +01:00
parent 3e15377b57
commit 090c04eedd
1 changed files with 96 additions and 62 deletions

158
main.js
View File

@ -24,11 +24,11 @@ var codelanguages = ["xml", "js", "sql"];
var tagmark = "+"; var tagmark = "+";
// globals // globals
var currentnote = null; var currentguid = null;
var notesindex = null;
var fileindex = 0; var fileindex = 0;
var workerid = null; var workerid = null;
var backup = ""; var backup = "";
var localdata = null;
var saved = true; var saved = true;
var lastsaved = ""; var lastsaved = "";
var pending = false; var pending = false;
@ -380,11 +380,6 @@ function decryptstring(str)
}) })
} }
function getnote(title)
{
return localdata.find(note => note.title == title);
}
function getrangecontent(range) function getrangecontent(range)
{ {
return md.value.substring(range.start, range.end); return md.value.substring(range.start, range.end);
@ -878,7 +873,7 @@ function restoresettings()
function editsettings() function editsettings()
{ {
bindfile( bind(
{ {
title: "settings.json", title: "settings.json",
content: JSON.stringify(settings, null, " ") content: JSON.stringify(settings, null, " ")
@ -933,7 +928,7 @@ function decryptnote()
function editpgpkeys() function editpgpkeys()
{ {
bindfile( bind(
{ {
title: "pgpkeys", title: "pgpkeys",
content: localStorage.getItem("pgpkeys") || "" content: localStorage.getItem("pgpkeys") || ""
@ -992,13 +987,13 @@ function searchtags()
.then(loadnote); .then(loadnote);
} }
function gettags(note) function gettags(content)
{ {
var i = note.content.indexOf("tags: "); var i = content.indexOf("tags: ");
if (i > -1) if (i > -1)
{ {
var j = note.content.indexOf("\n", i); var j = content.indexOf("\n", i);
return note.content.substring(i + 6, j) return content.substring(i + 6, j)
.split(",") .split(",")
.map(t => t.toLowerCase().trim()) .map(t => t.toLowerCase().trim())
.filter(t => t.length); .filter(t => t.length);
@ -1180,8 +1175,21 @@ function gotoline(line)
function loadstorage() function loadstorage()
{ {
var item = window.localStorage.getItem("data"); notesindex = JSON.parse(localStorage.getItem("index"));
localdata = item ? JSON.parse(item) : []; if (!notesindex)
{
notesindex = {};
// todo: refactor in "add new note"
var guid = crypto.randomUUID();
var content = defaultheaders();
var item = {
title: timestamp(),
pos: content.length
};
notesindex[guid] = item;
localStorage.setItem("index", JSON.stringify(notesindex));
localStorage.setItem(guid, content);
}
var params = new URLSearchParams(window.location.search); var params = new URLSearchParams(window.location.search);
var title = params.get("n") || params.get("name"); var title = params.get("n") || params.get("name");
@ -1201,7 +1209,8 @@ function loadstorage()
inserttodo("@clip " + clip).then(window.close); inserttodo("@clip " + clip).then(window.close);
} }
if (currentnote) // when multiple tabs or split?
/*if (currentnote)
{ {
currentnote = getnote(currentnote.title); currentnote = getnote(currentnote.title);
} }
@ -1214,11 +1223,11 @@ function loadstorage()
currentnote = {title: title, content: newcontent, pos: newcontent.length}; currentnote = {title: title, content: newcontent, pos: newcontent.length};
localdata.unshift(currentnote); localdata.unshift(currentnote);
} }
} }*/
if (currentnote) if (currentguid)
{ {
bindfile(currentnote); bind(currentguid);
if (line) if (line)
{ {
gotoline(line); gotoline(line);
@ -1288,8 +1297,29 @@ function initsnippets()
}); });
} }
function migratelegacystorage()
{
var legacy = localStorage.getItem("data");
if (legacy)
{
var legacy = JSON.parse(legacy);
var index = {};
legacy.forEach(note =>
{
var guid = crypto.randomUUID();
localStorage.setItem(guid, note.content);
note.tags = gettags(note.content);
delete note.content;
index[guid] = note;
});
localStorage.setItem("index", JSON.stringify(index));
localStorage.removeItem("data");
}
}
function init() function init()
{ {
migratelegacystorage();
loadsettings(); loadsettings();
window.onbeforeunload = checksaved; window.onbeforeunload = checksaved;
@ -1349,14 +1379,14 @@ function init()
} }
} }
function getorcreate(title, content) function getorcreate(guid, content)
{ {
var note = getnote(title); var note = getnote(guid);
if (!note) /*if (!note)
{ {
note = {title: title, content: content, pos: content.length}; note = {title: title, content: content, pos: content.length};
localdata.push(note) localdata.push(note)
} }*/
return note; return note;
} }
@ -1514,7 +1544,7 @@ function md2html(content)
function loadlast() function loadlast()
{ {
loadnote(localdata.length ? localdata[0].title : timestamp()); loadnote(Object.keys(notesindex)[0]);
} }
function loadprevious() function loadprevious()
@ -1578,7 +1608,7 @@ function showgrepresult(needle, grepresult)
grepcontent.push("No result."); grepcontent.push("No result.");
} }
bindfile( bind(
{ {
title: "Search result", title: "Search result",
content: grepcontent.join("\n") content: grepcontent.join("\n")
@ -1796,11 +1826,8 @@ function resize()
function putontop() function putontop()
{ {
if (localdata.find(n => n == currentnote)) console.warn("todo: put on top");
{ return;
localdata.splice(localdata.indexOf(currentnote), 1);
localdata.unshift(currentnote);
}
} }
function postpone() function postpone()
@ -1819,13 +1846,27 @@ function setsaved()
lastsaved = timestamp(); lastsaved = timestamp();
} }
function serialize()
{
// serialize all gui stuff to local storage
var item = notesindex[currentguid];
item.title = title.value;
item.pos = md.selectionStart;
item.tags = gettags(md.value);
putontop();
localStorage.setItem("index", JSON.stringify(notesindex));
localStorage.setItem(currentguid, md.value);
}
function save() function save()
{ {
return new Promise(function(resolve, reject) return new Promise(function(resolve, reject)
{ {
clearTimeout(workerid); clearTimeout(workerid);
if (currentnote.title == "settings.json") if (title.value == "settings.json")
{ {
settings = JSON.parse(md.value); settings = JSON.parse(md.value);
savesettings(); savesettings();
@ -1833,17 +1874,12 @@ function save()
setsaved(); setsaved();
resolve(); resolve();
} }
else if (currentnote.title == "pgpkeys") else if (title.value == "pgpkeys")
{ {
localStorage.setItem("pgpkeys", md.value); localStorage.setItem("pgpkeys", md.value);
setsaved(); setsaved();
resolve(); resolve();
} }
else if (!localdata)
{
showtemporaryinfo("cannot push empty data");
reject();
}
else if (pending) else if (pending)
{ {
console.log("pending query: save cancelled"); console.log("pending query: save cancelled");
@ -1859,16 +1895,12 @@ function save()
var content = md.value; var content = md.value;
if ((content == "" && backup != "") || content == "null" || content == "undefined") if ((content == "" && backup != "") || content == "null" || content == "undefined")
{ {
showtemporaryinfo("Invalid content '" + content + "', file '" + currentnote.title + "' not saved"); showtemporaryinfo("Invalid content '" + content + "', file '" + title.value + "' not saved");
reject(); reject();
} }
else else
{ {
currentnote.pos = md.selectionStart; serialize();
currentnote.content = content;
putontop();
window.localStorage.setItem("data", JSON.stringify(localdata));
if (settings.sync) if (settings.sync)
{ {
@ -2246,7 +2278,7 @@ function showhelp()
help.push("##Sources"); help.push("##Sources");
help.push("https://github.com/quenousimporte/notes"); help.push("https://github.com/quenousimporte/notes");
bindfile( bind(
{ {
title: "Help", title: "Help",
content: help.join("\n") content: help.join("\n")
@ -2307,7 +2339,8 @@ function istodo(note)
function currentistodo() function currentistodo()
{ {
return istodo(currentnote); //return istodo(currentnote);
return title.value.includes("todo") || gettags(md.value).includes("todo");
} }
function sorttodotxt(note) function sorttodotxt(note)
@ -2648,7 +2681,7 @@ function mainkeydownhandler()
function setwindowtitle() function setwindowtitle()
{ {
document.title = currentnote.title; document.title = title.value;
} }
function ontitlechange() function ontitlechange()
@ -2862,16 +2895,15 @@ function togglepreviewwithsubs()
} }
} }
function bindfile(note) function bind(title, content, pos)
{ {
var changed = currentnote != note; var changed = title.value != title;
backup = note.content; backup = content;
currentnote = note; title.value = title;
title.value = note.title;
setwindowtitle(); setwindowtitle();
seteditorcontent(note.content || "", true); seteditorcontent(content || "", true);
if (changed) if (changed)
{ {
@ -2879,7 +2911,7 @@ function bindfile(note)
} }
resize(); resize();
setpos(note.pos || 0); setpos(pos || 0);
if (!issplit() && searchdialog.hidden) if (!issplit() && searchdialog.hidden)
{ {
@ -2899,14 +2931,16 @@ function defaultheaders(tags = "")
"",""].join("\n"); "",""].join("\n");
} }
function loadnote(name) function loadnote(guid)
{ {
var note = getorcreate(name, defaultheaders()); currentguid = guid;
var content = localStorage.getItem(guid);
var item = notesindex[guid];
if (gettags(note).includes("journal")) /*if (gettags(content).includes("journal"))
{ {
// remove empty entries // remove empty entries
note.content = note.content.replace(/\d{4}-\d{2}-\d{2}\n*(\d{4}-\d{2}-\d{2})/g, "$1"); content = content.replace(/\d{4}-\d{2}-\d{2}\n*(\d{4}-\d{2}-\d{2})/g, "$1");
// create new entry for today // create new entry for today
var hat = headerandtext(note); var hat = headerandtext(note);
@ -2916,20 +2950,20 @@ function loadnote(name)
note.content = hat.header + "\n" + today + "\n\n" + hat.text; note.content = hat.header + "\n" + today + "\n\n" + hat.text;
note.pos = hat.header.length + 12; note.pos = hat.header.length + 12;
} }
} }*/
if (settings.autosorttodo && istodo(note)) /*if (settings.autosorttodo && istodo(note))
{ {
sorttodotxt(note); sorttodotxt(note);
} }*/
bindfile(note); bind(item.title, content, item.pos);
stat.cur.q = 0; stat.cur.q = 0;
stat.cur.d = 0; stat.cur.d = 0;
stat.cur.t = timestamp(); stat.cur.t = timestamp();
if (!preview.hidden || (preview.hidden && (gettags(note).indexOf("preview") !== -1))) if (!preview.hidden || (preview.hidden && (gettags(md.value).indexOf("preview") !== -1)))
{ {
togglepreview(); togglepreview();
} }