notes/main.js

2125 lines
39 KiB
JavaScript
Raw Normal View History

2023-01-26 12:01:15 +01:00
var defaultsettings =
2023-01-18 12:34:55 +01:00
{
bgcolor: "white",
fontfamily: "'Inconsolata', 'Consolas', monospace",
fontsize: "90%",
fontcolor: "black",
lineheight: "130%",
accentcolor: "#5AA7CE",
margins: "7%",
savedelay: 2000,
2023-01-18 12:34:55 +01:00
foldmarkstart: 22232,
defaultpreviewinsplit: false,
enablefolding: false,
tagautocomplete: false,
titleinaccentcolor: false
2023-01-18 12:34:55 +01:00
};
//builtin
var markerslist = ["* ", "- ", " * ", " - ", ">> ", "> ", "=> ", "— ", "[ ] ", " "];
2023-01-18 12:34:55 +01:00
var sectionmarks = ["---", "### ", "## ", "# ", "```"];
var codelanguages = ["xml", "js", "sql"];
// globals
var currentnote = null;
var fileindex = 0;
var workerid = null;
2023-01-18 12:34:55 +01:00
var folds = [];
var backup = "";
var localdata = null;
2023-01-25 15:41:21 +01:00
var saved = true;
var pending = false;
2023-01-18 12:34:55 +01:00
var settings = null;
var tags = null;
var currentvault = "";
var currenttag = "";
2023-01-18 12:34:55 +01:00
var vaults = ["local", "remote", "sandbox"];
2023-01-26 12:01:15 +01:00
var stat =
{
ses:
{
q: 0,
t: timestamp()
},
cur:
{
q: 0,
t: timestamp()
}
}
2023-01-26 12:01:15 +01:00
var themes =
{
Default:
{
bgcolor: "white",
fontfamily: "'Inconsolata', 'Consolas', monospace",
fontsize: "90%",
fontcolor: "black",
lineheight: "130%",
accentcolor: "#5AA7CE"
},
Notion:
{
bgcolor: "white",
fontfamily: "ui-sans-serif, -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, 'Apple Color Emoji', Arial, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'",
fontsize: "16px",
fontcolor: "rgb(55,53,47)",
lineheight: "24px",
accentcolor: "rgb(55,53,47)"
},
Monkey:
{
bgcolor: "rgb(227,227,227)",
fontfamily: "'Hack', 'Consolas', monospace",
fontsize: "14px",
fontcolor: "rgb(55,55,55)",
lineheight: "24px",
accentcolor: "#5AA7CE"
2023-01-23 13:42:04 +01:00
},
Mariana:
{
bgcolor: "rgb(48,56,65)",
fontfamily: "'Consolas', monospace",
fontsize: "15px",
fontcolor: "rgb(216,222,233)",
lineheight: "110%",
2023-01-26 12:01:15 +01:00
accentcolor: "rgb(249,174,88)"
},
"Plus plus":
{
bgcolor: "white",
2023-01-25 18:10:21 +01:00
fontfamily: "'Consolas', 'Courier New', monospace",
fontsize: "15px",
fontcolor: "black",
lineheight: "110%",
2023-01-26 12:01:15 +01:00
accentcolor: "rgb(128,0,255)"
},
Calmly:
{
bgcolor: "rgb(250,250,250)",
fontfamily: "'Droid Serif', serif",
2023-01-25 22:01:31 +01:00
fontsize: "19px",
fontcolor: "rgb(60,60,60)",
2023-01-25 22:01:31 +01:00
lineheight: "28.5px",
accentcolor: "rgb(60,60,60)"
},
Breakers:
{
bgcolor: "rgb(252,253,253)",
fontfamily: "'Consolas', monospace",
fontsize: "15px",
fontcolor: "rgb(50,50,50)",
lineheight: "110%",
accentcolor: "rgb(95,180,180)"
},
Cryptee:
{
bgcolor: "white",
fontfamily: "'Josefin Sans', sans-serif",
fontsize: "16px",
fontcolor: "rgb(78,78,78)",
lineheight: "24px",
accentcolor: "rgb(54,54,54)"
}
};
2023-01-18 12:34:55 +01:00
var commands = [
{
hint: "Close menu"
},
{
shortcut: "ctrl+p",
hint: "Show notes list",
action: searchandloadnote
},
{
hint: "Share note",
action: share,
allowunsaved: true
},
2023-01-18 12:34:55 +01:00
{
hint: "Share note (html)",
action: sharehtml
},
2023-01-18 12:34:55 +01:00
{
shortcut: "ctrl+n",
hint: "New note",
action: startnewnote
},
{
shortcut: "ctrl+shift+P",
hint: "Command palette",
allowunsaved: true,
2023-01-18 12:34:55 +01:00
action: commandpalette,
excludepalette: true
},
{
shortcut: "ctrl+t",
hint: "Open todo",
action: loadtodo
},
{
shortcut: "ctrl+q",
hint: "Open quick note",
action: loadquicknote
},
{
shortcut: "ctrl+g",
2023-01-18 12:34:55 +01:00
hint: "Find in notes",
action: showgrep
},
{
shortcut: "ctrl+i",
hint: "Toggle title",
action: toggletitle,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
shortcut: "ctrl+m",
hint: "Toggle preview",
action: togglepreview,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
shortcut: "ctrl+d",
hint: "Delete note",
action: deletecurrentnote
2023-01-18 12:34:55 +01:00
},
{
hint: "Restore note",
action: restore
},
{
shortcut: "ctrl+h",
hint: "Insert markdown header",
action: insertheader,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
shortcut: "F1",
hint: "Show help",
action: showhelp
},
{
shortcut: "ctrl+shift+C",
hint: "Fold",
action: fold,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
shortcut: "ctrl+shift+O",
hint: "Unfold",
action: unfold,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
hint: "Unfold all",
action: unfoldall,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
hint: "Search tags",
action: searchtags,
shortcut: "ctrl+shift+T"
},
{
hint: "Log out",
action: logout,
},
{
hint: "Toggle split view",
action: togglesplit
},
{
hint: "Load previous note",
action: loadprevious,
shortcut: "ctrl+b"
2023-01-18 12:34:55 +01:00
},
{
hint: "Sort text",
action: sortselection,
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
hint: "Settings",
2023-01-26 12:01:15 +01:00
action: editsettings
2023-01-18 12:34:55 +01:00
},
{
hint: "Restore default settings",
2023-01-26 12:01:15 +01:00
action: restoresettings
2023-01-18 12:34:55 +01:00
},
{
hint: "Note outline",
action: showoutline,
shortcut: "ctrl+o",
allowunsaved: true
2023-01-18 12:34:55 +01:00
},
{
hint: "Show connected notes",
action: shownotelinks,
shortcut: "ctrl+l"
},
{
hint: "Change vault",
action: switchvault,
shortcut: "ctrl+shift+V"
},
{
hint: "Add tag filter",
action: addtagfilter,
shortcut: "ctrl+shift+F",
},
{
hint: "Select theme",
action: selecttheme,
allowunsaved: true
},
{
hint: "Show info",
action: showinfo,
shortcut: "ctrl+w",
allowunsaved: true
2023-01-25 23:50:48 +01:00
},
{
hint: "Force save",
action: save,
shortcut: "ctrl+s",
allowunsaved: true
},
{
hint: "Toggle spell check",
action: togglespellcheck,
allowunsaved: true,
shortcut: "F7"
},
{
hint: "Create subnote from selection",
action: createsubnote
},
{
hint: "Merge subnote",
action: includesub
2023-01-30 10:16:07 +01:00
},
{
hint: "Comment selection",
action: comment
},
{
hint: "Download note",
action: downloadnote
},
{
hint: "Download note with merged subnotes",
action: downloadnotewithsubs
},
{
hint: "Download vault",
action: downloadvault,
shortcut: "ctrl+shift+S"
2023-01-25 23:50:48 +01:00
}];
2023-01-18 12:34:55 +01:00
var snippets = [
{
command: "/code",
hint: "Code block",
insert: "```\n\n```",
cursor: -4
},
{
command: "/date",
hint: "Current date",
insert: (new Date).toISOString().substring(0, 10) + " ",
cursor: 0
},
{
command: "/bonjour",
hint: "Standard answer (fr)",
insert: "Bonjour ,\n\n\n\nBien cordialement,\nSimon",
cursor: -29
},
{
command: "/hello",
hint: "Standard answer (en)",
insert: "Hello ,\n\n\n\nKind regards,\nSimon",
cursor: -24
},
{
command: "/-",
hint: "Dialog mark",
insert: "— ",
cursor: 0
2023-01-18 12:34:55 +01:00
}];
function ask(question)
{
return new Promise( (resolve) =>
{
filter.placeholder = question;
return searchinlist(["Yes", "No"])
.then(answer =>
{
resolve(answer);
});
});
}
function getnote(title)
{
return localdata.find(note => note.title == title);
}
function createsubnote(suggestedtitle)
{
var name = [];
if (suggestedtitle)
{
name.push(suggestedtitle);
}
var range = getlinesrange();
var content = md.value.substring(range.start, range.end);
filter.placeholder = "Subnote title...";
searchinlist(name)
.then(title =>
{
if (!title)
{
showtemporaryinfo("No title provided");
setpos(md.selectionStart);
}
else if (getnote(title))
{
showtemporaryinfo("'" + title + "' already exists");
setpos(md.selectionStart);
}
else
{
var newnote =
{
title: title,
content: content
}
localdata.unshift(newnote);
md.value = md.value.substring(0, range.start)
+ "[[" + title + "]]"
+ md.value.substring(range.end);
datachanged();
}
2023-01-30 10:16:07 +01:00
});
}
function comment()
{
md.value = md.value.substring(0, md.selectionStart)
+ "<!-- "
+ md.value.substring(md.selectionStart, md.selectionEnd)
+ " -->"
+ md.value.substring(md.selectionEnd);
}
function includesub()
{
var range = linkrangeatpos();
if (range)
{
var title = linkatpos();
ask("Replace [[" + title + "]] by its content?")
.then( (answser) =>
{
if (answser != "Yes") return;
var subnote = getnote(title);
md.value =
md.value.substring(0, range.start)
+ subnote.content
+ md.value.substring(range.end);
ask("Delete '" + title + "'?")
.then( (answser) =>
{
if (answser != "Yes") return;
deletenote(subnote);
})
.finally(datachanged);
});
}
}
function togglespellcheck()
{
md.spellcheck = !md.spellcheck;
}
function showinfo()
{
var tags = gettags(currentnote);
showtemporaryinfo(
2023-01-26 12:01:15 +01:00
[
"title: " + currentnote.title,
"vault: " + currentvault,
(tags ? "tags: " + tags : ""),
"saved: " + saved,
"word count: " + getwords(),
"current filter: " + currenttag || "",
"current note start: " + stat.cur.t,
"current note queries: " + stat.cur.q,
"session start: " + stat.ses.t,
"session queries: " + stat.ses.q
], "Note info");
}
function loadtheme(theme)
{
for (var i in themes[theme])
{
settings[i] = themes[theme][i];
}
applystyle();
resize();
}
function savesettings()
{
window.localStorage.setItem("settings", JSON.stringify(settings));
}
function selecttheme()
{
searchinlist(Object.keys(themes), loadtheme)
2023-01-26 12:01:15 +01:00
.then(t =>
{
loadtheme(t);
savesettings();
});
}
function addtagfilter()
{
var command = commands.find(c => c.action == addtagfilter);
2023-01-26 12:01:15 +01:00
if (!currenttag)
{
tagslist()
2023-01-26 12:01:15 +01:00
.then(t =>
{
currenttag = t;
command.hint = "Remove tag filter '" + currenttag + "'";
setwindowtitle();
2023-01-26 12:01:15 +01:00
});
}
else
{
currenttag = "";
command.hint = "Add tag filter";
setwindowtitle();
}
}
function switchvault()
{
searchinlist(vaults)
.then(vault =>
{
window.localStorage.setItem("vault", vault);
init();
datafile.hidden = vault != "sandbox";
});
}
function ancestors(note)
{
var list = [... new Set(parents(note))];
list.forEach(title =>
{
var parent = localdata.find(n => n.title == title);
if (parent && !list.find(p => p.title == parent))
{
list = list.concat(ancestors(parent));
}
})
return list;
}
function descendants(note)
{
var list = [... new Set(children(note))];
list.forEach(title =>
{
var child = localdata.find(n => n.title == title);
if (child && !list.find(p => p.title == child))
{
list = list.concat(descendants(localdata.find(n => n.title == title)));
}
})
return list;
}
function children(note)
{
return (note.content
.match(/\[\[([^\]]*)\]\]/g) || [])
.map(l => l.replace("[[", "").replace("]]", ""));
}
function parents(note)
2023-01-18 12:34:55 +01:00
{
return localdata
.filter(n => n.content.indexOf("[[" + note.title + "]]") != -1)
.map(n => n.title);
}
function shownotelinks()
{
try
{
var list = ancestors(currentnote).reverse();
var index = list.length;
list.push(currentnote.title);
list = list.concat(descendants(currentnote));
searchinlist(list, null, index)
.then(loadnote);
}
catch(err)
{
showtemporaryinfo("Loop detected");
}
2023-01-18 12:34:55 +01:00
}
function showoutline()
{
var outline = {};
var pos = 0;
2023-01-30 10:36:43 +01:00
getnotecontent().split("\n").forEach((line, index, lines) =>
2023-01-18 12:34:55 +01:00
{
pos += line.length + 1;
if (line.startsWith("#"))
2023-01-18 12:34:55 +01:00
{
line = line
.replace("# ", "")
.replace(/#/g, "\xa0".repeat(4));
2023-01-18 12:34:55 +01:00
outline[line] = pos;
2023-01-26 12:01:15 +01:00
}
2023-01-18 12:34:55 +01:00
});
2023-01-30 10:36:43 +01:00
var keys = Object
.keys(outline)
.sort((a,b) =>
{
return outline[a] - outline[b];
});
searchinlist(keys)
2023-01-18 12:34:55 +01:00
.then(line =>
{
md.setSelectionRange(outline[line], outline[line]);
md.focus();
});
}
function linkrangeatpos()
{
var start = md.value.lastIndexOf("[[", md.selectionStart);
if (start == -1 || md.value.substring(start, md.selectionStart).indexOf("\n") != -1) return null
var end = md.value.indexOf("]]", md.selectionStart);
if (end == -1 || md.value.substring(md.selectionStart, end).indexOf("\n") != -1) return null;
return {
start: start,
end: end + 2
};
}
function linkatpos()
{
var range = linkrangeatpos();
if (range)
{
return md.value.substring(range.start + 2, range.end - 2);
}
return null;
}
function tagatpos()
{
2023-01-30 14:53:42 +01:00
if (md.value.lastIndexOf("tags: ", md.selectionStart) < md.value.lastIndexOf("\n", md.selectionStart) || md.selectionStart < 6)
{
return null;
}
var start = md.value.lastIndexOf(" ", md.selectionStart);
if (start == -1 || md.value.substring(start, md.selectionStart).indexOf("\n") != -1) return "";
2023-01-30 14:53:42 +01:00
var eol = md.value.indexOf("\n", md.selectionStart);
var end = md.value.indexOf(",", md.selectionStart);
2023-01-30 14:53:42 +01:00
if (end == -1 || eol < end)
{
2023-01-30 14:53:42 +01:00
end = eol;
}
return md.value.substring(start + 1, end);
}
function clickeditor()
{
if (event.ctrlKey)
{
var link = linkatpos();
var tag = tagatpos();
if (link)
{
loadnote(link);
}
else if (tag)
{
tagslist();
2023-01-23 12:59:46 +01:00
searchinlist(tags[tag.toLowerCase()])
.then(loadnote);
}
else
{
checkfolding();
}
}
}
2023-01-18 12:34:55 +01:00
function restoresettings()
{
if (confirm("Restore default settings?"))
{
settings = defaultsettings;
savesettings();
2023-01-18 12:34:55 +01:00
loadsettings();
}
}
function editsettings()
{
bindfile(
{
title: "settings.json",
content: JSON.stringify(settings, null, " ")
});
}
function showtemporaryinfo(data, title)
2023-01-18 12:34:55 +01:00
{
if (typeof data == "string")
{
data = new Array(data);
}
filter.placeholder = title || "Info";
searchinlist(data)
2023-01-26 12:01:15 +01:00
.then(() =>
2023-01-25 18:10:21 +01:00
{
filter.placeholder = "Search...";
});
md.focus();
2023-01-18 12:34:55 +01:00
}
function getwords()
2023-01-18 12:34:55 +01:00
{
return getnotecontent().split(/\s+\b/).length;
2023-01-18 12:34:55 +01:00
}
function issplit()
{
return window.location !== window.parent.location;
}
function togglesplit()
{
if (issplit())
{
window.parent.location = "index.html";
}
else
{
window.location = "split.html";
}
}
function isremote()
{
return currentvault == "remote";
}
2023-01-18 12:34:55 +01:00
function logout()
{
if (isremote())
{
window.localStorage.removeItem("password");
2023-01-26 12:01:15 +01:00
togglepassword();
}
2023-01-18 12:34:55 +01:00
}
function tagslist()
2023-01-18 12:34:55 +01:00
{
tags = {};
2023-01-18 12:34:55 +01:00
localdata
2023-01-26 12:01:15 +01:00
.forEach(n =>
2023-01-18 12:34:55 +01:00
{
var ts = gettags(n);
2023-01-26 12:01:15 +01:00
ts.forEach(t =>
2023-01-18 12:34:55 +01:00
{
tags[t] = tags[t] || [];
tags[t].push(n.title);
});
});
return searchinlist(Object.keys(tags).sort());
}
function searchtags()
{
tagslist()
2023-01-18 12:34:55 +01:00
.then(tag => searchinlist(tags[tag]))
.then(loadnote);
2023-01-18 12:34:55 +01:00
}
function gettags(note)
{
var i = note.content.indexOf("tags: ");
if (i > -1)
{
var j = note.content.indexOf("\n", i);
return note.content.substring(i + 6, j).split(",").map(t => t.toLowerCase().trim());
}
return [];
}
function share()
2023-01-18 12:34:55 +01:00
{
if (navigator.share)
{
navigator.share(
{
text: getnotecontent(),
2023-01-18 12:34:55 +01:00
title: currentnote.title
2023-01-26 12:01:15 +01:00
});
}
2023-01-18 12:34:55 +01:00
}
function sharehtml()
{
if (navigator.share)
{
var file = new File(['<html><body>' + md2html(getnotecontent()) + '</body></html>'],
currentnote.title + ".html",
{
type: "text/html",
});
navigator.share(
{
title: currentnote.title,
files: [file]
});
}
2023-01-18 12:34:55 +01:00
}
function download(filename, content)
{
// trick: https://www.bitdegree.org/learn/javascript-download
// to improve...
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function downloadnotes()
{
localdata
.forEach(note =>
{
download(note.title + ".md", note.content);
});
}
function downloadvault()
2023-01-18 12:34:55 +01:00
{
download("notes " + timestamp() + " " + currentvault + ".json", window.localStorage.getItem(currentvault));
2023-01-18 12:34:55 +01:00
}
function downloadnotewithsubs()
{
try
{
descendants(currentnote);
}
catch (err)
{
showtemporaryinfo("Loop detected");
return;
}
var tempnote =
{
title: currentnote.title + " (with subnotes)",
content: getnotecontent()
};
var kids = children(tempnote);
while (kids.length)
{
kids.forEach(t =>
{
tempnote.content = tempnote.content.replaceAll("[[" + t + "]]", getnote(t).content);
});
kids = children(tempnote);
}
download(tempnote.title + ".md", tempnote.content);
}
2023-01-18 12:34:55 +01:00
function downloadnote()
{
download(currentnote.title + ".md", getnotecontent());
}
function remotecallfailed(error)
{
if (error)
{
console.warn(error);
showtemporaryinfo(error, "Error");
2023-01-18 12:34:55 +01:00
}
}
function loadstorage()
{
var item = window.localStorage.getItem(currentvault);
2023-01-18 12:34:55 +01:00
localdata = item ? JSON.parse(item) : [];
// only refresh content?
2023-01-18 12:34:55 +01:00
if (currentnote)
{
currentnote = localdata.find(n => n.title == currentnote.title);
}
if (currentnote)
{
bindfile(currentnote);
}
else
{
loadlast();
}
}
function applystyle()
{
document.body.style.background = settings.bgcolor;
document.body.style.fontFamily = settings.fontfamily;
document.body.style.fontSize = settings.fontsize;
document.body.style.lineHeight = settings.lineheight;
document.body.style.color = settings.fontcolor;
document.body.style.caretColor = settings.accentcolor;
document.body.style.marginLeft = settings.margins;
document.body.style.marginRight = settings.margins;
2023-01-26 12:01:15 +01:00
if (settings.titleinaccentcolor)
{
2023-01-26 12:01:15 +01:00
title.style.color = settings.accentcolor;
}
}
2023-01-18 12:34:55 +01:00
function loadsettings()
{
settings = {...defaultsettings};
var item = window.localStorage.getItem("settings");
if (item)
{
item = JSON.parse(item);
for (var key in settings)
2023-01-18 12:34:55 +01:00
{
if (typeof item[key] !== "undefined")
{
2023-01-26 12:01:15 +01:00
settings[key] = item[key];
}
2023-01-18 12:34:55 +01:00
}
}
applystyle();
2023-01-18 12:34:55 +01:00
if (!settings.enablefolding)
{
commands = commands.filter(c => !c.hint.toLowerCase().includes("fold"));
}
}
function checksaved()
{
2023-01-25 15:41:21 +01:00
if (!saved)
2023-01-18 12:34:55 +01:00
{
return "not saved";
}
2023-01-18 12:34:55 +01:00
}
function initsnippets()
2023-01-18 12:34:55 +01:00
{
// code languages
2023-01-18 12:34:55 +01:00
codelanguages.forEach(lang =>
{
if (!snippets.find(s => s.command == "/" + lang))
2023-01-18 12:34:55 +01:00
{
snippets.push(
{
command: "/" + lang,
hint: lang + " code block",
insert: "```" + lang + "\n\n```",
cursor: -4
});
}
});
// md headings
for (var i = 1; i <= 3; i++)
{
if (!snippets.find(s => s.command == "/" + i))
{
snippets.push(
{
command: "/" + i,
hint: "Heading " + i,
insert: "#".repeat(i) + " ",
cursor: 0
});
}
}
}
function initvault()
{
currentvault = window.localStorage.getItem("vault") || "local";
}
function loaddatafile(filepath)
{
reader = new FileReader();
if (filepath.files && filepath.files[0])
{
reader.onload = function (e)
{
localdata = JSON.parse(e.target.result);
loadlast();
datafile.hidden = true;
};
reader.readAsText(filepath.files[0]);
}
return true;
}
function init()
{
loadsettings();
initvault();
window.onbeforeunload = checksaved;
window.onclick = focuseditor;
2023-01-26 12:01:15 +01:00
initsnippets();
currenttag = "";
if (isremote())
2023-01-18 12:34:55 +01:00
{
queryremote({action: "fetch"})
.then(data =>
{
localdata = data;
window.localStorage.setItem("remote", JSON.stringify(data));
2023-01-18 12:34:55 +01:00
loadlast();
})
.catch(remotecallfailed);
}
else
{
loadstorage();
}
if (issplit())
{
window.onstorage = loadstorage;
2023-01-18 12:34:55 +01:00
if (settings.defaultpreviewinsplit && name == "right")
{
2023-01-26 12:01:15 +01:00
togglepreview();
}
2023-01-18 12:34:55 +01:00
else if (name == "left")
{
2023-01-26 12:01:15 +01:00
md.focus();
2023-01-18 12:34:55 +01:00
}
}
}
function togglepassword()
{
password.value = "";
authentpage.hidden = false;
notepage.style.display = "none";
document.title = "notes";
password.focus();
}
function queryremote(params)
{
return new Promise( (apply, failed) => {
stat.cur.q++;
stat.ses.q++;
2023-01-18 12:34:55 +01:00
params.password = window.localStorage.getItem("password");
var paramlist = [];
for (var i in params)
{
paramlist.push(i + "=" + encodeURIComponent(params[i]));
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "handler.php");
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onerror = function()
{
failed("XMLHttpRequest error");
}
xhr.onload = function()
{
if (xhr.status !== 200)
{
failed("Http status " + xhr.status);
}
else
{
var data = {};
try
{
data = JSON.parse(xhr.responseText);
if (data.error)
{
if (data.error == "authent")
{
failed();
2023-01-18 12:34:55 +01:00
togglepassword();
}
else
{
failed("Remote handler returned an error: " + data.error);
}
}
else
{
authentpage.hidden = true;
notepage.style.display = "table";
apply(data);
}
}
catch(error)
{
failed("Handler result is not valid. JS error: " + error);
2023-01-26 12:01:15 +01:00
}
2023-01-18 12:34:55 +01:00
}
}
xhr.send(paramlist.join("&"));
});
}
function applyfolds(content)
{
for (var i = folds.length - 1; i >= 0; i--)
{
content = content.replace(String.fromCodePoint(settings.foldmarkstart + i), folds[i]);
}
return content;
}
function getlinesrange()
{
var start = md.selectionStart;
var end = md.selectionEnd;
while (start > 0 && md.value[start - 1] != "\n") start--;
while (end < md.value.length && md.value[end] != "\n") end++;
return {
start: start,
end: end
};
}
function sortselection()
{
var content = getnotecontent();
var range = {start: 0, end: content.length};
if (md.selectionStart != md.selectionEnd)
{
range = getlinesrange();
}
var selection = content.substring(range.start, range.end);
var sorted = selection.split("\n").sort().join("\n");
md.value = content.substring(0, range.start) + sorted + content.substring(range.end);
2023-01-25 15:41:21 +01:00
datachanged();
2023-01-18 12:34:55 +01:00
}
function selectlines()
{
var range = getlinesrange();
md.selectionStart = range.start;
md.selectionEnd = range.end;
}
function isfold(linecontent)
{
var res = linecontent.length == 1 && linecontent.codePointAt(0) >= settings.foldmarkstart;
if (res)
{
//security: if > 100, probably not a fold. Maybe an emoji. To improve.
res &= foldindex(linecontent) < 100;
}
return res;
}
function foldindex(foldmark)
{
return foldmark.codePointAt(0) - settings.foldmarkstart;
}
function fold()
{
// todo: forbid if > 100?
var start = md.selectionStart;
selectlines();
var content = md.value;
var char = String.fromCodePoint(settings.foldmarkstart + folds.length);
var value = content.substring(md.selectionStart, md.selectionEnd)
folds.push(value);
setnotecontent(content.substring(0, md.selectionStart)
+ char
+ content.substring(md.selectionEnd));
md.focus();
setpos(start);
resize();
}
function unfold()
{
var range = getlinesrange();
var linecontent = md.value.substring(range.start, range.end);
if (isfold(linecontent))
{
var i = foldindex(linecontent);
md.value = md.value.replace(linecontent, folds[i]);
md.focus();
setpos(range.start + folds[i].length);
}
resize();
}
function unfoldall()
{
md.value = getnotecontent();
resetfolds();
setpos(0);
md.focus();
resize();
}
function checkfolding()
{
var range = getlinesrange();
var line = md.value.substring(range.start, range.end);
var sectionmark = sectionmarks.find(m => line.startsWith(m));
if (sectionmark)
{
event.preventDefault();
// move to next line
setpos(range.end + 1);
range = getlinesrange();
var nextline = md.value.substring(range.start, range.end);
if (isfold(nextline))
{
unfold();
}
else
{
// find next occurence. If not found take all the remaining file.
if (md.value.includes("\n" + sectionmark, range.end))
{
sectionend = md.value.indexOf("\n" + sectionmark, range.end);
}
else
{
sectionend = md.value.length;
}
// keep last empty line if any
if (md.value[sectionend] == "\n")
{
sectionend--;
}
md.setSelectionRange(range.start, sectionend);
if (settings.enablefolding)
{
fold();
}
else
{
createsubnote(currentnote.title + " -" + line.replace(/#/g, ""));
}
2023-01-18 12:34:55 +01:00
}
}
else if (isfold(line))
{
event.preventDefault();
2023-01-18 12:34:55 +01:00
unfold();
}
}
function setnotecontent(content)
{
md.value = content;
}
function getnotecontent()
{
return applyfolds(md.value);
}
function ontopbarclick()
{
if (title.hidden)
{
commandpalette();
}
}
/*function checkfoldmismatch()
{
start = settings.foldmarkstart.toString(16);
end = (settings.foldmarkstart + 100).toString(16);
var match = md.value.match(new RegExp("[\\u" + start + "-\\u" + end + "]", "g"));
var markcount = 0;
if (match)
{
markcount = match.length;
}
var diff = folds.length - markcount;
if (diff)
{
console.warn(diff + " fold(s) missing.");
}
}*/
function md2html(content)
{
// dumb fallback for offline mode
if (typeof showdown == "undefined") return content
.replace(/\*\*([^\*]*)\*\*/g, "<strong>$1</strong>")
.replace(/\*([^\*]*)\*/g, "<em>$1</em>")
.replace(/\## (.*)/g, "<h2>$1</h2>")
.replace(/\# (.*)/g, "<h1>$1</h1>")
.replace(/\n/g, "<br>");
var converter = new showdown.Converter();
converter.setOption("simplifiedAutoLink", true);
converter.setOption("simpleLineBreaks", true);
converter.setOption("metadata", true);
var html = converter.makeHtml(content);
// internal links
html = html.replace(/\[\[([^\]]*)\]\]/g, "<a href='#' onclick='loadnote(\"$1\");'>$1</a>");
2023-01-18 12:34:55 +01:00
return html;
}
function list()
{
return localdata
.filter(n => currenttag == "" || gettags(n).includes(currenttag))
.map(n => n.title);
2023-01-18 12:34:55 +01:00
}
function loadlast()
{
loadnote(list().shift() || timestamp());
}
function loadprevious()
{
loadnote(list()[1]);
2023-01-18 12:34:55 +01:00
}
function grep(needle)
{
var result = {};
localdata
.forEach(note =>
{
if (note.title.toLowerCase().includes(needle.toLowerCase()))
{
result[note.title] = {};
}
note.content.split("\n")
.forEach((line, nb) => {
if (line.toLowerCase().includes(needle.toLowerCase()))
{
result[note.title] = result[note.title] || {};
result[note.title][nb] = line;
}
});
});
return result;
}
function showgrepresult(grepresult)
{
var grepcontent = ["# Search results: \"" + filter.value + "\""];
for (var file in grepresult)
{
grepcontent.push("[[" + file + "]]");
for (var l in grepresult[file])
{
grepcontent.push("[" + l + "] " + grepresult[file][l].replace(new RegExp("(" + filter.value + ")", "gi"), "**$1**"));
}
grepcontent.push("");
}
if (grepcontent.length == 0)
{
grepcontent.push("No result.");
}
bindfile(
{
title: "Search result",
content: grepcontent.join("\n")
});
if (preview.hidden)
{
togglepreview();
}
}
function showgrep()
{
filteredlist.hidden = true;
searchdialog.hidden = false;
filter.focus();
filter.select();
filter.onkeydown = function()
{
if (event.key === "Enter")
{
event.preventDefault();
searchdialog.hidden = true;
2023-01-26 12:01:15 +01:00
showgrepresult(grep(filter.value));
2023-01-18 12:34:55 +01:00
}
}
// live search
/*filter.oninput = function()
{
if (filter.value.length > 1)
{
showgrepresult(grep(filter.value));
2023-01-26 12:01:15 +01:00
}
2023-01-18 12:34:55 +01:00
}*/
}
function commandpalette()
{
searchinlist(commands
.filter(c => !c.excludepalette)
.map(c => c.hint)
.concat(snippets.map(s => "Insert snippet: " + s.hint)))
.then(hint =>
{
var command = commands.find(c => c.hint == hint);
if (command)
2023-01-18 12:34:55 +01:00
{
2023-01-26 12:01:15 +01:00
executecommand(command);
2023-01-18 12:34:55 +01:00
}
else
{
var snippet = snippets.find(s => "Insert snippet: " + s.hint == hint);
if (snippet)
{
insert(snippet.insert, snippet.cursor);
md.focus();
}
}
});
}
function insert(text, cursoroffset = 0, nbtodelete = 0)
{
var pos = md.selectionStart;
var content = md.value;
md.value =
content.substring(0, pos - nbtodelete)
+ text
+ content.substring(pos);
setpos(pos - nbtodelete + text.length + cursoroffset);
2023-01-25 15:41:21 +01:00
datachanged();
2023-01-18 12:34:55 +01:00
}
function searchinlist(list, customevent, index)
2023-01-18 12:34:55 +01:00
{
return new Promise(selectitem =>
{
fileindex = 0;
searchdialog.hidden = false;
filteredlist.hidden = false;
filteredlist.innerHTML = "";
filter.value = "";
list.forEach(item =>
{
var elt = document.createElement("div");
elt.textContent = item;
elt.onclick = function()
{
searchdialog.hidden = true;
selectitem(item);
}
elt.customevent = customevent;
2023-01-18 12:34:55 +01:00
filteredlist.appendChild(elt);
});
applyfilter();
if (index)
{
fileindex = index;
applyfileindex();
}
2023-01-18 12:34:55 +01:00
filter.onkeydown = function()
{
// doesn't work if focus is lost.
if (event.key === "Enter")
{
event.preventDefault();
searchdialog.hidden = true;
var selected = document.getElementsByClassName("selected")[0];
selectitem(selected ? selected.textContent : filter.value);
}
}
filter.focus();
2023-01-18 12:34:55 +01:00
});
}
function applyfileindex()
{
var i = 0;
[...filteredlist.children].forEach(child =>
{
if (child.nodeName == "DIV")
{
child.className = "";
if(!child.hidden)
{
if (i++ == fileindex)
{
child.className = "selected";
if (child.customevent)
{
child.customevent(child.textContent);
filter.focus();
}
2023-01-18 12:34:55 +01:00
}
}
}
});
}
function getpos()
{
return md.selectionStart;
}
function setpos(pos)
{
md.setSelectionRange(pos, pos);
}
function before(nb)
{
return md.value.substring(getpos() - nb, getpos());
}
function resize()
{
if (md.clientHeight < md.scrollHeight)
2023-01-18 12:34:55 +01:00
{
md.style.height = md.scrollHeight + 'px';
}
2023-01-18 12:34:55 +01:00
}
function putontop()
{
if (localdata.find(n => n == currentnote))
{
localdata.splice(localdata.indexOf(currentnote), 1);
2023-01-26 12:01:15 +01:00
localdata.unshift(currentnote);
2023-01-18 12:34:55 +01:00
}
}
2023-01-25 15:41:21 +01:00
function postpone()
{
return new Promise(function(resolve)
{
clearTimeout(workerid);
workerid = setTimeout(resolve, settings.savedelay);
});
}
2023-01-25 23:50:48 +01:00
function save()
2023-01-18 12:34:55 +01:00
{
2023-01-25 23:50:48 +01:00
clearTimeout(workerid);
2023-01-26 00:32:00 +01:00
if (currentnote.title == "settings.json")
{
settings = JSON.parse(md.value);
savesettings();
loadsettings();
saved = true;
return;
}
2023-01-26 00:32:00 +01:00
if (!localdata)
{
2023-01-26 00:32:00 +01:00
showtemporaryinfo("cannot push empty data");
return;
}
2023-01-25 15:41:21 +01:00
2023-01-26 00:32:00 +01:00
if (pending)
{
console.log("pending query: save cancelled");
return;
}
2023-01-25 15:41:21 +01:00
2023-01-26 00:32:00 +01:00
var content = getnotecontent();
if ((content == "" && backup != "") || content == "null" || content == "undefined")
{
showtemporaryinfo("Invalid content '" + content + "', file '" + currentnote.title + "' not saved");
return;
}
2023-01-25 15:41:21 +01:00
2023-01-26 00:32:00 +01:00
currentnote.pos = md.selectionStart;
currentnote.content = content;
window.localStorage.setItem(currentvault, JSON.stringify(localdata));
console.log("data serialized in local storage")
if (isremote())
{
console.log("sending data to php server...");
2023-01-25 15:41:21 +01:00
2023-01-26 00:32:00 +01:00
pending = true;
queryremote({action: "push", data: JSON.stringify(localdata)})
.then(() =>
{
console.log("...data saved on server");
saved = true;
})
.catch(remotecallfailed)
.finally(() =>
{
pending = false;
if (content != getnotecontent())
2023-01-25 15:41:21 +01:00
{
2023-01-26 00:32:00 +01:00
console.log("but content changed: will save again");
datachanged();
2023-01-25 15:41:21 +01:00
}
2023-01-26 00:32:00 +01:00
else if (!saved)
2023-01-25 15:41:21 +01:00
{
2023-01-26 00:32:00 +01:00
console.log("save failed. Data unsaved on server, manual action required.");
2023-01-25 15:41:21 +01:00
}
2023-01-26 00:32:00 +01:00
});
}
else
{
saved = true;
}
2023-01-18 12:34:55 +01:00
}
2023-01-25 23:50:48 +01:00
function datachanged()
{
resize();
saved = false;
postpone()
.then(save);
}
2023-01-18 12:34:55 +01:00
function loadtodo()
{
loadnote("todo");
2023-01-18 12:34:55 +01:00
}
function loadquicknote()
{
loadnote("Quick note");
2023-01-18 12:34:55 +01:00
}
function timestamp()
{
2023-01-30 10:08:15 +01:00
var utc = new Date();
var loc = new Date(utc - utc.getTimezoneOffset() * 60 * 1000);
return loc.toISOString().replace("T", " ").replace(/\..*/, "").replace(/:/g, ".");
2023-01-18 12:34:55 +01:00
}
function startnewnote()
{
loadnote(timestamp());
2023-01-18 12:34:55 +01:00
}
function showhelp()
{
var help = ["# Notes"];
help.push("## Shortcuts");
commands
.filter(command => Boolean(command.shortcut))
.forEach(command => help.push(command.hint + ": " + command.shortcut));
help.push("## Snippets");
snippets.forEach(snippet =>
{
help.push(snippet.hint + ": " + snippet.command);
});
help.push("## Libs");
help.push("[Showdown](https://showdownjs.com/)");
2023-01-26 08:45:56 +01:00
help.push("## Fonts");
help.push("[Inconsolata](https://levien.com/type/myfonts/inconsolata.html)");
2023-01-26 08:45:56 +01:00
help.push("[Hack](https://sourcefoundry.org/hack/)");
help.push("[Droid Serif](https://fonts.adobe.com/fonts/droid-serif)");
help.push("[Josefin Sans](https://fonts.google.com/specimen/Josefin+Sans)");
2023-01-18 12:34:55 +01:00
help.push("## Inspiration");
help.push("[rwtxt](https://rwtxt.com)");
help.push("[Offline Notepad](https://offlinenotepad.com/)");
help.push("[Writemonkey3](http://writemonkey.com/wm3/)");
help.push("[Sublime Text](https://www.sublimetext.com/)");
2023-01-26 08:45:56 +01:00
help.push("[Notion](https://www.notion.so/)");
help.push("[Calmly Writer](https://calmlywriter.com/)");
help.push("[Cryptee](https://crypt.ee/)");
2023-01-18 12:34:55 +01:00
bindfile(
{
title: "Help",
content: help.join("\n")
});
if (preview.hidden)
{
togglepreview();
}
}
function toggletitle()
{
if (title.hidden)
{
title.hidden = false;
title.focus();
}
else
{
title.hidden = true;
md.focus();
}
}
function selectnote()
{
return searchinlist(list()/*, loadnote*/);
2023-01-18 12:34:55 +01:00
}
function searchautocomplete()
{
selectnote().then(insertautocomplete);
}
function searchandloadnote()
{
selectnote().then(loadnote);
2023-01-18 12:34:55 +01:00
}
function renamereferences(newname)
{
localdata
.filter(note => note != currentnote)
.forEach(note =>
{
note.content = note.content.replaceAll("[[" + currentnote.title + "]]", "[[" + newname + "]]");
});
}
2023-01-18 12:34:55 +01:00
function rename(newname)
{
if (localdata.find(n => n.title == newname))
{
var error = newname + " alreday exists";
console.warn(error);
return error;
}
renamereferences(newname);
2023-01-18 12:34:55 +01:00
currentnote.title = newname;
2023-01-25 15:41:21 +01:00
datachanged();
2023-01-18 12:34:55 +01:00
return "";
}
function deletenote(note)
2023-01-18 12:34:55 +01:00
{
var trash = JSON.parse(window.localStorage.getItem("trash")) || [];
trash.push(note);
window.localStorage.setItem("trash", JSON.stringify(trash));
localdata = localdata.filter(n => n != note);
renamereferences(note.title + " (deleted)");
}
function deletecurrentnote()
{
if (confirm('delete "' + currentnote.title + '"?'))
{
deletenote(currentnote);
loadlast();
datachanged();
2023-01-18 12:34:55 +01:00
}
}
function restore()
{
if (confirm('restore "' + currentnote.title + '"?'))
{
setnotecontent(backup);
2023-01-25 15:41:21 +01:00
datachanged();
2023-01-18 12:34:55 +01:00
}
}
function insertheader()
{
if (!getnotecontent().startsWith("---"))
{
var headers = "---\ndate: " + (new Date).toISOString().substring(0, 10) + "\ntags: \n---\n\n";
md.value = headers + md.value;
setpos(27);
}
resize();
}
function splitshortcut(s)
{
var r = {};
s = s.split("+");
r.key = s.pop();
s.forEach(e => {
r[e] = true;
})
return r;
}
function executecommand(command)
{
if (!command.allowunsaved && !saved)
{
showtemporaryinfo("Cannot perform '" + command.hint + "' because current note is not saved.");
}
else if (command.action)
{
command.action();
}
}
2023-01-18 12:34:55 +01:00
function mainkeydownhandler()
{
2023-01-25 23:50:48 +01:00
if (event.key == "Escape")
2023-01-18 12:34:55 +01:00
{
if (!searchdialog.hidden)
{
event.preventDefault();
searchdialog.hidden = true;
2023-01-25 18:10:21 +01:00
filter.placeholder = "Search...";
2023-01-18 12:34:55 +01:00
md.focus();
}
2023-01-25 18:10:21 +01:00
else if (currentnote.title == "Help" || currentnote.title == "Search result")
{
loadlast();
}
2023-01-18 12:34:55 +01:00
else if (preview.hidden == false)
{
togglepreview();
}
}
2023-01-25 15:41:21 +01:00
else if (!searchdialog.hidden && (event.key == "Tab" || event.keyCode == "40" || event.keyCode == "38"))
2023-01-18 12:34:55 +01:00
{
event.preventDefault();
fileindex += (event.shiftKey || event.keyCode == "38") ? -1 : 1;
fileindex = Math.min(fileindex, filteredlist.children.length - 1);
fileindex = Math.max(fileindex, 0);
applyfileindex();
}
2023-01-25 15:41:21 +01:00
else
2023-01-18 12:34:55 +01:00
{
2023-01-25 15:41:21 +01:00
commands.filter(c => c.shortcut)
.forEach(command =>
2023-01-18 12:34:55 +01:00
{
2023-01-25 15:41:21 +01:00
var s = splitshortcut(command.shortcut);
if (event.key == s.key && !(s.ctrl && !event.ctrlKey && !event.altKey) && !(s.shift && !event.shiftKey))
2023-01-18 12:34:55 +01:00
{
2023-01-25 15:41:21 +01:00
event.preventDefault();
2023-01-26 12:01:15 +01:00
executecommand(command);
2023-01-18 12:34:55 +01:00
}
2023-01-25 15:41:21 +01:00
});
}
2023-01-18 12:34:55 +01:00
}
function setwindowtitle()
{
document.title = currentnote.title;
}
2023-01-18 12:34:55 +01:00
function ontitlechange()
{
var oldname = currentnote.title;
2023-01-26 12:01:15 +01:00
if (localdata.find(n => n.title == title.value))
2023-01-18 12:34:55 +01:00
{
showtemporaryinfo(title.value + " alreday exists");
2023-01-18 12:34:55 +01:00
title.value = currentnote.title;
return;
2023-01-18 12:34:55 +01:00
}
// rename internal references
localdata
.filter(note => note != currentnote)
.forEach(note =>
{
note.content = note.content.replaceAll("[[" + currentnote.title + "]]", "[[" + title.value + "]]");
});
currentnote.title = title.value;
datachanged();
setwindowtitle();
toggletitle();
2023-01-18 12:34:55 +01:00
}
function applyfilter()
{
[...filteredlist.children].forEach(div =>
{
div.hidden = div.textContent.toLowerCase().indexOf(filter.value.toLowerCase()) < 0;
});
fileindex = 0;
applyfileindex();
}
function backspace(nb)
{
var pos = getpos();
var c = md.value;
md.value = c.substring(0, pos - nb) + c.substring(pos);
setpos(pos - nb);
2023-01-25 15:41:21 +01:00
datachanged();
2023-01-18 12:34:55 +01:00
}
function editorkeydown()
{
if (event.key == "Enter")
{
var line = md.value.substring(0, getpos()).split("\n").pop();
markerslist.filter(marker => line.startsWith(marker))
2023-01-18 12:34:55 +01:00
.forEach(marker =>
{
event.preventDefault();
if (line != marker)
2023-01-18 12:34:55 +01:00
{
insert("\n" + marker);
}
else
{
backspace(marker.length);
}
});
}
else if (event.key === "Tab")
{
event.preventDefault();
// todo: reverse with shift
if (before(2) == "* " || before(2) == "- ")
{
setpos(getpos() - 2);
insert(" ", 2);
}
// disable tab
2023-01-26 12:01:15 +01:00
/*else
2023-01-18 12:34:55 +01:00
{
insert(" ");
}*/
}
2023-01-21 21:25:09 +01:00
else if (event.key === "[" && before(1) == "[")
{
event.preventDefault();
insert("[");
searchautocomplete();
}
else if (settings.tagautocomplete && event.key == " " && before(1) == "," && md.value.substring(0, getpos()).split("\n").pop().startsWith("tags: "))
2023-01-21 21:25:09 +01:00
{
event.preventDefault();
// search in tags list
console.log(event.key);
tagslist()
2023-01-26 12:01:15 +01:00
.then(tag =>
2023-01-21 21:25:09 +01:00
{
insert(" " + tag);
md.focus();
})
}
else
2023-01-21 21:25:09 +01:00
{
var snippet = snippets.find(s => before(s.command.length - 1) + event.key == s.command);
if (snippet)
{
event.preventDefault();
insert(snippet.insert, snippet.cursor, snippet.command.length - 1);
}
}
2023-01-18 12:34:55 +01:00
}
function insertautocomplete(selectednote)
{
md.focus();
insert(selectednote + "]] ");
}
function togglepreview()
{
preview.innerHTML = md2html(getnotecontent());
md.hidden = !md.hidden;
preview.hidden = !preview.hidden;
if (preview.hidden)
{
resize();
md.focus();
}
}
function resetfolds()
{
folds = [];
}
function bindfile(note)
{
var changed = currentnote != note;
2023-01-18 12:34:55 +01:00
backup = note.content;
currentnote = note;
title.value = note.title;
setwindowtitle();
2023-01-18 12:34:55 +01:00
setnotecontent(note.content || "");
preview.innerHTML = md2html(getnotecontent());
resetfolds();
if (changed)
{
md.style.height = "0px";
}
2023-01-18 12:34:55 +01:00
resize();
2023-01-23 12:59:46 +01:00
setpos(note.pos || 0);
2023-01-18 12:34:55 +01:00
// to improve...
if (!issplit() && searchdialog.hidden)
2023-01-18 12:34:55 +01:00
{
md.focus();
}
}
function loadnote(name)
2023-01-18 12:34:55 +01:00
{
var note = localdata.find(n => n.title == name);
if (!note)
{
note = {title: name, content: ""};
localdata.unshift(note);
}
if (!preview.hidden)
{
togglepreview();
}
bindfile(note);
putontop();
stat.cur.q = 0;
stat.cur.t = timestamp();
2023-01-18 12:34:55 +01:00
}
function sendpassword()
{
if (!authentpage.hidden && (event.type == "blur" || event.key == "Enter"))
2023-01-18 12:34:55 +01:00
{
event.preventDefault();
window.localStorage.setItem("password", password.value);
init();
}
}
function focuseditor()
{
if (document.documentElement == event.srcElement)
{
md.focus();
console.log("Forced focus");
}
}