fictioneer/js/bookmarks.min.js
2024-12-06 17:38:32 +01:00

1 line
5.8 KiB
JavaScript

application.register("fictioneer-bookmarks",class extends Stimulus.Controller{static get targets(){return["bookmarkScroll","shortcodeBlock","dataCard","overviewPageIconLink","noBookmarksNote"]}timeout=0;chapterId=_$(".chapter__article")?.id;currentBookmark=null;cardTemplate=_$(".bookmark-small-card-template");initialize(){fcn()?.userReady||!FcnUtils.loggedIn()?this.#e=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#e=!0,this.refreshView(),this.#t()}))}connect(){window.FictioneerApp.Controllers.fictioneerBookmarks=this,this.#e&&(this.refreshView(),this.#t())}data(){return this.bookmarksCachedData=FcnUtils.loggedIn()?this.#r():this.#a(),this.#o(this.bookmarksCachedData).data}toggle(e,t="none"){if(!this.chapterId)return;const r=this.data(),a=r[this.chapterId];if(a&&a["paragraph-id"]==e)"none"!==t&&t!==a.color?r[this.chapterId].color=t:delete r[this.chapterId];else{Object.keys(r).length>=50&&delete r[Object.keys(r)[0]];const a=_$(`[data-paragraph-id="${e}"]`),o=_$$$("chapter-bookmark-data").dataset;r[this.chapterId]={"paragraph-id":e,progress:100*(FcnUtils.offset(a).top-FcnUtils.offset(a.parentElement).top)/a.parentElement.clientHeight,date:(new Date).toISOString(),color:t,chapter:o.title.trim(),link:o.link,thumb:o.thumb,image:o.image,story:o.storyTitle.trim(),content:FcnUtils.extractTextNodes(a).substring(0,128)+"…"}}this.set(r),this.refreshView()}remove({params:{id:e}}){const t=this.data();delete t[e],this.set(t),this.refreshView()}clear(){this.set({data:{}}),this.refreshView()}set(e){if("object"!=typeof e)return;e=this.#o({data:e});const t=JSON.stringify(e);if(FcnUtils.loggedIn()){const e=fcn().userData();e&&(e.bookmarks=t,fcn().setUserData(e)),this.#s(t),localStorage.removeItem("fcnChapterBookmarks")}else localStorage.setItem("fcnChapterBookmarks",t)}refreshView(){const e=this.data(),t=Object.keys(e).length;this.hasOverviewPageIconLinkTarget&&this.overviewPageIconLinkTargets.forEach((e=>{e.classList.toggle("hidden",t<1)})),this.refreshChapterBookmark(),this.refreshCards(),this.refreshProfile()}refreshCards(){if(!this.hasShortcodeBlockTarget)return;const e=this.data(),t=Object.keys(e).length<1;this.shortcodeBlockTargets.forEach((e=>{e.classList.toggle("hidden",t)})),_$$(".show-if-bookmarks").forEach((e=>{e.classList.toggle("hidden",t)})),this.hasNoBookmarksNoteTarget&&this.noBookmarksNoteTargets.forEach((e=>{e.classList.toggle("hidden",!t)})),!t&&this.cardTemplate?this.shortcodeBlockTargets.forEach((t=>{const r=t.querySelector("ul"),a=document.createDocumentFragment(),o=Object.entries(e).sort(((e,t)=>new Date(t[1].date)-new Date(e[1].date)));let s=parseInt(t.dataset.count)??8;o.forEach((([e,{color:t,progress:r,link:o,chapter:i,"paragraph-id":c,date:n,image:h,thumb:d,content:l}])=>{if(0==s--)return;const k=this.cardTemplate.content.cloneNode(!0),m=new Date(n).toLocaleDateString(navigator.language??"en-US",{year:"2-digit",month:"short",day:"numeric"});h&&k.querySelector(".bookmark-card__image")?(k.querySelector(".bookmark-card__image").href=h,k.querySelector(".bookmark-card__image img").src=d):k.querySelector(".bookmark-card__image")?.remove(),k.querySelector(".bookmark-card__excerpt").innerHTML+=l,k.querySelector(".bookmark-card").classList.add(`bookmark-${e}`),k.querySelector(".bookmark-card").dataset.color=t,k.querySelector(".bookmark-card__title > a").href=`${o}#paragraph-${c}`,k.querySelector(".bookmark-card__title > a").innerText=i,k.querySelector(".bookmark-card__percentage").innerText=`${r.toFixed(1)} %`,k.querySelector(".bookmark-card__progress").style.width=`calc(${r.toFixed(1)}% - var(--bookmark-progress-offset, 0px))`,k.querySelector("time").innerText=m,k.querySelector(".button-delete-bookmark").setAttribute("data-fictioneer-bookmarks-id-param",e),a.appendChild(k)})),r.innerHTML="",r.appendChild(a)})):this.shortcodeBlockTargets.forEach((e=>{e.querySelector("ul").innerHTML=""}))}refreshProfile(){this.hasDataCardTarget&&(this.dataCardTarget.innerHTML=this.dataCardTarget.innerHTML.replace("%s",Object.keys(this.data()).length))}refreshChapterBookmark(){const e=this.data();if(this.currentBookmark?.classList.remove("current-bookmark"),!this.chapterId||!e[this.chapterId])return;const t=e[this.chapterId]["paragraph-id"],r=_$(`[data-paragraph-id="${t}"]`),a=e[this.chapterId].color??"none";t&&r&&(r.classList.add("current-bookmark"),r.setAttribute("data-bookmark-color",a),this.currentBookmark=r,this.hasBookmarkScrollTarget&&this.bookmarkScrollTargets.forEach((e=>e.removeAttribute("hidden"))))}#e=!1;#i=!1;#a(){return FcnUtils.parseJSON(localStorage.getItem("fcnChapterBookmarks"))??{data:{}}}#r(){return FcnUtils.parseJSON(FcnUtils.userData()?.bookmarks)??{data:{}}}#o(e){if("object"!=typeof e||!("data"in e)||Array.isArray(e.data)&&0===e.data.length)return{data:{}};const t={};for(const r in e.data)if(r.startsWith("ch-")){const a=this.#c(e.data[r]);a&&(t[r]=a)}return{data:t}}#c(e){const t={},r={"paragraph-id":"",progress:0,date:"",color:"",chapter:"",link:"",thumb:"",image:"",story:"",content:""};for(const a in r){if(typeof e[a]!=typeof r[a])return null;t[a]=e[a]}const a=new Date(t.date);return a&&"[object Date]"===Object.prototype.toString.call(a)&&!isNaN(a)||(t.date=(new Date).toISOString()),("number"!=typeof t.progress||t.progress<0)&&(t.progress=0),t}#n(){return JSON.stringify(this.bookmarksCachedData??0)!==JSON.stringify(this.data())}#h(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#i&&this.#n()&&this.refreshView()}),3e4+1e3*Math.random()))}#t(){this.#h(),this.visibilityStateCheck=()=>{"visible"===document.visibilityState?(this.#i=!1,this.refreshView(),this.#h()):(this.#i=!0,clearInterval(this.refreshInterval),this.refreshInterval=null)},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#s(e){clearTimeout(this.timeout),this.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_save_bookmarks",{payload:{bookmarks:e}})}),FcnGlobals.debounceRate)}});