UNPKG

almostnojs

Version:

A minimalist, dependency-free JavaScript framework for DOM manipulation, event handling, animations, state management, and HTTP requests.

4 lines (3 loc) 13 kB
/* AlmostNo.js v1.1.3 Full */ (()=>{var B=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>{for(var n in e)B(t,n,{get:e[n],enumerable:!0})};var O,i,l=b(()=>{O=typeof window<"u"?window:global;if(!O.__AnJS__){class t extends Array{constructor(n){super(),n&&(n instanceof HTMLElement||n.nodeType===1?this.push(n):n instanceof NodeList||Array.isArray(n)?this.push(...n):typeof n=="string"&&this.push(...document.querySelectorAll(n)))}each(n){return this.forEach(n),this}get(n){return n===void 0?this:this.at(n)}clone(n=!0){return this[0]?this[0].cloneNode(n):null}}O.__AnJS__=t}i=O.__AnJS__});var nt={};var x=b(()=>{l();Object.assign(i.prototype,{filter(t){return typeof t=="function"?new i([...this].filter(t)):new i([...this].filter(e=>e.matches(t)))},find(t){return new i(this.flatMap(e=>[...e.querySelectorAll(t)]))},first(){return new i(this.length?[this[0]]:[])},last(){return new i(this.length?[this[this.length-1]]:[])},even(){return new i(this.filter((t,e)=>!(e%2)))},odd(){return new i(this.filter((t,e)=>e%2))}})});var rt={};var F=b(()=>{l();Object.assign(i.prototype,{next(){return new i(this[0]?.nextElementSibling?[this[0].nextElementSibling]:[])},prev(){return new i(this[0]?.previousElementSibling?[this[0].previousElementSibling]:[])},parent(){return new i(this[0]?.parentElement?[this[0].parentElement]:[])},children(){return new i(this[0]?[...this[0].children]:[])},siblings(){let t=this[0]?.parentElement;return new i(t?[...t.children].filter(e=>e!==this[0]):[])},closest(t){return new i(this[0]?.closest(t)?[this[0].closest(t)]:[])}})});var M={};L(M,{bindings:()=>p,localBindings:()=>E});function ot(t,e,n){return new Proxy(e,{get:(r,o)=>r[o],set:(r,o,s)=>(r[o]=s,n&&(n==="session"?sessionStorage:localStorage).setItem(t,JSON.stringify(r)),!0)})}var p,E,c,w,U,J=b(()=>{l();p={},E=new Map,c=typeof window<"u"&&(window.__AnJS_GLOBAL_STATES__||(window.__AnJS_GLOBAL_STATES__={}))||{},w={},U=new Set(["disabled","checked","selected","readonly","multiple","hidden","autoplay","controls","loop","muted"]);i.prototype.global=function(t,e,n={}){if(!t||typeof t!="string")throw new Error("Global state must have a unique name.");if(!c[t]&&e===void 0)throw new Error(`Global state "${t}" does not exist. Provide an initial state.`);if(n.persist){let o=(n.persist==="session"?sessionStorage:localStorage).getItem(t);o&&(e=JSON.parse(o))}return!c[t]&&e!==void 0&&(c[t]=$.state(ot(t,e,n.persist))),c[t]};i.prototype.clearGlobal=function(t){c[t]&&(delete c[t],localStorage.removeItem(t),sessionStorage.removeItem(t))};i.prototype.hasGlobal=function(t){return!!c[t]};i.prototype.state=function(t={},e={}){var r;if(e.global){if(!e.name)throw new Error("Global state must have a name.");t=c[r=e.name]??(c[r]=t)}let n=new Proxy(t,{get:(o,s)=>o[s],set:(o,s,a)=>(o[s]=a,Object.keys(p).forEach(u=>{let[f,...y]=u.split(".");if(!p[u])return;let _=y.reduce((A,m)=>A?.[m],c[f]);p[u].forEach(A=>A.textContent=_??"")}),p[s]?.forEach(u=>u.textContent=a??""),E.get(n)?.[s]?.forEach(u=>u.textContent=a??""),w[s]?.forEach(({el:u,attr:f})=>{a==null?u.removeAttribute(f):U.has(f.toLowerCase())?u.toggleAttribute(f,!!a):u.setAttribute(f,a)}),!0)});return E.set(n,{}),this.bind(n),n};i.prototype.bind=function(t,e=document){e.querySelectorAll("[data-bind], [data-bind-this], [data-bind-attr]").forEach(n=>{var u;if(n.dataset.bound)return;n.dataset.bound="true";let[r,o]=n.getAttribute("data-bind-attr")?.split(":")||[null,n.getAttribute("data-bind")||n.getAttribute("data-bind-this")],s=o?.split("."),a=s?.length>1?s.slice(1).reduce((f,y)=>f?.[y],c[s[0]]??t):t[o]??c[o];n.hasAttribute("data-bind")?((p[o]||(p[o]=[])).push(n),n.textContent=a??""):n.hasAttribute("data-bind-this")?(((u=E.get(t))[o]||(u[o]=[])).push(n),n.textContent=a??""):((w[o]||(w[o]=[])).push({el:n,attr:r}),U.has(r.toLowerCase())?n.toggleAttribute(r,!!a):n.setAttribute(r,a??""),r==="value"&&["INPUT","TEXTAREA"].includes(n.tagName)&&n.addEventListener("input",()=>t[o]=n.value))}),this.autoEvents(t,e)};i.prototype.autoEvents=function(t,e=document){e.querySelectorAll("[data-on]").forEach(n=>{var s;let[r,o]=n.getAttribute("data-on")?.split(":");if(!n.dataset.boundEvent&&typeof t[o]=="function"){n.dataset.boundEvent="true";let a=u=>t[o]?.(u,t);n.addEventListener(r,a),E.has(t)||E.set(t,{}),((s=E.get(t))[r]||(s[r]=[])).push({el:n,event:r,handler:a})}}),e.querySelectorAll("[data-action]").forEach(n=>{let r=n.dataset.action;n.dataset.boundAction||(n.dataset.boundAction="true",n.addEventListener("click",o=>{if(typeof t[r]=="function")return t[r](o,t);let[s,a]=(r||"").split(".");typeof c[s]?.[a]=="function"&&c[s][a](o,c[s])}))})};i.prototype.unbind=function(t){Object.values(E.get(t)).forEach(e=>e.forEach(({el:n,event:r,handler:o})=>n.removeEventListener(r,o))),[p,w].forEach(e=>Object.keys(t).forEach(n=>delete e[n])),E.delete(t)}});var v={};L(v,{default:()=>it,startObserver:()=>P});function P(){document.readyState!=="loading"?S.observer():document.addEventListener("DOMContentLoaded",()=>S.observer())}var S,it,I=b(()=>{l();S={registry:{},observer(){new MutationObserver(t=>{t.forEach(({addedNodes:e})=>{e.forEach(n=>{n.nodeType===Node.ELEMENT_NODE&&this.registry[n.tagName.toLowerCase()]&&this.mount(n,n.tagName.toLowerCase())})})}).observe(document.body,{childList:!0,subtree:!0})},register(t,e,n,r){if(!n&&!r)return;let o=()=>$.state({}),s=()=>{};if(typeof n=="function")try{o=typeof n()=="object"?n:o}catch{s=n}typeof r=="function"&&(s=r),this.registry[t.toLowerCase()]={template:e,state:o,handlers:s},document.querySelectorAll(t.toLowerCase()).forEach(a=>this.mount(a,t))},mount(t,e){let{template:n,state:r,handlers:o}=this.registry[e.toLowerCase()];if(t.dataset.__mounted)return;t.dataset.__mounted="true";let s=Object.fromEntries([...t.attributes].map(f=>[f.name,f.value])),a=i.prototype.state({...r(),...s}),u=this.render(n({state:a,props:s}),a);t.replaceWith(u),$(u).bind(a),u.querySelectorAll(Object.keys(this.registry).join(",")).forEach(f=>this.mount(f,f.tagName.toLowerCase())),this.bind(u,o,a)},render(t,e={}){let n=document.createElement("div");n.innerHTML=t.trim();let r=n.firstElementChild||null;return r?(e&&$(r).bind(e),r):null},bind(t,e,n){if(typeof e=="function")return e($(t),n);Object.entries(e).forEach(([r,o])=>{$(t).on(r,"[data-action]",s=>{let a=s.target.dataset.action;o[a]&&(o[a](n,s),$(t).bind(n))})})}};i.prototype.component=function(t,e,n,r){S.register(t,e,n,r)};i.prototype.render=S.render;P();it=S});var G={};L(G,{default:()=>ft,http:()=>H,request:()=>g});function st(t={},e){let n={Accept:"application/json",...t};return e&&!n["Content-Type"]&&(n["Content-Type"]="application/json"),n}function at(t,e){return t instanceof FormData?(delete e["Content-Type"],t):e["Content-Type"]==="application/x-www-form-urlencoded"?new URLSearchParams(t).toString():JSON.stringify(t)}function ut(t,e,n){return e===0||e==null?t:Promise.race([t,new Promise((r,o)=>setTimeout(()=>o(new Error(`Request timed out: ${n}`)),e))])}function g(t,e="GET",n=null,r={}){let{timeout:o=5e3,signal:s}=r,a=new URL(t,window.location.origin),u=n&&!["GET","DELETE"].includes(e),f=st(r.headers,u),y=u?at(n,f):void 0,_={method:e,headers:f,...y&&{body:y},...s&&{signal:s}},A=fetch(a.toString(),_).then(m=>{if(!m.ok)throw new Error(`HTTP ${m.status} at ${t}`);return(m.headers?.get("Content-Type")||"").includes("application/json")?m.json():m.text()});return ut(A,o,t)}var H,ft,k=b(()=>{l();i.prototype.request=function(t,e="GET",n=null,r={}){return g(t,e,n,r)};H={head:(t,e={})=>g(t,"HEAD",null,e),get:(t,e={})=>g(t,"GET",null,e),options:(t,e={})=>g(t,"OPTIONS",null,e),post:(t,e,n={})=>g(t,"POST",e,n),put:(t,e,n={})=>g(t,"PUT",e,n),patch:(t,e,n={})=>g(t,"PATCH",e,n),delete:(t,e={})=>g(t,"DELETE",null,e),abortController:()=>new AbortController},ft=H});var ct={};var D=b(()=>{l();Object.assign(i.prototype,{animate(t,e=400,n="ease"){return this.each(r=>{r.style.transition=`all ${e}ms ${n}`,Object.assign(r.style,t),e>0&&setTimeout(()=>r.style.transition="",e)})},fade(t=+(this[0]?.style.opacity==="0"),e=400){return this.animate({opacity:t},e)},fadeIn(t){return this.fade(1,t)},fadeOut(t){return this.fade(0,t)}})});l();l();Object.assign(i.prototype,{content(t,e=!1){return t===void 0?this[0]?e?this[0].innerHTML:this[0].textContent:"":this.each(n=>e?n.innerHTML=t:n.textContent=t)},text(t){return this.content(t,!1)},html(t){return this.content(t,!0)},css(t,e){return e===void 0?this[0]?.style.getPropertyValue(t)||"":this.each(n=>n.style[t]=e)},class(t,e){return this.each(n=>n.classList[e===void 0?"toggle":e?"add":"remove"](t))},display(t){return this.each(e=>e.style.display=t?"":"none")},hide(){return this.display(!1)},show(){return this.display(!0)},remove(){return this.each(t=>t.remove())},empty(){return this.each(t=>t.innerHTML="")},insert(t,e="before"){let n={before:"beforeBegin",prepend:"afterBegin",append:"beforeEnd",after:"afterEnd"};return n[e]?this.each(r=>{if(typeof t=="string")return r.insertAdjacentHTML(n[e],t);(Array.isArray(t)?t:[t]).forEach(o=>r.insertAdjacentElement(n[e],o.cloneNode(!0)))}):this},prop(t,e){return arguments.length===1?this[0]?.[t]:this.each(n=>n[t]=e)},val(t){return arguments.length===0?this[0]?.value:this.each(e=>e.value=t)},has(t){return this[0]?.classList.contains(t)??!1},focus(){return this[0]?.focus(),this},blur(){return this[0]?.blur(),this}});l();Object.assign(i.prototype,{attr(t,e){return e===void 0?this[0]?.getAttribute(t):e===null?this.each(n=>n.removeAttribute(t)):this.each(n=>n.setAttribute(t,e))},id(t){return t===void 0?this.attr("id"):this.attr("id",t)},removeAttr(t){return this.attr(t,null)},serialize(){return this[0]instanceof HTMLFormElement?new URLSearchParams(new FormData(this[0])).toString():""}});l();var T=new WeakMap;Object.assign(i.prototype,{on(t,e,n){return typeof e=="function"?this.delegate(t,null,e):this.delegate(t,e,n)},off(t,e,n){return typeof e=="function"?this.undelegate(t,null,e):this.undelegate(t,e,n)},delegate(t,e,n){return this.each(r=>{T.has(r)||T.set(r,{});let o=T.get(r);o[t]||(o[t]=[]);let s=a=>{let u=e?a.target.closest(e):r;u&&r.contains(u)&&n.call(u,a)};o[t].push({selector:e,handler:n,delegateHandler:s}),r.addEventListener(t,s)})},undelegate(t,e,n){return this.each(r=>{if(!T.has(r))return;let o=T.get(r);o[t]&&(n?(o[t]=o[t].filter(s=>s.selector===e&&s.handler===n?(r.removeEventListener(t,s.delegateHandler),!1):!0),o[t].length===0&&delete o[t]):(o[t].forEach(s=>r.removeEventListener(t,s.delegateHandler)),delete o[t]),Object.keys(o).length===0&&T.delete(r))})},trigger(t){return this.each(e=>e.dispatchEvent(new Event(t,{bubbles:!0})))}});var d={},N={emit(t,e){d[t]?.forEach(n=>n(e))},listen(t,e){d[t]||(d[t]=[]),d[t].push(e)},forget(t,e){d[t]&&(d[t]=d[t].filter(n=>n!==e),d[t].length===0&&delete d[t])}};l();["append","prepend","before","after"].forEach(t=>i.prototype[t]=function(e){return this.insert(e,t)});["click","change","submit","keydown","keyup","mouseover","mouseout"].forEach(t=>{i.prototype[t]=function(e){return e?this.on(t,e):this.trigger(t)}});var V=t=>t.trim(),q=t=>{try{return JSON.parse(t)}catch{return null}},W=(t,e,n)=>(t-e)*(t-n)<=0,z=t=>typeof t=="function",X=t=>t!==null&&typeof t=="object",Q=t=>typeof t=="string",Y=t=>typeof t=="number"&&!isNaN(t),Z=(t,e)=>t!==e&&t.contains(e),K=(t,e)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>t(...r),e)}},tt=(t,e)=>{let n=0;return(...r)=>{let o=Date.now();o-n>=e&&(n=o,t(...r))}},et=(t,e={},n=[])=>{let r=document.createElement(t);return Object.entries(e).forEach(([o,s])=>r.setAttribute(o,s)),n.forEach(o=>r.append(o instanceof Node?o:document.createTextNode(o))),r},R={trim:V,json:q,range:W,isFunction:z,isObject:X,isString:Q,isNumber:Y,contains:Z,debounce:K,throttle:tt,element:et};l();var j=function(t,e,n=!1){if(typeof t=="object")return typeof e=="boolean"&&(n=e),Object.keys(t).forEach(r=>j(r,t[r],n));!n&&i.prototype.hasOwnProperty(t)||(i.prototype[t]=e)},C={extend:j};typeof FEATURE_HTTP>"u"&&(globalThis.FEATURE_HTTP=!0);typeof FEATURE_ANIMATE>"u"&&(globalThis.FEATURE_ANIMATE=!0);typeof FEATURE_SELECTION>"u"&&(globalThis.FEATURE_SELECTION=!0);typeof FEATURE_FILTERING>"u"&&(globalThis.FEATURE_FILTERING=!0);typeof FEATURE_TRAVERSAL>"u"&&(globalThis.FEATURE_TRAVERSAL=!0);function h(t){return new i(t)}["on","off","trigger"].forEach(t=>{h[t]=(...e)=>i.prototype[t].apply(h(),e)});FEATURE_SELECTION&&(Promise.resolve().then(()=>(x(),nt)).then(t=>Object.assign(h,t)),Promise.resolve().then(()=>(F(),rt)).then(t=>Object.assign(h,t)));Promise.resolve().then(()=>(J(),M)).then(()=>{["state","global"].forEach(t=>{h[t]=(...e)=>i.prototype[t].apply(h(),e)})});Promise.resolve().then(()=>(I(),v)).then(t=>{["component"].forEach(e=>{h[e]=(...n)=>i.prototype[e].apply(h(),n)}),h.define=(e,n)=>customElements.define(e,n)});FEATURE_HTTP&&Promise.resolve().then(()=>(k(),G)).then(t=>{Object.assign(h,t.http)});FEATURE_ANIMATE&&Promise.resolve().then(()=>(D(),ct));Object.assign(h,N,R,C);h.define=(t,e)=>customElements.define(t,e);typeof window<"u"&&(window.$=h);var Pt=h;})(); window.$ = $;