UNPKG

@extralam/microui

Version:

A lightweight, modern JavaScript utility library that makes DOM manipulation and event handling simple and efficient.

3 lines (2 loc) 18.6 kB
/*! MicroUI v1.0.3 | MIT License | https://github.com/lam0819/microui */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).MicroUI=t()}(this,function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,l(r.key),r)}}function r(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function o(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return s}}(e,t)||f(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||f(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}function f(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var d=new Map;function h(e){if(d.has(e)){var t=d.get(e);if(document.contains(t))return t;d.delete(e)}var n=document.querySelector(e);return n&&d.set(e,n),n}var v=new Map;function y(e,t,n){e.split(" ").forEach(function(e){var r="".concat(e,":").concat(t);v.has(r)||(v.set(r,new Set),document.addEventListener(e,function(e){var n=e.target.closest(t);if(n){var o=v.get(r);o&&o.forEach(function(t){return t.call(n,e)})}})),v.get(r).add(n)})}function p(e,t,n){e.split(" ").forEach(function(e){var r="".concat(e,":").concat(t),o=v.get(r);o&&(n?o.delete(n):o.clear(),0===o.size&&v.delete(r))})}var m={method:"GET",headers:{"Content-Type":"application/json"},timeout:5e3};function g(e){var t=a(a({},m),e);return new Promise(function(e,n){var r=new XMLHttpRequest,o=!1,i=setTimeout(function(){o=!0,r.abort(),n(new Error("Request timeout"))},t.timeout);if(r.open(t.method,t.url),t.headers&&Object.entries(t.headers).forEach(function(e){var t=s(e,2),n=t[0],o=t[1];r.setRequestHeader(n,o)}),r.onload=function(){if(clearTimeout(i),r.status>=200&&r.status<300)try{var t=r.getResponseHeader("Content-Type"),o=r.responseText;t&&t.includes("application/json")&&(o=JSON.parse(r.responseText)),e(o)}catch(e){n(new Error("Invalid JSON response"))}else n(new Error("HTTP ".concat(r.status,": ").concat(r.statusText)))},r.onerror=function(){clearTimeout(i),n(new Error("Network error"))},r.onabort=function(){clearTimeout(i),o||n(new Error("Request aborted"))},t.data)if("GET"===t.method){var a=new URLSearchParams(t.data).toString();r.open(t.method,"".concat(t.url,"?").concat(a)),r.send()}else{var c="string"==typeof t.data?t.data:JSON.stringify(t.data);r.send(c)}else r.send()})}function b(e){return g(a(a({},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),{},{method:"GET",url:e}))}function w(e){return e&&"object"===u(e)&&!Array.isArray(e)}var S={set:function(e,t){try{var n=JSON.stringify(t);localStorage.setItem(e,n)}catch(e){console.warn("Failed to save to localStorage:",e)}},get:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;try{var n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(e){return console.warn("Failed to retrieve from localStorage:",e),t}},remove:function(e){try{localStorage.removeItem(e)}catch(e){console.warn("Failed to remove from localStorage:",e)}},clear:function(){try{localStorage.clear()}catch(e){console.warn("Failed to clear localStorage:",e)}},keys:function(){try{return Object.keys(localStorage)}catch(e){return console.warn("Failed to get localStorage keys:",e),[]}}},E={set:function(e,t){try{var n=JSON.stringify(t);sessionStorage.setItem(e,n)}catch(e){console.warn("Failed to save to sessionStorage:",e)}},get:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;try{var n=sessionStorage.getItem(e);return n?JSON.parse(n):t}catch(e){return console.warn("Failed to retrieve from sessionStorage:",e),t}},remove:function(e){try{sessionStorage.removeItem(e)}catch(e){console.warn("Failed to remove from sessionStorage:",e)}},clear:function(){try{sessionStorage.clear()}catch(e){console.warn("Failed to clear sessionStorage:",e)}},keys:function(){try{return Object.keys(sessionStorage)}catch(e){return console.warn("Failed to get sessionStorage keys:",e),[]}}},O=function(){return r(function e(n,r){var o=this;t(this,e),this.name=n,this.template=r.template||"",this.props=r.props||{},this.state=a({},r.state)||{},this.methods=r.methods||{},this.events=r.events||{},this.lifecycle=r.lifecycle||{},this.element=null,this.mounted=!1,Object.keys(this.methods).forEach(function(e){o.methods[e]=o.methods[e].bind(o)})},[{key:"render",value:function(){var e=this.template,t=a(a({},this.props),this.state);return Object.keys(t).forEach(function(n){var r=new RegExp("{{".concat(n,"}}"),"g");e=e.replace(r,t[n])}),e}},{key:"update",value:function(){var e=this;if(this.element){this._eventHandlers&&(this._eventHandlers.forEach(function(t){var n=t.eventType,r=t.handler;e.element.removeEventListener(n,r,!0)}),this._eventHandlers=[]);var t=this.render();this.element.innerHTML=t,this.bindEvents()}}},{key:"bindEvents",value:function(){var e=this;this.element&&Object.keys(this.events).forEach(function(t){var n=t.trim().split(/\s+/),r=n[0],o=n.slice(1).join(" "),i=e.events[t],a=e.methods[i];if(a&&o&&r){var s=function(t){var n=t.target.closest(o);n&&e.element.contains(n)&&a.call(e,t)};e._eventHandlers=e._eventHandlers||[],e._eventHandlers.push({eventType:r,handler:s}),e.element.addEventListener(r,s,!0)}})}},{key:"mount",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.props=a(a({},this.props),t),this.lifecycle.created&&this.lifecycle.created.call(this);var n=document.createElement("div");return n.innerHTML=this.render(),this.element=n.firstElementChild,"string"==typeof e&&(e=document.querySelector(e)),e.appendChild(this.element),this.bindEvents(),this.mounted=!0,this.lifecycle.mounted&&this.lifecycle.mounted.call(this),this}},{key:"unmount",value:function(){var e=this;this.lifecycle.beforeDestroy&&this.lifecycle.beforeDestroy.call(this),this._eventHandlers&&this.element&&(this._eventHandlers.forEach(function(t){var n=t.eventType,r=t.handler;e.element.removeEventListener(n,r,!0)}),this._eventHandlers=[]),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.mounted=!1,this.lifecycle.destroyed&&this.lifecycle.destroyed.call(this)}},{key:"setState",value:function(e){this.state=a(a({},this.state),e),this.update()}},{key:"setProps",value:function(e){this.props=a(a({},this.props),e),this.update()}}])}(),j=new Map;var T=function(){return r(function e(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;t(this,e),this.name=n,this.container=r,this.handlers=new Map,this.active=!0},[{key:"on",value:function(e,t,n){var r="".concat(e,":").concat(t);return this.handlers.has(r)||this.handlers.set(r,new Set),this.handlers.get(r).add(n),1===this.handlers.get(r).size&&this.attachListener(e,t),this}},{key:"off",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r="".concat(e,":").concat(t);return this.handlers.has(r)?(n?(this.handlers.get(r).delete(n),0===this.handlers.get(r).size&&(this.detachListener(e,t),this.handlers.delete(r))):(this.detachListener(e,t),this.handlers.delete(r)),this):this}},{key:"once",value:function(e,t,n){var r=this,o=function(i){n.call(i.target,i),r.off(e,t,o)};return this.on(e,t,o)}},{key:"trigger",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.container.querySelectorAll(e).forEach(function(e){var r=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0});e.dispatchEvent(r)}),this}},{key:"attachListener",value:function(e,t){var n=this,r="".concat(e,":").concat(t),o=function(e){if(n.active){var o=e.target.closest(t);if(o&&n.container.contains(o)){var i=n.handlers.get(r);i&&i.forEach(function(t){try{t.call(o,e)}catch(e){setTimeout(function(){throw new Error("Delegation handler error in ".concat(n.name,": ").concat(e.message))},0)}})}}};this._actualHandlers=this._actualHandlers||new Map,this._actualHandlers.set(r,o),this.container.addEventListener(e,o,!0)}},{key:"detachListener",value:function(e,t){var n="".concat(e,":").concat(t);if(this._actualHandlers&&this._actualHandlers.has(n)){var r=this._actualHandlers.get(n);this.container.removeEventListener(e,r,!0),this._actualHandlers.delete(n)}}},{key:"pause",value:function(){return this.active=!1,this}},{key:"resume",value:function(){return this.active=!0,this}},{key:"isActive",value:function(){return this.active}},{key:"getHandlers",value:function(){var e={};return this.handlers.forEach(function(t,n){e[n]=Array.from(t)}),e}},{key:"destroy",value:function(){var e=this;this.handlers.forEach(function(t,n){var r=s(n.split(":"),2),o=r[0],i=r[1];e.detachListener(o,i)}),this.handlers.clear(),this._actualHandlers&&this._actualHandlers.clear(),this.active=!1,k.has(this.name)&&k.delete(this.name)}}])}(),k=new Map;function H(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document;return k.has(e)?t=k.get(e):(t=new T(e,r),k.set(e,t)),Object.keys(n).forEach(function(e){var r=s(e.split(" "),2),o=r[0],i=r[1],a=n[e];o&&i&&"function"==typeof a&&t.on(o,i,a)}),t}function L(e){var t=k.get(e);return t&&t.destroy(),!k.has(e)}var A={$:h,$$:function(e){return document.querySelectorAll(e)},addClass:function(e,t){var n,r="string"==typeof e?h(e):e;if(r){var o=t.split(" ").filter(function(e){return e.trim()});(n=r.classList).add.apply(n,c(o))}},removeClass:function(e,t){var n,r="string"==typeof e?h(e):e;if(r){var o=t.split(" ").filter(function(e){return e.trim()});(n=r.classList).remove.apply(n,c(o))}},toggleClass:function(e,t,n){var r="string"==typeof e?h(e):e;if(r)return r.classList.toggle(t,n)},hasClass:function(e,t){var n="string"==typeof e?h(e):e;return!!n&&n.classList.contains(t)},attr:function(e,t,n){var r="string"==typeof e?h(e):e;if(r)return void 0===n?r.getAttribute(t):void(null===n?r.removeAttribute(t):r.setAttribute(t,n))},data:function(e,t,n){var r="string"==typeof e?h(e):e;if(r){if(void 0===n){var o=r.dataset[t];try{return JSON.parse(o)}catch(e){return o}}r.dataset[t]="object"===u(n)?JSON.stringify(n):n}},html:function(e,t){var n="string"==typeof e?h(e):e;n&&(n.innerHTML=t)},append:function(e,t){var n="string"==typeof e?h(e):e;n&&n.insertAdjacentHTML("beforeend",t)},prepend:function(e,t){var n="string"==typeof e?h(e):e;n&&n.insertAdjacentHTML("afterbegin",t)},remove:function(e){var t="string"==typeof e?h(e):e;t&&t.remove()},closest:function(e,t){return e.closest(t)},on:y,off:p,once:function(e,t,n){var r=function(o){n.call(this,o),p(e,t,r)};y(e,t,r)},trigger:function(e,t,n){var r="string"==typeof e?document.querySelector(e):e;if(r){var o=new CustomEvent(t,{detail:n,bubbles:!0,cancelable:!0});r.dispatchEvent(o)}},ready:function(e){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()},ajax:g,get:b,post:function(e,t){return g(a(a({},arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}),{},{method:"POST",url:e,data:t}))},put:function(e,t){return g(a(a({},arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}),{},{method:"PUT",url:e,data:t}))},delete:function(e){return g(a(a({},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),{},{method:"DELETE",url:e}))},load:function(e,t){return b(t).then(function(t){var n="string"==typeof e?document.querySelector(e):e;return n&&(n.innerHTML=t),t})},fadeIn:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:300,n=arguments.length>2?arguments[2]:void 0,r="string"==typeof e?document.querySelector(e):e;if(r){r.style.display="none"===r.style.display?"":r.style.display;var o=r.animate([{opacity:0},{opacity:1}],{duration:t,easing:"ease-in-out",fill:"forwards"});return n&&o.addEventListener("finish",n),o}},fadeOut:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:300,n=arguments.length>2?arguments[2]:void 0,r="string"==typeof e?document.querySelector(e):e;if(r){var o=r.animate([{opacity:1},{opacity:0}],{duration:t,easing:"ease-in-out",fill:"forwards"});return o.addEventListener("finish",function(){r.style.display="none",n&&n()}),o}},slideDown:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:400,n=arguments.length>2?arguments[2]:void 0,r="string"==typeof e?document.querySelector(e):e;if(r){var o=r.offsetHeight;r.style.overflow="hidden",r.style.display="none"===r.style.display?"block":r.style.display;var i=r.scrollHeight,a=r.animate([{height:"".concat(o,"px")},{height:"".concat(i,"px")}],{duration:t,easing:"ease-in-out",fill:"forwards"});return a.addEventListener("finish",function(){r.style.height="",r.style.overflow="",n&&n()}),a}},slideUp:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:400,n=arguments.length>2?arguments[2]:void 0,r="string"==typeof e?document.querySelector(e):e;if(r){var o=r.offsetHeight;r.style.overflow="hidden";var i=r.animate([{height:"".concat(o,"px")},{height:"0px"}],{duration:t,easing:"ease-in-out",fill:"forwards"});return i.addEventListener("finish",function(){r.style.display="none",r.style.height="",r.style.overflow="",n&&n()}),i}},animate:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r="string"==typeof e?document.querySelector(e):e;if(r){var o=a(a({},{duration:1e3,easing:"ease",fill:"both"}),n);return r.animate(t,o)}},store:S,session:E,component:function(e,t){return j.set(e,t),t},mount:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=j.get(t);if(!r)throw new Error('Component "'.concat(t,'" not found'));return new O(t,r).mount(e,n)},create:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=j.get(e);if(!n)throw new Error('Component "'.concat(e,'" not found'));var r=new O(e,n);return r.props=a(a({},r.props),t),r},getComponent:function(e){return j.get(e)},listComponents:function(){return Array.from(j.keys())},delegate:H,getNamespace:function(e){return k.get(e)},destroyNamespace:L,listNamespaces:function(){return Array.from(k.keys())},pauseAll:function(){k.forEach(function(e){return e.pause()})},resumeAll:function(){k.forEach(function(e){return e.resume()})},destroyAll:function(){Array.from(k.keys()).forEach(function(e){return L(e)}),k.clear()},scope:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"scope_".concat(Date.now());if("string"==typeof e&&(e=document.querySelector(e)),!e)throw new Error("Container element not found");return H(t,{},e)},advanced:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.container,r=void 0===n?document:n,o=t.middleware,i=void 0===o?[]:o,a=t.errorHandler,s=void 0===a?null:a,c=H(e,{},r),l=c.on;return c.on=function(e,t,n){var r=this;return l.call(this,e,t,function(e){var t=0,o=function(){if(t<i.length){var a=i[t++];try{a(e,o)}catch(t){s?s(t,e):setTimeout(function(){throw new Error("Middleware error: ".concat(t.message))},0)}}else try{n.call(r,e)}catch(t){s?s(t,e):setTimeout(function(){throw new Error("Handler error: ".concat(t.message))},0)}};o()})},c},debounce:function(e,t){var n;return function(){for(var r=this,o=arguments.length,i=new Array(o),a=0;a<o;a++)i[a]=arguments[a];clearTimeout(n),n=setTimeout(function(){clearTimeout(n),e.apply(r,i)},t)}},throttle:function(e,t){var n;return function(){if(!n){for(var r=arguments.length,o=new Array(r),i=0;i<r;i++)o[i]=arguments[i];e.apply(this,o),n=!0,setTimeout(function(){return n=!1},t)}}},extend:function e(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];if(!r.length)return t;var a=r.shift();if(w(t)&&w(a))for(var s in a)w(a[s])?(t[s]||Object.assign(t,o({},s,{})),e(t[s],a[s])):Object.assign(t,o({},s,a[s]));return e.apply(void 0,[t].concat(r))},uniqueId:function(){return"".concat(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"id","_").concat(Math.random().toString(36).substr(2,9))},isVisible:function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},offset:function(e){var t=e.getBoundingClientRect();return{top:t.top+window.pageYOffset,left:t.left+window.pageXOffset}},version:"1.0.3"};return"undefined"!=typeof window&&(window.MicroUI=A),A});