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

1 line
6.8 KiB
JavaScript

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"))||{};localStorage.setItem("fcnUserData",JSON.stringify({...e,lastLoaded:0,timestamp:0,loggedIn:!1,follows:!1,reminders:!1,checkmarks:!1,likes:null,bookmarks:null,fingerprint:!1,isAdmin:!1,isModerator:!1,isAuthor:!1,isEditor:!1}))},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<e.length;t++){if(-1!==e[t].trim().indexOf("fcnLoggedIn="))return!0}return!1},async aGet(e={},t=null,n={}){try{return fcn_ajaxGet(e,t,n)}catch(e){throw console.error("aGet Error:",e),e}},async aPost(e={},t=null,n={}){try{return await fcn_ajaxPost(e,t,n)}catch(e){throw console.error("aPost Error:",e),e}},remoteAction(e,{element:t=null,callback:n=null,errorCallback:o=null,finalCallback:a=null,nonce:r=null,fast:i=!0,payload:l={}}={}){t?.classList.add("ajax-in-progress"),FcnUtils.aPost({action:e,fcn_fast_ajax:!!i,nonce:r??FcnUtils.nonce(),...l}).then((e=>{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<n.length;o++){const e=n[o].trim();if(0==e.indexOf(t))return decodeURIComponent(e.substring(t.length,e.length))}return null},nonce:()=>_$$$("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=`<i class="fa-solid fa-triangle-exclamation"></i><div>${n?FcnUtils.sanitizeHTML(a):a}</div>`,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)}