1 line
23 KiB
JavaScript
1 line
23 KiB
JavaScript
const fcn_theSite=_$$$("site"),fcn_theBody=_$("body"),fcn_theRoot=document.documentElement,fcn_inlineStorage=_$$$("inline-storage").dataset,fcn_mainNavigation=_$$$("full-navigation"),fcn_urlSearchParams=new URLSearchParams(window.location.search),fcn_urlParams=Object.fromEntries(fcn_urlSearchParams.entries()),fcn_pageLoadTimestamp=Date.now(),fcn_ajaxLimitThreshold=Date.now()-parseInt(fictioneer_ajax.ttl),fcn_eventNonceReady=new Event("nonceReady"),fcn_isAjaxAuth=fcn_theRoot.dataset.ajaxAuth;var fcn_viewportWidth,fcn_mediaMinTablet,fcn_cssVars=getComputedStyle(document.documentElement),fcn_isLoggedIn=fcn_theBody.classList.contains("logged-in");const{__:__,_x:_x,_n:_n,sprintf:sprintf}=wp.i18n;function fcn_cleanupLocalStorage(e=!1){localStorage.removeItem("fcnProfileAvatar"),localStorage.removeItem("fcnStoryFollows"),localStorage.removeItem("fcnStoryReminders"),localStorage.removeItem("fcnCheckmarks"),localStorage.removeItem("fcnLoginState"),localStorage.removeItem("fcnNonce"),localStorage.removeItem("fcnFingerprint"),localStorage.removeItem("fcnBookshelfContent"),e||localStorage.removeItem("fcnChapterBookmarks")}function fcn_cleanupGuestView(){fcn_isLoggedIn=!1,fcn_theBody.classList.remove("logged-in","is-admin","is-moderator","is-editor","is-author"),_$$(".only-moderators, .only-admins, .only-authors, .only-editors").forEach((e=>{e.remove()}))}function fcn_fetchNonce(){let e=localStorage.getItem("fcnNonce");e=!(!e||!fcn_isValidJSONString(e))&&JSON.parse(e),e&&(fcn_addNonceAndAuth(e.nonceHtml),fcn_ajaxLimitThreshold<e.lastLoaded)||fcn_ajaxGet({action:"fictioneer_ajax_get_nonce"}).then((e=>{_$$$("fictioneer-ajax-nonce")?.remove(),e.success?(fcn_addNonceAndAuth(e.data.nonceHtml),localStorage.setItem("fcnNonce",JSON.stringify({lastLoaded:Date.now(),nonceHtml:e.data.nonceHtml}))):(_$$$("fictioneer-ajax-nonce")?.remove(),fcn_cleanupGuestView())})).catch((()=>{localStorage.removeItem("fcnNonce"),_$$$("fictioneer-ajax-nonce")?.remove(),fcn_cleanupGuestView()}))}function fcn_addNonceAndAuth(e){let t=document.createElement("div");t.innerHTML+=e,fcn_theBody.appendChild(t.firstChild),fcn_theRoot.dispatchEvent(fcn_eventNonceReady),!fcn_isLoggedIn&&fcn_isAjaxAuth&&fcn_fetchLoginState()}function fcn_fetchLoginState(){let e=localStorage.getItem("fcnLoginState");e=!(!e||!fcn_isValidJSONString(e))&&JSON.parse(e),e&&e.loggedIn&&(fcn_setLoggedInState(e,!1),Date.now()-fictioneer_ajax.login_ttl<e.lastLoaded)||fcn_ajaxGet({action:"fictioneer_ajax_is_user_logged_in"}).then((t=>{t.success&&t.data.loggedIn?(fcn_setLoggedInState(t.data,!e.loggedIn),localStorage.setItem("fcnLoginState",JSON.stringify({lastLoaded:Date.now(),loggedIn:t.data.loggedIn,isAdmin:t.data.isAdmin,isModerator:t.data.isModerator,isAuthor:t.data.isAuthor,isEditor:t.data.isEditor}))):(fcn_cleanupLocalStorage(!0),fcn_cleanupGuestView())})).catch((()=>{fcn_cleanupLocalStorage(),fcn_cleanupGuestView()}))}function fcn_setLoggedInState(e,t=!0){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),e.isAdmin||_$$(".only-admins").forEach((e=>{e.remove()})),e.isModerator||e.isAdmin||_$$(".only-moderators").forEach((e=>{e.remove()})),e.isAuthor||e.isAdmin||_$$(".only-authors").forEach((e=>{e.remove()})),e.isModerator||e.isAdmin||_$$(".only-editors").forEach((e=>{e.remove()})),t&&("function"==typeof fcn_initializeCheckmarks&&fcn_initializeCheckmarks(),"function"==typeof fcn_initializeFollows&&fcn_initializeFollows(),"function"==typeof fcn_initializeReminders&&fcn_initializeReminders(),"function"==typeof fcn_getBookmarksForUser&&fcn_getBookmarksForUser(),"function"==typeof fcn_showChapterBookmark&&fcn_showChapterBookmark(),fcn_initializeFingerprint(),fcn_getProfileImage())}function fcn_updateViewportVariables(){fcn_viewportWidth=Math.max(document.documentElement.clientWidth??0,window.innerWidth??0),fcn_mediaMinTablet=fcn_viewportWidth>=768}function fcn_loadEmbed(e){let t=e.target;t.classList.add("hidden"),t.parentNode.querySelectorAll("iframe, script")[0].src=t.dataset.src,t.onclick=null}fcn_isLoggedIn||fcn_isAjaxAuth||fcn_cleanupLocalStorage(!0),"undefined"!=typeof speechSynthesis&&window.speechSynthesis.cancel(),history.replaceState&&history.replaceState(null,"",location.pathname+location.search.replace(/[\?&]failure=[^&]+/,"").replace(/^&/,"?")+location.hash),history.replaceState&&history.replaceState(null,"",location.pathname+location.search.replace(/[\?&]success=[^&]+/,"").replace(/^&/,"?")+location.hash),fcn_theRoot.dataset.ajaxNonce&&fcn_fetchNonce(),fcn_isLoggedIn||!fcn_isAjaxAuth||fcn_theRoot.dataset.ajaxNonce||fcn_fetchLoginState(),fcn_bindEventToAnimationFrame("scroll","scroll.rAF"),fcn_bindEventToAnimationFrame("resize","resize.rAF"),fcn_updateViewportVariables(),window.addEventListener("resize.rAF",fcn_throttle(fcn_updateViewportVariables,125)),_$$(".iframe-consent, .twitter-consent").forEach((e=>{e.onclick=e=>{fcn_loadEmbed(e)}}));var fcn_lastScrollTop=0;function fcn_scrollDirection(){if(fcn_theSite.classList.contains("transformed-scroll"))return;let e=window.scrollY??document.documentElement.scrollTop;Math.abs(fcn_lastScrollTop-e)>=5&&(fcn_theBody.classList.toggle("scrolling-down",e>fcn_lastScrollTop),fcn_theBody.classList.toggle("scrolling-up",!(e>fcn_lastScrollTop)),fcn_lastScrollTop=Math.max(e,0))}window.addEventListener("scroll.rAF",fcn_throttle(fcn_scrollDirection,200));const fcn_mainObserver=new IntersectionObserver((([e])=>fcn_theBody.classList.toggle("is-inside-main",e.intersectionRatio<1)),{threshold:[1]});(observer=_$(".main-observer"))&&fcn_mainObserver.observe(observer);const fcn_endOfChapterObserver=new IntersectionObserver((([e])=>{fcn_theBody.classList.toggle("is-end-of-chapter",e.isIntersecting||e.boundingClientRect.top<0)}),{root:null,threshold:0});(observer=_$(".chapter-end"))&&fcn_endOfChapterObserver.observe(observer);const fct_navStickyObserver=new IntersectionObserver((([e])=>{fcn_mainNavigation.classList.toggle("is-sticky",e.intersectionRatio<1)}),{threshold:[1]});function fcn_dragElement(e){let t,n,i=e.querySelector(".drag-anchor")??e;function o(i){i.preventDefault(),e.style.top=e.offsetTop-(n-i.clientY)+"px",e.style.left=e.offsetLeft-(t-i.clientX)+"px",t=i.clientX,n=i.clientY}function a(){i.onmouseup=null,i.onmousemove=null}i.onmousedown=function(e){e.preventDefault(),t=e.clientX,n=e.clientY,i.onmousemove=o,i.onmouseup=a}}function fcn_showNotification(e,t=3,n="base"){let i=_$("#notifications"),o=document.createElement("div");o.innerHTML=e,o.classList.add("notifications__message",`_${n}`),o.style.opacity=1,o.style.transitionDelay=`${t}s`,i.prepend(o),o.addEventListener("transitionend",(e=>{i.removeChild(e.target)})),o.addEventListener("click",(e=>{i.removeChild(e.currentTarget)})),setTimeout((()=>{o.style.opacity=0}),100)}(observer=_$$$("nav-observer-sticky"))&&fct_navStickyObserver.observe(observer),setTimeout((()=>{fcn_theRoot.scrollTop>40&&fcn_mainNavigation?.classList.add("is-sticky")}),50),_$$(".modal__header.drag-anchor").forEach((e=>{fcn_dragElement(e.closest(".modal__wrapper"))})),"oauth_email_taken"===fcn_urlParams.failure&&fcn_showNotification(__("The associated email address is already taken. You can link additional accounts in your profile.","fictioneer"),5),"oauth_new_subscriber"===fcn_urlParams.success&&fcn_showNotification(__("Your account has been successfully linked. <strong>Hint:</strong> You can change your display name in your profile and link additional accounts.","fictioneer"),10),fcn_urlParams.success?.includes("oauth_merged_")&&fcn_showNotification(__("Account has been successfully linked.","fictioneer"));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-resets"),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":"";let n=_$$$("reader-settings-lightmode-toggle");n&&(n.checked=e),t||fcn_updateThemeColor()}function fcn_updateFontWeight(){let 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)}));let t=e>=0?1+Math.pow(e,2):1-Math.pow(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(){if("-"==this.value||""==this.value)return;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)}));let t=e>=0?1+Math.pow(e,2):1-Math.pow(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(){if("-"==this.value||""==this.value)return;fcn_updateSaturation((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,"hue-rotate":0}}function fcn_getSiteSettings(){let e=localStorage.getItem("fcnSiteSettings");return e=e&&fcn_isValidJSONString(e)?JSON.parse(e):fcn_defaultSiteSettings(),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=>{let 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"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_inlineToggleReminder(e){if(!fcn_isLoggedIn)return fcn_showNotification(__("You need to be logged in.","fictioneer")),void(_$$$("modal-login-toggle").checked=!0);fcn_toggleReminder(e)}function fcn_inlineToggleFollow(e){if(!fcn_isLoggedIn)return fcn_showNotification(__("You need to be logged in.","fictioneer")),void(_$$$("modal-login-toggle").checked=!0);fcn_toggleFollow(e)}function fcn_inlineToggleCheckmark(e,t="story",n=null,i="toggle"){if(!fcn_isLoggedIn)return fcn_showNotification(__("You need to be logged in.","fictioneer")),void(_$$$("modal-login-toggle").checked=!0);fcn_toggleCheckmark(e,t,n,null,i),fcn_updateCheckmarksView()}function fcn_bindPageNumberJumps(){_$$(".page-numbers.dots").forEach((e=>{e.tabIndex=0,e.addEventListener("click",(e=>{let t=parseInt(window.prompt(_x("Enter page number:","Pagination jump prompt.","fictioneer")));if(t>0){let n=e.currentTarget.nextElementSibling.href;if(!n)return;n.includes("page=")?window.location.href=n.replace(/page=\d+/,"page="+t):n.includes("paged=")?window.location.href=n.replace(/paged=\d+/,"paged="+t):n.includes("comment-page-")?window.location.href=n.replace(/comment-page-\d+/,`comment-page-${t}`):window.location.href=n.replace(/page\/\d+/,"page/"+t)}}))}))}fcn_settingEvents.forEach((e=>{_$$$(`site-setting-${e}`).onchange=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_applySiteSettings(fcn_siteSettings),_$$(".site-setting-site-theme").forEach((e=>{e.value=fcn_siteSettings.hasOwnProperty("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(),fcn_theRoot.dataset.disablePageJump||fcn_bindPageNumberJumps();const fcn_cardLists=_$$(".card-list:not(._no-mutation-observer)");var fcn_cardListMutationObserver=new MutationObserver((e=>{e[0].addedNodes&&("function"==typeof fcn_updateFollowsView&&fcn_updateFollowsView(),"function"==typeof fcn_updateCheckmarksView&&fcn_updateCheckmarksView(),"function"==typeof fcn_updateRemindersView&&fcn_updateRemindersView(),_$$(".toggle-last-clicked").forEach((e=>{e.addEventListener("click",(e=>{fcn_toggleLastClicked(e.currentTarget),e.stopPropagation()}))})),fcn_theRoot.dataset.disablePageJump||fcn_bindPageNumberJumps())}));function fct_spoiler(e){e.classList.toggle("_open")}function fcn_revealCommentImage(e){let t=e.parentElement.querySelector("img");t.src=t.dataset.src,e.remove()}function fcn_contactFormSubmit(e){let t=e.closest("form"),n=new FormData(t),i={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)i[e]=t;t.classList.add("ajax-in-progress"),fcn_ajaxPost(i).then((n=>{n.success?(t.querySelector("textarea").value="",e.innerHTML=e.dataset.done,fcn_showNotification(n.data.success,3,"success")):n.data.error&&(e.disabled=!1,e.innerHTML=e.dataset.enabled,fcn_showNotification(n.data.error,5,"warning"))})).catch((t=>{t.status&&t.statusText&&(fcn_showNotification(`${t.status}: ${t.statusText}`,5,"warning"),e.disabled=!1,e.innerHTML=e.dataset.enabled)})).then((()=>{t.classList.remove("ajax-in-progress")}))}}fcn_cardLists.length&&fcn_cardLists.forEach((e=>{fcn_cardListMutationObserver.observe(e,{childList:!0,subtree:!0})})),_$$("[for*=group-toggle]").forEach((e=>{e.addEventListener("click",(e=>{list=e.currentTarget.closest(".chapter-group").querySelector(".chapter-group__list"),list.style.height=`${list.scrollHeight}px`})),e.closest(".chapter-group").querySelector(".chapter-group__list").addEventListener("transitionend",(e=>{list=e.currentTarget.closest(".chapter-group").querySelector(".chapter-group__list"),list.style.height="",list.querySelectorAll("a").forEach((e=>{e.tabIndex="-1"==e.tabIndex?"0":"-1"}))}))})),fcn_theBody.addEventListener("click",(e=>{!e.target.parentNode?.classList.contains("spoiler")||e.target.parentNode?.classList.contains("selected-paragraph")?e.target.classList.contains("spoiler")&&fct_spoiler(e.target):fct_spoiler(e.target.parentNode)})),_$$(".contact-form").forEach((e=>{e.querySelector(".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){let t=e.currentTarget.nextElementSibling.querySelector('[tabindex="0"]');t?.focus(),t?.blur()}else fcn_theSite.querySelector(`label[for="${e.currentTarget.id}"]`)?.focus()}))})),fcn_theBody.addEventListener("keydown",(e=>{let t=document.activeElement.closest('[tabindex="0"]:not(a, input, button, select)');t&&(32!=e.keyCode&&13!=e.keyCode||(e.preventDefault(),t.click())),27==e.keyCode&&(_$$(".modal-toggle:checked").forEach((e=>{let t=fcn_theSite.querySelector(`label[for="${e.id}"]`);t?.focus(),t?.blur(),e.checked=!1})),_$(".lightbox.show")?.querySelector(".lightbox__close").click())}));class FCN_KeywordInput{constructor(e){this.input=e,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(){let e=this.tabSuggestion.innerText.length>0?this.tabSuggestion.innerText.length:this.input.value.length;fcn_resizeInput(this.input,e)}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){return encodeURIComponent(e.toLowerCase()).replace(/'/g,"%27")}filterSuggestions(){let e=this.input.value.toLowerCase(),t=0,n="";""==e?this.suggestionList.querySelectorAll(".keyword-button").forEach((e=>{e.hidden=!0})):this.suggestionList.querySelectorAll(".keyword-button").forEach((i=>{let o=i.innerText.toLowerCase();o.includes(e)&&this.keywords.indexOf(o)<0?(i.hidden=!1,t++,""==n&&o.startsWith(e)&&(n=o)):i.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){let t=e??this.input.value.replace(",",""),n=this.allowList[this.encode(t)];if(!n||this.keywords.indexOf(n)>-1)return;this.keywords.push(n);let i=document.createElement("div");i.innerHTML=`<span class="node-name">${t}</span><span class="node-delete"><i class="fa-solid fa-xmark"></i></span>`,i.classList.add("node"),i.dataset.value=n,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.splice(this.keywords.indexOf(e),1),this.updateCollection(),this.filterSuggestions(),this.resize()}updateCollection(){this.collection.value=this.keywords.join(","),this.form.querySelector(".search-form__current").innerHTML=""}bindEvents(){this.input.addEventListener("input",(e=>{e.currentTarget.value.includes(",")&&this.addNode(),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",(e=>{this.allowList[this.encode(this.input.value)]?this.blurTimeout=setTimeout((()=>{this.addNode()}),150):(this.input.value="",this.tabSuggestion.innerHTML="",this.filterSuggestions(),this.resize())})),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)}))}))}}_$$(".search-form").forEach((e=>{let t=[];e.classList.contains("_simple")||(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",(i=>{t.forEach((e=>{e.reset()})),e.querySelector("input[name=s]").value="",e.querySelector("select[name=post_type]").value="any",e.querySelector("select[name=sentence]").value="0",e.querySelector("select[name=orderby]").value="modified",e.querySelector("select[name=order]").value="desc",e.querySelector(".search-form__current").innerHTML="",fcn_showNotification(n.dataset.reset,2)}))})))})); |