UNPKG

uxlib

Version:

A clean and powerful utility library by Subrata

2 lines (1 loc) â€ĸ 18.5 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={logDisabled:!1};function n(e){return(...n)=>{const o=t.logDisabled;t.logDisabled=!0;try{return e(...n)}finally{t.logDisabled=o}}}const o=(()=>{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})(),r="undefined"!=typeof localStorage&&"true"===localStorage.getItem("UXLIB_DEBUG"),i=(()=>{if("undefined"!=typeof document){const e=document.currentScript,t=e?.getAttribute("debug");return""===t||"true"===t}return!1})(),s="undefined"!=typeof process&&"development"===process.env?.NODE_ENV,a="undefined"!=typeof process&&void 0!==process.env?.UXLIB_DEBUG&&"true"===process.env.UXLIB_DEBUG;function l(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||o||i}function c(){return l()||a||s||r||o||i||"undefined"!=typeof window&&!0===window.UXLIB_DEBUG}const u=new Set;function d(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!u.has(t)&&(u.add(t),setTimeout(()=>u.delete(t),500),!0)}catch(e){return!0}}function f(...e){t.logDisabled||setTimeout(()=>{if(!c()||!d(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 m(...e){t.logDisabled||setTimeout(()=>{c()&&d(e)&&console.warn("[UXLIB]",...e)},0)}function p(...e){t.logDisabled||setTimeout(()=>{c()&&d(e)&&console.error("[UXLIB]",...e)},0)}var g=Object.freeze({__proto__:null,DEBUG:l,isDev:c,devLog:f,devWarn:m,devError:p});async function y(){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 h(e){return e&&"object"==typeof e&&!Array.isArray(e)}var w=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:h,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||h(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 b(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 v=null,E=null,x=0;const _={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 L(e,{duration:t=3e3,position:n="top-right",preset:o="default"}={}){const r=Date.now(),i=`${e}-${o}`;if(i===E&&r-x<300)return void f("âąī¸ Duplicate toast skipped:",e);E=i,x=r,function(e){if(v)return;if(v=document.createElement("div"),v.className=`uxlib-toast-container ${e}`,document.body.appendChild(v),!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 s=document.createElement("div");s.className=`uxlib-toast ${_[o]||_.default}`,s.innerText=e,v.appendChild(s),setTimeout(()=>{s.classList.add("fade-out"),s.addEventListener("transitionend",()=>s.remove())},t),f("🔔 Toast shown:",{message:e,duration:t,position:n,preset:o})}function $(e){if(e){if("string"==typeof e)return L(e);if("object"==typeof e){const{message:t,duration:n,position:o,preset:r}=e;return L(t||"✅ Default Toast",{duration:n,position:o,preset:r})}f("❌ Invalid toast config:",e)}}const C=$;var S=Object.freeze({__proto__:null,toaster:$,showToast:C,toastSuccess:(e,t={})=>L(e,{...t,preset:"success"}),toastError:(e,t={})=>L(e,{...t,preset:"error"}),toastWarning:(e,t={})=>L(e,{...t,preset:"warning"}),toastInfo:(e,t={})=>L(e,{...t,preset:"info"}),toastInverse:(e,t={})=>L(e,{...t,preset:"inverse"}),toastDefault:(e,t={})=>L(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:s=()=>{},onEnd:a=()=>{},showToast:l=!1,showAlert:c=!1,highlightArea:u=null,changeButtonText:d=!1,duration:m=3e3}=t,{type:p,value:g,element:y}=b(e);if(!g||"error"===p)return f("❌ Failed to resolve input for copy:",g),s(g),a(),void o({success:!1,message:"Failed to resolve input",error:g});try{r(g,y),f("📍 onStart triggered.")}catch(e){f("âš ī¸ 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(f("✅ 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(c){const e="string"==typeof c?c:"Copied!";alert(e),f("đŸ“Ŗ 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:s}=b(n);if(!s)return void f(`âš ī¸ Highlight skipped: Element not found for selector '${n}'`);if(s.classList.remove(r),s.offsetWidth,s.classList.add(r),setTimeout(()=>s.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)}f("Highlight applied to:",n)}(u,m),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}=b(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),f("Button text will revert in:",o)):f("Button text changed permanently.")}}(d),a(g,y),n({success:!0,message:"Copied successfully",text:g,element:y})}).catch(e=>{f("❌ Copy failed:",e),s(e,y),a(g,y),o({success:!1,message:"Copy failed",error:e,text:g,element:y})})})}});function A(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),f("❗ ERROR HANDLED:",n)}var D=Object.freeze({__proto__:null,callApi:async function({method:e="GET",url:t,baseURL:n="",headers:o={},data:r=null,token:i=null,timeout:s=1e4,showToast:a=!1,showLoader:l=!1,onStart:c=()=>{},onSuccess:u=()=>{},onError:d=()=>{},onEnd:m=()=>{}}={}){const p=n+t,g=new AbortController,y=setTimeout(()=>g.abort(),s),h={"Content-Type":"application/json",...o};i&&(h.Authorization=`Bearer ${i}`);try{l&&f("🔄 Loader Start"),c()}catch(e){f("âš ī¸ onStart error:",e)}f("📡 API REQUEST",{method:e,url:p,headers:h,body:r});try{const t=await fetch(p,{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();f("✅ API RESPONSE:",o);const i={success:t.ok,status:t.status,message:t.statusText,data:o};if(!t.ok)throw A(i,a),d(o,t.status),i;return u(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 A(t,a),d(t),t}finally{try{m()}catch(e){f("âš ī¸ onEnd hook error:",e)}l&&f("✅ Loader End")}}});let k=null;var I=Object.freeze({__proto__:null,isOnline:function(){return"undefined"!=typeof navigator&&"boolean"==typeof navigator.onLine?(f("🌐 Network Status:",navigator.onLine?"Online":"Offline"),navigator.onLine):(f("âš ī¸ navigator.onLine not supported"),!0)},onNetworkChange:function(e){if("undefined"==typeof window||"function"!=typeof e)return;const t=()=>{const t=navigator.onLine?"online":"offline";f(`🔄 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&&(k=()=>{const t=navigator.onLine;f("📡 Connection status: "+(t?"Online":"Offline")),e({online:t})},window.addEventListener("online",k),window.addEventListener("offline",k),f("👀 Started watching network status"))},stopWatchingNetwork:function(){k&&(window.removeEventListener("online",k),window.removeEventListener("offline",k),f("👋 Stopped watching network status"),k=null)}});function U(e,t=!0){const{element:n,type:o}=b(e);let r=0,i=!0;"number"==typeof t?r=t:"boolean"==typeof t&&(i=t);let s=n;if(("class"===o||"string"===o)&&"string"==typeof e)try{s=document.querySelectorAll(e)[r]||null}catch(t){return m("❌ getElement(): Invalid selector syntax →",e,t),null}if(!s&&i){const t="string"==typeof e&&/^[a-z][a-z0-9-]*$/.test(e.trim());return m(`❌ 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 f("✅ getElement():",s?.cloneNode?.(!0)||s),s}function B(e,...t){const n=b(e);if(!n||"error"===n.type)return m(`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 m(`getElements(): Unsupported input type for ${r}`),null;i=[n.element]}}catch(e){return m(`getElements(): Error while querying ${r}`,e),null}let s=i;if(t.length){if(t.includes("even"))s=i.filter((e,t)=>t%2==0);else if(t.includes("odd"))s=i.filter((e,t)=>t%2!=0);else{s=t.filter(e=>"number"==typeof e&&e>=0&&e<i.length).map(e=>i[e]).filter(Boolean)}return f({collapsed:!0},`[UXLIB] getElements: Returning ${s.length} filtered element(s) for ${r}`,...s.map((e,t)=>`→ [${t}] ${e.outerHTML}`)),s}return f({collapsed:!0},`[UXLIB] getElements: Returning ${i.length} element(s) for ${r}`,...i.map((e,t)=>`→ [${t}] ${e.outerHTML}`)),i}var j=Object.freeze({__proto__:null,getElement:U,getElements:B}),O=Object.freeze({__proto__:null});const N=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 m("getData: Selector must be a valid string."),null;try{const o=document.querySelectorAll(e);if(0===o.length)return m(`getData: No elements found for selector "${e}"`),null;if(n<0||n>=o.length)return m(`getData: Index ${n} is out of range. Total found: ${o.length}`),null;const r=o[n].dataset[t];if(void 0===r)return m(`getData: Element found but does not contain data-${t}`),null;const i=e.startsWith("#")?"":`[${n}]`;return f(`getData: data-${t} value from "${e}"${i} →`,r),r}catch(e){return p("getData: Unexpected error →",e),null}}(e,t,n)}});var z=Object.freeze({__proto__:null,getData:N});function M(e,t,o){const r=n(U)(e);if(!r)return void m(`No elements found for selector: "${e}"`);const i=n=>{const r=e=>{f(`📌 ${t} event on:`,n.cloneNode?.(!0)||n,`Callback: ${o.name||"anonymous"}`),o(e)},i=n._uxlibListeners?.some(e=>e.type===t&&e.originalCallback===o);i?m(`Duplicate listener prevented: ${t} on`,n):(n.removeEventListener(t,r),n.addEventListener(t,r),n._uxlibListeners||(n._uxlibListeners=[]),n._uxlibListeners.push({type:t,originalCallback:o,wrappedCallback:r}),f({collapsed:!0},`[onEvent:bind] ${t}`,{selector:e,element:n.cloneNode?.(!0)||n,callback:o.name||"anonymous"}))};r instanceof NodeList||Array.isArray(r)?r.forEach(i):i(r)}var H=Object.freeze({__proto__:null,onEvent:M,onClick:function(e,t){M(e,"click",t)},onHover:function(e,t){M(e,"mouseover",t)},onChange:function(e,t){M(e,"change",t)},onInput:function(e,t){M(e,"input",t)}});const P=n(B);function R(e){return Array.isArray(e)?e:"string"==typeof e?P(e):[e]}function X(e,t){const n=R(e);n&&n.length?n.forEach(e=>{e.classList.contains(t)?f(`[addClass] â„šī¸ Element already has class "${t}":`,e):(e.classList.add(t),f(`[addClass] ✅ Added class "${t}" to:`,e))}):m(`[addClass] ❌ No elements found for selector: "${e}"`)}function G(e,t){const n=R(e);n&&n.length?n.forEach(e=>{e.classList.contains(t)?(e.classList.remove(t),f(`[removeClass] đŸ—‘ī¸ Removed class "${t}" from:`,e)):f(`[removeClass] â„šī¸ Element does not have class "${t}":`,e)}):m(`[removeClass] ❌ No elements found for selector: "${e}"`)}var q=Object.freeze({__proto__:null,addClass:X,toggleClass:function(e,t){const n=R(e);n&&n.length?n.forEach(e=>{if(Array.isArray(t)&&2===t.length){const[n,o]=t;e.classList.contains(n)?(G(e,n),X(e,o)):(G(e,o),X(e,n))}else"string"==typeof t?e.classList.contains(t)?G(e,t):X(e,t):m("[toggleClass] ❌ Invalid className provided",t)}):m(`[toggleClass] ❌ No elements found for selector: "${e}"`)},removeClass:G,show:function(e,t="block"){const n=R(e);n&&n.length?n.forEach(e=>{e.style.display=t,f(`[show] đŸ‘ī¸ Shown element (display: ${t}):`,e)}):m(`[show] ❌ No elements found for selector: "${e}"`)},hide:function(e){const t=R(e);t&&t.length?t.forEach(e=>{e.style.display="none",f("[hide] 🙈 Hidden element (display:none):",e)}):m(`[hide] ❌ No elements found for selector: "${e}"`)}});!function(){if("undefined"!=typeof window){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",y):y(),window.__ulib_signature__=!0;f(`✅ uxlib initialized Version: ${"1.0.4"}`)}}();const W={...w,...T,...g,...D,...I,...j,...O,...z,...S,...H,...q};if("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. Using 'uxlib'")}window.uxlib=W,window[e]=W;for(const[e,t]of Object.entries(W))if("function"==typeof t){const n=`_${e}`;void 0===window[n]&&(window[n]=t)}}e.default=W,Object.defineProperty(e,"__esModule",{value:!0})});