@je-es/client 0.0.1 → 0.0.2
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/README.md +1 -1
- package/dist/main.cjs +5 -5
- package/dist/main.cjs.map +1 -1
- package/dist/main.js +5 -5
- package/dist/main.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
</div>
|
|
9
9
|
|
|
10
10
|
<div align="center">
|
|
11
|
-
<img src="https://img.shields.io/badge/v-0.0.
|
|
11
|
+
<img src="https://img.shields.io/badge/v-0.0.2-black"/>
|
|
12
12
|
<img src="https://img.shields.io/badge/🔥-@je--es-black"/>
|
|
13
13
|
<br>
|
|
14
14
|
<img src="https://github.com/je-es/client/actions/workflows/ci.yml/badge.svg" alt="CI" />
|
package/dist/main.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
'use strict';var vdom=require('@je-es/vdom'),capi=require('@je-es/capi');var ut=Object.defineProperty;var
|
|
1
|
+
'use strict';var vdom=require('@je-es/vdom'),capi=require('@je-es/capi');var ut=Object.defineProperty;var w=(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&&ut(t,e,n),n};var T=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
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 h=`[data-scope="${e}"] ${u}`;n.push(`${h} ${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 D(o,...t){let e="";for(let r=0;r<o.length;r++)e+=o[r],r<t.length&&(e+=t[r]);return e}var L=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}},x=new L;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&&x.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,x.schedule(()=>{this._isScheduledForUpdate=false,this._updateBatch.clear(),this._performUpdate();})));}forceUpdate(){!this._isMounted||this._isUnmounting||x.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);vdom.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 E=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){if(this.isNavigating){console.warn("Navigation already in progress");return}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 vdom.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;console.log("\u{1F3A8} Mounting:",r.name||"Component"),this.currentComponent=new r,this.currentComponent&&(await this.currentComponent.mount(this.routerOutlet),console.log("\u2705 Mounted successfully!"));}catch(e){throw this._renderError(t.path,e),e}}async _resolveComponent(t){if(console.log("\u{1F50D} Resolving component..."),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 console.log("\u2705 Direct component class"),t;console.log("\u{1F4E6} Lazy loading...");try{let s=await t();return console.log("\u{1F4E6} Module keys:",Object.keys(s)),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=`
|
|
3
|
+
`)}static clear(){for(let[,t]of this.styles)t.parentElement&&t.parentElement.removeChild(t);this.styles.clear();}};function D(o,...t){let e="";for(let r=0;r<o.length;r++)e+=o[r],r<t.length&&(e+=t[r]);return e}var L=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}},x=new L;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&&x.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,x.schedule(()=>{this._isScheduledForUpdate=false,this._updateBatch.clear(),this._performUpdate();})));}forceUpdate(){!this._isMounted||this._isUnmounting||x.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=T.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&&T.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);vdom.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 E=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){if(this.isNavigating){console.warn("Navigation already in progress");return}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 vdom.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
4
|
<div style="padding: 2rem; background: #fee; border: 2px solid #c00;
|
|
5
5
|
border-radius: 8px; margin: 2rem;">
|
|
6
6
|
<h2 style="color: #c00; margin-top: 0;">\u26A0\uFE0F Failed to Load Component</h2>
|
|
7
7
|
<p><strong>Route:</strong> ${t}</p>
|
|
8
8
|
<p><strong>Error:</strong> ${r}</p>
|
|
9
9
|
</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},{}):{}}},_=new E;function pt(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{let e=await Bun.build({entrypoints:[t.build.entry],outdir:t.build.output.substring(0,t.build.output.lastIndexOf("/")),target:"browser",minify:!1,sourcemap:t.build.sourcemap?"external":"none",splitting:t.build.optimization?.splitChunks??!1,naming:{entry:t.build.output.substring(t.build.output.lastIndexOf("/")+1)}});if(!e.success)throw console.error("\u274C Build failed:",e.logs),new Error("Build failed");console.log("\u2705 Build completed successfully!"),console.log(`\u{1F4E6} Output: ${t.build.output}`);}catch(e){throw console.error("\u274C Build error:",e),e}},init(){if(console.log("\u{1F680} 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}),capi.configureApi(e);}t.router&&t.app?.routes&&(_.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&_.beforeEach(t.router.beforeEach),t.router.afterEach&&_.afterEach(t.router.afterEach)),t.app?.root&&(document.querySelector(t.app.root)?console.log("\u2705 Client initialized successfully!"):console.error(`\u274C Root element "${t.app.root}" not found`)),t.devTools?.enabled&&this._enableDevTools();},_enableDevTools(){console.log("\u{1F6E0}\uFE0F Dev tools enabled"),window.__JEES_DEV__={router:_,config:t,version:"0.0.1"},t.devTools?.showRouterInfo&&_.afterEach((e,r)=>{console.log("\u{1F4CD} Route changed:",{from:r.path,to:e.path,params:e.params,query:e.query});});},getConfig(){return t}}}var R=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 U(o){return new R(o)}function ft(o,t){let e=U({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 mt(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(h){let d=this,f=d[c];f!==h&&(d[c]=h,typeof d._invalidateAllComputed=="function"&&d._invalidateAllComputed(),typeof d._triggerWatchers=="function"&&d._triggerWatchers(a,h,f),d._isMounted&&typeof d.update=="function"&&d.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 gt(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,h=`_computed_cache_${c}`,d=`_computed_dirty_${c}`;return function(){let f=this;return f[d]===void 0&&(f[d]=true),f[d]===true&&(f[h]=u.call(this),f[d]=false),f[h]}}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 vt(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(){console.log("\u{1F4DD} SmartForm mounted with",this.fields.length,"fields");}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;for(let r of this.fields){let n=this.validateField(r,this.formData[r.name]);r.error=n,r.touched=true,n&&(e=false);}return this.update(),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 capi.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();}}renderField(e){let r=this.formData[e.name]||"",n=e.touched&&e.error;switch(e.type){case "textarea":return vdom.html`
|
|
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},{}):{}}},C=new E;function pt(o){let t=o;return {async build(){if(!t.build){console.warn("No build configuration provided");return}try{let e=await Bun.build({entrypoints:[t.build.entry],outdir:t.build.output.substring(0,t.build.output.lastIndexOf("/")),target:"browser",minify:!1,sourcemap:t.build.sourcemap?"external":"none",splitting:t.build.optimization?.splitChunks??!1,naming:{entry:t.build.output.substring(t.build.output.lastIndexOf("/")+1)}});if(!e.success)throw console.error("\u274C Build failed:",e.logs),new Error("Build failed")}catch(e){throw console.error("\u274C Build error:",e),e}},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}),capi.configureApi(e);}t.router&&t.app?.routes&&(C.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&C.beforeEach(t.router.beforeEach),t.router.afterEach&&C.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:C,config:t,version:"0.0.1"};},getConfig(){return t}}}var R=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 U(o){return new R(o)}function ft(o,t){let e=U({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 mt(o,t,e){return o.subscribe(n=>{let s=e(n);Object.assign(t,s),typeof t.update=="function"&&t.update();})}function _(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(h){let d=this,f=d[c];f!==h&&(d[c]=h,typeof d._invalidateAllComputed=="function"&&d._invalidateAllComputed(),typeof d._triggerWatchers=="function"&&d._triggerWatchers(a,h,f),d._isMounted&&typeof d.update=="function"&&d.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 gt(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,h=`_computed_cache_${c}`,d=`_computed_dirty_${c}`;return function(){let f=this;return f[d]===void 0&&(f[d]=true),f[d]===true&&(f[h]=u.call(this),f[d]=false),f[h]}}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 vt(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;for(let r of this.fields){let n=this.validateField(r,this.formData[r.name]);r.error=n,r.touched=true,n&&(e=false);}return this.update(),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 capi.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();}}renderField(e){let r=this.formData[e.name]||"",n=e.touched&&e.error;switch(e.type){case "textarea":return vdom.html`
|
|
11
11
|
<div class="form-field ${e.className||""}">
|
|
12
12
|
${e.label?vdom.html`<label for=${e.name}>${e.label}</label>`:""}
|
|
13
13
|
<textarea
|
|
@@ -165,9 +165,9 @@
|
|
|
165
165
|
background: #d1fae5;
|
|
166
166
|
color: #065f46;
|
|
167
167
|
}
|
|
168
|
-
`}};
|
|
168
|
+
`}};w([_],g.prototype,"fields"),w([_],g.prototype,"formData"),w([_],g.prototype,"isSubmitting"),w([_],g.prototype,"submitError"),w([_],g.prototype,"submitSuccess");function _t(o){return new g(o).render()}function K(o,t){let e=null;return (...r)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,o(...r);},t);}}function B(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 z(...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 q(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 y(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=>y(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(y(r),y(e));}),t}if(o instanceof Set){let t=new Set;return o.forEach(e=>{t.add(y(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]=y(o[e]));return t}return o}function $(o,...t){if(!t.length)return o;let e=t.shift();if(!e)return o;if(P(o)&&P(e)){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r],s=o[r];n!==void 0&&(P(n)&&!Array.isArray(n)?((!s||!P(s))&&(o[r]={}),$(o[r],n)):o[r]=n);}}return $(o,...t)}function P(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}var A=0;function W(o="id"){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,11);A=(A||0)+1;let r=A.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 G(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 Q(o){return o?o.charAt(0).toUpperCase()+o.slice(1):""}function J(o){return o?o.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase():""}function H(o){return o?o.replace(/[-_\s]+(.)?/g,(t,e)=>e?e.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase()):""}function Y(o){if(!o)return "";let t=H(o);return t.charAt(0).toUpperCase()+t.slice(1)}function Z(o,t,e="..."){return !o||o.length<=t?o:o.substring(0,t-e.length)+e}function X(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 tt(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 et(o,t,e){return Math.min(Math.max(o,t),e)}function rt(){return typeof window<"u"&&typeof document<"u"}function nt(o,t){try{return JSON.parse(o)}catch{return t}}var yt={debounce:K,throttle:B,classNames:z,formatDate:q,deepClone:y,deepMerge:$,uniqueId:W,sleep:j,isEmpty:G,capitalize:Q,kebabCase:J,camelCase:H,pascalCase:Y,truncate:Z,parseQuery:X,stringifyQuery:tt,clamp:et,isBrowser:rt,safeJsonParse:nt};var k=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 Tt(o){return new k(o)}var I=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 vdom.html`
|
|
169
169
|
<div class="context-provider" style="display: contents;">
|
|
170
170
|
${t}
|
|
171
171
|
</div>
|
|
172
|
-
`}};function Ct(o,t){let e=o.subscribe(()=>{t.isMounted&&t.update();});return t.subscribe(()=>e),o.value}var V=class{constructor(t){this.contexts=new Map;for(let[e,r]of Object.entries(t))this.contexts.set(e,new k(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 St(o){return new V(o)}var p=null,S=0,O=new WeakMap;function ot(o){p=o,S=0;}function st(){p=null,S=0;}function M(o){return O.has(o)||O.set(o,[]),O.get(o)}function v(o){if(!p)throw new Error("useState must be called inside a component");let t=p,e=S++,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(!p)throw new Error("useEffect must be called inside a component");let e=p,r=S++,n=M(e),s=n[r];if(!s||!t||!at(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 it(o,t){if(!p)throw new Error("useMemo must be called inside a component");let e=S++,r=M(p),n=r[e];return (!n||!at(n.deps,t))&&(r[e]={value:o(),deps:[...t]}),r[e].value}function F(o,t){return it(()=>o,t)}function N(o){if(!p)throw new Error("useRef must be called inside a component");let t=S++,e=M(p);return e[t]===void 0&&(e[t]={value:{current:o}}),e[t].value}function xt(o,t){let[e,r]=v(t),n=F(s=>{r(a=>o(a,s));},[o]);return [e,n]}function kt(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 Et(o,t){let[e,r]=v(o);return b(()=>{let n=setTimeout(()=>{r(o);},t);return ()=>{clearTimeout(n);}},[o,t]),e}function Rt(o){let t=N(void 0);return b(()=>{t.current=o;}),t.current}function Pt(o=false){let[t,e]=v(o),r=F(()=>{e(n=>!n);},[]);return [t,r]}function $t(o,t){let e=N(o);b(()=>{e.current=o;},[o]),b(()=>{if(t===null)return;let r=setInterval(()=>e.current(),t);return ()=>clearInterval(r)},[t]);}function Vt(o,t){let[e,r]=v(null),[n,s]=v(true),[a,i]=v(null),u=F(async()=>{s(true),i(null);try{let c=await fetch(o,t);if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);let h=await c.json();r(h);}catch(c){i(c);}finally{s(false);}},[o]);return b(()=>{u();},[u]),{data:e,loading:n,error:a,refetch:u}}function Mt(){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 Ft(o,t,e=window){let r=N(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 Nt(o,t){class e extends m{render(){ot(this);try{return o(this.props)}finally{st();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function at(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}Object.defineProperty(exports,"createDOMElement",{enumerable:true,get:function(){return vdom.createDOMElement}});Object.defineProperty(exports,"createElement",{enumerable:true,get:function(){return vdom.createElement}});Object.defineProperty(exports,"html",{enumerable:true,get:function(){return vdom.html}});Object.defineProperty(exports,"patch",{enumerable:true,get:function(){return vdom.patch}});Object.defineProperty(exports,"api",{enumerable:true,get:function(){return capi.api}});Object.defineProperty(exports,"configureApi",{enumerable:true,get:function(){return capi.configureApi}});Object.defineProperty(exports,"getApiConfig",{enumerable:true,get:function(){return capi.getApiConfig}});Object.defineProperty(exports,"http",{enumerable:true,get:function(){return capi.http}});Object.defineProperty(exports,"resetApiConfig",{enumerable:true,get:function(){return capi.resetApiConfig}});exports.CombinedContext=V;exports.Component=m;exports.Context=k;exports.Provider=
|
|
172
|
+
`}};function Ct(o,t){let e=o.subscribe(()=>{t.isMounted&&t.update();});return t.subscribe(()=>e),o.value}var V=class{constructor(t){this.contexts=new Map;for(let[e,r]of Object.entries(t))this.contexts.set(e,new k(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 St(o){return new V(o)}var p=null,S=0,O=new WeakMap;function ot(o){p=o,S=0;}function st(){p=null,S=0;}function M(o){return O.has(o)||O.set(o,[]),O.get(o)}function v(o){if(!p)throw new Error("useState must be called inside a component");let t=p,e=S++,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(!p)throw new Error("useEffect must be called inside a component");let e=p,r=S++,n=M(e),s=n[r];if(!s||!t||!at(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 it(o,t){if(!p)throw new Error("useMemo must be called inside a component");let e=S++,r=M(p),n=r[e];return (!n||!at(n.deps,t))&&(r[e]={value:o(),deps:[...t]}),r[e].value}function F(o,t){return it(()=>o,t)}function N(o){if(!p)throw new Error("useRef must be called inside a component");let t=S++,e=M(p);return e[t]===void 0&&(e[t]={value:{current:o}}),e[t].value}function xt(o,t){let[e,r]=v(t),n=F(s=>{r(a=>o(a,s));},[o]);return [e,n]}function kt(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 Et(o,t){let[e,r]=v(o);return b(()=>{let n=setTimeout(()=>{r(o);},t);return ()=>{clearTimeout(n);}},[o,t]),e}function Rt(o){let t=N(void 0);return b(()=>{t.current=o;}),t.current}function Pt(o=false){let[t,e]=v(o),r=F(()=>{e(n=>!n);},[]);return [t,r]}function $t(o,t){let e=N(o);b(()=>{e.current=o;},[o]),b(()=>{if(t===null)return;let r=setInterval(()=>e.current(),t);return ()=>clearInterval(r)},[t]);}function Vt(o,t){let[e,r]=v(null),[n,s]=v(true),[a,i]=v(null),u=F(async()=>{s(true),i(null);try{let c=await fetch(o,t);if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);let h=await c.json();r(h);}catch(c){i(c);}finally{s(false);}},[o]);return b(()=>{u();},[u]),{data:e,loading:n,error:a,refetch:u}}function Mt(){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 Ft(o,t,e=window){let r=N(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 Nt(o,t){class e extends m{render(){ot(this);try{return o(this.props)}finally{st();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function at(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}vdom.setConfig({devMode:false,sanitizeHTML:true});Object.defineProperty(exports,"createDOMElement",{enumerable:true,get:function(){return vdom.createDOMElement}});Object.defineProperty(exports,"createElement",{enumerable:true,get:function(){return vdom.createElement}});Object.defineProperty(exports,"html",{enumerable:true,get:function(){return vdom.html}});Object.defineProperty(exports,"patch",{enumerable:true,get:function(){return vdom.patch}});Object.defineProperty(exports,"api",{enumerable:true,get:function(){return capi.api}});Object.defineProperty(exports,"configureApi",{enumerable:true,get:function(){return capi.configureApi}});Object.defineProperty(exports,"getApiConfig",{enumerable:true,get:function(){return capi.getApiConfig}});Object.defineProperty(exports,"http",{enumerable:true,get:function(){return capi.http}});Object.defineProperty(exports,"resetApiConfig",{enumerable:true,get:function(){return capi.resetApiConfig}});exports.CombinedContext=V;exports.Component=m;exports.Context=k;exports.Provider=I;exports.Router=E;exports.SmartForm=_t;exports.SmartFormComponent=g;exports.Store=R;exports.StyleManager=T;exports.camelCase=H;exports.capitalize=Q;exports.clamp=et;exports.classNames=z;exports.clearHookContext=st;exports.client=pt;exports.computed=gt;exports.connect=mt;exports.createCombinedContext=St;exports.createComputedStore=ft;exports.createContext=Tt;exports.createFunctionalComponent=Nt;exports.createStore=U;exports.css=D;exports.debounce=K;exports.deepClone=y;exports.deepMerge=$;exports.formatDate=q;exports.isBrowser=rt;exports.isEmpty=G;exports.kebabCase=J;exports.parseQuery=X;exports.pascalCase=Y;exports.router=C;exports.safeJsonParse=nt;exports.scheduler=x;exports.setHookContext=ot;exports.sleep=j;exports.state=_;exports.stringifyQuery=tt;exports.throttle=B;exports.truncate=Z;exports.uniqueId=W;exports.useCallback=F;exports.useContext=Ct;exports.useDebounce=Et;exports.useEffect=b;exports.useEventListener=Ft;exports.useFetch=Vt;exports.useInterval=$t;exports.useLocalStorage=kt;exports.useMemo=it;exports.usePrevious=Rt;exports.useReducer=xt;exports.useRef=N;exports.useState=v;exports.useToggle=Pt;exports.useWindowSize=Mt;exports.utils=yt;exports.watch=vt;//# sourceMappingURL=main.cjs.map
|
|
173
173
|
//# sourceMappingURL=main.cjs.map
|