fictioneer/js/application.min.js
2024-10-12 16:37:11 +02:00

2 lines
32 KiB
JavaScript

const fcn_theSite=_$$$("site"),fcn_theBody=_$("body"),fcn_theRoot=document.documentElement,fcn_inlineStorage=_$$$("inline-storage").dataset,fcn_urlParams=Object.fromEntries(new URLSearchParams(window.location.search).entries()),fcn_pageLoadTimestamp=Date.now(),fcn_ajaxLimitThreshold=Date.now()-parseInt(fictioneer_ajax.ttl);var fcn_isLoggedIn=fcn_theBody.classList.contains("logged-in"),fcn_chapterList=_$("#story-chapter-list > ul");function fcn_cleanupWebStorage(e=!1){const t=["fcnProfileAvatar","fcnBookshelfContent"];e||t.push("fcnChapterBookmarks"),t.forEach((e=>localStorage.removeItem(e)));const n=["loggedIn","follows","reminders","checkmarks","bookmarks","fingerprint"],o=fcn_parseJSON(localStorage.getItem("fcnUserData"));o&&(n.forEach((e=>o[e]=!1)),localStorage.setItem("fcnUserData",JSON.stringify(o)));const s=fcn_parseJSON(localStorage.getItem("fcnAuth"));s?.loggedIn&&localStorage.removeItem("fcnAuth")}function fcn_prepareLogin(){localStorage.removeItem("fcnUserData"),localStorage.removeItem("fcnAuth")}function fcn_cleanupGuestView(){fcn_isLoggedIn=!1,fcn_theBody.classList.remove("logged-in","is-admin","is-moderator","is-editor","is-author"),_$$$("fictioneer-ajax-nonce")?.remove(),_$$(".only-moderators, .only-admins, .only-authors, .only-editors, .chapter-group__list-item-checkmark").forEach((e=>{e.remove()}))}function fcn_ajaxAuth(){let e=!1,t=fcn_parseJSON(localStorage.getItem("fcnAuth"))??!1;if(fcn_isLoggedIn&&!t?.loggedIn&&(localStorage.removeItem("fcnAuth"),t=!1),t){fcn_addNonceHTML(t.nonceHtml);const n=new CustomEvent("fcnAuthReady",{detail:{nonceHtml:t.nonceHtml,nonce:t.nonce,loggedIn:t.loggedIn,isAdmin:t.isAdmin,isModerator:t.isModerator,isAuthor:t.isAuthor,isEditor:t.isEditor},bubbles:!0,cancelable:!1});if(document.dispatchEvent(n),e=!0,fcn_ajaxLimitThreshold<t.lastLoaded)return}fcn_ajaxGet({action:"fictioneer_ajax_get_auth",fcn_fast_ajax:1}).then((t=>{if(t.success){fcn_addNonceHTML(t.data.nonceHtml);const n={lastLoaded:Date.now(),nonceHtml:t.data.nonceHtml,nonce:t.data.nonce,loggedIn:t.data.loggedIn,isAdmin:t.data.isAdmin,isModerator:t.data.isModerator,isAuthor:t.data.isAuthor,isEditor:t.data.isEditor};if(!e){const e=new CustomEvent("fcnAuthReady",{detail:n,bubbles:!0,cancelable:!1});document.dispatchEvent(e)}localStorage.setItem("fcnAuth",JSON.stringify(n))}else{fcn_cleanupGuestView();const e=new Event("fcnAuthFailed");document.dispatchEvent(e)}})).catch((()=>{localStorage.removeItem("fcnAuth"),fcn_cleanupGuestView();const e=new Event("fcnAuthError");document.dispatchEvent(e)}))}function fcn_addNonceHTML(e){_$$$("fictioneer-ajax-nonce")?.remove(),fcn_theBody.appendChild(fcn_html`${e}`)}function fcn_setLoggedInState(e){fcn_isLoggedIn=e.loggedIn,fcn_theBody.classList.add("logged-in"),fcn_theBody.classList.toggle("is-admin",e.isAdmin),fcn_theBody.classList.toggle("is-moderator",e.isModerator),fcn_theBody.classList.toggle("is-author",e.isAuthor),fcn_theBody.classList.toggle("is-editor",e.isEditor);const t=['label[for="modal-login-toggle"]',"#modal-login-toggle","#login-modal"];e.isAdmin||(t.push(".only-admins"),e.isModerator||t.push(".only-moderators"),e.isAuthor||t.push(".only-authors"),e.isEditor||t.push(".only-editors")),_$$(t.join(", ")).forEach((e=>e.remove())),fcn_getProfileImage(),fcn_fetchUserData()}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 o=n.content.cloneNode(!0);t.classList.add("menu-item-has-children"),t.querySelector('[href="#"]').addEventListener("click",(e=>{e.preventDefault()})),t.appendChild(o)}fcn_chapterList&&(fcn_chapterList=fcn_chapterList.cloneNode(!0),_$$$("story-chapter-list").remove(),fcn_chapterList.querySelector(`[data-id="${fcn_chapterList.dataset.currentId}"]`)?.classList.add("current-chapter")),fcn_isLoggedIn||fcn_theRoot.dataset.ajaxAuth||(fcn_cleanupWebStorage(!0),fcn_cleanupGuestView()),"function"==typeof fcn_removeQueryArgs&&fcn_removeQueryArgs(),_$("#wp-admin-bar-logout a")?.addEventListener("click",(()=>{fcn_cleanupWebStorage()})),_$$(".subscriber-login, .oauth-login-link, [data-prepare-login]").forEach((e=>{e.addEventListener("click",(()=>{fcn_prepareLogin()}))})),document.addEventListener("DOMContentLoaded",(()=>{fcn_theRoot.dataset.ajaxAuth&&fcn_ajaxAuth()})),!fcn_isLoggedIn&&fcn_theRoot.dataset.ajaxAuth&&document.addEventListener("fcnAuthReady",(e=>{e.detail.loggedIn?fcn_setLoggedInState(e.detail):(fcn_cleanupWebStorage(!0),fcn_cleanupGuestView())})),fcn_bindEventToAnimationFrame("scroll","scroll.rAF"),fcn_bindEventToAnimationFrame("resize","resize.rAF"),fcn_theBody.addEventListener("click",(e=>{const t=e.target.closest(".toggle-last-clicked");if(t&&(!["BUTTON","A","INPUT","SELECT"].includes(e.target.tagName)||e.target.classList.contains("toggle-last-clicked")))return fcn_toggleLastClicked?.(t),"function"==typeof fcn_popupPosition&&fcn_popupPosition(),void e.stopPropagation();const n=e.target.closest(".page-numbers.dots:not(button)");if(n)return void fcn_jumpPage(n);const o=e.target.closest(".spoiler");if(o)return void o.classList.toggle("_open");e.target.closest(".oauth-login-link, .subscriber-login, [data-prepare-login]")&&fcn_prepareLogin();const s=e.target.closest("[data-click]"),a=s?.dataset.click;if(a)switch(a){case"copy-to-clipboard":s.select(),fcn_copyToClipboard(s.value,s.dataset.message);break;case"reset-consent":fcn_deleteCookie("fcn_cookie_consent"),location.reload();break;case"clear-cookies":fcn_deleteAllCookies(),alert(s.dataset.message);break;case"logout":fcn_cleanupWebStorage();break;case"card-toggle-follow":fcn_isLoggedIn?fcn_toggleFollow(s.dataset.storyId):_$$$("modal-login-toggle")?.click();break;case"card-toggle-reminder":fcn_isLoggedIn?fcn_toggleReminder(s.dataset.storyId):_$$$("modal-login-toggle")?.click();break;case"card-toggle-checkmarks":fcn_isLoggedIn?(fcn_toggleCheckmark(parseInt(s.dataset.storyId),s.dataset.type,parseInt(s.dataset.chapterId),null,s.dataset.mode),fcn_updateCheckmarksView()):_$$$("modal-login-toggle")?.click();break;case"toggle-obfuscation":s.closest("[data-obfuscation-target]").classList.toggle("_obfuscated")}})),fcn_theBody.addEventListener("change",(e=>{const t=e.target.closest('[type="checkbox"]');if(!t)return;const n=t.name,o=n?_$$(`label[for="${n}"]`):[],s=t.checked;t.closest("[aria-checked]")?.setAttribute("aria-checked",s),o.forEach((e=>{e.closest("[aria-checked]")?.setAttribute("aria-checked",s)}))})),_$$(".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<t.offsetHeight&&t.classList.add("_oversized-navigation"),_$$(".main-navigation .trigger-term-menu-categories").forEach((e=>{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)}))}));var fcn_lastScrollTop=0;function fcn_scrollDirection(){if(fcn_theSite.classList.contains("transformed-scroll"))return;const e="hidden"!==window.getComputedStyle(document.documentElement).overflow?window.scrollY??document.documentElement.scrollTop:fcn_theBody.scrollTop??1;fcn_theBody.classList.toggle("scrolled-to-top",0===e),e>fcn_lastScrollTop&&Math.abs(fcn_lastScrollTop-e)>=10?(fcn_theBody.classList.add("scrolling-down"),fcn_theBody.classList.remove("scrolling-up"),fcn_lastScrollTop=Math.max(e,0)):e<fcn_lastScrollTop&&Math.abs(fcn_lastScrollTop-e)>=50&&(fcn_theBody.classList.add("scrolling-up"),fcn_theBody.classList.remove("scrolling-down"),fcn_lastScrollTop=Math.max(e,0))}function fcn_observe(e,t,n={}){const o=_$(e);if(!o)return null;new IntersectionObserver((e=>t(e[0])),n).observe(o)}function fcn_dragElement(e){const t=e.querySelector(".drag-anchor")??e;let n,o;function s(t){t.preventDefault(),e.style.top=e.offsetTop-(o-t.clientY)+"px",e.style.left=e.offsetLeft-(n-t.clientX)+"px",n=t.clientX,o=t.clientY}function a(){t.onmouseup=null,t.onmousemove=null}t.onmousedown=function(e){e.preventDefault(),n=e.clientX,o=e.clientY,t.onmousemove=s,t.onmouseup=a}}function fcn_showNotification(e,t=3,n="base"){const o=_$("#notifications"),s=document.createElement("div");s.innerHTML=e,s.classList.add("notifications__message",`_${n}`),s.style.opacity=1,s.style.transitionDelay=`${t}s`,o.prepend(s),s.addEventListener("transitionend",(e=>{"opacity"===e.propertyName&&o.removeChild(e.target)})),s.addEventListener("click",(e=>{o.removeChild(e.currentTarget)})),setTimeout((()=>{s.style.opacity=0}),100)}if(window.addEventListener("scroll.rAF",fcn_throttle(fcn_scrollDirection,200)),fcn_scrollDirection(),document.addEventListener("DOMContentLoaded",(()=>{fcn_observe(".main-observer",(e=>{fcn_theBody.classList.toggle("is-inside-main",e.intersectionRatio<1&&e.boundingClientRect.top<=0)}),{threshold:[1]}),fcn_observe(".chapter-end",(e=>{fcn_theBody.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"))})),fcn_urlParams){switch(fcn_urlParams.failure&&console.error("Failure:",fcn_urlParams.failure),fcn_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"===fcn_urlParams.success)fcn_showNotification(fictioneer_tl.notification.oauthNew,10);else fcn_urlParams.success?.startsWith("oauth_merged_")&&fcn_showNotification(fictioneer_tl.notification.oauthAccountLinked,3,"success");if(fcn_urlParams["fictioneer-notice"]){let e="1"===fcn_urlParams.failure?"warning":"base";e="1"===fcn_urlParams.success?"success":e,fcn_showNotification(fcn_sanitizeHTML(fcn_urlParams["fictioneer-notice"]),3,e)}}const fcn_settingMinimal=_$$$("site-setting-minimal"),fcn_settingChapterProgressBar=_$$$("site-setting-chapter-progress-bar"),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","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"==fcn_theRoot.dataset.modeDefault))}function fcn_setLightMode(e,t=!1){localStorage.setItem("fcnLightmode",e),fcn_theRoot.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",fcn_theRoot.dataset.fontWeight="default",fcn_applySiteSettings(fcn_siteSettings)}function fcn_updateHueRotate(e){e=fcn_clamp(0,360,e??0),fcn_settingHueRotateText.value=e,fcn_settingHueRotateRange.value=e,fcn_settingHueRotateReset.classList.toggle("_modified",0!=e),fcn_theRoot.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=fcn_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;fcn_theRoot.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=fcn_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;fcn_theRoot.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=fcn_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;fcn_theRoot.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,"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=fcn_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":fcn_theRoot.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:fcn_theRoot.classList.toggle(`no-${e[0]}`,!e[1])}})),fcn_setSiteSettings(e)}function fcn_updateSiteTheme(e){fcn_siteSettings["site-theme"]=e,fcn_theRoot.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_jumpPage(e){if(fcn_theRoot.dataset.disablePageJump)return;const t=parseInt(window.prompt(fictioneer_tl.notification.enterPageNumber));if(t>0){const n=e.nextElementSibling.getAttribute("href"),o=["page=","paged=","comment-page-","pg="];for(const e of o)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}`)}}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"==fcn_theRoot.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,fcn_theRoot.dataset.fontWeight=e.target.value,fcn_applySiteSettings(fcn_siteSettings),fcn_updateFontWeight()}})),fcn_settingHueRotateReset?.addEventListener("click",(()=>{fcn_updateHueRotate(0)})),fcn_settingHueRotateRange?.addEventListener("input",fcn_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",fcn_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",fcn_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",fcn_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();const fcn_cardListMutationObserver=new MutationObserver((e=>{e.forEach((e=>{e.addedNodes.length>0&&("function"==typeof fcn_updateFollowsView&&fcn_updateFollowsView(),"function"==typeof fcn_updateCheckmarksView&&fcn_updateCheckmarksView(),"function"==typeof fcn_updateRemindersView&&fcn_updateRemindersView())}))}));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),o={action:"fictioneer_ajax_submit_contact_form"};if(t.reportValidity()&&(e.disabled=!0,e.innerHTML=e.dataset.disabled,!(Date.now()<fcn_pageLoadTimestamp+3e3))){for(const[e,t]of n)o[e]=t;t.classList.add("ajax-in-progress"),fcn_ajaxPost(o).then((n=>{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,fcn_showNotification(n.data.failure,5,"warning"))})).catch((t=>{t.status&&t.statusText&&(fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning"),e.disabled=!1,e.innerHTML=e.dataset.enabled),console.error(t)})).then((()=>{t.classList.remove("ajax-in-progress")}))}}_$$(".card-list:not(._no-mutation-observer)").forEach((e=>fcn_cardListMutationObserver.observe(e,{childList:!0,subtree:!0}))),_$$(".chapter-group__name").forEach((e=>{e.addEventListener("click",(e=>{const t=e.currentTarget.closest(".chapter-group"),n=t.querySelector(".chapter-group__list"),o=!t.classList.contains("_closed");_$(".main__background")?.classList.add("will-change"),n.style.height=`${n.scrollHeight}px`,requestAnimationFrame((()=>{requestAnimationFrame((()=>{t.classList.toggle("_closed",o),n.style.height=o?"0":`${n.scrollHeight}px`}))}))}))})),_$$(".chapter-group__list").forEach((e=>{e.addEventListener("transitionend",(t=>{e.style.height="",e.querySelectorAll("a, button, label, input:not([hidden])").forEach((t=>{t.tabIndex=e.parentElement.classList.contains("_closed")?"-1":"0"})),_$(".main__background")?.classList.remove("will-change")}))})),_$(".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)}))})),fcn_theBody.querySelectorAll(".modal-toggle").forEach((e=>{e.addEventListener("change",(e=>{if(e.currentTarget.checked){const t=e.currentTarget.nextElementSibling.querySelector('[tabindex="0"]');t?.focus(),t?.blur()}else fcn_theBody.classList.contains("user-is-tabbing")&&fcn_theSite.querySelector(`label[for="${e.currentTarget.id}"]`)?.focus()}))})),_$$('[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",(e=>{"dialog"===e.target.tagName.toLowerCase()&&(e.preventDefault(),e.target.close())}))})),_$(".content-section")?.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,o=e.target.dataset.dialogContent;o.length>200&&(t.style="--modal-width: 400px;"),n&&(t.querySelector('[data-finder="tooltip-dialog-header"]').innerHTML=n),t.querySelector('[data-finder="tooltip-dialog-content"]').innerHTML=o,t.showModal()}})),fcn_theBody.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&&(32!=e.keyCode&&13!=e.keyCode||(e.preventDefault(),t.click())),27==e.keyCode){_$$(".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.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=JSON.parse(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((o=>{const s=o.innerText.toLowerCase();s.includes(e)&&this.keywords.indexOf(s)<0?(o.hidden=!1,t++,""==n&&s.startsWith(e)&&(n=s)):o.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 o=this.allowList[this.encode(n)];if("authors"!=this.collection.name&&"ex_authors"!=this.collection.name||!t||(o=this.allowList[this.encode(n)+`_${t.value}`]),!o||this.keywords.indexOf(o)>-1)return;this.keywords.push(o);const s=document.createElement("div");s.innerHTML=`<span class="node-name">${n}</span><span class="node-delete"><i class="fa-solid fa-xmark"></i></span>`,s.classList.add("node"),s.dataset.value=o,this.inputWrapper.parentNode.insertBefore(s,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=>{9!=e.keyCode&&13!=e.keyCode||""!=this.tabSuggestion.innerText&&(e.preventDefault(),this.input.value=this.tabSuggestion.innerText,this.addNode()),27==e.keyCode&&(this.input.value="",this.tabSuggestion.innerHTML="",document.activeElement.blur()),8==e.keyCode&&""==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){9==e.keyCode&&(fcn_theBody.classList.add("user-is-tabbing"),window.removeEventListener("keydown",fcn_handleTabInput),window.addEventListener("mousedown",fcn_handleMouseInput))}function fcn_handleMouseInput(){fcn_theBody.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=fcn_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="${fcn_theBody.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(!fcn_theRoot.dataset.ageConfirmation&&e&&"adult"!==e)return void _$$$("age-confirmation-modal")?.remove();const t=_$$$("age-confirmation-leave");fcn_theRoot.classList.add("age-modal-open"),_$$$("age-confirmation-modal").classList.add("_open"),_$$$("age-confirmation-confirm")?.addEventListener("click",(e=>{fcn_theRoot.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",fcn_throttle(fcn_popupPosition,250)),_$$(".modal-toggle").forEach((e=>{e.addEventListener("change",(e=>{const t=_$$$(e.currentTarget.dataset.target);t.classList.toggle("_open",e.currentTarget.checked),t.hidden=!e.currentTarget.checked;const n=t.querySelector(".close");n?.focus(),n?.blur()}))})),fcn_theBody.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 o=n.replace("#",""),s=_$$(`[name="${o}"], [id="${o}"]`)[0],a=t.closest(".comment._story-comment");a&&(window.location.href=a.querySelector(".fictioneer-comment__link").href+n),s&&(e.preventDefault(),s.scrollIntoView({behavior:"smooth",block:t.dataset?.block??"start"}))})),fcn_markCurrentMenuItem(),_$$$("age-confirmation-modal")&&"1"!==localStorage.getItem("fcnAgeConfirmation")&&!fcn_isSearchEngineCrawler()?setTimeout((()=>{fcn_showAgeConfirmationModal()
}),2500):_$$$("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()}))}));