UNPKG

uxlib

Version:

A clean and powerful utility library by Subrata

2 lines (1 loc) 15.9 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).uxlib={})}(this,function(e){"use strict";const t=(()=>{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})(),n="undefined"!=typeof localStorage&&"true"===localStorage.getItem("UXLIB_DEBUG"),o=(()=>{if("undefined"!=typeof document){const e=document.currentScript,t=e?.getAttribute("debug");return""===t||"true"===t}return!1})(),r="undefined"!=typeof process&&"development"===process.env?.NODE_ENV,i="undefined"!=typeof process&&void 0!==process.env?.UXLIB_DEBUG&&"true"===process.env.UXLIB_DEBUG;function a(e){if("undefined"==typeof window)return;"boolean"==typeof e&&(localStorage.setItem("UXLIB_DEBUG",e?"true":"false"),window.ULIB_DEBUG=e);return"true"===localStorage.getItem("UXLIB_DEBUG")||!0===window.ULIB_DEBUG||t||o}function s(){return a()||i||r||n||t||o||"undefined"!=typeof window&&!0===window.UXLIB_DEBUG}const l=new Set;function u(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!l.has(t)&&(l.add(t),setTimeout(()=>l.delete(t),500),!0)}catch(e){return!0}}function c(...e){setTimeout(()=>{if(!s()||!u(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 d(...e){setTimeout(()=>{s()&&u(e)&&console.warn("[UXLIB]",...e)},0)}function f(...e){setTimeout(()=>{s()&&u(e)&&console.error("[UXLIB]",...e)},0)}var p=Object.freeze({__proto__:null,DEBUG:a,isDev:s,devLog:c,devWarn:d,devError:f});async function m(){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 g(e){return e&&"object"==typeof e&&!Array.isArray(e)}var y=Object.freeze({__proto__:null,formatDate:function(e){return console.log("format date function"),new Date(e).toLocaleDateString("en-IN")},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"},isObject:g,isArray:function(e){return Array.isArray(e)},isString:function(e){return"string"==typeof e},isEmpty:function(e){return null==e||"string"==typeof e&&""===e.trim()||Array.isArray(e)&&0===e.length||g(e)&&0===Object.keys(e).length},isMobile:function(){return/Mobi|Android/i.test(navigator.userAgent)},isOnline:function(){return navigator.onLine},getQueryParams:function(e){const t=new URLSearchParams(window.location.search);return e?t.get(e):Object.fromEntries(t.entries())},updateQueryParam:function(e,t){const n=new URL(window.location.href);n.searchParams.set(e,t),window.history.pushState({},"",n)},randomId:function(e=6){return Math.random().toString(36).substr(2,e)},randomColor:function(){return`#${Math.floor(16777215*Math.random()).toString(16).padStart(6,"0")}`}});function w(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 h=null,b=null,v=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 E(e,{duration:t=3e3,position:n="top-right",preset:o="default"}={}){const r=Date.now(),i=`${e}-${o}`;if(i===b&&r-v<300)return void c("⏱️ Duplicate toast skipped:",e);b=i,v=r,function(e){if(h)return;if(h=document.createElement("div"),h.className=`uxlib-toast-container ${e}`,document.body.appendChild(h),!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 a=document.createElement("div");a.className=`uxlib-toast ${x[o]||x.default}`,a.innerText=e,h.appendChild(a),setTimeout(()=>{a.classList.add("fade-out"),a.addEventListener("transitionend",()=>a.remove())},t),c("🔔 Toast shown:",{message:e,duration:t,position:n,preset:o})}function _(e){if(e){if("string"==typeof e)return E(e);if("object"==typeof e){const{message:t,duration:n,position:o,preset:r}=e;return E(t||"✅ Default Toast",{duration:n,position:o,preset:r})}c("❌ Invalid toast config:",e)}}const L=_;var S=Object.freeze({__proto__:null,toaster:_,showToast:L,toastSuccess:(e,t={})=>E(e,{...t,preset:"success"}),toastError:(e,t={})=>E(e,{...t,preset:"error"}),toastWarning:(e,t={})=>E(e,{...t,preset:"warning"}),toastInfo:(e,t={})=>E(e,{...t,preset:"info"}),toastInverse:(e,t={})=>E(e,{...t,preset:"inverse"}),toastDefault:(e,t={})=>E(e,{...t,preset:"default"})});var T=Object.freeze({__proto__:null,copyToClipboard:function(e,t={}){return new Promise((n,o)=>{const{onStart:r=()=>{},onSuccess:i=()=>{},onFail:a=()=>{},onEnd:s=()=>{},showToast:l=!1,showAlert:u=!1,highlightArea:d=null,changeButtonText:f=!1,duration:p=3e3}=t,{type:m,value:g,element:y}=w(e);if(!g||"error"===m)return c("❌ Failed to resolve input for copy:",g),a(g),s(),void o({success:!1,message:"Failed to resolve input",error:g});try{r(g,y),c("📍 onStart triggered.")}catch(e){c("⚠️ Error in onStart:",e)}(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(g):new Promise((e,t)=>{try{const n=document.createElement("textarea");n.value=g,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(c("✅ Copy successful:",g),i(g,y),l){_("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(u){const e="string"==typeof u?u:"Copied!";alert(e),c("📣 Alert shown:",e)}!function(e,t=2e3){if(!e)return;let n="",o=t,r="copyArea",i=!0;"string"==typeof e?n=e:"object"==typeof e&&(n=e.selector,o=e.duration||o,r=e.setClass||r,(e.setId||e.setClass)&&(i=!1));const{element:a}=w(n);if(!a)return void c(`⚠️ Highlight skipped: Element not found for selector '${n}'`);if(a.classList.remove(r),a.offsetWidth,a.classList.add(r),setTimeout(()=>a.classList.remove(r),o),i&&!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)}c("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}=w(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),c("Button text will revert in:",o)):c("Button text changed permanently.")}}(f),s(g,y),n({success:!0,message:"Copied successfully",text:g,element:y})}).catch(e=>{c("❌ Copy failed:",e),a(e,y),s(g,y),o({success:!1,message:"Copy failed",error:e,text:g,element:y})})})}});function $(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),c("❗ ERROR HANDLED:",n)}var A=Object.freeze({__proto__:null,callApi:async function({method:e="GET",url:t,baseURL:n="",headers:o={},data:r=null,token:i=null,timeout:a=1e4,showToast:s=!1,showLoader:l=!1,onStart:u=()=>{},onSuccess:d=()=>{},onError:f=()=>{},onEnd:p=()=>{}}={}){const m=n+t,g=new AbortController,y=setTimeout(()=>g.abort(),a),w={"Content-Type":"application/json",...o};i&&(w.Authorization=`Bearer ${i}`);try{l&&c("🔄 Loader Start"),u()}catch(e){c("⚠️ onStart error:",e)}c("📡 API REQUEST",{method:e,url:m,headers:w,body:r});try{const t=await fetch(m,{method:e,headers:w,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();c("✅ API RESPONSE:",o);const i={success:t.ok,status:t.status,message:t.statusText,data:o};if(!t.ok)throw $(i,s),f(o,t.status),i;return d(o),i}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 $(t,s),f(t),t}finally{try{p()}catch(e){c("⚠️ onEnd hook error:",e)}l&&c("✅ Loader End")}}});let C=null;var U=Object.freeze({__proto__:null,isOnline:function(){return"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine?(c("🌐 Network Status:",navigator.onLine?"Online":"Offline"),navigator.onLine):(c("⚠️ navigator.onLine not supported"),!0)},onNetworkChange:function(e){if("undefined"==typeof window||"function"!=typeof e)return;const t=()=>{const t=navigator.onLine?"online":"offline";c(`🔄 Network changed: ${t}`),e({online:navigator.onLine,status:t})};return window.addEventListener("online",t),window.addEventListener("offline",t),t(),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",t)}},watchNetworkStatus:function(e){"undefined"!=typeof window&&"function"==typeof e&&(C=()=>{const t=navigator.onLine;c("📡 Connection status: "+(t?"Online":"Offline")),e({online:t})},window.addEventListener("online",C),window.addEventListener("offline",C),c("👀 Started watching network status"))},stopWatchingNetwork:function(){C&&(window.removeEventListener("online",C),window.removeEventListener("offline",C),c("👋 Stopped watching network status"),C=null)}});var D=Object.freeze({__proto__:null,getElement:function(e,t=!0){const{element:n,type:o}=w(e);let r=0,i=!0;"number"==typeof t?r=t:"boolean"==typeof t&&(i=t);let a=n;if(("class"===o||"string"===o)&&"string"==typeof e)try{a=document.querySelectorAll(e)[r]||null}catch(t){return d("❌ getElement(): Invalid selector syntax →",e,t),null}if(!a&&i){const t="string"==typeof e&&/^[a-z][a-z0-9-]*$/.test(e.trim());return d(`❌ 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 c("✅ getElement():",a?.cloneNode?.(!0)||a),a}});var I=Object.freeze({__proto__:null,getElements:function(e,...t){const n=w(e);if(!n||"error"===n.type)return d(`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 i=[];try{if("id"===o&&n.element)i=[n.element];else if("class"===o||"string"===o||"tag"===o)i=Array.from(document.querySelectorAll(e));else{if(!("element"===o&&n.element instanceof HTMLElement))return d(`getElements(): Unsupported input type for ${r}`),null;i=[n.element]}}catch(e){return d(`getElements(): Error while querying ${r}`,e),null}let a=i;if(t.length){if(t.includes("even"))a=i.filter((e,t)=>t%2==0);else if(t.includes("odd"))a=i.filter((e,t)=>t%2!=0);else{a=t.filter(e=>"number"==typeof e&&e>=0&&e<i.length).map(e=>i[e]).filter(Boolean)}return c({collapsed:!0},`[UXLIB] getElements: Returning ${a.length} filtered element(s) for ${r}`,...a.map((e,t)=>`→ [${t}] ${e.outerHTML}`)),a}return c({collapsed:!0},`[UXLIB] getElements: Returning ${i.length} element(s) for ${r}`,...i.map((e,t)=>`→ [${t}] ${e.outerHTML}`)),i}});const B=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 d("getData: Selector must be a valid string."),null;try{const o=document.querySelectorAll(e);if(0===o.length)return d(`getData: No elements found for selector "${e}"`),null;if(n<0||n>=o.length)return d(`getData: Index ${n} is out of range. Total found: ${o.length}`),null;const r=o[n].dataset[t];if(void 0===r)return d(`getData: Element found but does not contain data-${t}`),null;const i=e.startsWith("#")?"":`[${n}]`;return c(`getData: data-${t} value from "${e}"${i} →`,r),r}catch(e){return f("getData: Unexpected error →",e),null}}(e,t,n)}});var k=Object.freeze({__proto__:null,getData:B});"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",m):m(),window.__ulib_signature__=!0,c("✅ uxlib initialized Version: 1.0.3"));const j={...y,...T,...p,...A,...U,...D,...I,...k,...S};if("undefined"!=typeof window&&(window.uxlib=j),"undefined"!=typeof window){let e="uxlib";try{const t=document.getElementsByTagName("script"),n=(document.currentScript||t[t.length-1]).getAttribute("name");n&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(n)&&(e=n)}catch(e){console.warn("UXLib: Failed to detect custom name attribute. Defaulting to 'uxlib'.")}window[e]=j}e.default=j,Object.defineProperty(e,"__esModule",{value:!0})});