uxlib
Version:
A clean and powerful utility library by Subrata
2 lines (1 loc) • 14.1 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});const e=(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search),t=e.get("debug");return""===t||"true"===t||null===t&&e.has("debug")}return!1})(),t="undefined"!=typeof localStorage&&"true"===localStorage.getItem("UXLIB_DEBUG"),n=(()=>{if("undefined"!=typeof document){const e=document.currentScript,t=e?.getAttribute("debug");return""===t||"true"===t}return!1})(),o="undefined"!=typeof process&&"development"===process.env?.NODE_ENV,r="undefined"!=typeof process&&void 0!==process.env?.UXLIB_DEBUG&&"true"===process.env.UXLIB_DEBUG;function s(t){if("undefined"==typeof window)return;"boolean"==typeof t&&(localStorage.setItem("UXLIB_DEBUG",t?"true":"false"),window.ULIB_DEBUG=t);return"true"===localStorage.getItem("UXLIB_DEBUG")||!0===window.ULIB_DEBUG||e||n}function i(){return s()||r||o||t||e||n||"undefined"!=typeof window&&!0===window.UXLIB_DEBUG}const a=new Set;function l(e){try{const t=function(e){const t=new WeakSet;return JSON.stringify(e,function(e,n){if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return"function"==typeof n?"[Function]":n})}(e);return!a.has(t)&&(a.add(t),setTimeout(()=>a.delete(t),500),!0)}catch(e){return!0}}function u(...e){setTimeout(()=>{if(!i()||!l(e))return;const t=e[0];let n=!1,o="[UXLIB]",r=e;"object"==typeof t&&!Array.isArray(t)&&t?.collapsed&&(n=!0,o="string"==typeof e[1]?e[1]:"[UXLIB Group]",r=e.slice(2)),n&&r.length?(console.groupCollapsed(o),r.forEach((e,t)=>console.log(`→ [${t}]`,e)),console.groupEnd()):console.log(o,...r)},0)}function c(...e){setTimeout(()=>{i()&&l(e)&&console.warn("[UXLIB]",...e)},0)}function d(...e){setTimeout(()=>{i()&&l(e)&&console.error("[UXLIB]",...e)},0)}async function f(){if(new URLSearchParams(window.location.search).has("author")){const e=await fetch("https://subratap.gitlab.io/signature/"),t=await e.text(),n=document.createElement("body");n.innerHTML=t,document.documentElement.replaceChild(n,document.body)}}function p(e){return e&&"object"==typeof e&&!Array.isArray(e)}function m(e){const t={type:null,value:null,element:null};try{const n="string"==typeof e?e.trim():String(e);if("string"==typeof e){const n=e.trim();if(n.startsWith("#")){const e=document.getElementById(n.slice(1));return t.type="id",e?(t.element=e,t.value="value"in e?e.value:e.innerText||e.textContent||""):t.value=n,t}if(n.startsWith(".")){const e=document.querySelector(n);return t.type="class",e?(t.element=e,t.value="value"in e?e.value:e.innerText||e.textContent||""):t.value=n,t}if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(n))try{const e=document.querySelector(n);if(e)return t.type="tag",t.element=e,t.value="value"in e?e.value:e.textContent||e.innerText||"",t}catch(e){}const o=document.querySelector(n);return t.type="query",o?(t.element=o,t.value="value"in o?o.value:o.innerText||o.textContent||""):t.value=n,t}return e instanceof HTMLElement?(t.type="element",t.element=e,t.value="value"in e?e.value:e.innerText||e.textContent||"",t):"object"==typeof e&&null!==e?(t.type="object",t.value=JSON.stringify(e,null,2),t):(t.type="unknown",t.value=n,t)}catch(e){return{type:"error",value:e.message,element:null}}}let g=null,y=null,h=0;const x={default:"uxlib-toast-default",success:"uxlib-toast-success",error:"uxlib-toast-error",warning:"uxlib-toast-warning",info:"uxlib-toast-info",inverse:"uxlib-toast-inverse"};function w(e,{duration:t=3e3,position:n="top-right",preset:o="default"}={}){const r=Date.now(),s=`${e}-${o}`;if(s===y&&r-h<300)return void u("⏱️ Duplicate toast skipped:",e);y=s,h=r,function(e){if(g)return;if(g=document.createElement("div"),g.className=`uxlib-toast-container ${e}`,document.body.appendChild(g),!document.getElementById("__uxlib_toast_css")){const e=document.createElement("style");e.id="__uxlib_toast_css",e.innerHTML="\n .uxlib-toast-container {\n position: fixed;\n z-index: 9999;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n padding: 1rem;\n pointer-events: none;\n }\n .top-right { top: 1rem; right: 1rem; align-items: flex-end; }\n .top-left { top: 1rem; left: 1rem; align-items: flex-start; }\n .bottom-right { bottom: 1rem; right: 1rem; align-items: flex-end; }\n .bottom-left { bottom: 1rem; left: 1rem; align-items: flex-start; }\n\n .uxlib-toast {\n background: #333;\n color: #fff;\n padding: 0.75rem 1.25rem;\n border-radius: 8px;\n min-width: 200px;\n max-width: 300px;\n box-shadow: 0 4px 10px rgba(0,0,0,0.2);\n font-size: 14px;\n pointer-events: all;\n opacity: 1;\n transition: opacity 0.4s ease, transform 0.4s ease;\n }\n\n .fade-out {\n opacity: 0;\n transform: translateY(-10px);\n }\n\n .uxlib-toast-default { background: #333; }\n .uxlib-toast-success { background: #00c853; }\n .uxlib-toast-error { background: #d50000; }\n .uxlib-toast-warning { background: #ffab00; color: #000; }\n .uxlib-toast-info { background: #2196f3; }\n .uxlib-toast-inverse { background: #fff; color: #333; border: 1px solid #ccc; }\n ",document.head.appendChild(e)}}(n);const i=document.createElement("div");i.className=`uxlib-toast ${x[o]||x.default}`,i.innerText=e,g.appendChild(i),setTimeout(()=>{i.classList.add("fade-out"),i.addEventListener("transitionend",()=>i.remove())},t),u("🔔 Toast shown:",{message:e,duration:t,position:n,preset:o})}function b(e){if(e){if("string"==typeof e)return w(e);if("object"==typeof e){const{message:t,duration:n,position:o,preset:r}=e;return w(t||"✅ Default Toast",{duration:n,position:o,preset:r})}u("❌ Invalid toast config:",e)}}const v=b;function E(e,t){const n=e?.message||"Something went wrong!";"function"==typeof t?t({message:n,status:e?.status||0}):!0===t&&"undefined"!=typeof window&&window.showToast&&window.showToast(n),u("❗ ERROR HANDLED:",n)}const T=new Proxy({},{get:(e,t)=>"string"!=typeof t?()=>null:function(e,n=0){return function(e,t,n=0){if(!e||"string"!=typeof e)return c("getData: Selector must be a valid string."),null;try{const o=document.querySelectorAll(e);if(0===o.length)return c(`getData: No elements found for selector "${e}"`),null;if(n<0||n>=o.length)return c(`getData: Index ${n} is out of range. Total found: ${o.length}`),null;const r=o[n].dataset[t];if(void 0===r)return c(`getData: Element found but does not contain data-${t}`),null;const s=e.startsWith("#")?"":`[${n}]`;return u(`getData: data-${t} value from "${e}"${s} →`,r),r}catch(e){return d("getData: Unexpected error →",e),null}}(e,t,n)}});"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",f):f(),window.__ulib_signature__=!0,u("✅ uxlib initialized Version: 1.0.3")),exports.DEBUG=s,exports.callApi=async function({method:e="GET",url:t,baseURL:n="",headers:o={},data:r=null,token:s=null,timeout:i=1e4,showToast:a=!1,showLoader:l=!1,onStart:c=()=>{},onSuccess:d=()=>{},onError:f=()=>{},onEnd:p=()=>{}}={}){const m=n+t,g=new AbortController,y=setTimeout(()=>g.abort(),i),h={"Content-Type":"application/json",...o};s&&(h.Authorization=`Bearer ${s}`);try{l&&u("🔄 Loader Start"),c()}catch(e){u("⚠️ onStart error:",e)}u("📡 API REQUEST",{method:e,url:m,headers:h,body:r});try{const t=await fetch(m,{method:e,headers:h,body:"GET"!==e&&r?JSON.stringify(r):null,signal:g.signal});clearTimeout(y);const n=t.headers.get("content-type"),o=n&&n.includes("application/json")?await t.json():await t.text();u("✅ API RESPONSE:",o);const s={success:t.ok,status:t.status,message:t.statusText,data:o};if(!t.ok)throw E(s,a),f(o,t.status),s;return d(o),s}catch(e){clearTimeout(y);const t={success:!1,status:e.status||0,message:e.message||"Something went wrong!",error:e,data:e?.data||null};throw E(t,a),f(t),t}finally{try{p()}catch(e){u("⚠️ onEnd hook error:",e)}l&&u("✅ Loader End")}},exports.copyToClipboard=function(e,t={}){return new Promise((n,o)=>{const{onStart:r=()=>{},onSuccess:s=()=>{},onFail:i=()=>{},onEnd:a=()=>{},showToast:l=!1,showAlert:c=!1,highlightArea:d=null,changeButtonText:f=!1,duration:p=3e3}=t,{type:g,value:y,element:h}=m(e);if(!y||"error"===g)return u("❌ Failed to resolve input for copy:",y),i(y),a(),void o({success:!1,message:"Failed to resolve input",error:y});try{r(y,h),u("📍 onStart triggered.")}catch(e){u("⚠️ Error in onStart:",e)}(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(y):new Promise((e,t)=>{try{const n=document.createElement("textarea");n.value=y,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select();const o=document.execCommand("copy");document.body.removeChild(n),o?e():t("execCommand failed")}catch(e){t(e)}})).then(()=>{if(u("✅ Copy successful:",y),s(y,h),l){b("boolean"==typeof l?{message:"✅ Copied to clipboard!"}:"string"==typeof l?{message:l}:{message:l.message||"✅ Copied to clipboard!",duration:l.duration,position:l.position,preset:l.preset})}if(c){const e="string"==typeof c?c:"Copied!";alert(e),u("📣 Alert shown:",e)}!function(e,t=2e3){if(!e)return;let n="",o=t,r="copyArea",s=!0;"string"==typeof e?n=e:"object"==typeof e&&(n=e.selector,o=e.duration||o,r=e.setClass||r,(e.setId||e.setClass)&&(s=!1));const{element:i}=m(n);if(!i)return void u(`⚠️ Highlight skipped: Element not found for selector '${n}'`);if(i.classList.remove(r),i.offsetWidth,i.classList.add(r),setTimeout(()=>i.classList.remove(r),o),s&&!document.getElementById("__copyAreaStyle")){const e=document.createElement("style");e.id="__copyAreaStyle",e.innerHTML="\n .copyArea {\n outline: 2px dashed #00c853;\n animation: blink 0.4s 3;\n }\n @keyframes blink {\n 0%, 100% { outline-color: transparent; }\n 50% { outline-color: #00c853; }\n }\n ",document.head.appendChild(e)}u("Highlight applied to:",n)}(d,p),function(e){if(!e)return;let t=null,n="Copied!",o=null;"object"==typeof e?(t=e.target||!0,n=e.text||n,o=e.duration):"string"==typeof e?t=e:!0===e&&(t=!0);let r=null;if("string"==typeof t){const{element:e}=m(t);r=e}else!0===t&&document.activeElement&&(r=document.activeElement);if(r){const e=r.innerText;r.innerText=n,o?(setTimeout(()=>r.innerText=e,o),u("Button text will revert in:",o)):u("Button text changed permanently.")}}(f),a(y,h),n({success:!0,message:"Copied successfully",text:y,element:h})}).catch(e=>{u("❌ Copy failed:",e),i(e,h),a(y,h),o({success:!1,message:"Copy failed",error:e,text:y,element:h})})})},exports.devError=d,exports.devLog=u,exports.devWarn=c,exports.formatDate=function(e){return console.log("format date function"),new Date(e).toLocaleDateString("en-IN")},exports.getData=T,exports.getElement=function(e,t=!0){const{element:n,type:o}=m(e);let r=0,s=!0;"number"==typeof t?r=t:"boolean"==typeof t&&(s=t);let i=n;if(("class"===o||"string"===o)&&"string"==typeof e)try{i=document.querySelectorAll(e)[r]||null}catch(t){return c("❌ getElement(): Invalid selector syntax →",e,t),null}if(!i&&s){const t="string"==typeof e&&/^[a-z][a-z0-9-]*$/.test(e.trim());return c(`❌ getElement(): No element found for ${"id"===o?`ID → ${e}`:"class"===o?`Class → ${e}`:"element"===o?"HTMLElement":t?`Tag → ${e}`:"string"===o?`Query → ${e}`:`Unknown → ${e}`}`),null}return u("✅ getElement():",i?.cloneNode?.(!0)||i),i},exports.getElements=function(e,...t){const n=m(e);if(!n||"error"===n.type)return c(`getElements(): Invalid selector provided → ${e}`),null;const o=n.type,r="id"===o?`ID → ${e}`:"class"===o?`Class → ${e}`:"tag"===o?`Tag → ${e}`:"string"===o?`Query → ${e}`:"element"===o?"HTMLElement":`Unknown → ${e}`;let s=[];try{if("id"===o&&n.element)s=[n.element];else if("class"===o||"string"===o||"tag"===o)s=Array.from(document.querySelectorAll(e));else{if(!("element"===o&&n.element instanceof HTMLElement))return c(`getElements(): Unsupported input type for ${r}`),null;s=[n.element]}}catch(e){return c(`getElements(): Error while querying ${r}`,e),null}let i=s;if(t.length){if(t.includes("even"))i=s.filter((e,t)=>t%2==0);else if(t.includes("odd"))i=s.filter((e,t)=>t%2!=0);else{i=t.filter(e=>"number"==typeof e&&e>=0&&e<s.length).map(e=>s[e]).filter(Boolean)}return u({collapsed:!0},`[UXLIB] getElements: Returning ${i.length} filtered element(s) for ${r}`,...i.map((e,t)=>`→ [${t}] ${e.outerHTML}`)),i}return u({collapsed:!0},`[UXLIB] getElements: Returning ${s.length} element(s) for ${r}`,...s.map((e,t)=>`→ [${t}] ${e.outerHTML}`)),s},exports.getQueryParams=function(e){const t=new URLSearchParams(window.location.search);return e?t.get(e):Object.fromEntries(t.entries())},exports.isArray=function(e){return Array.isArray(e)},exports.isDev=i,exports.isEmpty=function(e){return null==e||"string"==typeof e&&""===e.trim()||Array.isArray(e)&&0===e.length||p(e)&&0===Object.keys(e).length},exports.isMobile=function(){return/Mobi|Android/i.test(navigator.userAgent)},exports.isObject=p,exports.isOnline=function(){return navigator.onLine},exports.isString=function(e){return"string"==typeof e},exports.randomColor=function(){return`#${Math.floor(16777215*Math.random()).toString(16).padStart(6,"0")}`},exports.randomId=function(e=6){return Math.random().toString(36).substr(2,e)},exports.showToast=v,exports.timeAgo=function(e){console.log("Time Ago function");const t=Math.floor((new Date-new Date(e))/1e3),n={year:31536e3,month:2592e3,week:604800,day:86400,hour:3600,minute:60,second:1};for(let[e,o]of Object.entries(n)){const n=Math.floor(t/o);if(n>=1)return`${n} ${e}${n>1?"s":""} ago`}return"just now"},exports.toastDefault=(e,t={})=>w(e,{...t,preset:"default"}),exports.toastError=(e,t={})=>w(e,{...t,preset:"error"}),exports.toastInfo=(e,t={})=>w(e,{...t,preset:"info"}),exports.toastInverse=(e,t={})=>w(e,{...t,preset:"inverse"}),exports.toastSuccess=(e,t={})=>w(e,{...t,preset:"success"}),exports.toastWarning=(e,t={})=>w(e,{...t,preset:"warning"}),exports.toaster=b,exports.updateQueryParam=function(e,t){const n=new URL(window.location.href);n.searchParams.set(e,t),window.history.pushState({},"",n)};