From c2c08db3421415886d73e306d4167d1adf2a40af Mon Sep 17 00:00:00 2001 From: Ryan Prather Date: Sun, 9 Jun 2024 20:26:54 -0400 Subject: [PATCH] Add saveFailCounter Fix bug with not clearing noteId Refactor a class removal and additions Add script.min.js --- public/js/script.js | 24 ++++++++++++++++-------- public/js/script.min.js | 1 + 2 files changed, 17 insertions(+), 8 deletions(-) create mode 100644 public/js/script.min.js diff --git a/public/js/script.js b/public/js/script.js index b6a91c8..4da4ed9 100644 --- a/public/js/script.js +++ b/public/js/script.js @@ -8,6 +8,7 @@ let saveTimeout = 15000; var to = null; let controller; var BOOKS = {}; +let saveFailCounter = 0; $(function () { setHeight(); @@ -160,6 +161,7 @@ function newNote() { document.querySelector('#template').value = 0; document.querySelector('#passage').value = ''; document.querySelector('#recording').value = ''; + document.querySelector('#noteId').value = ''; document.querySelector('#ref-list').innerHTML = ''; document.querySelector('#ref').innerHTML = ''; @@ -209,8 +211,7 @@ function saveNote(event) { }) .done(function (data) { if (data.msg == 'saved' && !saved) { - saveCheck.classList.remove('saving'); - saveCheck.classList.remove('error'); + saveCheck.classList.remove('saving', 'error', 'fa-times', 'fa-check'); showSave(); if (noteText == document.querySelector('#notes').value) { saved = true; @@ -224,17 +225,22 @@ function saveNote(event) { } }) .fail(function (xhr, status, error) { - saveCheck.classList.remove('saving'); - saveCheck.classList.add('error'); + saveFailCounter++; + saveCheck.classList.remove('saving', 'fa-check'); + saveCheck.classList.add('fa-times', 'error'); console.error(error); }) .always(function (xhr, status) { if (status == 'timeout') { - saveCheck.classList.remove('saving'); - saveCheck.classList.add('error'); + saveCheck.classList.remove('saving', 'fa-check'); + saveCheck.classList.add('error', 'fa-times'); } clearTimeout(to); - to = setTimeout(saveNote, saveTimeout); + if (saveFailCounter < 5) { + to = setTimeout(saveNote, saveTimeout); + } else { + saveFailCounter = 0; + } }); } @@ -262,7 +268,8 @@ function isUuidValid(uuid) { } function startSave() { - document.querySelector('#save-check').classList.add('saving'); + document.querySelector('#save-check').classList.remove('error', 'fa-times', 'fa-check'); + document.querySelector('#save-check').classList.add('saving', 'fa-check'); document.querySelector('#save-check').style.opacity = 1; } @@ -276,6 +283,7 @@ function showSave() { if (saved) { return; } var checkmark = document.getElementById("save-check"); + checkmark.classList.add('fa-check'); // Schedule the animation to run every 1 second (which is equivalent to a 1-second delay between each iteration) var si = setInterval(function () { diff --git a/public/js/script.min.js b/public/js/script.min.js new file mode 100644 index 0000000..b4c1e4b --- /dev/null +++ b/public/js/script.min.js @@ -0,0 +1 @@ +function setBooks(){fetch("/js/data.json").then(res=>{if(!res.ok)throw new Error("HTTP Error: Status: ${res.status}");return res.json()}).then(data=>{BOOKS=data}).catch(error=>{console.log(error)})}function setEventListeners(){document.addEventListener("keyup",function(event){"F3"==event.key&&openRef(!1)}),document.querySelector("#notes").addEventListener("keyup",function(event){let key=event.keyCode;(key>=48&&key<=90||key>=96&&key<=111||key>=186&&key<=222)&&(textDirty=!0,document.querySelector("#note-header-left h2").classList.add("dirty"))})}function setHeight(){md=new markdownit({html:!0,linkify:!0,breaks:!0}),body=document.querySelector("body"),body.style.height=window.innerHeight+"px",cont=document.querySelector("#main"),cont.style.height=window.innerHeight+"px",tabs=document.querySelector(".ref-tab"),tabs.style.height=window.innerHeight-13+"px",ref=document.querySelector(".ref"),ref.style.height=window.innerHeight-50+"px",noteList=document.querySelector("#note-list"),noteList.style.height=window.innerHeight-50+"px",notes=document.querySelector(".notes"),notes.style.height=window.innerHeight-50+"px",notePreview=document.querySelector("#notePreview"),notePreview.style.height=window.innerHeight-50+"px",$("#noteDate")&&$("#noteDate").datepicker(),$("#query")&&document.querySelector("#query").addEventListener("keyup",function(event){"Enter"==event.key&&search()}),to||(to=setTimeout(saveNote,saveTimeout))}function search(){query=document.querySelector("#query").value,fetch("/index.php/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:query})}).then(response=>response.json()).then(results=>{var oldNotes=document.querySelector("#old-notes");for(var n in oldNotes.innerHTML="",results){var link=document.createElement("a");link.href="#",link.setAttribute("onclick","retrieveNote('"+results[n].id+"');openNote();"),link.innerHTML=results[n].title;var p=document.createElement("p");p.innerHTML=results[n].passage;var article=document.createElement("article");article.appendChild(link),article.appendChild(p),oldNotes.append(article)}})}function newNote(){notes=document.querySelector("#notes"),notes.text="",notes.value="",references={},saved=!0,textDirty=!1,document.querySelector("#note-header-left h2").classList.remove("dirty"),dt=new Date,document.querySelector("#noteDate").value=dt.getFullYear()+"-"+(dt.getMonth()<9?"0"+(dt.getMonth()+1):dt.getMonth()+1)+"-"+(dt.getDate()<10?"0"+dt.getDate():dt.getDate()),document.querySelector("#noteTitle").value="",document.querySelector("#speaker").value=0,document.querySelector("#series").value=0,document.querySelector("#template").value=0,document.querySelector("#passage").value="",document.querySelector("#recording").value="",document.querySelector("#noteId").value="",document.querySelector("#ref-list").innerHTML="",document.querySelector("#ref").innerHTML="",document.querySelector(".toggle").click()}function saveNote(event){if(event&&event.preventDefault(),!textDirty||!validateNote())return clearTimeout(to),void(to=setTimeout(saveNote,saveTimeout));let saveCheck=document.querySelector("#save-check");var noteText=document.querySelector("#notes").value;startSave();var note={id:document.querySelector("#noteId").value,date:document.querySelector("#noteDate").value,title:document.querySelector("#noteTitle").value,speaker:document.querySelector("#speaker").value,series:document.querySelector("#series").value,passage:document.querySelector("#passage").value,note:document.querySelector("#notes").value,recording:document.querySelector("#recording").value,refs:references};$.ajax({url:"/index.php/save-note",method:"POST",contentType:"application/json",data:JSON.stringify(note),dataType:"json",timeout:5e3}).done(function(data){"saved"!=data.msg||saved||(saveCheck.classList.remove("saving","error","fa-times","fa-check"),showSave(),noteText==document.querySelector("#notes").value&&(saved=!0,textDirty=!1,document.querySelector("#note-header-left h2").classList.remove("dirty")),data.new&&(document.querySelector("#noteId").value=data.id))}).fail(function(xhr,status,error){saveFailCounter++,saveCheck.classList.remove("saving","fa-check"),saveCheck.classList.add("fa-times","error"),console.error(error)}).always(function(xhr,status){"timeout"==status&&(saveCheck.classList.remove("saving","fa-check"),saveCheck.classList.add("error","fa-times")),clearTimeout(to),saveFailCounter<5?to=setTimeout(saveNote,saveTimeout):saveFailCounter=0})}function validateNote(){const note=document.querySelector("#notes"),date=document.querySelector("#noteDate"),speaker=document.querySelector("#speaker"),series=document.querySelector("#series"),title=document.querySelector("#noteTitle"),psg=document.querySelector("#passage");return!!title.value.length&&(!!date.value&&(!!parseInt(speaker.value)&&(!!parseInt(series.value)&&(!!psg.value&&!!note.value.length))))}function isUuidValid(uuid){const regex=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[8|9|a|b][a-f0-9]{3}-[a-f0-9]{12}$/i;return regex.test(uuid)}function startSave(){document.querySelector("#save-check").classList.remove("error","fa-times","fa-check"),document.querySelector("#save-check").classList.add("saving","fa-check"),document.querySelector("#save-check").style.opacity=1}function showSave(){if(!saved){var checkmark=document.getElementById("save-check");checkmark.classList.add("fa-check");var si=setInterval(function(){op=parseFloat(checkmark.style.opacity),checkmark.style.opacity=op-.1,.1==checkmark.style.opacity&&(checkmark.style.opacity=0,clearInterval(si),saved=!1)},100)}}function discardNote(){document.querySelector("#noteTitle").value="",document.querySelector("#speaker").value=0,document.querySelector("#series").value=0,document.querySelector("#template").value=0,document.querySelector("#passage").value="",document.querySelector("#notes").value="",document.querySelector("#recording").value="",document.querySelector("#noteDate").value="",document.querySelector("#noteId").value="",fetch("/index.php/discard-note",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:document.querySelector("#noteId").value}).then(response=>response.json()).then(data=>{"deleted"==data.msg&&alert("Note deleted.")})}),openRef()}function newSpeaker(){"new"==document.querySelector("#speaker").value&&(document.querySelector("#newSpeaker").style.display="inline-block",document.querySelector("#speaker").style.display="none"),saved=!1,textDirty=!0}function saveSpeaker(event){13==event.keyCode&&fetch("/index.php/save-speaker",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({speakerName:document.querySelector("#newSpeaker").value})}).then(response=>response.json()).then(results=>{var newSpeaker=document.createElement("option");newSpeaker.text=document.querySelector("#newSpeaker").value,newSpeaker.value=results.id,document.querySelector("#speaker").add(newSpeaker),alert(results.msg),document.querySelector("#newSpeaker").style.display="none",document.querySelector("#speaker").style.display="inline-block",document.querySelector("#newSpeaker").value="",document.querySelector("#speaker").value=results.id})}function newSeries(){"new"==document.querySelector("#series").value&&(document.querySelector("#newSeries").style.display="inline-block",document.querySelector("#series").style.display="none"),saved=!1,textDirty=!0}function saveSeries(event){13==event.keyCode&&fetch("/index.php/save-series",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seriesName:document.querySelector("#newSeries").value})}).then(response=>response.json()).then(results=>{var newSeries=document.createElement("option");newSeries.text=document.querySelector("#newSeries").value,newSeries.value=results.id,document.querySelector("#series").add(newSeries),alert(results.msg),document.querySelector("#newSeries").style.display="none",document.querySelector("#series").style.display="inline-block",document.querySelector("#newSeries").value="",document.querySelector("#series").value=results.id})}function openRef(closeSidebar=!0){document.querySelector("#openRefBtn").classList.add("active"),refQuery=document.querySelector("#refQuery"),refQuery.style.display="block",ref=document.querySelector("#ref"),refQuery.style.left=ref.offsetLeft+"px",refQuery.style.top=ref.offsetTop+"px",closeSidebar&&document.querySelector(".toggle").click()}function closeRef(){document.querySelector("#referenceSearch").value="",document.querySelector("#referenceSearch").style.display="",document.querySelector("#referenceType").value="",document.querySelector("#referenceBook").value="",document.querySelector("#referenceBook").style.display="none",document.querySelector("#chapter-range").innerText="",document.querySelector("#verse-range").innerText="",document.querySelector("#refQuery").style.display="none",document.querySelector("#openRefBtn").classList.remove("active")}function queryRef(type=null,book=null,input=null){if(!input)var input=document.querySelector("#refQuery #referenceSearch").value;if(!type)var type=document.querySelector("#referenceType").value;if(!book)var book=document.querySelector("#referenceBook").value;fetch("/index.php/retrieve-reference",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:type,book:book,reference:input})}).then(response=>response.json()).then(results=>{const list=document.querySelector("#ref-list");var newList=document.createElement("li");newList.className="tab",button=makeButton(results.title),newList.appendChild(button),list.appendChild(newList);const ref=document.querySelector("#ref");ref.innerHTML=md.render(results.text),references[results.title]=results.text,closeRef(),saved=!1,textDirty=!0,saveNote(),findRefLinks()})}function makeButton(title){var btn=document.createElement("button");return btn.innerText=title,btn.class="button",btn.addEventListener("click",function(){removeActiveRef(),document.querySelector("#ref").innerHTML=md.render(references[title]),this.classList.add("active"),findRefLinks()}),btn.addEventListener("dblclick",function(){document.querySelector("#ref").innerHTML="",delete references[title];var list=this.parentElement;list.remove(),saved=!1,textDirty=!0,saveNote()}),removeActiveRef(),btn.classList.add("active"),btn}function removeActiveRef(){for(var t in tabs=document.querySelectorAll(".active"),tabs)isFinite(parseInt(t))&&tabs[t].classList.remove("active")}function retrieveTemplate(orig,dest){const temp=document.querySelector("#"+orig);"0"!=temp.value?fetch("/index.php/retrieve-template",{method:"POST",headers:{"Content-Type":"plain/text"},body:JSON.stringify({template:temp.value})}).then(response=>response.text()).then(results=>{const div=document.querySelector("#"+dest);div.value=results}):document.querySelector("#"+dest).value=""}function saveTemplate(){fetch("/index.php/save-template",{method:"POST",headers:{"Content-Type":"plain/text"},body:JSON.stringify({template_id:document.querySelector("#template_id").value,template_name:document.querySelector("#template_name").value,template_value:document.querySelector("#template_value").value})}).then(response=>response.text()).then(results=>{alert(results)})}function toggleFields(){const fieldsContainer=document.getElementById("fields-container"),showHideBtn=document.getElementById("show-hide-btn");fieldsContainer.classList.contains("show")?(fieldsContainer.classList.remove("show"),fieldsContainer.style.display="none",showHideBtn.classList.remove("active")):(fieldsContainer.classList.add("show"),fieldsContainer.style.display="block",showHideBtn.classList.add("active")),setHeight()}function retrieveBooks(){document.querySelector("#chapter-range").innerText="",document.querySelector("#verse-range").innerText="",document.querySelector("#referenceSearch").value="",document.querySelector("#referenceSearch").style.display="none";const selectedType=document.querySelector("#referenceType").value;if(selectedType){var bookList=document.querySelector("#referenceBook");if(bookList.style.display="block",bookList.innerHTML="","bible"==selectedType){document.querySelector("#referenceSearch").style.display="block";var none=document.createElement("option");for(var x in none.value="",none.text="-- Select --",bookList.appendChild(none),BOOKS.bible){var newBook=document.createElement("option");newBook.text=x,bookList.appendChild(newBook)}}else if("creed"==selectedType){var none=document.createElement("option");for(var x in none.value="",none.text="-- Select --",bookList.appendChild(none),BOOKS.creed){var newBook=document.createElement("option");newBook.value=x,newBook.text=BOOKS.creed[x],bookList.appendChild(newBook)}}else if("cd"==selectedType){var none=document.createElement("option");for(var x in none.value="",none.text="-- Select --",bookList.appendChild(none),BOOKS.cd){var newBook=document.createElement("option");newBook.text=BOOKS.cd[x],bookList.appendChild(newBook)}}else if("note"==selectedType){var none=document.createElement("option");none.value="",none.text="-- Select --",bookList.appendChild(none),fetch("/index.php/retrieve-reference",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"note"})}).then(response=>response.json()).then(results=>{for(var x in results){var newBook=document.createElement("option");newBook.value=results[x].id,newBook.text=results[x].title,bookList.appendChild(newBook)}})}else{var min=BOOKS[selectedType][0],max=BOOKS[selectedType][1],none=document.createElement("option");none.value="",none.text="-- Select --",bookList.appendChild(none);for(var x=min;x<=max;x++){var newBook=document.createElement("option");newBook.value=x,newBook.text=x,bookList.appendChild(newBook)}}}}function filterBooks(){if(document.querySelector("#chapter-range").innerText="",document.querySelector("#verse-range").innerText="","bible"==document.querySelector("#referenceType").value){var bookList=document.querySelector("#referenceBook"),book=BOOKS.bible[bookList.value],max=Object.keys(book).length,chapterRange=document.querySelector("#chapter-range");chapterRange.innerText="Chapters: "+max}}function filterVerse(){if("bible"==document.querySelector("#referenceType").value){var bookList=document.querySelector("#referenceBook").value,search=document.querySelector("#referenceSearch").value,chapter=search.split(":")[0],verseRange=document.querySelector("#verse-range");if(BOOKS.bible[bookList]&&BOOKS.bible[bookList][chapter]){var verse=BOOKS.bible[bookList][chapter];verseRange.innerText="Verse: "+verse}else verseRange.innerText="Unknown Chapter"}}function retrieveReferenceType(el){fetch("/index.php/reference/"+el.value,{method:"GET",header:{"Content-Type":"application/json"}}).then(response=>response.json()).then(results=>{document.querySelector("#referenceSeries").innerHTML="";var none=document.createElement("option");for(var x in none.value="",none.text="-- Select --",document.querySelector("#referenceSeries").appendChild(none),results){var newSeries=document.createElement("option");newSeries.value=results[x].id,newSeries.text=results[x].label,document.querySelector("#referenceSeries").appendChild(newSeries)}})}function retrieveReference(el){"new"!=el.value?fetch("/index.php/get-reference",{method:"POST",header:{"Content-Type":"application/json"},body:JSON.stringify({id:el.value})}).then(response=>response.json()).then(results=>{document.querySelector("#reference").value=results.text}):document.querySelector("#refName").style.display="inline-block"}function saveReference(){var select=document.querySelector("#references");fetch("/index.php/save-reference",{method:"POST",header:{"Content-Type":"application/json"},body:JSON.stringify({type:select.options[select.selectedIndex].getAttribute("type"),file:select.value,text:document.querySelector("#reference").value})}).then(response=>response.json()).then(results=>{alert(results.msg),document.querySelector("#reference").value="",document.querySelector("#references").value=""})}function previewNote(){var noteText=document.querySelector("#notes"),notePreview=document.querySelector("#notePreview"),previewButton=document.querySelector("#previewBtn");const title=document.querySelector("#noteTitle"),speaker=document.querySelector("#speaker"),passage=document.querySelector("#passage"),markdownPreview="# "+title.value+" - "+speaker.options[speaker.selectedIndex].text+" - "+passage.value+"\n\n"+noteText.value;notePreview.innerHTML=md.render(markdownPreview),previewButton.classList.contains("active")?(noteText.style.display="block",notePreview.style.display="none",previewButton.classList.remove("active")):(noteText.style.display="none",notePreview.style.display="block",previewButton.classList.add("active")),findLinks()}function findLinks(){for(var links=document.querySelector("#notePreview").querySelectorAll("a"),i=0;iresponse.text()).then(result=>{passage=passage.replace(/\+/g," "),psg=passage.split(" "),psg.length>2?(book=psg[0]+" "+psg[1],cv=psg[2]):(book=psg[0],cv=psg[1]),showPassage(e,"  
"+result)})}})}function findRefLinks(){for(var links=document.querySelector("#ref").querySelectorAll("a"),i=0;iresponse.text()).then(result=>{passage=passage.replace(/\+/g," "),psg=passage.split(" "),psg.length>2?(book=psg[0]+" "+psg[1],cv=psg[2]):(book=psg[0],cv=psg[1]),showPassage(e,"  
"+result)})}})}function showPassage(event,text){const popup=document.querySelector("#passage-popup");popup.innerHTML=md.render(text);let x=event.clientX+window.scrollX,y=event.clientY+window.scrollY;popup.style.top=`${y}px`,popup.style.left=`${x}px`,popup.style.display="block"}function closePopup(){const popup=document.querySelector("#passage-popup");popup.innerHTML="",popup.style.display="none"}function openNote(openSidebar=!0){const noteList=document.querySelector("#note-list"),refs=document.querySelector("#ref");"block"==noteList.style.display?(noteList.style.display="none",refs.style.display="block"):(noteList.style.display="block",refs.style.display="none"),openSidebar&&document.querySelector(".toggle").click()}function retrieveNote(id,runOpen=!0){fetch("/index.php/get-note",{method:"POST",header:{"Content-Type":"application/json"},body:JSON.stringify({id:id})}).then(response=>response.json()).then(result=>{var dt=new Date(result.date.date);document.querySelector("#notes").value=result.text,document.querySelector("#passage").value=result.passage,document.querySelector("#series").value=result.series.id,document.querySelector("#speaker").value=result.speaker.id,document.querySelector("#noteTitle").value=result.title,document.querySelector("#noteDate").value="",document.querySelector("#noteDate").value=(dt.getMonth()<9?"0"+(dt.getMonth()+1):dt.getMonth()+1)+"/"+(dt.getDate()<10?"0"+dt.getDate():dt.getDate())+"/"+dt.getFullYear(),document.querySelector("#noteId").value=result.id,result.refs&&(references=result.refs);const list=document.querySelector("#ref-list");list.innerHTML="";var newList=null;for(var x in references){var newList=document.createElement("li");newList.className="tab";var button=makeButton(x);newList.appendChild(button),list.appendChild(newList)}runOpen&&openNote(!1)})}function increaseFont(){var currentSize=document.querySelector("#ref").style.fontSize;document.querySelector("#ref").style.fontSize=parseInt(currentSize)+1+"pt"}function decreaseFont(){var currentSize=document.querySelector("#ref").style.fontSize;document.querySelector("#ref").style.fontSize=parseInt(currentSize)-1+"pt"}function uuidv4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){const r=16*Math.random()|0,v="x"==c?r:3&r|8;return v.toString(16)})}var md=null,references={},tabs=[];let saved=!1,textDirty=!1,saveTimeout=15e3;var to=null;let controller;var BOOKS={};let saveFailCounter=0;$(function(){setHeight(),setBooks(),setEventListeners(),$("#note-table").DataTable({paging:!1,ajax:{url:"/index.php/get-notes",type:"POST"},columns:[{data:"link"},{data:"speaker.name"},{data:"passage"},{data:"date.date",render:DataTable.render.date("L")}]})}); \ No newline at end of file