var defaultsettings = { savedelay: 5000, bgcolor: "white", fontfamily: "'Inconsolata', 'Consolas', monospace", fontsize: "90%", fontcolor: "black", lineheight: "130%", foldmarkstart: 22232, defaultpreviewinsplit: false, enablefolding: false, tagautocomplete: false, light: false }; //builtin var markerslist = ["* ", "- ", " * ", " - ", ">> ", "> ", "=> ", "— "]; var sectionmarks = ["---", "### ", "## ", "# ", "```"]; var codelanguages = ["xml", "js", "sql"]; // globals var currentnote = null; var fileindex = 0; var workerid = null; var folds = []; var backup = ""; var localdata = null; var saved = true; var settings = null; var tags = null; var currentvault = ""; var currenttag = ""; var commands = [ { hint: "Close menu" }, { shortcut: "ctrl+p", hint: "Show notes list", savedonly: true, action: searchandloadnote }, { hint: "Share note", savedonly: true, action: share }/*, { hint: "Share note (html)", savedonly: true, action: sharehtml }*/, { shortcut: "ctrl+n", hint: "New note", savedonly: true, action: startnewnote }, { shortcut: "ctrl+shift+P", hint: "Command palette", savedonly: false, action: commandpalette, excludepalette: true }, { shortcut: "ctrl+t", hint: "Open todo", savedonly: true, action: loadtodo }, { shortcut: "ctrl+q", hint: "Open quick note", savedonly: true, action: loadquicknote }, { shortcut: "ctrl+g", hint: "Find in notes", savedonly: true, action: showgrep }, { shortcut: "ctrl+i", hint: "Toggle title", savedonly: true, action: toggletitle }, { shortcut: "ctrl+m", hint: "Toggle preview", savedonly: true, action: togglepreview }, { shortcut: "ctrl+d", hint: "Delete note", savedonly: true, action: deletenote }, { hint: "Restore note", savedonly: true, action: restore }, { shortcut: "ctrl+h", hint: "Insert markdown header", action: insertheader }, { savedonly: true, shortcut: "F1", hint: "Show help", action: showhelp }, { savedonly: true, shortcut: "ctrl+shift+C", hint: "Fold", action: fold }, { savedonly: true, shortcut: "ctrl+shift+O", hint: "Unfold", action: unfold }, { savedonly: true, hint: "Unfold all", action: unfoldall }, { savedonly: true, hint: "Download note", action: downloadnote }, { savedonly: true, hint: "Download local data", action: downloadlocal, shortcut: "ctrl+shift+S" }/*, { savedonly: true, hint: "Download all notes", action: downloadnotes }*/, { hint: "Force save", action: save, shortcut: "ctrl+s" }, { hint: "Search tags", action: searchtags, savedonly: true, shortcut: "ctrl+shift+T" }, { hint: "Log out", action: logout, savedonly: true }, { hint: "Toggle split view", savedonly: true, action: togglesplit }, { hint: "Load previous note", savedonly: true, action: loadprevious, shortcut: "ctrl+b" }, { hint: "Sort text", savedonly: true, action: sortselection }, { hint: "Word count", action: wordcount, shortcut: "ctrl+w" }, { hint: "Settings", savedonly: true, action: editsettings }, { hint: "Restore default settings", savedonly: true, action: restoresettings }, { hint: "Note outline", savedonly: true, action: showoutline, shortcut: "ctrl+o" }, { hint: "Internal links", savedonly: true, action: showinternallinks }, { hint: "Switch vault", savedonly: true, action: switchvault, shortcut: "ctrl+shift+V" }, { hint: "Add tag filter", action: addtagfilter, shortcut: "ctrl+shift+F", savedonly: true }]; 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 }]; function addtagfilter() { var command = commands.find(c => c.action == addtagfilter); if (!currenttag) { tagslist() .then(t => { currenttag = t; command.hint = "Remove tag filter '" + currenttag + "'"; setwindowtitle(); }); } else { currenttag = ""; command.hint = "Add tag filter"; setwindowtitle(); } } function switchvault() { var other = othervault(); if (confirm("Switch to " + other + "?")) { clearInterval(workerid); window.localStorage.setItem("vault", other); init(); } } function showinternallinks() { searchinlist( getnotecontent() .match(/\[\[([^\]]*)\]\]/g || []) .map(l => l.replace("[[", "").replace("]]", ""))) .then(loadnote); } function showoutline() { var outline = {}; var pos = 0; getnotecontent().split("\n").forEach(line => { pos += line.length + 1; if (line.startsWith("#")) { line = line .replace("# ", "") .replace(/#/g, "\xa0\xa0\xa0\xa0"); outline[line] = pos; } }); searchinlist(Object.keys(outline)) .then(line => { md.setSelectionRange(outline[line], outline[line]); md.focus(); }); } function linkatpos() { var s = md.selectionStart; while (s > 2 && md.value[s] != "\n") { if (md.value.substring(s - 2, s) == "[[") { var e = md.selectionStart; while (e < md.value.length - 2 && md.value[e-2] != "\n") { if (md.value.substring(e, e + 2) == "]]") { return md.value.substring(s, e); } e++; } } s--; } return ""; } function tagatpos() { if (md.value.substring(0, getpos()).split("\n").pop().startsWith("tags: ")) { var s = md.selectionStart; while (s > 1 && md.value[s] != "\n") { var c = md.value[s-1]; if (c == " " || c == ",") { var e = md.selectionStart; while (e < md.value.length - 1 && md.value[e-1] != "\n") { c = md.value[e]; if (c == " " || c == "," || c == "\n") { return md.value.substring(s, e); } e++; } } s--; } return ""; } } function clickeditor() { if (event.ctrlKey) { var link = linkatpos(); var tag = tagatpos(); if (link) { loadnote(link); } else if (tag) { tagslist(); searchinlist(tags[tag]) .then(loadnote); } else { checkfolding(); } } } function restoresettings() { if (confirm("Restore default settings?")) { window.localStorage.setItem("settings", JSON.stringify(defaultsettings)); loadsettings(); } } function editsettings() { bindfile( { title: "settings.json", content: JSON.stringify(settings, null, " ") }); } function showtemporaryinfo(str) { alert(str); } function wordcount() { showtemporaryinfo(getnotecontent().split(/\s+\b/).length + " words"); } 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"; } function logout() { if (isremote()) { window.localStorage.removeItem("password"); togglepassword(); } } function tagslist() { tags = {}; localdata .filter(n => !n.title.startsWith(".")) .forEach(n => { var ts = gettags(n); ts.forEach(t => { tags[t] = tags[t] || []; tags[t].push(n.title); }); }); return searchinlist(Object.keys(tags).sort()); } function searchtags() { tagslist() .then(tag => searchinlist(tags[tag])) .then(loadnote); } 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 marksaved() { saved = true; mark.textContent = "\xa0"; } function markunsaved(text) { saved = false; if (text) { mark.textContent = text; } } function share(html) { if (navigator.share) { navigator.share( { text: html ? md2html(getnotecontent()) : getnotecontent(), title: currentnote.title }); } } function sharehtml() { share(true); } 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 .filter(note => !note.title.startsWith(".")) .forEach(note => { download(note.title + ".md", note.content); }); } function downloadlocal() { download(timestamp() + " " + currentvault + " notes.json", JSON.stringify(localdata)); } function downloadnote() { download(currentnote.title + ".md", getnotecontent()); } function save() { var content = getnotecontent(); if ((content == "" && backup != "") || content == "null" || content == "undefined") { console.warn("Invalid content '" + content + "', file '" + currentnote.title + "' not saved"); } else { currentnote.content = content; window.localStorage.setItem(currentvault, JSON.stringify(localdata)); if (currentnote.title == "settings.json") { window.localStorage.setItem("settings", content); } console.log("data serialized in local storage") if (isremote()) { pushtoremote(); } else { marksaved(); } } } function remotecallfailed(error) { markunsaved("!"); if (error) { console.warn(error); showtemporaryinfo(error); } } function loadstorage() { currentvault = window.localStorage.getItem("vault"); var item = window.localStorage.getItem(currentvault); localdata = item ? JSON.parse(item) : []; if (currentnote) { currentnote = localdata.find(n => n.title == currentnote.title); } if (currentnote) { bindfile(currentnote); } else { loadlast(); } } function loadsettings() { settings = {...defaultsettings}; var item = window.localStorage.getItem("settings"); if (item) { item = JSON.parse(item); for (var key in settings) { if (item[key]) { settings[key] = item[key]; } } } 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; if (!settings.enablefolding) { commands = commands.filter(c => !c.hint.toLowerCase().includes("fold")); } } function checksaved() { if (!saved) { return "not saved"; } } function initsnippets() { // code languages codelanguages.forEach(lang => { if (!snippets.find(s => s.command == "/" + lang)) { 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 othervault() { return isremote() ? "local" : "remote"; } function initvault() { currentvault = window.localStorage.getItem("vault") || "local"; } function startworker() { workerid = setInterval(function() { if (!saved) { save(); } }, settings.savedelay); } function init() { loadsettings(); initvault(); commands.find(c => c.action == switchvault).hint = "Switch to " + othervault() + " vault"; window.onbeforeunload = checksaved; window.onclick = focuseditor; initsnippets(); if (isremote()) { queryremote({action: "fetch"}) .then(data => { localdata = data; loadlast(); startworker(); }) .catch(remotecallfailed); } else { loadstorage(); startworker(); } if (issplit()) { window.onstorage = loadstorage; if (settings.defaultpreviewinsplit && name == "right") { togglepreview(); } else if (name == "left") { md.focus(); } } } function togglepassword() { clearInterval(workerid); password.value = ""; authentpage.hidden = false; notepage.style.display = "none"; document.title = "notes"; password.focus(); } function pushtoremote() { console.log("sending data to php server"); markunsaved("⇅"); if (localdata) { var content = getnotecontent(); queryremote({action: "push", data: JSON.stringify(localdata)}) .then(() => { console.log("data saved on server"); if (getnotecontent() == content) { marksaved(); } else { console.warn("Content changed in the meantime, keep as unsaved"); markunsaved("*"); } }) .catch(remotecallfailed); } else { console.warn("Cannot push empty data"); } } function queryremote(params) { return new Promise( (apply, failed) => { 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(); 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); } } } 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); notecontentchanged(); } 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() { if (!settings.enablefolding) { console.log("folding is disabled."); return; } 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); fold(); } } else if (isfold(line)) { event.preventDefault(); 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, "$1") .replace(/\*([^\*]*)\*/g, "$1") .replace(/\## (.*)/g, "