diff --git a/js/application.min.js b/js/application.min.js index 7693117d..91f03269 100644 --- a/js/application.min.js +++ b/js/application.min.js @@ -1,2 +1,2 @@ -const FcnGlobals={eSite:_$$$("site"),urlParams:Object.fromEntries(new URLSearchParams(window.location.search).entries()),pageLoadTimestamp:Date.now(),ajaxLimitThreshold:Date.now()-parseInt(fictioneer_ajax.ttl),ajaxURL:fictioneer_ajax.ajax_url,restURL:fictioneer_ajax.rest_url,ffcnrURL:fictioneer_ajax.ffcnr_url,ffcnrAuth:fictioneer_ajax.ffcnr_auth,debounceRate:fictioneer_ajax.post_debounce_rate,fonts:fictioneer_fonts??[],fontColors:fictioneer_font_colors??[],commentFormSelector:fictioneer_comments?.selector??"#comment",commentStack:[]};function fcn(){const e=window.FictioneerApp?.Controllers?.fictioneer;return e||{userData:FcnUtils.userData,setUserData:FcnUtils.setUserData,resetUserData:FcnUtils.resetUserData,removeUserData:FcnUtils.removeUserData}}function fcn_getUserData(){return FcnUtils.userData()}function fcn_setUserData(e){return FcnUtils.setUserData(e)}function fcn_cleanUpWebStorage(){["fcnBookshelfContent"].forEach((e=>localStorage.removeItem(e))),fcn().resetUserData()}function fcn_cleanUpGuestView(){document.body.classList.remove("logged-in","is-admin","is-moderator","is-editor","is-author"),_$$$("fictioneer-ajax-nonce")?.remove(),_$$(".only-moderators, .only-admins, .only-authors, .only-editors, .only-logged-in").forEach((e=>{e.remove()}))}function fcn_setLoggedInState(){const e=fcn().userData(),t=!0===e.loggedIn;document.body.classList.toggle("logged-in",t),document.body.classList.toggle("is-admin",e.isAdmin),document.body.classList.toggle("is-moderator",e.isModerator),document.body.classList.toggle("is-author",e.isAuthor),document.body.classList.toggle("is-editor",e.isEditor);const n=[];t&&(n.push('[data-fictioneer-id-param="login-modal"]'),n.push("#login-modal")),e.isAdmin||(n.push(".only-admins"),e.isModerator||n.push(".only-moderators"),e.isAuthor||n.push(".only-authors"),e.isEditor||n.push(".only-editors")),_$$(n.join(", ")).forEach((e=>e.remove()))}function fcn_setAvatar(){const e=fcn().userData()?.avatarUrl;e&&_$$('[data-fictioneer-target="avatarWrapper"]').forEach((t=>{const n=document.createElement("img");n.classList.add("user-profile-image"),n.src=e,t.firstChild.remove(),t.appendChild(n)}))}Object.freeze(FcnGlobals),window.FictioneerApp=window.FictioneerApp||{},window.FictioneerApp.Controllers=window.FictioneerApp.Controllers||{},application.register("fictioneer",class extends Stimulus.Controller{static get targets(){return["avatarWrapper","modal","mobileMenuToggle"]}static values={fingerprint:String,ageConfirmation:{type:Boolean,default:!1},ajaxAuth:{type:Boolean,default:!1},ajaxSubmit:{type:Boolean,default:!1},cachingActive:{type:Boolean,default:!1},publicCaching:{type:Boolean,default:!1},forceChildTheme:{type:Boolean,default:!1},editTime:{type:Number,default:15}};userReady=!1;lastModalToggle=null;currentModal=null;initialize(){if(FcnUtils.loggedIn()||this.ajaxAuthValue)this.fetchUserData();else{fcn_cleanUpWebStorage();const e=new CustomEvent("fcnUserDataReady",{detail:{data:this.userData(),time:new Date,loggedOut:!0},bubbles:!0,cancelable:!1});document.dispatchEvent(e)}}connect(){window.FictioneerApp.Controllers.fictioneer=this}userData(){return FcnUtils.userData()}setUserData(e){FcnUtils.setUserData(e)}resetUserData(){FcnUtils.resetUserData()}removeUserData(){FcnUtils.removeUserData()}fetchUserData(){let e=this.userData();if(FcnUtils.loggedIn()&&!1===e.loggedIn&&(this.removeUserData(),e=this.userData()),FcnGlobals.ajaxLimitThreshold{if(t.success){let n=this.userData();n=t.data,n.lastLoaded=Date.now(),this.setUserData(n),fcn_setAvatar(),e.nonceHtml&&this.#e(e.nonceHtml);const s=new CustomEvent("fcnUserDataReady",{detail:{data:t.data,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(s)}else{const e=this.userData();e.lastLoaded=Date.now(),e.loggedIn=!1,this.setUserData(e);const n=new CustomEvent("fcnUserDataFailed",{detail:{data:t,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(n)}this.userReady=!0})).catch((e=>{localStorage.removeItem("fcnUserData");const t=new CustomEvent("fcnUserDataError",{detail:{error:e,time:new Date},bubbles:!0,cancelable:!1});document.dispatchEvent(t)}))}copyInput(e){e.currentTarget.select(),FcnUtils.copyToClipboard(e.currentTarget.value,e.currentTarget.dataset.message)}clearConsent(e){FcnUtils.toggleInProgress(e.currentTarget),FcnUtils.deleteCookie("fcn_cookie_consent"),location.reload()}clearCookies(e){const t=e.currentTarget;if(!FcnUtils.loggedIn())return fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),void alert(t.dataset.message);FcnUtils.toggleInProgress(t),FcnUtils.aGet({action:"fictioneer_ajax_clear_cookies",nonce:FcnUtils.nonce()}).then((e=>{e.success?(fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),alert(e.data.success)):e.data.error&&(alert(e.data.failure),console.error("Error:",e.data.error))})).catch((e=>{alert(e),console.error(e)})).then((()=>{FcnUtils.toggleInProgress(t)}))}logout(){fcn_cleanUpWebStorage()}toggleObfuscation(e){e.target.closest('[data-fictioneer-target="obfuscated"]').classList.toggle("_obfuscated")}bodyClick(e){let t;this.dispatch("bodyClick",{detail:{event:e,target:e.target}}),(t=e.target.closest(".page-numbers.dots:not(button)"))?this.#t(t):(t=e.target.closest(".spoiler"))&&t.classList.toggle("_open")}toggleChapterGroup(e){const t=e.currentTarget.closest(".chapter-group"),n=t.querySelector(".chapter-group__list"),s=!t.classList.contains("_closed");n.addEventListener("transitionend",(()=>{n.style.height="",n.querySelectorAll("a, button, label, input:not([hidden])").forEach((e=>{e.tabIndex=n.parentElement.classList.contains("_closed")?"-1":"0"})),_$(".main__background")?.classList.remove("will-change")}),{once:!0}),_$(".main__background")?.classList.add("will-change"),n.style.height=`${n.scrollHeight}px`,requestAnimationFrame((()=>{requestAnimationFrame((()=>{t.classList.toggle("_closed",s),n.style.height=s?"0":`${n.scrollHeight}px`}))}))}toggleModal(e){e.preventDefault(),this.toggleModalVisibility(e.currentTarget,e.params.id)}toggleModalVisibility(e,t){const n=_$$$(t);if(n)if(this.currentModal!==n&&this.closeModals(),this.lastModalToggle=e,n.hidden=!n.hidden,n.hidden)this.closeModals();else{const e=n.querySelector(".close");e?.focus(),e?.blur()}}closeModals(){this.hasModalTarget&&this.modalTargets.forEach((e=>{e.hidden=!0})),this.lastModalToggle&&(this.lastModalToggle?.focus(),this.lastModalToggle?.blur(),this.lastModalToggle.null)}backgroundCloseModals({target:e}){e.classList.contains("modal")&&this.closeModals()}toggleMobileMenu(e){e.preventDefault();const t=window.FictioneerApp.Controllers.fictioneerMobileMenu;t&&t.toggle()}#e(e){_$$$("fictioneer-ajax-nonce")?.remove(),document.body.appendChild(FcnUtils.html`${e}`)}#t(e){if(document.documentElement.dataset.disablePageJump)return;const t=parseInt(window.prompt(fictioneer_tl.notification.enterPageNumber));if(t>0){const n=e.nextElementSibling.getAttribute("href"),s=["page=","paged=","comment-page-","pg="];for(const e of s)if(n.includes(e))return void(window.location.href=n.replace(new RegExp(`${e}\\d+`),e+t));window.location.href=n.replace(/page\/\d+/,`page/${t}`)}}}),"function"==typeof fcn_removeQueryArgs&&fcn_removeQueryArgs(),document.addEventListener("fcnUserDataReady",(()=>{fcn().userData().loggedIn||(fcn_cleanUpWebStorage(),fcn_cleanUpGuestView())})),_$("#wp-admin-bar-logout a")?.addEventListener("click",(()=>{fcn_cleanUpWebStorage()})),_$$(".subscriber-login, .oauth-login-link, [data-prepare-login]").forEach((e=>{e.addEventListener("click",(()=>{fcn().removeUserData()}))})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setLoggedInState()})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setAvatar()}));var fcn_animFrameEvents=new Map;function fcn_bindEventToAnimationFrame(e,t,n=window){n.addEventListener(e,(function(){fcn_animFrameEvents.get(t)||(fcn_animFrameEvents.set(t,!0),requestAnimationFrame((()=>{n.dispatchEvent(new CustomEvent(t)),fcn_animFrameEvents.set(t,!1)})))}))}function fcn_loadEmbed(e){e.target.parentNode.querySelectorAll("iframe, script")[0].src=e.target.dataset.src,e.target.parentElement.querySelector(".embed-logo")?.remove(),e.target.remove()}function fcn_appendTermMenu(e,t){const n=_$$$(`term-submenu-${e}`);if(!n)return;const s=n.content.cloneNode(!0);t.classList.add("menu-item-has-children"),t.querySelector('[href="#"]').addEventListener("click",(e=>{e.preventDefault()})),t.appendChild(s)}fcn_bindEventToAnimationFrame("scroll","scroll.rAF"),fcn_bindEventToAnimationFrame("resize","resize.rAF"),document.body.addEventListener("change",(e=>{const t=e.target.closest('[type="checkbox"]');if(!t)return;const n=t.name,s=n?_$$(`label[for="${n}"]`):[],i=t.checked;t.closest("[aria-checked]")?.setAttribute("aria-checked",i),s.forEach((e=>{e.closest("[aria-checked]")?.setAttribute("aria-checked",i)}))})),_$$(".iframe-consent, .twitter-consent").forEach((e=>{e.onclick=e=>{fcn_loadEmbed(e)}})),document.addEventListener("DOMContentLoaded",(()=>{const e=_$("#menu-navigation > .menu-item"),t=_$$$("full-navigation");e&&t&&e.offsetHeight{fcn_appendTermMenu("category",e)})),_$$(".main-navigation .trigger-term-menu-tags").forEach((e=>{fcn_appendTermMenu("post_tag",e)})),_$$(".main-navigation .trigger-term-menu-genres").forEach((e=>{fcn_appendTermMenu("fcn_genre",e)})),_$$(".main-navigation .trigger-term-menu-fandoms").forEach((e=>{fcn_appendTermMenu("fcn_fandom",e)})),_$$(".main-navigation .trigger-term-menu-characters").forEach((e=>{fcn_appendTermMenu("fcn_character",e)})),_$$(".main-navigation .trigger-term-menu-warnings").forEach((e=>{fcn_appendTermMenu("fcn_content_warning",e)}))})),_$$$("full-navigation")?.addEventListener("mouseover",(()=>{document.dispatchEvent(new CustomEvent("fcnRemoveLastClicked"))}));var fcn_lastScrollTop=0;function fcn_scrollDirection(){if(FcnGlobals.eSite.classList.contains("transformed-scroll"))return;const e="hidden"!==window.getComputedStyle(document.documentElement).overflow?window.scrollY??document.documentElement.scrollTop:document.body.scrollTop??1;document.body.classList.toggle("scrolled-to-top",0===e),e>fcn_lastScrollTop&&Math.abs(fcn_lastScrollTop-e)>=10?(document.body.classList.add("scrolling-down"),document.body.classList.remove("scrolling-up"),fcn_lastScrollTop=Math.max(e,0)):e=50&&(document.body.classList.add("scrolling-up"),document.body.classList.remove("scrolling-down"),fcn_lastScrollTop=Math.max(e,0))}function fcn_observe(e,t,n={}){const s=_$(e);if(!s)return null;new IntersectionObserver((e=>t(e[0])),n).observe(s)}function fcn_dragElement(e){const t=e.querySelector(".drag-anchor")??e;let n,s;function i(t){t.preventDefault(),e.style.top=e.offsetTop-(s-t.clientY)+"px",e.style.left=e.offsetLeft-(n-t.clientX)+"px",n=t.clientX,s=t.clientY}function a(){t.onmouseup=null,t.onmousemove=null}t.onmousedown=function(e){e.preventDefault(),n=e.clientX,s=e.clientY,t.onmousemove=i,t.onmouseup=a}}function fcn_showNotification(e,t=3,n="base"){const s=_$("#notifications"),i=document.createElement("div");i.innerHTML=e,i.classList.add("notifications__message",`_${n}`),i.style.opacity=1,i.style.transitionDelay=`${t}s`,s.prepend(i),i.addEventListener("transitionend",(e=>{"opacity"===e.propertyName&&s.removeChild(e.target)})),i.addEventListener("click",(e=>{s.removeChild(e.currentTarget)})),setTimeout((()=>{i.style.opacity=0}),100)}if(window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_scrollDirection,200)),fcn_scrollDirection(),document.addEventListener("DOMContentLoaded",(()=>{fcn_observe(".main-observer",(e=>{document.body.classList.toggle("is-inside-main",e.intersectionRatio<1&&e.boundingClientRect.top<=0)}),{threshold:[1]}),fcn_observe(".chapter-end",(e=>{document.body.classList.toggle("is-end-of-chapter",e.isIntersecting||e.boundingClientRect.top<0)}),{root:null,threshold:0}),fcn_observe("#nav-observer-sticky",(e=>{_$$$("full-navigation").classList.toggle("is-sticky",e.intersectionRatio<1)}),{threshold:[1]})})),_$$(".modal__header.drag-anchor").forEach((e=>{fcn_dragElement(e.closest(".modal__wrapper"))})),FcnGlobals.urlParams){switch(FcnGlobals.urlParams.failure&&console.error("Failure:",FcnGlobals.urlParams.failure),FcnGlobals.urlParams.failure){case"oauth_email_taken":fcn_showNotification(fictioneer_tl.notification.oauthEmailTaken,5,"warning");break;case"oauth_already_linked":fcn_showNotification(fictioneer_tl.notification.oauthAccountAlreadyLinked,5,"warning")}if("oauth_new"===FcnGlobals.urlParams.success)fcn_showNotification(fictioneer_tl.notification.oauthNew,10);else FcnGlobals.urlParams.success?.startsWith("oauth_merged_")&&fcn_showNotification(fictioneer_tl.notification.oauthAccountLinked,3,"success");if(FcnGlobals.urlParams["fictioneer-notice"]){let e="1"===FcnGlobals.urlParams.failure?"warning":"base";e="1"===FcnGlobals.urlParams.success?"success":e,fcn_showNotification(FcnUtils.sanitizeHTML(FcnGlobals.urlParams["fictioneer-notice"]),3,e)}}function fcn_updateThemeColor(e=null){const t=fcn_siteSettings.darken?fcn_siteSettings.darken:0,n=fcn_siteSettings.saturation?fcn_siteSettings.saturation:0,s=fcn_siteSettings["hue-rotate"]?fcn_siteSettings["hue-rotate"]:0,i=t>=0?1+t**2:1-t**2,a=n>=0?1+n**2:1-n**2;let o=getComputedStyle(document.documentElement).getPropertyValue("--theme-color-base").trim().split(" ");o=`hsl(${(parseInt(o[0])+s)%360}deg ${(parseInt(o[1])*a).toFixed(2)}% ${(parseInt(o[2])*i).toFixed(2)}%)`,_$("meta[name=theme-color]").setAttribute("content",e??o)}const fcn_settingHueRotateRange=_$$$("site-setting-hue-rotate-range"),fcn_settingHueRotateText=_$$$("site-setting-hue-rotate-text"),fcn_settingHueRotateReset=_$$$("site-setting-hue-rotate-reset"),fcn_settingDarkenRanges=_$$(".setting-darken-range"),fcn_settingDarkenTexts=_$$(".setting-darken-text"),fcn_settingDarkenResets=_$$(".setting-darken-reset"),fcn_settingSaturationRanges=_$$(".setting-saturation-range"),fcn_settingSaturationTexts=_$$(".setting-saturation-text"),fcn_settingSaturationResets=_$$(".setting-saturation-reset"),fcn_settingFontLightnessRanges=_$$(".setting-font-lightness-range"),fcn_settingFontLightnessTexts=_$$(".setting-font-lightness-text"),fcn_settingFontLightnessResets=_$$(".setting-font-lightness-reset"),fcn_settingEvents=["nav-sticky","background-textures","polygons","covers","taxonomies","text-shadows","minimal","chapter-progress-bar"];var fcn_siteSettings=fcn_getSiteSettings();function fcn_updateSiteSetting(e,t,n){e.checked=n,fcn_siteSettings[t]=n,fcn_applySiteSettings(fcn_siteSettings)}function fcn_toggleLightMode(){fcn_setLightMode(!(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault))}function fcn_setLightMode(e,t=!1){localStorage.setItem("fcnLightmode",e),document.documentElement.dataset.mode=e?"light":"dark",_$$(".toggle-light-mode").forEach((t=>{t.closest("[aria-checked]")?.setAttribute("aria-checked",e)})),t||fcn_updateThemeColor()}function fcn_updateFontWeight(){const e="default"!=fcn_siteSettings["font-weight"];_$$(".site-setting-font-weight").forEach((e=>{e.value=fcn_siteSettings["font-weight"]})),_$$(".font-weight-reset").forEach((t=>{t.classList.toggle("_modified",e)}))}function fcn_resetFontWeight(){fcn_siteSettings["font-weight"]="default",document.documentElement.dataset.fontWeight="default",fcn_applySiteSettings(fcn_siteSettings)}function fcn_updateHueRotate(e){e=FcnUtils.clamp(0,360,e??0),fcn_settingHueRotateText.value=e,fcn_settingHueRotateRange.value=e,fcn_settingHueRotateReset.classList.toggle("_modified",0!=e),document.documentElement.style.setProperty("--hue-rotate",`(${e}deg + var(--hue-offset))`),fcn_siteSettings["hue-rotate"]=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setHueRotate(){fcn_updateHueRotate(this.value)}function fcn_updateDarken(e=null){e=FcnUtils.clamp(-1,1,e??fcn_siteSettings.darken),e=Math.round(100*(e+Number.EPSILON))/100,fcn_settingDarkenResets.forEach((t=>{t.classList.toggle("_modified",0!=e)})),fcn_settingDarkenRanges.forEach((t=>{t.value=e})),fcn_settingDarkenTexts.forEach((t=>{t.value=parseInt(100*e)}));const t=e>=0?1+e**2:1-e**2;document.documentElement.style.setProperty("--darken",`(${t} + var(--lightness-offset))`),fcn_siteSettings.darken=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setDarkenFromRange(){fcn_updateDarken(this.value)}function fcn_setDarkenFromText(){"-"!=this.value&&""!=this.value&&fcn_updateDarken((parseInt(this.value)??0)/100)}function fcn_updateSaturation(e=null){e=FcnUtils.clamp(-1,1,e??fcn_siteSettings.saturation),fcn_settingSaturationResets.forEach((t=>{t.classList.toggle("_modified",0!=e)})),fcn_settingSaturationRanges.forEach((t=>{t.value=e})),fcn_settingSaturationTexts.forEach((t=>{t.value=parseInt(100*e)}));const t=e>=0?1+e**2:1-e**2;document.documentElement.style.setProperty("--saturation",`(${t} + var(--saturation-offset))`),fcn_siteSettings.saturation=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setSaturationFromRange(){fcn_updateSaturation(this.value)}function fcn_setSaturationFromText(){"-"!=this.value&&""!=this.value&&fcn_updateSaturation((parseInt(this.value)??0)/100)}function fcn_updateFontLightness(e=null){e=FcnUtils.clamp(-1,1,e??fcn_siteSettings["font-lightness"]??1),fcn_settingFontLightnessResets.forEach((t=>{t.classList.toggle("_modified",0!=e)})),fcn_settingFontLightnessRanges.forEach((t=>{t.value=e})),fcn_settingFontLightnessTexts.forEach((t=>{t.value=parseInt(100*e)}));const t=e>=0?1+e**2:1-e**2;document.documentElement.style.setProperty("--font-lightness",`(${t} + var(--font-lightness-offset))`),fcn_siteSettings["font-lightness"]=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setFontLightnessFromRange(){fcn_updateFontLightness(this.value)}function fcn_setFontLightnessFromText(){"-"!=this.value&&""!=this.value&&fcn_updateFontLightness((parseInt(this.value)??0)/100)}function fcn_defaultSiteSettings(){return{"nav-sticky":!0,"background-textures":!0,polygons:!0,covers:!0,taxonomies:!0,"text-shadows":!1,minimal:!1,"chapter-progress-bar":!0,"site-theme":"default","font-weight":"default",darken:0,saturation:0,"font-saturation":0,"font-lightness":0,"hue-rotate":0}}function fcn_getSiteSettings(){const e=FcnUtils.parseJSON(localStorage.getItem("fcnSiteSettings"))??fcn_defaultSiteSettings();return fcn_setSiteSettings(e),e}function fcn_setSiteSettings(e=null){"object"==typeof(e=e||fcn_siteSettings)&&(fcn_siteSettings=e,localStorage.setItem("fcnSiteSettings",JSON.stringify(e)))}function fcn_applySiteSettings(e){e="object"!=typeof e?fcn_defaultSiteSettings():e,Object.entries(e).forEach((e=>{const t=_$$$(`site-setting-${e[0]}`);switch(t&&(t.checked=e[1]),e[0]){case"minimal":document.documentElement.classList.toggle("minimal",e[1]);break;case"darken":fcn_updateDarken();break;case"saturation":fcn_updateSaturation();break;case"font-saturation":break;case"font-lightness":fcn_updateFontLightness();break;case"hue-rotate":fcn_updateHueRotate(e[1]);break;case"font-weight":fcn_updateFontWeight();break;default:document.documentElement.classList.toggle(`no-${e[0]}`,!e[1])}})),fcn_setSiteSettings(e)}function fcn_updateSiteTheme(e){fcn_siteSettings["site-theme"]=e,document.documentElement.dataset.theme=e,_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=e),fcn_applySiteSettings(fcn_siteSettings),fcn_updateThemeColor()}function fcn_resetSiteTheme(){fcn_updateSiteTheme("default"),_$$(".site-setting-site-theme").forEach((e=>{e.value="default"}))}function fcn_revealCommentImage(e){const t=e.parentElement.querySelector("img");t.src=t.dataset.src,e.remove()}function fcn_contactFormSubmit(e){const t=e.closest("form"),n=new FormData(t);if(!t.reportValidity())return;if(e.disabled=!0,e.innerHTML=e.dataset.disabled,Date.now(){n.success?(t.querySelector("textarea").value="",e.innerHTML=e.dataset.done,fcn_showNotification(n.data.success,3,"success")):n.data.failure&&(e.disabled=!1,e.innerHTML=e.dataset.enabled)},errorCallback:()=>{e.disabled=!1,e.innerHTML=e.dataset.enabled}})}fcn_settingEvents.forEach((e=>{_$$$(`site-setting-${e}`)?.addEventListener("change",(t=>{fcn_updateSiteSetting(t.currentTarget,e,t.currentTarget.checked)}))})),fcn_setLightMode(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault,!0),_$$(".toggle-light-mode").forEach((e=>{e.onclick=()=>fcn_toggleLightMode()})),_$$(".font-weight-reset").forEach((e=>{e.addEventListener("click",fcn_resetFontWeight)})),_$$(".site-setting-font-weight").forEach((e=>{e.onchange=e=>{fcn_siteSettings["font-weight"]=e.target.value,document.documentElement.dataset.fontWeight=e.target.value,fcn_applySiteSettings(fcn_siteSettings),fcn_updateFontWeight()}})),fcn_settingHueRotateReset?.addEventListener("click",(()=>{fcn_updateHueRotate(0)})),fcn_settingHueRotateRange?.addEventListener("input",FcnUtils.throttle(fcn_setHueRotate,1e3/24)),fcn_settingHueRotateText?.addEventListener("input",fcn_setHueRotate),fcn_settingDarkenResets.forEach((e=>{e.addEventListener("click",(()=>{fcn_updateDarken(0)}))})),fcn_settingDarkenRanges.forEach((e=>{e.addEventListener("input",FcnUtils.throttle(fcn_setDarkenFromRange,1e3/24))})),fcn_settingDarkenTexts.forEach((e=>{e.addEventListener("input",fcn_setDarkenFromText)})),fcn_settingSaturationResets.forEach((e=>{e.addEventListener("click",(()=>{fcn_updateSaturation(0)}))})),fcn_settingSaturationRanges.forEach((e=>{e.addEventListener("input",FcnUtils.throttle(fcn_setSaturationFromRange,1e3/24))})),fcn_settingSaturationTexts.forEach((e=>{e.addEventListener("input",fcn_setSaturationFromText)})),fcn_settingFontLightnessResets.forEach((e=>{e.addEventListener("click",(()=>{fcn_updateFontLightness(0)}))})),fcn_settingFontLightnessRanges.forEach((e=>{e.addEventListener("input",FcnUtils.throttle(fcn_setFontLightnessFromRange,1e3/24))})),fcn_settingFontLightnessTexts.forEach((e=>{e.addEventListener("input",fcn_setFontLightnessFromText)})),fcn_applySiteSettings(fcn_siteSettings),_$$(".site-setting-site-theme").forEach((e=>{e.value=fcn_siteSettings["site-theme"]?fcn_siteSettings["site-theme"]:"default",_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=e.value),e.addEventListener("change",(e=>{fcn_updateSiteTheme(e.target.value)}))})),_$$$("site-setting-theme-reset")?.addEventListener("click",fcn_resetSiteTheme),fcn_updateThemeColor(),_$(".fictioneer-comments")?.addEventListener("click",(e=>{e.target?.classList.contains("consent-button")&&fcn_revealCommentImage(e.target)})),_$$(".fcn-contact-form").forEach((e=>{e.querySelector(".fcn-contact-form__submit").addEventListener("click",(e=>{fcn_contactFormSubmit(e.currentTarget)}))})),_$$('[data-click-action*="open-dialog-modal"]').forEach((e=>{e.addEventListener("click",(e=>{document.querySelector(e.currentTarget.dataset.clickTarget).showModal()}))})),_$$('[data-click-action*="close-dialog-modal"], button[formmethod="dialog"][value="cancel"]').forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),e.target.closest("dialog").close()}))})),_$$("dialog").forEach((e=>{e.addEventListener("mousedown",(t=>{if(t.target===t.currentTarget){const n=e.getBoundingClientRect();(t.clientXn.right||t.clientYn.bottom)&&(t.preventDefault(),t.target.close())}}))})),_$$(".content-section").forEach((e=>{e.addEventListener("click",(e=>{if(e.target.closest('[data-click-action*="open-tooltip-modal"]')&&!window.getSelection().toString()){const t=_$$$("fictioneer-tooltip-dialog"),n=e.target.dataset.dialogHeader,s=e.target.dataset.dialogContent;s.length>200?t.style.setProperty("--modal-width","400px"):t.style.removeProperty("--modal-width"),n&&(t.querySelector('[data-finder="tooltip-dialog-header"]').innerHTML=n),t.querySelector('[data-finder="tooltip-dialog-content"]').innerHTML=s,t.showModal()}}))})),document.body.addEventListener("keydown",(e=>{let t=document.activeElement.closest('[tabindex="0"]:not(a, input, button, select)');if(["BUTTON","A","INPUT","SELECT"].includes(document.activeElement.tagName)&&(t=null),t&&(" "!==e.key&&"Enter"!==e.key||(e.preventDefault(),t.click())),"Escape"===e.key){_$$(".modal-toggle:checked").forEach((e=>{e.checked=!1,e.dispatchEvent(new Event("change"))}));const e=_$(".lightbox.show");if(e)return void e.querySelector(".lightbox__close").click();const t=_$(".selected-paragraph #button-close-paragraph-tools");if(t)return void t.click();const n=_$("#tts-interface:not(.hidden)");if(n){if(n.classList.contains("playing")){const e=_$$$("button-tts-pause");e?.click(),e?.focus(),e?.blur()}else _$$$("button-tts-stop").click();return}}}));class FCN_KeywordInput{constructor(e){this.input=e,this.type=e.dataset.type,this.operator=e.closest(".keyword-input").querySelector(".keyword-input__operator input"),this.inputWrapper=e.closest(".keyword-input__input-wrapper"),this.block=e.closest(".keyword-input"),this.form=this.block.closest(".search-form"),this.collection=this.block.querySelector(".keyword-input__collection"),this.suggestionList=this.block.querySelector(".keyword-input__suggestion-list"),this.tabSuggestion=this.block.querySelector(".keyword-input__tab-suggestion"),this.allowText=this.form.querySelector(".allow-list")?.innerText??"{}",this.allowList=FcnUtils.parseJSON(this.allowText),this.hints=this.block.querySelector(".keyword-input__hints"),this.noHint=this.block.querySelector(".keyword-input__no-suggestions"),this.keywords=this.collection.value.length>0?this.collection.value.split(","):[],this.bindEvents(),this.resize(),this.filterSuggestions()}resize(){const e=this.tabSuggestion.innerText.length>0?this.tabSuggestion.innerText.length:this.input.value.length;this.input.style.width=.88*e+2+"ch"}reset(){this.keywords=[],this.block.querySelectorAll(".node").forEach((e=>{e.remove()})),this.block.querySelectorAll(".keyword-input__operator > input").forEach((e=>{e.checked=!1})),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}encode(e){const t=(new TextEncoder).encode(e.toLowerCase());return btoa(String.fromCharCode.apply(null,t))}filterSuggestions(){const e=this.input.value.toLowerCase();let t=0,n="";""==e?this.suggestionList.querySelectorAll(".keyword-button").forEach((e=>{e.hidden=!0})):this.suggestionList.querySelectorAll(".keyword-button").forEach((s=>{const i=s.innerText.toLowerCase();i.includes(e)&&this.keywords.indexOf(i)<0?(s.hidden=!1,t++,""==n&&i.startsWith(e)&&(n=i)):s.hidden=!0})),this.hints.querySelectorAll(".keyword-button").forEach((e=>{this.keywords.indexOf(e.value.toLowerCase())>-1?e.hidden=!0:e.hidden=!1})),this.tabSuggestion.innerHTML=n,this.hints.hidden=!(""==e),this.noHint.hidden=!(""!=e&&t<1)}addNode(e=null,t=null){const n=e??this.input.value.replace(",","");let s=this.allowList[`${this.type}_${this.encode(n)}`];if("authors"!=this.collection.name&&"ex_authors"!=this.collection.name||!t||(s=this.allowList[`${this.type}_${this.encode(n)}_${t.value}`]),!s||this.keywords.indexOf(s)>-1)return;this.keywords.push(s);const i=document.createElement("div");i.innerHTML=`${n}`,i.classList.add("node"),i.dataset.value=s,this.inputWrapper.parentNode.insertBefore(i,this.inputWrapper),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}removeNodeByValue(e){this.block.querySelector(`[data-value="${e}"]`)?.remove(),this.keywords=this.keywords.filter((t=>t!=e)),this.updateCollection(),this.filterSuggestions(),this.resize()}updateCollection(){this.collection.value=this.keywords.join(","),this.block.classList.toggle("_empty",""===this.collection.value),this.form.querySelector(".search-form__current").innerHTML=""}bindEvents(){this.input.addEventListener("input",(e=>{e.currentTarget.value.includes(",")&&this.addNode(),this.block.classList.toggle("_empty",""===e.currentTarget.value&&""===this.collection.value),this.filterSuggestions(),this.resize()})),this.input.addEventListener("keydown",(e=>{"Tab"!==e.key&&"Enter"!==e.key||""!=this.tabSuggestion.innerText&&(e.preventDefault(),this.input.value=this.tabSuggestion.innerText,this.addNode()),"Escape"===e.key&&(this.input.value="",this.tabSuggestion.innerHTML="",document.activeElement.blur()),"Backspace"===e.key&&""==this.input.value&&this.keywords.length>0&&this.removeNodeByValue(this.keywords.slice(-1))})),this.input.addEventListener("blur",(()=>{const e=this.allowList[this.encode(this.input.value)];this.blurTimeout=e?setTimeout((()=>{this.addNode()}),150):setTimeout((()=>{this.input.value="",this.tabSuggestion.innerHTML="",this.filterSuggestions(),this.resize()}),150)})),this.block.addEventListener("click",(e=>{e.target.closest(".node-delete")&&(e.preventDefault(),this.removeNodeByValue(e.target.closest(".node").dataset.value))})),this.block.querySelectorAll(".keyword-button").forEach((e=>{e.addEventListener("click",(e=>{clearTimeout(this.blurTimeout),this.addNode(e.currentTarget.innerText,e.currentTarget)}))}))}}function fcn_resetSearchForm(e,t,n){n.forEach((e=>e.reset())),t.querySelectorAll("input, select").forEach((e=>{e.value=e.dataset.default??e.value})),t.querySelector(".search-form__current").innerHTML="",fcn_showNotification(e.dataset.reset,2)}function fcn_handleTabInput(e){"Tab"==e.key&&(document.body.classList.add("user-is-tabbing"),window.removeEventListener("keydown",fcn_handleTabInput),window.addEventListener("mousedown",fcn_handleMouseInput))}function fcn_handleMouseInput(){document.body.classList.remove("user-is-tabbing"),window.removeEventListener("mousedown",fcn_handleMouseInput),window.addEventListener("keydown",fcn_handleTabInput)}function fcn_popupPosition(){_$$(".popup-menu-toggle.last-clicked .popup-menu:not(._fixed-position)").forEach((e=>{if("none"===window.getComputedStyle(e).display)return;const t=FcnUtils.detectScreenCollision(e);t&&0===t.length||(t.includes("top")?(e.classList.remove("_top"),e.classList.add("_bottom")):t.includes("bottom")&&(e.classList.remove("_bottom"),e.classList.add("_top")),e.closest("._fixed-horizontal")||(t.includes("left")?(e.classList.remove("_center","_justify-right"),e.classList.add("_justify-left")):t.includes("right")&&(e.classList.remove("_center","_justify-left"),e.classList.add("_justify-right"))))}))}function fcn_markCurrentMenuItem(){_$$(`.menu-item > [data-nav-object-id="${document.body.dataset.postId}"]`).forEach((e=>{e.setAttribute("aria-current","page"),e.closest(".menu-item").classList.add("current-menu-item")}))}function fcn_showAgeConfirmationModal(){const e=_$(".story__article, .chapter__article")?.dataset.ageRating;if(!document.documentElement.dataset.ageConfirmation&&e&&"adult"!==e)return void _$$$("age-confirmation-modal")?.remove();const t=_$$$("age-confirmation-leave");document.documentElement.classList.add("age-modal-open"),_$$$("age-confirmation-modal").hidden=!1,_$$$("age-confirmation-confirm")?.addEventListener("click",(e=>{document.documentElement.classList.remove("age-modal-open"),e.currentTarget.closest(".modal").remove(),localStorage.setItem("fcnAgeConfirmation","1")})),t?.addEventListener("click",(()=>{window.location.href=t.dataset.redirect??"https://search.brave.com/",localStorage.removeItem("fcnAgeConfirmation")}))}_$$(".search-form").forEach((e=>{if(e.classList.contains("_simple"))return;const t=[] -;e.querySelectorAll(".keyword-input__input").forEach((e=>{t.push(new FCN_KeywordInput(e))})),e.querySelector(".allow-list")?.remove(),e.addEventListener("change",(t=>{t.target.classList.contains("search-form__advanced-control")||t.target.classList.contains("search-form__string")||(e.querySelector(".search-form__current").innerHTML="")})),e.querySelectorAll(".reset").forEach((n=>{n.addEventListener("click",(()=>{fcn_resetSearchForm(n,e,t)}))}))})),_$$(".search-form__advanced-toggle").forEach((e=>{e.addEventListener("click",(e=>{const t=e.currentTarget.closest("form");t.dataset.advanced="true"==t.dataset.advanced?"false":"true"}))})),window.addEventListener("keydown",fcn_handleTabInput),window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_popupPosition,250)),document.body.addEventListener("click",(e=>{const t=e.target.closest("[href]"),n=t?.getAttribute("href");if(!t||"A"===!t.tagName||!n.startsWith("#")||n.length<2||"#respond"===n)return;const s=n.replace("#",""),i=_$$(`[name="${s}"], [id="${s}"]`)[0],a=t.closest(".comment._story-comment");a&&(window.location.href=a.querySelector(".fictioneer-comment__link").href+n),i&&(e.preventDefault(),i.scrollIntoView({behavior:"smooth",block:t.dataset?.block??"start"}))})),fcn_markCurrentMenuItem(),_$$$("age-confirmation-modal")&&"1"!==localStorage.getItem("fcnAgeConfirmation")&&!FcnUtils.isSearchEngineCrawler()?fcn_showAgeConfirmationModal():_$$$("age-confirmation-modal")?.remove(),document.addEventListener("DOMContentLoaded",(()=>{_$$(".splide:not(.no-auto-splide, .is-initialized)").forEach((e=>{e.querySelector(".splide__list")&&"undefined"!=typeof Splide&&(e.classList.remove("_splide-placeholder"),new Splide(e).mount())})),_$$(".temp-script, .splide-placeholder-styles").forEach((e=>{e.remove()}))})),application.register("fictioneer-large-card",class extends Stimulus.Controller{static get targets(){return["controls","menu"]}static values={postId:Number,storyId:Number,chapterId:Number};initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#s(),this.#n=!0,this.#i()}))}connect(){if(window.FictioneerApp.Controllers.fictioneerLargeCard=this,this.#n&&(this.#s(),this.#i()),document.addEventListener("click",(e=>{e.target.closest(`.card.post-${this.postIdValue}`)||this.#a()})),document.addEventListener("toggledLastClick",(e=>{this.#o(e.detail.target,e.detail.force)})),this.hasMenuTarget)for(this.menuFragment=document.createDocumentFragment();this.menuTarget.firstChild;)this.menuFragment.appendChild(this.menuTarget.firstChild)}disconnect(){this.#c()}isFollowed(){return!(!this.#r()||!this.#l()?.follows?.data?.[this.storyIdValue])}isRemembered(){return!(!this.#r()||!this.#l()?.reminders?.data?.[this.storyIdValue])}isRead(){if(!this.#r())return!1;const e=this.#l()?.checkmarks?.data?.[this.storyIdValue];return!!e&&(e.includes(this.chapterIdValue)||e.includes(this.storyIdValue))}cardClick(e){e.target.closest(".card__controls")||this.#d()}toggleMenu(){this.menuTarget.querySelector("*")?this.#d():this.#u()}toggleFollow(){this.#r()?(fcn_toggleFollow(this.storyIdValue,!this.isFollowed()),this.#h()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleReminder(){this.#r()?(fcn_toggleReminder(this.storyIdValue,!this.isRemembered()),this.#g()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleCheckmarks(){this.#r()?(fcn_toggleCheckmark(this.storyIdValue,this.chapterIdValue),this.#f()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}setCheckmarks(e){this.toggleCheckmarks("set",e.params?.type??"story")}unsetCheckmarks(e){this.toggleCheckmarks("unset",e.params?.type??"story")}#m=!1;#n=!1;#_=!1;#r(){const e=FcnUtils.loggedIn();return e||(this.#c(),this.#n=!1,this.#_=!0),e}#l(){return this.userData=fcn().userData(),this.userData}#p(){return this.#r()&&JSON.stringify(this.userData??0)!==JSON.stringify(this.#l())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#_&&this.#p()&&this.#s()}),3e4+1e3*Math.random()))}#i(){this.#v(),this.visibilityStateCheck=()=>{this.#r()&&("visible"===document.visibilityState?(this.#_=!1,this.#s(),this.#v()):(this.#_=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#c(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}#s(){this.#h(),this.#g(),this.#f()}#h(){this.element.classList.toggle("has-follow",this.isFollowed())}#g(){this.element.classList.toggle("has-reminder",this.isRemembered())}#f(){this.element.classList.toggle("has-checkmark",this.isRead())}#a(){this.#d()}#u(){this.#m=!0,this.menuTarget.appendChild(this.menuFragment.cloneNode(!0))}#d(){if(this.#m)for(this.#m=!1;this.menuTarget.firstChild;)this.menuTarget.removeChild(this.menuTarget.firstChild)}#o(e,t){t?e&&!e.closest(`.card.post-${this.postIdValue}`)&&this.#m&&this.#d():this.#d()}}),application.register("fictioneer-last-click",class extends Stimulus.Controller{static get targets(){return["toggle"]}last=null;connect(){window.FictioneerApp.Controllers.fictioneerLastClick=this,document.addEventListener("fcnRemoveLastClicked",(()=>{this.last&&this.removeLastClick()}))}removeAll(){this.last&&(this.#b(this.last,!1),this.removeLastClick())}toggle(e){const t=e.target.closest('[data-fictioneer-last-click-target="toggle"]');if(!t||["BUTTON","A","INPUT","SELECT"].includes(e.target.tagName)&&!e.target.hasAttribute("data-fictioneer-last-click-target"))return;const n=!t.classList.contains("last-clicked");"function"==typeof fcn_popupPosition&&fcn_popupPosition(),t.classList.toggle("last-clicked",n),t.closest(".watch-last-clicked")?.classList.toggle("has-last-clicked",n),this.last&&this.last!=t&&this.removeLastClick(),this.last=t,this.#b(t,n),e.stopPropagation()}removeLastClick(){this.last&&(this.last.closest(".watch-last-clicked")?.classList.remove("has-last-clicked"),this.last.classList.remove("last-clicked"),this.last=null,document.activeElement?.blur())}#b(e,t){document.dispatchEvent(new CustomEvent("toggledLastClick",{detail:{target:e,force:t}}))}});const fcn_consentBanner=_$$$("consent-banner");function fcn_loadConsentBanner(){fcn_consentBanner.classList.remove("hidden"),fcn_consentBanner.hidden=!1,_$$$("consent-accept-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","full"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0})),_$$$("consent-reject-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","necessary"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0}))}function fcn_showLightbox(e){const t=_$$$("fictioneer-lightbox"),n=_$(".lightbox__content");let s=!1,i=null;if(n.innerHTML="",e.classList.add("lightbox-last-trigger"),"IMG"==e.tagName?(i=e.cloneNode(),s=!0):e.href&&(i=document.createElement("img"),i.src=e.href,s=!0),s&&i){["class","style","height","width"].forEach((e=>i.removeAttribute(e))),n.appendChild(i),t.classList.add("show");const e=t.querySelector(".lightbox__close");e?.focus(),e?.blur()}}fcn_consentBanner&&""===(FcnUtils.getCookie("fcn_cookie_consent")??"")&&!FcnUtils.isSearchEngineCrawler()?setTimeout((()=>{fcn_loadConsentBanner()}),4e3):fcn_consentBanner?.remove(),document.body.addEventListener("click",(e=>{const t=e.target.closest("[data-lightbox]:not(.no-auto-lightbox)");t&&(e.preventDefault(),fcn_showLightbox(t))})),document.body.addEventListener("keydown",(e=>{const t=e.target.closest("[data-lightbox]:not(.no-auto-lightbox)");t&&(" "!==e.key&&"Enter"!==e.key||(e.preventDefault(),fcn_showLightbox(t)))})),document.querySelectorAll(".lightbox__close, .lightbox").forEach((e=>{e.addEventListener("click",(e=>{if("IMG"!=e.target.tagName){_$$$("fictioneer-lightbox").classList.remove("show");const e=_$(".lightbox-last-trigger");e?.focus(),e?.blur(),e?.classList.remove("lightbox-last-trigger")}}))})); \ No newline at end of file +const FcnGlobals={eSite:_$$$("site"),urlParams:Object.fromEntries(new URLSearchParams(window.location.search).entries()),pageLoadTimestamp:Date.now(),ajaxLimitThreshold:Date.now()-parseInt(fictioneer_ajax.ttl),ajaxURL:fictioneer_ajax.ajax_url,restURL:fictioneer_ajax.rest_url,ffcnrURL:fictioneer_ajax.ffcnr_url,ffcnrAuth:fictioneer_ajax.ffcnr_auth,debounceRate:fictioneer_ajax.post_debounce_rate,ajaxAuth:document.documentElement.dataset.fictioneerAjaxAuthValue??!1,fonts:fictioneer_fonts??[],fontColors:fictioneer_font_colors??[],commentFormSelector:fictioneer_comments?.selector??"#comment",commentStack:[]};function fcn(){const e=window.FictioneerApp?.Controllers?.fictioneer;return e||{userData:FcnUtils.userData,setUserData:FcnUtils.setUserData,resetUserData:FcnUtils.resetUserData,removeUserData:FcnUtils.removeUserData}}function fcn_getUserData(){return FcnUtils.userData()}function fcn_setUserData(e){return FcnUtils.setUserData(e)}function fcn_cleanUpWebStorage(){["fcnBookshelfContent"].forEach((e=>localStorage.removeItem(e))),fcn().resetUserData()}function fcn_cleanUpGuestView(){document.body.classList.remove("logged-in","is-admin","is-moderator","is-editor","is-author"),_$$$("fictioneer-ajax-nonce")?.remove(),_$$(".only-moderators, .only-admins, .only-authors, .only-editors, .only-logged-in").forEach((e=>{e.remove()}))}function fcn_setLoggedInState(){const e=fcn().userData(),t=!0===e.loggedIn;document.body.classList.toggle("logged-in",t),document.body.classList.toggle("is-admin",e.isAdmin),document.body.classList.toggle("is-moderator",e.isModerator),document.body.classList.toggle("is-author",e.isAuthor),document.body.classList.toggle("is-editor",e.isEditor);const n=[];t&&(n.push('[data-fictioneer-id-param="login-modal"]'),n.push("#login-modal")),e.isAdmin||(n.push(".only-admins"),e.isModerator||n.push(".only-moderators"),e.isAuthor||n.push(".only-authors"),e.isEditor||n.push(".only-editors")),_$$(n.join(", ")).forEach((e=>e.remove()))}function fcn_setAvatar(){const e=fcn().userData()?.avatarUrl;e&&_$$('[data-fictioneer-target="avatarWrapper"]').forEach((t=>{const n=document.createElement("img");n.classList.add("user-profile-image"),n.src=e,t.firstChild.remove(),t.appendChild(n)}))}Object.freeze(FcnGlobals),window.FictioneerApp=window.FictioneerApp||{},window.FictioneerApp.Controllers=window.FictioneerApp.Controllers||{},application.register("fictioneer",class extends Stimulus.Controller{static get targets(){return["avatarWrapper","modal","mobileMenuToggle"]}static values={fingerprint:String,ageConfirmation:{type:Boolean,default:!1},ajaxAuth:{type:Boolean,default:!1},ajaxSubmit:{type:Boolean,default:!1},cachingActive:{type:Boolean,default:!1},publicCaching:{type:Boolean,default:!1},forceChildTheme:{type:Boolean,default:!1},editTime:{type:Number,default:15}};userReady=!1;lastModalToggle=null;currentModal=null;initialize(){if(FcnUtils.loggedIn()||this.ajaxAuthValue)this.fetchUserData();else{fcn_cleanUpWebStorage();const e=new CustomEvent("fcnUserDataReady",{detail:{data:this.userData(),time:new Date,loggedOut:!0},bubbles:!0,cancelable:!1});document.dispatchEvent(e)}}connect(){window.FictioneerApp.Controllers.fictioneer=this}userData(){return FcnUtils.userData()}setUserData(e){FcnUtils.setUserData(e)}resetUserData(){FcnUtils.resetUserData()}removeUserData(){FcnUtils.removeUserData()}fetchUserData(){let e=this.userData();if(FcnUtils.loggedIn()&&!1===e.loggedIn&&(this.removeUserData(),e=this.userData()),(FcnGlobals.ajaxLimitThreshold{if(t.success){let n=this.userData();n=t.data,n.lastLoaded=Date.now(),this.setUserData(n),fcn_setAvatar(),e.nonceHtml&&this.#e(e.nonceHtml);const s=new CustomEvent("fcnUserDataReady",{detail:{data:t.data,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(s)}else{const e=this.userData();e.lastLoaded=Date.now(),e.loggedIn=!1,this.setUserData(e);const n=new CustomEvent("fcnUserDataFailed",{detail:{data:t,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(n)}this.userReady=!0})).catch((e=>{localStorage.removeItem("fcnUserData");const t=new CustomEvent("fcnUserDataError",{detail:{error:e,time:new Date},bubbles:!0,cancelable:!1});document.dispatchEvent(t)}))}copyInput(e){e.currentTarget.select(),FcnUtils.copyToClipboard(e.currentTarget.value,e.currentTarget.dataset.message)}clearConsent(e){FcnUtils.toggleInProgress(e.currentTarget),FcnUtils.deleteCookie("fcn_cookie_consent"),location.reload()}clearCookies(e){const t=e.currentTarget;if(!FcnUtils.loggedIn())return fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),void alert(t.dataset.message);FcnUtils.toggleInProgress(t),FcnUtils.aGet({action:"fictioneer_ajax_clear_cookies",nonce:FcnUtils.nonce()}).then((e=>{e.success?(fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),alert(e.data.success)):e.data.error&&(alert(e.data.failure),console.error("Error:",e.data.error))})).catch((e=>{alert(e),console.error(e)})).then((()=>{FcnUtils.toggleInProgress(t)}))}logout(){fcn_cleanUpWebStorage()}toggleObfuscation(e){e.target.closest('[data-fictioneer-target="obfuscated"]').classList.toggle("_obfuscated")}bodyClick(e){let t;this.dispatch("bodyClick",{detail:{event:e,target:e.target}}),(t=e.target.closest(".page-numbers.dots:not(button)"))?this.#t(t):(t=e.target.closest(".spoiler"))&&t.classList.toggle("_open")}toggleChapterGroup(e){const t=e.currentTarget.closest(".chapter-group"),n=t.querySelector(".chapter-group__list"),s=!t.classList.contains("_closed");n.addEventListener("transitionend",(()=>{n.style.height="",n.querySelectorAll("a, button, label, input:not([hidden])").forEach((e=>{e.tabIndex=n.parentElement.classList.contains("_closed")?"-1":"0"})),_$(".main__background")?.classList.remove("will-change")}),{once:!0}),_$(".main__background")?.classList.add("will-change"),n.style.height=`${n.scrollHeight}px`,requestAnimationFrame((()=>{requestAnimationFrame((()=>{t.classList.toggle("_closed",s),n.style.height=s?"0":`${n.scrollHeight}px`}))}))}toggleModal(e){e.preventDefault(),this.toggleModalVisibility(e.currentTarget,e.params.id)}toggleModalVisibility(e,t){const n=_$$$(t);if(n)if(this.currentModal!==n&&this.closeModals(),this.lastModalToggle=e,n.hidden=!n.hidden,n.hidden)this.closeModals();else{const e=n.querySelector(".close");e?.focus(),e?.blur()}}closeModals(){this.hasModalTarget&&this.modalTargets.forEach((e=>{e.hidden=!0})),this.lastModalToggle&&(this.lastModalToggle?.focus(),this.lastModalToggle?.blur(),this.lastModalToggle.null)}backgroundCloseModals({target:e}){e.classList.contains("modal")&&this.closeModals()}toggleMobileMenu(e){e.preventDefault();const t=window.FictioneerApp.Controllers.fictioneerMobileMenu;t&&t.toggle()}#e(e){_$$$("fictioneer-ajax-nonce")?.remove(),document.body.appendChild(FcnUtils.html`${e}`)}#t(e){if(document.documentElement.dataset.disablePageJump)return;const t=parseInt(window.prompt(fictioneer_tl.notification.enterPageNumber));if(t>0){const n=e.nextElementSibling.getAttribute("href"),s=["page=","paged=","comment-page-","pg="];for(const e of s)if(n.includes(e))return void(window.location.href=n.replace(new RegExp(`${e}\\d+`),e+t));window.location.href=n.replace(/page\/\d+/,`page/${t}`)}}}),"function"==typeof fcn_removeQueryArgs&&fcn_removeQueryArgs(),document.addEventListener("fcnUserDataReady",(()=>{fcn().userData().loggedIn||(fcn_cleanUpWebStorage(),fcn_cleanUpGuestView())})),_$("#wp-admin-bar-logout a")?.addEventListener("click",(()=>{fcn_cleanUpWebStorage()})),_$$(".subscriber-login, .oauth-login-link, [data-prepare-login]").forEach((e=>{e.addEventListener("click",(()=>{fcn().removeUserData()}))})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setLoggedInState()})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setAvatar()}));var fcn_animFrameEvents=new Map;function fcn_bindEventToAnimationFrame(e,t,n=window){n.addEventListener(e,(function(){fcn_animFrameEvents.get(t)||(fcn_animFrameEvents.set(t,!0),requestAnimationFrame((()=>{n.dispatchEvent(new CustomEvent(t)),fcn_animFrameEvents.set(t,!1)})))}))}function fcn_loadEmbed(e){e.target.parentNode.querySelectorAll("iframe, script")[0].src=e.target.dataset.src,e.target.parentElement.querySelector(".embed-logo")?.remove(),e.target.remove()}function fcn_appendTermMenu(e,t){const n=_$$$(`term-submenu-${e}`);if(!n)return;const s=n.content.cloneNode(!0);t.classList.add("menu-item-has-children"),t.querySelector('[href="#"]').addEventListener("click",(e=>{e.preventDefault()})),t.appendChild(s)}fcn_bindEventToAnimationFrame("scroll","scroll.rAF"),fcn_bindEventToAnimationFrame("resize","resize.rAF"),document.body.addEventListener("change",(e=>{const t=e.target.closest('[type="checkbox"]');if(!t)return;const n=t.name,s=n?_$$(`label[for="${n}"]`):[],i=t.checked;t.closest("[aria-checked]")?.setAttribute("aria-checked",i),s.forEach((e=>{e.closest("[aria-checked]")?.setAttribute("aria-checked",i)}))})),_$$(".iframe-consent, .twitter-consent").forEach((e=>{e.onclick=e=>{fcn_loadEmbed(e)}})),document.addEventListener("DOMContentLoaded",(()=>{const e=_$("#menu-navigation > .menu-item"),t=_$$$("full-navigation");e&&t&&e.offsetHeight{fcn_appendTermMenu("category",e)})),_$$(".main-navigation .trigger-term-menu-tags").forEach((e=>{fcn_appendTermMenu("post_tag",e)})),_$$(".main-navigation .trigger-term-menu-genres").forEach((e=>{fcn_appendTermMenu("fcn_genre",e)})),_$$(".main-navigation .trigger-term-menu-fandoms").forEach((e=>{fcn_appendTermMenu("fcn_fandom",e)})),_$$(".main-navigation .trigger-term-menu-characters").forEach((e=>{fcn_appendTermMenu("fcn_character",e)})),_$$(".main-navigation .trigger-term-menu-warnings").forEach((e=>{fcn_appendTermMenu("fcn_content_warning",e)}))})),_$$$("full-navigation")?.addEventListener("mouseover",(()=>{document.dispatchEvent(new CustomEvent("fcnRemoveLastClicked"))}));var fcn_lastScrollTop=0;function fcn_scrollDirection(){if(FcnGlobals.eSite.classList.contains("transformed-scroll"))return;const e="hidden"!==window.getComputedStyle(document.documentElement).overflow?window.scrollY??document.documentElement.scrollTop:document.body.scrollTop??1;document.body.classList.toggle("scrolled-to-top",0===e),e>fcn_lastScrollTop&&Math.abs(fcn_lastScrollTop-e)>=10?(document.body.classList.add("scrolling-down"),document.body.classList.remove("scrolling-up"),fcn_lastScrollTop=Math.max(e,0)):e=50&&(document.body.classList.add("scrolling-up"),document.body.classList.remove("scrolling-down"),fcn_lastScrollTop=Math.max(e,0))}function fcn_observe(e,t,n={}){const s=_$(e);if(!s)return null;new IntersectionObserver((e=>t(e[0])),n).observe(s)}function fcn_dragElement(e){const t=e.querySelector(".drag-anchor")??e;let n,s;function i(t){t.preventDefault(),e.style.top=e.offsetTop-(s-t.clientY)+"px",e.style.left=e.offsetLeft-(n-t.clientX)+"px",n=t.clientX,s=t.clientY}function a(){t.onmouseup=null,t.onmousemove=null}t.onmousedown=function(e){e.preventDefault(),n=e.clientX,s=e.clientY,t.onmousemove=i,t.onmouseup=a}}function fcn_showNotification(e,t=3,n="base"){const s=_$("#notifications"),i=document.createElement("div");i.innerHTML=e,i.classList.add("notifications__message",`_${n}`),i.style.opacity=1,i.style.transitionDelay=`${t}s`,s.prepend(i),i.addEventListener("transitionend",(e=>{"opacity"===e.propertyName&&s.removeChild(e.target)})),i.addEventListener("click",(e=>{s.removeChild(e.currentTarget)})),setTimeout((()=>{i.style.opacity=0}),100)}if(window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_scrollDirection,200)),fcn_scrollDirection(),document.addEventListener("DOMContentLoaded",(()=>{fcn_observe(".main-observer",(e=>{document.body.classList.toggle("is-inside-main",e.intersectionRatio<1&&e.boundingClientRect.top<=0)}),{threshold:[1]}),fcn_observe(".chapter-end",(e=>{document.body.classList.toggle("is-end-of-chapter",e.isIntersecting||e.boundingClientRect.top<0)}),{root:null,threshold:0}),fcn_observe("#nav-observer-sticky",(e=>{_$$$("full-navigation").classList.toggle("is-sticky",e.intersectionRatio<1)}),{threshold:[1]})})),_$$(".modal__header.drag-anchor").forEach((e=>{fcn_dragElement(e.closest(".modal__wrapper"))})),FcnGlobals.urlParams){switch(FcnGlobals.urlParams.failure&&console.error("Failure:",FcnGlobals.urlParams.failure),FcnGlobals.urlParams.failure){case"oauth_email_taken":fcn_showNotification(fictioneer_tl.notification.oauthEmailTaken,5,"warning");break;case"oauth_already_linked":fcn_showNotification(fictioneer_tl.notification.oauthAccountAlreadyLinked,5,"warning")}if("oauth_new"===FcnGlobals.urlParams.success)fcn_showNotification(fictioneer_tl.notification.oauthNew,10);else FcnGlobals.urlParams.success?.startsWith("oauth_merged_")&&fcn_showNotification(fictioneer_tl.notification.oauthAccountLinked,3,"success");if(FcnGlobals.urlParams["fictioneer-notice"]){let e="1"===FcnGlobals.urlParams.failure?"warning":"base";e="1"===FcnGlobals.urlParams.success?"success":e,fcn_showNotification(FcnUtils.sanitizeHTML(FcnGlobals.urlParams["fictioneer-notice"]),3,e)}}function fcn_updateThemeColor(e=null){const t=fcn_siteSettings.darken?fcn_siteSettings.darken:0,n=fcn_siteSettings.saturation?fcn_siteSettings.saturation:0,s=fcn_siteSettings["hue-rotate"]?fcn_siteSettings["hue-rotate"]:0,i=t>=0?1+t**2:1-t**2,a=n>=0?1+n**2:1-n**2;let o=getComputedStyle(document.documentElement).getPropertyValue("--theme-color-base").trim().split(" ");o=`hsl(${(parseInt(o[0])+s)%360}deg ${(parseInt(o[1])*a).toFixed(2)}% ${(parseInt(o[2])*i).toFixed(2)}%)`,_$("meta[name=theme-color]").setAttribute("content",e??o)}const fcn_settingHueRotateRange=_$$$("site-setting-hue-rotate-range"),fcn_settingHueRotateText=_$$$("site-setting-hue-rotate-text"),fcn_settingHueRotateReset=_$$$("site-setting-hue-rotate-reset"),fcn_settingDarkenRanges=_$$(".setting-darken-range"),fcn_settingDarkenTexts=_$$(".setting-darken-text"),fcn_settingDarkenResets=_$$(".setting-darken-reset"),fcn_settingSaturationRanges=_$$(".setting-saturation-range"),fcn_settingSaturationTexts=_$$(".setting-saturation-text"),fcn_settingSaturationResets=_$$(".setting-saturation-reset"),fcn_settingFontLightnessRanges=_$$(".setting-font-lightness-range"),fcn_settingFontLightnessTexts=_$$(".setting-font-lightness-text"),fcn_settingFontLightnessResets=_$$(".setting-font-lightness-reset"),fcn_settingEvents=["nav-sticky","background-textures","polygons","covers","taxonomies","text-shadows","minimal","chapter-progress-bar"];var fcn_siteSettings=fcn_getSiteSettings();function fcn_updateSiteSetting(e,t,n){e.checked=n,fcn_siteSettings[t]=n,fcn_applySiteSettings(fcn_siteSettings)}function fcn_toggleLightMode(){fcn_setLightMode(!(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault))}function fcn_setLightMode(e,t=!1){localStorage.setItem("fcnLightmode",e),document.documentElement.dataset.mode=e?"light":"dark",_$$(".toggle-light-mode").forEach((t=>{t.closest("[aria-checked]")?.setAttribute("aria-checked",e)})),t||fcn_updateThemeColor()}function fcn_updateFontWeight(){const e="default"!=fcn_siteSettings["font-weight"];_$$(".site-setting-font-weight").forEach((e=>{e.value=fcn_siteSettings["font-weight"]})),_$$(".font-weight-reset").forEach((t=>{t.classList.toggle("_modified",e)}))}function fcn_resetFontWeight(){fcn_siteSettings["font-weight"]="default",document.documentElement.dataset.fontWeight="default",fcn_applySiteSettings(fcn_siteSettings)}function fcn_updateHueRotate(e){e=FcnUtils.clamp(0,360,e??0),fcn_settingHueRotateText.value=e,fcn_settingHueRotateRange.value=e,fcn_settingHueRotateReset.classList.toggle("_modified",0!=e),document.documentElement.style.setProperty("--hue-rotate",`(${e}deg + var(--hue-offset))`),fcn_siteSettings["hue-rotate"]=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setHueRotate(){fcn_updateHueRotate(this.value)}function fcn_updateDarken(e=null){e=FcnUtils.clamp(-1,1,e??fcn_siteSettings.darken),e=Math.round(100*(e+Number.EPSILON))/100,fcn_settingDarkenResets.forEach((t=>{t.classList.toggle("_modified",0!=e)})),fcn_settingDarkenRanges.forEach((t=>{t.value=e})),fcn_settingDarkenTexts.forEach((t=>{t.value=parseInt(100*e)}));const t=e>=0?1+e**2:1-e**2;document.documentElement.style.setProperty("--darken",`(${t} + var(--lightness-offset))`),fcn_siteSettings.darken=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setDarkenFromRange(){fcn_updateDarken(this.value)}function fcn_setDarkenFromText(){"-"!=this.value&&""!=this.value&&fcn_updateDarken((parseInt(this.value)??0)/100)}function fcn_updateSaturation(e=null){e=FcnUtils.clamp(-1,1,e??fcn_siteSettings.saturation),fcn_settingSaturationResets.forEach((t=>{t.classList.toggle("_modified",0!=e)})),fcn_settingSaturationRanges.forEach((t=>{t.value=e})),fcn_settingSaturationTexts.forEach((t=>{t.value=parseInt(100*e)}));const t=e>=0?1+e**2:1-e**2;document.documentElement.style.setProperty("--saturation",`(${t} + var(--saturation-offset))`),fcn_siteSettings.saturation=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setSaturationFromRange(){fcn_updateSaturation(this.value)}function fcn_setSaturationFromText(){"-"!=this.value&&""!=this.value&&fcn_updateSaturation((parseInt(this.value)??0)/100)}function fcn_updateFontLightness(e=null){e=FcnUtils.clamp(-1,1,e??fcn_siteSettings["font-lightness"]??1),fcn_settingFontLightnessResets.forEach((t=>{t.classList.toggle("_modified",0!=e)})),fcn_settingFontLightnessRanges.forEach((t=>{t.value=e})),fcn_settingFontLightnessTexts.forEach((t=>{t.value=parseInt(100*e)}));const t=e>=0?1+e**2:1-e**2;document.documentElement.style.setProperty("--font-lightness",`(${t} + var(--font-lightness-offset))`),fcn_siteSettings["font-lightness"]=e,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setFontLightnessFromRange(){fcn_updateFontLightness(this.value)}function fcn_setFontLightnessFromText(){"-"!=this.value&&""!=this.value&&fcn_updateFontLightness((parseInt(this.value)??0)/100)}function fcn_defaultSiteSettings(){return{"nav-sticky":!0,"background-textures":!0,polygons:!0,covers:!0,taxonomies:!0,"text-shadows":!1,minimal:!1,"chapter-progress-bar":!0,"site-theme":"default","font-weight":"default",darken:0,saturation:0,"font-saturation":0,"font-lightness":0,"hue-rotate":0}}function fcn_getSiteSettings(){const e=FcnUtils.parseJSON(localStorage.getItem("fcnSiteSettings"))??fcn_defaultSiteSettings();return fcn_setSiteSettings(e),e}function fcn_setSiteSettings(e=null){"object"==typeof(e=e||fcn_siteSettings)&&(fcn_siteSettings=e,localStorage.setItem("fcnSiteSettings",JSON.stringify(e)))}function fcn_applySiteSettings(e){e="object"!=typeof e?fcn_defaultSiteSettings():e,Object.entries(e).forEach((e=>{const t=_$$$(`site-setting-${e[0]}`);switch(t&&(t.checked=e[1]),e[0]){case"minimal":document.documentElement.classList.toggle("minimal",e[1]);break;case"darken":fcn_updateDarken();break;case"saturation":fcn_updateSaturation();break;case"font-saturation":break;case"font-lightness":fcn_updateFontLightness();break;case"hue-rotate":fcn_updateHueRotate(e[1]);break;case"font-weight":fcn_updateFontWeight();break;default:document.documentElement.classList.toggle(`no-${e[0]}`,!e[1])}})),fcn_setSiteSettings(e)}function fcn_updateSiteTheme(e){fcn_siteSettings["site-theme"]=e,document.documentElement.dataset.theme=e,_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=e),fcn_applySiteSettings(fcn_siteSettings),fcn_updateThemeColor()}function fcn_resetSiteTheme(){fcn_updateSiteTheme("default"),_$$(".site-setting-site-theme").forEach((e=>{e.value="default"}))}function fcn_revealCommentImage(e){const t=e.parentElement.querySelector("img");t.src=t.dataset.src,e.remove()}function fcn_contactFormSubmit(e){const t=e.closest("form"),n=new FormData(t);if(!t.reportValidity())return;if(e.disabled=!0,e.innerHTML=e.dataset.disabled,Date.now(){n.success?(t.querySelector("textarea").value="",e.innerHTML=e.dataset.done,fcn_showNotification(n.data.success,3,"success")):n.data.failure&&(e.disabled=!1,e.innerHTML=e.dataset.enabled)},errorCallback:()=>{e.disabled=!1,e.innerHTML=e.dataset.enabled}})}fcn_settingEvents.forEach((e=>{_$$$(`site-setting-${e}`)?.addEventListener("change",(t=>{fcn_updateSiteSetting(t.currentTarget,e,t.currentTarget.checked)}))})),fcn_setLightMode(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault,!0),_$$(".toggle-light-mode").forEach((e=>{e.onclick=()=>fcn_toggleLightMode()})),_$$(".font-weight-reset").forEach((e=>{e.addEventListener("click",fcn_resetFontWeight)})),_$$(".site-setting-font-weight").forEach((e=>{e.onchange=e=>{fcn_siteSettings["font-weight"]=e.target.value,document.documentElement.dataset.fontWeight=e.target.value,fcn_applySiteSettings(fcn_siteSettings),fcn_updateFontWeight()}})),fcn_settingHueRotateReset?.addEventListener("click",(()=>{fcn_updateHueRotate(0)})),fcn_settingHueRotateRange?.addEventListener("input",FcnUtils.throttle(fcn_setHueRotate,1e3/24)),fcn_settingHueRotateText?.addEventListener("input",fcn_setHueRotate),fcn_settingDarkenResets.forEach((e=>{e.addEventListener("click",(()=>{fcn_updateDarken(0)}))})),fcn_settingDarkenRanges.forEach((e=>{e.addEventListener("input",FcnUtils.throttle(fcn_setDarkenFromRange,1e3/24))})),fcn_settingDarkenTexts.forEach((e=>{e.addEventListener("input",fcn_setDarkenFromText)})),fcn_settingSaturationResets.forEach((e=>{e.addEventListener("click",(()=>{fcn_updateSaturation(0)}))})),fcn_settingSaturationRanges.forEach((e=>{e.addEventListener("input",FcnUtils.throttle(fcn_setSaturationFromRange,1e3/24))})),fcn_settingSaturationTexts.forEach((e=>{e.addEventListener("input",fcn_setSaturationFromText)})),fcn_settingFontLightnessResets.forEach((e=>{e.addEventListener("click",(()=>{fcn_updateFontLightness(0)}))})),fcn_settingFontLightnessRanges.forEach((e=>{e.addEventListener("input",FcnUtils.throttle(fcn_setFontLightnessFromRange,1e3/24))})),fcn_settingFontLightnessTexts.forEach((e=>{e.addEventListener("input",fcn_setFontLightnessFromText)})),fcn_applySiteSettings(fcn_siteSettings),_$$(".site-setting-site-theme").forEach((e=>{e.value=fcn_siteSettings["site-theme"]?fcn_siteSettings["site-theme"]:"default",_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=e.value),e.addEventListener("change",(e=>{fcn_updateSiteTheme(e.target.value)}))})),_$$$("site-setting-theme-reset")?.addEventListener("click",fcn_resetSiteTheme),fcn_updateThemeColor(),_$(".fictioneer-comments")?.addEventListener("click",(e=>{e.target?.classList.contains("consent-button")&&fcn_revealCommentImage(e.target)})),_$$(".fcn-contact-form").forEach((e=>{e.querySelector(".fcn-contact-form__submit").addEventListener("click",(e=>{fcn_contactFormSubmit(e.currentTarget)}))})),_$$('[data-click-action*="open-dialog-modal"]').forEach((e=>{e.addEventListener("click",(e=>{document.querySelector(e.currentTarget.dataset.clickTarget).showModal()}))})),_$$('[data-click-action*="close-dialog-modal"], button[formmethod="dialog"][value="cancel"]').forEach((e=>{e.addEventListener("click",(e=>{e.preventDefault(),e.target.closest("dialog").close()}))})),_$$("dialog").forEach((e=>{e.addEventListener("mousedown",(t=>{if(t.target===t.currentTarget){const n=e.getBoundingClientRect();(t.clientXn.right||t.clientYn.bottom)&&(t.preventDefault(),t.target.close())}}))})),_$$(".content-section").forEach((e=>{e.addEventListener("click",(e=>{if(e.target.closest('[data-click-action*="open-tooltip-modal"]')&&!window.getSelection().toString()){const t=_$$$("fictioneer-tooltip-dialog"),n=e.target.dataset.dialogHeader,s=e.target.dataset.dialogContent;s.length>200?t.style.setProperty("--modal-width","400px"):t.style.removeProperty("--modal-width"),n&&(t.querySelector('[data-finder="tooltip-dialog-header"]').innerHTML=n),t.querySelector('[data-finder="tooltip-dialog-content"]').innerHTML=s,t.showModal()}}))})),document.body.addEventListener("keydown",(e=>{let t=document.activeElement.closest('[tabindex="0"]:not(a, input, button, select)');if(["BUTTON","A","INPUT","SELECT"].includes(document.activeElement.tagName)&&(t=null),t&&(" "!==e.key&&"Enter"!==e.key||(e.preventDefault(),t.click())),"Escape"===e.key){_$$(".modal-toggle:checked").forEach((e=>{e.checked=!1,e.dispatchEvent(new Event("change"))}));const e=_$(".lightbox.show");if(e)return void e.querySelector(".lightbox__close").click();const t=_$(".selected-paragraph #button-close-paragraph-tools");if(t)return void t.click();const n=_$("#tts-interface:not(.hidden)");if(n){if(n.classList.contains("playing")){const e=_$$$("button-tts-pause");e?.click(),e?.focus(),e?.blur()}else _$$$("button-tts-stop").click();return}}}));class FCN_KeywordInput{constructor(e){this.input=e,this.type=e.dataset.type,this.operator=e.closest(".keyword-input").querySelector(".keyword-input__operator input"),this.inputWrapper=e.closest(".keyword-input__input-wrapper"),this.block=e.closest(".keyword-input"),this.form=this.block.closest(".search-form"),this.collection=this.block.querySelector(".keyword-input__collection"),this.suggestionList=this.block.querySelector(".keyword-input__suggestion-list"),this.tabSuggestion=this.block.querySelector(".keyword-input__tab-suggestion"),this.allowText=this.form.querySelector(".allow-list")?.innerText??"{}",this.allowList=FcnUtils.parseJSON(this.allowText),this.hints=this.block.querySelector(".keyword-input__hints"),this.noHint=this.block.querySelector(".keyword-input__no-suggestions"),this.keywords=this.collection.value.length>0?this.collection.value.split(","):[],this.bindEvents(),this.resize(),this.filterSuggestions()}resize(){const e=this.tabSuggestion.innerText.length>0?this.tabSuggestion.innerText.length:this.input.value.length;this.input.style.width=.88*e+2+"ch"}reset(){this.keywords=[],this.block.querySelectorAll(".node").forEach((e=>{e.remove()})),this.block.querySelectorAll(".keyword-input__operator > input").forEach((e=>{e.checked=!1})),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}encode(e){const t=(new TextEncoder).encode(e.toLowerCase());return btoa(String.fromCharCode.apply(null,t))}filterSuggestions(){const e=this.input.value.toLowerCase();let t=0,n="";""==e?this.suggestionList.querySelectorAll(".keyword-button").forEach((e=>{e.hidden=!0})):this.suggestionList.querySelectorAll(".keyword-button").forEach((s=>{const i=s.innerText.toLowerCase();i.includes(e)&&this.keywords.indexOf(i)<0?(s.hidden=!1,t++,""==n&&i.startsWith(e)&&(n=i)):s.hidden=!0})),this.hints.querySelectorAll(".keyword-button").forEach((e=>{this.keywords.indexOf(e.value.toLowerCase())>-1?e.hidden=!0:e.hidden=!1})),this.tabSuggestion.innerHTML=n,this.hints.hidden=!(""==e),this.noHint.hidden=!(""!=e&&t<1)}addNode(e=null,t=null){const n=e??this.input.value.replace(",","");let s=this.allowList[`${this.type}_${this.encode(n)}`];if("authors"!=this.collection.name&&"ex_authors"!=this.collection.name||!t||(s=this.allowList[`${this.type}_${this.encode(n)}_${t.value}`]),!s||this.keywords.indexOf(s)>-1)return;this.keywords.push(s);const i=document.createElement("div");i.innerHTML=`${n}`,i.classList.add("node"),i.dataset.value=s,this.inputWrapper.parentNode.insertBefore(i,this.inputWrapper),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}removeNodeByValue(e){this.block.querySelector(`[data-value="${e}"]`)?.remove(),this.keywords=this.keywords.filter((t=>t!=e)),this.updateCollection(),this.filterSuggestions(),this.resize()}updateCollection(){this.collection.value=this.keywords.join(","),this.block.classList.toggle("_empty",""===this.collection.value),this.form.querySelector(".search-form__current").innerHTML=""}bindEvents(){this.input.addEventListener("input",(e=>{e.currentTarget.value.includes(",")&&this.addNode(),this.block.classList.toggle("_empty",""===e.currentTarget.value&&""===this.collection.value),this.filterSuggestions(),this.resize()})),this.input.addEventListener("keydown",(e=>{"Tab"!==e.key&&"Enter"!==e.key||""!=this.tabSuggestion.innerText&&(e.preventDefault(),this.input.value=this.tabSuggestion.innerText,this.addNode()),"Escape"===e.key&&(this.input.value="",this.tabSuggestion.innerHTML="",document.activeElement.blur()),"Backspace"===e.key&&""==this.input.value&&this.keywords.length>0&&this.removeNodeByValue(this.keywords.slice(-1))})),this.input.addEventListener("blur",(()=>{const e=this.allowList[this.encode(this.input.value)];this.blurTimeout=e?setTimeout((()=>{this.addNode()}),150):setTimeout((()=>{this.input.value="",this.tabSuggestion.innerHTML="",this.filterSuggestions(),this.resize()}),150)})),this.block.addEventListener("click",(e=>{e.target.closest(".node-delete")&&(e.preventDefault(),this.removeNodeByValue(e.target.closest(".node").dataset.value))})),this.block.querySelectorAll(".keyword-button").forEach((e=>{e.addEventListener("click",(e=>{clearTimeout(this.blurTimeout),this.addNode(e.currentTarget.innerText,e.currentTarget)}))}))}}function fcn_resetSearchForm(e,t,n){n.forEach((e=>e.reset())),t.querySelectorAll("input, select").forEach((e=>{e.value=e.dataset.default??e.value})),t.querySelector(".search-form__current").innerHTML="",fcn_showNotification(e.dataset.reset,2)}function fcn_handleTabInput(e){"Tab"==e.key&&(document.body.classList.add("user-is-tabbing"),window.removeEventListener("keydown",fcn_handleTabInput),window.addEventListener("mousedown",fcn_handleMouseInput))}function fcn_handleMouseInput(){document.body.classList.remove("user-is-tabbing"),window.removeEventListener("mousedown",fcn_handleMouseInput),window.addEventListener("keydown",fcn_handleTabInput)}function fcn_popupPosition(){_$$(".popup-menu-toggle.last-clicked .popup-menu:not(._fixed-position)").forEach((e=>{if("none"===window.getComputedStyle(e).display)return;const t=FcnUtils.detectScreenCollision(e);t&&0===t.length||(t.includes("top")?(e.classList.remove("_top"),e.classList.add("_bottom")):t.includes("bottom")&&(e.classList.remove("_bottom"),e.classList.add("_top")),e.closest("._fixed-horizontal")||(t.includes("left")?(e.classList.remove("_center","_justify-right"),e.classList.add("_justify-left")):t.includes("right")&&(e.classList.remove("_center","_justify-left"),e.classList.add("_justify-right"))))}))}function fcn_markCurrentMenuItem(){_$$(`.menu-item > [data-nav-object-id="${document.body.dataset.postId}"]`).forEach((e=>{e.setAttribute("aria-current","page"),e.closest(".menu-item").classList.add("current-menu-item")}))}function fcn_showAgeConfirmationModal(){const e=_$(".story__article, .chapter__article")?.dataset.ageRating;if(!document.documentElement.dataset.ageConfirmation&&e&&"adult"!==e)return void _$$$("age-confirmation-modal")?.remove();const t=_$$$("age-confirmation-leave");document.documentElement.classList.add("age-modal-open"),_$$$("age-confirmation-modal").hidden=!1,_$$$("age-confirmation-confirm")?.addEventListener("click",(e=>{document.documentElement.classList.remove("age-modal-open"),e.currentTarget.closest(".modal").remove(),localStorage.setItem("fcnAgeConfirmation","1")})),t?.addEventListener("click",(()=>{window.location.href=t.dataset.redirect??"https://search.brave.com/",localStorage.removeItem("fcnAgeConfirmation")}))} +_$$(".search-form").forEach((e=>{if(e.classList.contains("_simple"))return;const t=[];e.querySelectorAll(".keyword-input__input").forEach((e=>{t.push(new FCN_KeywordInput(e))})),e.querySelector(".allow-list")?.remove(),e.addEventListener("change",(t=>{t.target.classList.contains("search-form__advanced-control")||t.target.classList.contains("search-form__string")||(e.querySelector(".search-form__current").innerHTML="")})),e.querySelectorAll(".reset").forEach((n=>{n.addEventListener("click",(()=>{fcn_resetSearchForm(n,e,t)}))}))})),_$$(".search-form__advanced-toggle").forEach((e=>{e.addEventListener("click",(e=>{const t=e.currentTarget.closest("form");t.dataset.advanced="true"==t.dataset.advanced?"false":"true"}))})),window.addEventListener("keydown",fcn_handleTabInput),window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_popupPosition,250)),document.body.addEventListener("click",(e=>{const t=e.target.closest("[href]"),n=t?.getAttribute("href");if(!t||"A"===!t.tagName||!n.startsWith("#")||n.length<2||"#respond"===n)return;const s=n.replace("#",""),i=_$$(`[name="${s}"], [id="${s}"]`)[0],a=t.closest(".comment._story-comment");a&&(window.location.href=a.querySelector(".fictioneer-comment__link").href+n),i&&(e.preventDefault(),i.scrollIntoView({behavior:"smooth",block:t.dataset?.block??"start"}))})),fcn_markCurrentMenuItem(),_$$$("age-confirmation-modal")&&"1"!==localStorage.getItem("fcnAgeConfirmation")&&!FcnUtils.isSearchEngineCrawler()?fcn_showAgeConfirmationModal():_$$$("age-confirmation-modal")?.remove(),document.addEventListener("DOMContentLoaded",(()=>{_$$(".splide:not(.no-auto-splide, .is-initialized)").forEach((e=>{e.querySelector(".splide__list")&&"undefined"!=typeof Splide&&(e.classList.remove("_splide-placeholder"),new Splide(e).mount())})),_$$(".temp-script, .splide-placeholder-styles").forEach((e=>{e.remove()}))})),application.register("fictioneer-large-card",class extends Stimulus.Controller{static get targets(){return["controls","menu"]}static values={postId:Number,storyId:Number,chapterId:Number};initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#s(),this.#n=!0,this.#i()}))}connect(){if(window.FictioneerApp.Controllers.fictioneerLargeCard=this,this.#n&&(this.#s(),this.#i()),document.addEventListener("click",(e=>{e.target.closest(`.card.post-${this.postIdValue}`)||this.#a()})),document.addEventListener("toggledLastClick",(e=>{this.#o(e.detail.target,e.detail.force)})),this.hasMenuTarget)for(this.menuFragment=document.createDocumentFragment();this.menuTarget.firstChild;)this.menuFragment.appendChild(this.menuTarget.firstChild)}disconnect(){this.#c()}isFollowed(){return!(!this.#r()||!this.#l()?.follows?.data?.[this.storyIdValue])}isRemembered(){return!(!this.#r()||!this.#l()?.reminders?.data?.[this.storyIdValue])}isRead(){if(!this.#r())return!1;const e=this.#l()?.checkmarks?.data?.[this.storyIdValue];return!!e&&(e.includes(this.chapterIdValue)||e.includes(this.storyIdValue))}cardClick(e){e.target.closest(".card__controls")||this.#d()}toggleMenu(){this.menuTarget.querySelector("*")?this.#d():this.#u()}toggleFollow(){this.#r()?(fcn_toggleFollow(this.storyIdValue,!this.isFollowed()),this.#h()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleReminder(){this.#r()?(fcn_toggleReminder(this.storyIdValue,!this.isRemembered()),this.#g()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleCheckmarks(){this.#r()?(fcn_toggleCheckmark(this.storyIdValue,this.chapterIdValue),this.#f()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}setCheckmarks(e){this.toggleCheckmarks("set",e.params?.type??"story")}unsetCheckmarks(e){this.toggleCheckmarks("unset",e.params?.type??"story")}#m=!1;#n=!1;#_=!1;#r(){const e=FcnUtils.loggedIn();return e||(this.#c(),this.#n=!1,this.#_=!0),e}#l(){return this.userData=fcn().userData(),this.userData}#p(){return this.#r()&&JSON.stringify(this.userData??0)!==JSON.stringify(this.#l())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#_&&this.#p()&&this.#s()}),3e4+1e3*Math.random()))}#i(){this.#v(),this.visibilityStateCheck=()=>{this.#r()&&("visible"===document.visibilityState?(this.#_=!1,this.#s(),this.#v()):(this.#_=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#c(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}#s(){this.#h(),this.#g(),this.#f()}#h(){this.element.classList.toggle("has-follow",this.isFollowed())}#g(){this.element.classList.toggle("has-reminder",this.isRemembered())}#f(){this.element.classList.toggle("has-checkmark",this.isRead())}#a(){this.#d()}#u(){this.#m=!0,this.menuTarget.appendChild(this.menuFragment.cloneNode(!0))}#d(){if(this.#m)for(this.#m=!1;this.menuTarget.firstChild;)this.menuTarget.removeChild(this.menuTarget.firstChild)}#o(e,t){t?e&&!e.closest(`.card.post-${this.postIdValue}`)&&this.#m&&this.#d():this.#d()}}),application.register("fictioneer-last-click",class extends Stimulus.Controller{static get targets(){return["toggle"]}last=null;connect(){window.FictioneerApp.Controllers.fictioneerLastClick=this,document.addEventListener("fcnRemoveLastClicked",(()=>{this.last&&this.removeLastClick()}))}removeAll(){this.last&&(this.#b(this.last,!1),this.removeLastClick())}toggle(e){const t=e.target.closest('[data-fictioneer-last-click-target="toggle"]');if(!t||["BUTTON","A","INPUT","SELECT"].includes(e.target.tagName)&&!e.target.hasAttribute("data-fictioneer-last-click-target"))return;const n=!t.classList.contains("last-clicked");"function"==typeof fcn_popupPosition&&fcn_popupPosition(),t.classList.toggle("last-clicked",n),t.closest(".watch-last-clicked")?.classList.toggle("has-last-clicked",n),this.last&&this.last!=t&&this.removeLastClick(),this.last=t,this.#b(t,n),e.stopPropagation()}removeLastClick(){this.last&&(this.last.closest(".watch-last-clicked")?.classList.remove("has-last-clicked"),this.last.classList.remove("last-clicked"),this.last=null,document.activeElement?.blur())}#b(e,t){document.dispatchEvent(new CustomEvent("toggledLastClick",{detail:{target:e,force:t}}))}});const fcn_consentBanner=_$$$("consent-banner");function fcn_loadConsentBanner(){fcn_consentBanner.classList.remove("hidden"),fcn_consentBanner.hidden=!1,_$$$("consent-accept-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","full"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0})),_$$$("consent-reject-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","necessary"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0}))}function fcn_showLightbox(e){const t=_$$$("fictioneer-lightbox"),n=_$(".lightbox__content");let s=!1,i=null;if(n.innerHTML="",e.classList.add("lightbox-last-trigger"),"IMG"==e.tagName?(i=e.cloneNode(),s=!0):e.href&&(i=document.createElement("img"),i.src=e.href,s=!0),s&&i){["class","style","height","width"].forEach((e=>i.removeAttribute(e))),n.appendChild(i),t.classList.add("show");const e=t.querySelector(".lightbox__close");e?.focus(),e?.blur()}}fcn_consentBanner&&""===(FcnUtils.getCookie("fcn_cookie_consent")??"")&&!FcnUtils.isSearchEngineCrawler()?setTimeout((()=>{fcn_loadConsentBanner()}),4e3):fcn_consentBanner?.remove(),document.body.addEventListener("click",(e=>{const t=e.target.closest("[data-lightbox]:not(.no-auto-lightbox)");t&&(e.preventDefault(),fcn_showLightbox(t))})),document.body.addEventListener("keydown",(e=>{const t=e.target.closest("[data-lightbox]:not(.no-auto-lightbox)");t&&(" "!==e.key&&"Enter"!==e.key||(e.preventDefault(),fcn_showLightbox(t)))})),document.querySelectorAll(".lightbox__close, .lightbox").forEach((e=>{e.addEventListener("click",(e=>{if("IMG"!=e.target.tagName){_$$$("fictioneer-lightbox").classList.remove("show");const e=_$(".lightbox-last-trigger");e?.focus(),e?.blur(),e?.classList.remove("lightbox-last-trigger")}}))})); \ No newline at end of file diff --git a/js/complete.min.js b/js/complete.min.js index 00c8fee7..722d71cb 100644 --- a/js/complete.min.js +++ b/js/complete.min.js @@ -1,6 +1,6 @@ -const _$=document.querySelector.bind(document),_$$=document.querySelectorAll.bind(document),_$$$=document.getElementById.bind(document),FcnUtils={userData:()=>({lastLoaded:0,timestamp:0,loggedIn:"pending",follows:!1,reminders:!1,checkmarks:!1,bookmarks:null,likes:null,fingerprint:!1,nonceHtml:"",nonce:"",isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1,...FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{}}),resetUserData(){const t=FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{},e={lastLoaded:t.lastLoaded??0,timestamp:0,loggedIn:"pending",follows:!1,reminders:!1,checkmarks:!1,likes:null,bookmarks:null,fingerprint:!1,isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1};localStorage.setItem("fcnUserData",JSON.stringify({...t,...e}))},removeUserData(){localStorage.removeItem("fcnUserData")},setUserData(t){localStorage.setItem("fcnUserData",JSON.stringify(t))},loggedInCache:null,loggedInCacheTime:0,loggedIn(){const t=Date.now();return null!==FcnUtils.loggedInCache&&t-FcnUtils.loggedInCacheTime<20||(FcnUtils.loggedInCache=FcnUtils.hasLoginCookie(),FcnUtils.loggedInCacheTime=t),FcnUtils.loggedInCache},hasLoginCookie(){const t=document.cookie.split(";");for(let e=0;e{n&&n(t,e),t.success||(fcn_showNotification(t.data.failure??t.data.error??fictioneer_tl.notification.error,10,"warning"),(t.data.error||t.data.failure)&&console.error("Error:",t.data.error??t.data.failure))})).catch((t=>{429===t.status?fcn_showNotification(fictioneer_tl.notification.slowDown,3,"warning"):t.status&&t.statusText&&fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning"),a&&a(t,e),console.error(t)})).then((()=>{e?.classList.remove("ajax-in-progress"),s&&s(e)}))},parseJSON(t){if(null==t||"string"!=typeof t)return null;try{return JSON.parse(t)}catch(t){return null}},copyToClipboard(t,e=!1){e=e||fictioneer_tl.notification.copiedToClipboard,navigator.clipboard&&(navigator.clipboard.writeText(t),e&&fcn_showNotification(e,2))},clamp:(t,e,n)=>Math.min(Math.max(n,t),e),offset(t){const e=t.getBoundingClientRect();return{top:e.top+window.scrollY,left:e.left+window.scrollX}},throttle(t,e,n){var a,s,i,o=null,r=0;n||(n={});var c=function(){r=!1===n.leading?0:Date.now(),o=null,i=t.apply(a,s),o||(a=s=null)};return function(){var l=Date.now();r||!1!==n.leading||(r=l);var d=e-(l-r);return a=this,s=arguments,d<=0||d>e?(o&&(clearTimeout(o),o=null),r=l,i=t.apply(a,s),o||(a=s=null)):o||!1===n.trailing||(o=setTimeout(c,d)),i}},deleteCookie(t){document.cookie=t+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"},deleteAllCookies(){localStorage.clear(),document.cookie.split(";").forEach((t=>{document.cookie=t.replace(/^ +/,"").replace(/=.*/,"=;expires="+(new Date).toUTCString()+";path=/")}))},setCookie(t,e,n=30){const a=new Date;a.setTime(a.getTime()+24*n*60*60*1e3);const s="expires="+a.toUTCString();document.cookie=t+"="+encodeURIComponent(e)+";"+s+";SameSite=Strict;path=/"},getCookie(t){const e=t+"=",n=document.cookie.split(";");for(var a=0;a_$$$("fictioneer-ajax-nonce")?.value??_$$$("general-fictioneer-nonce")?.value??_$('[name="fictioneer_nonce"]')?.value??0,buildUrl:(t={},e=null)=>(e=e?new URL(e):new URL(window.location.protocol+"//"+window.location.host+window.location.pathname),t&&Object.keys(t).forEach((n=>{e.searchParams.append(n,t[n])})),e),buildErrorNotice(t,e=!1,n=!0){console.error("Error:",t);const a=document.createElement("div");let s=t;return e&&(a.id=e),a.classList="notice _warning","object"==typeof t&&(s="",t.status&&(s=`${t.status}: `),t.statusText&&(s+=t.statusText),s||(s="Unknown error.")),a.innerHTML=`
${n?FcnUtils.sanitizeHTML(s):s}
`,a},detectScreenCollision(t){const e=t.getBoundingClientRect(),n=window.innerHeight??document.documentElement.clientHeight,a=window.innerWidth??document.documentElement.clientWidth,s=(t.closest(".popup-menu-toggle")?.clientHeight??32)+16,i=n-e.bottom,o=[];return e.top<=50&&i>50+s&&o.push("top"),e.bottom>=n-50&&e.top>50+s&&o.push("bottom"),e.left<=10&&o.push("left"),e.right>=a-10&&o.push("right"),o},sanitizeHTML(t){const e=document.createElement("div");return e.innerText=t instanceof HTMLElement?t.innerHTML:t,e.textContent="string"==typeof t?t:t.textContent,e.innerHTML},scrollTo(t,e=64){window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-e,behavior:"smooth"})},html(...t){const e=document.createElement("template");return e.innerHTML=String.raw(...t).trim(),e.content.firstChild},toggleInProgress(t,e=null){(e=null!==e?e:!t.disabled)?(t.dataset.enableWith=t.innerHTML,t.innerHTML=t.dataset.disableWith??"Processing",t.disabled=!0,t.classList.add("disabled")):(t.innerHTML=t.dataset.enableWith,t.disabled=!1,t.classList.remove("disabled"))},adjustTextarea(t){t&&(t.style.height="auto",t.style.height=`${t.scrollHeight}px`)},isSearchEngineCrawler(){const t=navigator.userAgent.toLowerCase();return["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","sogou","exabot","facebot","ia_archiver"].some((e=>t.includes(e)))},removeArrayItemOnce(t,e){var n=t.indexOf(e);return n>-1&&t.splice(n,1),t},extractTextNodes:t=>Array.from(t.childNodes).filter((t=>t.nodeType===Node.TEXT_NODE)).map((t=>t.textContent.trim())).join(" "),appendToComment(t){const e=_$(FcnGlobals.commentFormSelector);if(e)switch(e.tagName){case"TEXTAREA":e.value+=t,FcnUtils.adjustTextarea(e);break;case"DIV":e.innerHTML+=t}else FcnGlobals.commentStack.push(t)}};async function fcn_ajaxPost(t={},e=null,n={}){e&&!e.startsWith("http")&&(e=FcnGlobals.restURL+e),e=e||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL);let a={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};a={...a,...n},t={nonce:FcnUtils.nonce(),...t};const s=await fetch(e,{method:"POST",credentials:"same-origin",headers:a,mode:"same-origin",body:new URLSearchParams(t)});return s.ok?s.json():Promise.reject(s)}async function fcn_ajaxGet(t={},e=null,n={}){e&&!e.startsWith("http")&&(e=FcnGlobals.restURL+e),e=e||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL),t={nonce:FcnUtils.nonce(),...t},e=FcnUtils.buildUrl(t,e);let a={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};a={...a,...n};const s=await fetch(e,{method:"GET",credentials:"same-origin",headers:a,mode:"same-origin"});return s.ok?s.json():Promise.reject(s)}const FcnGlobals={eSite:_$$$("site"),urlParams:Object.fromEntries(new URLSearchParams(window.location.search).entries()),pageLoadTimestamp:Date.now(),ajaxLimitThreshold:Date.now()-parseInt(fictioneer_ajax.ttl),ajaxURL:fictioneer_ajax.ajax_url,restURL:fictioneer_ajax.rest_url,ffcnrURL:fictioneer_ajax.ffcnr_url,ffcnrAuth:fictioneer_ajax.ffcnr_auth,debounceRate:fictioneer_ajax.post_debounce_rate,fonts:fictioneer_fonts??[],fontColors:fictioneer_font_colors??[],commentFormSelector:fictioneer_comments?.selector??"#comment",commentStack:[]};function fcn(){const t=window.FictioneerApp?.Controllers?.fictioneer;return t||{userData:FcnUtils.userData,setUserData:FcnUtils.setUserData,resetUserData:FcnUtils.resetUserData,removeUserData:FcnUtils.removeUserData}}function fcn_getUserData(){return FcnUtils.userData()}function fcn_setUserData(t){return FcnUtils.setUserData(t)}function fcn_cleanUpWebStorage(){["fcnBookshelfContent"].forEach((t=>localStorage.removeItem(t))),fcn().resetUserData()}function fcn_cleanUpGuestView(){document.body.classList.remove("logged-in","is-admin","is-moderator","is-editor","is-author"),_$$$("fictioneer-ajax-nonce")?.remove(),_$$(".only-moderators, .only-admins, .only-authors, .only-editors, .only-logged-in").forEach((t=>{t.remove()}))}function fcn_setLoggedInState(){const t=fcn().userData(),e=!0===t.loggedIn;document.body.classList.toggle("logged-in",e),document.body.classList.toggle("is-admin",t.isAdmin),document.body.classList.toggle("is-moderator",t.isModerator),document.body.classList.toggle("is-author",t.isAuthor),document.body.classList.toggle("is-editor",t.isEditor);const n=[];e&&(n.push('[data-fictioneer-id-param="login-modal"]'),n.push("#login-modal")),t.isAdmin||(n.push(".only-admins"),t.isModerator||n.push(".only-moderators"),t.isAuthor||n.push(".only-authors"),t.isEditor||n.push(".only-editors")),_$$(n.join(", ")).forEach((t=>t.remove()))}function fcn_setAvatar(){const t=fcn().userData()?.avatarUrl;t&&_$$('[data-fictioneer-target="avatarWrapper"]').forEach((e=>{const n=document.createElement("img");n.classList.add("user-profile-image"),n.src=t,e.firstChild.remove(),e.appendChild(n)}))}Object.freeze(FcnGlobals),window.FictioneerApp=window.FictioneerApp||{},window.FictioneerApp.Controllers=window.FictioneerApp.Controllers||{},application.register("fictioneer",class extends Stimulus.Controller{static get targets(){return["avatarWrapper","modal","mobileMenuToggle"]}static values={fingerprint:String,ageConfirmation:{type:Boolean,default:!1},ajaxAuth:{type:Boolean,default:!1},ajaxSubmit:{type:Boolean,default:!1},cachingActive:{type:Boolean,default:!1},publicCaching:{type:Boolean,default:!1},forceChildTheme:{type:Boolean,default:!1},editTime:{type:Number,default:15}};userReady=!1;lastModalToggle=null;currentModal=null;initialize(){if(FcnUtils.loggedIn()||this.ajaxAuthValue)this.fetchUserData();else{fcn_cleanUpWebStorage();const t=new CustomEvent("fcnUserDataReady",{detail:{data:this.userData(),time:new Date,loggedOut:!0},bubbles:!0,cancelable:!1});document.dispatchEvent(t)}}connect(){window.FictioneerApp.Controllers.fictioneer=this}userData(){return FcnUtils.userData()}setUserData(t){FcnUtils.setUserData(t)}resetUserData(){FcnUtils.resetUserData()}removeUserData(){FcnUtils.removeUserData()}fetchUserData(){let t=this.userData();if(FcnUtils.loggedIn()&&!1===t.loggedIn&&(this.removeUserData(),t=this.userData()),FcnGlobals.ajaxLimitThreshold{if(e.success){let n=this.userData();n=e.data,n.lastLoaded=Date.now(),this.setUserData(n),fcn_setAvatar(),t.nonceHtml&&this.#t(t.nonceHtml);const a=new CustomEvent("fcnUserDataReady",{detail:{data:e.data,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(a)}else{const t=this.userData();t.lastLoaded=Date.now(),t.loggedIn=!1,this.setUserData(t);const n=new CustomEvent("fcnUserDataFailed",{detail:{data:e,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(n)}this.userReady=!0})).catch((t=>{localStorage.removeItem("fcnUserData");const e=new CustomEvent("fcnUserDataError",{detail:{error:t,time:new Date},bubbles:!0,cancelable:!1});document.dispatchEvent(e)}))}copyInput(t){t.currentTarget.select(),FcnUtils.copyToClipboard(t.currentTarget.value,t.currentTarget.dataset.message)}clearConsent(t){FcnUtils.toggleInProgress(t.currentTarget),FcnUtils.deleteCookie("fcn_cookie_consent"),location.reload()}clearCookies(t){const e=t.currentTarget;if(!FcnUtils.loggedIn())return fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),void alert(e.dataset.message);FcnUtils.toggleInProgress(e),FcnUtils.aGet({action:"fictioneer_ajax_clear_cookies",nonce:FcnUtils.nonce()}).then((t=>{t.success?(fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),alert(t.data.success)):t.data.error&&(alert(t.data.failure),console.error("Error:",t.data.error))})).catch((t=>{alert(t),console.error(t)})).then((()=>{FcnUtils.toggleInProgress(e)}))}logout(){fcn_cleanUpWebStorage()}toggleObfuscation(t){t.target.closest('[data-fictioneer-target="obfuscated"]').classList.toggle("_obfuscated")}bodyClick(t){let e;this.dispatch("bodyClick",{detail:{event:t,target:t.target}}),(e=t.target.closest(".page-numbers.dots:not(button)"))?this.#e(e):(e=t.target.closest(".spoiler"))&&e.classList.toggle("_open")}toggleChapterGroup(t){const e=t.currentTarget.closest(".chapter-group"),n=e.querySelector(".chapter-group__list"),a=!e.classList.contains("_closed");n.addEventListener("transitionend",(()=>{n.style.height="",n.querySelectorAll("a, button, label, input:not([hidden])").forEach((t=>{t.tabIndex=n.parentElement.classList.contains("_closed")?"-1":"0"})),_$(".main__background")?.classList.remove("will-change")}),{once:!0}),_$(".main__background")?.classList.add("will-change"),n.style.height=`${n.scrollHeight}px`,requestAnimationFrame((()=>{requestAnimationFrame((()=>{e.classList.toggle("_closed",a),n.style.height=a?"0":`${n.scrollHeight}px`}))}))}toggleModal(t){t.preventDefault(),this.toggleModalVisibility(t.currentTarget,t.params.id)}toggleModalVisibility(t,e){const n=_$$$(e);if(n)if(this.currentModal!==n&&this.closeModals(),this.lastModalToggle=t,n.hidden=!n.hidden,n.hidden)this.closeModals();else{const t=n.querySelector(".close");t?.focus(),t?.blur()}}closeModals(){this.hasModalTarget&&this.modalTargets.forEach((t=>{t.hidden=!0})),this.lastModalToggle&&(this.lastModalToggle?.focus(),this.lastModalToggle?.blur(),this.lastModalToggle.null)}backgroundCloseModals({target:t}){t.classList.contains("modal")&&this.closeModals()}toggleMobileMenu(t){t.preventDefault();const e=window.FictioneerApp.Controllers.fictioneerMobileMenu;e&&e.toggle()}#t(t){_$$$("fictioneer-ajax-nonce")?.remove(),document.body.appendChild(FcnUtils.html`${t}`)}#e(t){if(document.documentElement.dataset.disablePageJump)return;const e=parseInt(window.prompt(fictioneer_tl.notification.enterPageNumber));if(e>0){const n=t.nextElementSibling.getAttribute("href"),a=["page=","paged=","comment-page-","pg="];for(const t of a)if(n.includes(t))return void(window.location.href=n.replace(new RegExp(`${t}\\d+`),t+e));window.location.href=n.replace(/page\/\d+/,`page/${e}`)}}}),"function"==typeof fcn_removeQueryArgs&&fcn_removeQueryArgs(),document.addEventListener("fcnUserDataReady",(()=>{fcn().userData().loggedIn||(fcn_cleanUpWebStorage(),fcn_cleanUpGuestView())})),_$("#wp-admin-bar-logout a")?.addEventListener("click",(()=>{fcn_cleanUpWebStorage()})),_$$(".subscriber-login, .oauth-login-link, [data-prepare-login]").forEach((t=>{t.addEventListener("click",(()=>{fcn().removeUserData()}))})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setLoggedInState()})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setAvatar()}));var fcn_animFrameEvents=new Map;function fcn_bindEventToAnimationFrame(t,e,n=window){n.addEventListener(t,(function(){fcn_animFrameEvents.get(e)||(fcn_animFrameEvents.set(e,!0),requestAnimationFrame((()=>{n.dispatchEvent(new CustomEvent(e)),fcn_animFrameEvents.set(e,!1)})))}))}function fcn_loadEmbed(t){t.target.parentNode.querySelectorAll("iframe, script")[0].src=t.target.dataset.src,t.target.parentElement.querySelector(".embed-logo")?.remove(),t.target.remove()}function fcn_appendTermMenu(t,e){const n=_$$$(`term-submenu-${t}`);if(!n)return;const a=n.content.cloneNode(!0);e.classList.add("menu-item-has-children"),e.querySelector('[href="#"]').addEventListener("click",(t=>{t.preventDefault()})),e.appendChild(a)}fcn_bindEventToAnimationFrame("scroll","scroll.rAF"),fcn_bindEventToAnimationFrame("resize","resize.rAF"),document.body.addEventListener("change",(t=>{const e=t.target.closest('[type="checkbox"]');if(!e)return;const n=e.name,a=n?_$$(`label[for="${n}"]`):[],s=e.checked;e.closest("[aria-checked]")?.setAttribute("aria-checked",s),a.forEach((t=>{t.closest("[aria-checked]")?.setAttribute("aria-checked",s)}))})),_$$(".iframe-consent, .twitter-consent").forEach((t=>{t.onclick=t=>{fcn_loadEmbed(t)}})),document.addEventListener("DOMContentLoaded",(()=>{const t=_$("#menu-navigation > .menu-item"),e=_$$$("full-navigation");t&&e&&t.offsetHeight{fcn_appendTermMenu("category",t)})),_$$(".main-navigation .trigger-term-menu-tags").forEach((t=>{fcn_appendTermMenu("post_tag",t)})),_$$(".main-navigation .trigger-term-menu-genres").forEach((t=>{fcn_appendTermMenu("fcn_genre",t)})),_$$(".main-navigation .trigger-term-menu-fandoms").forEach((t=>{fcn_appendTermMenu("fcn_fandom",t)})),_$$(".main-navigation .trigger-term-menu-characters").forEach((t=>{fcn_appendTermMenu("fcn_character",t)})),_$$(".main-navigation .trigger-term-menu-warnings").forEach((t=>{fcn_appendTermMenu("fcn_content_warning",t)}))})),_$$$("full-navigation")?.addEventListener("mouseover",(()=>{document.dispatchEvent(new CustomEvent("fcnRemoveLastClicked"))}));var fcn_lastScrollTop=0;function fcn_scrollDirection(){if(FcnGlobals.eSite.classList.contains("transformed-scroll"))return;const t="hidden"!==window.getComputedStyle(document.documentElement).overflow?window.scrollY??document.documentElement.scrollTop:document.body.scrollTop??1;document.body.classList.toggle("scrolled-to-top",0===t),t>fcn_lastScrollTop&&Math.abs(fcn_lastScrollTop-t)>=10?(document.body.classList.add("scrolling-down"),document.body.classList.remove("scrolling-up"),fcn_lastScrollTop=Math.max(t,0)):t=50&&(document.body.classList.add("scrolling-up"),document.body.classList.remove("scrolling-down"),fcn_lastScrollTop=Math.max(t,0))}function fcn_observe(t,e,n={}){const a=_$(t);if(!a)return null;new IntersectionObserver((t=>e(t[0])),n).observe(a)}function fcn_dragElement(t){const e=t.querySelector(".drag-anchor")??t;let n,a;function s(e){e.preventDefault(),t.style.top=t.offsetTop-(a-e.clientY)+"px",t.style.left=t.offsetLeft-(n-e.clientX)+"px",n=e.clientX,a=e.clientY}function i(){e.onmouseup=null,e.onmousemove=null}e.onmousedown=function(t){t.preventDefault(),n=t.clientX,a=t.clientY,e.onmousemove=s,e.onmouseup=i}}function fcn_showNotification(t,e=3,n="base"){const a=_$("#notifications"),s=document.createElement("div");s.innerHTML=t,s.classList.add("notifications__message",`_${n}`),s.style.opacity=1,s.style.transitionDelay=`${e}s`,a.prepend(s),s.addEventListener("transitionend",(t=>{"opacity"===t.propertyName&&a.removeChild(t.target)})),s.addEventListener("click",(t=>{a.removeChild(t.currentTarget)})),setTimeout((()=>{s.style.opacity=0}),100)}if(window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_scrollDirection,200)),fcn_scrollDirection(),document.addEventListener("DOMContentLoaded",(()=>{fcn_observe(".main-observer",(t=>{document.body.classList.toggle("is-inside-main",t.intersectionRatio<1&&t.boundingClientRect.top<=0)}),{threshold:[1]}),fcn_observe(".chapter-end",(t=>{document.body.classList.toggle("is-end-of-chapter",t.isIntersecting||t.boundingClientRect.top<0)}),{root:null,threshold:0}),fcn_observe("#nav-observer-sticky",(t=>{_$$$("full-navigation").classList.toggle("is-sticky",t.intersectionRatio<1)}),{threshold:[1]})})),_$$(".modal__header.drag-anchor").forEach((t=>{fcn_dragElement(t.closest(".modal__wrapper"))})),FcnGlobals.urlParams){switch(FcnGlobals.urlParams.failure&&console.error("Failure:",FcnGlobals.urlParams.failure),FcnGlobals.urlParams.failure){case"oauth_email_taken":fcn_showNotification(fictioneer_tl.notification.oauthEmailTaken,5,"warning");break;case"oauth_already_linked":fcn_showNotification(fictioneer_tl.notification.oauthAccountAlreadyLinked,5,"warning")}if("oauth_new"===FcnGlobals.urlParams.success)fcn_showNotification(fictioneer_tl.notification.oauthNew,10);else FcnGlobals.urlParams.success?.startsWith("oauth_merged_")&&fcn_showNotification(fictioneer_tl.notification.oauthAccountLinked,3,"success");if(FcnGlobals.urlParams["fictioneer-notice"]){let t="1"===FcnGlobals.urlParams.failure?"warning":"base";t="1"===FcnGlobals.urlParams.success?"success":t,fcn_showNotification(FcnUtils.sanitizeHTML(FcnGlobals.urlParams["fictioneer-notice"]),3,t)}}function fcn_updateThemeColor(t=null){const e=fcn_siteSettings.darken?fcn_siteSettings.darken:0,n=fcn_siteSettings.saturation?fcn_siteSettings.saturation:0,a=fcn_siteSettings["hue-rotate"]?fcn_siteSettings["hue-rotate"]:0,s=e>=0?1+e**2:1-e**2,i=n>=0?1+n**2:1-n**2;let o=getComputedStyle(document.documentElement).getPropertyValue("--theme-color-base").trim().split(" ");o=`hsl(${(parseInt(o[0])+a)%360}deg ${(parseInt(o[1])*i).toFixed(2)}% ${(parseInt(o[2])*s).toFixed(2)}%)`,_$("meta[name=theme-color]").setAttribute("content",t??o)}const fcn_settingHueRotateRange=_$$$("site-setting-hue-rotate-range"),fcn_settingHueRotateText=_$$$("site-setting-hue-rotate-text"),fcn_settingHueRotateReset=_$$$("site-setting-hue-rotate-reset"),fcn_settingDarkenRanges=_$$(".setting-darken-range"),fcn_settingDarkenTexts=_$$(".setting-darken-text"),fcn_settingDarkenResets=_$$(".setting-darken-reset"),fcn_settingSaturationRanges=_$$(".setting-saturation-range"),fcn_settingSaturationTexts=_$$(".setting-saturation-text"),fcn_settingSaturationResets=_$$(".setting-saturation-reset"),fcn_settingFontLightnessRanges=_$$(".setting-font-lightness-range"),fcn_settingFontLightnessTexts=_$$(".setting-font-lightness-text"),fcn_settingFontLightnessResets=_$$(".setting-font-lightness-reset"),fcn_settingEvents=["nav-sticky","background-textures","polygons","covers","taxonomies","text-shadows","minimal","chapter-progress-bar"];var fcn_siteSettings=fcn_getSiteSettings();function fcn_updateSiteSetting(t,e,n){t.checked=n,fcn_siteSettings[e]=n,fcn_applySiteSettings(fcn_siteSettings)}function fcn_toggleLightMode(){fcn_setLightMode(!(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault))}function fcn_setLightMode(t,e=!1){localStorage.setItem("fcnLightmode",t),document.documentElement.dataset.mode=t?"light":"dark",_$$(".toggle-light-mode").forEach((e=>{e.closest("[aria-checked]")?.setAttribute("aria-checked",t)})),e||fcn_updateThemeColor()}function fcn_updateFontWeight(){const t="default"!=fcn_siteSettings["font-weight"];_$$(".site-setting-font-weight").forEach((t=>{t.value=fcn_siteSettings["font-weight"]})),_$$(".font-weight-reset").forEach((e=>{e.classList.toggle("_modified",t)}))}function fcn_resetFontWeight(){fcn_siteSettings["font-weight"]="default",document.documentElement.dataset.fontWeight="default",fcn_applySiteSettings(fcn_siteSettings)}function fcn_updateHueRotate(t){t=FcnUtils.clamp(0,360,t??0),fcn_settingHueRotateText.value=t,fcn_settingHueRotateRange.value=t,fcn_settingHueRotateReset.classList.toggle("_modified",0!=t),document.documentElement.style.setProperty("--hue-rotate",`(${t}deg + var(--hue-offset))`),fcn_siteSettings["hue-rotate"]=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setHueRotate(){fcn_updateHueRotate(this.value)}function fcn_updateDarken(t=null){t=FcnUtils.clamp(-1,1,t??fcn_siteSettings.darken),t=Math.round(100*(t+Number.EPSILON))/100,fcn_settingDarkenResets.forEach((e=>{e.classList.toggle("_modified",0!=t)})),fcn_settingDarkenRanges.forEach((e=>{e.value=t})),fcn_settingDarkenTexts.forEach((e=>{e.value=parseInt(100*t)}));const e=t>=0?1+t**2:1-t**2;document.documentElement.style.setProperty("--darken",`(${e} + var(--lightness-offset))`),fcn_siteSettings.darken=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setDarkenFromRange(){fcn_updateDarken(this.value)}function fcn_setDarkenFromText(){"-"!=this.value&&""!=this.value&&fcn_updateDarken((parseInt(this.value)??0)/100)}function fcn_updateSaturation(t=null){t=FcnUtils.clamp(-1,1,t??fcn_siteSettings.saturation),fcn_settingSaturationResets.forEach((e=>{e.classList.toggle("_modified",0!=t)})),fcn_settingSaturationRanges.forEach((e=>{e.value=t})),fcn_settingSaturationTexts.forEach((e=>{e.value=parseInt(100*t)}));const e=t>=0?1+t**2:1-t**2;document.documentElement.style.setProperty("--saturation",`(${e} + var(--saturation-offset))`),fcn_siteSettings.saturation=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setSaturationFromRange(){fcn_updateSaturation(this.value)}function fcn_setSaturationFromText(){"-"!=this.value&&""!=this.value&&fcn_updateSaturation((parseInt(this.value)??0)/100)}function fcn_updateFontLightness(t=null){t=FcnUtils.clamp(-1,1,t??fcn_siteSettings["font-lightness"]??1),fcn_settingFontLightnessResets.forEach((e=>{e.classList.toggle("_modified",0!=t)})),fcn_settingFontLightnessRanges.forEach((e=>{e.value=t})),fcn_settingFontLightnessTexts.forEach((e=>{e.value=parseInt(100*t)}));const e=t>=0?1+t**2:1-t**2;document.documentElement.style.setProperty("--font-lightness",`(${e} + var(--font-lightness-offset))`),fcn_siteSettings["font-lightness"]=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setFontLightnessFromRange(){fcn_updateFontLightness(this.value)}function fcn_setFontLightnessFromText(){"-"!=this.value&&""!=this.value&&fcn_updateFontLightness((parseInt(this.value)??0)/100)}function fcn_defaultSiteSettings(){return{"nav-sticky":!0,"background-textures":!0,polygons:!0,covers:!0,taxonomies:!0,"text-shadows":!1,minimal:!1,"chapter-progress-bar":!0,"site-theme":"default","font-weight":"default",darken:0,saturation:0,"font-saturation":0,"font-lightness":0,"hue-rotate":0}}function fcn_getSiteSettings(){const t=FcnUtils.parseJSON(localStorage.getItem("fcnSiteSettings"))??fcn_defaultSiteSettings();return fcn_setSiteSettings(t),t}function fcn_setSiteSettings(t=null){"object"==typeof(t=t||fcn_siteSettings)&&(fcn_siteSettings=t,localStorage.setItem("fcnSiteSettings",JSON.stringify(t)))}function fcn_applySiteSettings(t){t="object"!=typeof t?fcn_defaultSiteSettings():t,Object.entries(t).forEach((t=>{const e=_$$$(`site-setting-${t[0]}`);switch(e&&(e.checked=t[1]),t[0]){case"minimal":document.documentElement.classList.toggle("minimal",t[1]);break;case"darken":fcn_updateDarken();break;case"saturation":fcn_updateSaturation();break;case"font-saturation":break;case"font-lightness":fcn_updateFontLightness();break;case"hue-rotate":fcn_updateHueRotate(t[1]);break;case"font-weight":fcn_updateFontWeight();break;default:document.documentElement.classList.toggle(`no-${t[0]}`,!t[1])}})),fcn_setSiteSettings(t)}function fcn_updateSiteTheme(t){fcn_siteSettings["site-theme"]=t,document.documentElement.dataset.theme=t,_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=t),fcn_applySiteSettings(fcn_siteSettings),fcn_updateThemeColor()}function fcn_resetSiteTheme(){fcn_updateSiteTheme("default"),_$$(".site-setting-site-theme").forEach((t=>{t.value="default"}))}function fcn_revealCommentImage(t){const e=t.parentElement.querySelector("img");e.src=e.dataset.src,t.remove()}function fcn_contactFormSubmit(t){const e=t.closest("form"),n=new FormData(e);if(!e.reportValidity())return;if(t.disabled=!0,t.innerHTML=t.dataset.disabled,Date.now(){n.success?(e.querySelector("textarea").value="",t.innerHTML=t.dataset.done,fcn_showNotification(n.data.success,3,"success")):n.data.failure&&(t.disabled=!1,t.innerHTML=t.dataset.enabled)},errorCallback:()=>{t.disabled=!1,t.innerHTML=t.dataset.enabled}})}fcn_settingEvents.forEach((t=>{_$$$(`site-setting-${t}`)?.addEventListener("change",(e=>{fcn_updateSiteSetting(e.currentTarget,t,e.currentTarget.checked)}))})),fcn_setLightMode(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault,!0),_$$(".toggle-light-mode").forEach((t=>{t.onclick=()=>fcn_toggleLightMode()})),_$$(".font-weight-reset").forEach((t=>{t.addEventListener("click",fcn_resetFontWeight)})),_$$(".site-setting-font-weight").forEach((t=>{t.onchange=t=>{fcn_siteSettings["font-weight"]=t.target.value,document.documentElement.dataset.fontWeight=t.target.value,fcn_applySiteSettings(fcn_siteSettings),fcn_updateFontWeight()}})),fcn_settingHueRotateReset?.addEventListener("click",(()=>{fcn_updateHueRotate(0)})),fcn_settingHueRotateRange?.addEventListener("input",FcnUtils.throttle(fcn_setHueRotate,1e3/24)),fcn_settingHueRotateText?.addEventListener("input",fcn_setHueRotate),fcn_settingDarkenResets.forEach((t=>{t.addEventListener("click",(()=>{fcn_updateDarken(0)}))})),fcn_settingDarkenRanges.forEach((t=>{t.addEventListener("input",FcnUtils.throttle(fcn_setDarkenFromRange,1e3/24))})),fcn_settingDarkenTexts.forEach((t=>{t.addEventListener("input",fcn_setDarkenFromText)})),fcn_settingSaturationResets.forEach((t=>{t.addEventListener("click",(()=>{fcn_updateSaturation(0)}))})),fcn_settingSaturationRanges.forEach((t=>{t.addEventListener("input",FcnUtils.throttle(fcn_setSaturationFromRange,1e3/24))})),fcn_settingSaturationTexts.forEach((t=>{t.addEventListener("input",fcn_setSaturationFromText)})),fcn_settingFontLightnessResets.forEach((t=>{t.addEventListener("click",(()=>{fcn_updateFontLightness(0)}))})),fcn_settingFontLightnessRanges.forEach((t=>{t.addEventListener("input",FcnUtils.throttle(fcn_setFontLightnessFromRange,1e3/24))})),fcn_settingFontLightnessTexts.forEach((t=>{t.addEventListener("input",fcn_setFontLightnessFromText)})),fcn_applySiteSettings(fcn_siteSettings),_$$(".site-setting-site-theme").forEach((t=>{t.value=fcn_siteSettings["site-theme"]?fcn_siteSettings["site-theme"]:"default",_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=t.value),t.addEventListener("change",(t=>{fcn_updateSiteTheme(t.target.value)}))})),_$$$("site-setting-theme-reset")?.addEventListener("click",fcn_resetSiteTheme),fcn_updateThemeColor(),_$(".fictioneer-comments")?.addEventListener("click",(t=>{t.target?.classList.contains("consent-button")&&fcn_revealCommentImage(t.target)})),_$$(".fcn-contact-form").forEach((t=>{t.querySelector(".fcn-contact-form__submit").addEventListener("click",(t=>{fcn_contactFormSubmit(t.currentTarget)}))})),_$$('[data-click-action*="open-dialog-modal"]').forEach((t=>{t.addEventListener("click",(t=>{document.querySelector(t.currentTarget.dataset.clickTarget).showModal()}))})),_$$('[data-click-action*="close-dialog-modal"], button[formmethod="dialog"][value="cancel"]').forEach((t=>{t.addEventListener("click",(t=>{t.preventDefault(),t.target.closest("dialog").close()}))})),_$$("dialog").forEach((t=>{t.addEventListener("mousedown",(e=>{if(e.target===e.currentTarget){const n=t.getBoundingClientRect();(e.clientXn.right||e.clientYn.bottom)&&(e.preventDefault(),e.target.close())}}))})),_$$(".content-section").forEach((t=>{t.addEventListener("click",(t=>{if(t.target.closest('[data-click-action*="open-tooltip-modal"]')&&!window.getSelection().toString()){const e=_$$$("fictioneer-tooltip-dialog"),n=t.target.dataset.dialogHeader,a=t.target.dataset.dialogContent;a.length>200?e.style.setProperty("--modal-width","400px"):e.style.removeProperty("--modal-width"),n&&(e.querySelector('[data-finder="tooltip-dialog-header"]').innerHTML=n),e.querySelector('[data-finder="tooltip-dialog-content"]').innerHTML=a,e.showModal()}}))})),document.body.addEventListener("keydown",(t=>{let e=document.activeElement.closest('[tabindex="0"]:not(a, input, button, select)');if(["BUTTON","A","INPUT","SELECT"].includes(document.activeElement.tagName)&&(e=null),e&&(" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),e.click())),"Escape"===t.key){_$$(".modal-toggle:checked").forEach((t=>{t.checked=!1,t.dispatchEvent(new Event("change"))}));const t=_$(".lightbox.show");if(t)return void t.querySelector(".lightbox__close").click() -;const e=_$(".selected-paragraph #button-close-paragraph-tools");if(e)return void e.click();const n=_$("#tts-interface:not(.hidden)");if(n){if(n.classList.contains("playing")){const t=_$$$("button-tts-pause");t?.click(),t?.focus(),t?.blur()}else _$$$("button-tts-stop").click();return}}}));class FCN_KeywordInput{constructor(t){this.input=t,this.type=t.dataset.type,this.operator=t.closest(".keyword-input").querySelector(".keyword-input__operator input"),this.inputWrapper=t.closest(".keyword-input__input-wrapper"),this.block=t.closest(".keyword-input"),this.form=this.block.closest(".search-form"),this.collection=this.block.querySelector(".keyword-input__collection"),this.suggestionList=this.block.querySelector(".keyword-input__suggestion-list"),this.tabSuggestion=this.block.querySelector(".keyword-input__tab-suggestion"),this.allowText=this.form.querySelector(".allow-list")?.innerText??"{}",this.allowList=FcnUtils.parseJSON(this.allowText),this.hints=this.block.querySelector(".keyword-input__hints"),this.noHint=this.block.querySelector(".keyword-input__no-suggestions"),this.keywords=this.collection.value.length>0?this.collection.value.split(","):[],this.bindEvents(),this.resize(),this.filterSuggestions()}resize(){const t=this.tabSuggestion.innerText.length>0?this.tabSuggestion.innerText.length:this.input.value.length;this.input.style.width=.88*t+2+"ch"}reset(){this.keywords=[],this.block.querySelectorAll(".node").forEach((t=>{t.remove()})),this.block.querySelectorAll(".keyword-input__operator > input").forEach((t=>{t.checked=!1})),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}encode(t){const e=(new TextEncoder).encode(t.toLowerCase());return btoa(String.fromCharCode.apply(null,e))}filterSuggestions(){const t=this.input.value.toLowerCase();let e=0,n="";""==t?this.suggestionList.querySelectorAll(".keyword-button").forEach((t=>{t.hidden=!0})):this.suggestionList.querySelectorAll(".keyword-button").forEach((a=>{const s=a.innerText.toLowerCase();s.includes(t)&&this.keywords.indexOf(s)<0?(a.hidden=!1,e++,""==n&&s.startsWith(t)&&(n=s)):a.hidden=!0})),this.hints.querySelectorAll(".keyword-button").forEach((t=>{this.keywords.indexOf(t.value.toLowerCase())>-1?t.hidden=!0:t.hidden=!1})),this.tabSuggestion.innerHTML=n,this.hints.hidden=!(""==t),this.noHint.hidden=!(""!=t&&e<1)}addNode(t=null,e=null){const n=t??this.input.value.replace(",","");let a=this.allowList[`${this.type}_${this.encode(n)}`];if("authors"!=this.collection.name&&"ex_authors"!=this.collection.name||!e||(a=this.allowList[`${this.type}_${this.encode(n)}_${e.value}`]),!a||this.keywords.indexOf(a)>-1)return;this.keywords.push(a);const s=document.createElement("div");s.innerHTML=`${n}`,s.classList.add("node"),s.dataset.value=a,this.inputWrapper.parentNode.insertBefore(s,this.inputWrapper),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}removeNodeByValue(t){this.block.querySelector(`[data-value="${t}"]`)?.remove(),this.keywords=this.keywords.filter((e=>e!=t)),this.updateCollection(),this.filterSuggestions(),this.resize()}updateCollection(){this.collection.value=this.keywords.join(","),this.block.classList.toggle("_empty",""===this.collection.value),this.form.querySelector(".search-form__current").innerHTML=""}bindEvents(){this.input.addEventListener("input",(t=>{t.currentTarget.value.includes(",")&&this.addNode(),this.block.classList.toggle("_empty",""===t.currentTarget.value&&""===this.collection.value),this.filterSuggestions(),this.resize()})),this.input.addEventListener("keydown",(t=>{"Tab"!==t.key&&"Enter"!==t.key||""!=this.tabSuggestion.innerText&&(t.preventDefault(),this.input.value=this.tabSuggestion.innerText,this.addNode()),"Escape"===t.key&&(this.input.value="",this.tabSuggestion.innerHTML="",document.activeElement.blur()),"Backspace"===t.key&&""==this.input.value&&this.keywords.length>0&&this.removeNodeByValue(this.keywords.slice(-1))})),this.input.addEventListener("blur",(()=>{const t=this.allowList[this.encode(this.input.value)];this.blurTimeout=t?setTimeout((()=>{this.addNode()}),150):setTimeout((()=>{this.input.value="",this.tabSuggestion.innerHTML="",this.filterSuggestions(),this.resize()}),150)})),this.block.addEventListener("click",(t=>{t.target.closest(".node-delete")&&(t.preventDefault(),this.removeNodeByValue(t.target.closest(".node").dataset.value))})),this.block.querySelectorAll(".keyword-button").forEach((t=>{t.addEventListener("click",(t=>{clearTimeout(this.blurTimeout),this.addNode(t.currentTarget.innerText,t.currentTarget)}))}))}}function fcn_resetSearchForm(t,e,n){n.forEach((t=>t.reset())),e.querySelectorAll("input, select").forEach((t=>{t.value=t.dataset.default??t.value})),e.querySelector(".search-form__current").innerHTML="",fcn_showNotification(t.dataset.reset,2)}function fcn_handleTabInput(t){"Tab"==t.key&&(document.body.classList.add("user-is-tabbing"),window.removeEventListener("keydown",fcn_handleTabInput),window.addEventListener("mousedown",fcn_handleMouseInput))}function fcn_handleMouseInput(){document.body.classList.remove("user-is-tabbing"),window.removeEventListener("mousedown",fcn_handleMouseInput),window.addEventListener("keydown",fcn_handleTabInput)}function fcn_popupPosition(){_$$(".popup-menu-toggle.last-clicked .popup-menu:not(._fixed-position)").forEach((t=>{if("none"===window.getComputedStyle(t).display)return;const e=FcnUtils.detectScreenCollision(t);e&&0===e.length||(e.includes("top")?(t.classList.remove("_top"),t.classList.add("_bottom")):e.includes("bottom")&&(t.classList.remove("_bottom"),t.classList.add("_top")),t.closest("._fixed-horizontal")||(e.includes("left")?(t.classList.remove("_center","_justify-right"),t.classList.add("_justify-left")):e.includes("right")&&(t.classList.remove("_center","_justify-left"),t.classList.add("_justify-right"))))}))}function fcn_markCurrentMenuItem(){_$$(`.menu-item > [data-nav-object-id="${document.body.dataset.postId}"]`).forEach((t=>{t.setAttribute("aria-current","page"),t.closest(".menu-item").classList.add("current-menu-item")}))}function fcn_showAgeConfirmationModal(){const t=_$(".story__article, .chapter__article")?.dataset.ageRating;if(!document.documentElement.dataset.ageConfirmation&&t&&"adult"!==t)return void _$$$("age-confirmation-modal")?.remove();const e=_$$$("age-confirmation-leave");document.documentElement.classList.add("age-modal-open"),_$$$("age-confirmation-modal").hidden=!1,_$$$("age-confirmation-confirm")?.addEventListener("click",(t=>{document.documentElement.classList.remove("age-modal-open"),t.currentTarget.closest(".modal").remove(),localStorage.setItem("fcnAgeConfirmation","1")})),e?.addEventListener("click",(()=>{window.location.href=e.dataset.redirect??"https://search.brave.com/",localStorage.removeItem("fcnAgeConfirmation")}))}_$$(".search-form").forEach((t=>{if(t.classList.contains("_simple"))return;const e=[];t.querySelectorAll(".keyword-input__input").forEach((t=>{e.push(new FCN_KeywordInput(t))})),t.querySelector(".allow-list")?.remove(),t.addEventListener("change",(e=>{e.target.classList.contains("search-form__advanced-control")||e.target.classList.contains("search-form__string")||(t.querySelector(".search-form__current").innerHTML="")})),t.querySelectorAll(".reset").forEach((n=>{n.addEventListener("click",(()=>{fcn_resetSearchForm(n,t,e)}))}))})),_$$(".search-form__advanced-toggle").forEach((t=>{t.addEventListener("click",(t=>{const e=t.currentTarget.closest("form");e.dataset.advanced="true"==e.dataset.advanced?"false":"true"}))})),window.addEventListener("keydown",fcn_handleTabInput),window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_popupPosition,250)),document.body.addEventListener("click",(t=>{const e=t.target.closest("[href]"),n=e?.getAttribute("href");if(!e||"A"===!e.tagName||!n.startsWith("#")||n.length<2||"#respond"===n)return;const a=n.replace("#",""),s=_$$(`[name="${a}"], [id="${a}"]`)[0],i=e.closest(".comment._story-comment");i&&(window.location.href=i.querySelector(".fictioneer-comment__link").href+n),s&&(t.preventDefault(),s.scrollIntoView({behavior:"smooth",block:e.dataset?.block??"start"}))})),fcn_markCurrentMenuItem(),_$$$("age-confirmation-modal")&&"1"!==localStorage.getItem("fcnAgeConfirmation")&&!FcnUtils.isSearchEngineCrawler()?fcn_showAgeConfirmationModal():_$$$("age-confirmation-modal")?.remove(),document.addEventListener("DOMContentLoaded",(()=>{_$$(".splide:not(.no-auto-splide, .is-initialized)").forEach((t=>{t.querySelector(".splide__list")&&"undefined"!=typeof Splide&&(t.classList.remove("_splide-placeholder"),new Splide(t).mount())})),_$$(".temp-script, .splide-placeholder-styles").forEach((t=>{t.remove()}))})),application.register("fictioneer-large-card",class extends Stimulus.Controller{static get targets(){return["controls","menu"]}static values={postId:Number,storyId:Number,chapterId:Number};initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#a(),this.#n=!0,this.#s()}))}connect(){if(window.FictioneerApp.Controllers.fictioneerLargeCard=this,this.#n&&(this.#a(),this.#s()),document.addEventListener("click",(t=>{t.target.closest(`.card.post-${this.postIdValue}`)||this.#i()})),document.addEventListener("toggledLastClick",(t=>{this.#o(t.detail.target,t.detail.force)})),this.hasMenuTarget)for(this.menuFragment=document.createDocumentFragment();this.menuTarget.firstChild;)this.menuFragment.appendChild(this.menuTarget.firstChild)}disconnect(){this.#r()}isFollowed(){return!(!this.#c()||!this.#l()?.follows?.data?.[this.storyIdValue])}isRemembered(){return!(!this.#c()||!this.#l()?.reminders?.data?.[this.storyIdValue])}isRead(){if(!this.#c())return!1;const t=this.#l()?.checkmarks?.data?.[this.storyIdValue];return!!t&&(t.includes(this.chapterIdValue)||t.includes(this.storyIdValue))}cardClick(t){t.target.closest(".card__controls")||this.#d()}toggleMenu(){this.menuTarget.querySelector("*")?this.#d():this.#h()}toggleFollow(){this.#c()?(fcn_toggleFollow(this.storyIdValue,!this.isFollowed()),this.#f()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleReminder(){this.#c()?(fcn_toggleReminder(this.storyIdValue,!this.isRemembered()),this.#g()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleCheckmarks(){this.#c()?(fcn_toggleCheckmark(this.storyIdValue,this.chapterIdValue),this.#u()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}setCheckmarks(t){this.toggleCheckmarks("set",t.params?.type??"story")}unsetCheckmarks(t){this.toggleCheckmarks("unset",t.params?.type??"story")}#m=!1;#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#n=!1,this.#p=!0),t}#l(){return this.userData=fcn().userData(),this.userData}#_(){return this.#c()&&JSON.stringify(this.userData??0)!==JSON.stringify(this.#l())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.#a()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.#a(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}#a(){this.#f(),this.#g(),this.#u()}#f(){this.element.classList.toggle("has-follow",this.isFollowed())}#g(){this.element.classList.toggle("has-reminder",this.isRemembered())}#u(){this.element.classList.toggle("has-checkmark",this.isRead())}#i(){this.#d()}#h(){this.#m=!0,this.menuTarget.appendChild(this.menuFragment.cloneNode(!0))}#d(){if(this.#m)for(this.#m=!1;this.menuTarget.firstChild;)this.menuTarget.removeChild(this.menuTarget.firstChild)}#o(t,e){e?t&&!t.closest(`.card.post-${this.postIdValue}`)&&this.#m&&this.#d():this.#d()}}),application.register("fictioneer-last-click",class extends Stimulus.Controller{static get targets(){return["toggle"]}last=null;connect(){window.FictioneerApp.Controllers.fictioneerLastClick=this,document.addEventListener("fcnRemoveLastClicked",(()=>{this.last&&this.removeLastClick()}))}removeAll(){this.last&&(this.#b(this.last,!1),this.removeLastClick())}toggle(t){const e=t.target.closest('[data-fictioneer-last-click-target="toggle"]');if(!e||["BUTTON","A","INPUT","SELECT"].includes(t.target.tagName)&&!t.target.hasAttribute("data-fictioneer-last-click-target"))return;const n=!e.classList.contains("last-clicked");"function"==typeof fcn_popupPosition&&fcn_popupPosition(),e.classList.toggle("last-clicked",n),e.closest(".watch-last-clicked")?.classList.toggle("has-last-clicked",n),this.last&&this.last!=e&&this.removeLastClick(),this.last=e,this.#b(e,n),t.stopPropagation()}removeLastClick(){this.last&&(this.last.closest(".watch-last-clicked")?.classList.remove("has-last-clicked"),this.last.classList.remove("last-clicked"),this.last=null,document.activeElement?.blur())}#b(t,e){document.dispatchEvent(new CustomEvent("toggledLastClick",{detail:{target:t,force:e}}))}});const fcn_consentBanner=_$$$("consent-banner");function fcn_loadConsentBanner(){fcn_consentBanner.classList.remove("hidden"),fcn_consentBanner.hidden=!1,_$$$("consent-accept-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","full"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0})),_$$$("consent-reject-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","necessary"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0}))}function fcn_showLightbox(t){const e=_$$$("fictioneer-lightbox"),n=_$(".lightbox__content");let a=!1,s=null;if(n.innerHTML="",t.classList.add("lightbox-last-trigger"),"IMG"==t.tagName?(s=t.cloneNode(),a=!0):t.href&&(s=document.createElement("img"),s.src=t.href,a=!0),a&&s){["class","style","height","width"].forEach((t=>s.removeAttribute(t))),n.appendChild(s),e.classList.add("show");const t=e.querySelector(".lightbox__close");t?.focus(),t?.blur()}}fcn_consentBanner&&""===(FcnUtils.getCookie("fcn_cookie_consent")??"")&&!FcnUtils.isSearchEngineCrawler()?setTimeout((()=>{fcn_loadConsentBanner()}),4e3):fcn_consentBanner?.remove(),document.body.addEventListener("click",(t=>{const e=t.target.closest("[data-lightbox]:not(.no-auto-lightbox)");e&&(t.preventDefault(),fcn_showLightbox(e))})),document.body.addEventListener("keydown",(t=>{const e=t.target.closest("[data-lightbox]:not(.no-auto-lightbox)");e&&(" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),fcn_showLightbox(e)))})),document.querySelectorAll(".lightbox__close, .lightbox").forEach((t=>{t.addEventListener("click",(t=>{if("IMG"!=t.target.tagName){_$$$("fictioneer-lightbox").classList.remove("show");const t=_$(".lightbox-last-trigger");t?.focus(),t?.blur(),t?.classList.remove("lightbox-last-trigger")}}))})),application.register("fictioneer-mobile-menu",class extends Stimulus.Controller{static get targets(){return["frame","bookmarks","panelBookmarks"]}advanced=!!_$(".mobile-menu._advanced-mobile-menu");open=!1;editingBookmarks=!1;currentFrame=null;bookmarkTemplate=_$$$("mobile-bookmark-template");chapterId=_$("article")?.id;connect(){window.FictioneerApp.Controllers.fictioneerMobileMenu=this}toggle(t=null){this.open=t??!this.open,this.advanced?this.#k(this.open):this.#F(this.open)}clickOutside({detail:{target:t}}){this.open&&"site"===t?.id&&this.toggle(!1)}openFrame({params:{frame:t}}){const e=`mobile-frame-${t}`;this.editingBookmarks=!1,this.panelBookmarksTarget.dataset.editing=!1,this.hasFrameTarget&&this.frameTargets.forEach((t=>{t.classList.toggle("_active",t.id===e),t.id===e&&(this.currentFrame=t)}))}back(){this.openFrame({params:{frame:"main"}})}setMobileBookmarks(){const t=window.FictioneerApp.Controllers.fictioneerBookmarks;if(t&&this.hasBookmarksTarget){const e=Object.entries(t.data());if(this.bookmarksTarget.innerHTML="",!e||e.length<1){const t=document.createElement("li");return t.classList.add("no-bookmarks"),t.textContent=this.bookmarksTarget.dataset.empty,void this.bookmarksTarget.appendChild(t)}const n=document.createDocumentFragment();e.forEach((([t,{color:e,progress:a,link:s,chapter:i,"paragraph-id":o}])=>{const r=this.bookmarkTemplate.content.cloneNode(!0),c=r.querySelector(".mobile-menu__bookmark");c.classList.add(`bookmark-${t}`),c.dataset.color=e,r.querySelector(".mobile-menu__bookmark-progress > div > div").style.width=`${a.toFixed(1)}%`,r.querySelector(".mobile-menu__bookmark a").href=`${s}#paragraph-${o}`,r.querySelector(".mobile-menu__bookmark a span").innerText=i,r.querySelector(".mobile-menu-bookmark-delete-button").setAttribute("data-fictioneer-mobile-menu-id-param",t),n.appendChild(r)})),this.bookmarksTarget.appendChild(n)}}deleteBookmark({params:{id:t}}){const e=window.FictioneerApp.Controllers.fictioneerBookmarks;e?(e.remove({params:{id:t}}),this.setMobileBookmarks()):fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning")}toggleBookmarksEdit(){this.editingBookmarks=!this.editingBookmarks,this.panelBookmarksTarget.dataset.editing=this.editingBookmarks}scrollToComments(){this.#w(_$$$("comments"))}scrollToBookmark(){const t=window.FictioneerApp.Controllers.fictioneerBookmarks;if(!t)return void fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning");const e=t.data()?.[this.chapterId]?.["paragraph-id"],n=_$(`[data-paragraph-id="${e}"]`);this.#w(n)}changeLightness({currentTarget:t}){fcn_updateDarken(fcn_siteSettings.darken+parseFloat(t.value))}#w(t){this.toggle(!1),t&&setTimeout((()=>{FcnUtils.scrollTo(t)}),200)}#F(t){this.back(),t?(document.body.classList.add("mobile-menu-open","scrolling-down"),document.body.classList.remove("scrolling-up")):document.body.classList.remove("mobile-menu-open")}#k(t){const e=_$$$("wpadminbar")?.offsetHeight??0,n=window.scrollY,a=FcnGlobals.eSite.scrollTop;this.back(),t?(document.body.classList.add("mobile-menu-open","scrolling-down","scrolled-to-top"),document.body.classList.remove("scrolling-up"),FcnGlobals.eSite.classList.add("transformed-scroll","transformed-site"),FcnGlobals.eSite.scrollTop=n-e):(FcnGlobals.eSite.classList.remove("transformed-site","transformed-scroll"),document.body.classList.remove("mobile-menu-open"),document.documentElement.style.scrollBehavior="auto",window.scroll(0,a+e),document.documentElement.style.scrollBehavior="")}}),application.register("fictioneer-chapter",class extends Stimulus.Controller{static get targets(){return["bookmarkScroll","contentWrapper","index","content"]}static values={chapterId:Number,storyId:Number};startClick=0;lastToolsParagraph=null;tools=_$$$("paragraph-tools");progressBar=_$(".progress__bar");hasPassword=!!_$("article._password");checkmarkUpdated=!1;checkboxProgressBar=_$$$("site-setting-chapter-progress-bar");checkboxMinimalist=_$$$("site-setting-minimal");initialize(){this.progressBar&&this.hasContentTarget&&!this.hasPassword&&(this.trackProgress(),window.addEventListener("scroll.rAF",FcnUtils.throttle(this.trackProgress.bind(this),1e3/48)))}connect(){window.FictioneerApp.Controllers.fictioneerChapter=this,this.hasIndexTarget&&this.indexTargets.forEach((t=>{t.querySelector(`[data-id="${this.chapterIdValue}"]`)?.classList.add("current")}))}clickOutside({detail:{target:t}}){this.lastToolsParagraph&&!t.closest(".selected-paragraph")&&this.closeTools()}scrollToBookmark(){const t=window.FictioneerApp.Controllers.fictioneerBookmarks;if(!t)return void fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning");const e=t.data()?.[`ch-${this.chapterIdValue}`]?.["paragraph-id"];if(!e)return;const n=_$(`[data-paragraph-id="${e}"]`);n?.scrollIntoView({behavior:"smooth"})}openFullscreen(){document.documentElement.requestFullscreen?document.documentElement.requestFullscreen():document.documentElement.webkitRequestFullscreen&&document.documentElement.webkitRequestFullscreen()}closeFullscreen(){document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}toggleTools(t){this.lastToolsParagraph?.classList.remove("selected-paragraph"),this.lastToolsParagraph!==t?(this.lastToolsParagraph=t,t.classList.add("selected-paragraph"),t.append(this.tools)):this.closeTools()}closeTools(){this.lastToolsParagraph?.classList.remove("selected-paragraph"),this.lastToolsParagraph=null}fastClick(t){""==window.getSelection().toString()&&(this.startClick=Date.now(),document.addEventListener("mouseup",(()=>{Date.now()16&&n.replace(/\s/g,"").length){const t=Math.ceil(.25*n.length);let e=fictioneer_tl.partial.quoteFragmentPrefix,a=fictioneer_tl.partial.quoteFragmentSuffix;n.startsWith(s.substring(0,t+1))&&(e=""),n.endsWith(s.substring(s.length-t,s.length))&&(a=""),s=`${e}${n}${a}`}fcn_showNotification(fictioneer_tl.notification.quoteAppendedToComment),FcnUtils.appendToComment(`\n[quote]${s} ${a}[/quote]\n`)}toggleBookmark({target:t}){const e=window.FictioneerApp.Controllers.fictioneerBookmarks;e?(e.toggle(t.closest("p[data-paragraph-id]").dataset.paragraphId,t.closest("[data-color]")?.dataset.color??"none"),window.matchMedia("(min-width: 1024px)").matches&&this.closeTools()):fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning")}copyLink(t){const e=t.target.closest("p[data-paragraph-id]");e&&FcnUtils.copyToClipboard(`${location.protocol}//${location.host}${location.pathname}#${e.id}`,fictioneer_tl.notification.linkCopiedToClipboard)}toggleIndexOrder({currentTarget:t}){const e=t.closest(".chapter-index");e.dataset.order="asc"===e.dataset.order?"desc":"asc"}trackProgress(){if(!this.progressBar||!this.hasContentTarget||this.hasPassword||this.checkboxMinimalist.checked||!(this.checkboxProgressBar?.checked??1))return;const t=this.contentTarget.getBoundingClientRect(),e=t.height,n=e-t.bottom-Math.max(t.top,0)+window.innerHeight;let a=100*n/e;if(document.body.classList.toggle("hasProgressBar",!(a<0||n>e+500)),a=FcnUtils.clamp(0,100,a),this.progressBar.style.width=`${a}%`,!this.checkmarkUpdated&&this.storyIdValue&&a>=100&&FcnUtils.loggedIn()){if(this.checkmarkUpdated=!0,!this.chapterIdValue||"function"!=typeof fcn_toggleCheckmark)return;fcn_toggleCheckmark(this.storyIdValue,this.chapterIdValue,!0)}}#T(t){return!(t.classList.contains("spoiler")||!t.closest("p[data-paragraph-id]")?.textContent.trim().length||!t.closest("p")?.parentElement?.classList.contains("chapter-formatting")||t.closest(".popup-menu-toggle, .skip-tools, .tts-interface, .paragraph-tools__actions, .hidden, .inside-epub, a, button, label, input, textarea, select, option"))}});const fcn_chapterKeyboardNavigation=t=>{if(["INPUT","TEXTAREA","SELECT","OPTION"].includes(t.target.tagName)||t.target.isContentEditable)return;const e={ArrowLeft:"a.button._navigation._prev",ArrowRight:"a.button._navigation._next"};if(!e[t.code])return;const n=_$(e[t.code]);n?.href&&(window.location.href=`${n.href}#start`)};if(document.addEventListener("keydown",fcn_chapterKeyboardNavigation),"#start"===window.location.hash){history.replaceState(null,document.title,window.location.pathname);const t=_$(".chapter__article");t&&FcnUtils.scrollTo(t,128)}const FcnFormatting={eFormattingTarget:_$(".chapter-formatting"),defaults:()=>({"font-saturation":0,"font-color":FcnGlobals.fontColors[0].css,"font-name":FcnGlobals.fonts[0].css,"font-size":100,"letter-spacing":0,"line-height":1.7,"paragraph-spacing":1.5,"site-width":document.documentElement.dataset.siteWidthDefault??"960",indent:!0,"show-sensitive-content":!0,"show-chapter-notes":!0,justify:!1,"show-comments":!0,"show-paragraph-tools":!0,timestamp:1664797604825,...FcnUtils.parseJSON(document.documentElement.dataset.defaultFormatting??"{}")}),get(){let t=FcnUtils.parseJSON(localStorage.getItem("fcnChapterFormatting"))??FcnFormatting.defaults();return Object.keys(t).length<15&&(t=FcnFormatting.defaults(),FcnFormatting.set(t)),t.timestamp<1651164557584&&(t=FcnFormatting.defaults(),t.timestamp=Date.now(),FcnFormatting.set(t)),t},set(t){"object"==typeof t&&localStorage.setItem("fcnChapterFormatting",JSON.stringify(t))}};function fcn_updateToggle(t,e,n,a={}){const s=FcnFormatting.get();a={save:!0,...a};const i=Boolean(t),o=_$(e);if(o&&(o.checked=i,o.closest("label").setAttribute("aria-checked",i)),a.toggleClass&&FcnFormatting.eFormattingTarget.classList.toggle(a.toggleClass,a.invertClass?!i:i),a.sensitiveContent){const t=_$$$("inline-sensitive-content-toggle");t?.classList.toggle("hide-sensitive",!i),t?.setAttribute("aria-checked",!i)}a.notes&&_$$(".chapter-note-hideable").forEach((t=>{t.classList.toggle("hidden",!i)})),a.comments&&_$$(".chapter-comments-hideable").forEach((t=>{t.classList.toggle("hidden",!i)})),s[n]=i,a.save&&FcnFormatting.set(s)}(()=>{"use strict";const t=_$$$("reader-settings-font-size-text"),e=_$$$("reader-settings-font-size-range"),n=_$$$("reader-settings-font-size-reset");if(!n)return;function a(a,s=!0){const i=FcnFormatting.get();a=FcnUtils.clamp(50,200,a??100),t.value=a,e.value=a,n.classList.toggle("_modified",100!=a),_$$(".resize-font").forEach((t=>{t.style.fontSize=`${a}%`})),i["font-size"]=a,s&&FcnFormatting.set(i)}function s(){a(this.value)}function i(){const t=FcnFormatting.get();a(parseFloat(t["font-size"])+parseFloat(this.dataset.modifier))}_$$$("reset-font")?.addEventListener("click",(()=>{a(100)})),n?.addEventListener("click",(()=>{a(100)})),e?.addEventListener("input",FcnUtils.throttle(s,1e3/24)),t?.addEventListener("input",s),_$$$("increase-font")?.addEventListener("click",i),_$$$("decrease-font")?.addEventListener("click",i);a(FcnFormatting.get()["font-size"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-font-color-reset"),e=_$$$("reader-settings-font-color-select");if(!t)return;function n(n,a=!0){const s=FcnFormatting.get();n=FcnUtils.clamp(0,FcnGlobals.fontColors.length-1,n),t.classList.toggle("_modified",n>0),e.value=n,FcnFormatting.eFormattingTarget.style.setProperty("--text-chapter",FcnGlobals.fontColors[n].css),s["font-color"]=FcnGlobals.fontColors[n].css,a&&FcnFormatting.set(s)}t.onclick=()=>{n(0)},e.onchange=t=>{n(t.target.value)},_$$(".font-color-stepper").forEach((t=>{t.addEventListener("click",(t=>{!function(t=1){let a=(e.selectedIndex+parseInt(t))%FcnGlobals.fontColors.length;a=a<0?FcnGlobals.fontColors.length-1:a,n(a)}(t.currentTarget.value)}))}));const a=FcnFormatting.get();n(FcnGlobals.fontColors.findIndex((t=>t.css==a["font-color"])),!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-font-reset"),e=_$$$("reader-settings-font-select");if(!t)return;function n(a,s=!0){const i=FcnFormatting.get();a=FcnUtils.clamp(0,FcnGlobals.fonts.length-1,a);let o=FcnGlobals.fonts[a].css;FcnGlobals.fonts[a].alt&&(o=`${o}, ${FcnGlobals.fonts[a].alt}`),a<0?n(0):(t.classList.toggle("_modified",a>0),e.value=a,_$$(".chapter-font-family").forEach((t=>{t.style.fontFamily=""===o?"var(--ff-system)":o+", var(--ff-system)"})),i["font-name"]=FcnGlobals.fonts[a].css,s&&FcnFormatting.set(i))}t.onclick=()=>{n(0)},e.onchange=t=>{n(t.target.value)},_$$(".font-stepper").forEach((t=>{t.addEventListener("click",(t=>{!function(t=1){let a=(e.selectedIndex+parseInt(t))%FcnGlobals.fonts.length;a=a<0?FcnGlobals.fonts.length-1:a,n(a)}(t.currentTarget.value)}))}));const a=FcnFormatting.get();n(FcnGlobals.fonts.findIndex((t=>t.css==a["font-name"])),!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-font-saturation-text"),e=_$$$("reader-settings-font-saturation-range"),n=_$$$("reader-settings-font-saturation-reset");if(!n)return;function a(a,s=!0){const i=FcnFormatting.get();a=FcnUtils.clamp(-1,1,a??0),t.value=parseInt(100*a),e.value=a,n.classList.toggle("_modified",0!=a),FcnFormatting.eFormattingTarget.style.setProperty("--font-saturation",`(${a>=0?1+a**2:1-a**2} + var(--font-saturation-offset))`),i["font-saturation"]=a,s&&FcnFormatting.set(i)}n?.addEventListener("click",(()=>{a(0)})),e?.addEventListener("input",FcnUtils.throttle((function(){a(this.value)}),1e3/24)),t?.addEventListener("input",(function(){a(parseInt(this.value)/100)}));a(FcnFormatting.get()["font-saturation"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-letter-spacing-text"),e=_$$$("reader-settings-letter-spacing-range"),n=_$$$("reader-settings-letter-spacing-reset"),a=FcnFormatting.defaults()["letter-spacing"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get();s=FcnUtils.clamp(-.1,.2,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),FcnFormatting.eFormattingTarget.style.letterSpacing=`calc(${s}em + var(--font-letter-spacing-base))`,o["letter-spacing"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["letter-spacing"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-paragraph-spacing-text"),e=_$$$("reader-settings-paragraph-spacing-range"),n=_$$$("reader-settings-paragraph-spacing-reset"),a=FcnFormatting.defaults()["paragraph-spacing"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get();s=FcnUtils.clamp(0,3,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),FcnFormatting.eFormattingTarget.style.setProperty("--paragraph-spacing",`${s}em`),o["paragraph-spacing"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["paragraph-spacing"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-line-height-text"),e=_$$$("reader-settings-line-height-range"),n=_$$$("reader-settings-line-height-reset"),a=FcnFormatting.defaults()["line-height"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get();s=FcnUtils.clamp(.8,3,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),FcnFormatting.eFormattingTarget.style.lineHeight=`${s}`,o["line-height"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["line-height"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-site-width-text"),e=_$$$("reader-settings-site-width-range"),n=_$$$("reader-settings-site-width-reset"),a=FcnFormatting.defaults()["site-width"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get(),r=_$("main");s=FcnUtils.clamp(640,1920,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),r.style.setProperty("--site-width",`${s}px`),r.classList.toggle("_default-width",s==document.documentElement.dataset.siteWidthDefault),r.classList.toggle("_below-1024",s<1024&&s>=768),r.classList.toggle("_below-768",s<768&&s>640),r.classList.toggle("_640-and-below",s<=640),o["site-width"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["site-width"],!1)})(),_$$("#reader-settings-indent-toggle").forEach((t=>{const e={invertClass:!0,toggleClass:"no-indent"},n="indent";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-justify-toggle").forEach((t=>{const e={toggleClass:"justify"},n="justify";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-paragraph-tools-toggle").forEach((t=>{const e="show-paragraph-tools";t.onclick=n=>{fcn_updateToggle(n.currentTarget.checked,`#${t.id}`,e)};fcn_updateToggle(FcnFormatting.get()[e],`#${t.id}`,e,{save:!1}) -})),_$$("#reader-settings-chapter-notes-toggle").forEach((t=>{const e={notes:!0},n="show-chapter-notes";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-comments-toggle").forEach((t=>{const e={comments:!0},n="show-comments";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-sensitive-content-toggle").forEach((t=>{const e={toggleClass:"hide-sensitive",invertClass:!0,sensitiveContent:!0},n="show-sensitive-content";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})}));var diff_match_patch=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},DIFF_DELETE=-1,DIFF_INSERT=1,DIFF_EQUAL=0;diff_match_patch.Diff=function(t,e){this[0]=t,this[1]=e},diff_match_patch.Diff.prototype.length=2,diff_match_patch.Diff.prototype.toString=function(){return this[0]+","+this[1]},diff_match_patch.prototype.diff_main=function(t,e,n,a){if(void 0===a&&(a=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout),null==t||null==e)throw Error("Null input. (diff_main)");if(t==e)return t?[new diff_match_patch.Diff(DIFF_EQUAL,t)]:[];void 0===n&&(n=!0);var s=n,i=this.diff_commonPrefix(t,e);n=t.substring(0,i),t=t.substring(i),e=e.substring(i),i=this.diff_commonSuffix(t,e);var o=t.substring(t.length-i);return t=t.substring(0,t.length-i),e=e.substring(0,e.length-i),t=this.diff_compute_(t,e,s,a),n&&t.unshift(new diff_match_patch.Diff(DIFF_EQUAL,n)),o&&t.push(new diff_match_patch.Diff(DIFF_EQUAL,o)),this.diff_cleanupMerge(t),t},diff_match_patch.prototype.diff_compute_=function(t,e,n,a){if(!t)return[new diff_match_patch.Diff(DIFF_INSERT,e)];if(!e)return[new diff_match_patch.Diff(DIFF_DELETE,t)];var s=t.length>e.length?t:e,i=t.length>e.length?e:t,o=s.indexOf(i);return-1!=o?(n=[new diff_match_patch.Diff(DIFF_INSERT,s.substring(0,o)),new diff_match_patch.Diff(DIFF_EQUAL,i),new diff_match_patch.Diff(DIFF_INSERT,s.substring(o+i.length))],t.length>e.length&&(n[0][0]=n[2][0]=DIFF_DELETE),n):1==i.length?[new diff_match_patch.Diff(DIFF_DELETE,t),new diff_match_patch.Diff(DIFF_INSERT,e)]:(s=this.diff_halfMatch_(t,e))?(e=s[1],i=s[3],t=s[4],s=this.diff_main(s[0],s[2],n,a),n=this.diff_main(e,i,n,a),s.concat([new diff_match_patch.Diff(DIFF_EQUAL,t)],n)):n&&100n);m++){for(var p=-m+h;p<=m-f;p+=2){for(var _=i+p,v=p==-m||p!=m&&r[_-1]a)f+=2;else if(b>s)h+=2;else if(d&&(0<=(_=i+l-p)&&_=k)return this.diff_bisectSplit_(t,e,v,b,n)}}for(p=-m+g;p<=m-u;p+=2){for(_=i+p,v=(k=p==-m||p!=m&&c[_-1]a)u+=2;else if(v>s)g+=2;else if(!d&&(0<=(_=i+l-p)&&_=(k=a-k))))return this.diff_bisectSplit_(t,e,v,b,n)}}return[new diff_match_patch.Diff(DIFF_DELETE,t),new diff_match_patch.Diff(DIFF_INSERT,e)]},diff_match_patch.prototype.diff_bisectSplit_=function(t,e,n,a,s){var i=t.substring(0,n),o=e.substring(0,a);return t=t.substring(n),e=e.substring(a),i=this.diff_main(i,o,!1,s),s=this.diff_main(t,e,!1,s),i.concat(s)},diff_match_patch.prototype.diff_linesToChars_=function(t,e){function n(t){for(var e="",n=0,o=-1,r=a.length;oa?t=t.substring(n-a):n=t.length?[a,s,o,r,d]:null}if(0>=this.Diff_Timeout)return null;var a=t.length>e.length?t:e,s=t.length>e.length?e:t;if(4>a.length||2*s.lengtha[4].length?o:a:o,t.length>e.length){a=o[0],s=o[1];var r=o[2],c=o[3]}else r=o[0],c=o[1],a=o[2],s=o[3];return[a,s,r,c,o[4]]},diff_match_patch.prototype.diff_cleanupSemantic=function(t){for(var e=!1,n=[],a=0,s=null,i=0,o=0,r=0,c=0,l=0;i=(s=this.diff_commonOverlap_(n,e))?(a>=e.length/2||a>=n.length/2)&&(t.splice(i,0,new diff_match_patch.Diff(DIFF_EQUAL,n.substring(0,a))),t[i-1][1]=e.substring(0,e.length-a),t[i+1][1]=n.substring(a),i++):(s>=e.length/2||s>=n.length/2)&&(t.splice(i,0,new diff_match_patch.Diff(DIFF_EQUAL,e.substring(0,s))),t[i-1][0]=DIFF_INSERT,t[i-1][1]=n.substring(0,n.length-s),t[i+1][0]=DIFF_DELETE,t[i+1][1]=e.substring(s),i++),i++),i++},diff_match_patch.prototype.diff_cleanupSemanticLossless=function(t){function e(t,e){if(!t||!e)return 6;var n=t.charAt(t.length-1),a=e.charAt(0),s=n.match(diff_match_patch.nonAlphaNumericRegex_),i=a.match(diff_match_patch.nonAlphaNumericRegex_),o=s&&n.match(diff_match_patch.whitespaceRegex_),r=i&&a.match(diff_match_patch.whitespaceRegex_);n=o&&n.match(diff_match_patch.linebreakRegex_),a=r&&a.match(diff_match_patch.linebreakRegex_);var c=n&&t.match(diff_match_patch.blanklineEndRegex_),l=a&&e.match(diff_match_patch.blanklineStartRegex_);return c||l?5:n||a?4:s&&!o&&r?3:o||r?2:s||i?1:0}for(var n=1;n=l&&(l=d,o=a,r=s,c=i)}t[n-1][1]!=o&&(o?t[n-1][1]=o:(t.splice(n-1,1),n--),t[n][1]=r,c?t[n+1][1]=c:(t.splice(n+1,1),n--))}n++}},diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/,diff_match_patch.whitespaceRegex_=/\s/,diff_match_patch.linebreakRegex_=/[\r\n]/,diff_match_patch.blanklineEndRegex_=/\n\r?\n$/,diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/,diff_match_patch.prototype.diff_cleanupEfficiency=function(t){for(var e=!1,n=[],a=0,s=null,i=0,o=!1,r=!1,c=!1,l=!1;ie));n++)i=a,o=s;return t.length!=n&&t[n][0]===DIFF_DELETE?o:o+(e-i)},diff_match_patch.prototype.diff_prettyHtml=function(t){for(var e=[],n=/&/g,a=//g,i=/\n/g,o=0;o");switch(r){case DIFF_INSERT:e[o]=''+c+"";break;case DIFF_DELETE:e[o]=''+c+"";break;case DIFF_EQUAL:e[o]=""+c+""}}return e.join("")},diff_match_patch.prototype.diff_text1=function(t){for(var e=[],n=0;nthis.Match_MaxBits)throw Error("Pattern too long for this browser.");var s=this.match_alphabet_(e),i=this,o=this.Match_Threshold,r=t.indexOf(e,n);-1!=r&&(o=Math.min(a(0,r),o),-1!=(r=t.lastIndexOf(e,n+e.length))&&(o=Math.min(a(0,r),o)));var c=1<=l;u--){var m=s[t.charAt(u-1)];if(d[u]=0===g?(d[u+1]<<1|1)&m:(d[u+1]<<1|1)&m|(h[u+1]|h[u])<<1|1|h[u+1],d[u]&c&&(m=a(g,u-1))<=o){if(o=m,!((r=u-1)>n))break;l=Math.max(1,2*n-r)}}if(a(g+1,n)>o)break;h=d}return r},diff_match_patch.prototype.match_alphabet_=function(t){for(var e={},n=0;n=2*this.Patch_Margin&&s&&(this.patch_addContext_(t,r),n.push(t),t=new diff_match_patch.patch_obj,s=0,r=a,i=o)}l!==DIFF_INSERT&&(i+=d.length),l!==DIFF_DELETE&&(o+=d.length)}return s&&(this.patch_addContext_(t,r),n.push(t)),n},diff_match_patch.prototype.patch_deepCopy=function(t){for(var e=[],n=0;nthis.Match_MaxBits){var l=this.match_main(e,r.substring(0,this.Match_MaxBits),o);-1!=l&&(-1==(c=this.match_main(e,r.substring(r.length-this.Match_MaxBits),o+r.length-this.Match_MaxBits))||l>=c)&&(l=-1)}else l=this.match_main(e,r,o);if(-1==l)s[i]=!1,a-=t[i].length2-t[i].length1;else if(s[i]=!0,a=l-o,r==(o=-1==c?e.substring(l,l+r.length):e.substring(l,c+this.Match_MaxBits)))e=e.substring(0,l)+this.diff_text2(t[i].diffs)+e.substring(l+r.length);else if(o=this.diff_main(r,o,!1),r.length>this.Match_MaxBits&&this.diff_levenshtein(o)/r.length>this.Patch_DeleteThreshold)s[i]=!1;else{var d;for(this.diff_cleanupSemanticLossless(o),r=0,c=0;cs[0][1].length){var i=e-s[0][1].length;s[0][1]=n.substring(s[0][1].length)+s[0][1],a.start1-=i,a.start2-=i,a.length1+=i,a.length2+=i}return 0==(s=(a=t[t.length-1]).diffs).length||s[s.length-1][0]!=DIFF_EQUAL?(s.push(new diff_match_patch.Diff(DIFF_EQUAL,n)),a.length1+=e,a.length2+=e):e>s[s.length-1][1].length&&(i=e-s[s.length-1][1].length,s[s.length-1][1]+=n.substring(0,i),a.length1+=i,a.length2+=i),n},diff_match_patch.prototype.patch_splitMax=function(t){for(var e=this.Match_MaxBits,n=0;n2*e?(r.length1+=l.length,s+=l.length,c=!1,r.diffs.push(new diff_match_patch.Diff(o,l)),a.diffs.shift()):(l=l.substring(0,e-r.length1-this.Patch_Margin),r.length1+=l.length,s+=l.length,o===DIFF_EQUAL?(r.length2+=l.length,i+=l.length):c=!1,r.diffs.push(new diff_match_patch.Diff(o,l)),l==a.diffs[0][1]?a.diffs.shift():a.diffs[0][1]=a.diffs[0][1].substring(l.length))}o=(o=this.diff_text2(r.diffs)).substring(o.length-this.Patch_Margin),""!==(l=this.diff_text1(a.diffs).substring(0,this.Patch_Margin))&&(r.length1+=l.length,r.length2+=l.length,0!==r.diffs.length&&r.diffs[r.diffs.length-1][0]===DIFF_EQUAL?r.diffs[r.diffs.length-1][1]+=l:r.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL,l))),c||t.splice(++n,0,r)}}},diff_match_patch.prototype.patch_toText=function(t){for(var e=[],n=0;n/g,i=/\n/g,o=0;o");switch(r){case 1:e[o]=`${c}`;break;case-1:e[o]=`${c}`;break;case 0:e[o]=`${c}`}}return e.join("")},application.register("fictioneer-suggestion",class extends Stimulus.Controller{modal=_$$$("suggestions-modal");floatingButton=_$$$("selection-tools");input=_$$$("suggestions-modal-input");current=_$$$("suggestions-modal-original");diff=_$$$("suggestions-modal-diff");reset=_$$$("button-suggestion-reset");submit=_$$$("button-suggestion-submit");original="";text="";open=!1;paragraph=null;dmp=new diff_match_patch;initialize(){this.floatingButton&&this.floatingButton.addEventListener("click",(t=>{this.toggleModalViaSelection(t.currentTarget)})),this.input.addEventListener("input",(()=>this.#E())),this.reset.addEventListener("click",(()=>this.#y())),this.submit.addEventListener("click",(()=>this.#$()))}connect(){window.FictioneerApp.Controllers.fictioneerSuggestion=this}clickOutside(){this.open&&this.#L()}toggleModalViaSelection(t){this.paragraph=this.#S(),this.toggleModalVisibility(t)}toggleModalViaParagraph(t){this.paragraph=_$(".selected-paragraph"),this.text=FcnUtils.extractTextNodes(this.paragraph),this.toggleModalVisibility(t.currentTarget)}toggleModalVisibility(t){const e=fcn(),n=window.FictioneerApp.Controllers.fictioneerChapter;e?n?(e.toggleModalVisibility(t,"suggestions-modal"),n.closeTools(),this.#C(),this.original=this.text,this.current.innerText=this.text,this.diff.innerText=this.text,this.input.value=this.text,this.input.focus()):fcn_showNotification("Error: Chapter Controller not connected.",3,"warning"):fcn_showNotification("Error: Fictioneer Controller not connected.",3,"warning")}toggleFloatingButton(){FcnGlobals.eSite.classList.contains("transformed-site")||window.getSelection().rangeCount<1||!window.getSelection().getRangeAt(0).startContainer.parentNode.closest(".content-section")||setTimeout((()=>{if(this.text=window.getSelection().toString().replaceAll("\n\n","\n").trim(),""!==this.text){const t=this.#I();this.#D(t.x,t.y)}else this.#L()}),10)}closeModal(){this.open=!1,this.original="",this.text="",this.paragraph=null,fcn().closeModals()}#D(t,e){this.open=!0;const n=document.documentElement.offsetWidth/2+this.floatingButton.offsetWidth,a=_$$$("wpadminbar")?.offsetHeight??0;this.floatingButton.style.transform=t>n?"translate(-100%)":"translate(0)",this.floatingButton.style.top=e+4-a+"px",this.floatingButton.style.left=`${t}px`,this.floatingButton.classList.remove("invisible")}#L(){this.open=!1,this.floatingButton.style.top="0",this.floatingButton.style.left="-1000px",this.floatingButton.classList.add("invisible")}#S(){const t=window.getSelection();return t.rangeCount?t.getRangeAt(0).startContainer.parentNode.closest("p"):null}#I(){let t=0,e=0;if(void 0!==window.getSelection){const n=window.getSelection();if(0!==n.rangeCount){let a=n.getRangeAt(0).cloneRange().getClientRects();a=a[a.length-1],a&&(t=a.right+window.scrollX,e=a.bottom+window.scrollY)}}return{x:t,y:e}}#C(){window.getSelection&&(window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges())}#E(){this.diff.innerHTML=this.#x(this.original,this.input.value)}#y(){this.input.value=this.original,this.diff.innerText=this.original}#x(t,e){const n=this.dmp.diff_main(t,e);return this.dmp.diff_cleanupEfficiency(n),this.dmp.fcn_prettyHtml(n)}#$(){const t=this.paragraph?.id??null;let e=this.diff.innerHTML;[["¶","¶\n"],["
","\n"],["","[ins]"],["","[/ins]"],["","[del]"],["","[/del]"]].forEach((([t,n])=>{e=e.replaceAll(t,n)})),t&&(e=`${e} [anchor]${t}[/anchor]`),FcnUtils.appendToComment(`\n[quote]${e}[/quote]\n`),this.closeModal(),fcn_showNotification(fictioneer_tl.notification.suggestionAppendedToComment)}});const fcn_ttsInterface=_$$$("tts-interface");var fcn_utter,fcn_synth,fcn_ttsStack=[],fcn_currentReadingId=-1,fcn_ttsPauseTimestamp=-1,fcn_ttsCurrentText="",fcn_ttsSettings=fcn_getTTSsettings(),fcn_voices=[];if("undefined"!=typeof speechSynthesis&&fcn_ttsInterface){fcn_synth=window.speechSynthesis,(fcn_utter=new SpeechSynthesisUtterance).lang=document.documentElement.lang;const t=setTimeout((()=>{fcn_setupTTS()}),2e3);"onvoiceschanged"in speechSynthesis&&fcn_synth.addEventListener("voiceschanged",(()=>{fcn_setupTTS(),clearTimeout(t)}),{once:!0})}function fcn_setupTTS(){fcn_voices.length>0||(fcn_setUpVoices(),fcn_updateVolume(fcn_ttsSettings.volume),fcn_updatePitch(fcn_ttsSettings.pitch),fcn_updateRate(fcn_ttsSettings.rate))}function fcn_setTTSsettings(t){fcn_ttsSettings=t,localStorage.setItem("ttsSettings",JSON.stringify(t))}function fcn_getTTSsettings(){const t=FcnUtils.parseJSON(localStorage.getItem("ttsSettings"))??{};return fcn_setTTSsettings(t),t}function fcn_setUpVoices(){const t=fcn_synth.getVoices(),e=_$$$("tts-voice-select");if(!e)return;let n=0;for(let a=0;a{fcn_updateVoice(t.currentTarget.value)})),fcn_updateVoice(fcn_ttsSettings.voice))}function fcn_updateVoice(t){if(isNaN(t)||void 0===fcn_voices[t]){let e=fcn_voices.findIndex((t=>"Samantha"===t.name&&("en-US"===t.lang||"en_US"===t.lang)));e<0&&(e=fcn_voices.findIndex((t=>"en-US"===t.lang||"en_US"===t.lang))),t=e>-1?e:0}fcn_utter.voice=fcn_voices[t],_$$$("tts-voice-select").value=t,fcn_ttsSettings.voice=t,fcn_setTTSsettings(fcn_ttsSettings)}function fcn_updateVolume(t){t=isNaN(t)?100:parseInt(t),t=FcnUtils.clamp(0,100,t),_$$$("tts-volume-range").value=t,_$$$("tts-volume-text").value=t,_$$$("tts-volume-reset").classList.toggle("_modified",100!=t),fcn_ttsSettings.volume=t,fcn_setTTSsettings(fcn_ttsSettings),fcn_utter.volume=t/100}function fcn_updatePitch(t){t=isNaN(t)?1:parseFloat(t),t=FcnUtils.clamp(.2,1.8,t),_$$$("tts-pitch-range").value=t,_$$$("tts-pitch-text").value=t,_$$$("tts-pitch-reset").classList.toggle("_modified",1!=t),fcn_ttsSettings.pitch=t,fcn_setTTSsettings(fcn_ttsSettings),fcn_utter.pitch=t}function fcn_updateRate(t){t=isNaN(t)?1:parseFloat(t),t=FcnUtils.clamp(.2,1.8,t),_$$$("tts-rate-range").value=t,_$$$("tts-rate-text").value=t,_$$$("tts-rate-reset").classList.toggle("_modified",1!=t),fcn_ttsSettings.rate=t,fcn_setTTSsettings(fcn_ttsSettings),fcn_utter.rate=t}function fcn_readTextStack(){const t=_$(".current-reading");if(0===fcn_ttsStack.length)return fcn_ttsInterface.classList.add("ended"),t&&t.classList.remove("current-reading"),fcn_currentReadingId=-1,void(fcn_ttsCurrentText="");const e=fcn_ttsStack.shift();fcn_ttsCurrentText=e[1],fcn_currentReadingId!=e[0]&&(fcn_currentReadingId=e[0],t&&t.classList.remove("current-reading"),_$$$(fcn_currentReadingId).classList.add("current-reading")),fcn_utter.text=fcn_ttsCurrentText,fcn_utter.addEventListener("end",fcn_readTextStack,{once:!0}),fcn_synth.speak(fcn_utter)}function fcn_cleanUpActions(){_$$(".story__actions > *").forEach((t=>{const e=window.getComputedStyle(t);"none"!==e.display&&"hidden"!==e.visibility||t.remove()}))}function fcn_unsetOauth(t){const e=prompt(t.dataset.warning);e&&e.toLowerCase()==t.dataset.confirm.toLowerCase()&&FcnUtils.remoteAction("fictioneer_ajax_unset_my_oauth",{nonce:t.dataset.nonce,element:_$$$(`oauth-${t.dataset.channel}`),payload:{channel:t.dataset.channel,id:t.dataset.id},callback:(t,e)=>{t.success?(e.classList.remove("_connected"),e.classList.add("_disconnected"),e.querySelector("button").remove(),fcn_showNotification(e.dataset.unset)):e.style.background="var(--notice-warning-background)"},errorCallback:(t,e)=>{e.style.background="var(--notice-warning-background)"}})}function fcn_deleteMyAccount(t){const e=prompt(t.dataset.warning);e&&e.toLowerCase()==t.dataset.confirm.toLowerCase()&&(t.disabled=!0,FcnUtils.remoteAction("fictioneer_ajax_delete_my_account",{nonce:t.dataset.nonce,element:t,payload:{id:t.dataset.id},callback:(t,e)=>{t.success?location.reload():e.innerHTML=t.data.button},errorCallback:(t,e)=>{e.innerHTML=t.status??fictioneer_tl.notification.error}}))}function fcn_dataDeletionPrompt(t){const e=prompt(t.dataset.warning);return!(!e||e.toLowerCase()!=t.dataset.confirm.toLowerCase())}function fcn_clearData(t,e){const n=t.closest(".card");localStorage.removeItem("fcnBookshelfContent"),t.remove(),FcnUtils.remoteAction(e,{nonce:t.dataset.nonce,element:n,callback:(t,e)=>{t.success&&e&&(e.querySelector(".card__content").innerHTML=t.data.success)}})}function fcn_toggleFollow(t,e=null){const n=window.FictioneerApp.Controllers.fictioneerFollows;if(!n)return void fcn_showNotification("Error: Follows Controller not connected.",3,"warning");const a=FcnUtils.userData();(e=e??!a.follows.data[t])?a.follows.data[t]={story_id:parseInt(t),timestamp:Date.now()}:delete a.follows.data[t],a.lastLoaded=0,FcnUtils.setUserData(a),n.refreshView(),clearTimeout(n.timeout),n.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_toggle_follow",{payload:{set:e,story_id:t}})}),FcnGlobals.debounceRate)}function fcn_toggleCheckmark(t,e=null,n=null){const a=window.FictioneerApp.Controllers.fictioneerCheckmarks;if(!a)return void fcn_showNotification("Error: Checkmarks Controller not connected.",3,"warning");const s=FcnUtils.userData();let i="story";if((t=parseInt(t??0))<1)return void fcn_showNotification("Error: Invalid story ID.",3,"warning");if(null!==e){if((e=parseInt(e))<1)return void fcn_showNotification("Error: Invalid chapter ID.",3,"warning");i="chapter"}s.checkmarks.data[t]||(s.checkmarks.data[t]=[]),null===n&&(n="chapter"===i?!s.checkmarks.data[t]?.includes(e):!s.checkmarks.data[t]?.includes(t));const o="chapter"===i?e:t;n?s.checkmarks.data[t].push(o):(FcnUtils.removeArrayItemOnce(s.checkmarks.data[t],o),"chapter"===i&&FcnUtils.removeArrayItemOnce(s.checkmarks.data[t],t)),s.checkmarks.data[t]=s.checkmarks.data[t].filter(((t,e,n)=>n.indexOf(t)==e)), -s.lastLoaded=0,FcnUtils.setUserData(s),a.refreshView(),clearTimeout(a.timeout),a.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_set_checkmark",{payload:{update:s.checkmarks.data[t].join(" "),story_id:t}})}),FcnGlobals.debounceRate)}function fcn_toggleReminder(t,e=null){const n=window.FictioneerApp.Controllers.fictioneerReminders;if(!n)return void fcn_showNotification("Error: Reminders Controller not connected.",3,"warning");const a=FcnUtils.userData();(e=e??!a.reminders.data[t])?a.reminders.data[t]={story_id:parseInt(t),timestamp:Date.now()}:delete a.reminders.data[t],a.lastLoaded=0,FcnUtils.setUserData(a),n.refreshView(),clearTimeout(n.timeout),n.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_toggle_reminder",{payload:{set:e,story_id:t}})}),FcnGlobals.debounceRate)}function fcn_wrapInTag(t,e,n={}){const a=n.href?' href="'+n.href+'" target="_blank" rel="nofollow noreferrer noopener"':"",s=n.shortcode?["[","]"]:["<",">"],i=t.selectionStart,o=t.selectionEnd,r=s[0]+e+a+s[1],c=s[0]+"/"+e+s[1],l=r+t.value.substring(i,o)+c;t.value=t.value.substring(0,i)+l+t.value.substring(o,t.value.length),t.setSelectionRange(i+r.length,o+r.length),t.focus()}"undefined"!=typeof speechSynthesis&&fcn_ttsInterface&&(_$$$("button-tts-set").addEventListener("click",(t=>{fcn_ttsStack=[],fcn_currentReadingId=-1;const e=_$(".chapter-formatting")?.classList.contains("hide-sensitive")??!1?"sensitive-content":"sensitive-alternative",n=_$$$("button-tts-play"),a=new RegExp(fcn_ttsInterface.dataset.regex,"gm");fcn_synth.speaking&&fcn_utter.removeEventListener("end",fcn_readTextStack),fcn_synth.cancel();const s=new Set(["P","H1","H2","H3","H4","H5","H6"]),i=["skip-tts","inside-epub",e];let o=t.target.closest("p[data-paragraph-id]");for(fcn_ttsStack.push(o);o=o.nextElementSibling;)s.has(o.tagName)&&!i.some((t=>o.classList.contains(t)))&&fcn_ttsStack.push(o);fcn_ttsStack=fcn_ttsStack.flatMap((t=>{const e=[],n=t.querySelector(".paragraph-inner");return(n?n.textContent:t.textContent).replace(a,"$1|").split("|").forEach((n=>{const a=n.trim();a.length>0&&e.push([t.id,a])})),e})),fcn_readTextStack(),document.body.classList.add("tts-open"),fcn_ttsInterface.classList.remove("hidden","ended","paused"),fcn_ttsInterface.classList.add("playing"),n.focus(),n.blur()})),_$$$("button-tts-stop")?.addEventListener("click",(()=>{const t=_$(".current-reading");fcn_ttsInterface.classList.add("hidden","ended"),fcn_ttsInterface.classList.remove("playing","paused"),document.body.classList.remove("tts-open"),t&&t.classList.remove("current-reading"),fcn_ttsStack=[],fcn_currentReadingId=-1,fcn_utter.removeEventListener("end",fcn_readTextStack),fcn_synth.cancel()})),_$$$("button-tts-play")?.addEventListener("click",(()=>{fcn_synth.resume(),-1!==fcn_ttsPauseTimestamp&&Date.now()-fcn_ttsPauseTimestamp>1e4&&(fcn_ttsStack.unshift([fcn_currentReadingId,fcn_ttsCurrentText]),fcn_synth.cancel(),fcn_readTextStack(),fcn_ttsPauseTimestamp=-1),fcn_ttsInterface.classList.add("playing"),fcn_ttsInterface.classList.remove("paused")})),_$$$("button-tts-pause")?.addEventListener("click",(()=>{fcn_synth.pause(),fcn_ttsPauseTimestamp=Date.now(),fcn_ttsInterface.classList.remove("playing"),fcn_ttsInterface.classList.add("paused")})),_$$$("button-tts-skip")?.addEventListener("click",(()=>{fcn_utter.removeEventListener("end",fcn_readTextStack),fcn_synth.cancel(),fcn_readTextStack(),fcn_ttsInterface.classList.remove("paused"),fcn_ttsInterface.classList.add("playing")})),_$$$("button-tts-scroll")?.addEventListener("click",(()=>{FcnUtils.scrollTo(_$(`p[id="${fcn_currentReadingId}"]`),128)})),_$$("#tts-volume-range, #tts-volume-text").forEach((t=>{t.addEventListener("input",(t=>{fcn_updateVolume(t.target.value)}))})),_$$$("tts-volume-reset")?.addEventListener("click",(()=>{fcn_updateVolume(100)})),_$$("#tts-pitch-range, #tts-pitch-text").forEach((t=>{t.addEventListener("input",(t=>{fcn_updatePitch(t.target.value)}))})),_$$$("tts-pitch-reset")?.addEventListener("click",(()=>{fcn_updatePitch(1)})),_$$("#tts-rate-range, #tts-rate-text").forEach((t=>{t.addEventListener("input",(t=>{fcn_updateRate(t.target.value)}))})),_$$$("tts-rate-reset")?.addEventListener("click",(()=>{fcn_updateRate(1)})),window.addEventListener("beforeunload",(()=>{fcn_synth.cancel()}))),application.register("fictioneer-story",class extends Stimulus.Controller{static get targets(){return["tab","tabContent","commentsPlaceholder","commentsWrapper","commentsList"]}static values={id:Number};commentPage=1;connect(){window.FictioneerApp.Controllers.fictioneerStory=this,this.#U()}toggleChapterOrder(){const t=this.#M();t.order="asc"===t.order?"desc":"asc",this.#A(t),this.#U()}toggleChapterView(){const t=this.#M();t.view="list"===t.view?"grid":"list",this.#A(t),this.#U()}unfoldChapters(t){const e=t.currentTarget.closest(".chapter-group[data-folded]");e&&(e.dataset.folded="true"==e.dataset.folded?"false":"true")}toggleTab(t){const e=t.currentTarget;this.tabTargets.forEach((t=>{t.classList.remove("_current")})),this.tabContentTargets.forEach((e=>{e.dataset.tabName===t.params.tabName?e.classList.add("_current"):e.classList.remove("_current")})),e.classList.add("_current")}loadComments(t){this.hasIdValue&&this.hasCommentsListTarget&&(t.currentTarget.remove(),this.hasCommentsPlaceholderTarget&&this.commentsPlaceholderTarget.classList.remove("hidden"),FcnUtils.aGet({post_id:this.idValue,page:this.commentPage},"get_story_comments").then((t=>{this.hasCommentsPlaceholderTarget&&this.commentsPlaceholderTarget.remove(),t.success?(this.commentsListTarget.innerHTML+=t.data.html,this.commentPage++):t.data?.error&&this.commentsListTarget.appendChild(FcnUtils.buildErrorNotice(t.data.error))})).catch((t=>{this.hasCommentsPlaceholderTarget&&this.commentsPlaceholderTarget.remove(),this.commentsListTarget.appendChild(FcnUtils.buildErrorNotice(t))})))}startEpubDownload(t){t.preventDefault(),this.#R(t.currentTarget,0)}#M(){let t=FcnUtils.parseJSON(localStorage.getItem("fcnStorySettings"))??this.#N();return t.timestamp<1674770712849&&(t=this.#N(),t.timestamp=Date.now()),this.#A(t),t}#N(){return{view:"list",order:"asc",timestamp:1674770712849}}#A(t){"object"==typeof t&&localStorage.setItem("fcnStorySettings",JSON.stringify(t))}#U(){const t=this.#M();"object"==typeof t&&(_$$("[data-view]").forEach((e=>{e.dataset.view=t.view})),_$$("[data-order]").forEach((e=>{e.dataset.order=t.order})))}#R(t,e=0){!t.classList.contains("ajax-in-progress")&&this.hasIdValue&&(e>3?t.classList.remove("ajax-in-progress"):(t.classList.add("ajax-in-progress"),FcnUtils.aGet({action:"fictioneer_ajax_download_epub",story_id:this.idValue}).then((n=>{n.success?(window.location.href=t.href,setTimeout((()=>{t.classList.remove("ajax-in-progress")}),2e3)):setTimeout((()=>{fcn_startEpubDownload(t,e+1)}),2e3)})).catch((e=>{t.classList.remove("ajax-in-progress"),e.status&&e.statusText&&fcn_showNotification(`${e.status}: ${e.statusText}`,5,"warning")}))))}}),document.addEventListener("fcnUserDataReady",(()=>{fcn_cleanUpActions()})),_$$(".button-unset-oauth").forEach((t=>{t.addEventListener("click",(t=>{fcn_unsetOauth(t.currentTarget)}))})),_$$$("button-delete-my-account")?.addEventListener("click",(t=>{fcn_deleteMyAccount(t.currentTarget)})),_$(".button-clear-comments")?.addEventListener("click",(t=>{fcn_dataDeletionPrompt(t.currentTarget)&&fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_comments")})),_$(".button-clear-comment-subscriptions")?.addEventListener("click",(t=>{fcn_dataDeletionPrompt(t.currentTarget)&&fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_comment_subscriptions")})),_$(".button-clear-checkmarks")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerCheckmarks;if(!e)return void fcn_showNotification("Error: Checkmarks Controller not connected.",3,"warning");e.clear(),fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_checkmarks",!0)}})),_$(".button-clear-reminders")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerReminders;if(!e)return void fcn_showNotification("Error: Reminders Controller not connected.",3,"warning");e.clear(),fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_reminders",!0)}})),_$(".button-clear-follows")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerFollows;if(!e)return void fcn_showNotification("Error: Follows Controller not connected.",3,"warning");e.clear(),fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_follows",!0)}})),_$(".button-clear-bookmarks")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerBookmarks,n=_$$$("profile-data-translations")?.dataset;if(!e)return void fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning");e.clear(),t.currentTarget.closest(".card").querySelector(".card__content").innerHTML=n.clearedSuccess}})),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.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#n=!0,this.refreshView(),this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerBookmarks=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.bookmarksCachedData=FcnUtils.loggedIn()?this.#j():this.#B(),this.#P(this.bookmarksCachedData).data}toggle(t,e="none"){if(!this.chapterId)return;const n=this.data(),a=n[this.chapterId];if(a&&a["paragraph-id"]==t)"none"!==e&&e!==a.color?n[this.chapterId].color=e:delete n[this.chapterId];else{Object.keys(n).length>=50&&delete n[Object.keys(n)[0]];const a=_$(`[data-paragraph-id="${t}"]`),s=_$$$("chapter-bookmark-data").dataset;n[this.chapterId]={"paragraph-id":t,progress:100*(FcnUtils.offset(a).top-FcnUtils.offset(a.parentElement).top)/a.parentElement.clientHeight,date:(new Date).toISOString(),color:e,chapter:s.title.trim(),link:s.link,thumb:s.thumb,image:s.image,story:s.storyTitle.trim(),content:FcnUtils.extractTextNodes(a).substring(0,128)+"…"}}this.set(n),this.refreshView()}remove({params:{id:t}}){const e=this.data();delete e[t],this.set(e),this.refreshView()}clear(){this.set({data:{}}),this.refreshView()}set(t){if("object"!=typeof t)return;t=this.#P({data:t});const e=JSON.stringify(t);if(FcnUtils.loggedIn()){const t=fcn().userData();t&&(t.bookmarks=e,fcn().setUserData(t)),this.#O(e),localStorage.removeItem("fcnChapterBookmarks")}else localStorage.setItem("fcnChapterBookmarks",e)}refreshView(){const t=this.data(),e=Object.keys(t).length;this.hasOverviewPageIconLinkTarget&&this.overviewPageIconLinkTargets.forEach((t=>{t.classList.toggle("hidden",e<1)})),this.refreshChapterBookmark(),this.refreshCards(),this.refreshProfile()}refreshCards(){if(!this.hasShortcodeBlockTarget)return;const t=this.data(),e=Object.keys(t).length<1;this.shortcodeBlockTargets.forEach((t=>{t.classList.toggle("hidden",e)})),_$$(".show-if-bookmarks").forEach((t=>{t.classList.toggle("hidden",e)})),this.hasNoBookmarksNoteTarget&&this.noBookmarksNoteTargets.forEach((t=>{t.classList.toggle("hidden",!e)})),!e&&this.cardTemplate?this.shortcodeBlockTargets.forEach((e=>{const n=e.querySelector("ul"),a=document.createDocumentFragment(),s=Object.entries(t).sort(((t,e)=>new Date(e[1].date)-new Date(t[1].date)));let i=parseInt(e.dataset.count)??8;s.forEach((([t,{color:e,progress:n,link:s,chapter:o,"paragraph-id":r,date:c,image:l,thumb:d,content:h}])=>{if(0==i--)return;const f=this.cardTemplate.content.cloneNode(!0),g=new Date(c).toLocaleDateString(navigator.language??"en-US",{year:"2-digit",month:"short",day:"numeric"});l&&f.querySelector(".bookmark-card__image")?(f.querySelector(".bookmark-card__image").href=l,f.querySelector(".bookmark-card__image img").src=d):f.querySelector(".bookmark-card__image")?.remove(),f.querySelector(".bookmark-card__excerpt").innerHTML+=h,f.querySelector(".bookmark-card").classList.add(`bookmark-${t}`),f.querySelector(".bookmark-card").dataset.color=e,f.querySelector(".bookmark-card__title > a").href=`${s}#paragraph-${r}`,f.querySelector(".bookmark-card__title > a").innerText=o,f.querySelector(".bookmark-card__percentage").innerText=`${n.toFixed(1)} %`,f.querySelector(".bookmark-card__progress").style.width=`calc(${n.toFixed(1)}% - var(--bookmark-progress-offset, 0px))`,f.querySelector("time").innerText=g,f.querySelector(".button-delete-bookmark").setAttribute("data-fictioneer-bookmarks-id-param",t),a.appendChild(f)})),n.innerHTML="",n.appendChild(a)})):this.shortcodeBlockTargets.forEach((t=>{t.querySelector("ul").innerHTML=""}))}refreshProfile(){this.hasDataCardTarget&&(this.dataCardTarget.innerHTML=this.dataCardTarget.innerHTML.replace("%s",Object.keys(this.data()).length))}refreshChapterBookmark(){const t=this.data();if(this.currentBookmark?.classList.remove("current-bookmark"),!this.chapterId||!t[this.chapterId])return;const e=t[this.chapterId]["paragraph-id"],n=_$(`[data-paragraph-id="${e}"]`),a=t[this.chapterId].color??"none";e&&n&&(n.classList.add("current-bookmark"),n.setAttribute("data-bookmark-color",a),this.currentBookmark=n,this.hasBookmarkScrollTarget&&this.bookmarkScrollTargets.forEach((t=>t.removeAttribute("hidden"))))}#n=!1;#p=!1;#B(){return FcnUtils.parseJSON(localStorage.getItem("fcnChapterBookmarks"))??{data:{}}}#j(){return FcnUtils.parseJSON(FcnUtils.userData()?.bookmarks)??{data:{}}}#P(t){if("object"!=typeof t||!("data"in t)||Array.isArray(t.data)&&0===t.data.length)return{data:{}};const e={};for(const n in t.data)if(n.startsWith("ch-")){const a=this.#H(t.data[n]);a&&(e[n]=a)}return{data:e}}#H(t){const e={},n={"paragraph-id":"",progress:0,date:"",color:"",chapter:"",link:"",thumb:"",image:"",story:"",content:""};for(const a in n){if(typeof t[a]!=typeof n[a])return null;e[a]=t[a]}const a=new Date(e.date);return a&&"[object Date]"===Object.prototype.toString.call(a)&&!isNaN(a)||(e.date=(new Date).toISOString()),("number"!=typeof e.progress||e.progress<0)&&(e.progress=0),e}#_(){return JSON.stringify(this.bookmarksCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{"visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null)},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#O(t){clearTimeout(this.timeout),this.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_save_bookmarks",{payload:{bookmarks:t}})}),FcnGlobals.debounceRate)}}),application.register("fictioneer-follows",class extends Stimulus.Controller{static get targets(){return["toggleButton","newDisplay","scrollList","mobileScrollList","mobileMarkRead"]}followsLoaded=!1;markedRead=!1;timeout=0;initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.refreshView(),this.#n=!0,this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerFollows=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.followsCachedData=FcnUtils.userData().follows?.data,Array.isArray(this.followsCachedData)&&0===this.followsCachedData.length&&(this.followsCachedData={}),this.followsCachedData}isFollowed(t){return!(!FcnUtils.loggedIn()||!this.data()?.[t])}unreadCount(){return parseInt(FcnUtils.userData()?.follows?.new??0)}toggleFollow({params:{id:t}}){this.#c()&&(fcn_toggleFollow(t,!this.isFollowed(t)),this.refreshView())}clear(){const t=FcnUtils.userData();t.follows={data:{}},fcn().setUserData(t),this.refreshView()}refreshView(){this.toggleButtonTargets.forEach((t=>{const e=t.dataset.storyId;t.classList.toggle("_followed",this.isFollowed(e))}));const t=this.unreadCount();this.newDisplayTargets.forEach((e=>{e.classList.toggle("_new",t>0),t>0&&(e.dataset.newCount=t,this.hasMobileMarkReadTarget&&this.mobileMarkReadTarget.classList.remove("hidden"))}))}loadFollowsHtml(){this.followsLoaded||FcnUtils.aGet({action:"fictioneer_ajax_get_follows_notifications",fcn_fast_ajax:1}).then((t=>{t.data.html&&(this.hasScrollListTarget&&(this.scrollListTarget.innerHTML=t.data.html),this.hasMobileScrollListTarget&&(this.mobileScrollListTarget.innerHTML=t.data.html),!1===FcnUtils.userData().loggedIn&&(fcn().removeUserData(),fcn().fetchUserData()))})).catch((t=>{429===t.status?fcn_showNotification(fictioneer_tl.notification.slowDown,3,"warning"):t.status&&t.statusText&&fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning"),this.hasScrollListTarget&&this.scrollListTarget.remove(),this.hasMobileScrollListTarget&&this.mobileScrollListTarget.remove()})).then((()=>{this.followsLoaded=!0,this.hasNewDisplayTarget&&this.newDisplayTargets.forEach((t=>{t.classList.add("_loaded")}))}))}markRead(){if(!this.followsLoaded&&this.unreadCount()>0||this.markedRead)return;this.markedRead=!0,this.newDisplayTargets.forEach((t=>{t.classList.remove("_new")})),this.hasMobileMarkReadTarget&&this.mobileMarkReadTarget.classList.add("hidden");const t=FcnUtils.userData();t.new=0,t.lastLoaded=0,FcnUtils.setUserData(t),FcnUtils.aPost({action:"fictioneer_ajax_mark_follows_read",fcn_fast_ajax:1}).catch((t=>{t.status&&t.statusText&&fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning")}))}#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#p=!0),t}#_(){return this.#c()&&JSON.stringify(this.followsCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}}),application.register("fictioneer-checkmarks",class extends Stimulus.Controller{static get targets(){return["chapterCheck","storyCheck","ribbon"]}timeout=0;initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.refreshView(),this.#n=!0,this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerCheckmarks=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.checkmarksCachedData=FcnUtils.userData().checkmarks?.data,Array.isArray(this.checkmarksCachedData)&&0===this.checkmarksCachedData.length&&(this.checkmarksCachedData={}),this.checkmarksCachedData}toggleChapter({params:{chapter:t,story:e}}){fcn_toggleCheckmark(e,t)}toggleStory({params:{story:t}}){fcn_toggleCheckmark(t)}clear(){const t=FcnUtils.userData();t.checkmarks={data:{},updated:Date.now()},fcn().setUserData(t),this.refreshView()}refreshView(){const t=this.data();!t||Object.keys(t).length<1?this.uncheckAll():Object.entries(t).forEach((([t,e])=>{t=parseInt(t);const n=e?.includes(t);this.hasChapterCheckTarget&&(n?this.chapterCheckTargets.forEach((t=>{t.classList.toggle("marked",!0),t.setAttribute("aria-checked",!0)})):this.chapterCheckTargets.forEach((n=>{const a=parseInt(n.dataset.fictioneerCheckmarksChapterParam);if(parseInt(n.dataset.fictioneerCheckmarksStoryParam)===t){const t=e?.includes(a);n.classList.toggle("marked",t),n.setAttribute("aria-checked",t)}}))),this.hasStoryCheckTarget&&(this.storyCheckTarget.classList.toggle("marked",n),this.storyCheckTarget.setAttribute("aria-checked",n)),this.hasRibbonTarget&&this.ribbonTarget.classList.toggle("hidden",!n)}))}uncheckAll(){this.hasChapterCheckTarget&&this.chapterCheckTargets.forEach((t=>{t.classList.toggle("marked",!1),t.setAttribute("aria-checked",!1)})),this.hasStoryCheckTarget&&(this.storyCheckTarget.classList.toggle("marked",!1),this.storyCheckTarget.setAttribute("aria-checked",!1))}#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#p=!0),t}#_(){return this.#c()&&JSON.stringify(this.checkmarksCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}}),application.register("fictioneer-reminders",class extends Stimulus.Controller{static get targets(){return["toggleButton"]}remindersLoaded=!1;timeout=0;initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.refreshView(),this.#n=!0,this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerReminders=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.remindersCachedData=FcnUtils.userData().reminders?.data,Array.isArray(this.remindersCachedData)&&0===this.remindersCachedData.length&&(this.remindersCachedData={}),this.remindersCachedData}isRemembered(t){return!(!FcnUtils.loggedIn()||!this.data()?.[t])}toggleReminder({params:{id:t}}){this.#c()&&(fcn_toggleReminder(t,!this.isRemembered(t)),this.refreshView())}clear(){const t=FcnUtils.userData();t.reminders={data:{}},fcn().setUserData(t),this.refreshView()}refreshView(){this.toggleButtonTargets.forEach((t=>{const e=t.dataset.storyId;t.classList.toggle("_remembered",this.isRemembered(e))}))}#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#p=!0),t}#_(){return this.#c()&&JSON.stringify(this.remindersCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}}),document.addEventListener("fcnUserDataReady",(()=>{fcn().userData().fingerprint==document.documentElement.dataset.authorFingerprint&&document.body.classList.add("is-post-author")}));const fcn_ajaxCommentForm=_$$$("ajax-comment-form-target");function fcn_setupCommentFormObserver(){const t=new IntersectionObserver((([e])=>{e.isIntersecting&&(fcn_getCommentForm(),t.disconnect())}),{rootMargin:"450px",threshold:1});t.observe(fcn_ajaxCommentForm)}function fcn_getCommentForm(){let t;FcnUtils.aGet({action:"fictioneer_ajax_get_comment_form",post_id:_$$$("comments").dataset.postId,fcn_fast_comment_ajax:1}).then((e=>{if(e.success){const t=document.createElement("div");t.innerHTML=e.data.html;const n=t.querySelector("#comment_post_ID"),a=t.querySelector("#cancel-comment-reply-link"),s=t.querySelector(".logout-link");n&&(n.value=e.data.postId),a&&(a.href="#respond"),s&&(s.href=_$$$("comments").dataset.logoutUrl),fcn_ajaxCommentForm.innerHTML=t.innerHTML,t.remove(),fcn_applyCommentStack(),_$$$("fictioneer-ajax-nonce")?.remove(),document.body.appendChild(FcnUtils.html`${e.data.nonceHtml}`)}else t=FcnUtils.buildErrorNotice(e.data.error)})).catch((e=>{t=FcnUtils.buildErrorNotice(e)})).then((()=>{fcn_ajaxCommentForm.classList.remove("comments-skeleton"),t&&(fcn_ajaxCommentForm.innerHTML="",fcn_ajaxCommentForm.appendChild(t))}))}function fcn_applyCommentStack(t=null){(t=t??_$(FcnGlobals.commentFormSelector))&&("TEXTAREA"==t.tagName?(FcnGlobals.commentStack.forEach((e=>{t.value+=e})),FcnUtils.adjustTextarea(t)):"DIV"==t.tagName&&FcnGlobals.commentStack.forEach((e=>{t.innerHTML+=e})),FcnGlobals.commentStack=[])}fcn_ajaxCommentForm&&document.addEventListener("fcnUserDataReady",(()=>{fcn_setupCommentFormObserver()})),application.register("fictioneer-comment-form",class extends Stimulus.Controller{static get targets(){return["submit","cancel","textarea","privateToggle","emailNotificationToggle","author","email","cookies","privacyPolicy"]}initialize(){this.respond=this.element.closest("#respond"),this.order=this.respond.closest(".fictioneer-comments")?.dataset.order??"desc",this.parent=this.element.querySelector("#comment_parent"),this.addJSTrap()}adjustTextarea(){FcnUtils.adjustTextarea(this.textareaTarget)}toolbarButtons(t){const e=t.target.closest("[data-bbcode]");e&&fcn_wrapInTag(this.textareaTarget,e.dataset.bbcode,{shortcode:!0})}keyComboCodes(t){if(_$(".fictioneer-comment-toolbar")&&"TEXTAREA"===document.activeElement.tagName&&(t.ctrlKey||t.metaKey)){const e=t.key.toLowerCase();if(["b","i","s","q","h","l"].includes(e)){t.preventDefault();const n={q:"quote",h:"spoiler",l:"link"};fcn_wrapInTag(document.activeElement,n[e]||e,{shortcode:!0})}}}addJSTrap(){this.element.appendChild(FcnUtils.html` +const _$=document.querySelector.bind(document),_$$=document.querySelectorAll.bind(document),_$$$=document.getElementById.bind(document),FcnUtils={userData:()=>({lastLoaded:0,timestamp:0,loggedIn:"pending",follows:!1,reminders:!1,checkmarks:!1,bookmarks:null,likes:null,fingerprint:!1,nonceHtml:"",nonce:"",isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1,...FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{}}),resetUserData(){const t=FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{},e={lastLoaded:t.lastLoaded??0,timestamp:0,loggedIn:(!FcnGlobals.ajaxAuth||!1!==t.loggedIn)&&"pending",follows:!1,reminders:!1,checkmarks:!1,likes:null,bookmarks:null,fingerprint:!1,isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1};localStorage.setItem("fcnUserData",JSON.stringify({...t,...e}))},removeUserData(){localStorage.removeItem("fcnUserData")},setUserData(t){localStorage.setItem("fcnUserData",JSON.stringify(t))},loggedInCache:null,loggedInCacheTime:0,loggedIn(){const t=Date.now();return null!==FcnUtils.loggedInCache&&t-FcnUtils.loggedInCacheTime<20||(FcnUtils.loggedInCache=FcnUtils.hasLoginCookie(),FcnUtils.loggedInCacheTime=t),FcnUtils.loggedInCache},hasLoginCookie(){const t=document.cookie.split(";");for(let e=0;e{n&&n(t,e),t.success||(fcn_showNotification(t.data.failure??t.data.error??fictioneer_tl.notification.error,10,"warning"),(t.data.error||t.data.failure)&&console.error("Error:",t.data.error??t.data.failure))})).catch((t=>{429===t.status?fcn_showNotification(fictioneer_tl.notification.slowDown,3,"warning"):t.status&&t.statusText&&fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning"),a&&a(t,e),console.error(t)})).then((()=>{e?.classList.remove("ajax-in-progress"),s&&s(e)}))},parseJSON(t){if(null==t||"string"!=typeof t)return null;try{return JSON.parse(t)}catch(t){return null}},copyToClipboard(t,e=!1){e=e||fictioneer_tl.notification.copiedToClipboard,navigator.clipboard&&(navigator.clipboard.writeText(t),e&&fcn_showNotification(e,2))},clamp:(t,e,n)=>Math.min(Math.max(n,t),e),offset(t){const e=t.getBoundingClientRect();return{top:e.top+window.scrollY,left:e.left+window.scrollX}},throttle(t,e,n){var a,s,i,o=null,r=0;n||(n={});var c=function(){r=!1===n.leading?0:Date.now(),o=null,i=t.apply(a,s),o||(a=s=null)};return function(){var l=Date.now();r||!1!==n.leading||(r=l);var d=e-(l-r);return a=this,s=arguments,d<=0||d>e?(o&&(clearTimeout(o),o=null),r=l,i=t.apply(a,s),o||(a=s=null)):o||!1===n.trailing||(o=setTimeout(c,d)),i}},deleteCookie(t){document.cookie=t+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"},deleteAllCookies(){localStorage.clear(),document.cookie.split(";").forEach((t=>{document.cookie=t.replace(/^ +/,"").replace(/=.*/,"=;expires="+(new Date).toUTCString()+";path=/")}))},setCookie(t,e,n=30){const a=new Date;a.setTime(a.getTime()+24*n*60*60*1e3);const s="expires="+a.toUTCString();document.cookie=t+"="+encodeURIComponent(e)+";"+s+";SameSite=Strict;path=/"},getCookie(t){const e=t+"=",n=document.cookie.split(";");for(var a=0;a_$$$("fictioneer-ajax-nonce")?.value??_$$$("general-fictioneer-nonce")?.value??_$('[name="fictioneer_nonce"]')?.value??0,buildUrl:(t={},e=null)=>(e=e?new URL(e):new URL(window.location.protocol+"//"+window.location.host+window.location.pathname),t&&Object.keys(t).forEach((n=>{e.searchParams.append(n,t[n])})),e),buildErrorNotice(t,e=!1,n=!0){console.error("Error:",t);const a=document.createElement("div");let s=t;return e&&(a.id=e),a.classList="notice _warning","object"==typeof t&&(s="",t.status&&(s=`${t.status}: `),t.statusText&&(s+=t.statusText),s||(s="Unknown error.")),a.innerHTML=`
${n?FcnUtils.sanitizeHTML(s):s}
`,a},detectScreenCollision(t){const e=t.getBoundingClientRect(),n=window.innerHeight??document.documentElement.clientHeight,a=window.innerWidth??document.documentElement.clientWidth,s=(t.closest(".popup-menu-toggle")?.clientHeight??32)+16,i=n-e.bottom,o=[];return e.top<=50&&i>50+s&&o.push("top"),e.bottom>=n-50&&e.top>50+s&&o.push("bottom"),e.left<=10&&o.push("left"),e.right>=a-10&&o.push("right"),o},sanitizeHTML(t){const e=document.createElement("div");return e.innerText=t instanceof HTMLElement?t.innerHTML:t,e.textContent="string"==typeof t?t:t.textContent,e.innerHTML},scrollTo(t,e=64){window.scrollTo({top:t.getBoundingClientRect().top+window.scrollY-e,behavior:"smooth"})},html(...t){const e=document.createElement("template");return e.innerHTML=String.raw(...t).trim(),e.content.firstChild},toggleInProgress(t,e=null){(e=null!==e?e:!t.disabled)?(t.dataset.enableWith=t.innerHTML,t.innerHTML=t.dataset.disableWith??"Processing",t.disabled=!0,t.classList.add("disabled")):(t.innerHTML=t.dataset.enableWith,t.disabled=!1,t.classList.remove("disabled"))},adjustTextarea(t){t&&(t.style.height="auto",t.style.height=`${t.scrollHeight}px`)},isSearchEngineCrawler(){const t=navigator.userAgent.toLowerCase();return["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","sogou","exabot","facebot","ia_archiver"].some((e=>t.includes(e)))},removeArrayItemOnce(t,e){var n=t.indexOf(e);return n>-1&&t.splice(n,1),t},extractTextNodes:t=>Array.from(t.childNodes).filter((t=>t.nodeType===Node.TEXT_NODE)).map((t=>t.textContent.trim())).join(" "),appendToComment(t){const e=_$(FcnGlobals.commentFormSelector);if(e)switch(e.tagName){case"TEXTAREA":e.value+=t,FcnUtils.adjustTextarea(e);break;case"DIV":e.innerHTML+=t}else FcnGlobals.commentStack.push(t)}};async function fcn_ajaxPost(t={},e=null,n={}){e&&!e.startsWith("http")&&(e=FcnGlobals.restURL+e),e=e||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL);let a={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};a={...a,...n},t={nonce:FcnUtils.nonce(),...t};const s=await fetch(e,{method:"POST",credentials:"same-origin",headers:a,mode:"same-origin",body:new URLSearchParams(t)});return s.ok?s.json():Promise.reject(s)}async function fcn_ajaxGet(t={},e=null,n={}){e&&!e.startsWith("http")&&(e=FcnGlobals.restURL+e),e=e||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL),t={nonce:FcnUtils.nonce(),...t},e=FcnUtils.buildUrl(t,e);let a={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};a={...a,...n};const s=await fetch(e,{method:"GET",credentials:"same-origin",headers:a,mode:"same-origin"});return s.ok?s.json():Promise.reject(s)}const FcnGlobals={eSite:_$$$("site"),urlParams:Object.fromEntries(new URLSearchParams(window.location.search).entries()),pageLoadTimestamp:Date.now(),ajaxLimitThreshold:Date.now()-parseInt(fictioneer_ajax.ttl),ajaxURL:fictioneer_ajax.ajax_url,restURL:fictioneer_ajax.rest_url,ffcnrURL:fictioneer_ajax.ffcnr_url,ffcnrAuth:fictioneer_ajax.ffcnr_auth,debounceRate:fictioneer_ajax.post_debounce_rate,ajaxAuth:document.documentElement.dataset.fictioneerAjaxAuthValue??!1,fonts:fictioneer_fonts??[],fontColors:fictioneer_font_colors??[],commentFormSelector:fictioneer_comments?.selector??"#comment",commentStack:[]};function fcn(){const t=window.FictioneerApp?.Controllers?.fictioneer;return t||{userData:FcnUtils.userData,setUserData:FcnUtils.setUserData,resetUserData:FcnUtils.resetUserData,removeUserData:FcnUtils.removeUserData}}function fcn_getUserData(){return FcnUtils.userData()}function fcn_setUserData(t){return FcnUtils.setUserData(t)}function fcn_cleanUpWebStorage(){["fcnBookshelfContent"].forEach((t=>localStorage.removeItem(t))),fcn().resetUserData()}function fcn_cleanUpGuestView(){document.body.classList.remove("logged-in","is-admin","is-moderator","is-editor","is-author"),_$$$("fictioneer-ajax-nonce")?.remove(),_$$(".only-moderators, .only-admins, .only-authors, .only-editors, .only-logged-in").forEach((t=>{t.remove()}))}function fcn_setLoggedInState(){const t=fcn().userData(),e=!0===t.loggedIn;document.body.classList.toggle("logged-in",e),document.body.classList.toggle("is-admin",t.isAdmin),document.body.classList.toggle("is-moderator",t.isModerator),document.body.classList.toggle("is-author",t.isAuthor),document.body.classList.toggle("is-editor",t.isEditor);const n=[];e&&(n.push('[data-fictioneer-id-param="login-modal"]'),n.push("#login-modal")),t.isAdmin||(n.push(".only-admins"),t.isModerator||n.push(".only-moderators"),t.isAuthor||n.push(".only-authors"),t.isEditor||n.push(".only-editors")),_$$(n.join(", ")).forEach((t=>t.remove()))}function fcn_setAvatar(){const t=fcn().userData()?.avatarUrl;t&&_$$('[data-fictioneer-target="avatarWrapper"]').forEach((e=>{const n=document.createElement("img");n.classList.add("user-profile-image"),n.src=t,e.firstChild.remove(),e.appendChild(n)}))}Object.freeze(FcnGlobals),window.FictioneerApp=window.FictioneerApp||{},window.FictioneerApp.Controllers=window.FictioneerApp.Controllers||{},application.register("fictioneer",class extends Stimulus.Controller{static get targets(){return["avatarWrapper","modal","mobileMenuToggle"]}static values={fingerprint:String,ageConfirmation:{type:Boolean,default:!1},ajaxAuth:{type:Boolean,default:!1},ajaxSubmit:{type:Boolean,default:!1},cachingActive:{type:Boolean,default:!1},publicCaching:{type:Boolean,default:!1},forceChildTheme:{type:Boolean,default:!1},editTime:{type:Number,default:15}};userReady=!1;lastModalToggle=null;currentModal=null;initialize(){if(FcnUtils.loggedIn()||this.ajaxAuthValue)this.fetchUserData();else{fcn_cleanUpWebStorage();const t=new CustomEvent("fcnUserDataReady",{detail:{data:this.userData(),time:new Date,loggedOut:!0},bubbles:!0,cancelable:!1});document.dispatchEvent(t)}}connect(){window.FictioneerApp.Controllers.fictioneer=this}userData(){return FcnUtils.userData()}setUserData(t){FcnUtils.setUserData(t)}resetUserData(){FcnUtils.resetUserData()}removeUserData(){FcnUtils.removeUserData()}fetchUserData(){let t=this.userData();if(FcnUtils.loggedIn()&&!1===t.loggedIn&&(this.removeUserData(),t=this.userData()),(FcnGlobals.ajaxLimitThreshold{if(e.success){let n=this.userData();n=e.data,n.lastLoaded=Date.now(),this.setUserData(n),fcn_setAvatar(),t.nonceHtml&&this.#t(t.nonceHtml);const a=new CustomEvent("fcnUserDataReady",{detail:{data:e.data,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(a)}else{const t=this.userData();t.lastLoaded=Date.now(),t.loggedIn=!1,this.setUserData(t);const n=new CustomEvent("fcnUserDataFailed",{detail:{data:e,time:new Date,cached:!1},bubbles:!0,cancelable:!1});document.dispatchEvent(n)}this.userReady=!0})).catch((t=>{localStorage.removeItem("fcnUserData");const e=new CustomEvent("fcnUserDataError",{detail:{error:t,time:new Date},bubbles:!0,cancelable:!1});document.dispatchEvent(e)}))}copyInput(t){t.currentTarget.select(),FcnUtils.copyToClipboard(t.currentTarget.value,t.currentTarget.dataset.message)}clearConsent(t){FcnUtils.toggleInProgress(t.currentTarget),FcnUtils.deleteCookie("fcn_cookie_consent"),location.reload()}clearCookies(t){const e=t.currentTarget;if(!FcnUtils.loggedIn())return fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),void alert(e.dataset.message);FcnUtils.toggleInProgress(e),FcnUtils.aGet({action:"fictioneer_ajax_clear_cookies",nonce:FcnUtils.nonce()}).then((t=>{t.success?(fcn_cleanUpWebStorage(),FcnUtils.deleteAllCookies(),alert(t.data.success)):t.data.error&&(alert(t.data.failure),console.error("Error:",t.data.error))})).catch((t=>{alert(t),console.error(t)})).then((()=>{FcnUtils.toggleInProgress(e)}))}logout(){fcn_cleanUpWebStorage()}toggleObfuscation(t){t.target.closest('[data-fictioneer-target="obfuscated"]').classList.toggle("_obfuscated")}bodyClick(t){let e;this.dispatch("bodyClick",{detail:{event:t,target:t.target}}),(e=t.target.closest(".page-numbers.dots:not(button)"))?this.#e(e):(e=t.target.closest(".spoiler"))&&e.classList.toggle("_open")}toggleChapterGroup(t){const e=t.currentTarget.closest(".chapter-group"),n=e.querySelector(".chapter-group__list"),a=!e.classList.contains("_closed");n.addEventListener("transitionend",(()=>{n.style.height="",n.querySelectorAll("a, button, label, input:not([hidden])").forEach((t=>{t.tabIndex=n.parentElement.classList.contains("_closed")?"-1":"0"})),_$(".main__background")?.classList.remove("will-change")}),{once:!0}),_$(".main__background")?.classList.add("will-change"),n.style.height=`${n.scrollHeight}px`,requestAnimationFrame((()=>{requestAnimationFrame((()=>{e.classList.toggle("_closed",a),n.style.height=a?"0":`${n.scrollHeight}px`}))}))}toggleModal(t){t.preventDefault(),this.toggleModalVisibility(t.currentTarget,t.params.id)}toggleModalVisibility(t,e){const n=_$$$(e);if(n)if(this.currentModal!==n&&this.closeModals(),this.lastModalToggle=t,n.hidden=!n.hidden,n.hidden)this.closeModals();else{const t=n.querySelector(".close");t?.focus(),t?.blur()}}closeModals(){this.hasModalTarget&&this.modalTargets.forEach((t=>{t.hidden=!0})),this.lastModalToggle&&(this.lastModalToggle?.focus(),this.lastModalToggle?.blur(),this.lastModalToggle.null)}backgroundCloseModals({target:t}){t.classList.contains("modal")&&this.closeModals()}toggleMobileMenu(t){t.preventDefault();const e=window.FictioneerApp.Controllers.fictioneerMobileMenu;e&&e.toggle()}#t(t){_$$$("fictioneer-ajax-nonce")?.remove(),document.body.appendChild(FcnUtils.html`${t}`)}#e(t){if(document.documentElement.dataset.disablePageJump)return;const e=parseInt(window.prompt(fictioneer_tl.notification.enterPageNumber));if(e>0){const n=t.nextElementSibling.getAttribute("href"),a=["page=","paged=","comment-page-","pg="];for(const t of a)if(n.includes(t))return void(window.location.href=n.replace(new RegExp(`${t}\\d+`),t+e));window.location.href=n.replace(/page\/\d+/,`page/${e}`)}}}),"function"==typeof fcn_removeQueryArgs&&fcn_removeQueryArgs(),document.addEventListener("fcnUserDataReady",(()=>{fcn().userData().loggedIn||(fcn_cleanUpWebStorage(),fcn_cleanUpGuestView())})),_$("#wp-admin-bar-logout a")?.addEventListener("click",(()=>{fcn_cleanUpWebStorage()})),_$$(".subscriber-login, .oauth-login-link, [data-prepare-login]").forEach((t=>{t.addEventListener("click",(()=>{fcn().removeUserData()}))})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setLoggedInState()})),document.addEventListener("fcnUserDataReady",(()=>{fcn_setAvatar()}));var fcn_animFrameEvents=new Map;function fcn_bindEventToAnimationFrame(t,e,n=window){n.addEventListener(t,(function(){fcn_animFrameEvents.get(e)||(fcn_animFrameEvents.set(e,!0),requestAnimationFrame((()=>{n.dispatchEvent(new CustomEvent(e)),fcn_animFrameEvents.set(e,!1)})))}))}function fcn_loadEmbed(t){t.target.parentNode.querySelectorAll("iframe, script")[0].src=t.target.dataset.src,t.target.parentElement.querySelector(".embed-logo")?.remove(),t.target.remove()}function fcn_appendTermMenu(t,e){const n=_$$$(`term-submenu-${t}`);if(!n)return;const a=n.content.cloneNode(!0);e.classList.add("menu-item-has-children"),e.querySelector('[href="#"]').addEventListener("click",(t=>{t.preventDefault()})),e.appendChild(a)}fcn_bindEventToAnimationFrame("scroll","scroll.rAF"),fcn_bindEventToAnimationFrame("resize","resize.rAF"),document.body.addEventListener("change",(t=>{const e=t.target.closest('[type="checkbox"]');if(!e)return;const n=e.name,a=n?_$$(`label[for="${n}"]`):[],s=e.checked;e.closest("[aria-checked]")?.setAttribute("aria-checked",s),a.forEach((t=>{t.closest("[aria-checked]")?.setAttribute("aria-checked",s)}))})),_$$(".iframe-consent, .twitter-consent").forEach((t=>{t.onclick=t=>{fcn_loadEmbed(t)}})),document.addEventListener("DOMContentLoaded",(()=>{const t=_$("#menu-navigation > .menu-item"),e=_$$$("full-navigation");t&&e&&t.offsetHeight{fcn_appendTermMenu("category",t)})),_$$(".main-navigation .trigger-term-menu-tags").forEach((t=>{fcn_appendTermMenu("post_tag",t)})),_$$(".main-navigation .trigger-term-menu-genres").forEach((t=>{fcn_appendTermMenu("fcn_genre",t)})),_$$(".main-navigation .trigger-term-menu-fandoms").forEach((t=>{fcn_appendTermMenu("fcn_fandom",t)})),_$$(".main-navigation .trigger-term-menu-characters").forEach((t=>{fcn_appendTermMenu("fcn_character",t)})),_$$(".main-navigation .trigger-term-menu-warnings").forEach((t=>{fcn_appendTermMenu("fcn_content_warning",t)}))})),_$$$("full-navigation")?.addEventListener("mouseover",(()=>{document.dispatchEvent(new CustomEvent("fcnRemoveLastClicked"))}));var fcn_lastScrollTop=0;function fcn_scrollDirection(){if(FcnGlobals.eSite.classList.contains("transformed-scroll"))return;const t="hidden"!==window.getComputedStyle(document.documentElement).overflow?window.scrollY??document.documentElement.scrollTop:document.body.scrollTop??1;document.body.classList.toggle("scrolled-to-top",0===t),t>fcn_lastScrollTop&&Math.abs(fcn_lastScrollTop-t)>=10?(document.body.classList.add("scrolling-down"),document.body.classList.remove("scrolling-up"),fcn_lastScrollTop=Math.max(t,0)):t=50&&(document.body.classList.add("scrolling-up"),document.body.classList.remove("scrolling-down"),fcn_lastScrollTop=Math.max(t,0))}function fcn_observe(t,e,n={}){const a=_$(t);if(!a)return null;new IntersectionObserver((t=>e(t[0])),n).observe(a)}function fcn_dragElement(t){const e=t.querySelector(".drag-anchor")??t;let n,a;function s(e){e.preventDefault(),t.style.top=t.offsetTop-(a-e.clientY)+"px",t.style.left=t.offsetLeft-(n-e.clientX)+"px",n=e.clientX,a=e.clientY}function i(){e.onmouseup=null,e.onmousemove=null}e.onmousedown=function(t){t.preventDefault(),n=t.clientX,a=t.clientY,e.onmousemove=s,e.onmouseup=i}}function fcn_showNotification(t,e=3,n="base"){const a=_$("#notifications"),s=document.createElement("div");s.innerHTML=t,s.classList.add("notifications__message",`_${n}`),s.style.opacity=1,s.style.transitionDelay=`${e}s`,a.prepend(s),s.addEventListener("transitionend",(t=>{"opacity"===t.propertyName&&a.removeChild(t.target)})),s.addEventListener("click",(t=>{a.removeChild(t.currentTarget)})),setTimeout((()=>{s.style.opacity=0}),100)}if(window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_scrollDirection,200)),fcn_scrollDirection(),document.addEventListener("DOMContentLoaded",(()=>{fcn_observe(".main-observer",(t=>{document.body.classList.toggle("is-inside-main",t.intersectionRatio<1&&t.boundingClientRect.top<=0)}),{threshold:[1]}),fcn_observe(".chapter-end",(t=>{document.body.classList.toggle("is-end-of-chapter",t.isIntersecting||t.boundingClientRect.top<0)}),{root:null,threshold:0}),fcn_observe("#nav-observer-sticky",(t=>{_$$$("full-navigation").classList.toggle("is-sticky",t.intersectionRatio<1)}),{threshold:[1]})})),_$$(".modal__header.drag-anchor").forEach((t=>{fcn_dragElement(t.closest(".modal__wrapper"))})),FcnGlobals.urlParams){switch(FcnGlobals.urlParams.failure&&console.error("Failure:",FcnGlobals.urlParams.failure),FcnGlobals.urlParams.failure){case"oauth_email_taken":fcn_showNotification(fictioneer_tl.notification.oauthEmailTaken,5,"warning");break;case"oauth_already_linked":fcn_showNotification(fictioneer_tl.notification.oauthAccountAlreadyLinked,5,"warning")}if("oauth_new"===FcnGlobals.urlParams.success)fcn_showNotification(fictioneer_tl.notification.oauthNew,10);else FcnGlobals.urlParams.success?.startsWith("oauth_merged_")&&fcn_showNotification(fictioneer_tl.notification.oauthAccountLinked,3,"success");if(FcnGlobals.urlParams["fictioneer-notice"]){let t="1"===FcnGlobals.urlParams.failure?"warning":"base";t="1"===FcnGlobals.urlParams.success?"success":t,fcn_showNotification(FcnUtils.sanitizeHTML(FcnGlobals.urlParams["fictioneer-notice"]),3,t)}}function fcn_updateThemeColor(t=null){const e=fcn_siteSettings.darken?fcn_siteSettings.darken:0,n=fcn_siteSettings.saturation?fcn_siteSettings.saturation:0,a=fcn_siteSettings["hue-rotate"]?fcn_siteSettings["hue-rotate"]:0,s=e>=0?1+e**2:1-e**2,i=n>=0?1+n**2:1-n**2;let o=getComputedStyle(document.documentElement).getPropertyValue("--theme-color-base").trim().split(" ");o=`hsl(${(parseInt(o[0])+a)%360}deg ${(parseInt(o[1])*i).toFixed(2)}% ${(parseInt(o[2])*s).toFixed(2)}%)`,_$("meta[name=theme-color]").setAttribute("content",t??o)}const fcn_settingHueRotateRange=_$$$("site-setting-hue-rotate-range"),fcn_settingHueRotateText=_$$$("site-setting-hue-rotate-text"),fcn_settingHueRotateReset=_$$$("site-setting-hue-rotate-reset"),fcn_settingDarkenRanges=_$$(".setting-darken-range"),fcn_settingDarkenTexts=_$$(".setting-darken-text"),fcn_settingDarkenResets=_$$(".setting-darken-reset"),fcn_settingSaturationRanges=_$$(".setting-saturation-range"),fcn_settingSaturationTexts=_$$(".setting-saturation-text"),fcn_settingSaturationResets=_$$(".setting-saturation-reset"),fcn_settingFontLightnessRanges=_$$(".setting-font-lightness-range"),fcn_settingFontLightnessTexts=_$$(".setting-font-lightness-text"),fcn_settingFontLightnessResets=_$$(".setting-font-lightness-reset"),fcn_settingEvents=["nav-sticky","background-textures","polygons","covers","taxonomies","text-shadows","minimal","chapter-progress-bar"];var fcn_siteSettings=fcn_getSiteSettings();function fcn_updateSiteSetting(t,e,n){t.checked=n,fcn_siteSettings[e]=n,fcn_applySiteSettings(fcn_siteSettings)}function fcn_toggleLightMode(){fcn_setLightMode(!(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault))}function fcn_setLightMode(t,e=!1){localStorage.setItem("fcnLightmode",t),document.documentElement.dataset.mode=t?"light":"dark",_$$(".toggle-light-mode").forEach((e=>{e.closest("[aria-checked]")?.setAttribute("aria-checked",t)})),e||fcn_updateThemeColor()}function fcn_updateFontWeight(){const t="default"!=fcn_siteSettings["font-weight"];_$$(".site-setting-font-weight").forEach((t=>{t.value=fcn_siteSettings["font-weight"]})),_$$(".font-weight-reset").forEach((e=>{e.classList.toggle("_modified",t)}))}function fcn_resetFontWeight(){fcn_siteSettings["font-weight"]="default",document.documentElement.dataset.fontWeight="default",fcn_applySiteSettings(fcn_siteSettings)}function fcn_updateHueRotate(t){t=FcnUtils.clamp(0,360,t??0),fcn_settingHueRotateText.value=t,fcn_settingHueRotateRange.value=t,fcn_settingHueRotateReset.classList.toggle("_modified",0!=t),document.documentElement.style.setProperty("--hue-rotate",`(${t}deg + var(--hue-offset))`),fcn_siteSettings["hue-rotate"]=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setHueRotate(){fcn_updateHueRotate(this.value)}function fcn_updateDarken(t=null){t=FcnUtils.clamp(-1,1,t??fcn_siteSettings.darken),t=Math.round(100*(t+Number.EPSILON))/100,fcn_settingDarkenResets.forEach((e=>{e.classList.toggle("_modified",0!=t)})),fcn_settingDarkenRanges.forEach((e=>{e.value=t})),fcn_settingDarkenTexts.forEach((e=>{e.value=parseInt(100*t)}));const e=t>=0?1+t**2:1-t**2;document.documentElement.style.setProperty("--darken",`(${e} + var(--lightness-offset))`),fcn_siteSettings.darken=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setDarkenFromRange(){fcn_updateDarken(this.value)}function fcn_setDarkenFromText(){"-"!=this.value&&""!=this.value&&fcn_updateDarken((parseInt(this.value)??0)/100)}function fcn_updateSaturation(t=null){t=FcnUtils.clamp(-1,1,t??fcn_siteSettings.saturation),fcn_settingSaturationResets.forEach((e=>{e.classList.toggle("_modified",0!=t)})),fcn_settingSaturationRanges.forEach((e=>{e.value=t})),fcn_settingSaturationTexts.forEach((e=>{e.value=parseInt(100*t)}));const e=t>=0?1+t**2:1-t**2;document.documentElement.style.setProperty("--saturation",`(${e} + var(--saturation-offset))`),fcn_siteSettings.saturation=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setSaturationFromRange(){fcn_updateSaturation(this.value)}function fcn_setSaturationFromText(){"-"!=this.value&&""!=this.value&&fcn_updateSaturation((parseInt(this.value)??0)/100)}function fcn_updateFontLightness(t=null){t=FcnUtils.clamp(-1,1,t??fcn_siteSettings["font-lightness"]??1),fcn_settingFontLightnessResets.forEach((e=>{e.classList.toggle("_modified",0!=t)})),fcn_settingFontLightnessRanges.forEach((e=>{e.value=t})),fcn_settingFontLightnessTexts.forEach((e=>{e.value=parseInt(100*t)}));const e=t>=0?1+t**2:1-t**2;document.documentElement.style.setProperty("--font-lightness",`(${e} + var(--font-lightness-offset))`),fcn_siteSettings["font-lightness"]=t,fcn_setSiteSettings(),fcn_updateThemeColor()}function fcn_setFontLightnessFromRange(){fcn_updateFontLightness(this.value)}function fcn_setFontLightnessFromText(){"-"!=this.value&&""!=this.value&&fcn_updateFontLightness((parseInt(this.value)??0)/100)}function fcn_defaultSiteSettings(){return{"nav-sticky":!0,"background-textures":!0,polygons:!0,covers:!0,taxonomies:!0,"text-shadows":!1,minimal:!1,"chapter-progress-bar":!0,"site-theme":"default","font-weight":"default",darken:0,saturation:0,"font-saturation":0,"font-lightness":0,"hue-rotate":0}}function fcn_getSiteSettings(){const t=FcnUtils.parseJSON(localStorage.getItem("fcnSiteSettings"))??fcn_defaultSiteSettings();return fcn_setSiteSettings(t),t}function fcn_setSiteSettings(t=null){"object"==typeof(t=t||fcn_siteSettings)&&(fcn_siteSettings=t,localStorage.setItem("fcnSiteSettings",JSON.stringify(t)))}function fcn_applySiteSettings(t){t="object"!=typeof t?fcn_defaultSiteSettings():t,Object.entries(t).forEach((t=>{const e=_$$$(`site-setting-${t[0]}`);switch(e&&(e.checked=t[1]),t[0]){case"minimal":document.documentElement.classList.toggle("minimal",t[1]);break;case"darken":fcn_updateDarken();break;case"saturation":fcn_updateSaturation();break;case"font-saturation":break;case"font-lightness":fcn_updateFontLightness();break;case"hue-rotate":fcn_updateHueRotate(t[1]);break;case"font-weight":fcn_updateFontWeight();break;default:document.documentElement.classList.toggle(`no-${t[0]}`,!t[1])}})),fcn_setSiteSettings(t)}function fcn_updateSiteTheme(t){fcn_siteSettings["site-theme"]=t,document.documentElement.dataset.theme=t,_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=t),fcn_applySiteSettings(fcn_siteSettings),fcn_updateThemeColor()}function fcn_resetSiteTheme(){fcn_updateSiteTheme("default"),_$$(".site-setting-site-theme").forEach((t=>{t.value="default"}))}function fcn_revealCommentImage(t){const e=t.parentElement.querySelector("img");e.src=e.dataset.src,t.remove()}function fcn_contactFormSubmit(t){const e=t.closest("form"),n=new FormData(e);if(!e.reportValidity())return;if(t.disabled=!0,t.innerHTML=t.dataset.disabled,Date.now(){n.success?(e.querySelector("textarea").value="",t.innerHTML=t.dataset.done,fcn_showNotification(n.data.success,3,"success")):n.data.failure&&(t.disabled=!1,t.innerHTML=t.dataset.enabled)},errorCallback:()=>{t.disabled=!1,t.innerHTML=t.dataset.enabled}})}fcn_settingEvents.forEach((t=>{_$$$(`site-setting-${t}`)?.addEventListener("change",(e=>{fcn_updateSiteSetting(e.currentTarget,t,e.currentTarget.checked)}))})),fcn_setLightMode(localStorage.getItem("fcnLightmode")?"true"==localStorage.getItem("fcnLightmode"):"light"==document.documentElement.dataset.modeDefault,!0),_$$(".toggle-light-mode").forEach((t=>{t.onclick=()=>fcn_toggleLightMode()})),_$$(".font-weight-reset").forEach((t=>{t.addEventListener("click",fcn_resetFontWeight)})),_$$(".site-setting-font-weight").forEach((t=>{t.onchange=t=>{fcn_siteSettings["font-weight"]=t.target.value,document.documentElement.dataset.fontWeight=t.target.value,fcn_applySiteSettings(fcn_siteSettings),fcn_updateFontWeight()}})),fcn_settingHueRotateReset?.addEventListener("click",(()=>{fcn_updateHueRotate(0)})),fcn_settingHueRotateRange?.addEventListener("input",FcnUtils.throttle(fcn_setHueRotate,1e3/24)),fcn_settingHueRotateText?.addEventListener("input",fcn_setHueRotate),fcn_settingDarkenResets.forEach((t=>{t.addEventListener("click",(()=>{fcn_updateDarken(0)}))})),fcn_settingDarkenRanges.forEach((t=>{t.addEventListener("input",FcnUtils.throttle(fcn_setDarkenFromRange,1e3/24))})),fcn_settingDarkenTexts.forEach((t=>{t.addEventListener("input",fcn_setDarkenFromText)})),fcn_settingSaturationResets.forEach((t=>{t.addEventListener("click",(()=>{fcn_updateSaturation(0)}))})),fcn_settingSaturationRanges.forEach((t=>{t.addEventListener("input",FcnUtils.throttle(fcn_setSaturationFromRange,1e3/24))})),fcn_settingSaturationTexts.forEach((t=>{t.addEventListener("input",fcn_setSaturationFromText)})),fcn_settingFontLightnessResets.forEach((t=>{t.addEventListener("click",(()=>{fcn_updateFontLightness(0)}))})),fcn_settingFontLightnessRanges.forEach((t=>{t.addEventListener("input",FcnUtils.throttle(fcn_setFontLightnessFromRange,1e3/24))})),fcn_settingFontLightnessTexts.forEach((t=>{t.addEventListener("input",fcn_setFontLightnessFromText)})),fcn_applySiteSettings(fcn_siteSettings),_$$(".site-setting-site-theme").forEach((t=>{t.value=fcn_siteSettings["site-theme"]?fcn_siteSettings["site-theme"]:"default",_$$$("site-setting-theme-reset").classList.toggle("_modified","default"!=t.value),t.addEventListener("change",(t=>{fcn_updateSiteTheme(t.target.value)}))})),_$$$("site-setting-theme-reset")?.addEventListener("click",fcn_resetSiteTheme),fcn_updateThemeColor(),_$(".fictioneer-comments")?.addEventListener("click",(t=>{t.target?.classList.contains("consent-button")&&fcn_revealCommentImage(t.target)})),_$$(".fcn-contact-form").forEach((t=>{t.querySelector(".fcn-contact-form__submit").addEventListener("click",(t=>{fcn_contactFormSubmit(t.currentTarget)}))})),_$$('[data-click-action*="open-dialog-modal"]').forEach((t=>{t.addEventListener("click",(t=>{document.querySelector(t.currentTarget.dataset.clickTarget).showModal()}))})),_$$('[data-click-action*="close-dialog-modal"], button[formmethod="dialog"][value="cancel"]').forEach((t=>{t.addEventListener("click",(t=>{t.preventDefault(),t.target.closest("dialog").close()}))})),_$$("dialog").forEach((t=>{t.addEventListener("mousedown",(e=>{if(e.target===e.currentTarget){const n=t.getBoundingClientRect();(e.clientXn.right||e.clientYn.bottom)&&(e.preventDefault(),e.target.close())}}))})),_$$(".content-section").forEach((t=>{t.addEventListener("click",(t=>{if(t.target.closest('[data-click-action*="open-tooltip-modal"]')&&!window.getSelection().toString()){const e=_$$$("fictioneer-tooltip-dialog"),n=t.target.dataset.dialogHeader,a=t.target.dataset.dialogContent;a.length>200?e.style.setProperty("--modal-width","400px"):e.style.removeProperty("--modal-width"),n&&(e.querySelector('[data-finder="tooltip-dialog-header"]').innerHTML=n),e.querySelector('[data-finder="tooltip-dialog-content"]').innerHTML=a,e.showModal()}}))})),document.body.addEventListener("keydown",(t=>{let e=document.activeElement.closest('[tabindex="0"]:not(a, input, button, select)');if(["BUTTON","A","INPUT","SELECT"].includes(document.activeElement.tagName)&&(e=null),e&&(" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),e.click())),"Escape"===t.key){_$$(".modal-toggle:checked").forEach((t=>{t.checked=!1, +t.dispatchEvent(new Event("change"))}));const t=_$(".lightbox.show");if(t)return void t.querySelector(".lightbox__close").click();const e=_$(".selected-paragraph #button-close-paragraph-tools");if(e)return void e.click();const n=_$("#tts-interface:not(.hidden)");if(n){if(n.classList.contains("playing")){const t=_$$$("button-tts-pause");t?.click(),t?.focus(),t?.blur()}else _$$$("button-tts-stop").click();return}}}));class FCN_KeywordInput{constructor(t){this.input=t,this.type=t.dataset.type,this.operator=t.closest(".keyword-input").querySelector(".keyword-input__operator input"),this.inputWrapper=t.closest(".keyword-input__input-wrapper"),this.block=t.closest(".keyword-input"),this.form=this.block.closest(".search-form"),this.collection=this.block.querySelector(".keyword-input__collection"),this.suggestionList=this.block.querySelector(".keyword-input__suggestion-list"),this.tabSuggestion=this.block.querySelector(".keyword-input__tab-suggestion"),this.allowText=this.form.querySelector(".allow-list")?.innerText??"{}",this.allowList=FcnUtils.parseJSON(this.allowText),this.hints=this.block.querySelector(".keyword-input__hints"),this.noHint=this.block.querySelector(".keyword-input__no-suggestions"),this.keywords=this.collection.value.length>0?this.collection.value.split(","):[],this.bindEvents(),this.resize(),this.filterSuggestions()}resize(){const t=this.tabSuggestion.innerText.length>0?this.tabSuggestion.innerText.length:this.input.value.length;this.input.style.width=.88*t+2+"ch"}reset(){this.keywords=[],this.block.querySelectorAll(".node").forEach((t=>{t.remove()})),this.block.querySelectorAll(".keyword-input__operator > input").forEach((t=>{t.checked=!1})),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}encode(t){const e=(new TextEncoder).encode(t.toLowerCase());return btoa(String.fromCharCode.apply(null,e))}filterSuggestions(){const t=this.input.value.toLowerCase();let e=0,n="";""==t?this.suggestionList.querySelectorAll(".keyword-button").forEach((t=>{t.hidden=!0})):this.suggestionList.querySelectorAll(".keyword-button").forEach((a=>{const s=a.innerText.toLowerCase();s.includes(t)&&this.keywords.indexOf(s)<0?(a.hidden=!1,e++,""==n&&s.startsWith(t)&&(n=s)):a.hidden=!0})),this.hints.querySelectorAll(".keyword-button").forEach((t=>{this.keywords.indexOf(t.value.toLowerCase())>-1?t.hidden=!0:t.hidden=!1})),this.tabSuggestion.innerHTML=n,this.hints.hidden=!(""==t),this.noHint.hidden=!(""!=t&&e<1)}addNode(t=null,e=null){const n=t??this.input.value.replace(",","");let a=this.allowList[`${this.type}_${this.encode(n)}`];if("authors"!=this.collection.name&&"ex_authors"!=this.collection.name||!e||(a=this.allowList[`${this.type}_${this.encode(n)}_${e.value}`]),!a||this.keywords.indexOf(a)>-1)return;this.keywords.push(a);const s=document.createElement("div");s.innerHTML=`${n}`,s.classList.add("node"),s.dataset.value=a,this.inputWrapper.parentNode.insertBefore(s,this.inputWrapper),this.input.value="",this.updateCollection(),this.filterSuggestions(),this.resize()}removeNodeByValue(t){this.block.querySelector(`[data-value="${t}"]`)?.remove(),this.keywords=this.keywords.filter((e=>e!=t)),this.updateCollection(),this.filterSuggestions(),this.resize()}updateCollection(){this.collection.value=this.keywords.join(","),this.block.classList.toggle("_empty",""===this.collection.value),this.form.querySelector(".search-form__current").innerHTML=""}bindEvents(){this.input.addEventListener("input",(t=>{t.currentTarget.value.includes(",")&&this.addNode(),this.block.classList.toggle("_empty",""===t.currentTarget.value&&""===this.collection.value),this.filterSuggestions(),this.resize()})),this.input.addEventListener("keydown",(t=>{"Tab"!==t.key&&"Enter"!==t.key||""!=this.tabSuggestion.innerText&&(t.preventDefault(),this.input.value=this.tabSuggestion.innerText,this.addNode()),"Escape"===t.key&&(this.input.value="",this.tabSuggestion.innerHTML="",document.activeElement.blur()),"Backspace"===t.key&&""==this.input.value&&this.keywords.length>0&&this.removeNodeByValue(this.keywords.slice(-1))})),this.input.addEventListener("blur",(()=>{const t=this.allowList[this.encode(this.input.value)];this.blurTimeout=t?setTimeout((()=>{this.addNode()}),150):setTimeout((()=>{this.input.value="",this.tabSuggestion.innerHTML="",this.filterSuggestions(),this.resize()}),150)})),this.block.addEventListener("click",(t=>{t.target.closest(".node-delete")&&(t.preventDefault(),this.removeNodeByValue(t.target.closest(".node").dataset.value))})),this.block.querySelectorAll(".keyword-button").forEach((t=>{t.addEventListener("click",(t=>{clearTimeout(this.blurTimeout),this.addNode(t.currentTarget.innerText,t.currentTarget)}))}))}}function fcn_resetSearchForm(t,e,n){n.forEach((t=>t.reset())),e.querySelectorAll("input, select").forEach((t=>{t.value=t.dataset.default??t.value})),e.querySelector(".search-form__current").innerHTML="",fcn_showNotification(t.dataset.reset,2)}function fcn_handleTabInput(t){"Tab"==t.key&&(document.body.classList.add("user-is-tabbing"),window.removeEventListener("keydown",fcn_handleTabInput),window.addEventListener("mousedown",fcn_handleMouseInput))}function fcn_handleMouseInput(){document.body.classList.remove("user-is-tabbing"),window.removeEventListener("mousedown",fcn_handleMouseInput),window.addEventListener("keydown",fcn_handleTabInput)}function fcn_popupPosition(){_$$(".popup-menu-toggle.last-clicked .popup-menu:not(._fixed-position)").forEach((t=>{if("none"===window.getComputedStyle(t).display)return;const e=FcnUtils.detectScreenCollision(t);e&&0===e.length||(e.includes("top")?(t.classList.remove("_top"),t.classList.add("_bottom")):e.includes("bottom")&&(t.classList.remove("_bottom"),t.classList.add("_top")),t.closest("._fixed-horizontal")||(e.includes("left")?(t.classList.remove("_center","_justify-right"),t.classList.add("_justify-left")):e.includes("right")&&(t.classList.remove("_center","_justify-left"),t.classList.add("_justify-right"))))}))}function fcn_markCurrentMenuItem(){_$$(`.menu-item > [data-nav-object-id="${document.body.dataset.postId}"]`).forEach((t=>{t.setAttribute("aria-current","page"),t.closest(".menu-item").classList.add("current-menu-item")}))}function fcn_showAgeConfirmationModal(){const t=_$(".story__article, .chapter__article")?.dataset.ageRating;if(!document.documentElement.dataset.ageConfirmation&&t&&"adult"!==t)return void _$$$("age-confirmation-modal")?.remove();const e=_$$$("age-confirmation-leave");document.documentElement.classList.add("age-modal-open"),_$$$("age-confirmation-modal").hidden=!1,_$$$("age-confirmation-confirm")?.addEventListener("click",(t=>{document.documentElement.classList.remove("age-modal-open"),t.currentTarget.closest(".modal").remove(),localStorage.setItem("fcnAgeConfirmation","1")})),e?.addEventListener("click",(()=>{window.location.href=e.dataset.redirect??"https://search.brave.com/",localStorage.removeItem("fcnAgeConfirmation")}))}_$$(".search-form").forEach((t=>{if(t.classList.contains("_simple"))return;const e=[];t.querySelectorAll(".keyword-input__input").forEach((t=>{e.push(new FCN_KeywordInput(t))})),t.querySelector(".allow-list")?.remove(),t.addEventListener("change",(e=>{e.target.classList.contains("search-form__advanced-control")||e.target.classList.contains("search-form__string")||(t.querySelector(".search-form__current").innerHTML="")})),t.querySelectorAll(".reset").forEach((n=>{n.addEventListener("click",(()=>{fcn_resetSearchForm(n,t,e)}))}))})),_$$(".search-form__advanced-toggle").forEach((t=>{t.addEventListener("click",(t=>{const e=t.currentTarget.closest("form");e.dataset.advanced="true"==e.dataset.advanced?"false":"true"}))})),window.addEventListener("keydown",fcn_handleTabInput),window.addEventListener("scroll.rAF",FcnUtils.throttle(fcn_popupPosition,250)),document.body.addEventListener("click",(t=>{const e=t.target.closest("[href]"),n=e?.getAttribute("href");if(!e||"A"===!e.tagName||!n.startsWith("#")||n.length<2||"#respond"===n)return;const a=n.replace("#",""),s=_$$(`[name="${a}"], [id="${a}"]`)[0],i=e.closest(".comment._story-comment");i&&(window.location.href=i.querySelector(".fictioneer-comment__link").href+n),s&&(t.preventDefault(),s.scrollIntoView({behavior:"smooth",block:e.dataset?.block??"start"}))})),fcn_markCurrentMenuItem(),_$$$("age-confirmation-modal")&&"1"!==localStorage.getItem("fcnAgeConfirmation")&&!FcnUtils.isSearchEngineCrawler()?fcn_showAgeConfirmationModal():_$$$("age-confirmation-modal")?.remove(),document.addEventListener("DOMContentLoaded",(()=>{_$$(".splide:not(.no-auto-splide, .is-initialized)").forEach((t=>{t.querySelector(".splide__list")&&"undefined"!=typeof Splide&&(t.classList.remove("_splide-placeholder"),new Splide(t).mount())})),_$$(".temp-script, .splide-placeholder-styles").forEach((t=>{t.remove()}))})),application.register("fictioneer-large-card",class extends Stimulus.Controller{static get targets(){return["controls","menu"]}static values={postId:Number,storyId:Number,chapterId:Number};initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#a(),this.#n=!0,this.#s()}))}connect(){if(window.FictioneerApp.Controllers.fictioneerLargeCard=this,this.#n&&(this.#a(),this.#s()),document.addEventListener("click",(t=>{t.target.closest(`.card.post-${this.postIdValue}`)||this.#i()})),document.addEventListener("toggledLastClick",(t=>{this.#o(t.detail.target,t.detail.force)})),this.hasMenuTarget)for(this.menuFragment=document.createDocumentFragment();this.menuTarget.firstChild;)this.menuFragment.appendChild(this.menuTarget.firstChild)}disconnect(){this.#r()}isFollowed(){return!(!this.#c()||!this.#l()?.follows?.data?.[this.storyIdValue])}isRemembered(){return!(!this.#c()||!this.#l()?.reminders?.data?.[this.storyIdValue])}isRead(){if(!this.#c())return!1;const t=this.#l()?.checkmarks?.data?.[this.storyIdValue];return!!t&&(t.includes(this.chapterIdValue)||t.includes(this.storyIdValue))}cardClick(t){t.target.closest(".card__controls")||this.#d()}toggleMenu(){this.menuTarget.querySelector("*")?this.#d():this.#h()}toggleFollow(){this.#c()?(fcn_toggleFollow(this.storyIdValue,!this.isFollowed()),this.#f()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleReminder(){this.#c()?(fcn_toggleReminder(this.storyIdValue,!this.isRemembered()),this.#g()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}toggleCheckmarks(){this.#c()?(fcn_toggleCheckmark(this.storyIdValue,this.chapterIdValue),this.#u()):_$('[data-fictioneer-id-param="login-modal"]')?.click()}setCheckmarks(t){this.toggleCheckmarks("set",t.params?.type??"story")}unsetCheckmarks(t){this.toggleCheckmarks("unset",t.params?.type??"story")}#m=!1;#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#n=!1,this.#p=!0),t}#l(){return this.userData=fcn().userData(),this.userData}#_(){return this.#c()&&JSON.stringify(this.userData??0)!==JSON.stringify(this.#l())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.#a()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.#a(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}#a(){this.#f(),this.#g(),this.#u()}#f(){this.element.classList.toggle("has-follow",this.isFollowed())}#g(){this.element.classList.toggle("has-reminder",this.isRemembered())}#u(){this.element.classList.toggle("has-checkmark",this.isRead())}#i(){this.#d()}#h(){this.#m=!0,this.menuTarget.appendChild(this.menuFragment.cloneNode(!0))}#d(){if(this.#m)for(this.#m=!1;this.menuTarget.firstChild;)this.menuTarget.removeChild(this.menuTarget.firstChild)}#o(t,e){e?t&&!t.closest(`.card.post-${this.postIdValue}`)&&this.#m&&this.#d():this.#d()}}),application.register("fictioneer-last-click",class extends Stimulus.Controller{static get targets(){return["toggle"]}last=null;connect(){window.FictioneerApp.Controllers.fictioneerLastClick=this,document.addEventListener("fcnRemoveLastClicked",(()=>{this.last&&this.removeLastClick()}))}removeAll(){this.last&&(this.#b(this.last,!1),this.removeLastClick())}toggle(t){const e=t.target.closest('[data-fictioneer-last-click-target="toggle"]');if(!e||["BUTTON","A","INPUT","SELECT"].includes(t.target.tagName)&&!t.target.hasAttribute("data-fictioneer-last-click-target"))return;const n=!e.classList.contains("last-clicked");"function"==typeof fcn_popupPosition&&fcn_popupPosition(),e.classList.toggle("last-clicked",n),e.closest(".watch-last-clicked")?.classList.toggle("has-last-clicked",n),this.last&&this.last!=e&&this.removeLastClick(),this.last=e,this.#b(e,n),t.stopPropagation()}removeLastClick(){this.last&&(this.last.closest(".watch-last-clicked")?.classList.remove("has-last-clicked"),this.last.classList.remove("last-clicked"),this.last=null,document.activeElement?.blur())}#b(t,e){document.dispatchEvent(new CustomEvent("toggledLastClick",{detail:{target:t,force:e}}))}});const fcn_consentBanner=_$$$("consent-banner");function fcn_loadConsentBanner(){fcn_consentBanner.classList.remove("hidden"),fcn_consentBanner.hidden=!1,_$$$("consent-accept-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","full"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0})),_$$$("consent-reject-button")?.addEventListener("click",(()=>{FcnUtils.setCookie("fcn_cookie_consent","necessary"),fcn_consentBanner.classList.add("hidden"),fcn_consentBanner.hidden=!0}))}function fcn_showLightbox(t){const e=_$$$("fictioneer-lightbox"),n=_$(".lightbox__content");let a=!1,s=null;if(n.innerHTML="",t.classList.add("lightbox-last-trigger"),"IMG"==t.tagName?(s=t.cloneNode(),a=!0):t.href&&(s=document.createElement("img"),s.src=t.href,a=!0),a&&s){["class","style","height","width"].forEach((t=>s.removeAttribute(t))),n.appendChild(s),e.classList.add("show");const t=e.querySelector(".lightbox__close");t?.focus(),t?.blur()}}fcn_consentBanner&&""===(FcnUtils.getCookie("fcn_cookie_consent")??"")&&!FcnUtils.isSearchEngineCrawler()?setTimeout((()=>{fcn_loadConsentBanner()}),4e3):fcn_consentBanner?.remove(),document.body.addEventListener("click",(t=>{const e=t.target.closest("[data-lightbox]:not(.no-auto-lightbox)");e&&(t.preventDefault(),fcn_showLightbox(e))})),document.body.addEventListener("keydown",(t=>{const e=t.target.closest("[data-lightbox]:not(.no-auto-lightbox)");e&&(" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),fcn_showLightbox(e)))})),document.querySelectorAll(".lightbox__close, .lightbox").forEach((t=>{t.addEventListener("click",(t=>{if("IMG"!=t.target.tagName){_$$$("fictioneer-lightbox").classList.remove("show");const t=_$(".lightbox-last-trigger");t?.focus(),t?.blur(),t?.classList.remove("lightbox-last-trigger")}}))})),application.register("fictioneer-mobile-menu",class extends Stimulus.Controller{static get targets(){return["frame","bookmarks","panelBookmarks"]}advanced=!!_$(".mobile-menu._advanced-mobile-menu");open=!1;editingBookmarks=!1;currentFrame=null;bookmarkTemplate=_$$$("mobile-bookmark-template");chapterId=_$("article")?.id;connect(){window.FictioneerApp.Controllers.fictioneerMobileMenu=this}toggle(t=null){this.open=t??!this.open,this.advanced?this.#k(this.open):this.#F(this.open)}clickOutside({detail:{target:t}}){this.open&&"site"===t?.id&&this.toggle(!1)}openFrame({params:{frame:t}}){const e=`mobile-frame-${t}`;this.editingBookmarks=!1,this.panelBookmarksTarget.dataset.editing=!1,this.hasFrameTarget&&this.frameTargets.forEach((t=>{t.classList.toggle("_active",t.id===e),t.id===e&&(this.currentFrame=t)}))}back(){this.openFrame({params:{frame:"main"}})}setMobileBookmarks(){const t=window.FictioneerApp.Controllers.fictioneerBookmarks;if(t&&this.hasBookmarksTarget){const e=Object.entries(t.data());if(this.bookmarksTarget.innerHTML="",!e||e.length<1){const t=document.createElement("li");return t.classList.add("no-bookmarks"),t.textContent=this.bookmarksTarget.dataset.empty,void this.bookmarksTarget.appendChild(t)}const n=document.createDocumentFragment();e.forEach((([t,{color:e,progress:a,link:s,chapter:i,"paragraph-id":o}])=>{const r=this.bookmarkTemplate.content.cloneNode(!0),c=r.querySelector(".mobile-menu__bookmark");c.classList.add(`bookmark-${t}`),c.dataset.color=e,r.querySelector(".mobile-menu__bookmark-progress > div > div").style.width=`${a.toFixed(1)}%`,r.querySelector(".mobile-menu__bookmark a").href=`${s}#paragraph-${o}`,r.querySelector(".mobile-menu__bookmark a span").innerText=i,r.querySelector(".mobile-menu-bookmark-delete-button").setAttribute("data-fictioneer-mobile-menu-id-param",t),n.appendChild(r)})),this.bookmarksTarget.appendChild(n)}}deleteBookmark({params:{id:t}}){const e=window.FictioneerApp.Controllers.fictioneerBookmarks;e?(e.remove({params:{id:t}}),this.setMobileBookmarks()):fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning")}toggleBookmarksEdit(){this.editingBookmarks=!this.editingBookmarks,this.panelBookmarksTarget.dataset.editing=this.editingBookmarks}scrollToComments(){this.#w(_$$$("comments"))}scrollToBookmark(){const t=window.FictioneerApp.Controllers.fictioneerBookmarks;if(!t)return void fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning");const e=t.data()?.[this.chapterId]?.["paragraph-id"],n=_$(`[data-paragraph-id="${e}"]`);this.#w(n)}changeLightness({currentTarget:t}){fcn_updateDarken(fcn_siteSettings.darken+parseFloat(t.value))}#w(t){this.toggle(!1),t&&setTimeout((()=>{FcnUtils.scrollTo(t)}),200)}#F(t){this.back(),t?(document.body.classList.add("mobile-menu-open","scrolling-down"),document.body.classList.remove("scrolling-up")):document.body.classList.remove("mobile-menu-open")}#k(t){const e=_$$$("wpadminbar")?.offsetHeight??0,n=window.scrollY,a=FcnGlobals.eSite.scrollTop;this.back(),t?(document.body.classList.add("mobile-menu-open","scrolling-down","scrolled-to-top"),document.body.classList.remove("scrolling-up"),FcnGlobals.eSite.classList.add("transformed-scroll","transformed-site"),FcnGlobals.eSite.scrollTop=n-e):(FcnGlobals.eSite.classList.remove("transformed-site","transformed-scroll"),document.body.classList.remove("mobile-menu-open"),document.documentElement.style.scrollBehavior="auto",window.scroll(0,a+e),document.documentElement.style.scrollBehavior="")}}),application.register("fictioneer-chapter",class extends Stimulus.Controller{static get targets(){return["bookmarkScroll","contentWrapper","index","content"]}static values={chapterId:Number,storyId:Number};startClick=0;lastToolsParagraph=null;tools=_$$$("paragraph-tools");progressBar=_$(".progress__bar");hasPassword=!!_$("article._password");checkmarkUpdated=!1;checkboxProgressBar=_$$$("site-setting-chapter-progress-bar");checkboxMinimalist=_$$$("site-setting-minimal");initialize(){this.progressBar&&this.hasContentTarget&&!this.hasPassword&&(this.trackProgress(),window.addEventListener("scroll.rAF",FcnUtils.throttle(this.trackProgress.bind(this),1e3/48)))}connect(){window.FictioneerApp.Controllers.fictioneerChapter=this,this.hasIndexTarget&&this.indexTargets.forEach((t=>{t.querySelector(`[data-id="${this.chapterIdValue}"]`)?.classList.add("current")}))}clickOutside({detail:{target:t}}){this.lastToolsParagraph&&!t.closest(".selected-paragraph")&&this.closeTools()}scrollToBookmark(){const t=window.FictioneerApp.Controllers.fictioneerBookmarks;if(!t)return void fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning");const e=t.data()?.[`ch-${this.chapterIdValue}`]?.["paragraph-id"];if(!e)return;const n=_$(`[data-paragraph-id="${e}"]`);n?.scrollIntoView({behavior:"smooth"})}openFullscreen(){document.documentElement.requestFullscreen?document.documentElement.requestFullscreen():document.documentElement.webkitRequestFullscreen&&document.documentElement.webkitRequestFullscreen()}closeFullscreen(){document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}toggleTools(t){this.lastToolsParagraph?.classList.remove("selected-paragraph"),this.lastToolsParagraph!==t?(this.lastToolsParagraph=t,t.classList.add("selected-paragraph"),t.append(this.tools)):this.closeTools()}closeTools(){this.lastToolsParagraph?.classList.remove("selected-paragraph"),this.lastToolsParagraph=null}fastClick(t){""==window.getSelection().toString()&&(this.startClick=Date.now(),document.addEventListener("mouseup",(()=>{Date.now()16&&n.replace(/\s/g,"").length){const t=Math.ceil(.25*n.length);let e=fictioneer_tl.partial.quoteFragmentPrefix,a=fictioneer_tl.partial.quoteFragmentSuffix;n.startsWith(s.substring(0,t+1))&&(e=""),n.endsWith(s.substring(s.length-t,s.length))&&(a=""),s=`${e}${n}${a}`}fcn_showNotification(fictioneer_tl.notification.quoteAppendedToComment),FcnUtils.appendToComment(`\n[quote]${s} ${a}[/quote]\n`)}toggleBookmark({target:t}){const e=window.FictioneerApp.Controllers.fictioneerBookmarks;e?(e.toggle(t.closest("p[data-paragraph-id]").dataset.paragraphId,t.closest("[data-color]")?.dataset.color??"none"),window.matchMedia("(min-width: 1024px)").matches&&this.closeTools()):fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning")}copyLink(t){const e=t.target.closest("p[data-paragraph-id]");e&&FcnUtils.copyToClipboard(`${location.protocol}//${location.host}${location.pathname}#${e.id}`,fictioneer_tl.notification.linkCopiedToClipboard)}toggleIndexOrder({currentTarget:t}){const e=t.closest(".chapter-index");e.dataset.order="asc"===e.dataset.order?"desc":"asc"}trackProgress(){if(!this.progressBar||!this.hasContentTarget||this.hasPassword||this.checkboxMinimalist.checked||!(this.checkboxProgressBar?.checked??1))return;const t=this.contentTarget.getBoundingClientRect(),e=t.height,n=e-t.bottom-Math.max(t.top,0)+window.innerHeight;let a=100*n/e;if(document.body.classList.toggle("hasProgressBar",!(a<0||n>e+500)),a=FcnUtils.clamp(0,100,a),this.progressBar.style.width=`${a}%`,!this.checkmarkUpdated&&this.storyIdValue&&a>=100&&FcnUtils.loggedIn()){if(this.checkmarkUpdated=!0,!this.chapterIdValue||"function"!=typeof fcn_toggleCheckmark)return;fcn_toggleCheckmark(this.storyIdValue,this.chapterIdValue,!0)}}#T(t){return!(t.classList.contains("spoiler")||!t.closest("p[data-paragraph-id]")?.textContent.trim().length||!t.closest("p")?.parentElement?.classList.contains("chapter-formatting")||t.closest(".popup-menu-toggle, .skip-tools, .tts-interface, .paragraph-tools__actions, .hidden, .inside-epub, a, button, label, input, textarea, select, option"))}});const fcn_chapterKeyboardNavigation=t=>{if(["INPUT","TEXTAREA","SELECT","OPTION"].includes(t.target.tagName)||t.target.isContentEditable)return;const e={ArrowLeft:"a.button._navigation._prev",ArrowRight:"a.button._navigation._next"};if(!e[t.code])return;const n=_$(e[t.code]);n?.href&&(window.location.href=`${n.href}#start`)};if(document.addEventListener("keydown",fcn_chapterKeyboardNavigation),"#start"===window.location.hash){history.replaceState(null,document.title,window.location.pathname);const t=_$(".chapter__article");t&&FcnUtils.scrollTo(t,128)}const FcnFormatting={eFormattingTarget:_$(".chapter-formatting"),defaults:()=>({"font-saturation":0,"font-color":FcnGlobals.fontColors[0].css,"font-name":FcnGlobals.fonts[0].css,"font-size":100,"letter-spacing":0,"line-height":1.7,"paragraph-spacing":1.5,"site-width":document.documentElement.dataset.siteWidthDefault??"960",indent:!0,"show-sensitive-content":!0,"show-chapter-notes":!0,justify:!1,"show-comments":!0,"show-paragraph-tools":!0,timestamp:1664797604825,...FcnUtils.parseJSON(document.documentElement.dataset.defaultFormatting??"{}")}),get(){let t=FcnUtils.parseJSON(localStorage.getItem("fcnChapterFormatting"))??FcnFormatting.defaults();return Object.keys(t).length<15&&(t=FcnFormatting.defaults(),FcnFormatting.set(t)),t.timestamp<1651164557584&&(t=FcnFormatting.defaults(),t.timestamp=Date.now(),FcnFormatting.set(t)),t},set(t){"object"==typeof t&&localStorage.setItem("fcnChapterFormatting",JSON.stringify(t))}};function fcn_updateToggle(t,e,n,a={}){const s=FcnFormatting.get();a={save:!0,...a};const i=Boolean(t),o=_$(e);if(o&&(o.checked=i,o.closest("label").setAttribute("aria-checked",i)),a.toggleClass&&FcnFormatting.eFormattingTarget.classList.toggle(a.toggleClass,a.invertClass?!i:i),a.sensitiveContent){const t=_$$$("inline-sensitive-content-toggle");t?.classList.toggle("hide-sensitive",!i),t?.setAttribute("aria-checked",!i)}a.notes&&_$$(".chapter-note-hideable").forEach((t=>{t.classList.toggle("hidden",!i)})),a.comments&&_$$(".chapter-comments-hideable").forEach((t=>{t.classList.toggle("hidden",!i)})),s[n]=i,a.save&&FcnFormatting.set(s)}(()=>{"use strict";const t=_$$$("reader-settings-font-size-text"),e=_$$$("reader-settings-font-size-range"),n=_$$$("reader-settings-font-size-reset");if(!n)return;function a(a,s=!0){const i=FcnFormatting.get();a=FcnUtils.clamp(50,200,a??100),t.value=a,e.value=a,n.classList.toggle("_modified",100!=a),_$$(".resize-font").forEach((t=>{t.style.fontSize=`${a}%`})),i["font-size"]=a,s&&FcnFormatting.set(i)}function s(){a(this.value)}function i(){const t=FcnFormatting.get();a(parseFloat(t["font-size"])+parseFloat(this.dataset.modifier))}_$$$("reset-font")?.addEventListener("click",(()=>{a(100)})),n?.addEventListener("click",(()=>{a(100)})),e?.addEventListener("input",FcnUtils.throttle(s,1e3/24)),t?.addEventListener("input",s),_$$$("increase-font")?.addEventListener("click",i),_$$$("decrease-font")?.addEventListener("click",i);a(FcnFormatting.get()["font-size"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-font-color-reset"),e=_$$$("reader-settings-font-color-select");if(!t)return;function n(n,a=!0){const s=FcnFormatting.get();n=FcnUtils.clamp(0,FcnGlobals.fontColors.length-1,n),t.classList.toggle("_modified",n>0),e.value=n,FcnFormatting.eFormattingTarget.style.setProperty("--text-chapter",FcnGlobals.fontColors[n].css),s["font-color"]=FcnGlobals.fontColors[n].css,a&&FcnFormatting.set(s)}t.onclick=()=>{n(0)},e.onchange=t=>{n(t.target.value)},_$$(".font-color-stepper").forEach((t=>{t.addEventListener("click",(t=>{!function(t=1){let a=(e.selectedIndex+parseInt(t))%FcnGlobals.fontColors.length;a=a<0?FcnGlobals.fontColors.length-1:a,n(a)}(t.currentTarget.value)}))}));const a=FcnFormatting.get();n(FcnGlobals.fontColors.findIndex((t=>t.css==a["font-color"])),!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-font-reset"),e=_$$$("reader-settings-font-select");if(!t)return;function n(a,s=!0){const i=FcnFormatting.get();a=FcnUtils.clamp(0,FcnGlobals.fonts.length-1,a);let o=FcnGlobals.fonts[a].css;FcnGlobals.fonts[a].alt&&(o=`${o}, ${FcnGlobals.fonts[a].alt}`),a<0?n(0):(t.classList.toggle("_modified",a>0),e.value=a,_$$(".chapter-font-family").forEach((t=>{t.style.fontFamily=""===o?"var(--ff-system)":o+", var(--ff-system)"})),i["font-name"]=FcnGlobals.fonts[a].css,s&&FcnFormatting.set(i))}t.onclick=()=>{n(0)},e.onchange=t=>{n(t.target.value)},_$$(".font-stepper").forEach((t=>{t.addEventListener("click",(t=>{!function(t=1){let a=(e.selectedIndex+parseInt(t))%FcnGlobals.fonts.length;a=a<0?FcnGlobals.fonts.length-1:a,n(a)}(t.currentTarget.value)}))}));const a=FcnFormatting.get();n(FcnGlobals.fonts.findIndex((t=>t.css==a["font-name"])),!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-font-saturation-text"),e=_$$$("reader-settings-font-saturation-range"),n=_$$$("reader-settings-font-saturation-reset");if(!n)return;function a(a,s=!0){const i=FcnFormatting.get();a=FcnUtils.clamp(-1,1,a??0),t.value=parseInt(100*a),e.value=a,n.classList.toggle("_modified",0!=a),FcnFormatting.eFormattingTarget.style.setProperty("--font-saturation",`(${a>=0?1+a**2:1-a**2} + var(--font-saturation-offset))`),i["font-saturation"]=a,s&&FcnFormatting.set(i)}n?.addEventListener("click",(()=>{a(0)})),e?.addEventListener("input",FcnUtils.throttle((function(){a(this.value)}),1e3/24)),t?.addEventListener("input",(function(){a(parseInt(this.value)/100)}));a(FcnFormatting.get()["font-saturation"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-letter-spacing-text"),e=_$$$("reader-settings-letter-spacing-range"),n=_$$$("reader-settings-letter-spacing-reset"),a=FcnFormatting.defaults()["letter-spacing"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get();s=FcnUtils.clamp(-.1,.2,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),FcnFormatting.eFormattingTarget.style.letterSpacing=`calc(${s}em + var(--font-letter-spacing-base))`,o["letter-spacing"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["letter-spacing"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-paragraph-spacing-text"),e=_$$$("reader-settings-paragraph-spacing-range"),n=_$$$("reader-settings-paragraph-spacing-reset"),a=FcnFormatting.defaults()["paragraph-spacing"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get();s=FcnUtils.clamp(0,3,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),FcnFormatting.eFormattingTarget.style.setProperty("--paragraph-spacing",`${s}em`),o["paragraph-spacing"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["paragraph-spacing"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-line-height-text"),e=_$$$("reader-settings-line-height-range"),n=_$$$("reader-settings-line-height-reset"),a=FcnFormatting.defaults()["line-height"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get();s=FcnUtils.clamp(.8,3,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),FcnFormatting.eFormattingTarget.style.lineHeight=`${s}`,o["line-height"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["line-height"],!1)})(),(()=>{"use strict";const t=_$$$("reader-settings-site-width-text"),e=_$$$("reader-settings-site-width-range"),n=_$$$("reader-settings-site-width-reset"),a=FcnFormatting.defaults()["site-width"];if(!n)return;function s(s,i=!0){const o=FcnFormatting.get(),r=_$("main");s=FcnUtils.clamp(640,1920,s??a),t.value=s,e.value=s,n.classList.toggle("_modified",s!=a),r.style.setProperty("--site-width",`${s}px`),r.classList.toggle("_default-width",s==document.documentElement.dataset.siteWidthDefault),r.classList.toggle("_below-1024",s<1024&&s>=768),r.classList.toggle("_below-768",s<768&&s>640),r.classList.toggle("_640-and-below",s<=640),o["site-width"]=s,i&&FcnFormatting.set(o)}function i(){s(this.value)}n?.addEventListener("click",(()=>{s(a)})),e?.addEventListener("input",FcnUtils.throttle(i,1e3/24)),t?.addEventListener("input",i);s(FcnFormatting.get()["site-width"],!1)})(),_$$("#reader-settings-indent-toggle").forEach((t=>{const e={invertClass:!0,toggleClass:"no-indent"},n="indent";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-justify-toggle").forEach((t=>{const e={toggleClass:"justify"},n="justify";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-paragraph-tools-toggle").forEach((t=>{const e="show-paragraph-tools" +;t.onclick=n=>{fcn_updateToggle(n.currentTarget.checked,`#${t.id}`,e)};fcn_updateToggle(FcnFormatting.get()[e],`#${t.id}`,e,{save:!1})})),_$$("#reader-settings-chapter-notes-toggle").forEach((t=>{const e={notes:!0},n="show-chapter-notes";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-comments-toggle").forEach((t=>{const e={comments:!0},n="show-comments";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})})),_$$("#reader-settings-sensitive-content-toggle").forEach((t=>{const e={toggleClass:"hide-sensitive",invertClass:!0,sensitiveContent:!0},n="show-sensitive-content";t.onclick=a=>{fcn_updateToggle(a.currentTarget.checked,`#${t.id}`,n,e)};fcn_updateToggle(FcnFormatting.get()[n],`#${t.id}`,n,{save:!1,...e})}));var diff_match_patch=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},DIFF_DELETE=-1,DIFF_INSERT=1,DIFF_EQUAL=0;diff_match_patch.Diff=function(t,e){this[0]=t,this[1]=e},diff_match_patch.Diff.prototype.length=2,diff_match_patch.Diff.prototype.toString=function(){return this[0]+","+this[1]},diff_match_patch.prototype.diff_main=function(t,e,n,a){if(void 0===a&&(a=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout),null==t||null==e)throw Error("Null input. (diff_main)");if(t==e)return t?[new diff_match_patch.Diff(DIFF_EQUAL,t)]:[];void 0===n&&(n=!0);var s=n,i=this.diff_commonPrefix(t,e);n=t.substring(0,i),t=t.substring(i),e=e.substring(i),i=this.diff_commonSuffix(t,e);var o=t.substring(t.length-i);return t=t.substring(0,t.length-i),e=e.substring(0,e.length-i),t=this.diff_compute_(t,e,s,a),n&&t.unshift(new diff_match_patch.Diff(DIFF_EQUAL,n)),o&&t.push(new diff_match_patch.Diff(DIFF_EQUAL,o)),this.diff_cleanupMerge(t),t},diff_match_patch.prototype.diff_compute_=function(t,e,n,a){if(!t)return[new diff_match_patch.Diff(DIFF_INSERT,e)];if(!e)return[new diff_match_patch.Diff(DIFF_DELETE,t)];var s=t.length>e.length?t:e,i=t.length>e.length?e:t,o=s.indexOf(i);return-1!=o?(n=[new diff_match_patch.Diff(DIFF_INSERT,s.substring(0,o)),new diff_match_patch.Diff(DIFF_EQUAL,i),new diff_match_patch.Diff(DIFF_INSERT,s.substring(o+i.length))],t.length>e.length&&(n[0][0]=n[2][0]=DIFF_DELETE),n):1==i.length?[new diff_match_patch.Diff(DIFF_DELETE,t),new diff_match_patch.Diff(DIFF_INSERT,e)]:(s=this.diff_halfMatch_(t,e))?(e=s[1],i=s[3],t=s[4],s=this.diff_main(s[0],s[2],n,a),n=this.diff_main(e,i,n,a),s.concat([new diff_match_patch.Diff(DIFF_EQUAL,t)],n)):n&&100n);m++){for(var p=-m+h;p<=m-f;p+=2){for(var _=i+p,v=p==-m||p!=m&&r[_-1]a)f+=2;else if(b>s)h+=2;else if(d&&(0<=(_=i+l-p)&&_=k)return this.diff_bisectSplit_(t,e,v,b,n)}}for(p=-m+g;p<=m-u;p+=2){for(_=i+p,v=(k=p==-m||p!=m&&c[_-1]a)u+=2;else if(v>s)g+=2;else if(!d&&(0<=(_=i+l-p)&&_=(k=a-k))))return this.diff_bisectSplit_(t,e,v,b,n)}}return[new diff_match_patch.Diff(DIFF_DELETE,t),new diff_match_patch.Diff(DIFF_INSERT,e)]},diff_match_patch.prototype.diff_bisectSplit_=function(t,e,n,a,s){var i=t.substring(0,n),o=e.substring(0,a);return t=t.substring(n),e=e.substring(a),i=this.diff_main(i,o,!1,s),s=this.diff_main(t,e,!1,s),i.concat(s)},diff_match_patch.prototype.diff_linesToChars_=function(t,e){function n(t){for(var e="",n=0,o=-1,r=a.length;oa?t=t.substring(n-a):n=t.length?[a,s,o,r,d]:null}if(0>=this.Diff_Timeout)return null;var a=t.length>e.length?t:e,s=t.length>e.length?e:t;if(4>a.length||2*s.lengtha[4].length?o:a:o,t.length>e.length){a=o[0],s=o[1];var r=o[2],c=o[3]}else r=o[0],c=o[1],a=o[2],s=o[3];return[a,s,r,c,o[4]]},diff_match_patch.prototype.diff_cleanupSemantic=function(t){for(var e=!1,n=[],a=0,s=null,i=0,o=0,r=0,c=0,l=0;i=(s=this.diff_commonOverlap_(n,e))?(a>=e.length/2||a>=n.length/2)&&(t.splice(i,0,new diff_match_patch.Diff(DIFF_EQUAL,n.substring(0,a))),t[i-1][1]=e.substring(0,e.length-a),t[i+1][1]=n.substring(a),i++):(s>=e.length/2||s>=n.length/2)&&(t.splice(i,0,new diff_match_patch.Diff(DIFF_EQUAL,e.substring(0,s))),t[i-1][0]=DIFF_INSERT,t[i-1][1]=n.substring(0,n.length-s),t[i+1][0]=DIFF_DELETE,t[i+1][1]=e.substring(s),i++),i++),i++},diff_match_patch.prototype.diff_cleanupSemanticLossless=function(t){function e(t,e){if(!t||!e)return 6;var n=t.charAt(t.length-1),a=e.charAt(0),s=n.match(diff_match_patch.nonAlphaNumericRegex_),i=a.match(diff_match_patch.nonAlphaNumericRegex_),o=s&&n.match(diff_match_patch.whitespaceRegex_),r=i&&a.match(diff_match_patch.whitespaceRegex_);n=o&&n.match(diff_match_patch.linebreakRegex_),a=r&&a.match(diff_match_patch.linebreakRegex_);var c=n&&t.match(diff_match_patch.blanklineEndRegex_),l=a&&e.match(diff_match_patch.blanklineStartRegex_);return c||l?5:n||a?4:s&&!o&&r?3:o||r?2:s||i?1:0}for(var n=1;n=l&&(l=d,o=a,r=s,c=i)}t[n-1][1]!=o&&(o?t[n-1][1]=o:(t.splice(n-1,1),n--),t[n][1]=r,c?t[n+1][1]=c:(t.splice(n+1,1),n--))}n++}},diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/,diff_match_patch.whitespaceRegex_=/\s/,diff_match_patch.linebreakRegex_=/[\r\n]/,diff_match_patch.blanklineEndRegex_=/\n\r?\n$/,diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/,diff_match_patch.prototype.diff_cleanupEfficiency=function(t){for(var e=!1,n=[],a=0,s=null,i=0,o=!1,r=!1,c=!1,l=!1;ie));n++)i=a,o=s;return t.length!=n&&t[n][0]===DIFF_DELETE?o:o+(e-i)},diff_match_patch.prototype.diff_prettyHtml=function(t){for(var e=[],n=/&/g,a=//g,i=/\n/g,o=0;o");switch(r){case DIFF_INSERT:e[o]=''+c+"";break;case DIFF_DELETE:e[o]=''+c+"";break;case DIFF_EQUAL:e[o]=""+c+""}}return e.join("")},diff_match_patch.prototype.diff_text1=function(t){for(var e=[],n=0;nthis.Match_MaxBits)throw Error("Pattern too long for this browser.");var s=this.match_alphabet_(e),i=this,o=this.Match_Threshold,r=t.indexOf(e,n);-1!=r&&(o=Math.min(a(0,r),o),-1!=(r=t.lastIndexOf(e,n+e.length))&&(o=Math.min(a(0,r),o)));var c=1<=l;u--){var m=s[t.charAt(u-1)];if(d[u]=0===g?(d[u+1]<<1|1)&m:(d[u+1]<<1|1)&m|(h[u+1]|h[u])<<1|1|h[u+1],d[u]&c&&(m=a(g,u-1))<=o){if(o=m,!((r=u-1)>n))break;l=Math.max(1,2*n-r)}}if(a(g+1,n)>o)break;h=d}return r},diff_match_patch.prototype.match_alphabet_=function(t){for(var e={},n=0;n=2*this.Patch_Margin&&s&&(this.patch_addContext_(t,r),n.push(t),t=new diff_match_patch.patch_obj,s=0,r=a,i=o)}l!==DIFF_INSERT&&(i+=d.length),l!==DIFF_DELETE&&(o+=d.length)}return s&&(this.patch_addContext_(t,r),n.push(t)),n},diff_match_patch.prototype.patch_deepCopy=function(t){for(var e=[],n=0;nthis.Match_MaxBits){var l=this.match_main(e,r.substring(0,this.Match_MaxBits),o);-1!=l&&(-1==(c=this.match_main(e,r.substring(r.length-this.Match_MaxBits),o+r.length-this.Match_MaxBits))||l>=c)&&(l=-1)}else l=this.match_main(e,r,o);if(-1==l)s[i]=!1,a-=t[i].length2-t[i].length1;else if(s[i]=!0,a=l-o,r==(o=-1==c?e.substring(l,l+r.length):e.substring(l,c+this.Match_MaxBits)))e=e.substring(0,l)+this.diff_text2(t[i].diffs)+e.substring(l+r.length);else if(o=this.diff_main(r,o,!1),r.length>this.Match_MaxBits&&this.diff_levenshtein(o)/r.length>this.Patch_DeleteThreshold)s[i]=!1;else{var d;for(this.diff_cleanupSemanticLossless(o),r=0,c=0;cs[0][1].length){var i=e-s[0][1].length;s[0][1]=n.substring(s[0][1].length)+s[0][1],a.start1-=i,a.start2-=i,a.length1+=i,a.length2+=i}return 0==(s=(a=t[t.length-1]).diffs).length||s[s.length-1][0]!=DIFF_EQUAL?(s.push(new diff_match_patch.Diff(DIFF_EQUAL,n)),a.length1+=e,a.length2+=e):e>s[s.length-1][1].length&&(i=e-s[s.length-1][1].length,s[s.length-1][1]+=n.substring(0,i),a.length1+=i,a.length2+=i),n},diff_match_patch.prototype.patch_splitMax=function(t){for(var e=this.Match_MaxBits,n=0;n2*e?(r.length1+=l.length,s+=l.length,c=!1,r.diffs.push(new diff_match_patch.Diff(o,l)),a.diffs.shift()):(l=l.substring(0,e-r.length1-this.Patch_Margin),r.length1+=l.length,s+=l.length,o===DIFF_EQUAL?(r.length2+=l.length,i+=l.length):c=!1,r.diffs.push(new diff_match_patch.Diff(o,l)),l==a.diffs[0][1]?a.diffs.shift():a.diffs[0][1]=a.diffs[0][1].substring(l.length))}o=(o=this.diff_text2(r.diffs)).substring(o.length-this.Patch_Margin),""!==(l=this.diff_text1(a.diffs).substring(0,this.Patch_Margin))&&(r.length1+=l.length,r.length2+=l.length,0!==r.diffs.length&&r.diffs[r.diffs.length-1][0]===DIFF_EQUAL?r.diffs[r.diffs.length-1][1]+=l:r.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL,l))),c||t.splice(++n,0,r)}}},diff_match_patch.prototype.patch_toText=function(t){for(var e=[],n=0;n/g,i=/\n/g,o=0;o");switch(r){case 1:e[o]=`${c}`;break;case-1:e[o]=`${c}`;break;case 0:e[o]=`${c}`}}return e.join("")},application.register("fictioneer-suggestion",class extends Stimulus.Controller{modal=_$$$("suggestions-modal");floatingButton=_$$$("selection-tools");input=_$$$("suggestions-modal-input");current=_$$$("suggestions-modal-original");diff=_$$$("suggestions-modal-diff");reset=_$$$("button-suggestion-reset");submit=_$$$("button-suggestion-submit");original="";text="";open=!1;paragraph=null;dmp=new diff_match_patch;initialize(){this.floatingButton&&this.floatingButton.addEventListener("click",(t=>{this.toggleModalViaSelection(t.currentTarget)})),this.input.addEventListener("input",(()=>this.#E())),this.reset.addEventListener("click",(()=>this.#y())),this.submit.addEventListener("click",(()=>this.#$()))}connect(){window.FictioneerApp.Controllers.fictioneerSuggestion=this}clickOutside(){this.open&&this.#L()}toggleModalViaSelection(t){this.paragraph=this.#S(),this.toggleModalVisibility(t)}toggleModalViaParagraph(t){this.paragraph=_$(".selected-paragraph"),this.text=FcnUtils.extractTextNodes(this.paragraph),this.toggleModalVisibility(t.currentTarget)}toggleModalVisibility(t){const e=fcn(),n=window.FictioneerApp.Controllers.fictioneerChapter;e?n?(e.toggleModalVisibility(t,"suggestions-modal"),n.closeTools(),this.#C(),this.original=this.text,this.current.innerText=this.text,this.diff.innerText=this.text,this.input.value=this.text,this.input.focus()):fcn_showNotification("Error: Chapter Controller not connected.",3,"warning"):fcn_showNotification("Error: Fictioneer Controller not connected.",3,"warning")}toggleFloatingButton(){FcnGlobals.eSite.classList.contains("transformed-site")||window.getSelection().rangeCount<1||!window.getSelection().getRangeAt(0).startContainer.parentNode.closest(".content-section")||setTimeout((()=>{if(this.text=window.getSelection().toString().replaceAll("\n\n","\n").trim(),""!==this.text){const t=this.#I();this.#D(t.x,t.y)}else this.#L()}),10)}closeModal(){this.open=!1,this.original="",this.text="",this.paragraph=null,fcn().closeModals()}#D(t,e){this.open=!0;const n=document.documentElement.offsetWidth/2+this.floatingButton.offsetWidth,a=_$$$("wpadminbar")?.offsetHeight??0;this.floatingButton.style.transform=t>n?"translate(-100%)":"translate(0)",this.floatingButton.style.top=e+4-a+"px",this.floatingButton.style.left=`${t}px`,this.floatingButton.classList.remove("invisible")}#L(){this.open=!1,this.floatingButton.style.top="0",this.floatingButton.style.left="-1000px",this.floatingButton.classList.add("invisible")}#S(){const t=window.getSelection();return t.rangeCount?t.getRangeAt(0).startContainer.parentNode.closest("p"):null}#I(){let t=0,e=0;if(void 0!==window.getSelection){const n=window.getSelection();if(0!==n.rangeCount){let a=n.getRangeAt(0).cloneRange().getClientRects();a=a[a.length-1],a&&(t=a.right+window.scrollX,e=a.bottom+window.scrollY)}}return{x:t,y:e}}#C(){window.getSelection&&(window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges())}#E(){this.diff.innerHTML=this.#x(this.original,this.input.value)}#y(){this.input.value=this.original,this.diff.innerText=this.original}#x(t,e){const n=this.dmp.diff_main(t,e);return this.dmp.diff_cleanupEfficiency(n),this.dmp.fcn_prettyHtml(n)}#$(){const t=this.paragraph?.id??null;let e=this.diff.innerHTML;[["¶","¶\n"],["
","\n"],["","[ins]"],["","[/ins]"],["","[del]"],["","[/del]"]].forEach((([t,n])=>{e=e.replaceAll(t,n)})),t&&(e=`${e} [anchor]${t}[/anchor]`),FcnUtils.appendToComment(`\n[quote]${e}[/quote]\n`),this.closeModal(),fcn_showNotification(fictioneer_tl.notification.suggestionAppendedToComment)}});const fcn_ttsInterface=_$$$("tts-interface");var fcn_utter,fcn_synth,fcn_ttsStack=[],fcn_currentReadingId=-1,fcn_ttsPauseTimestamp=-1,fcn_ttsCurrentText="",fcn_ttsSettings=fcn_getTTSsettings(),fcn_voices=[];if("undefined"!=typeof speechSynthesis&&fcn_ttsInterface){fcn_synth=window.speechSynthesis,(fcn_utter=new SpeechSynthesisUtterance).lang=document.documentElement.lang;const t=setTimeout((()=>{fcn_setupTTS()}),2e3);"onvoiceschanged"in speechSynthesis&&fcn_synth.addEventListener("voiceschanged",(()=>{fcn_setupTTS(),clearTimeout(t)}),{once:!0})}function fcn_setupTTS(){fcn_voices.length>0||(fcn_setUpVoices(),fcn_updateVolume(fcn_ttsSettings.volume),fcn_updatePitch(fcn_ttsSettings.pitch),fcn_updateRate(fcn_ttsSettings.rate))}function fcn_setTTSsettings(t){fcn_ttsSettings=t,localStorage.setItem("ttsSettings",JSON.stringify(t))}function fcn_getTTSsettings(){const t=FcnUtils.parseJSON(localStorage.getItem("ttsSettings"))??{};return fcn_setTTSsettings(t),t}function fcn_setUpVoices(){const t=fcn_synth.getVoices(),e=_$$$("tts-voice-select");if(!e)return;let n=0;for(let a=0;a{fcn_updateVoice(t.currentTarget.value)})),fcn_updateVoice(fcn_ttsSettings.voice))}function fcn_updateVoice(t){if(isNaN(t)||void 0===fcn_voices[t]){let e=fcn_voices.findIndex((t=>"Samantha"===t.name&&("en-US"===t.lang||"en_US"===t.lang)));e<0&&(e=fcn_voices.findIndex((t=>"en-US"===t.lang||"en_US"===t.lang))),t=e>-1?e:0}fcn_utter.voice=fcn_voices[t],_$$$("tts-voice-select").value=t,fcn_ttsSettings.voice=t,fcn_setTTSsettings(fcn_ttsSettings)}function fcn_updateVolume(t){t=isNaN(t)?100:parseInt(t),t=FcnUtils.clamp(0,100,t),_$$$("tts-volume-range").value=t,_$$$("tts-volume-text").value=t,_$$$("tts-volume-reset").classList.toggle("_modified",100!=t),fcn_ttsSettings.volume=t,fcn_setTTSsettings(fcn_ttsSettings),fcn_utter.volume=t/100}function fcn_updatePitch(t){t=isNaN(t)?1:parseFloat(t),t=FcnUtils.clamp(.2,1.8,t),_$$$("tts-pitch-range").value=t,_$$$("tts-pitch-text").value=t,_$$$("tts-pitch-reset").classList.toggle("_modified",1!=t),fcn_ttsSettings.pitch=t,fcn_setTTSsettings(fcn_ttsSettings),fcn_utter.pitch=t}function fcn_updateRate(t){t=isNaN(t)?1:parseFloat(t),t=FcnUtils.clamp(.2,1.8,t),_$$$("tts-rate-range").value=t,_$$$("tts-rate-text").value=t,_$$$("tts-rate-reset").classList.toggle("_modified",1!=t),fcn_ttsSettings.rate=t,fcn_setTTSsettings(fcn_ttsSettings),fcn_utter.rate=t}function fcn_readTextStack(){const t=_$(".current-reading");if(0===fcn_ttsStack.length)return fcn_ttsInterface.classList.add("ended"),t&&t.classList.remove("current-reading"),fcn_currentReadingId=-1,void(fcn_ttsCurrentText="");const e=fcn_ttsStack.shift();fcn_ttsCurrentText=e[1],fcn_currentReadingId!=e[0]&&(fcn_currentReadingId=e[0],t&&t.classList.remove("current-reading"),_$$$(fcn_currentReadingId).classList.add("current-reading")),fcn_utter.text=fcn_ttsCurrentText,fcn_utter.addEventListener("end",fcn_readTextStack,{once:!0}),fcn_synth.speak(fcn_utter)}function fcn_cleanUpActions(){_$$(".story__actions > *").forEach((t=>{const e=window.getComputedStyle(t);"none"!==e.display&&"hidden"!==e.visibility||t.remove()}))}function fcn_unsetOauth(t){const e=prompt(t.dataset.warning);e&&e.toLowerCase()==t.dataset.confirm.toLowerCase()&&FcnUtils.remoteAction("fictioneer_ajax_unset_my_oauth",{nonce:t.dataset.nonce,element:_$$$(`oauth-${t.dataset.channel}`),payload:{channel:t.dataset.channel,id:t.dataset.id},callback:(t,e)=>{t.success?(e.classList.remove("_connected"),e.classList.add("_disconnected"),e.querySelector("button").remove(),fcn_showNotification(e.dataset.unset)):e.style.background="var(--notice-warning-background)"},errorCallback:(t,e)=>{e.style.background="var(--notice-warning-background)"}})}function fcn_deleteMyAccount(t){const e=prompt(t.dataset.warning);e&&e.toLowerCase()==t.dataset.confirm.toLowerCase()&&(t.disabled=!0,FcnUtils.remoteAction("fictioneer_ajax_delete_my_account",{nonce:t.dataset.nonce,element:t,payload:{id:t.dataset.id},callback:(t,e)=>{t.success?location.reload():e.innerHTML=t.data.button},errorCallback:(t,e)=>{e.innerHTML=t.status??fictioneer_tl.notification.error}}))}function fcn_dataDeletionPrompt(t){const e=prompt(t.dataset.warning);return!(!e||e.toLowerCase()!=t.dataset.confirm.toLowerCase())}function fcn_clearData(t,e){const n=t.closest(".card");localStorage.removeItem("fcnBookshelfContent"),t.remove(),FcnUtils.remoteAction(e,{nonce:t.dataset.nonce,element:n,callback:(t,e)=>{t.success&&e&&(e.querySelector(".card__content").innerHTML=t.data.success)}})}function fcn_toggleFollow(t,e=null){const n=window.FictioneerApp.Controllers.fictioneerFollows;if(!n)return void fcn_showNotification("Error: Follows Controller not connected.",3,"warning");const a=FcnUtils.userData();(e=e??!a.follows.data[t])?a.follows.data[t]={story_id:parseInt(t),timestamp:Date.now()}:delete a.follows.data[t],a.lastLoaded=0,FcnUtils.setUserData(a),n.refreshView(),clearTimeout(n.timeout),n.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_toggle_follow",{payload:{set:e,story_id:t}})}),FcnGlobals.debounceRate)}function fcn_toggleCheckmark(t,e=null,n=null){const a=window.FictioneerApp.Controllers.fictioneerCheckmarks;if(!a)return void fcn_showNotification("Error: Checkmarks Controller not connected.",3,"warning");const s=FcnUtils.userData();let i="story";if((t=parseInt(t??0))<1)return void fcn_showNotification("Error: Invalid story ID.",3,"warning");if(null!==e){if((e=parseInt(e))<1)return void fcn_showNotification("Error: Invalid chapter ID.",3,"warning");i="chapter"}s.checkmarks.data[t]||(s.checkmarks.data[t]=[]),null===n&&(n="chapter"===i?!s.checkmarks.data[t]?.includes(e):!s.checkmarks.data[t]?.includes(t));const o="chapter"===i?e:t;n?s.checkmarks.data[t].push(o):(FcnUtils.removeArrayItemOnce(s.checkmarks.data[t],o), +"chapter"===i&&FcnUtils.removeArrayItemOnce(s.checkmarks.data[t],t)),s.checkmarks.data[t]=s.checkmarks.data[t].filter(((t,e,n)=>n.indexOf(t)==e)),s.lastLoaded=0,FcnUtils.setUserData(s),a.refreshView(),clearTimeout(a.timeout),a.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_set_checkmark",{payload:{update:s.checkmarks.data[t].join(" "),story_id:t}})}),FcnGlobals.debounceRate)}function fcn_toggleReminder(t,e=null){const n=window.FictioneerApp.Controllers.fictioneerReminders;if(!n)return void fcn_showNotification("Error: Reminders Controller not connected.",3,"warning");const a=FcnUtils.userData();(e=e??!a.reminders.data[t])?a.reminders.data[t]={story_id:parseInt(t),timestamp:Date.now()}:delete a.reminders.data[t],a.lastLoaded=0,FcnUtils.setUserData(a),n.refreshView(),clearTimeout(n.timeout),n.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_toggle_reminder",{payload:{set:e,story_id:t}})}),FcnGlobals.debounceRate)}function fcn_wrapInTag(t,e,n={}){const a=n.href?' href="'+n.href+'" target="_blank" rel="nofollow noreferrer noopener"':"",s=n.shortcode?["[","]"]:["<",">"],i=t.selectionStart,o=t.selectionEnd,r=s[0]+e+a+s[1],c=s[0]+"/"+e+s[1],l=r+t.value.substring(i,o)+c;t.value=t.value.substring(0,i)+l+t.value.substring(o,t.value.length),t.setSelectionRange(i+r.length,o+r.length),t.focus()}"undefined"!=typeof speechSynthesis&&fcn_ttsInterface&&(_$$$("button-tts-set").addEventListener("click",(t=>{fcn_ttsStack=[],fcn_currentReadingId=-1;const e=_$(".chapter-formatting")?.classList.contains("hide-sensitive")??!1?"sensitive-content":"sensitive-alternative",n=_$$$("button-tts-play"),a=new RegExp(fcn_ttsInterface.dataset.regex,"gm");fcn_synth.speaking&&fcn_utter.removeEventListener("end",fcn_readTextStack),fcn_synth.cancel();const s=new Set(["P","H1","H2","H3","H4","H5","H6"]),i=["skip-tts","inside-epub",e];let o=t.target.closest("p[data-paragraph-id]");for(fcn_ttsStack.push(o);o=o.nextElementSibling;)s.has(o.tagName)&&!i.some((t=>o.classList.contains(t)))&&fcn_ttsStack.push(o);fcn_ttsStack=fcn_ttsStack.flatMap((t=>{const e=[],n=t.querySelector(".paragraph-inner");return(n?n.textContent:t.textContent).replace(a,"$1|").split("|").forEach((n=>{const a=n.trim();a.length>0&&e.push([t.id,a])})),e})),fcn_readTextStack(),document.body.classList.add("tts-open"),fcn_ttsInterface.classList.remove("hidden","ended","paused"),fcn_ttsInterface.classList.add("playing"),n.focus(),n.blur()})),_$$$("button-tts-stop")?.addEventListener("click",(()=>{const t=_$(".current-reading");fcn_ttsInterface.classList.add("hidden","ended"),fcn_ttsInterface.classList.remove("playing","paused"),document.body.classList.remove("tts-open"),t&&t.classList.remove("current-reading"),fcn_ttsStack=[],fcn_currentReadingId=-1,fcn_utter.removeEventListener("end",fcn_readTextStack),fcn_synth.cancel()})),_$$$("button-tts-play")?.addEventListener("click",(()=>{fcn_synth.resume(),-1!==fcn_ttsPauseTimestamp&&Date.now()-fcn_ttsPauseTimestamp>1e4&&(fcn_ttsStack.unshift([fcn_currentReadingId,fcn_ttsCurrentText]),fcn_synth.cancel(),fcn_readTextStack(),fcn_ttsPauseTimestamp=-1),fcn_ttsInterface.classList.add("playing"),fcn_ttsInterface.classList.remove("paused")})),_$$$("button-tts-pause")?.addEventListener("click",(()=>{fcn_synth.pause(),fcn_ttsPauseTimestamp=Date.now(),fcn_ttsInterface.classList.remove("playing"),fcn_ttsInterface.classList.add("paused")})),_$$$("button-tts-skip")?.addEventListener("click",(()=>{fcn_utter.removeEventListener("end",fcn_readTextStack),fcn_synth.cancel(),fcn_readTextStack(),fcn_ttsInterface.classList.remove("paused"),fcn_ttsInterface.classList.add("playing")})),_$$$("button-tts-scroll")?.addEventListener("click",(()=>{FcnUtils.scrollTo(_$(`p[id="${fcn_currentReadingId}"]`),128)})),_$$("#tts-volume-range, #tts-volume-text").forEach((t=>{t.addEventListener("input",(t=>{fcn_updateVolume(t.target.value)}))})),_$$$("tts-volume-reset")?.addEventListener("click",(()=>{fcn_updateVolume(100)})),_$$("#tts-pitch-range, #tts-pitch-text").forEach((t=>{t.addEventListener("input",(t=>{fcn_updatePitch(t.target.value)}))})),_$$$("tts-pitch-reset")?.addEventListener("click",(()=>{fcn_updatePitch(1)})),_$$("#tts-rate-range, #tts-rate-text").forEach((t=>{t.addEventListener("input",(t=>{fcn_updateRate(t.target.value)}))})),_$$$("tts-rate-reset")?.addEventListener("click",(()=>{fcn_updateRate(1)})),window.addEventListener("beforeunload",(()=>{fcn_synth.cancel()}))),application.register("fictioneer-story",class extends Stimulus.Controller{static get targets(){return["tab","tabContent","commentsPlaceholder","commentsWrapper","commentsList"]}static values={id:Number};commentPage=1;connect(){window.FictioneerApp.Controllers.fictioneerStory=this,this.#U()}toggleChapterOrder(){const t=this.#M();t.order="asc"===t.order?"desc":"asc",this.#A(t),this.#U()}toggleChapterView(){const t=this.#M();t.view="list"===t.view?"grid":"list",this.#A(t),this.#U()}unfoldChapters(t){const e=t.currentTarget.closest(".chapter-group[data-folded]");e&&(e.dataset.folded="true"==e.dataset.folded?"false":"true")}toggleTab(t){const e=t.currentTarget;this.tabTargets.forEach((t=>{t.classList.remove("_current")})),this.tabContentTargets.forEach((e=>{e.dataset.tabName===t.params.tabName?e.classList.add("_current"):e.classList.remove("_current")})),e.classList.add("_current")}loadComments(t){this.hasIdValue&&this.hasCommentsListTarget&&(t.currentTarget.remove(),this.hasCommentsPlaceholderTarget&&this.commentsPlaceholderTarget.classList.remove("hidden"),FcnUtils.aGet({post_id:this.idValue,page:this.commentPage},"get_story_comments").then((t=>{this.hasCommentsPlaceholderTarget&&this.commentsPlaceholderTarget.remove(),t.success?(this.commentsListTarget.innerHTML+=t.data.html,this.commentPage++):t.data?.error&&this.commentsListTarget.appendChild(FcnUtils.buildErrorNotice(t.data.error))})).catch((t=>{this.hasCommentsPlaceholderTarget&&this.commentsPlaceholderTarget.remove(),this.commentsListTarget.appendChild(FcnUtils.buildErrorNotice(t))})))}startEpubDownload(t){t.preventDefault(),this.#R(t.currentTarget,0)}#M(){let t=FcnUtils.parseJSON(localStorage.getItem("fcnStorySettings"))??this.#N();return t.timestamp<1674770712849&&(t=this.#N(),t.timestamp=Date.now()),this.#A(t),t}#N(){return{view:"list",order:"asc",timestamp:1674770712849}}#A(t){"object"==typeof t&&localStorage.setItem("fcnStorySettings",JSON.stringify(t))}#U(){const t=this.#M();"object"==typeof t&&(_$$("[data-view]").forEach((e=>{e.dataset.view=t.view})),_$$("[data-order]").forEach((e=>{e.dataset.order=t.order})))}#R(t,e=0){!t.classList.contains("ajax-in-progress")&&this.hasIdValue&&(e>3?t.classList.remove("ajax-in-progress"):(t.classList.add("ajax-in-progress"),FcnUtils.aGet({action:"fictioneer_ajax_download_epub",story_id:this.idValue}).then((n=>{n.success?(window.location.href=t.href,setTimeout((()=>{t.classList.remove("ajax-in-progress")}),2e3)):setTimeout((()=>{fcn_startEpubDownload(t,e+1)}),2e3)})).catch((e=>{t.classList.remove("ajax-in-progress"),e.status&&e.statusText&&fcn_showNotification(`${e.status}: ${e.statusText}`,5,"warning")}))))}}),document.addEventListener("fcnUserDataReady",(()=>{fcn_cleanUpActions()})),_$$(".button-unset-oauth").forEach((t=>{t.addEventListener("click",(t=>{fcn_unsetOauth(t.currentTarget)}))})),_$$$("button-delete-my-account")?.addEventListener("click",(t=>{fcn_deleteMyAccount(t.currentTarget)})),_$(".button-clear-comments")?.addEventListener("click",(t=>{fcn_dataDeletionPrompt(t.currentTarget)&&fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_comments")})),_$(".button-clear-comment-subscriptions")?.addEventListener("click",(t=>{fcn_dataDeletionPrompt(t.currentTarget)&&fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_comment_subscriptions")})),_$(".button-clear-checkmarks")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerCheckmarks;if(!e)return void fcn_showNotification("Error: Checkmarks Controller not connected.",3,"warning");e.clear(),fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_checkmarks",!0)}})),_$(".button-clear-reminders")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerReminders;if(!e)return void fcn_showNotification("Error: Reminders Controller not connected.",3,"warning");e.clear(),fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_reminders",!0)}})),_$(".button-clear-follows")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerFollows;if(!e)return void fcn_showNotification("Error: Follows Controller not connected.",3,"warning");e.clear(),fcn_clearData(t.currentTarget,"fictioneer_ajax_clear_my_follows",!0)}})),_$(".button-clear-bookmarks")?.addEventListener("click",(t=>{if(fcn_dataDeletionPrompt(t.currentTarget)){const e=window.FictioneerApp.Controllers.fictioneerBookmarks,n=_$$$("profile-data-translations")?.dataset;if(!e)return void fcn_showNotification("Error: Bookmarks Controller not connected.",3,"warning");e.clear(),t.currentTarget.closest(".card").querySelector(".card__content").innerHTML=n.clearedSuccess}})),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.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.#n=!0,this.refreshView(),this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerBookmarks=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.bookmarksCachedData=FcnUtils.loggedIn()?this.#j():this.#B(),this.#P(this.bookmarksCachedData).data}toggle(t,e="none"){if(!this.chapterId)return;const n=this.data(),a=n[this.chapterId];if(a&&a["paragraph-id"]==t)"none"!==e&&e!==a.color?n[this.chapterId].color=e:delete n[this.chapterId];else{Object.keys(n).length>=50&&delete n[Object.keys(n)[0]];const a=_$(`[data-paragraph-id="${t}"]`),s=_$$$("chapter-bookmark-data").dataset;n[this.chapterId]={"paragraph-id":t,progress:100*(FcnUtils.offset(a).top-FcnUtils.offset(a.parentElement).top)/a.parentElement.clientHeight,date:(new Date).toISOString(),color:e,chapter:s.title.trim(),link:s.link,thumb:s.thumb,image:s.image,story:s.storyTitle.trim(),content:FcnUtils.extractTextNodes(a).substring(0,128)+"…"}}this.set(n),this.refreshView()}remove({params:{id:t}}){const e=this.data();delete e[t],this.set(e),this.refreshView()}clear(){this.set({data:{}}),this.refreshView()}set(t){if("object"!=typeof t)return;t=this.#P({data:t});const e=JSON.stringify(t);if(FcnUtils.loggedIn()){const t=fcn().userData();t&&(t.bookmarks=e,fcn().setUserData(t)),this.#O(e),localStorage.removeItem("fcnChapterBookmarks")}else localStorage.setItem("fcnChapterBookmarks",e)}refreshView(){const t=this.data(),e=Object.keys(t).length;this.hasOverviewPageIconLinkTarget&&this.overviewPageIconLinkTargets.forEach((t=>{t.classList.toggle("hidden",e<1)})),this.refreshChapterBookmark(),this.refreshCards(),this.refreshProfile()}refreshCards(){if(!this.hasShortcodeBlockTarget)return;const t=this.data(),e=Object.keys(t).length<1;this.shortcodeBlockTargets.forEach((t=>{t.classList.toggle("hidden",e)})),_$$(".show-if-bookmarks").forEach((t=>{t.classList.toggle("hidden",e)})),this.hasNoBookmarksNoteTarget&&this.noBookmarksNoteTargets.forEach((t=>{t.classList.toggle("hidden",!e)})),!e&&this.cardTemplate?this.shortcodeBlockTargets.forEach((e=>{const n=e.querySelector("ul"),a=document.createDocumentFragment(),s=Object.entries(t).sort(((t,e)=>new Date(e[1].date)-new Date(t[1].date)));let i=parseInt(e.dataset.count)??8;s.forEach((([t,{color:e,progress:n,link:s,chapter:o,"paragraph-id":r,date:c,image:l,thumb:d,content:h}])=>{if(0==i--)return;const f=this.cardTemplate.content.cloneNode(!0),g=new Date(c).toLocaleDateString(navigator.language??"en-US",{year:"2-digit",month:"short",day:"numeric"});l&&f.querySelector(".bookmark-card__image")?(f.querySelector(".bookmark-card__image").href=l,f.querySelector(".bookmark-card__image img").src=d):f.querySelector(".bookmark-card__image")?.remove(),f.querySelector(".bookmark-card__excerpt").innerHTML+=h,f.querySelector(".bookmark-card").classList.add(`bookmark-${t}`),f.querySelector(".bookmark-card").dataset.color=e,f.querySelector(".bookmark-card__title > a").href=`${s}#paragraph-${r}`,f.querySelector(".bookmark-card__title > a").innerText=o,f.querySelector(".bookmark-card__percentage").innerText=`${n.toFixed(1)} %`,f.querySelector(".bookmark-card__progress").style.width=`calc(${n.toFixed(1)}% - var(--bookmark-progress-offset, 0px))`,f.querySelector("time").innerText=g,f.querySelector(".button-delete-bookmark").setAttribute("data-fictioneer-bookmarks-id-param",t),a.appendChild(f)})),n.innerHTML="",n.appendChild(a)})):this.shortcodeBlockTargets.forEach((t=>{t.querySelector("ul").innerHTML=""}))}refreshProfile(){this.hasDataCardTarget&&(this.dataCardTarget.innerHTML=this.dataCardTarget.innerHTML.replace("%s",Object.keys(this.data()).length))}refreshChapterBookmark(){const t=this.data();if(this.currentBookmark?.classList.remove("current-bookmark"),!this.chapterId||!t[this.chapterId])return;const e=t[this.chapterId]["paragraph-id"],n=_$(`[data-paragraph-id="${e}"]`),a=t[this.chapterId].color??"none";e&&n&&(n.classList.add("current-bookmark"),n.setAttribute("data-bookmark-color",a),this.currentBookmark=n,this.hasBookmarkScrollTarget&&this.bookmarkScrollTargets.forEach((t=>t.removeAttribute("hidden"))))}#n=!1;#p=!1;#B(){return FcnUtils.parseJSON(localStorage.getItem("fcnChapterBookmarks"))??{data:{}}}#j(){return FcnUtils.parseJSON(FcnUtils.userData()?.bookmarks)??{data:{}}}#P(t){if("object"!=typeof t||!("data"in t)||Array.isArray(t.data)&&0===t.data.length)return{data:{}};const e={};for(const n in t.data)if(n.startsWith("ch-")){const a=this.#H(t.data[n]);a&&(e[n]=a)}return{data:e}}#H(t){const e={},n={"paragraph-id":"",progress:0,date:"",color:"",chapter:"",link:"",thumb:"",image:"",story:"",content:""};for(const a in n){if(typeof t[a]!=typeof n[a])return null;e[a]=t[a]}const a=new Date(e.date);return a&&"[object Date]"===Object.prototype.toString.call(a)&&!isNaN(a)||(e.date=(new Date).toISOString()),("number"!=typeof e.progress||e.progress<0)&&(e.progress=0),e}#_(){return JSON.stringify(this.bookmarksCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{"visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null)},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#O(t){clearTimeout(this.timeout),this.timeout=setTimeout((()=>{FcnUtils.remoteAction("fictioneer_ajax_save_bookmarks",{payload:{bookmarks:t}})}),FcnGlobals.debounceRate)}}),application.register("fictioneer-follows",class extends Stimulus.Controller{static get targets(){return["toggleButton","newDisplay","scrollList","mobileScrollList","mobileMarkRead"]}followsLoaded=!1;markedRead=!1;timeout=0;initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.refreshView(),this.#n=!0,this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerFollows=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.followsCachedData=FcnUtils.userData().follows?.data,Array.isArray(this.followsCachedData)&&0===this.followsCachedData.length&&(this.followsCachedData={}),this.followsCachedData}isFollowed(t){return!(!FcnUtils.loggedIn()||!this.data()?.[t])}unreadCount(){return parseInt(FcnUtils.userData()?.follows?.new??0)}toggleFollow({params:{id:t}}){this.#c()&&(fcn_toggleFollow(t,!this.isFollowed(t)),this.refreshView())}clear(){const t=FcnUtils.userData();t.follows={data:{}},fcn().setUserData(t),this.refreshView()}refreshView(){this.toggleButtonTargets.forEach((t=>{const e=t.dataset.storyId;t.classList.toggle("_followed",this.isFollowed(e))}));const t=this.unreadCount();this.newDisplayTargets.forEach((e=>{e.classList.toggle("_new",t>0),t>0&&(e.dataset.newCount=t,this.hasMobileMarkReadTarget&&this.mobileMarkReadTarget.classList.remove("hidden"))}))}loadFollowsHtml(){this.followsLoaded||FcnUtils.aGet({action:"fictioneer_ajax_get_follows_notifications",fcn_fast_ajax:1}).then((t=>{t.data.html&&(this.hasScrollListTarget&&(this.scrollListTarget.innerHTML=t.data.html),this.hasMobileScrollListTarget&&(this.mobileScrollListTarget.innerHTML=t.data.html),!1===FcnUtils.userData().loggedIn&&(fcn().removeUserData(),fcn().fetchUserData()))})).catch((t=>{429===t.status?fcn_showNotification(fictioneer_tl.notification.slowDown,3,"warning"):t.status&&t.statusText&&fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning"),this.hasScrollListTarget&&this.scrollListTarget.remove(),this.hasMobileScrollListTarget&&this.mobileScrollListTarget.remove()})).then((()=>{this.followsLoaded=!0,this.hasNewDisplayTarget&&this.newDisplayTargets.forEach((t=>{t.classList.add("_loaded")}))}))}markRead(){if(!this.followsLoaded&&this.unreadCount()>0||this.markedRead)return;this.markedRead=!0,this.newDisplayTargets.forEach((t=>{t.classList.remove("_new")})),this.hasMobileMarkReadTarget&&this.mobileMarkReadTarget.classList.add("hidden");const t=FcnUtils.userData();t.new=0,t.lastLoaded=0,FcnUtils.setUserData(t),FcnUtils.aPost({action:"fictioneer_ajax_mark_follows_read",fcn_fast_ajax:1}).catch((t=>{t.status&&t.statusText&&fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning")}))}#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#p=!0),t}#_(){return this.#c()&&JSON.stringify(this.followsCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}}),application.register("fictioneer-checkmarks",class extends Stimulus.Controller{static get targets(){return["chapterCheck","storyCheck","ribbon"]}timeout=0;initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.refreshView(),this.#n=!0,this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerCheckmarks=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.checkmarksCachedData=FcnUtils.userData().checkmarks?.data,Array.isArray(this.checkmarksCachedData)&&0===this.checkmarksCachedData.length&&(this.checkmarksCachedData={}),this.checkmarksCachedData}toggleChapter({params:{chapter:t,story:e}}){fcn_toggleCheckmark(e,t)}toggleStory({params:{story:t}}){fcn_toggleCheckmark(t)}clear(){const t=FcnUtils.userData();t.checkmarks={data:{},updated:Date.now()},fcn().setUserData(t),this.refreshView()}refreshView(){const t=this.data();!t||Object.keys(t).length<1?this.uncheckAll():Object.entries(t).forEach((([t,e])=>{t=parseInt(t);const n=e?.includes(t);this.hasChapterCheckTarget&&(n?this.chapterCheckTargets.forEach((t=>{t.classList.toggle("marked",!0),t.setAttribute("aria-checked",!0)})):this.chapterCheckTargets.forEach((n=>{const a=parseInt(n.dataset.fictioneerCheckmarksChapterParam);if(parseInt(n.dataset.fictioneerCheckmarksStoryParam)===t){const t=e?.includes(a);n.classList.toggle("marked",t),n.setAttribute("aria-checked",t)}}))),this.hasStoryCheckTarget&&(this.storyCheckTarget.classList.toggle("marked",n),this.storyCheckTarget.setAttribute("aria-checked",n)),this.hasRibbonTarget&&this.ribbonTarget.classList.toggle("hidden",!n)}))}uncheckAll(){this.hasChapterCheckTarget&&this.chapterCheckTargets.forEach((t=>{t.classList.toggle("marked",!1),t.setAttribute("aria-checked",!1)})),this.hasStoryCheckTarget&&(this.storyCheckTarget.classList.toggle("marked",!1),this.storyCheckTarget.setAttribute("aria-checked",!1))}#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#p=!0),t}#_(){return this.#c()&&JSON.stringify(this.checkmarksCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}}),application.register("fictioneer-reminders",class extends Stimulus.Controller{static get targets(){return["toggleButton"]}remindersLoaded=!1;timeout=0;initialize(){fcn()?.userReady?this.#n=!0:document.addEventListener("fcnUserDataReady",(()=>{this.refreshView(),this.#n=!0,this.#s()}))}connect(){window.FictioneerApp.Controllers.fictioneerReminders=this,this.#n&&(this.refreshView(),this.#s())}data(){return this.remindersCachedData=FcnUtils.userData().reminders?.data,Array.isArray(this.remindersCachedData)&&0===this.remindersCachedData.length&&(this.remindersCachedData={}),this.remindersCachedData}isRemembered(t){return!(!FcnUtils.loggedIn()||!this.data()?.[t])}toggleReminder({params:{id:t}}){this.#c()&&(fcn_toggleReminder(t,!this.isRemembered(t)),this.refreshView())}clear(){const t=FcnUtils.userData();t.reminders={data:{}},fcn().setUserData(t),this.refreshView()}refreshView(){this.toggleButtonTargets.forEach((t=>{const e=t.dataset.storyId;t.classList.toggle("_remembered",this.isRemembered(e))}))}#n=!1;#p=!1;#c(){const t=FcnUtils.loggedIn();return t||(this.#r(),this.#p=!0),t}#_(){return this.#c()&&JSON.stringify(this.remindersCachedData??0)!==JSON.stringify(this.data())}#v(){this.refreshInterval||(this.refreshInterval=setInterval((()=>{!this.#p&&this.#_()&&this.refreshView()}),3e4+1e3*Math.random()))}#s(){this.#v(),this.visibilityStateCheck=()=>{this.#c()&&("visible"===document.visibilityState?(this.#p=!1,this.refreshView(),this.#v()):(this.#p=!0,clearInterval(this.refreshInterval),this.refreshInterval=null))},document.addEventListener("visibilitychange",this.visibilityStateCheck)}#r(){clearInterval(this.refreshInterval),document.removeEventListener("visibilitychange",this.visibilityStateCheck)}}),document.addEventListener("fcnUserDataReady",(()=>{fcn().userData().fingerprint==document.documentElement.dataset.authorFingerprint&&document.body.classList.add("is-post-author")}));const fcn_ajaxCommentForm=_$$$("ajax-comment-form-target");function fcn_setupCommentFormObserver(){const t=new IntersectionObserver((([e])=>{e.isIntersecting&&(fcn_getCommentForm(),t.disconnect())}),{rootMargin:"450px",threshold:1});t.observe(fcn_ajaxCommentForm)}function fcn_getCommentForm(){let t;FcnUtils.aGet({action:"fictioneer_ajax_get_comment_form",post_id:_$$$("comments").dataset.postId,fcn_fast_comment_ajax:1}).then((e=>{if(e.success){const t=document.createElement("div");t.innerHTML=e.data.html;const n=t.querySelector("#comment_post_ID"),a=t.querySelector("#cancel-comment-reply-link"),s=t.querySelector(".logout-link");n&&(n.value=e.data.postId),a&&(a.href="#respond"),s&&(s.href=_$$$("comments").dataset.logoutUrl),fcn_ajaxCommentForm.innerHTML=t.innerHTML,t.remove(),fcn_applyCommentStack(),_$$$("fictioneer-ajax-nonce")?.remove(),document.body.appendChild(FcnUtils.html`${e.data.nonceHtml}`)}else t=FcnUtils.buildErrorNotice(e.data.error)})).catch((e=>{t=FcnUtils.buildErrorNotice(e)})).then((()=>{fcn_ajaxCommentForm.classList.remove("comments-skeleton"),t&&(fcn_ajaxCommentForm.innerHTML="",fcn_ajaxCommentForm.appendChild(t))}))}function fcn_applyCommentStack(t=null){(t=t??_$(FcnGlobals.commentFormSelector))&&("TEXTAREA"==t.tagName?(FcnGlobals.commentStack.forEach((e=>{t.value+=e})),FcnUtils.adjustTextarea(t)):"DIV"==t.tagName&&FcnGlobals.commentStack.forEach((e=>{t.innerHTML+=e})),FcnGlobals.commentStack=[])}fcn_ajaxCommentForm&&document.addEventListener("fcnUserDataReady",(()=>{fcn_setupCommentFormObserver()})),application.register("fictioneer-comment-form",class extends Stimulus.Controller{static get targets(){return["submit","cancel","textarea","privateToggle","emailNotificationToggle","author","email","cookies","privacyPolicy"]}initialize(){this.respond=this.element.closest("#respond"),this.order=this.respond.closest(".fictioneer-comments")?.dataset.order??"desc",this.parent=this.element.querySelector("#comment_parent"),this.addJSTrap()}adjustTextarea(){FcnUtils.adjustTextarea(this.textareaTarget)}toolbarButtons(t){const e=t.target.closest("[data-bbcode]");e&&fcn_wrapInTag(this.textareaTarget,e.dataset.bbcode,{shortcode:!0})}keyComboCodes(t){if(_$(".fictioneer-comment-toolbar")&&"TEXTAREA"===document.activeElement.tagName&&(t.ctrlKey||t.metaKey)){const e=t.key.toLowerCase();if(["b","i","s","q","h","l"].includes(e)){t.preventDefault();const n={q:"quote",h:"spoiler",l:"link"};fcn_wrapInTag(document.activeElement,n[e]||e,{shortcode:!0})}}}addJSTrap(){this.element.appendChild(FcnUtils.html` `)}revealFormInputs(){this.respond.querySelectorAll(".fictioneer-respond__form-actions, .fictioneer-respond__form-bottom").forEach((t=>{t.classList.remove("hidden")}))}ajaxSubmit(t){if(Date.now(){this.submitTarget.value=this.submitTarget.dataset.enabled,this.submitTarget.classList.remove("_disabled")}),2e3)):void this.element.classList.add("_invalid");if(t.preventDefault(),!this.element.reportValidity())return void this.element.classList.add("_invalid");const e=new FormData(this.element),n=Object.fromEntries(e.entries()),a=n.comment_parent??0,s=_$$$(`comment-${a}`),i=this.textareaTarget.value.length>1;let o=!0,r=!0;if(this.textareaTarget.classList.toggle("_error",!i),this.hasPrivacyPolicyTarget&&(r=this.privacyPolicyTarget.checked,this.privacyPolicyTarget.classList.toggle("_error",!r)),this.hasEmailTarget&&this.emailTarget?.value.length>0&&(o=/\S+@\S+\.\S+/.test(this.emailTarget.value),this.emailTarget.classList.toggle("_error",!o)),!i||!r||!o)return;this.element.classList.add("ajax-in-progress"),this.submitTarget.value=this.submitTarget.dataset.disabled,this.submitTarget.disabled=!0;const c={action:"fictioneer_ajax_submit_comment",content:this.textareaTarget.value,depth:s?parseInt(s.dataset.depth)+1:1,fcn_fast_comment_ajax:1,...n};this.hasEmailTarget&&this.emailTarget?.value&&(c.email=this.emailTarget.value),this.hasAuthorTarget&&this.authorTarget?.value&&(c.author=this.authorTarget.value),_$$$("comment-submit-error-notice")?.remove(),FcnUtils.aPost(c).then((t=>{if(t.success&&t.data?.comment){let e=_$(".commentlist"),n="insertBefore";if(e&&!s&&e.firstElementChild){let t=null;if(e.firstElementChild.classList.contains("_sticky"))for(t=e.firstElementChild,e=t,n="insertAfter";t.nextElementSibling&&t.nextElementSibling.classList.contains("_sticky");)t=e.nextElementSibling,e=t}if(e||(e=document.createElement("ol"),e.classList="fictioneer-comments__list commentlist",_$$$("comments").appendChild(e),n="append"),s&&(e=s.querySelector(".children"),n="append",!e)){const t=document.createElement("ol");s.appendChild(t),e=t}let a=document.createElement("div");switch(a.innerHTML=t.data.comment,a=a.firstChild,n){case"append":e.appendChild(a);break;case"insertBefore":e.insertBefore(a,e.firstChild);break;case"insertAfter":e.nextSibling?e.parentNode.insertBefore(a,e.nextSibling):e.parentNode.appendChild(a)}this.textareaTarget.value="",this.textareaTarget.style.height="","0"!=this.parent.value&&this.cancelTarget.click();const i=window.location.protocol+"//"+window.location.host+window.location.pathname;("desc"!=this.order||FcnGlobals.urlParams.corder)&&(FcnGlobals.urlParams.corder=this.order),t.data.commentcode&&(FcnGlobals.urlParams.commentcode=t.data.commentcode);let o=Object.entries(FcnGlobals.urlParams).map((([t,e])=>`${t}=${e}`)).join("&");""!==o&&(o=`?${o}`),history.replaceState({path:i},"",i+o+`#comment-${t.data.comment_id}`),a.scrollIntoView({behavior:"smooth"})}else this.element.insertBefore(FcnUtils.buildErrorNotice(t.data.failure??t.data.error??fictioneer_tl.notification.error,"comment-submit-error-notice",!1),this.element.firstChild),console.error("Error:",t.data.error??t.data.failure??"Unknown")})).catch((t=>{this.element.insertBefore(FcnUtils.buildErrorNotice(`${t.statusText} (${t.status})`,"comment-submit-error-notice"),this.element.firstChild)})).then((()=>{this.element.classList.remove("ajax-in-progress"),this.submitTarget.disabled=!1,this.submitTarget.value=this.submitTarget.dataset.enabled}))}togglePrivate(){this.respond.classList.toggle("_private",this.privateToggleTarget.checked)}}),application.register("fictioneer-comment",class extends Stimulus.Controller{static get targets(){return["modMenuToggle","modMenu","modIcon","editLink","flagButton","deleteButton","editButton","content","inlineEditWrapper","inlineEditTextarea","inlineEditButtons","inlineEditSubmit","editNote"]}static values={id:Number,timestamp:Number,fingerprint:String};comment=this.element.closest(".fictioneer-comment");menuOpen=!1;initialize(){document.addEventListener("fcnLastClicked",(t=>{t.detail?.element?.closest(`[data-fictioneer-comment-id-value="${this.idValue}"]`)||this.#d()})),document.addEventListener("click",(t=>{t.target.closest(`[data-fictioneer-comment-id-value="${this.idValue}"]`)||this.#d()}))}connect(){this.hasModMenuTarget&&(this.editLink=this.modMenuTarget.dataset.editLink),fcn().userData().fingerprint?(this.#q(),this.#V()):document.addEventListener("fcnUserDataReady",(()=>{this.#q(),this.#V()})),this.hasInlineEditTextareaTarget&&this.inlineEditTextareaTarget.addEventListener("input",(()=>{FcnUtils.adjustTextarea(this.inlineEditTextareaTarget)})),document.addEventListener("toggledLastClick",(t=>{!t.detail.force&&this.menuOpen&&this.#d()}))}toggleMenu(t=null){this.hasModMenuTarget&&(!this.menuOpen&&"close"!==t||"open"===t?this.#h():this.#d())}mouseLeave(){this.hasModMenuTarget&&this.menuOpen&&(this.#d(),document.dispatchEvent(new CustomEvent("fcnRemoveLastClicked")))}commentClick(t){t.target.closest('[data-fictioneer-comment-target="modMenuToggle"]')||this.#d()}approve(){this.#G("approve")}unapprove(){this.#G("unapprove")}offensive(){this.#G("offensive")}unoffensive(){this.#G("unoffensive")}open(){this.#G("open")}close(){this.#G("close")}sticky(){this.#G("sticky")}unsticky(){this.#G("unsticky")}trash(){this.#G("trash")}spam(){this.#G("spam")}flag(){FcnUtils.loggedIn()&&this.hasFlagButtonTarget&&(this.comment.classList.contains("ajax-in-progress")||FcnUtils.remoteAction("fictioneer_ajax_report_comment",{element:this.comment,payload:{id:this.idValue,dubious:this.flagButtonTarget.classList.contains("_dubious")},callback:t=>{t.success&&(this.flagButtonTarget.classList.toggle("on",t.data.flagged),this.flagButtonTarget.classList.remove("_dubious"),t.data.resync&&fcn_showNotification(t.data.resync))}}))}selfDelete(){if(!FcnUtils.loggedIn()||!this.hasDeleteButtonTarget)return;const t=prompt(this.deleteButtonTarget.dataset.dialogMessage);t&&t.toLowerCase()==this.deleteButtonTarget.dataset.dialogConfirm.toLowerCase()&&(this.comment.classList.contains("ajax-in-progress")||FcnUtils.remoteAction("fictioneer_ajax_delete_my_comment",{element:this.comment,payload:{comment_id:this.idValue},callback:(t,e)=>{t.success&&(e.classList.add("_deleted"),this.element.innerHTML=t.data.html)}}))}startEditInline(){const t=_$$$("template-comment-inline-edit-form")?.content.cloneNode(!0);t&&(this.comment.classList.add("_editing"),this.commentEditUndo=this.inlineEditTextareaTarget.value,this.inlineEditWrapperTarget.appendChild(t),this.contentTarget.hidden=!0,this.inlineEditWrapperTarget.hidden=!1,this.inlineEditTextareaTarget.style.height=`${this.inlineEditTextareaTarget.scrollHeight}px`,FcnUtils.adjustTextarea(this.inlineEditTextareaTarget))}cancelEditInline(){this.#Q(!0)}submitEditInline(){this.inlineEditTextareaTarget.value!==this.commentEditUndo?(this.inlineEditSubmitTarget.innerHTML=this.inlineEditSubmitTarget.dataset.disabled,this.inlineEditSubmitTarget.disabled=!0,FcnUtils.remoteAction("fictioneer_ajax_edit_comment",{element:this.inlineEditWrapperTarget,payload:{comment_id:this.idValue,content:this.inlineEditTextareaTarget.value},callback:t=>{if(t.success){this.contentTarget.innerHTML=t.data.content,this.#Q(!1,t.data.raw);let e=this.editNoteTarget;this.hasEditNoteTarget||(e=document.createElement("div")),e.classList.add("fictioneer-comment__edit-note"),e.dataset.fictioneerCommentTarget="editNote",e.innerHTML=t.data.edited,this.contentTarget.parentNode.appendChild(e)}else this.#Q(!0)},errorCallback:()=>{this.#Q(!0)},finalCallback:()=>{this.hasInlineEditSubmitTarget&&(this.inlineEditSubmitTarget.innerHTML=this.inlineEditSubmitTarget.dataset.enabled,this.inlineEditSubmitTarget.disabled=!1)}})):this.#Q(!0)}keyComboCodes(t){if(_$(".fictioneer-comment-toolbar")&&"TEXTAREA"===document.activeElement.tagName&&(t.ctrlKey||t.metaKey)){const e=t.key.toLowerCase();if(["b","i","s","q","h","l"].includes(e)){t.preventDefault();const n={q:"quote",h:"spoiler",l:"link"};fcn_wrapInTag(document.activeElement,n[e]||e,{shortcode:!0})}}}#q(){this.hasDeleteButtonTarget&&this.#W()&&(this.deleteButtonTarget.hidden=!1)}#V(){let t=parseInt(document.documentElement.dataset.editTime);if(t&&(t=t>0?6e4*t:t,this.hasEditButtonTarget&&this.#W())){if(t>0&&parseInt(this.timestampValue)+t{if(t.success){const e=t.data.operation,n={sticky:{action:"add",className:"_sticky"},unsticky:{action:"remove",className:"_sticky"},offensive:{action:"add",className:"_offensive"},unoffensive:{action:"remove",className:"_offensive"},approve:{action:"remove",className:"_unapproved"},unapprove:{action:"add",className:"_unapproved"},open:{action:"remove",className:"_closed"},close:{action:"add",className:"_closed"}};if(e in n){const{action:t,className:a}=n[e];this.comment.classList[t](a)}else"trash"!==e&&"spam"!==e||(this.comment.style.cssText="overflow: hidden; height: 0; margin: 0; opacity: 0;")}else this.#z()},errorCallback:()=>{this.#z()},finalCallback:()=>{this.#d(),document.dispatchEvent(new CustomEvent("fcnRemoveLastClicked"))}}))}});const fcn_commentSection=_$("#comments[data-ajax-comments]");function fcn_getCommentSection(t=null,e=null,n=null,a=!1){if(!fcn_commentSection)return;let s,i="",o=_$(FcnGlobals.commentFormSelector);if(o&&(i=o.value),fcn_commentSection.classList.contains("ajax-in-progress"))return;if(fcn_commentSection.classList.add("ajax-in-progress"),e||(e=FcnGlobals.urlParams.pg??1),n||(n=n??fcn_commentSection.dataset.order??"desc"),!fcn_commentSection)return;const r={action:"fictioneer_ajax_get_comment_section",post_id:t??fcn_commentSection.dataset.postId,page:parseInt(e),corder:n,fcn_fast_comment_ajax:1};FcnGlobals.urlParams.commentcode&&(r.commentcode=FcnGlobals.urlParams.commentcode),FcnUtils.aGet(r).then((t=>{if(t.success){e=t.data.page,fcn_commentSection.dataset.page=e;const s=document.createElement("div");if(s.innerHTML=t.data.html,s.querySelector("#comment_post_ID")){s.querySelector("#comment_post_ID").value=t.data.postId,s.querySelector("#cancel-comment-reply-link").href="#respond";const e=s.querySelector(".logout-link");e&&(e.href=fcn_commentSection.dataset.logoutUrl)}fcn_commentSection.innerHTML=s.innerHTML,s.remove(),o=_$(FcnGlobals.commentFormSelector),o&&!t.data.disabled&&(o.value=i,fcn_applyCommentStack(o));const r=location.hash.includes("#comment")?location.hash:".respond",c=document.querySelector(r)??_$$$("respond");a&&c.scrollIntoView({behavior:"smooth"});const l=window.location.protocol+"//"+window.location.host+window.location.pathname;(e>1||FcnGlobals.urlParams.pg)&&(FcnGlobals.urlParams.pg=e),("desc"!=n||FcnGlobals.urlParams.corder)&&(FcnGlobals.urlParams.corder=n);let d=Object.entries(FcnGlobals.urlParams).map((([t,e])=>`${t}=${e}`)).join("&");""!==d&&(d=`?${d}`),window.history.pushState({path:l},"",l+d+location.hash)}else s=FcnUtils.buildErrorNotice(t.data.error)})).catch((t=>{s=FcnUtils.buildErrorNotice(t)})).then((()=>{fcn_commentSection.classList.remove("ajax-in-progress"),s&&(fcn_commentSection.innerHTML="",fcn_commentSection.appendChild(s))}))}function fcn_reloadCommentsPage(t=null){fcn_getCommentSection(null,t,null,!0)}function fcn_jumpToCommentPage(){const t=parseInt(window.prompt(fictioneer_tl.notification.enterPageNumber));t>0&&fcn_reloadCommentsPage(t)}var fct_commentSectionObserver;function fcn_setupCommentSectionObserver(){fct_commentSectionObserver=new IntersectionObserver((([t])=>{t.isIntersecting&&(fcn_getCommentSection(),fct_commentSectionObserver.disconnect())}),{rootMargin:"450px",threshold:1}),fcn_commentSection&&fct_commentSectionObserver.observe(fcn_commentSection)}function fcn_loadCommentEarly(){fcn_commentSection&&location.hash.includes("#comment")&&(_$(FcnGlobals.commentFormSelector)||(fct_commentSectionObserver.disconnect(),fcn_reloadCommentsPage()))}function fcn_toggleCommentOrder(t){const e=t.closest(".fictioneer-comments"),n="desc"==e.dataset.order;e.dataset.order=n?"asc":"desc",t.classList.toggle("_on",!n),t.classList.toggle("_off",n),fcn_reloadCommentsPage(e.dataset.page)}document.addEventListener("fcnUserDataReady",(()=>{fcn_setupCommentSectionObserver()})),document.addEventListener("fcnUserDataReady",(()=>{fcn_loadCommentEarly()})),_$(".fictioneer-comments")?.addEventListener("click",(t=>{if(t.target.closest("button[data-page-jump]"))return void fcn_jumpToCommentPage();const e=t.target.closest("button[data-page]");if(e)return void fcn_reloadCommentsPage(e.dataset.page);const n=t.target.closest("button[data-toggle-order]");n&&fcn_toggleCommentOrder(n)}));const fcn_bookshelfTarget=_$$$("ajax-bookshelf-target");function fcn_getBookshelfContent(){return FcnUtils.parseJSON(localStorage.getItem("fcnBookshelfContent"))??{html:{},count:{}}}function fcn_updateBookshelfView(t=null,e=null,n=null,a=!1){let s=fcn_getBookshelfContent();const i=(t=t??fcn_bookshelfTarget.dataset.action)+(e=e??fcn_bookshelfTarget.dataset.page)+(n=n??fcn_bookshelfTarget.dataset.order);if(!s.timestamp||s.timestamp+6e4{n.success?(i.timestamp=Date.now(),i.html[s]=n.data.html,i.count[t]=n.data.count,localStorage.setItem("fcnBookshelfContent",JSON.stringify(i)),fcn_bookshelfTarget.innerHTML=n.data.html,fcn_bookshelfTarget.dataset.page=e,_$(".item-number").innerHTML=`(${n.data.count})`):(fcn_bookshelfTarget.innerHTML="",fcn_bookshelfTarget.appendChild(FcnUtils.buildErrorNotice(n.data.error)))})).catch((t=>{_$(".item-number").innerHTML="",fcn_bookshelfTarget.innerHTML="",fcn_bookshelfTarget.appendChild(FcnUtils.buildErrorNotice(`${t.status}: ${t.statusText}`))})).then((()=>{fcn_bookshelfTarget.classList.remove("ajax-in-progress"),a&&_$$$("main").scrollIntoView({behavior:"smooth"})}))}fcn_bookshelfTarget&&document.addEventListener("fcnUserDataReady",(()=>{fcn_updateBookshelfView()})),_$(".bookshelf__list")?.addEventListener("click",(t=>{const e=t.target.closest(".page-numbers[data-page]");e&&fcn_browseBookshelfPage(e.dataset.page)})); \ No newline at end of file diff --git a/js/utility.min.js b/js/utility.min.js index f7d0d82e..c0920333 100644 --- a/js/utility.min.js +++ b/js/utility.min.js @@ -1 +1 @@ -const _$=document.querySelector.bind(document),_$$=document.querySelectorAll.bind(document),_$$$=document.getElementById.bind(document),FcnUtils={userData:()=>({lastLoaded:0,timestamp:0,loggedIn:"pending",follows:!1,reminders:!1,checkmarks:!1,bookmarks:null,likes:null,fingerprint:!1,nonceHtml:"",nonce:"",isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1,...FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{}}),resetUserData(){const e=FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{},t={lastLoaded:e.lastLoaded??0,timestamp:0,loggedIn:"pending",follows:!1,reminders:!1,checkmarks:!1,likes:null,bookmarks:null,fingerprint:!1,isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1};localStorage.setItem("fcnUserData",JSON.stringify({...e,...t}))},removeUserData(){localStorage.removeItem("fcnUserData")},setUserData(e){localStorage.setItem("fcnUserData",JSON.stringify(e))},loggedInCache:null,loggedInCacheTime:0,loggedIn(){const e=Date.now();return null!==FcnUtils.loggedInCache&&e-FcnUtils.loggedInCacheTime<20||(FcnUtils.loggedInCache=FcnUtils.hasLoginCookie(),FcnUtils.loggedInCacheTime=e),FcnUtils.loggedInCache},hasLoginCookie(){const e=document.cookie.split(";");for(let t=0;t{n&&n(e,t),e.success||(fcn_showNotification(e.data.failure??e.data.error??fictioneer_tl.notification.error,10,"warning"),(e.data.error||e.data.failure)&&console.error("Error:",e.data.error??e.data.failure))})).catch((e=>{429===e.status?fcn_showNotification(fictioneer_tl.notification.slowDown,3,"warning"):e.status&&e.statusText&&fcn_showNotification(`${e.status}: ${e.statusText}`,5,"warning"),o&&o(e,t),console.error(e)})).then((()=>{t?.classList.remove("ajax-in-progress"),a&&a(t)}))},parseJSON(e){if(null==e||"string"!=typeof e)return null;try{return JSON.parse(e)}catch(e){return null}},copyToClipboard(e,t=!1){t=t||fictioneer_tl.notification.copiedToClipboard,navigator.clipboard&&(navigator.clipboard.writeText(e),t&&fcn_showNotification(t,2))},clamp:(e,t,n)=>Math.min(Math.max(n,e),t),offset(e){const t=e.getBoundingClientRect();return{top:t.top+window.scrollY,left:t.left+window.scrollX}},throttle(e,t,n){var o,a,r,i=null,l=0;n||(n={});var c=function(){l=!1===n.leading?0:Date.now(),i=null,r=e.apply(o,a),i||(o=a=null)};return function(){var s=Date.now();l||!1!==n.leading||(l=s);var d=t-(s-l);return o=this,a=arguments,d<=0||d>t?(i&&(clearTimeout(i),i=null),l=s,r=e.apply(o,a),i||(o=a=null)):i||!1===n.trailing||(i=setTimeout(c,d)),r}},deleteCookie(e){document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"},deleteAllCookies(){localStorage.clear(),document.cookie.split(";").forEach((e=>{document.cookie=e.replace(/^ +/,"").replace(/=.*/,"=;expires="+(new Date).toUTCString()+";path=/")}))},setCookie(e,t,n=30){const o=new Date;o.setTime(o.getTime()+24*n*60*60*1e3);const a="expires="+o.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+";"+a+";SameSite=Strict;path=/"},getCookie(e){const t=e+"=",n=document.cookie.split(";");for(var o=0;o_$$$("fictioneer-ajax-nonce")?.value??_$$$("general-fictioneer-nonce")?.value??_$('[name="fictioneer_nonce"]')?.value??0,buildUrl:(e={},t=null)=>(t=t?new URL(t):new URL(window.location.protocol+"//"+window.location.host+window.location.pathname),e&&Object.keys(e).forEach((n=>{t.searchParams.append(n,e[n])})),t),buildErrorNotice(e,t=!1,n=!0){console.error("Error:",e);const o=document.createElement("div");let a=e;return t&&(o.id=t),o.classList="notice _warning","object"==typeof e&&(a="",e.status&&(a=`${e.status}: `),e.statusText&&(a+=e.statusText),a||(a="Unknown error.")),o.innerHTML=`
${n?FcnUtils.sanitizeHTML(a):a}
`,o},detectScreenCollision(e){const t=e.getBoundingClientRect(),n=window.innerHeight??document.documentElement.clientHeight,o=window.innerWidth??document.documentElement.clientWidth,a=(e.closest(".popup-menu-toggle")?.clientHeight??32)+16,r=n-t.bottom,i=[];return t.top<=50&&r>50+a&&i.push("top"),t.bottom>=n-50&&t.top>50+a&&i.push("bottom"),t.left<=10&&i.push("left"),t.right>=o-10&&i.push("right"),i},sanitizeHTML(e){const t=document.createElement("div");return t.innerText=e instanceof HTMLElement?e.innerHTML:e,t.textContent="string"==typeof e?e:e.textContent,t.innerHTML},scrollTo(e,t=64){window.scrollTo({top:e.getBoundingClientRect().top+window.scrollY-t,behavior:"smooth"})},html(...e){const t=document.createElement("template");return t.innerHTML=String.raw(...e).trim(),t.content.firstChild},toggleInProgress(e,t=null){(t=null!==t?t:!e.disabled)?(e.dataset.enableWith=e.innerHTML,e.innerHTML=e.dataset.disableWith??"Processing",e.disabled=!0,e.classList.add("disabled")):(e.innerHTML=e.dataset.enableWith,e.disabled=!1,e.classList.remove("disabled"))},adjustTextarea(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)},isSearchEngineCrawler(){const e=navigator.userAgent.toLowerCase();return["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","sogou","exabot","facebot","ia_archiver"].some((t=>e.includes(t)))},removeArrayItemOnce(e,t){var n=e.indexOf(t);return n>-1&&e.splice(n,1),e},extractTextNodes:e=>Array.from(e.childNodes).filter((e=>e.nodeType===Node.TEXT_NODE)).map((e=>e.textContent.trim())).join(" "),appendToComment(e){const t=_$(FcnGlobals.commentFormSelector);if(t)switch(t.tagName){case"TEXTAREA":t.value+=e,FcnUtils.adjustTextarea(t);break;case"DIV":t.innerHTML+=e}else FcnGlobals.commentStack.push(e)}};async function fcn_ajaxPost(e={},t=null,n={}){t&&!t.startsWith("http")&&(t=FcnGlobals.restURL+t),t=t||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL);let o={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};o={...o,...n},e={nonce:FcnUtils.nonce(),...e};const a=await fetch(t,{method:"POST",credentials:"same-origin",headers:o,mode:"same-origin",body:new URLSearchParams(e)});return a.ok?a.json():Promise.reject(a)}async function fcn_ajaxGet(e={},t=null,n={}){t&&!t.startsWith("http")&&(t=FcnGlobals.restURL+t),t=t||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL),e={nonce:FcnUtils.nonce(),...e},t=FcnUtils.buildUrl(e,t);let o={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};o={...o,...n};const a=await fetch(t,{method:"GET",credentials:"same-origin",headers:o,mode:"same-origin"});return a.ok?a.json():Promise.reject(a)} \ No newline at end of file +const _$=document.querySelector.bind(document),_$$=document.querySelectorAll.bind(document),_$$$=document.getElementById.bind(document),FcnUtils={userData:()=>({lastLoaded:0,timestamp:0,loggedIn:"pending",follows:!1,reminders:!1,checkmarks:!1,bookmarks:null,likes:null,fingerprint:!1,nonceHtml:"",nonce:"",isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1,...FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{}}),resetUserData(){const e=FcnUtils.parseJSON(localStorage.getItem("fcnUserData"))||{},t={lastLoaded:e.lastLoaded??0,timestamp:0,loggedIn:(!FcnGlobals.ajaxAuth||!1!==e.loggedIn)&&"pending",follows:!1,reminders:!1,checkmarks:!1,likes:null,bookmarks:null,fingerprint:!1,isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1};localStorage.setItem("fcnUserData",JSON.stringify({...e,...t}))},removeUserData(){localStorage.removeItem("fcnUserData")},setUserData(e){localStorage.setItem("fcnUserData",JSON.stringify(e))},loggedInCache:null,loggedInCacheTime:0,loggedIn(){const e=Date.now();return null!==FcnUtils.loggedInCache&&e-FcnUtils.loggedInCacheTime<20||(FcnUtils.loggedInCache=FcnUtils.hasLoginCookie(),FcnUtils.loggedInCacheTime=e),FcnUtils.loggedInCache},hasLoginCookie(){const e=document.cookie.split(";");for(let t=0;t{n&&n(e,t),e.success||(fcn_showNotification(e.data.failure??e.data.error??fictioneer_tl.notification.error,10,"warning"),(e.data.error||e.data.failure)&&console.error("Error:",e.data.error??e.data.failure))})).catch((e=>{429===e.status?fcn_showNotification(fictioneer_tl.notification.slowDown,3,"warning"):e.status&&e.statusText&&fcn_showNotification(`${e.status}: ${e.statusText}`,5,"warning"),o&&o(e,t),console.error(e)})).then((()=>{t?.classList.remove("ajax-in-progress"),a&&a(t)}))},parseJSON(e){if(null==e||"string"!=typeof e)return null;try{return JSON.parse(e)}catch(e){return null}},copyToClipboard(e,t=!1){t=t||fictioneer_tl.notification.copiedToClipboard,navigator.clipboard&&(navigator.clipboard.writeText(e),t&&fcn_showNotification(t,2))},clamp:(e,t,n)=>Math.min(Math.max(n,e),t),offset(e){const t=e.getBoundingClientRect();return{top:t.top+window.scrollY,left:t.left+window.scrollX}},throttle(e,t,n){var o,a,r,i=null,l=0;n||(n={});var c=function(){l=!1===n.leading?0:Date.now(),i=null,r=e.apply(o,a),i||(o=a=null)};return function(){var s=Date.now();l||!1!==n.leading||(l=s);var d=t-(s-l);return o=this,a=arguments,d<=0||d>t?(i&&(clearTimeout(i),i=null),l=s,r=e.apply(o,a),i||(o=a=null)):i||!1===n.trailing||(i=setTimeout(c,d)),r}},deleteCookie(e){document.cookie=e+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"},deleteAllCookies(){localStorage.clear(),document.cookie.split(";").forEach((e=>{document.cookie=e.replace(/^ +/,"").replace(/=.*/,"=;expires="+(new Date).toUTCString()+";path=/")}))},setCookie(e,t,n=30){const o=new Date;o.setTime(o.getTime()+24*n*60*60*1e3);const a="expires="+o.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+";"+a+";SameSite=Strict;path=/"},getCookie(e){const t=e+"=",n=document.cookie.split(";");for(var o=0;o_$$$("fictioneer-ajax-nonce")?.value??_$$$("general-fictioneer-nonce")?.value??_$('[name="fictioneer_nonce"]')?.value??0,buildUrl:(e={},t=null)=>(t=t?new URL(t):new URL(window.location.protocol+"//"+window.location.host+window.location.pathname),e&&Object.keys(e).forEach((n=>{t.searchParams.append(n,e[n])})),t),buildErrorNotice(e,t=!1,n=!0){console.error("Error:",e);const o=document.createElement("div");let a=e;return t&&(o.id=t),o.classList="notice _warning","object"==typeof e&&(a="",e.status&&(a=`${e.status}: `),e.statusText&&(a+=e.statusText),a||(a="Unknown error.")),o.innerHTML=`
${n?FcnUtils.sanitizeHTML(a):a}
`,o},detectScreenCollision(e){const t=e.getBoundingClientRect(),n=window.innerHeight??document.documentElement.clientHeight,o=window.innerWidth??document.documentElement.clientWidth,a=(e.closest(".popup-menu-toggle")?.clientHeight??32)+16,r=n-t.bottom,i=[];return t.top<=50&&r>50+a&&i.push("top"),t.bottom>=n-50&&t.top>50+a&&i.push("bottom"),t.left<=10&&i.push("left"),t.right>=o-10&&i.push("right"),i},sanitizeHTML(e){const t=document.createElement("div");return t.innerText=e instanceof HTMLElement?e.innerHTML:e,t.textContent="string"==typeof e?e:e.textContent,t.innerHTML},scrollTo(e,t=64){window.scrollTo({top:e.getBoundingClientRect().top+window.scrollY-t,behavior:"smooth"})},html(...e){const t=document.createElement("template");return t.innerHTML=String.raw(...e).trim(),t.content.firstChild},toggleInProgress(e,t=null){(t=null!==t?t:!e.disabled)?(e.dataset.enableWith=e.innerHTML,e.innerHTML=e.dataset.disableWith??"Processing",e.disabled=!0,e.classList.add("disabled")):(e.innerHTML=e.dataset.enableWith,e.disabled=!1,e.classList.remove("disabled"))},adjustTextarea(e){e&&(e.style.height="auto",e.style.height=`${e.scrollHeight}px`)},isSearchEngineCrawler(){const e=navigator.userAgent.toLowerCase();return["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","sogou","exabot","facebot","ia_archiver"].some((t=>e.includes(t)))},removeArrayItemOnce(e,t){var n=e.indexOf(t);return n>-1&&e.splice(n,1),e},extractTextNodes:e=>Array.from(e.childNodes).filter((e=>e.nodeType===Node.TEXT_NODE)).map((e=>e.textContent.trim())).join(" "),appendToComment(e){const t=_$(FcnGlobals.commentFormSelector);if(t)switch(t.tagName){case"TEXTAREA":t.value+=e,FcnUtils.adjustTextarea(t);break;case"DIV":t.innerHTML+=e}else FcnGlobals.commentStack.push(e)}};async function fcn_ajaxPost(e={},t=null,n={}){t&&!t.startsWith("http")&&(t=FcnGlobals.restURL+t),t=t||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL);let o={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};o={...o,...n},e={nonce:FcnUtils.nonce(),...e};const a=await fetch(t,{method:"POST",credentials:"same-origin",headers:o,mode:"same-origin",body:new URLSearchParams(e)});return a.ok?a.json():Promise.reject(a)}async function fcn_ajaxGet(e={},t=null,n={}){t&&!t.startsWith("http")&&(t=FcnGlobals.restURL+t),t=t||(fictioneer_ajax.ajax_url??FcnGlobals.ajaxURL),e={nonce:FcnUtils.nonce(),...e},t=FcnUtils.buildUrl(e,t);let o={"Content-Type":"application/x-www-form-urlencoded","Cache-Control":"no-cache"};o={...o,...n};const a=await fetch(t,{method:"GET",credentials:"same-origin",headers:o,mode:"same-origin"});return a.ok?a.json():Promise.reject(a)} \ No newline at end of file diff --git a/src/js/application.js b/src/js/application.js index ac76a40c..3543bf36 100644 --- a/src/js/application.js +++ b/src/js/application.js @@ -75,6 +75,14 @@ const FcnGlobals = { debounceRate: fictioneer_ajax.post_debounce_rate, + /** + * Whether AJAX authentication is enabled. + * + * @type {Boolean} + */ + + ajaxAuth: document.documentElement.dataset.fictioneerAjaxAuthValue ?? false, + /** * Theme fonts. * @@ -235,7 +243,10 @@ application.register('fictioneer', class extends Stimulus.Controller { } // Only update from server after some time has passed (e.g. 60 seconds) - if (FcnGlobals.ajaxLimitThreshold < currentUserData.lastLoaded || currentUserData.loggedIn === false) { + if ( + (FcnGlobals.ajaxLimitThreshold < currentUserData.lastLoaded || currentUserData.loggedIn === false) && + currentUserData.loggedIn !== 'pending' + ) { // Prepare event const event = new CustomEvent( 'fcnUserDataReady', diff --git a/src/js/utility.js b/src/js/utility.js index 38dc98b7..61d918e4 100644 --- a/src/js/utility.js +++ b/src/js/utility.js @@ -88,7 +88,7 @@ const FcnUtils = { const reset = { 'lastLoaded': data.lastLoaded ?? 0, 'timestamp': 0, - 'loggedIn': 'pending', + 'loggedIn': (FcnGlobals.ajaxAuth && data.loggedIn === false) ? false : 'pending', 'follows': false, 'reminders': false, 'checkmarks': false,