@je-es/client 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,63 +1,70 @@
1
- import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMElement,createElement,html,patch}from'@je-es/vdom';import {configureApi,api}from'@je-es/capi';export{api,configureApi,getApiConfig,http,resetApiConfig}from'@je-es/capi';var lt=Object.defineProperty;var T=(o,t,e,r)=>{for(var n=void 0,s=o.length-1,a;s>=0;s--)(a=o[s])&&(n=(a(t,e,n))||n);return n&&lt(t,e,n),n};var C=class{static{this.styles=new Map;}static{this.scopeCounter=0;}static inject(t,e){let r=e||`style-${this.scopeCounter++}`;if(this.styles.has(r))return r;let n=document.createElement("style");n.setAttribute("data-component",r);let s=this.scopeStyles(t,r);return n.textContent=s,document.head.appendChild(n),this.styles.set(r,n),r}static remove(t){let e=this.styles.get(t);e&&e.parentElement&&(e.parentElement.removeChild(e),this.styles.delete(t));}static scopeStyles(t,e){let r=t.split(`
2
- `),n=[],a=0;for(let i of r){if(i=i.trim(),i.startsWith("@media")){n.push(i);continue}if(a+=(i.match(/{/g)||[]).length,a-=(i.match(/}/g)||[]).length,i.includes("{")&&!i.startsWith("@")&&!i.startsWith("}")){let u=i.substring(0,i.indexOf("{")).trim(),c=i.substring(i.indexOf("{"));if(u===":root"||u==="*"||i.startsWith("@"))n.push(i);else {let d=`[data-scope="${e}"] ${u}`;n.push(`${d} ${c}`);}}else n.push(i);}return n.join(`
3
- `)}static clear(){for(let[,t]of this.styles)t.parentElement&&t.parentElement.removeChild(t);this.styles.clear();}};function L(o,...t){let e="";for(let r=0;r<o.length;r++)e+=o[r],r<t.length&&(e+=t[r]);return e}var A=class{constructor(){this.queue=new Set;this.isFlushScheduled=false;this.isFlushing=false;}schedule(t){if(this.isFlushing){requestAnimationFrame(()=>this.schedule(t));return}this.queue.add(t),this.isFlushScheduled||(this.isFlushScheduled=true,Promise.resolve().then(()=>{requestAnimationFrame(()=>this.flush());}));}flushSync(t){t();}flush(){if(this.queue.size===0){this.isFlushScheduled=false;return}this.isFlushing=true,this.isFlushScheduled=false;let t=Array.from(this.queue);this.queue.clear();for(let e of t)try{e();}catch(r){console.error("Error during update:",r);}this.isFlushing=false,this.queue.size>0&&this.schedule(()=>{});}clear(){this.queue.clear(),this.isFlushScheduled=false;}get size(){return this.queue.size}},k=new A;var m=class{constructor(t,e){this._isMounted=false;this._isUnmounting=false;this._element=null;this._vnode=null;this._styleId=null;this._isScheduledForUpdate=false;this._updateBatch=new Set;this._refs=new Map;this._subscriptions=[];this._memoCache=new Map;this.props=t||{},this.state=e||{};}setState(t,e){let r={...this.state},n=typeof t=="function"?t(this.state):t;this.state={...this.state,...n},this.onStateChange?.(r,this.state),this.update(),e&&k.schedule(e);}setProps(t){let e={...this.props};this.props={...this.props,...t},this.onPropsChange?.(e,this.props),this.update();}batchUpdate(t){let e=this._isScheduledForUpdate;this._isScheduledForUpdate=true;try{t();}finally{e||(this._isScheduledForUpdate=false,this.update());}}update(t){!this._isMounted||this._isUnmounting||(t&&this._updateBatch.add(t),!this._isScheduledForUpdate&&(this._isScheduledForUpdate=true,k.schedule(()=>{this._isScheduledForUpdate=false,this._updateBatch.clear(),this._performUpdate();})));}forceUpdate(){!this._isMounted||this._isUnmounting||k.flushSync(()=>{this._performUpdate();});}async mount(t){if(this._isMounted){console.warn("Component is already mounted");return}try{await this.onBeforeMount?.(),this._vnode=this.render(),this._element=this._createElementFromVNode(this._vnode),this.styles&&(this._styleId=C.inject(this.styles(),this.constructor.name),this._element?.setAttribute("data-scope",this.constructor.name)),t.appendChild(this._element),this._isMounted=!0,await this.onMount?.();}catch(e){this._handleError(e,{componentStack:this.constructor.name});}}unmount(){if(!(!this._isMounted||this._isUnmounting)){this._isUnmounting=true;try{this.onBeforeUnmount?.(),this._isScheduledForUpdate=!1,this._updateBatch.clear(),this._styleId&&C.remove(this._styleId),this._subscriptions.forEach(t=>t()),this._subscriptions=[],this._element?.parentElement&&this._element.parentElement.removeChild(this._element),this._isMounted=!1,this._element=null,this._vnode=null,this.onUnmount?.(),this._refs.clear(),this._memoCache.clear();}catch(t){this._handleError(t,{componentStack:this.constructor.name});}finally{this._isUnmounting=false;}}}getRef(t){return this._refs.get(t)}createRef(t){return e=>{e?this._refs.set(t,e):this._refs.delete(t);}}memo(t,e,r){let n=this._memoCache.get(t);if(n&&this._areDepsEqual(n.args,r))return n.result;let s=e();return this._memoCache.set(t,{args:r,result:s}),s}subscribe(t){this._subscriptions.push(t);}debounce(t,e){let r=null;return (...n)=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,t.apply(this,n);},e);}}throttle(t,e){let r=0,n=null;return (...s)=>{let a=Date.now(),i=a-r;i>=e?(r=a,t.apply(this,s)):n||(n=setTimeout(()=>{r=Date.now(),n=null,t.apply(this,s);},e-i));}}get element(){return this._element}get isMounted(){return this._isMounted}get isUnmounting(){return this._isUnmounting}async _performUpdate(){if(!this._isMounted||!this._element||this._isUnmounting)return;let t={...this.props},e={...this.state};try{if(this.shouldUpdate&&!this.shouldUpdate(t,e))return;await this.onBeforeUpdate?.(t,e);let r=this.render(),n=this._element.parentElement;if(this._vnode&&n){let s=Array.from(n.childNodes).indexOf(this._element),a=this._convertToVDomNode(this._vnode),i=this._convertToVDomNode(r);patch(n,a,i,s),this._element=n.childNodes[s];}this._vnode=r,this.onUpdate?.(t,e);}catch(r){this._handleError(r,{componentStack:this.constructor.name});}}_convertToVDomNode(t){if(typeof t.type!="string")throw new Error("Component VNodes cannot be converted to VDom nodes");let e={};for(let[n,s]of Object.entries(t.props))n!=="children"&&(e[n]=s);let r=t.children.map(n=>n==null||typeof n=="boolean"?null:typeof n=="string"||typeof n=="number"?n:this._convertToVDomNode(n)).filter(n=>n!==null);return {type:t.type,props:e,children:r}}_createElementFromVNode(t){if(typeof t.type!="string")throw new Error("Component VNodes not supported in _createElementFromVNode");let e=document.createElement(t.type);for(let[r,n]of Object.entries(t.props))r!=="children"&&this._setElementProperty(e,r,n);for(let r of t.children)r==null||r===false||(typeof r=="string"||typeof r=="number"?e.appendChild(document.createTextNode(String(r))):typeof r=="object"&&"type"in r&&e.appendChild(this._createElementFromVNode(r)));return e}_setElementProperty(t,e,r){if(e.startsWith("on")&&typeof r=="function"){let n=e.substring(2).toLowerCase();t.addEventListener(n,r);return}if(e==="className"&&typeof r=="string"){t.className=r;return}if(e==="style"){typeof r=="string"?t.setAttribute("style",r):typeof r=="object"&&r!==null&&Object.assign(t.style,r);return}if(e==="ref"&&typeof r=="function"){r(t);return}if(e==="checked"||e==="disabled"||e==="selected"){(r==="true"||r===true||r==="")&&t.setAttribute(e,"");return}r!=null&&r!==false&&t.setAttribute(e,String(r));}_handleError(t,e){if(console.error(`Error in component ${this.constructor.name}:`,t),this.onError)this.onError(t,e);else throw t}_areDepsEqual(t,e){return t.length!==e.length?false:t.every((r,n)=>r===e[n])}_invalidateAllComputed(){for(let t in this)t.startsWith("_computed_dirty_")&&(this[t]=true);}_triggerWatchers(t,e,r){let n=this.constructor.__watchers__;if(n?.[t]){for(let s of n[t])if(typeof this[s]=="function")try{this[s].call(this,e,r);}catch(a){console.error(`Watcher error in ${s}:`,a);}}}};var R=class{constructor(){this.routes=[];this.currentRoute=null;this.mode="history";this.base="/";this.beforeEachHooks=[];this.afterEachHooks=[];this.currentComponent=null;this.routerOutlet=null;this.isNavigating=false;this.scrollBehavior="auto";this.notFoundHandler=null;this._internalPath=null;}init(t,e="history",r="/",n="auto"){this.routes=t,this.mode=e,this.base=r.endsWith("/")?r.slice(0,-1):r,this.scrollBehavior=n,this._initializeRouting(),this._handleRoute();}async push(t,e){this.isNavigating||(this._internalPath=t,this.mode==="history"?window.history.pushState(e||{},"",this._buildFullPath(t)):window.location.hash=t,await this._handleRoute());}async replace(t,e){return this._internalPath=t,this.mode==="history"?window.history.replaceState(e||{},"",this._buildFullPath(t)):window.location.hash=t,this._handleRoute()}back(){window.history.back();}forward(){window.history.forward();}go(t){window.history.go(t);}beforeEach(t){this.beforeEachHooks.push(t);}afterEach(t){this.afterEachHooks.push(t);}onNotFound(t){this.notFoundHandler=t;}getCurrentRoute(){return this.currentRoute?{...this.currentRoute}:null}isActive(t,e=false){return this.currentRoute?e?this.currentRoute.path===t:this.currentRoute.path.startsWith(t):false}outlet(){return createElement("div",{"data-router-outlet":"true",style:"display: contents;"})}getRoute(t){return this.routes.find(e=>e.name===t)}async pushNamed(t,e){let r=this.getRoute(t);if(!r){console.error(`Route with name "${t}" not found`);return}let n=r.path;if(e)for(let[s,a]of Object.entries(e))n=n.replace(`:${s}`,a);return this.push(n)}resolve(t){let e=this._matchRoute(t);if(!e)return null;let{route:r,params:n}=e;return {path:t,params:n,query:this._parseQuery(t),meta:r.meta||{},hash:t.includes("#")?t.split("#")[1]:"",name:r.name}}_initializeRouting(){window.addEventListener("popstate",()=>{this._internalPath=null,this._handleRoute();}),this.mode==="hash"&&window.addEventListener("hashchange",()=>{this._internalPath=null,this._handleRoute();}),document.addEventListener("click",t=>{let e=t.target.closest("a[href]");if(e&&this._shouldInterceptLink(e)){t.preventDefault();let r=e.getAttribute("href");if(r){let n=this.mode==="hash"&&r.startsWith("#")?r.substring(1):r.replace(this.base,"");this.push(n);}}});}_shouldInterceptLink(t){return !!(t.getAttribute("href")&&t.hostname===window.location.hostname&&t.target!=="_blank"&&!t.hasAttribute("download")&&t.rel!=="external")}async _handleRoute(){if(!this.isNavigating){this.isNavigating=true;try{let t=this._getCurrentPath(),e=this._matchRoute(t);if(!e){this._handleNotFound(t);return}let{route:r,params:n}=e,s=this._buildRouteObject(t,n,r),a=this.currentRoute||this._buildEmptyRoute();if(!await this._runNavigationGuards(r,s,a))return;this.currentRoute=s,await this._renderComponent(r),this._handleScrollBehavior(s,a),r.meta?.title&&typeof r.meta.title=="string"&&(document.title=r.meta.title),this.afterEachHooks.forEach(u=>u(s,a));}catch(t){console.error("Router error:",t);}finally{this.isNavigating=false;}}}_handleNotFound(t){console.warn(`No route matched for path: ${t}`),this.currentRoute={path:t,params:{},query:this._parseQuery(),meta:{},hash:window.location.hash.substring(1)},this.notFoundHandler&&this.notFoundHandler();}_buildRouteObject(t,e,r){return {path:t,params:e,query:this._parseQuery(),meta:r.meta||{},hash:window.location.hash.substring(1),name:r.name}}_buildEmptyRoute(){return {path:"",params:{},query:{},meta:{},hash:""}}async _runNavigationGuards(t,e,r){if(t.beforeEnter&&!await this._runGuard(t.beforeEnter,e,r))return false;for(let n of this.beforeEachHooks)if(!await this._runGuard(n,e,r))return false;return true}_runGuard(t,e,r){return new Promise(n=>{t(e,r,s=>{s===false?n(false):typeof s=="string"?(this.push(s),n(false)):n(true);});})}async _renderComponent(t){if(!this.routerOutlet&&(this.routerOutlet=document.querySelector('[data-router-outlet="true"]'),!this.routerOutlet)){console.warn("Router outlet not found");return}this.currentComponent&&(this.currentComponent.unmount(),this.currentComponent=null),this.routerOutlet.innerHTML="";try{let e=await this._resolveComponent(t.component);if(!e||typeof e!="function")throw new Error("Component is null or not a constructor");let r=e;this.currentComponent=new r,this.currentComponent&&await this.currentComponent.mount(this.routerOutlet);}catch(e){throw this._renderError(t.path,e),e}}async _resolveComponent(t){if(typeof t=="function"){let r="prototype"in t&&t.prototype?t.prototype:null;if(r&&typeof r=="object"&&"constructor"in r&&r.constructor===t)return t;try{let s=await t();return s.HomePage||s.TodoPage||s.default||Object.values(s).find(i=>{if(typeof i!="function")return !1;let c=i.prototype;return c!==null&&typeof c=="object"&&c!==void 0&&"constructor"in c})||null}catch(s){return console.error("Failed to load lazy component:",s),null}}return null}_renderError(t,e){if(this.routerOutlet){let r=e instanceof Error?e.message:String(e);this.routerOutlet.innerHTML=`
4
- <div style="padding: 2rem; background: #fee; border: 2px solid #c00;
1
+ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';export{createDOMElement,createElement,html,patch}from'@je-es/vdom';import {configureApi,api}from'@je-es/capi';export{api,configureApi,getApiConfig,http,resetApiConfig}from'@je-es/capi';var Ee=Object.defineProperty;var h=(s,t,e,n)=>{for(var r=void 0,i=s.length-1,o;i>=0;i--)(o=s[i])&&(r=(o(t,e,r))||r);return r&&Ee(t,e,r),r};var D=class{static{this.styles=new Map;}static{this.scopeCounter=0;}static inject(t,e){let n=e||`style-${this.scopeCounter++}`;if(this.styles.has(n))return n;let r=document.createElement("style");r.setAttribute("data-component",n);let i=this.scopeStyles(t,n);return r.textContent=i,document.head.appendChild(r),this.styles.set(n,r),n}static remove(t){let e=this.styles.get(t);e&&e.parentElement&&(e.parentElement.removeChild(e),this.styles.delete(t));}static scopeStyles(t,e){let n=t.split(`
2
+ `),r=[],o=0;for(let a of n){if(a=a.trim(),a.startsWith("@media")){r.push(a);continue}if(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,a.includes("{")&&!a.startsWith("@")&&!a.startsWith("}")){let l=a.substring(0,a.indexOf("{")).trim(),c=a.substring(a.indexOf("{"));if(l===":root"||l==="*"||a.startsWith("@"))r.push(a);else {let u=`[data-scope="${e}"] ${l}`;r.push(`${u} ${c}`);}}else r.push(a);}return r.join(`
3
+ `)}static clear(){for(let[,t]of this.styles)t.parentElement&&t.parentElement.removeChild(t);this.styles.clear();}};function be(s,...t){let e="";for(let n=0;n<s.length;n++)e+=s[n],n<t.length&&(e+=t[n]);return e}var ee=class{constructor(){this.queue=new Set;this.isFlushScheduled=false;this.isFlushing=false;}schedule(t){if(this.isFlushing){requestAnimationFrame(()=>this.schedule(t));return}this.queue.add(t),this.isFlushScheduled||(this.isFlushScheduled=true,Promise.resolve().then(()=>{requestAnimationFrame(()=>this.flush());}));}flushSync(t){t();}flush(){if(this.queue.size===0){this.isFlushScheduled=false;return}this.isFlushing=true,this.isFlushScheduled=false;let t=Array.from(this.queue);this.queue.clear();for(let e of t)try{e();}catch(n){console.error("Error during update:",n);}this.isFlushing=false,this.queue.size>0&&this.schedule(()=>{});}clear(){this.queue.clear(),this.isFlushScheduled=false;}get size(){return this.queue.size}},U=new ee;var m=class{constructor(t,e){this._isMounted=false;this._isUnmounting=false;this._element=null;this._vnode=null;this._styleId=null;this._isScheduledForUpdate=false;this._updateBatch=new Set;this._refs=new Map;this._subscriptions=[];this._memoCache=new Map;this._isInitializing=false;this._skipNextUpdate=false;this._preservedElements=new Map;this._updateInProgress=false;this.props=t||{},this.state=e||{};}setState(t,e){if(this._isInitializing){let o=typeof t=="function"?t(this.state):t;this.state={...this.state,...o};return}if(this._isUnmounting)return;let n={...this.state},r=typeof t=="function"?t(this.state):t,i=false;for(let o in r)if(n[o]!==r[o]){i=true;break}if(!i){e&&U.schedule(e);return}this.state={...this.state,...r},this.onStateChange?.(n,this.state),this.update(),e&&U.schedule(e);}setProps(t){if(this._isUnmounting)return;let e={...this.props},n=false;for(let r in t)if(e[r]!==t[r]){n=true;break}n&&(this.props={...this.props,...t},this.onPropsChange?.(e,this.props),this.update());}batchUpdate(t){let e=this._isScheduledForUpdate;this._isScheduledForUpdate=true;try{t();}finally{e||(this._isScheduledForUpdate=false,this.update());}}update(t){if(this._skipNextUpdate){this._skipNextUpdate=false;return}this._isInitializing||this._isUnmounting||!this._isMounted||this._updateInProgress||(t&&this._updateBatch.add(t),!this._isScheduledForUpdate&&(this._isScheduledForUpdate=true,U.schedule(()=>{this._isScheduledForUpdate=false,this._updateBatch.clear(),this._performUpdate();})));}forceUpdate(){!this._isMounted||this._isUnmounting||this._updateInProgress||U.flushSync(()=>{this._performUpdate();});}skipNextUpdate(){this._skipNextUpdate=true;}beginInitialization(){this._isInitializing=true;}endInitialization(){this._isInitializing=false;}async mount(t){if(this._isMounted){console.warn(`Component ${this.constructor.name} is already mounted`);return}if(!t)throw new Error(`Cannot mount ${this.constructor.name}: container is null or undefined`);try{this._isInitializing=!0,await this.onBeforeMount?.(),this._vnode=this.render(),this._element=this._createElementFromVNode(this._vnode),this.styles&&(this._styleId=D.inject(this.styles(),this.constructor.name),this._element?.setAttribute("data-scope",this.constructor.name)),t.appendChild(this._element),this._isMounted=!0,this._isInitializing=!1,await this.onMount?.();}catch(e){throw this._isInitializing=false,this._isMounted=false,this._handleError(e,{componentStack:this.constructor.name}),e}}unmount(){if(!(!this._isMounted||this._isUnmounting)){this._isUnmounting=true;try{this.onBeforeUnmount?.(),this._isScheduledForUpdate=!1,this._updateBatch.clear(),this._styleId&&(D.remove(this._styleId),this._styleId=null),this._subscriptions.forEach(t=>{try{t();}catch(e){console.error("Error during unsubscribe:",e);}}),this._subscriptions=[],this._element?.parentElement&&this._element.parentElement.removeChild(this._element),this._isMounted=!1,this._element=null,this._vnode=null,this.onUnmount?.(),this._refs.clear(),this._memoCache.clear(),this._preservedElements.clear();}catch(t){this._handleError(t,{componentStack:this.constructor.name});}finally{this._isUnmounting=false;}}}getRef(t){return this._refs.get(t)}createRef(t){return e=>{e?this._refs.set(t,e):this._refs.delete(t);}}memo(t,e,n){let r=this._memoCache.get(t);if(r&&this._areDepsEqual(r.args,n))return r.result;let i=e();return this._memoCache.set(t,{args:n,result:i}),i}subscribe(t){this._subscriptions.push(t);}debounce(t,e){let n=null;return (...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,t.apply(this,r);},e);}}throttle(t,e){let n=0,r=null;return (...i)=>{let o=Date.now(),a=o-n;a>=e?(n=o,t.apply(this,i)):r||(r=setTimeout(()=>{n=Date.now(),r=null,t.apply(this,i);},e-a));}}get element(){return this._element}get isMounted(){return this._isMounted}get isUnmounting(){return this._isUnmounting}get isInitializing(){return this._isInitializing}async _performUpdate(){if(!this._isMounted||!this._element||this._isUnmounting||this._isInitializing||this._updateInProgress)return;this._updateInProgress=true;let t={...this.props},e={...this.state};try{if(this.shouldUpdate&&!this.shouldUpdate(t,e))return;await this.onBeforeUpdate?.(t,e),this._preserveComponentMounts();let n=this.render(),r=this._element.parentElement;if(this._vnode&&r){let i=Array.from(r.childNodes).indexOf(this._element);if(i===-1){console.warn(`Component ${this.constructor.name} element removed from parent, skipping update`);return}let o=this._convertToVDomNode(this._vnode),a=this._convertToVDomNode(n);patch(r,o,a,i),this._element=r.childNodes[i];}this._vnode=n,this._restoreComponentMounts(),this.onUpdate?.(t,e);}catch(n){this._handleError(n,{componentStack:this.constructor.name});}finally{this._updateInProgress=false;}}_preserveComponentMounts(){if(!this._element)return;this._preservedElements.clear(),["[data-language-dropdown-mount]","[data-user-dropdown-mount]","[data-notifications-dropdown-mount]","[data-dropdown-id]","[data-preserve]","[data-toast-mount]","[data-popup-mount]","[data-loader-mount]","[data-navbar-notifications-list]"].forEach(e=>{this._element.querySelectorAll(e).forEach(r=>{r.children.length>0&&r.parentElement&&this._preservedElements.set(r,{parent:r,children:Array.from(r.childNodes)});});});}_restoreComponentMounts(){this._element&&(this._preservedElements.forEach((t,e)=>{let n=null,r=Array.from(e.attributes);for(let i of r)if(i.name.startsWith("data-")){let o=`[${i.name}="${i.value}"]`;if(n=this._element.querySelector(o),n)break}if(n&&t.children.length>0){for(;n.firstChild;)n.removeChild(n.firstChild);t.children.forEach(i=>{n.appendChild(i);});}}),this._preservedElements.clear());}_convertToVDomNode(t){if(typeof t.type!="string")throw new Error("Component VNodes cannot be converted to VDom nodes");let e={};for(let[r,i]of Object.entries(t.props))r!=="children"&&(e[r]=i);let n=t.children.map(r=>r==null||typeof r=="boolean"?null:typeof r=="string"||typeof r=="number"?r:this._convertToVDomNode(r)).filter(r=>r!==null);return {type:t.type,props:e,children:n}}_createElementFromVNode(t){if(typeof t.type!="string")throw new Error("Component VNodes not supported in _createElementFromVNode");let e=document.createElement(t.type);for(let[n,r]of Object.entries(t.props))n!=="children"&&this._setElementProperty(e,n,r);for(let n of t.children)n==null||n===false||(typeof n=="string"||typeof n=="number"?e.appendChild(document.createTextNode(String(n))):typeof n=="object"&&"type"in n&&e.appendChild(this._createElementFromVNode(n)));return e}_setElementProperty(t,e,n){if(e.startsWith("on")&&typeof n=="function"){let r=e.substring(2).toLowerCase();t.addEventListener(r,n);return}if(e==="className"&&typeof n=="string"){t.className=n;return}if(e==="style"){typeof n=="string"?t.setAttribute("style",n):typeof n=="object"&&n!==null&&Object.assign(t.style,n);return}if(e==="ref"&&typeof n=="function"){n(t);return}if(e==="checked"||e==="disabled"||e==="selected"){(n==="true"||n===true||n==="")&&t.setAttribute(e,"");return}n!=null&&n!==false&&t.setAttribute(e,String(n));}_handleError(t,e){if(console.error(`Error in component ${this.constructor.name}:`,t),console.error("Component stack:",e.componentStack),this.onError)this.onError(t,e);else throw t}_areDepsEqual(t,e){return t.length!==e.length?false:t.every((n,r)=>Object.is(n,e[r]))}_invalidateAllComputed(){for(let t in this)t.startsWith("_computed_dirty_")&&(this[t]=true);}_triggerWatchers(t,e,n){let r=this.constructor.__watchers__;if(r?.[t]){for(let i of r[t])if(typeof this[i]=="function")try{this[i].call(this,e,n);}catch(o){console.error(`Watcher error in ${i}:`,o);}}}setElement(t){this._element=t;}};function p(s,t){if(t&&typeof t=="object"&&"kind"in t){let o=t.name;return t.addInitializer(function(){let a=this;a.constructor.__reactiveProps__||(a.constructor.__reactiveProps__=[]),a.constructor.__reactiveProps__.includes(o)||a.constructor.__reactiveProps__.push(o);}),function(a){let l=this,c=`_state_${o}`;return l[c]=a,Object.defineProperty(this,o,{get(){return this[c]},set(u){let d=this,y=d[c];y!==u&&(d[c]=u,typeof d._invalidateAllComputed=="function"&&d._invalidateAllComputed(),typeof d._triggerWatchers=="function"&&d._triggerWatchers(o,u,y),d._isMounted&&typeof d.update=="function"&&d.update());},enumerable:true,configurable:true}),a}}let e=t,n=s.constructor;n.__reactiveProps__||(n.__reactiveProps__=[]),n.__reactiveProps__.includes(e)||n.__reactiveProps__.push(e);let r=`_state_${e}`,i=`_state_init_${e}`;Object.defineProperty(s,e,{get(){let o=this;if(o[i])return o[r]},set(o){let a=this;if(!a[i]){a[r]=o,a[i]=true;return}let l=a[r];l!==o&&(a[r]=o,typeof a._invalidateAllComputed=="function"&&a._invalidateAllComputed(),typeof a._triggerWatchers=="function"&&a._triggerWatchers(e,o,l),a._isMounted&&typeof a.update=="function"&&a.update());},enumerable:true,configurable:true});}function dt(s,t,e){if(t&&typeof t=="object"&&"kind"in t){let a=t;if(a.kind!=="getter")throw new Error("@computed can only be used on getters");let l=s,c=a.name,u=`_computed_cache_${c}`,d=`_computed_dirty_${c}`;return function(){let y=this;return y[d]===void 0&&(y[d]=true),y[d]===true&&(y[u]=l.call(this),y[d]=false),y[u]}}let n=t;if(!e)throw new Error("@computed requires a property descriptor");let r=e.get;if(!r)throw new Error("@computed can only be used on getters");let i=`_computed_cache_${n}`,o=`_computed_dirty_${n}`;return {get(){let a=this;return a[o]===void 0&&(a[o]=true),a[o]===true&&(a[i]=r.call(this),a[o]=false),a[i]},enumerable:e.enumerable,configurable:e.configurable}}function ht(s){function t(e,n,r){if(n&&typeof n=="object"&&"kind"in n){if(n.kind!=="method")throw new Error("@watch can only be used on methods");let l=n.name;n.addInitializer(function(){let c=this;c.constructor.__watchers__||(c.constructor.__watchers__={}),c.constructor.__watchers__[s]||(c.constructor.__watchers__[s]=[]),c.constructor.__watchers__[s].includes(l)||c.constructor.__watchers__[s].push(l);});return}let i=n;if(!r)throw new Error("@watch requires a property descriptor");let a=e.constructor;return a.__watchers__||(a.__watchers__={}),a.__watchers__[s]||(a.__watchers__[s]=[]),a.__watchers__[s].includes(i)||a.__watchers__[s].push(i),r}return t}var G=class{constructor(t){this._subscribers=new Set;this._value=t,this._defaultValue=t;}get value(){return this._value}set value(t){this._value!==t&&(this._value=t,this._notify());}subscribe(t){this._subscribers.add(t);try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}return ()=>{this._subscribers.delete(t);}}reset(){this.value=this._defaultValue;}update(t){this.value=t(this._value);}_notify(){for(let t of this._subscribers)try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}}get subscriberCount(){return this._subscribers.size}};function mt(s){return new G(s)}var ve=class extends m{onMount(){this.props.context.value=this.props.value;}onUpdate(){this.props.context.value=this.props.value;}onUnmount(){}render(){let t=Array.isArray(this.props.children)?this.props.children:[this.props.children];return html`
4
+ <div class="context-provider" style="display: contents;">
5
+ ${t}
6
+ </div>
7
+ `}};function bt(s,t){let e=s.subscribe(()=>{t.isMounted&&t.update();});return t.subscribe(()=>e),s.value}var te=class{constructor(t){this.contexts=new Map;for(let[e,n]of Object.entries(t))this.contexts.set(e,new G(n));}get(t){let e=this.contexts.get(t);if(!e)throw new Error(`Context key "${String(t)}" not found`);return e}set(t,e){let n=this.contexts.get(t);n&&(n.value=e);}subscribe(t,e){let n=this.contexts.get(t);if(!n)throw new Error(`Context key "${String(t)}" not found`);return n.subscribe(e)}reset(){for(let t of this.contexts.values())t.reset();}};function vt(s){return new te(s)}var L=null,A=0,ne=new WeakMap;function Me(s){L=s,A=0;}function Pe(){L=null,A=0;}function J(s){return ne.has(s)||ne.set(s,[]),ne.get(s)}function N(s){if(!L)throw new Error("useState must be called inside a component");let t=L,e=A++,n=J(t);n[e]===void 0&&(n[e]={value:typeof s=="function"?s():s});let r=i=>{let o=n[e],a=typeof i=="function"?i(o.value):i;o.value!==a&&(o.value=a,t.update());};return [n[e].value,r]}function O(s,t){if(!L)throw new Error("useEffect must be called inside a component");let e=L,n=A++,r=J(e),i=r[n];if(!i||!t||!ye(i.deps,t)){if(i?.value&&typeof i.value=="function")try{i.value();}catch(a){console.error("Error in effect cleanup:",a);}Promise.resolve().then(()=>{try{let a=s();r[n]={value:a,deps:t?[...t]:void 0};}catch(a){console.error("Error in effect:",a);}});}}function Ie(s,t){if(!L)throw new Error("useMemo must be called inside a component");let e=A++,n=J(L),r=n[e];return (!r||!ye(r.deps,t))&&(n[e]={value:s(),deps:[...t]}),n[e].value}function re(s,t){return Ie(()=>s,t)}function se(s){if(!L)throw new Error("useRef must be called inside a component");let t=A++,e=J(L);return e[t]===void 0&&(e[t]={value:{current:s}}),e[t].value}function Tt(s,t){let[e,n]=N(t),r=re(i=>{n(o=>s(o,i));},[s]);return [e,r]}function _t(s,t){let[e,n]=N(()=>{try{let i=window.localStorage.getItem(s);return i?JSON.parse(i):t}catch(i){return console.error("Error loading from localStorage:",i),t}});return [e,i=>{n(o=>{let a=i instanceof Function?i(o):i;try{window.localStorage.setItem(s,JSON.stringify(a));}catch(l){console.error("Error saving to localStorage:",l);}return a});}]}function Ct(s,t){let[e,n]=N(s);return O(()=>{let r=setTimeout(()=>{n(s);},t);return ()=>{clearTimeout(r);}},[s,t]),e}function St(s){let t=se(void 0);return O(()=>{t.current=s;}),t.current}function Et(s=false){let[t,e]=N(s),n=re(()=>{e(r=>!r);},[]);return [t,n]}function xt(s,t){let e=se(s);O(()=>{e.current=s;},[s]),O(()=>{if(t===null)return;let n=setInterval(()=>e.current(),t);return ()=>clearInterval(n)},[t]);}function kt(s,t){let[e,n]=N(null),[r,i]=N(true),[o,a]=N(null),l=re(async()=>{i(true),a(null);try{let c=await fetch(s,t);if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);let u=await c.json();n(u);}catch(c){a(c);}finally{i(false);}},[s]);return O(()=>{l();},[l]),{data:e,loading:r,error:o,refetch:l}}function Lt(){let[s,t]=N({width:window.innerWidth,height:window.innerHeight});return O(()=>{let e=()=>{t({width:window.innerWidth,height:window.innerHeight});};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),s}function Mt(s,t,e=window){let n=se(t);O(()=>{n.current=t;},[t]),O(()=>{if(!(e&&"addEventListener"in e))return;let i=o=>{n.current(o);};return e.addEventListener(s,i),()=>{e.removeEventListener(s,i);}},[s,e]);}function Pt(s,t){class e extends m{render(){Me(this);try{return s(this.props)}finally{Pe();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function ye(s,t){if(!s||s.length!==t.length)return false;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return false;return true}var ie=class{constructor(){this.routes=[];this.currentRoute=null;this.mode="history";this.base="/";this.beforeEachHooks=[];this.afterEachHooks=[];this.currentComponent=null;this.routerOutlet=null;this.isNavigating=false;this.scrollBehavior="auto";this.notFoundHandler=null;this._internalPath=null;}init(t,e="history",n="/",r="auto"){this.routes=t,this.mode=e,this.base=n.endsWith("/")?n.slice(0,-1):n,this.scrollBehavior=r,this._initializeRouting(),this._handleRoute();}async push(t,e){this.isNavigating&&(this.isNavigating=false),this._internalPath=t,this.mode==="history"?window.history.pushState(e||{},"",this._buildFullPath(t)):window.location.hash=t,await this._handleRoute();}async replace(t,e){return this._internalPath=t,this.mode==="history"?window.history.replaceState(e||{},"",this._buildFullPath(t)):window.location.hash=t,this._handleRoute()}back(){window.history.back();}forward(){window.history.forward();}go(t){window.history.go(t);}beforeEach(t){this.beforeEachHooks.push(t);}afterEach(t){this.afterEachHooks.push(t);}onNotFound(t){this.notFoundHandler=t;}getCurrentRoute(){return this.currentRoute?{...this.currentRoute}:null}isActive(t,e=false){return this.currentRoute?e?this.currentRoute.path===t:this.currentRoute.path.startsWith(t):false}outlet(){return createElement("div",{"data-router-outlet":"true",style:"display: contents;"})}getRoute(t){return this.routes.find(e=>e.name===t)}async pushNamed(t,e){let n=this.getRoute(t);if(!n){console.error(`Route with name "${t}" not found`);return}let r=n.path;if(e)for(let[i,o]of Object.entries(e))r=r.replace(`:${i}`,o);return this.push(r)}resolve(t){let e=this._matchRoute(t);if(!e)return null;let{route:n,params:r}=e;return {path:t,params:r,query:this._parseQuery(t),meta:n.meta||{},hash:t.includes("#")?t.split("#")[1]:"",name:n.name}}_initializeRouting(){window.addEventListener("popstate",()=>{this._internalPath=null,this._handleRoute();}),this.mode==="hash"&&window.addEventListener("hashchange",()=>{this._internalPath=null,this._handleRoute();}),document.addEventListener("click",t=>{let e=t.target.closest("a[href]");if(e&&this._shouldInterceptLink(e)){t.preventDefault();let n=e.getAttribute("href");if(n){let r=this.mode==="hash"&&n.startsWith("#")?n.substring(1):n.replace(this.base,"");this.push(r);}}});}_shouldInterceptLink(t){return !!(t.getAttribute("href")&&t.hostname===window.location.hostname&&t.target!=="_blank"&&!t.hasAttribute("download")&&t.rel!=="external")}async _handleRoute(){if(!this.isNavigating){this.isNavigating=true;try{let t=this._getCurrentPath(),e=this._matchRoute(t);if(!e){this._handleNotFound(t);return}let{route:n,params:r}=e,i=this._buildRouteObject(t,r,n),o=this.currentRoute||this._buildEmptyRoute();if(!await this._runNavigationGuards(n,i,o))return;this.currentRoute=i,await this._renderComponent(n),this._handleScrollBehavior(i,o),n.meta?.title&&typeof n.meta.title=="string"&&(document.title=n.meta.title),this.afterEachHooks.forEach(l=>l(i,o));}catch(t){console.error("Router error:",t);}finally{this.isNavigating=false;}}}_handleNotFound(t){console.warn(`No route matched for path: ${t}`),this.currentRoute={path:t,params:{},query:this._parseQuery(),meta:{},hash:window.location.hash.substring(1)},this.notFoundHandler&&this.notFoundHandler();}_buildRouteObject(t,e,n){return {path:t,params:e,query:this._parseQuery(),meta:n.meta||{},hash:window.location.hash.substring(1),name:n.name}}_buildEmptyRoute(){return {path:"",params:{},query:{},meta:{},hash:""}}async _runNavigationGuards(t,e,n){if(t.beforeEnter&&!await this._runGuard(t.beforeEnter,e,n))return false;for(let r of this.beforeEachHooks)if(!await this._runGuard(r,e,n))return false;return true}_runGuard(t,e,n){return new Promise(r=>{t(e,n,i=>{i===false?r(false):typeof i=="string"?(this.push(i),r(false)):r(true);});})}async _renderComponent(t){if(!this.routerOutlet&&(this.routerOutlet=document.querySelector('[data-router-outlet="true"]'),!this.routerOutlet)){console.warn("Router outlet not found");return}this.currentComponent&&(this.currentComponent.unmount(),this.currentComponent=null),this.routerOutlet.innerHTML="";try{let e=await this._resolveComponent(t.component);if(!e||typeof e!="function")throw new Error("Component is null or not a constructor");let n=e;this.currentComponent=new n,this.currentComponent&&await this.currentComponent.mount(this.routerOutlet);}catch(e){throw this._renderError(t.path,e),e}}async _resolveComponent(t){if(typeof t=="function"){let n="prototype"in t&&t.prototype?t.prototype:null;if(n&&typeof n=="object"&&"constructor"in n&&n.constructor===t)return t;try{let i=await t();return i.HomePage||i.TodoPage||i.default||Object.values(i).find(a=>{if(typeof a!="function")return !1;let c=a.prototype;return c!==null&&typeof c=="object"&&c!==void 0&&"constructor"in c})||null}catch(i){return console.error("Failed to load lazy component:",i),null}}return null}_renderError(t,e){if(this.routerOutlet){let n=e instanceof Error?e.message:String(e);this.routerOutlet.innerHTML=`
8
+ <div style="padding: 2rem; background: #121212ff; border: 2px solid #303030ff;
5
9
  border-radius: 8px; margin: 2rem;">
6
- <h2 style="color: #c00; margin-top: 0;">\u26A0\uFE0F Failed to Load Component</h2>
7
- <p><strong>Route:</strong> ${t}</p>
8
- <p><strong>Error:</strong> ${r}</p>
10
+ <h2 style="color: rgba(208, 31, 31, 1); margin-top: 0;">\u26A0\uFE0F Failed to Load Component</h2>
11
+ <p style="color: #a3a3a3ff;"><strong>Route:</strong> ${t}</p>
12
+ <p style="color: #a3a3a3ff;"><strong>Error:</strong> ${n}</p>
9
13
  </div>
10
- `;}}_handleScrollBehavior(t,e){if(t.hash){let r=document.getElementById(t.hash);if(r){r.scrollIntoView({behavior:this.scrollBehavior});return}}t.path!==e.path&&window.scrollTo({top:0,behavior:this.scrollBehavior});}_getCurrentPath(){if(this._internalPath!==null)return this._internalPath;if(this.mode==="hash")return window.location.hash.substring(1).split("?")[0]||"/";let t=window.location.pathname;return (!t||t==="blank"||t==="about:blank")&&(t="/"),this.base&&t.startsWith(this.base)&&(t=t.substring(this.base.length)),t||"/"}_buildFullPath(t){if(t.startsWith("http"))return t;let e=t.startsWith("/")?t:"/"+t;return this.base+e}_matchRoute(t){let e=t.split("?")[0].split("#")[0];for(let r of this.routes){let n=this._matchPath(r.path,e);if(n!==null)return {route:r,params:n}}return null}_matchPath(t,e){if(t==="*")return {};if(t===e)return {};let r=[],n=t.replace(/\*/g,".*").replace(/:([^/]+)/g,(i,u)=>(r.push(u),"([^/]+)")),s=new RegExp(`^${n}$`),a=e.match(s);return a?r.reduce((i,u,c)=>(i[u]=decodeURIComponent(a[c+1]),i),{}):null}_parseQuery(t){let e=t?t.includes("?")?t.split("?")[1].split("#")[0]:"":window.location.search.substring(1);return e?e.split("&").reduce((r,n)=>{let[s,a]=n.split("=").map(decodeURIComponent);return s&&(r[s]=a||""),r},{}):{}}},S=new R;function mt(o){let t=o;return {async build(){if(!t.build){console.warn("No build configuration provided");return}console.log("\u{1F528} Building @je-es/client application...");try{await this._buildJS(),await this._buildStyles(),console.log("\u2705 Build completed successfully!");}catch(e){throw console.error("\u274C Build error:",e),e}},async _buildJS(){if(!t.build)return;let e=await Bun.build({entrypoints:[t.build.entry],outdir:t.build.output.substring(0,t.build.output.lastIndexOf("/")),target:"browser",minify:t.build.minify??false,sourcemap:t.build.sourcemap?"external":"none",splitting:t.build.optimization?.splitChunks??false,naming:{entry:t.build.output.substring(t.build.output.lastIndexOf("/")+1)},external:["sass","fs","path","url","util","stream","buffer","events","crypto","os","child_process"]});if(!e.success)throw console.error("\u274C JS Build failed:",e.logs),new Error("JS Build failed")},async _buildStyles(){let e=t.build?.styles?.input||"./app/gui/style",r=t.build?.styles?.output||"./static/client.css",n=await import('sass'),{writeFileSync:s,existsSync:a,mkdirSync:i}=await import('fs'),{join:u,dirname:c}=await import('path'),d=c(r),l=r.split("/").pop()||"client.css",p=u(e,"index.scss");if(!a(p)){console.log("\u26A0\uFE0F No index.scss found, skipping CSS build");return}try{a(d)||i(d,{recursive:!0});let _=n.compile(p,{style:t.build?.minify?"compressed":"expanded",sourceMap:!!t.build?.sourcemap,loadPaths:[e]}),K=u(d,l);s(K,_.css,"utf-8"),t.build?.sourcemap&&_.sourceMap&&s(`${K}.map`,JSON.stringify(_.sourceMap),"utf-8");}catch(_){throw console.error("\u274C CSS Build failed:",_),_}},async _collectScssFiles(e){let{readdirSync:r,statSync:n,existsSync:s}=await import('fs'),{join:a,extname:i}=await import('path'),u=[];if(!s(e))return u;let c=r(e);for(let d of c){let l=a(e,d),p=n(l);p.isDirectory()?u.push(...await this._collectScssFiles(l)):p.isFile()&&i(d)===".scss"&&!d.startsWith("_")&&u.push(l);}return u.sort()},async watch(){console.log("\u{1F440} Watching for changes..."),await this.build();let{watch:e}=await import('fs'),{dirname:r}=await import('path'),{existsSync:n}=await import('fs');if(t.build?.entry){let a=r(t.build.entry);e(a,{recursive:true},async(i,u)=>{if(u&&(u.endsWith(".ts")||u.endsWith(".tsx"))){console.log(`\u{1F504} ${u} changed, rebuilding JS...`);try{await this._buildJS(),console.log("\u2705 JS rebuild complete");}catch(c){console.error("\u274C JS rebuild failed:",c);}}});}let s="./app/style";n(s)&&e(s,{recursive:true},async(a,i)=>{if(i&&i.endsWith(".scss")){console.log(`\u{1F504} ${i} changed, rebuilding CSS...`);try{await this._buildStyles(),console.log("\u2705 CSS rebuild complete");}catch(u){console.error("\u274C CSS rebuild failed:",u);}}});},init(){if(t.api){let e={baseURL:t.api.baseURL,timeout:t.api.timeout,headers:t.api.headers};t.api.interceptors&&(e.interceptors={request:t.api.interceptors.request||null,response:t.api.interceptors.response||null,error:t.api.interceptors.error||null}),configureApi(e);}t.router&&t.app?.routes&&(S.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&S.beforeEach(t.router.beforeEach),t.router.afterEach&&S.afterEach(t.router.afterEach)),t.app?.root&&(document.querySelector(t.app.root)||console.error(`\u274C Root element "${t.app.root}" not found`)),t.devTools?.enabled&&this._enableDevTools();},_enableDevTools(){window.__JEES_DEV__={router:S,config:t,version:"0.0.1"};},getConfig(){return t}}}var P=class{constructor(t){this._subscribers=new Set;this._storage=null;this._middleware=[];this._isHydrating=false;if(this._persist=t.persist??false,this._storageKey=t.storageKey||`store_${Date.now()}`,this._persist&&typeof window<"u"&&(this._storage=t.storage==="sessionStorage"?sessionStorage:localStorage),this._persist&&this._storage){let e=this._loadFromStorage();this._state=e!==null?e:t.state;}else this._state=t.state;t.middleware&&(this._middleware=t.middleware);}get state(){return {...this._state}}set state(t){this.setState(t);}setState(t,e){let r={...this._state},n=typeof t=="function"?t(r):t;this._state={...r,...n};for(let s of this._middleware)try{s(this._state,e);}catch(a){console.error("Store middleware error:",a);}this._persist&&!this._isHydrating&&this._saveToStorage(),this._notify();}get(t){return this._state[t]}set(t,e,r){this.setState({[t]:e},r);}subscribe(t){return this._subscribers.add(t),t(this._state),()=>{this._subscribers.delete(t);}}subscribeToKey(t,e){let r=this._state[t],n=s=>{let a=s[t];r!==a&&(r=a,e(a));};return this.subscribe(n)}use(t){this._middleware.push(t);}clear(){if(this._state={},this._persist&&this._storage)try{this._storage.removeItem(this._storageKey);}catch(t){console.error("Failed to clear storage:",t);}this._notify();}reset(t){this._state={...t},this._persist&&this._saveToStorage(),this._notify();}hydrate(){if(!this._persist||!this._storage){console.warn("Cannot hydrate: persistence not enabled");return}this._isHydrating=true;let t=this._loadFromStorage();t!==null&&(this._state=t,this._notify()),this._isHydrating=false;}getSnapshot(){return {state:{...this._state},subscribers:this._subscribers.size,storageKey:this._storageKey}}batch(t){let e=this._notify.bind(this),r=false;this._notify=()=>{r=true;};try{t();}finally{this._notify=e,r&&this._notify();}}_notify(){let t={...this._state};for(let e of this._subscribers)try{e(t);}catch(r){console.error("Store subscriber error:",r);}}_loadFromStorage(){if(!this._storage)return null;try{let t=this._storage.getItem(this._storageKey);return t?JSON.parse(t):null}catch(t){return console.error("Failed to load from storage:",t),null}}_saveToStorage(){if(this._storage)try{this._storage.setItem(this._storageKey,JSON.stringify(this._state));}catch(t){console.error("Failed to save to storage:",t),t instanceof DOMException&&t.name==="QuotaExceededError"&&console.warn("Storage quota exceeded");}}destroy(){this._subscribers.clear(),this._middleware=[],this._state={};}};function B(o){return new P(o)}function gt(o,t){let e=B({state:{value:t(...o.map(r=>r.state))}});for(let r of o)r.subscribe(()=>{e.setState({value:t(...o.map(n=>n.state))});});return e}function vt(o,t,e){return o.subscribe(n=>{let s=e(n);Object.assign(t,s),typeof t.update=="function"&&t.update();})}function y(o,t){if(t&&typeof t=="object"&&"kind"in t){let a=t.name;return t.addInitializer(function(){let i=this;i.constructor.__reactiveProps__||(i.constructor.__reactiveProps__=[]),i.constructor.__reactiveProps__.includes(a)||i.constructor.__reactiveProps__.push(a);}),function(i){let u=this,c=`_state_${a}`;return u[c]=i,Object.defineProperty(this,a,{get(){return this[c]},set(d){let l=this,p=l[c];p!==d&&(l[c]=d,typeof l._invalidateAllComputed=="function"&&l._invalidateAllComputed(),typeof l._triggerWatchers=="function"&&l._triggerWatchers(a,d,p),l._isMounted&&typeof l.update=="function"&&l.update());},enumerable:true,configurable:true}),i}}let e=t,r=o.constructor;r.__reactiveProps__||(r.__reactiveProps__=[]),r.__reactiveProps__.includes(e)||r.__reactiveProps__.push(e);let n=`_state_${e}`,s=`_state_init_${e}`;Object.defineProperty(o,e,{get(){let a=this;if(a[s])return a[n]},set(a){let i=this;if(!i[s]){i[n]=a,i[s]=true;return}let u=i[n];u!==a&&(i[n]=a,typeof i._invalidateAllComputed=="function"&&i._invalidateAllComputed(),typeof i._triggerWatchers=="function"&&i._triggerWatchers(e,a,u),i._isMounted&&typeof i.update=="function"&&i.update());},enumerable:true,configurable:true});}function bt(o,t,e){if(t&&typeof t=="object"&&"kind"in t){let i=t;if(i.kind!=="getter")throw new Error("@computed can only be used on getters");let u=o,c=i.name,d=`_computed_cache_${c}`,l=`_computed_dirty_${c}`;return function(){let p=this;return p[l]===void 0&&(p[l]=true),p[l]===true&&(p[d]=u.call(this),p[l]=false),p[d]}}let r=t;if(!e)throw new Error("@computed requires a property descriptor");let n=e.get;if(!n)throw new Error("@computed can only be used on getters");let s=`_computed_cache_${r}`,a=`_computed_dirty_${r}`;return {get(){let i=this;return i[a]===void 0&&(i[a]=true),i[a]===true&&(i[s]=n.call(this),i[a]=false),i[s]},enumerable:e.enumerable,configurable:e.configurable}}function _t(o){function t(e,r,n){if(r&&typeof r=="object"&&"kind"in r){if(r.kind!=="method")throw new Error("@watch can only be used on methods");let u=r.name;r.addInitializer(function(){let c=this;c.constructor.__watchers__||(c.constructor.__watchers__={}),c.constructor.__watchers__[o]||(c.constructor.__watchers__[o]=[]),c.constructor.__watchers__[o].includes(u)||c.constructor.__watchers__[o].push(u);});return}let s=r;if(!n)throw new Error("@watch requires a property descriptor");let i=e.constructor;return i.__watchers__||(i.__watchers__={}),i.__watchers__[o]||(i.__watchers__[o]=[]),i.__watchers__[o].includes(s)||i.__watchers__[o].push(s),n}return t}var g=class extends m{constructor(e){super(e);this.fields=[];this.formData={};this.isSubmitting=false;this.submitError="";this.submitSuccess=false;this.fields=this.props.fields.map(r=>({...r,error:void 0,touched:false}));for(let r of this.fields)this.formData[r.name]=r.value||"";}onMount(){}handleChange(e,r){this.formData[e]=r;let n=this.fields.find(s=>s.name===e);n&&this.props.autoValidate&&(n.error=this.validateField(n,r),n.touched=true),this.update();}handleBlur(e){let r=this.fields.find(n=>n.name===e);r&&(r.touched=true,r.error=this.validateField(r,this.formData[e]),this.update());}validateField(e,r){let n=e.validation;if(!n)return;if(n.required&&!r)return n.message||`${e.label||e.name} is required`;if(!r)return;let s=String(r);if(n.minLength&&s.length<n.minLength)return n.message||`Minimum ${n.minLength} characters required`;if(n.maxLength&&s.length>n.maxLength)return n.message||`Maximum ${n.maxLength} characters allowed`;if(n.min!==void 0&&Number(r)<n.min)return n.message||`Minimum value is ${n.min}`;if(n.max!==void 0&&Number(r)>n.max)return n.message||`Maximum value is ${n.max}`;if(n.pattern&&!n.pattern.test(s))return n.message||"Invalid format";if(n.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))return n.message||"Invalid email address";if(n.url&&!/^https?:\/\/.+/.test(s))return n.message||"Invalid URL";if(n.custom){let a=n.custom(r);if(a!==true)return typeof a=="string"?a:"Validation failed"}}validateForm(){let e=true,r={};for(let n of this.fields){let s=this.validateField(n,this.formData[n.name]);n.error=s,n.touched=true,s&&(e=false,r[n.name]=s);}return this.update(),!e&&this.props.onValidationError&&this.props.onValidationError(r),e}async handleSubmit(e){if(e.preventDefault(),!this.validateForm()){let r=this.fields.find(n=>n.error);r&&document.querySelector(`[name="${r.name}"]`)?.focus();return}this.isSubmitting=true,this.submitError="",this.submitSuccess=false,this.update();try{if(this.props.onSubmit)await this.props.onSubmit(this.formData,e);else if(this.props.endpoint){let r=await api({method:this.props.method||"POST",url:this.props.endpoint,data:this.formData});this.submitSuccess=!0,this.props.onSuccess&&this.props.onSuccess(r.data);}}catch(r){let n=r instanceof Error?r.message:"Submission failed";this.submitError=n,this.props.onError&&this.props.onError(r);}finally{this.isSubmitting=false,this.update();}}renderLabel(e){return !e.label&&!e.icon?"":e.icon?html`
14
+ `;}}_handleScrollBehavior(t,e){if(t.hash){let n=document.getElementById(t.hash);if(n){n.scrollIntoView({behavior:this.scrollBehavior});return}}t.path!==e.path&&window.scrollTo({top:0,behavior:this.scrollBehavior});}_getCurrentPath(){if(this._internalPath!==null)return this._internalPath;if(this.mode==="hash")return window.location.hash.substring(1).split("?")[0]||"/";let t=window.location.pathname;return (!t||t==="blank"||t==="about:blank")&&(t="/"),this.base&&t.startsWith(this.base)&&(t=t.substring(this.base.length)),t||"/"}_buildFullPath(t){if(t.startsWith("http"))return t;let e=t.startsWith("/")?t:"/"+t;return this.base+e}_matchRoute(t){let e=t.split("?")[0].split("#")[0];for(let n of this.routes){let r=this._matchPath(n.path,e);if(r!==null)return {route:n,params:r}}return null}_matchPath(t,e){if(t==="*")return {};if(t===e)return {};let n=[],r=t.replace(/\*/g,".*").replace(/:([^/]+)/g,(a,l)=>(n.push(l),"([^/]+)")),i=new RegExp(`^${r}$`),o=e.match(i);return o?n.reduce((a,l,c)=>(a[l]=decodeURIComponent(o[c+1]),a),{}):null}_parseQuery(t){let e=t?t.includes("?")?t.split("?")[1].split("#")[0]:"":window.location.search.substring(1);return e?e.split("&").reduce((n,r)=>{let[i,o]=r.split("=").map(decodeURIComponent);return i&&(n[i]=o||""),n},{}):{}}},R=new ie;function we(s,t=false){t?R.replace(s):R.push(s),window.dispatchEvent(new CustomEvent("navigation",{detail:{path:s}}));}function Ot(){R.back();}function Rt(){window.history.forward();}function oe(){return window.location.pathname}function $t(s){return oe()===s}function Vt(s){return oe().startsWith(s)}function Ft(){let s=oe();we(s,true);}function Kt(s,t){let e=new URLSearchParams(t).toString();we(`${s}?${e}`);}function Oe(){return new URLSearchParams(window.location.search)}function At(s){return Oe().get(s)}var ae=class{constructor(t){this._subscribers=new Set;this._storage=null;this._middleware=[];this._isHydrating=false;if(this._persist=t.persist??false,this._storageKey=t.storageKey||`store_${Date.now()}`,this._persist&&typeof window<"u"&&(this._storage=t.storage==="sessionStorage"?sessionStorage:localStorage),this._persist&&this._storage){let e=this._loadFromStorage();this._state=e!==null?e:t.state;}else this._state=t.state;t.middleware&&(this._middleware=t.middleware);}get state(){return {...this._state}}set state(t){this.setState(t);}setState(t,e){let n={...this._state},r=typeof t=="function"?t(n):t;this._state={...n,...r};for(let i of this._middleware)try{i(this._state,e);}catch(o){console.error("Store middleware error:",o);}this._persist&&!this._isHydrating&&this._saveToStorage(),this._notify();}get(t){return this._state[t]}set(t,e,n){this.setState({[t]:e},n);}subscribe(t){return this._subscribers.add(t),t(this._state),()=>{this._subscribers.delete(t);}}subscribeToKey(t,e){let n=this._state[t],r=i=>{let o=i[t];n!==o&&(n=o,e(o));};return this.subscribe(r)}use(t){this._middleware.push(t);}clear(){if(this._state={},this._persist&&this._storage)try{this._storage.removeItem(this._storageKey);}catch(t){console.error("Failed to clear storage:",t);}this._notify();}reset(t){this._state={...t},this._persist&&this._saveToStorage(),this._notify();}hydrate(){if(!this._persist||!this._storage){console.warn("Cannot hydrate: persistence not enabled");return}this._isHydrating=true;let t=this._loadFromStorage();t!==null&&(this._state=t,this._notify()),this._isHydrating=false;}getSnapshot(){return {state:{...this._state},subscribers:this._subscribers.size,storageKey:this._storageKey}}batch(t){let e=this._notify.bind(this),n=false;this._notify=()=>{n=true;};try{t();}finally{this._notify=e,n&&this._notify();}}_notify(){let t={...this._state};for(let e of this._subscribers)try{e(t);}catch(n){console.error("Store subscriber error:",n);}}_loadFromStorage(){if(!this._storage)return null;try{let t=this._storage.getItem(this._storageKey);return t?JSON.parse(t):null}catch(t){return console.error("Failed to load from storage:",t),null}}_saveToStorage(){if(this._storage)try{this._storage.setItem(this._storageKey,JSON.stringify(this._state));}catch(t){console.error("Failed to save to storage:",t),t instanceof DOMException&&t.name==="QuotaExceededError"&&console.warn("Storage quota exceeded");}}destroy(){this._subscribers.clear(),this._middleware=[],this._state={};}};function Re(s){return new ae(s)}function Dt(s,t){let e=Re({state:{value:t(...s.map(n=>n.state))}});for(let n of s)n.subscribe(()=>{e.setState({value:t(...s.map(r=>r.state))});});return e}function Ut(s,t,e){return s.subscribe(r=>{let i=e(r);Object.assign(t,i),typeof t.update=="function"&&t.update();})}function qt(s){let t=s;return {async build(){if(!t.build){console.warn("No build configuration provided");return}console.log("\u{1F528} Building @je-es/client application...");try{await this._buildJS(),await this._buildStyles(),console.log("\u2705 Build completed successfully!");}catch(e){throw console.error("\u274C Build error:",e),e}},async _buildJS(){if(!t.build)return;let e=await Bun.build({entrypoints:[t.build.entry],outdir:t.build.output.substring(0,t.build.output.lastIndexOf("/")),target:"browser",minify:t.build.minify??false,sourcemap:t.build.sourcemap?"external":"none",splitting:t.build.optimization?.splitChunks??false,naming:{entry:t.build.output.substring(t.build.output.lastIndexOf("/")+1)},external:["sass","fs","path","url","util","stream","buffer","events","crypto","os","child_process"]});if(!e.success)throw console.error("\u274C JS Build failed:",e.logs),new Error("JS Build failed")},async _buildStyles(){let e=t.build?.styles?.input||"./app/gui/style",n=t.build?.styles?.output||"./static/client.css",r=await import('sass'),{writeFileSync:i,existsSync:o,mkdirSync:a}=await import('fs'),{join:l,dirname:c}=await import('path'),u=c(n),d=n.split("/").pop()||"client.css",y=l(e,"index.scss");if(!o(y)){console.log("\u26A0\uFE0F No index.scss found, skipping CSS build");return}try{o(u)||a(u,{recursive:!0});let K=r.compile(y,{style:t.build?.minify?"compressed":"expanded",sourceMap:!!t.build?.sourcemap,loadPaths:[e]}),me=l(u,d);i(me,K.css,"utf-8"),t.build?.sourcemap&&K.sourceMap&&i(`${me}.map`,JSON.stringify(K.sourceMap),"utf-8");}catch(K){throw console.error("\u274C CSS Build failed:",K),K}},async _collectScssFiles(e){let{readdirSync:n,statSync:r,existsSync:i}=await import('fs'),{join:o,extname:a}=await import('path'),l=[];if(!i(e))return l;let c=n(e);for(let u of c){let d=o(e,u),y=r(d);y.isDirectory()?l.push(...await this._collectScssFiles(d)):y.isFile()&&a(u)===".scss"&&!u.startsWith("_")&&l.push(d);}return l.sort()},async watch(){console.log("\u{1F440} Watching for changes..."),await this.build();let{watch:e}=await import('fs'),{dirname:n}=await import('path'),{existsSync:r}=await import('fs');if(t.build?.entry){let o=n(t.build.entry);e(o,{recursive:true},async(a,l)=>{if(l&&(l.endsWith(".ts")||l.endsWith(".tsx"))){console.log(`\u{1F504} ${l} changed, rebuilding JS...`);try{await this._buildJS(),console.log("\u2705 JS rebuild complete");}catch(c){console.error("\u274C JS rebuild failed:",c);}}});}let i="./app/style";r(i)&&e(i,{recursive:true},async(o,a)=>{if(a&&a.endsWith(".scss")){console.log(`\u{1F504} ${a} changed, rebuilding CSS...`);try{await this._buildStyles(),console.log("\u2705 CSS rebuild complete");}catch(l){console.error("\u274C CSS rebuild failed:",l);}}});},async init(){if(console.log("\u{1F680} [client] Initializing @je-es/client..."),t.api){let e={baseURL:t.api.baseURL,timeout:t.api.timeout,headers:t.api.headers};t.api.interceptors&&(e.interceptors={request:t.api.interceptors.request||null,response:t.api.interceptors.response||null,error:t.api.interceptors.error||null}),configureApi(e);}t.router&&t.app?.routes&&(R.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&R.beforeEach(t.router.beforeEach),t.router.afterEach&&R.afterEach(t.router.afterEach)),t.app?.root&&(document.querySelector(t.app.root)||console.error(`\u274C Root element "${t.app.root}" not found`)),t.devTools?.enabled&&this._enableDevTools();},_enableDevTools(){window.__JEES_DEV__={router:R,config:t,version:"0.0.1"};},getConfig(){return t}}}var z=class{constructor(t){this.translations={};this.currentLanguage="en";this.defaultLanguage="en";this.supportedLanguages=new Set(["en"]);this.cachePath="";this.readyListeners=[];t&&(this.defaultLanguage=t.defaultLanguage||"en",this.cachePath=t.staticPath||"static/i18n",this.currentLanguage=this.getStoredLanguage()||t.defaultLanguage||"en",t.supportedLanguages&&(this.supportedLanguages=new Set(t.supportedLanguages)));}loadLanguage(t,e){this.translations[t]||(this.translations[t]={}),this.translations[t]={...this.translations[t],...e},this.supportedLanguages.add(t);}loadTranslations(t){Object.entries(t).forEach(([e,n])=>{this.loadLanguage(e,n);});}setLanguage(t){this.supportedLanguages.has(t)?(this.currentLanguage=t,this.storeLanguage(t),this.dispatchLanguageChangeEvent()):this.supportedLanguages.has(this.defaultLanguage)&&(this.currentLanguage=this.defaultLanguage);}getLanguage(){return this.currentLanguage}getSupportedLanguages(){return Array.from(this.supportedLanguages)}t(t,e,n){let r=this.currentLanguage,i=this.getTranslation(t,n);return e&&Object.entries(e).forEach(([o,a])=>{let l=this.translations[r]?.[a]||this.translations[this.defaultLanguage]?.[a]||a;i=i.replace(new RegExp(`\\{${o}\\}`,"g"),l);}),i}getTranslation(t,e){let n=this.currentLanguage;return this.translations[n]?.[t]?this.translations[n]?.[t]||this.translations[this.defaultLanguage]?.[t]:(console.warn(`Translation key not found: ${t}`),e||t)}tLang(t,e,n){let r=this.currentLanguage;this.currentLanguage=e;let i=this.t(t,n);return this.currentLanguage=r,i}tHtml(t,e){let n=this.t(t,e);return this.parseHtmlString(n)}parseHtmlString(t){let e=t.replace(/\\n|\/n/g,"<br>"),n=[],r=/<([^/>]+)>([^<]*)<\/\1>|<([^/>]+)\s*\/?>|([^<]+)/g,i;for(;(i=r.exec(e))!==null;){let o=i[1],a=i[2],l=i[3],c=i[4];if(c)n.push(c);else if(o){let u=o.split(/\s+/)[0].toLowerCase();n.push(createElement(u,{},a));}else if(l){let u=l.trim().toLowerCase();n.push(createElement(u,{}));}}return n.length>0?n:[t]}getTranslations(){return this.translations[this.currentLanguage]||{}}hasKey(t){return !!(this.translations[this.currentLanguage]?.[t]||this.translations[this.defaultLanguage]?.[t])}createTranslator(t){let e=()=>t();return typeof window<"u"?(window.addEventListener("languagechange",e),()=>window.removeEventListener("languagechange",e)):()=>{}}async loadFromUrl(t){let e=Array.isArray(t)?t:[t],n={};for(let r of e)if(r.includes("*")){let i=r.replace("*.json",""),o=this.supportedLanguages;for(let a of o)try{let l=`${i}${a}.json`;typeof window<"u"&&!l.startsWith("http")&&(l=window.location.origin+(l.startsWith("/")?l:"/"+l));let c=await fetch(l);if(c.ok){let u=await c.json();n[a]=u;}}catch{}}else try{let i=r;typeof window<"u"&&!i.startsWith("http")&&(i=window.location.origin+(i.startsWith("/")?i:"/"+i));let o=await fetch(i);if(o.ok){let a=await o.json(),l=r.match(/([a-z]{2,3})\.json$/i),c=l?l[1].toLowerCase():"en";n[c]=a,this.supportedLanguages.add(c);}}catch{}Object.keys(n).length>0&&(this.loadTranslations(n),this.notifyReady());}onReady(t){Object.keys(this.translations).length>0?t():this.readyListeners.push(t);}notifyReady(){for(let t of this.readyListeners)t();this.readyListeners=[];}getStoredLanguage(){return typeof localStorage<"u"&&localStorage.getItem("app-language")||null}storeLanguage(t){typeof localStorage<"u"&&localStorage.setItem("app-language",t);}dispatchLanguageChangeEvent(){typeof window<"u"&&window.dispatchEvent(new CustomEvent("languagechange",{detail:{language:this.currentLanguage}}));}},B=null;function S(){return B||(B=new z),B}function g(s,t,e){return S().t(s,t,e)}function Jt(s,t,e){return S().tLang(s,t,e)}function le(s,t){return S().tHtml(s,t)}function Qt(s){S().setLanguage(s);}async function Yt(s,t){let e=S(),n=e.getTranslations();if(!(Object.keys(n).length>0)&&t){let i=t.endsWith("/")?t:t+"/";try{await e.loadFromUrl(i+`${s}.json`);}catch(o){console.warn(`Failed to lazy-load language: ${s}`,o);}}e.setLanguage(s);}function Zt(){return S().getLanguage()}function Xt(s,t){S().loadLanguage(s,t);}function en(s){S().loadTranslations(s);}function tn(){return S().getSupportedLanguages()}function nn(s){return S().hasKey(s)}function rn(){return S().getTranslations()}function sn(s){return S().createTranslator(s)}async function on(s){return S().loadFromUrl(s)}function an(s){B=new z(s);}async function ln(s){let t=new z(s);if(B=t,s.staticPath){let e=s.staticPath.endsWith("/")?s.staticPath:s.staticPath+"/",n=t.getLanguage(),r=e+`${n}.json`;await t.loadFromUrl(r);}}async function cn(s,t){let e=S(),n=t||"static/i18n",i=(n.endsWith("/")?n:n+"/")+s+".json";await e.loadFromUrl(i);}var j={toast:"bb_toast",container:"bb_toastContainer",icon:"bb_toastIcon",msg:"bb_toastMsg"},Y=class extends m{constructor(){super(...arguments);this.messages=[];this.nextId=0;}show(e,n="info",r=2e3,i){let o=this.nextId++;this.messages=[...this.messages,{id:o,message:e,type:n,translateKey:i}],setTimeout(()=>{this.messages=this.messages.filter(a=>a.id!==o);},r);}success(e,n,r){this.show(e,"success",n,r);}error(e,n,r){this.show(e,"error",n,r);}info(e,n,r){this.show(e,"info",n,r);}warning(e,n,r){this.show(e,"warning",n,r);}render(){return this.messages.length===0?html``:createElement("div",{className:j.container},...this.messages.map(e=>this.renderToast(e)))}renderToast(e){let n={success:"fas fa-check-circle",error:"fas fa-exclamation-circle",info:"fas fa-info-circle",warning:"fas fa-exclamation-triangle"},r=e.translateKey?g(e.translateKey):e.message;return createElement("div",{key:String(e.id),className:`${j.toast} ${j.toast}--${e.type}`,"data-translate":e.translateKey||void 0},createElement("i",{className:`${n[e.type]} ${j.icon}`}),createElement("span",{className:j.msg},r))}};h([p],Y.prototype,"messages");var $=null;function Fe(s){if($)return $;let t=s||document.createElement("div");return s||document.body.appendChild(t),$=new Y,$.mount(t),$}function q(){return $||($=Fe()),$}var fn={show:(s,t="info",e,n)=>{q().show(s,t,e,n);},success:(s,t,e)=>{q().success(s,t,e);},error:(s,t,e)=>{q().error(s,t,e);},info:(s,t,e)=>{q().info(s,t,e);},warning:(s,t,e)=>{q().warning(s,t,e);}};var T={loader:{container:"bb_loaderContainer",containerOverlay:"bb_loaderContainer--overlay",bg:"bb_loaderBg",loader:"bb_loader"},spinner:{container:"bb_loaderSpinnerContainer",icon:"bb_loaderSpinnerIcon",dot:"bb_loaderSpinnerDot",pulse:"bb_loaderSpinnerPulse",text:"bb_loaderSpinnerText"},progress:{container:"bb_loaderProgressContainer",bar:"bb_loaderProgressBar",text:"bb_loaderProgressText"}},I=class extends m{constructor(){super(...arguments);this.visible=false;this.message="";this.variant="spinner";this.size="medium";this.overlay=true;this.progress=0;this.showProgress=false;this.animationFrame=null;this.hideTimeout=null;this.handleKeyPress=e=>{e.key==="Escape"&&this.visible&&!this.overlay&&this.hide();};}async onMount(){this.setupKeyboardListener(),this.initializeAccessibility(),window.addEventListener("languagechange",()=>{this.message||this.update();});}onUnmount(){this.animationFrame&&cancelAnimationFrame(this.animationFrame),this.hideTimeout&&clearTimeout(this.hideTimeout),document.removeEventListener("keydown",this.handleKeyPress);}render(){let e=[T.loader.container,this.overlay?`${T.loader.containerOverlay}`:"",`${T.loader.container}--${this.size}`].filter(Boolean).join(" ");return createElement("div",{className:e,"data-status":this.visible?"visible":"hidden",role:"status","aria-live":"polite","aria-busy":"true"},createElement("div",{className:T.loader.bg}),createElement("div",{className:T.loader.loader},this.renderSpinner(),this.renderMessage(),this.showProgress?this.renderProgressBar():null))}renderSpinner(){let e=`${T.spinner.container} ${T.spinner.container}--${this.variant}`;switch(this.variant){case "dots":return createElement("div",{className:e},createElement("div",{className:T.spinner.dot}),createElement("div",{className:T.spinner.dot}),createElement("div",{className:T.spinner.dot}));case "pulse":return createElement("div",{className:e},createElement("div",{className:T.spinner.pulse}));case "spinner":default:return createElement("div",{className:e},createElement("div",{className:T.spinner.icon}))}}renderMessage(){let e=this.message||g("global.loading");return createElement("div",{className:T.spinner.text,"data-translate":this.message?void 0:"global.loading"},e)}renderProgressBar(){return createElement("div",{className:T.progress.container},createElement("div",{className:T.progress.bar,style:`width: ${this.progress}%`,"aria-valuenow":this.progress.toString(),"aria-valuemin":"0","aria-valuemax":"100"}),createElement("div",{className:T.progress.text},`${Math.round(this.progress)}%`))}show(e){typeof e=="string"?this.message=e:e&&(this.message=e.message||"",this.variant=e.variant||"spinner",this.size=e.size||"medium",this.overlay=e.overlay!==void 0?e.overlay:true),this.visible=true,this.progress=0,this.showProgress=false,this.applyBodyLock(),this.update();}hide(e=0){this.hideTimeout&&clearTimeout(this.hideTimeout),e>0?this.hideTimeout=window.setTimeout(()=>{this.performHide();},e):this.performHide();}setMessage(e){this.message=e,this.update();}setProgress(e){this.showProgress=true,this.progress=Math.max(0,Math.min(100,e)),this.update();}updateProgress(e){this.setProgress(this.progress+e);}performHide(){this.visible=false,this.message="",this.progress=0,this.showProgress=false,this.removeBodyLock(),this.update();}applyBodyLock(){this.overlay&&(document.body.style.overflow="hidden");}removeBodyLock(){document.body.style.overflow="";}setupKeyboardListener(){this.handleKeyPress=this.handleKeyPress.bind(this),document.addEventListener("keydown",this.handleKeyPress);}initializeAccessibility(){let e=this.element?.querySelector(`.${T.spinner.container}`);e&&e.setAttribute("aria-label",g("loading"));}isVisible(){return this.visible}getStatus(){return {visible:this.visible,message:this.message,progress:this.progress}}};h([p],I.prototype,"visible"),h([p],I.prototype,"message"),h([p],I.prototype,"variant"),h([p],I.prototype,"size"),h([p],I.prototype,"overlay"),h([p],I.prototype,"progress"),h([p],I.prototype,"showProgress");var V=class extends m{constructor(e){super(e);this.fields=[];this.formData={};this.isSubmitting=false;this.submitError="";this.submitSuccess=false;this.fields=this.props.fields.map(n=>({...n,error:void 0,touched:false}));for(let n of this.fields)this.formData[n.name]=n.value||"";}onMount(){}handleChange(e,n){this.formData[e]=n;let r=this.fields.find(i=>i.name===e);r&&this.props.autoValidate&&(r.error=this.validateField(r,n),r.touched=true),this.update();}handleBlur(e){let n=this.fields.find(r=>r.name===e);n&&(n.touched=true,n.error=this.validateField(n,this.formData[e]),this.update());}validateField(e,n){let r=e.validation;if(!r)return;if(r.required&&!n)return r.message||`${e.label||e.name} is required`;if(!n)return;let i=String(n);if(r.minLength&&i.length<r.minLength)return r.message||`Minimum ${r.minLength} characters required`;if(r.maxLength&&i.length>r.maxLength)return r.message||`Maximum ${r.maxLength} characters allowed`;if(r.min!==void 0&&Number(n)<r.min)return r.message||`Minimum value is ${r.min}`;if(r.max!==void 0&&Number(n)>r.max)return r.message||`Maximum value is ${r.max}`;if(r.pattern&&!r.pattern.test(i))return r.message||"Invalid format";if(r.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))return r.message||"Invalid email address";if(r.url&&!/^https?:\/\/.+/.test(i))return r.message||"Invalid URL";if(r.custom){let o=r.custom(n);if(o!==true)return typeof o=="string"?o:"Validation failed"}}validateForm(){let e=true,n={};for(let r of this.fields){let i=this.validateField(r,this.formData[r.name]);r.error=i,r.touched=true,i&&(e=false,n[r.name]=i);}return this.update(),!e&&this.props.onValidationError&&this.props.onValidationError(n),e}async handleSubmit(e){if(e.preventDefault(),!this.validateForm()){let n=this.fields.find(r=>r.error);n&&document.querySelector(`[name="${n.name}"]`)?.focus();return}this.isSubmitting=true,this.submitError="",this.submitSuccess=false,this.update();try{if(this.props.onSubmit)await this.props.onSubmit(this.formData,e);else if(this.props.endpoint){let n=await api({method:this.props.method||"POST",url:this.props.endpoint,data:this.formData});this.submitSuccess=!0,this.props.onSuccess&&this.props.onSuccess(n.data);}}catch(n){let r=n instanceof Error?n.message:"Submission failed";this.submitError=r,this.props.onError&&this.props.onError(n);}finally{this.isSubmitting=false,this.update();}}renderLabel(e){return !e.label&&!e.icon?"":e.icon?html`
11
15
  <label for=${e.name}>
12
16
  <i class="fa ${e.icon}"></i>
13
17
  ${e.label?html`<span>${e.label}</span>`:""}
14
18
  </label>
15
- `:html`<label for=${e.name}>${e.label}</label>`}renderField(e){let r=this.formData[e.name]||"",n=this.renderLabel(e);switch(e.type){case "textarea":return html`
16
- <div class="form-field ${e.className||""}">
17
- ${n}
19
+ `:html`<label for=${e.name}>${e.label}</label>`}renderField(e){let n=this.formData[e.name]||"",r=this.renderLabel(e);switch(e.type){case "textarea":return html`
20
+ <div class="bb_formField ${e.className||""}">
21
+ ${r}
18
22
  <textarea
19
23
  id=${e.name}
20
24
  name=${e.name}
21
25
  placeholder=${e.placeholder||""}
22
- value=${String(r)}
26
+ value=${String(n)}
23
27
  disabled=${String(e.disabled||this.isSubmitting)}
24
- oninput=${s=>{let a=s.target;this.handleChange(e.name,a.value);}}
28
+ oninput=${i=>{let o=i.target;this.handleChange(e.name,o.value);}}
25
29
  onblur=${()=>this.handleBlur(e.name)}
30
+ class="bb_formFieldTextarea"
26
31
  ></textarea>
27
32
  ${e.error&&e.touched?html`
28
33
  <span class="field-error">${e.error}</span>
29
34
  `:""}
30
35
  </div>
31
- `;case "select":{let a=(e.options||[]).map(i=>html`
32
- <option value=${String(i.value)}>${i.label}</option>
36
+ `;case "select":{let o=(e.options||[]).map(a=>html`
37
+ <option value=${String(a.value)}>${a.label}</option>
33
38
  `);return html`
34
- <div class="form-field ${e.className||""}">
35
- ${n}
39
+ <div class="bb_formField ${e.className||""}">
40
+ ${r}
36
41
  <select
37
42
  id=${e.name}
38
43
  name=${e.name}
39
- value=${String(r)}
44
+ value=${String(n)}
40
45
  disabled=${String(e.disabled||this.isSubmitting)}
41
- onchange=${i=>{let u=i.target;this.handleChange(e.name,u.value);}}
46
+ onchange=${a=>{let l=a.target;this.handleChange(e.name,l.value);}}
42
47
  onblur=${()=>this.handleBlur(e.name)}
48
+ class="bb_formFieldSelect"
43
49
  >
44
50
  <option value="">Select...</option>
45
- ${a}
51
+ ${o}
46
52
  </select>
47
53
  ${e.error&&e.touched?html`
48
54
  <span class="field-error">${e.error}</span>
49
55
  `:""}
50
56
  </div>
51
57
  `}case "checkbox":return html`
52
- <div class="form-field form-field-checkbox ${e.className||""}">
58
+ <div class="bb_formField bb_formField-checkbox ${e.className||""}">
53
59
  <label>
54
60
  <input
55
61
  type="checkbox"
56
62
  id=${e.name}
57
63
  name=${e.name}
58
- checked=${String(r)}
64
+ checked=${String(n)}
59
65
  disabled=${String(e.disabled||this.isSubmitting)}
60
- onchange=${s=>{let a=s.target;this.handleChange(e.name,a.checked);}}
66
+ onchange=${i=>{let o=i.target;this.handleChange(e.name,o.checked);}}
67
+ class="bb_formFieldCheckbox"
61
68
  />
62
69
  ${e.icon?html`<i class="fa ${e.icon}"></i>`:""}
63
70
  ${e.label||""}
@@ -67,26 +74,27 @@ import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMEle
67
74
  `:""}
68
75
  </div>
69
76
  `;default:return html`
70
- <div class="form-field ${e.className||""}">
71
- ${n}
77
+ <div class="bb_formField ${e.className||""}">
78
+ ${r}
72
79
  <input
73
80
  type="${e.type||"text"}"
74
81
  id="${e.name}"
75
82
  name="${e.name}"
76
83
  placeholder="${e.placeholder||""}"
77
- value="${String(r)}"
84
+ value="${String(n)}"
78
85
  disabled="${e.disabled||this.isSubmitting}"
79
- oninput=${s=>{let a=s.target;this.handleChange(e.name,a.value);}}
86
+ oninput=${i=>{let o=i.target;this.handleChange(e.name,o.value);}}
80
87
  onblur=${()=>this.handleBlur(e.name)}
88
+ class="bb_formFieldInput"
81
89
  />
82
90
  ${e.error&&e.touched?html`
83
91
  <span class="field-error">${e.error}</span>
84
92
  `:""}
85
93
  </div>
86
- `}}render(){let e=this.props.submitButton||{},r=this.fields.map(n=>this.renderField(n));return html`
94
+ `}}render(){let e=this.props.submitButton||{},n=this.fields.map(r=>this.renderField(r));return html`
87
95
  <form
88
- class="smart-form ${this.props.className||""}"
89
- onsubmit=${n=>this.handleSubmit(n)}
96
+ class="smart_form ${this.props.className||""}"
97
+ onsubmit=${r=>this.handleSubmit(r)}
90
98
  >
91
99
  ${this.submitError?html`
92
100
  <div class="alert alert-error">${this.submitError}</div>
@@ -96,7 +104,7 @@ import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMEle
96
104
  <div class="alert alert-success">Submitted successfully!</div>
97
105
  `:""}
98
106
 
99
- ${r}
107
+ ${n}
100
108
 
101
109
  <button
102
110
  type="submit"
@@ -106,88 +114,5 @@ import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMEle
106
114
  ${this.isSubmitting?e.loadingLabel||"Submitting...":e.label||"Submit"}
107
115
  </button>
108
116
  </form>
109
- `}styles(){return L`
110
- .smart-form {
111
- max-width: 100%;
112
- }
113
- .form-field {
114
- margin-bottom: 1rem;
115
- }
116
- .form-field label {
117
- display: flex;
118
- align-items: center;
119
- gap: 0.5rem;
120
- margin-bottom: 0.5rem;
121
- font-weight: 500;
122
- }
123
- .form-field label i {
124
- color: #6b7280;
125
- }
126
- .form-field input,
127
- .form-field textarea,
128
- .form-field select {
129
- width: 100%;
130
- padding: 0.5rem;
131
- border: 1px solid #d1d5db;
132
- border-radius: 0.375rem;
133
- font-size: 1rem;
134
- }
135
- .form-field input:focus,
136
- .form-field textarea:focus,
137
- .form-field select:focus {
138
- outline: none;
139
- border-color: #3b82f6;
140
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
141
- }
142
- .form-field-checkbox label {
143
- display: flex;
144
- align-items: center;
145
- gap: 0.5rem;
146
- }
147
- .form-field-checkbox input[type="checkbox"] {
148
- width: auto;
149
- }
150
- .field-error {
151
- display: block;
152
- color: #dc2626;
153
- font-size: 0.875rem;
154
- margin-top: 0.25rem;
155
- }
156
- .submit-button {
157
- width: 100%;
158
- padding: 0.75rem 1rem;
159
- background: #3b82f6;
160
- color: white;
161
- border: none;
162
- border-radius: 0.375rem;
163
- font-size: 1rem;
164
- font-weight: 500;
165
- cursor: pointer;
166
- transition: background 0.2s;
167
- }
168
- .submit-button:hover:not(:disabled) {
169
- background: #2563eb;
170
- }
171
- .submit-button:disabled {
172
- opacity: 0.6;
173
- cursor: not-allowed;
174
- }
175
- .alert {
176
- padding: 0.75rem;
177
- border-radius: 0.375rem;
178
- margin-bottom: 1rem;
179
- }
180
- .alert-error {
181
- background: #fee2e2;
182
- color: #dc2626;
183
- }
184
- .alert-success {
185
- background: #d1fae5;
186
- color: #065f46;
187
- }
188
- `}};T([y],g.prototype,"fields"),T([y],g.prototype,"formData"),T([y],g.prototype,"isSubmitting"),T([y],g.prototype,"submitError"),T([y],g.prototype,"submitSuccess");function wt(o){return new g(o).render()}function z(o,t){let e=null;return (...r)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,o(...r);},t);}}function W(o,t){let e=0,r=null;return (...n)=>{let s=Date.now(),a=s-e;a>=t?(e=s,o(...n)):r||(r=setTimeout(()=>{e=Date.now(),r=null,o(...n);},t-a));}}function q(...o){let t=[];for(let e of o)if(e){if(typeof e=="string")t.push(e);else if(typeof e=="object")for(let[r,n]of Object.entries(e))n&&t.push(r);}return t.join(" ")}function j(o,t="YYYY-MM-DD"){let e=o instanceof Date?o:new Date(o);if(isNaN(e.getTime()))throw new Error("Invalid date provided to formatDate");let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),a=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),u=String(e.getSeconds()).padStart(2,"0");return t.replace("YYYY",String(r)).replace("MM",n).replace("DD",s).replace("HH",a).replace("mm",i).replace("ss",u)}function w(o){if(o===null||typeof o!="object")return o;if(o instanceof Date)return new Date(o.getTime());if(Array.isArray(o))return o.map(t=>w(t));if(o instanceof RegExp)return new RegExp(o.source,o.flags);if(o instanceof Map){let t=new Map;return o.forEach((e,r)=>{t.set(w(r),w(e));}),t}if(o instanceof Set){let t=new Set;return o.forEach(e=>{t.add(w(e));}),t}if(Object.prototype.toString.call(o)==="[object Object]"){let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=w(o[e]));return t}return o}function V(o,...t){if(!t.length)return o;let e=t.shift();if(!e)return o;if($(o)&&$(e)){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r],s=o[r];n!==void 0&&($(n)&&!Array.isArray(n)?((!s||!$(s))&&(o[r]={}),V(o[r],n)):o[r]=n);}}return V(o,...t)}function $(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}var H=0;function G(o="id"){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,11);H=(H||0)+1;let r=H.toString(36);return `${o}_${t}_${e}_${r}`}function J(o){if(o<0)throw new Error("Sleep duration must be non-negative");return new Promise(t=>setTimeout(t,o))}function Q(o){return o==null?true:typeof o=="string"?o.trim().length===0:Array.isArray(o)?o.length===0:o instanceof Map||o instanceof Set?o.size===0:typeof o=="object"?Object.keys(o).length===0:false}function Y(o){return o?o.charAt(0).toUpperCase()+o.slice(1):""}function Z(o){return o?o.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase():""}function I(o){return o?o.replace(/[-_\s]+(.)?/g,(t,e)=>e?e.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase()):""}function X(o){if(!o)return "";let t=I(o);return t.charAt(0).toUpperCase()+t.slice(1)}function tt(o,t,e="..."){return !o||o.length<=t?o:o.substring(0,t-e.length)+e}function et(o){let t={},e=o.replace(/^\?/,"");if(!e)return t;let r=e.split("&");for(let n of r){let[s,a]=n.split("=").map(decodeURIComponent);if(!s)continue;let i=a||"";if(s.endsWith("[]")){let u=s.slice(0,-2);t[u]||(t[u]=[]),t[u].push(i);}else t[s]=i;}return t}function rt(o){let t=[];for(let[e,r]of Object.entries(o))if(r!=null)if(Array.isArray(r))for(let n of r)n!=null&&t.push(`${encodeURIComponent(e)}[]=${encodeURIComponent(String(n))}`);else t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`);return t.length>0?`?${t.join("&")}`:""}function nt(o,t,e){return Math.min(Math.max(o,t),e)}function ot(){return typeof window<"u"&&typeof document<"u"}function st(o,t){try{return JSON.parse(o)}catch{return t}}var Tt={debounce:z,throttle:W,classNames:q,formatDate:j,deepClone:w,deepMerge:V,uniqueId:G,sleep:J,isEmpty:Q,capitalize:Y,kebabCase:Z,camelCase:I,pascalCase:X,truncate:tt,parseQuery:et,stringifyQuery:rt,clamp:nt,isBrowser:ot,safeJsonParse:st};var E=class{constructor(t){this._subscribers=new Set;this._value=t,this._defaultValue=t;}get value(){return this._value}set value(t){this._value!==t&&(this._value=t,this._notify());}subscribe(t){this._subscribers.add(t);try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}return ()=>{this._subscribers.delete(t);}}reset(){this.value=this._defaultValue;}update(t){this.value=t(this._value);}_notify(){for(let t of this._subscribers)try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}}get subscriberCount(){return this._subscribers.size}};function St(o){return new E(o)}var O=class extends m{onMount(){this.props.context.value=this.props.value;}onUpdate(){this.props.context.value=this.props.value;}onUnmount(){}render(){let t=Array.isArray(this.props.children)?this.props.children:[this.props.children];return html`
189
- <div class="context-provider" style="display: contents;">
190
- ${t}
191
- </div>
192
- `}};function xt(o,t){let e=o.subscribe(()=>{t.isMounted&&t.update();});return t.subscribe(()=>e),o.value}var F=class{constructor(t){this.contexts=new Map;for(let[e,r]of Object.entries(t))this.contexts.set(e,new E(r));}get(t){let e=this.contexts.get(t);if(!e)throw new Error(`Context key "${String(t)}" not found`);return e}set(t,e){let r=this.contexts.get(t);r&&(r.value=e);}subscribe(t,e){let r=this.contexts.get(t);if(!r)throw new Error(`Context key "${String(t)}" not found`);return r.subscribe(e)}reset(){for(let t of this.contexts.values())t.reset();}};function kt(o){return new F(o)}var f=null,x=0,U=new WeakMap;function it(o){f=o,x=0;}function at(){f=null,x=0;}function M(o){return U.has(o)||U.set(o,[]),U.get(o)}function v(o){if(!f)throw new Error("useState must be called inside a component");let t=f,e=x++,r=M(t);r[e]===void 0&&(r[e]={value:typeof o=="function"?o():o});let n=s=>{let a=r[e],i=typeof s=="function"?s(a.value):s;a.value!==i&&(a.value=i,t.update());};return [r[e].value,n]}function b(o,t){if(!f)throw new Error("useEffect must be called inside a component");let e=f,r=x++,n=M(e),s=n[r];if(!s||!t||!ct(s.deps,t)){if(s?.value&&typeof s.value=="function")try{s.value();}catch(i){console.error("Error in effect cleanup:",i);}Promise.resolve().then(()=>{try{let i=o();n[r]={value:i,deps:t?[...t]:void 0};}catch(i){console.error("Error in effect:",i);}});}}function ut(o,t){if(!f)throw new Error("useMemo must be called inside a component");let e=x++,r=M(f),n=r[e];return (!n||!ct(n.deps,t))&&(r[e]={value:o(),deps:[...t]}),r[e].value}function N(o,t){return ut(()=>o,t)}function D(o){if(!f)throw new Error("useRef must be called inside a component");let t=x++,e=M(f);return e[t]===void 0&&(e[t]={value:{current:o}}),e[t].value}function Et(o,t){let[e,r]=v(t),n=N(s=>{r(a=>o(a,s));},[o]);return [e,n]}function Rt(o,t){let[e,r]=v(()=>{try{let s=window.localStorage.getItem(o);return s?JSON.parse(s):t}catch(s){return console.error("Error loading from localStorage:",s),t}});return [e,s=>{r(a=>{let i=s instanceof Function?s(a):s;try{window.localStorage.setItem(o,JSON.stringify(i));}catch(u){console.error("Error saving to localStorage:",u);}return i});}]}function Pt(o,t){let[e,r]=v(o);return b(()=>{let n=setTimeout(()=>{r(o);},t);return ()=>{clearTimeout(n);}},[o,t]),e}function $t(o){let t=D(void 0);return b(()=>{t.current=o;}),t.current}function Vt(o=false){let[t,e]=v(o),r=N(()=>{e(n=>!n);},[]);return [t,r]}function Ft(o,t){let e=D(o);b(()=>{e.current=o;},[o]),b(()=>{if(t===null)return;let r=setInterval(()=>e.current(),t);return ()=>clearInterval(r)},[t]);}function Mt(o,t){let[e,r]=v(null),[n,s]=v(true),[a,i]=v(null),u=N(async()=>{s(true),i(null);try{let c=await fetch(o,t);if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);let d=await c.json();r(d);}catch(c){i(c);}finally{s(false);}},[o]);return b(()=>{u();},[u]),{data:e,loading:n,error:a,refetch:u}}function Nt(){let[o,t]=v({width:window.innerWidth,height:window.innerHeight});return b(()=>{let e=()=>{t({width:window.innerWidth,height:window.innerHeight});};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),o}function Dt(o,t,e=window){let r=D(t);b(()=>{r.current=t;},[t]),b(()=>{if(!(e&&"addEventListener"in e))return;let s=a=>{r.current(a);};return e.addEventListener(o,s),()=>{e.removeEventListener(o,s);}},[o,e]);}function Lt(o,t){class e extends m{render(){it(this);try{return o(this.props)}finally{at();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function ct(o,t){if(!o||o.length!==t.length)return false;for(let e=0;e<o.length;e++)if(o[e]!==t[e])return false;return true}setConfig({devMode:false,sanitizeHTML:true});export{F as CombinedContext,m as Component,E as Context,O as Provider,R as Router,wt as SmartForm,g as SmartFormComponent,P as Store,C as StyleManager,I as camelCase,Y as capitalize,nt as clamp,q as classNames,at as clearHookContext,mt as client,bt as computed,vt as connect,kt as createCombinedContext,gt as createComputedStore,St as createContext,Lt as createFunctionalComponent,B as createStore,L as css,z as debounce,w as deepClone,V as deepMerge,j as formatDate,ot as isBrowser,Q as isEmpty,Z as kebabCase,et as parseQuery,X as pascalCase,S as router,st as safeJsonParse,k as scheduler,it as setHookContext,J as sleep,y as state,rt as stringifyQuery,W as throttle,tt as truncate,G as uniqueId,N as useCallback,xt as useContext,Pt as useDebounce,b as useEffect,Dt as useEventListener,Mt as useFetch,Ft as useInterval,Rt as useLocalStorage,ut as useMemo,$t as usePrevious,Et as useReducer,D as useRef,v as useState,Vt as useToggle,Nt as useWindowSize,Tt as utils,_t as watch};//# sourceMappingURL=main.js.map
117
+ `}styles(){return be``}};h([p],V.prototype,"fields"),h([p],V.prototype,"formData"),h([p],V.prototype,"isSubmitting"),h([p],V.prototype,"submitError"),h([p],V.prototype,"submitSuccess");function _e(s){return new V(s).render()}var w={container:"bb_popupContainer",overlay:"bb_popupOverlay",popup:{base:"bb_popup",close:"bb_popupClose"},header:{container:"bb_popupHeader",icon:"bb_popupHeaderIcon",content:"bb_popupHeaderContent",title:"bb_popupHeaderContentTitle",description:"bb_popupHeaderContentDesc"},body:{container:"bb_popupBody",message:"bb_popupBodyMsg",input:"bb_popupBodyInput",formContainer:"bb_popupBodyFormContainer"},footer:"bb_popupFooter",button:"bb_btn"},Z=class extends m{constructor(){super(...arguments);this.popups=[];this.nextId=0;}async onMount(){this.setupKeyboardListener(),window.addEventListener("languagechange",()=>{this.update();});}onUnmount(){this.handleEscapeKey&&document.removeEventListener("keydown",this.handleEscapeKey);}render(){return this.popups.length===0?createElement("div",{className:w.container}):createElement("div",{className:w.container},...this.popups.map(e=>this.renderPopup(e)))}renderPopup(e){let n=`bb_popup--${e.size||"medium"}`,r=e.variant?`bb_popup--${e.variant}`:"";return createElement("div",{key:String(e.id),className:w.overlay,"data-popup-id":e.id,onClick:i=>{i.target.classList.contains(w.overlay)&&e.closeOnOverlay!==false&&this.closePopup(e.id,false);}},createElement("div",{className:`${w.popup.base} ${n} ${r}`,role:"dialog","aria-modal":"true","aria-labelledby":`popup-title-${e.id}`},e.showCloseButton!==false?createElement("button",{className:w.popup.close,onClick:()=>this.closePopup(e.id,false),"aria-label":"Close"},createElement("i",{className:"fas fa-times"})):null,createElement("div",{className:w.header.container},e.icon?createElement("div",{className:w.header.icon},createElement("i",{className:e.icon})):null,createElement("div",{className:w.header.content},createElement("h2",{id:`popup-title-${e.id}`,className:w.header.title,"data-translate":e.titleTranslateKey},e.titleTranslateKey?g(e.titleTranslateKey):e.title),e.description?createElement("p",{className:w.header.description,"data-translate":e.descriptionTranslateKey},e.descriptionTranslateKey?le(e.descriptionTranslateKey):e.description):null)),createElement("div",{className:w.body.container},e.message?createElement("p",{className:w.body.message,"data-translate":e.messageTranslateKey},e.messageTranslateKey?le(e.messageTranslateKey):e.message):null,e.type==="prompt"?createElement("input",{type:"text",className:w.body.input,value:e.inputValue||"",placeholder:g("popup.prompt.placeholder"),"data-translate":"popup.prompt.placeholder",onInput:i=>{e.inputValue=i.target.value;}}):null,e.type==="form"&&e.formConfig?createElement("div",{className:w.body.formContainer},_e(e.formConfig)):null,e.customContent||null),e.buttons&&e.buttons.length>0&&e.type!=="form"?createElement("div",{className:w.footer},...e.buttons.map(i=>createElement("button",{className:`${w.button} ${i.variant||"secondary"}`,"data-translate":i.translateKey,disabled:i.loading||e.isSubmitting,onClick:async()=>{i.loading||e.isSubmitting||await i.onClick();}},i.icon?createElement("i",{className:i.icon}):null,i.loading||e.isSubmitting?createElement("i",{className:"fas fa-spinner fa-spin"}):null," ",i.translateKey?g(i.translateKey):i.label))):null))}show(e){return new Promise(n=>{let r=this.nextId++,i={...e,id:r,resolve:n,type:e.type||"custom",size:e.size||"medium",closeOnOverlay:e.closeOnOverlay!==false,closeOnEscape:e.closeOnEscape!==false,showCloseButton:e.showCloseButton!==false,isSubmitting:false};this.popups=[...this.popups,i],this.applyBodyLock(),this.update();})}showForm(e){return new Promise((n,r)=>{let i=this.nextId++,o={...e.formConfig,onSubmit:async l=>{let c=this.popups.find(u=>u.id===i);c&&(c.isSubmitting=true,this.update());try{e.formConfig.onSubmit&&await e.formConfig.onSubmit(l,void 0),this.closePopup(i,l),n(l);}catch(u){c&&(c.isSubmitting=false,this.update()),e.formConfig.onError&&e.formConfig.onError(u);}},submitButton:{...e.formConfig.submitButton,className:e.formConfig.submitButton?.className||`${w.button} primary wide`}},a={title:e.title,titleTranslateKey:e.titleTranslateKey,description:e.description,descriptionTranslateKey:e.descriptionTranslateKey,type:"form",variant:e.variant||"default",size:e.size||"medium",icon:e.icon,formConfig:o,closeOnOverlay:e.closeOnOverlay!==false,closeOnEscape:e.closeOnEscape!==false,showCloseButton:e.showCloseButton!==false,id:i,resolve:n,isSubmitting:false};this.popups=[...this.popups,a],this.applyBodyLock(),this.update();})}confirm(e){return new Promise(n=>{let r=this.nextId++,i={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"confirm",variant:e.variant||"default",size:e.size||"small",icon:e.icon,resolve:n,onConfirm:e.onConfirm,onCancel:e.onCancel,buttons:[{label:e.cancelLabel||"Cancel",translateKey:e.cancelTranslateKey||"button.cancel",variant:"secondary",icon:"fas fa-times",onClick:async()=>{e.onCancel&&await e.onCancel(),this.closePopup(r,false);}},{label:e.confirmLabel||"Confirm",translateKey:e.confirmTranslateKey||"button.confirm",variant:e.variant==="danger"?"danger":"primary",icon:"fas fa-check",onClick:async()=>{e.onConfirm&&await e.onConfirm(),this.closePopup(r,true);}}]};this.popups=[...this.popups,i],this.applyBodyLock(),this.update();})}alert(e){return new Promise(n=>{let r=this.nextId++,i={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"alert",variant:e.variant||"info",size:e.size||"small",icon:e.icon,resolve:n,onConfirm:e.onConfirm,buttons:[{label:e.okLabel||"OK",translateKey:e.okTranslateKey||"popup.ok",variant:"primary",icon:"fas fa-check",onClick:async()=>{e.onConfirm&&await e.onConfirm(),this.closePopup(r,true);}}]};this.popups=[...this.popups,i],this.applyBodyLock(),this.update();})}prompt(e){return new Promise(n=>{let r=this.nextId++,i={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"prompt",variant:"default",icon:e.icon,inputValue:e.defaultValue||"",resolve:n,onConfirm:e.onConfirm,onCancel:e.onCancel,buttons:[{label:e.cancelLabel||"Cancel",translateKey:e.cancelTranslateKey||"popup.cancel",variant:"secondary",onClick:async()=>{e.onCancel&&await e.onCancel(),this.closePopup(r,null);}},{label:e.confirmLabel||"OK",translateKey:e.confirmTranslateKey||"popup.ok",variant:"primary",onClick:async()=>{let o=i.inputValue||"";e.onConfirm&&await e.onConfirm(o),this.closePopup(r,o);}}]};this.popups=[...this.popups,i],this.applyBodyLock();})}closePopup(e,n){let r=this.popups.find(i=>i.id===e);r?.resolve&&r.resolve(n),this.popups=this.popups.filter(i=>i.id!==e),this.popups.length===0&&this.removeBodyLock(),this.update();}closeAll(){this.popups.forEach(e=>{e.resolve&&e.resolve(false);}),this.popups=[],this.removeBodyLock(),this.update();}applyBodyLock(){document.body.style.overflow="hidden";}removeBodyLock(){document.body.style.overflow="";}setupKeyboardListener(){this.handleEscapeKey=e=>{if(e.key==="Escape"&&this.popups.length>0){let n=this.popups[this.popups.length-1];n.closeOnEscape!==false&&this.closePopup(n.id,false);}},document.addEventListener("keydown",this.handleEscapeKey);}};h([p],Z.prototype,"popups");var F=null;function Ae(s){if(F)return F;let t=s||document.createElement("div");return s||document.body.appendChild(t),F=new Z,F.mount(t),F}function M(){return F||(F=Ae()),F}var Kn={show:s=>M().show(s),confirm:s=>M().confirm(s),alert:s=>M().alert(s),prompt:s=>M().prompt(s),showForm:s=>M().showForm(s),closePopup:(s,t)=>M().closePopup(s,t),closeLastPopup:()=>M().closePopup(M().popups.length-1,false),closeFirstPopup:()=>M().closePopup(0,false),closeAll:()=>M().closeAll()};var P={container:"bb_tabbedview",header:"bb_tabbedviewHeader",tab:{base:"bb_tabbedviewTab",active:"bb_tabbedviewTab--active",disabled:"bb_tabbedviewTab--disabled",badge:"bb_tabbedviewBadge"},content:{container:"bb_tabbedviewContent",emptyState:"bb_tabbedviewEmptyState",error:"bb_tabbedviewError"}},x=class extends m{constructor(){super(...arguments);this.activeTabId="";this.tabs=[];this.position="top";this.style="default";this.className="";this.headerClassName="";this.contentClassName="";this.showTabCount=false;this.persistState=false;this.storageKey="tabbedview-active";this.currentTabComponent=null;}async onMount(){window.addEventListener("languagechange",()=>{this.update();});}onUnmount(){this.currentTabComponent&&typeof this.currentTabComponent.onUnmount=="function"&&this.currentTabComponent.onUnmount();}init(e){if(this.tabs=e.tabs,this.position=e.position||"top",this.style=e.style||"default",this.className=e.className||"",this.headerClassName=e.headerClassName||"",this.contentClassName=e.contentClassName||"",this.showTabCount=e.showTabCount||false,this.persistState=e.persistState||false,this.storageKey=e.storageKey||"tabbedview-active",this.onChange=e.onChange,this.persistState){let n=localStorage.getItem(this.storageKey);n&&this.tabs.find(r=>r.id===n)&&(this.activeTabId=n);}return this.activeTabId||(this.activeTabId=e.defaultTab||this.tabs[0]?.id||""),this.update(),this}async setActiveTab(e){let n=this.tabs.find(r=>r.id===e);!n||n.disabled||(this.currentTabComponent&&typeof this.currentTabComponent.onUnmount=="function"&&this.currentTabComponent.onUnmount(),this.currentTabComponent=null,this.activeTabId=e,this.persistState&&localStorage.setItem(this.storageKey,e),n.onActivate&&await n.onActivate(),this.onChange&&await this.onChange(e),this.update());}addTab(e){this.tabs=[...this.tabs,e],this.update();}removeTab(e){this.tabs=this.tabs.filter(n=>n.id!==e),this.activeTabId===e&&this.tabs.length>0&&(this.activeTabId=this.tabs[0].id),this.update();}updateTab(e,n){let r=this.tabs.find(i=>i.id===e);r&&(Object.assign(r,n),this.update());}getActiveTab(){return this.tabs.find(e=>e.id===this.activeTabId)}render(){let e=[P.container,`bb_tabbedview__--${this.position}`,`bb_tabbedview__--${this.style}`,this.className].filter(Boolean).join(" ");return createElement("div",{className:e},this.renderTabList(),this.renderTabContent())}renderTabList(){let e=[P.header,this.headerClassName].filter(Boolean).join(" ");return createElement("div",{className:e},...this.tabs.map(n=>this.renderTab(n)))}renderTab(e){let n=this.activeTabId===e.id,r=[P.tab.base,n?P.tab.active:"",e.disabled?P.tab.disabled:""].filter(Boolean).join(" "),i=e.translateKey?g(e.translateKey):e.label;return createElement("button",{key:e.id,className:r,onclick:()=>this.setActiveTab(e.id),disabled:e.disabled,"data-translate":e.translateKey,"aria-selected":n,role:"tab"},e.icon?createElement("i",{className:e.icon}):null,createElement("span",{},i),e.badge!==void 0&&e.badge!==null&&e.badge!==0?createElement("span",{className:P.tab.badge},typeof e.badge=="number"&&e.badge>99?"99+":String(e.badge)):null)}renderTabContent(){let e=[P.content.container,this.contentClassName].filter(Boolean).join(" "),n=this.getActiveTab();return n?createElement("div",{className:e,role:"tabpanel"},this.renderActiveTabContent(n)):createElement("div",{className:e},createElement("div",{className:P.content.emptyState},createElement("p",{},"No tab selected")))}renderActiveTabContent(e){if(e.component)try{if(e.component instanceof m){this.currentTabComponent=e.component;let n=this.currentTabComponent.render(),r={...n.props,ref:o=>{o&&this.currentTabComponent&&this.currentTabComponent.setElement(o),typeof n.props.ref=="function"&&n.props.ref(o);}},i={...n,props:r};return typeof this.currentTabComponent.onMount=="function"&&setTimeout(()=>{this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&this.currentTabComponent.onMount();},0),i}if(typeof e.component=="function"){let n=e.component;return n.prototype&&typeof n.prototype.render=="function"?(this.currentTabComponent||(this.currentTabComponent=new n,this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&setTimeout(()=>{this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&this.currentTabComponent.onMount();},0)),this.currentTabComponent.render()):n()}}catch(n){return console.error("Error rendering tab component:",n),createElement("div",{className:P.content.error},"Error rendering tab content")}return e.content?e.content:createElement("div",{className:P.content.emptyState},createElement("p",{},"No content available"))}};h([p],x.prototype,"activeTabId"),h([p],x.prototype,"tabs"),h([p],x.prototype,"position"),h([p],x.prototype,"style"),h([p],x.prototype,"className"),h([p],x.prototype,"headerClassName"),h([p],x.prototype,"contentClassName"),h([p],x.prototype,"showTabCount"),h([p],x.prototype,"persistState"),h([p],x.prototype,"storageKey");function He(s){let t=new x;return t.init(s),t}async function qn(s,t){let e=He(t);return await e.mount(s),e}var f={container:"bb_itemsLoaderContainer",list:"bb_itemsLoaderList",searchbar:"bb_itemsLoaderSearchbar",loading:"bb_itemsLoaderLoading",error:"bb_itemsLoaderError",trigger:"bb_itemsLoaderTrigger",end:"bb_itemsLoaderEnd",emptyState:"bb_tabbedviewEmptyState",button:"bb_btn",item:"bb_itemsLoader-item",formFieldInput:"bb_formFieldInput"},ue=class extends m{constructor(){super(...arguments);this.items=[];this.loadState={loading:false,error:null,hasMore:true,page:0,total:0};this.filters={};this.scrollContainer=null;this.loadMoreObserver=null;this.currentLoadMoreTrigger=null;this.loadMoreMutationObserver=null;this.visibilityObserver=null;this.viewedItems=new Set;this.dropdownIsOpen=false;this.itemsListContainer=null;this.searchInput=null;this.isUpdating=false;this.searchDebounceTimer=null;this.handleScroll=()=>{if(!this.scrollContainer||this.loadState.loading||!this.loadState.hasMore)return;let{scrollTop:e,scrollHeight:n,clientHeight:r}=this.scrollContainer;n-e-r<this.config.scrollThreshold&&this.loadMore();};this.handleItemClick=(e,n)=>{this.config.onItemClick?.(e,n);};}initialize(e){this.config={pageSize:10,loadMoreText:"Load More",loadingText:"Loading...",errorText:"Failed to load items",containerClassName:f.container,itemClassName:f.item,enableInfiniteScroll:true,scrollThreshold:200,enableSearch:false,searchPlaceholder:"Search...",searchFilterKey:"search",searchDebounceMs:300,enableVisibilityTracking:false,visibilityThreshold:.5,visibilityRootMargin:"0px",extractItems:n=>n.notifications||n.items||n.data||n.logs||[],extractTotal:n=>n.pagination?.total||n.total||n.count||0,...e},this.config.filters&&(this.filters={...this.config.filters}),this.config.initialItems&&(this.items=[...this.config.initialItems]);}async onMount(){this.items.length===0&&await this.loadMore(),this.config.enableInfiniteScroll&&this.setupInfiniteScroll(),this.config.scrollThreshold&&this.setupScrollListener(),this.config.enableVisibilityTracking&&this.setupVisibilityTracking();}onUnmount(){this.disconnectInfiniteScrollObserver(),this.disconnectVisibilityObserver(),this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null),this.scrollContainer&&(this.scrollContainer.removeEventListener("scroll",this.handleScroll),this.scrollContainer=null),this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);}async loadMore(){if(!(this.loadState.loading||!this.loadState.hasMore))try{let e=this.scrollContainer||this.findScrollContainer(),n=e?.scrollTop||0,r=e?.scrollHeight||0;this.loadState={...this.loadState,loading:!0,error:null},this.updateLoadingState();let i=this.loadState.page+1,o=this.buildUrl(i),a=await fetch(o,{credentials:"include",headers:this.buildHeaders()});if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let l=await a.json(),c=this.config.extractItems(l),u=this.config.extractTotal(l);this.items=[...this.items,...c],this.loadState={loading:!1,error:null,hasMore:this.items.length<u,page:i,total:u},this.updateLoadingState(),this.appendNewItems(c),e&&n>0&&(e.scrollTop=n,requestAnimationFrame(()=>{let y=e.scrollHeight-r;Math.abs(y)>10&&(e.scrollTop=n);})),this.reconnectInfiniteScrollObserver(),this.config.onLoadMore?.(i,this.items);}catch(e){this.loadState={...this.loadState,loading:false,error:e instanceof Error?e.message:this.config.errorText},this.updateLoadingState(),this.updateFooter(),this.config.onError?.(e instanceof Error?e:new Error("Unknown error"));}}async reload(){this.items=[],this.loadState={loading:false,error:null,hasMore:true,page:0,total:0},await this.loadMore();}async applyFilters(e){if(!this.isUpdating){this.isUpdating=true,this.filters={...e},this.items=[],this.loadState={loading:true,error:null,hasMore:true,page:0,total:0},this.updateLoadingState();try{let n=this.buildUrl(1),r=await fetch(n,{credentials:"include",headers:this.buildHeaders()});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);let i=await r.json(),o=this.config.extractItems(i),a=this.config.extractTotal(i);this.items=[...o],this.loadState={loading:!1,error:null,hasMore:this.items.length<a,page:1,total:a},this.itemsListContainer&&(this.itemsListContainer.innerHTML=""),this.element&&this.element.querySelectorAll(`.${f.trigger}, .${f.end}, .${f.error}, .${f.loading}, .${f.emptyState}`).forEach(l=>l.remove()),this.items.length>0?(this.itemsListContainer||(this.itemsListContainer=this.element?.querySelector(`.${f.list}`)),this.itemsListContainer&&this.appendNewItems(this.items)):this.updateFooter(),this.itemsListContainer=this.element?.querySelector(`.${f.list}`),this.reconnectInfiniteScrollObserver(),this.config.onLoadMore?.(1,this.items),this.config.onFiltersChange?.(this.filters);}catch(n){this.loadState={...this.loadState,loading:false,error:n instanceof Error?n.message:this.config.errorText},this.updateLoadingState(),this.config.onError?.(n instanceof Error?n:new Error("Unknown error"));}finally{this.isUpdating=false;}}}async handleSearch(e){this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{let n={...this.filters};e.trim()?n[this.config.searchFilterKey]=e.trim():delete n[this.config.searchFilterKey],await this.applyFilters(n);},this.config.searchDebounceMs);}updateItems(e){this.items=[...e],this.itemsListContainer&&(this.itemsListContainer.innerHTML="",this.appendNewItems(e));}setupVisibilityTracking(){if(!this.config.enableVisibilityTracking)return;this.visibilityObserver&&this.visibilityObserver.disconnect();let e=this.findScrollContainer();this.visibilityObserver=new IntersectionObserver(n=>{n.forEach(r=>{if(r.isIntersecting&&this.dropdownIsOpen){let i=r.target,o=parseInt(i.getAttribute("data-item-index")||"-1");if(o>=0&&o<this.items.length){let a=this.items[o],l=this.config.getItemId?.(a),c=this.config.shouldTrackItem?.(a)??true;l&&!this.viewedItems.has(l)&&c&&this.viewedItems.add(l);}}});},{root:e,rootMargin:this.config.visibilityRootMargin,threshold:this.config.visibilityThreshold}),this.observeTrackableItems();}observeTrackableItems(){if(!this.visibilityObserver||!this.itemsListContainer)return;this.itemsListContainer.querySelectorAll("[data-item-index]").forEach(n=>{let r=parseInt(n.getAttribute("data-item-index")||"-1");if(r>=0&&r<this.items.length){let i=this.items[r];(this.config.shouldTrackItem?.(i)??true)&&this.visibilityObserver.observe(n);}});}trackAlreadyVisibleItems(){if(!this.itemsListContainer)return;let e=this.findScrollContainer();if(!e)return;let n=this.itemsListContainer.querySelectorAll("[data-item-index]"),r=e.getBoundingClientRect();n.forEach(i=>{let o=parseInt(i.getAttribute("data-item-index")||"-1");if(o<0||o>=this.items.length)return;let a=this.items[o],l=this.config.getItemId?.(a);if(!l||this.viewedItems.has(l)||!(this.config.shouldTrackItem?.(a)??true))return;let u=i.getBoundingClientRect();u.top<r.bottom&&u.bottom>r.top&&u.top>=r.top-100&&u.bottom<=r.bottom+100&&this.viewedItems.add(l);});}disconnectVisibilityObserver(){this.visibilityObserver&&(this.visibilityObserver.disconnect(),this.visibilityObserver=null);}handleDropdownOpen(){this.dropdownIsOpen=true,this.viewedItems.clear(),this.config.enableVisibilityTracking&&(this.trackAlreadyVisibleItems(),this.observeTrackableItems()),this.config.onDropdownOpen?.();}async handleDropdownClose(){if(this.dropdownIsOpen=false,this.viewedItems.size>0&&this.config.onItemsViewed){let e=this.items.filter(n=>{let r=this.config.getItemId?.(n);return r&&this.viewedItems.has(r)});await this.config.onItemsViewed(e);}this.viewedItems.clear(),this.config.onDropdownClose?.();}async performBatchAction(e,n){this.config.onBatchAction&&await this.config.onBatchAction(e,n);}appendNewItems(e){if(this.itemsListContainer||(this.itemsListContainer=this.element?.querySelector(`.${f.list}`)),!this.itemsListContainer)return;let n=document.createDocumentFragment(),r=this.items.length-e.length;e.forEach((i,o)=>{let a=r+o,l=this.config.renderItem(i,a);l.setAttribute("data-item-index",a.toString()),this.config.onItemClick?(l.className=`${l.className} ${this.config.itemClassName} clickable`,l.onclick=()=>this.handleItemClick(i,a)):l.className=`${l.className} ${this.config.itemClassName}`,n.appendChild(l);}),this.itemsListContainer.appendChild(n),this.updateFooter(),this.config.enableVisibilityTracking&&this.dropdownIsOpen&&setTimeout(()=>this.observeTrackableItems(),100);}updateLoadingState(){let e=this.element?.querySelector(`.${f.container}`);if(!e)return;let n=e.querySelector(`.${f.loading}`);if(this.loadState.loading){if(!n){let r=this.renderLoading();n=this.createElementFromVNode(r),e.appendChild(n);}}else n&&n.remove();}updateFooter(){let e=this.element;if(e){if(e.querySelectorAll(`.${f.trigger}, .${f.end}, .${f.emptyState}`).forEach(n=>{n.remove();}),this.items.length===0&&!this.loadState.loading&&this.config.emptyStateConfig){let n=this.renderEmptyState(),r=createDOMElement(n);e.appendChild(r);return}if(this.loadState.hasMore&&!this.loadState.loading&&this.items.length>0){let n=this.renderLoadMoreTrigger(),r=createDOMElement(n);e.appendChild(r);}if(!this.loadState.hasMore&&this.items.length>0){let n=this.renderEndMessage(),r=createDOMElement(n);e.appendChild(r);}}}setupInfiniteScroll(){this.loadMoreObserver&&this.loadMoreObserver.disconnect(),this.loadMoreObserver=new IntersectionObserver(e=>{let[n]=e;n.isIntersecting&&!this.loadState.loading&&this.loadState.hasMore&&this.loadMore();},{threshold:.1,rootMargin:"50px"}),this.reconnectInfiniteScrollObserver();}reconnectInfiniteScrollObserver(){if(!this.config.enableInfiniteScroll||!this.loadMoreObserver)return;this.currentLoadMoreTrigger&&(this.loadMoreObserver.unobserve(this.currentLoadMoreTrigger),this.currentLoadMoreTrigger=null);let e=()=>{let n=this.element?.querySelector('[data-load-more-trigger="true"]');return n?(this.loadMoreObserver.observe(n),this.currentLoadMoreTrigger=n,true):false};e()||(this.loadMoreMutationObserver&&this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=new MutationObserver(()=>{e()&&this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null);}),this.element&&(this.loadMoreMutationObserver.observe(this.element,{childList:true,subtree:true}),setTimeout(()=>{this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null);},5e3)));}disconnectInfiniteScrollObserver(){this.loadMoreObserver&&this.currentLoadMoreTrigger&&(this.loadMoreObserver.unobserve(this.currentLoadMoreTrigger),this.currentLoadMoreTrigger=null);}setupScrollListener(){requestAnimationFrame(()=>{this.scrollContainer=this.findScrollContainer(),this.scrollContainer&&("scrollRestoration"in history&&(history.scrollRestoration="manual"),this.scrollContainer.addEventListener("scroll",this.handleScroll));});}findScrollContainer(){let e=[this.element?.closest(".bb_notificationsContent"),this.element?.closest(".bb_dropdownMenu"),this.element?.querySelector("[data-notifications-loader]"),this.element?.closest("[data-notifications-loader]"),this.element?.closest(".scrollbar-thin"),this.element?.parentElement,this.element];for(let n of e)if(n){let r=n;if(r.scrollHeight>r.clientHeight||r.classList.contains("scrollbar-thin"))return r}return null}buildUrl(e){if(typeof this.config.fetchUrl=="function")return this.config.fetchUrl(e,this.filters);let n=this.config.fetchUrl.includes("?")?"&":"?",r=new URLSearchParams({page:e.toString(),limit:this.config.pageSize.toString(),...this.filters});return `${this.config.fetchUrl}${n}${r}`}buildHeaders(){let e={"Content-Type":"application/json"},n=this.config.getAuthToken?.();return n&&(e.Authorization=`Bearer ${n}`),e}createElementFromVNode(e){if(typeof e.type!="string")throw new Error("Can only create elements from string types");let n=document.createElement(e.type);return e.props&&Object.entries(e.props).forEach(([r,i])=>{r==="className"?n.className=i:r==="style"?typeof i=="string"?n.setAttribute("style",i):typeof i=="object"&&i!==null&&Object.assign(n.style,i):r==="onclick"&&typeof i=="function"?n.addEventListener("click",i):r!=="children"&&r!=="ref"&&n.setAttribute(r,String(i));}),e.children&&e.children.forEach(r=>{r!=null&&(typeof r=="string"||typeof r=="number"?n.appendChild(document.createTextNode(String(r))):typeof r=="object"&&n.appendChild(this.createElementFromVNode(r)));}),n}render(){return createElement("div",{className:this.config.containerClassName},this.config.enableSearch?this.renderSearchBar():null,createElement("div",{className:f.list,ref:e=>{e&&(this.itemsListContainer=e);}}),this.loadState.error?this.renderError():null,this.loadState.loading?this.renderLoading():null,this.loadState.hasMore&&!this.loadState.loading&&this.items.length>0?this.renderLoadMoreTrigger():null,!this.loadState.hasMore&&this.items.length>0?this.renderEndMessage():null)}renderSearchBar(){return createElement("div",{className:f.searchbar},createElement("div",{className:"row gap-sm"},createElement("i",{className:"fas fa-search"}),createElement("input",{type:"text",className:f.formFieldInput,placeholder:this.config.searchPlaceholder,ref:e=>{e&&(this.searchInput=e,this.searchInput.addEventListener("input",n=>{let r=n.target.value;this.handleSearch(r);}));}})))}renderEmptyState(){let e=this.config.emptyStateConfig;return createElement("div",{className:f.emptyState},createElement("i",{className:`__icon ${e.icon}`}),createElement("h3",{className:"__title"},e.title),createElement("p",{className:"__desc"},e.description))}renderLoading(){return createElement("div",{className:f.loading},createElement("i",{className:"fas fa-spinner fa-spin"}),createElement("p",{},this.config.loadingText))}renderError(){return createElement("div",{className:f.error},createElement("i",{className:"fas fa-exclamation-triangle"}),createElement("p",{},this.loadState.error),createElement("button",{className:`${f.button} secondary`,onclick:()=>this.loadMore()},createElement("i",{className:"fas fa-redo"})," Retry"))}renderLoadMoreTrigger(){return createElement("div",{className:f.trigger,"data-load-more-trigger":"true",style:"height: 1px; visibility: hidden;"})}renderEndMessage(){return createElement("div",{className:f.end},createElement("i",{className:"fas fa-check-circle"}),g("All loaded",{count:String(this.loadState.total)}))}};function er(s){let t=new ue;return t.initialize(s),t}var de=class s{constructor(){this.dropdowns=new Map;this.hierarchy=new Map;this.setupGlobalClickHandler();}static getInstance(){return s.instance||(s.instance=new s),s.instance}register(t){this.dropdowns.set(t.config.id,t),t.config.parentId&&this.hierarchy.set(t.config.id,t.config.parentId);}unregister(t){this.dropdowns.delete(t),this.hierarchy.delete(t);}open(t){let e=this.dropdowns.get(t);e&&(this.closeSiblings(t),e.setOpen(true));}close(t){let e=this.dropdowns.get(t);e&&(e.setOpen(false),this.closeChildren(t));}closeAll(){Array.from(this.dropdowns.values()).filter(e=>!e.config.parentId).forEach(e=>this.close(e.config.id));}destroy(){this.clickHandler&&typeof window<"u"&&document.removeEventListener("click",this.clickHandler,true),this.dropdowns.clear(),this.hierarchy.clear();}isAncestor(t,e){let n=e;for(;n;){if(n===t)return true;n=this.hierarchy.get(n);}return false}isDescendant(t,e){return this.isAncestor(e,t)}getAncestors(t){let e=new Set,n=t;for(;n;){let r=this.hierarchy.get(n);if(r)e.add(r),n=r;else break}return e}getDescendants(t){let e=new Set,n=r=>{Array.from(this.hierarchy.entries()).filter(([o,a])=>a===r).map(([o,a])=>o).forEach(o=>{e.add(o),n(o);});};return n(t),e}closeSiblings(t){let e=this.dropdowns.get(t);if(!e)return;let n=e.config.parentId;Array.from(this.dropdowns.values()).filter(i=>i.config.parentId===n&&i.config.id!==t).forEach(i=>this.close(i.config.id));}closeChildren(t){Array.from(this.dropdowns.values()).filter(n=>n.config.parentId===t).forEach(n=>this.close(n.config.id));}hasOpenDropdowns(){return Array.from(this.dropdowns.values()).some(t=>t.isOpen)}findDropdownForElement(t){let e=t;for(;e&&e!==document.body;){let n=e.getAttribute("data-dropdown-id");if(n)return n;e=e.parentElement;}return null}setupGlobalClickHandler(){typeof window>"u"||(this.clickHandler=t=>{let e=t.target;if(!this.hasOpenDropdowns())return;let n=this.findDropdownForElement(e);if(!n){this.closeAll();return}if(this.dropdowns.get(n)?.config.preventAutoClose||e.closest(".bb_dropdownTrigger"))return;if(e.closest(".bb_dropdownMenu")){let a=this.getAncestors(n),l=this.getDescendants(n);Array.from(this.dropdowns.values()).filter(u=>!u.config.parentId).forEach(u=>{let d=u.config.id;d===n||a.has(d)||l.has(d)||this.isDescendant(n,d)||this.close(d);});}},document.addEventListener("click",this.clickHandler,true));}},W=de.getInstance(),he=class extends m{constructor(e){super();this.isOpen=false;this.mounted=false;this.config={closeOnItemClick:true,preventAutoClose:false,...e};}onMount(){this.mounted=true,W.register(this);}onUnmount(){this.mounted=false,W.unregister(this.config.id);}setOpen(e){this.isOpen!==e&&(this.isOpen=e,e?this.config.onOpen?.():this.config.onClose?.(),this.updateDOM());}toggle(e){e.preventDefault(),e.stopPropagation(),this.isOpen?W.close(this.config.id):W.open(this.config.id);}handleItemClick(e,n){if(e.disabled){n.preventDefault(),n.stopPropagation();return}this.config.closeOnItemClick&&(n.preventDefault(),n.stopPropagation(),W.close(this.config.id)),e.onclick?.(n);}render(){let e=this.renderTrigger(),n=this.isOpen?this.renderMenu():null;return createElement("div",{className:`bb_dropdown bb_dropdown--${this.config.position||"left"} ${this.isOpen?"bb_dropdown--open":""}`,"data-dropdown-id":this.config.id},e,n)}updateDOM(){if(!this.mounted||!this.element)return;this.isOpen?this.element.classList.add("bb_dropdown--open"):this.element.classList.remove("bb_dropdown--open");let n=this.element.querySelector(".bb_dropdownTrigger")?.nextElementSibling;if(this.isOpen){if(!n||!n.classList.contains("bb_dropdownMenu")){let r=this.renderMenu(),i=this.createElementFromVNode(r);this.element.appendChild(i);}}else n&&n.classList.contains("bb_dropdownMenu")&&n.remove();}createElementFromVNode(e){if(typeof e.type=="string"){let n=document.createElement(e.type);return e.props&&Object.entries(e.props).forEach(([r,i])=>{r==="className"?n.className=i:r==="onclick"&&typeof i=="function"?n.addEventListener("click",i):r!=="children"&&r!=="key"&&n.setAttribute(r,String(i));}),e.children&&e.children.forEach(r=>{r!=null&&(typeof r=="string"||typeof r=="number"?n.appendChild(document.createTextNode(String(r))):typeof r=="object"&&n.appendChild(this.createElementFromVNode(r)));}),n}return document.createElement("div")}renderTrigger(){let e=this.config.trigger.element?.(),n=["bb_dropdownTrigger",this.config.trigger.className||""].filter(Boolean).join(" ");return e?createElement("button",{className:n,onclick:r=>this.toggle(r)},e):createElement("button",{className:n,onclick:r=>this.toggle(r)},this.config.trigger.icon?createElement("i",{className:this.config.trigger.icon}):null,this.config.trigger.text?createElement("span",{},this.config.trigger.text):null,createElement("i",{className:`bb_dropdownArrow fas fa-chevron-down ${this.isOpen?"bb_dropdownArrow--open":""}`}))}renderMenu(){return createElement("div",{className:"bb_dropdownMenu",onclick:e=>{this.config.preventAutoClose&&e.stopPropagation();}},this.config.items.map((e,n)=>{if(e==="divider")return createElement("div",{className:"bb_dropdown__divider",key:`divider-${n}`});let r=["bb_dropdownItem",e.className||"",e.disabled?"bb_dropdownItem--disabled":"",e.selected?"bb_dropdownItem--selected":""].filter(Boolean).join(" "),i={key:e.id||`item-${n}`,className:r,onclick:o=>this.handleItemClick(e,o)};return e.disabled&&(i.disabled=true),createElement("button",i,e.icon?createElement("i",{className:e.icon}):null,createElement("span",{},e.label))}))}};function or(s){return new he(s)}function De(s,t){let e=null;return (...n)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,s(...n);},t);}}function Ue(s,t){let e=0,n=null;return (...r)=>{let i=Date.now(),o=i-e;o>=t?(e=i,s(...r)):n||(n=setTimeout(()=>{e=Date.now(),n=null,s(...r);},t-o));}}function Be(...s){let t=[];for(let e of s)if(e){if(typeof e=="string")t.push(e);else if(typeof e=="object")for(let[n,r]of Object.entries(e))r&&t.push(n);}return t.join(" ")}function ze(s,t="YYYY-MM-DD"){let e=s instanceof Date?s:new Date(s);if(isNaN(e.getTime()))throw new Error("Invalid date provided to formatDate");let n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),l=String(e.getSeconds()).padStart(2,"0");return t.replace("YYYY",String(n)).replace("MM",r).replace("DD",i).replace("HH",o).replace("mm",a).replace("ss",l)}function H(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s))return s.map(t=>H(t));if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){let t=new Map;return s.forEach((e,n)=>{t.set(H(n),H(e));}),t}if(s instanceof Set){let t=new Set;return s.forEach(e=>{t.add(H(e));}),t}if(Object.prototype.toString.call(s)==="[object Object]"){let t={};for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(t[e]=H(s[e]));return t}return s}function ge(s,...t){if(!t.length)return s;let e=t.shift();if(!e)return s;if(X(s)&&X(e)){for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let r=e[n],i=s[n];r!==void 0&&(X(r)&&!Array.isArray(r)?((!i||!X(i))&&(s[n]={}),ge(s[n],r)):s[n]=r);}}return ge(s,...t)}function X(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}var pe=0;function je(s="id"){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,11);pe=(pe||0)+1;let n=pe.toString(36);return `${s}_${t}_${e}_${n}`}function qe(s){if(s<0)throw new Error("Sleep duration must be non-negative");return new Promise(t=>setTimeout(t,s))}function We(s){return s==null?true:typeof s=="string"?s.trim().length===0:Array.isArray(s)?s.length===0:s instanceof Map||s instanceof Set?s.size===0:typeof s=="object"?Object.keys(s).length===0:false}function Ge(s){return s?s.charAt(0).toUpperCase()+s.slice(1):""}function Je(s){return s?s.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase():""}function Ce(s){return s?s.replace(/[-_\s]+(.)?/g,(t,e)=>e?e.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase()):""}function Qe(s){if(!s)return "";let t=Ce(s);return t.charAt(0).toUpperCase()+t.slice(1)}function Ye(s,t,e="..."){return !s||s.length<=t?s:s.substring(0,t-e.length)+e}function Ze(s){let t={},e=s.replace(/^\?/,"");if(!e)return t;let n=e.split("&");for(let r of n){let[i,o]=r.split("=").map(decodeURIComponent);if(!i)continue;let a=o||"";if(i.endsWith("[]")){let l=i.slice(0,-2);t[l]||(t[l]=[]),t[l].push(a);}else t[i]=a;}return t}function Xe(s){let t=[];for(let[e,n]of Object.entries(s))if(n!=null)if(Array.isArray(n))for(let r of n)r!=null&&t.push(`${encodeURIComponent(e)}[]=${encodeURIComponent(String(r))}`);else t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}function et(s,t,e){return Math.min(Math.max(s,t),e)}function tt(){return typeof window<"u"&&typeof document<"u"}function nt(s,t){try{return JSON.parse(s)}catch{return t}}var lr={debounce:De,throttle:Ue,classNames:Be,formatDate:ze,deepClone:H,deepMerge:ge,uniqueId:je,sleep:qe,isEmpty:We,capitalize:Ge,kebabCase:Je,camelCase:Ce,pascalCase:Qe,truncate:Ye,parseQuery:Ze,stringifyQuery:Xe,clamp:et,isBrowser:tt,safeJsonParse:nt};var Se=class{constructor(t){this.observer=null;this.observedElements=new Map;this.observer=new IntersectionObserver(e=>{e.forEach(n=>{let r=this.observedElements.get(n.target)??false,i=n.isIntersecting;i&&!r?(this.observedElements.set(n.target,true),t.onEnter?.(n),t.once&&this.unobserve(n.target)):!i&&r&&(this.observedElements.set(n.target,false),t.onExit?.(n));});},{root:t.root||null,rootMargin:t.rootMargin||"0px",threshold:t.threshold??.1});}observe(t){this.observer&&(this.observer.observe(t),this.observedElements.set(t,false));}unobserve(t){this.observer&&(this.observer.unobserve(t),this.observedElements.delete(t));}disconnect(){this.observer&&(this.observer.disconnect(),this.observedElements.clear());}};function ur(s,t){let e=new IntersectionObserver(n=>{n.forEach(r=>{r.isIntersecting&&(t(r),e.unobserve(s));});},{threshold:.1});return e.observe(s),()=>e.disconnect()}function fe(s){let t=typeof s=="string"?new Date(s):s,n=new Date().getTime()-t.getTime(),r=Math.floor(n/1e3),i=Math.floor(r/60),o=Math.floor(i/60),a=Math.floor(o/24),l=Math.floor(a/7),c=Math.floor(a/30),u=Math.floor(a/365),d="";return r<0?d=g("time.just_now"):r<60?d=g("time.just_now"):i<2?d=g("time.minute_ago"):i<60?d=g("time.minutes_ago",{count:i.toString()}):o<2?d=g("time.hour_ago"):o<24?d=g("time.hours_ago",{count:o.toString()}):a<2?d=g("time.day_ago"):a<7?d=g("time.days_ago",{count:a.toString()}):l<2?d=g("time.week_ago"):l<4?d=g("time.weeks_ago",{count:l.toString()}):c<2?d=g("time.month_ago"):c<12?d=g("time.months_ago",{count:c.toString()}):u<2?d=g("time.year_ago"):d=g("time.years_ago",{count:u.toString()}),{formatted:d,originalDate:t.toISOString(),title:t.toLocaleString()}}function pr(s){let{formatted:t,title:e}=fe(s);return {text:t,title:e}}function gr(s){return fe(s).formatted}function fr(s){return fe(s).title}setConfig({devMode:false,sanitizeHTML:true});export{te as CombinedContext,m as Component,G as Context,he as Dropdown,z as I18nManager,ue as ItemsLoader,I as Loader,Z as Popup,ve as Provider,ie as Router,_e as SmartForm,V as SmartFormComponent,ae as Store,D as StyleManager,x as TabbedView,Y as Toast,Se as VisibilityObserver,Ce as camelCase,Ge as capitalize,et as clamp,Be as classNames,Pe as clearHookContext,qt as client,dt as computed,Ut as connect,vt as createCombinedContext,Dt as createComputedStore,mt as createContext,or as createDropdown,Pt as createFunctionalComponent,er as createItemsLoader,Re as createStore,He as createTabbedView,sn as createTranslator,be as css,De as debounce,H as deepClone,ge as deepMerge,ze as formatDate,fe as formatRelativeTime,gr as formatTimeAgo,Zt as getCurrentLanguage,oe as getCurrentPath,S as getI18n,M as getPopup,At as getQueryParam,Oe as getQueryParams,tn as getSupportedLanguages,pr as getTimeDisplay,fr as getTimeTitle,q as getToast,rn as getTranslations,Ot as goBack,Rt as goForward,nn as hasKey,Ae as initPopup,Fe as initToast,an as initializeI18n,tt as isBrowser,$t as isCurrentPath,Vt as isCurrentPathPrefix,We as isEmpty,Je as kebabCase,on as loadFromUrl,Xt as loadLanguage,cn as loadLanguageFile,en as loadTranslations,qn as mountTabbedView,we as navigate,Kt as navigateWithQuery,ur as observeVisibility,Ze as parseQuery,Qe as pascalCase,Kn as popup,Ft as reloadRoute,R as router,nt as safeJsonParse,U as scheduler,Me as setHookContext,Qt as setLanguage,Yt as setLanguageAsync,ln as setupI18n,qe as sleep,p as state,Xe as stringifyQuery,g as t,le as tHtml,Jt as tLang,Ue as throttle,fn as toast,Ye as truncate,je as uniqueId,re as useCallback,bt as useContext,Ct as useDebounce,O as useEffect,Mt as useEventListener,kt as useFetch,xt as useInterval,_t as useLocalStorage,Ie as useMemo,St as usePrevious,Tt as useReducer,se as useRef,N as useState,Et as useToggle,Lt as useWindowSize,lr as utils,ht as watch};//# sourceMappingURL=main.js.map
193
118
  //# sourceMappingURL=main.js.map