@je-es/client 0.0.4 → 0.0.6
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 +10 -10
- package/dist/main.cjs.map +1 -1
- package/dist/main.d.cts +10 -1
- package/dist/main.d.ts +10 -1
- package/dist/main.js +10 -10
- package/dist/main.js.map +1 -1
- package/package.json +1 -1
package/dist/main.d.cts
CHANGED
|
@@ -129,6 +129,7 @@ declare abstract class Component<P = Record<string, unknown>, S = Record<string,
|
|
|
129
129
|
private _refs;
|
|
130
130
|
private _subscriptions;
|
|
131
131
|
private _memoCache;
|
|
132
|
+
private _childComponents;
|
|
132
133
|
constructor(props?: P, initialState?: S);
|
|
133
134
|
onBeforeMount?(): void | Promise<void>;
|
|
134
135
|
onMount?(): void | Promise<void>;
|
|
@@ -157,6 +158,14 @@ declare abstract class Component<P = Record<string, unknown>, S = Record<string,
|
|
|
157
158
|
subscribe(subscription: () => void): void;
|
|
158
159
|
debounce<T extends (...args: unknown[]) => unknown>(fn: T, delay: number): (...args: Parameters<T>) => void;
|
|
159
160
|
throttle<T extends (...args: unknown[]) => unknown>(fn: T, delay: number): (...args: Parameters<T>) => void;
|
|
161
|
+
/**
|
|
162
|
+
* Register a child component for lifecycle tracking
|
|
163
|
+
*/
|
|
164
|
+
registerChild(container: HTMLElement, component: Component): void;
|
|
165
|
+
/**
|
|
166
|
+
* Unregister a child component
|
|
167
|
+
*/
|
|
168
|
+
unregisterChild(container: HTMLElement): void;
|
|
160
169
|
get element(): HTMLElement | null;
|
|
161
170
|
get isMounted(): boolean;
|
|
162
171
|
get isUnmounting(): boolean;
|
|
@@ -247,7 +256,7 @@ declare class Router {
|
|
|
247
256
|
private _runNavigationGuards;
|
|
248
257
|
private _runGuard;
|
|
249
258
|
/**
|
|
250
|
-
* Render component -
|
|
259
|
+
* Render component - FIXED: Only clears outlet content, doesn't affect parent components
|
|
251
260
|
*/
|
|
252
261
|
private _renderComponent;
|
|
253
262
|
/**
|
package/dist/main.d.ts
CHANGED
|
@@ -129,6 +129,7 @@ declare abstract class Component<P = Record<string, unknown>, S = Record<string,
|
|
|
129
129
|
private _refs;
|
|
130
130
|
private _subscriptions;
|
|
131
131
|
private _memoCache;
|
|
132
|
+
private _childComponents;
|
|
132
133
|
constructor(props?: P, initialState?: S);
|
|
133
134
|
onBeforeMount?(): void | Promise<void>;
|
|
134
135
|
onMount?(): void | Promise<void>;
|
|
@@ -157,6 +158,14 @@ declare abstract class Component<P = Record<string, unknown>, S = Record<string,
|
|
|
157
158
|
subscribe(subscription: () => void): void;
|
|
158
159
|
debounce<T extends (...args: unknown[]) => unknown>(fn: T, delay: number): (...args: Parameters<T>) => void;
|
|
159
160
|
throttle<T extends (...args: unknown[]) => unknown>(fn: T, delay: number): (...args: Parameters<T>) => void;
|
|
161
|
+
/**
|
|
162
|
+
* Register a child component for lifecycle tracking
|
|
163
|
+
*/
|
|
164
|
+
registerChild(container: HTMLElement, component: Component): void;
|
|
165
|
+
/**
|
|
166
|
+
* Unregister a child component
|
|
167
|
+
*/
|
|
168
|
+
unregisterChild(container: HTMLElement): void;
|
|
160
169
|
get element(): HTMLElement | null;
|
|
161
170
|
get isMounted(): boolean;
|
|
162
171
|
get isUnmounting(): boolean;
|
|
@@ -247,7 +256,7 @@ declare class Router {
|
|
|
247
256
|
private _runNavigationGuards;
|
|
248
257
|
private _runGuard;
|
|
249
258
|
/**
|
|
250
|
-
* Render component -
|
|
259
|
+
* Render component - FIXED: Only clears outlet content, doesn't affect parent components
|
|
251
260
|
*/
|
|
252
261
|
private _renderComponent;
|
|
253
262
|
/**
|
package/dist/main.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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';import*as q from'sass';import {existsSync,readdirSync,statSync,mkdirSync,writeFileSync}from'fs';import {dirname,join,extname,relative}from'path';var ft=Object.defineProperty;var w=(o,t,e,r)=>{for(var n=void 0,s=o.length-1,i;s>=0;s--)(i=o[s])&&(n=(i(t,e,n))||n);return n&&ft(t,e,n),n};var
|
|
2
|
-
`),n=[],i=0;for(let a of r){if(a=a.trim(),a.startsWith("@media")){n.push(a);continue}if(i+=(a.match(/{/g)||[]).length,i-=(a.match(/}/g)||[]).length,a.includes("{")&&!a.startsWith("@")&&!a.startsWith("}")){let
|
|
3
|
-
`)}static clear(){for(let[,t]of this.styles)t.parentElement&&t.parentElement.removeChild(t);this.styles.clear();}};function A(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 i=Date.now(),a=i-r;a>=e?(r=i,t.apply(this,s)):n||(n=setTimeout(()=>{r=Date.now(),n=null,t.apply(this,s);},e-a));}}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),i=this._convertToVDomNode(this._vnode),a=this._convertToVDomNode(r);patch(n,i,a,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(i){console.error(`Watcher error in ${s}:`,i);}}}};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){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,i]of Object.entries(e))n=n.replace(`:${s}`,i);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),i=this.currentRoute||this._buildEmptyRoute();if(!await this._runNavigationGuards(r,s,i))return;this.currentRoute=s,await this._renderComponent(r),this._handleScrollBehavior(s,i),r.meta?.title&&typeof r.meta.title=="string"&&(document.title=r.meta.title),this.afterEachHooks.forEach(u=>u(s,i));}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(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(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=`
|
|
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';import*as q from'sass';import {existsSync,readdirSync,statSync,mkdirSync,writeFileSync}from'fs';import {dirname,join,extname,relative}from'path';var ft=Object.defineProperty;var w=(o,t,e,r)=>{for(var n=void 0,s=o.length-1,i;s>=0;s--)(i=o[s])&&(n=(i(t,e,n))||n);return n&&ft(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=[],i=0;for(let a of r){if(a=a.trim(),a.startsWith("@media")){n.push(a);continue}if(i+=(a.match(/{/g)||[]).length,i-=(a.match(/}/g)||[]).length,a.includes("{")&&!a.startsWith("@")&&!a.startsWith("}")){let c=a.substring(0,a.indexOf("{")).trim(),u=a.substring(a.indexOf("{"));if(c===":root"||c==="*"||a.startsWith("@"))n.push(a);else {let l=`[data-scope="${e}"] ${c}`;n.push(`${l} ${u}`);}}else n.push(a);}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}},x=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._childComponents=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=[];for(let[,t]of this._childComponents)t._isMounted&&t.unmount();this._childComponents.clear(),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 i=Date.now(),a=i-r;a>=e?(r=i,t.apply(this,s)):n||(n=setTimeout(()=>{r=Date.now(),n=null,t.apply(this,s);},e-a));}}registerChild(t,e){this._childComponents.set(t,e);}unregisterChild(t){this._childComponents.delete(t);}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),i=new Map;for(let[u,l]of this._childComponents){let d=u.getAttribute("data-theme-toggle")||u.getAttribute("data-language-toggle")||u.getAttribute("data-child-component");d&&i.set(d,{container:u,component:l});}let a=this._convertToVDomNode(this._vnode),c=this._convertToVDomNode(r);patch(n,a,c,s),this._element=n.childNodes[s];for(let[u,{component:l}]of i){let d=this._element.querySelector(`[data-theme-toggle="${u}"], [data-language-toggle="${u}"], [data-child-component="${u}"]`);if(d&&!l.element?.isConnected)try{await l.mount(d),this._childComponents.set(d,l);}catch(p){console.error("Error remounting child component:",p);}else d&&l.element?.isConnected&&(this._childComponents.delete(i.get(u).container),this._childComponents.set(d,l));}}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(i){console.error(`Watcher error in ${s}:`,i);}}}};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){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,i]of Object.entries(e))n=n.replace(`:${s}`,i);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),i=this.currentRoute||this._buildEmptyRoute();if(!await this._runNavigationGuards(r,s,i))return;this.currentRoute=s,await this._renderComponent(r),this._handleScrollBehavior(s,i),r.meta?.title&&typeof r.meta.title=="string"&&(document.title=r.meta.title),this.afterEachHooks.forEach(c=>c(s,i));}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}if(this.currentComponent){try{this.currentComponent.unmount();}catch(e){console.error("Error unmounting component:",e);}this.currentComponent=null;}for(;this.routerOutlet.firstChild;)this.routerOutlet.removeChild(this.routerOutlet.firstChild);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),window.dispatchEvent(new CustomEvent("route-component-mounted",{detail:{route:t.path,component:r.name}})));}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(a=>{if(typeof a!="function")return !1;let u=a.prototype;return u!==null&&typeof u=="object"&&u!==void 0&&"constructor"in u})||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,(a,
|
|
11
|
-
/* ${relative(e,
|
|
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,(a,c)=>(r.push(c),"([^/]+)")),s=new RegExp(`^${n}$`),i=e.match(s);return i?r.reduce((a,c,u)=>(a[c]=decodeURIComponent(i[u+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((r,n)=>{let[s,i]=n.split("=").map(decodeURIComponent);return s&&(r[s]=i||""),r},{}):{}}},T=new E;function Tt(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)}});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/style",r=t.build?.styles?.output||"./static/client.css",n=dirname(r),s=r.split("/").pop()||"client.css";if(!existsSync(e)){console.log("\u26A0\uFE0F No style directory found, skipping CSS build");return}try{existsSync(n)||mkdirSync(n,{recursive:!0});let i=this._collectSassFiles(e);if(i.length===0){console.log("\u26A0\uFE0F No SASS/SCSS files found, skipping CSS build");return}let a="";for(let u of i)try{let l=q.compile(u,{style:t.build?.minify?"compressed":"expanded",sourceMap:!!t.build?.sourcemap});a+=`
|
|
11
|
+
/* ${relative(e,u)} */
|
|
12
12
|
`,a+=l.css,a+=`
|
|
13
|
-
`;}catch(l){throw console.error(`\u274C Error compiling ${
|
|
13
|
+
`;}catch(l){throw console.error(`\u274C Error compiling ${u}:`,l),l}let c=join(n,s);writeFileSync(c,a,"utf-8"),t.build?.sourcemap&&writeFileSync(`${c}.map`,JSON.stringify({version:3,sources:i.map(u=>relative(n,u)),names:[],mappings:""}),"utf-8");}catch(i){throw console.error("\u274C CSS Build failed:",i),i}},_collectSassFiles(e){let r=[];if(!existsSync(e))return r;let n=readdirSync(e);for(let s of n){let i=join(e,s),a=statSync(i);if(a.isDirectory())r.push(...this._collectSassFiles(i));else if(a.isFile()){let c=extname(s);(c===".sass"||c===".scss")&&!s.startsWith("_")&&r.push(i);}}return r.sort()},async watch(){console.log("\u{1F440} Watching for changes..."),await this.build();let{watch:e}=await import('fs');if(t.build?.entry){let n=dirname(t.build.entry);e(n,{recursive:true},async(s,i)=>{if(i&&(i.endsWith(".ts")||i.endsWith(".tsx"))){console.log(`\u{1F504} ${i} changed, rebuilding JS...`);try{await this._buildJS(),console.log("\u2705 JS rebuild complete");}catch(a){console.error("\u274C JS rebuild failed:",a);}}});}let r="./app/style";existsSync(r)&&e(r,{recursive:true},async(n,s)=>{if(s&&(s.endsWith(".sass")||s.endsWith(".scss"))){console.log(`\u{1F504} ${s} changed, rebuilding CSS...`);try{await this._buildStyles(),console.log("\u2705 CSS rebuild complete");}catch(i){console.error("\u274C CSS rebuild failed:",i);}}});},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&&(T.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&T.beforeEach(t.router.beforeEach),t.router.afterEach&&T.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:T,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(i){console.error("Store middleware error:",i);}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 i=s[t];r!==i&&(r=i,e(i));};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 j(o){return new P(o)}function St(o,t){let e=j({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 xt(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 i=t.name;return t.addInitializer(function(){let a=this;a.constructor.__reactiveProps__||(a.constructor.__reactiveProps__=[]),a.constructor.__reactiveProps__.includes(i)||a.constructor.__reactiveProps__.push(i);}),function(a){let c=this,u=`_state_${i}`;return c[u]=a,Object.defineProperty(this,i,{get(){return this[u]},set(l){let d=this,p=d[u];p!==l&&(d[u]=l,typeof d._invalidateAllComputed=="function"&&d._invalidateAllComputed(),typeof d._triggerWatchers=="function"&&d._triggerWatchers(i,l,p),d._isMounted&&typeof d.update=="function"&&d.update());},enumerable:true,configurable:true}),a}}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 i=this;if(i[s])return i[n]},set(i){let a=this;if(!a[s]){a[n]=i,a[s]=true;return}let c=a[n];c!==i&&(a[n]=i,typeof a._invalidateAllComputed=="function"&&a._invalidateAllComputed(),typeof a._triggerWatchers=="function"&&a._triggerWatchers(e,i,c),a._isMounted&&typeof a.update=="function"&&a.update());},enumerable:true,configurable:true});}function kt(o,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 c=o,u=a.name,l=`_computed_cache_${u}`,d=`_computed_dirty_${u}`;return function(){let p=this;return p[d]===void 0&&(p[d]=true),p[d]===true&&(p[l]=c.call(this),p[d]=false),p[l]}}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}`,i=`_computed_dirty_${r}`;return {get(){let a=this;return a[i]===void 0&&(a[i]=true),a[i]===true&&(a[s]=n.call(this),a[i]=false),a[s]},enumerable:e.enumerable,configurable:e.configurable}}function Et(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 c=r.name;r.addInitializer(function(){let u=this;u.constructor.__watchers__||(u.constructor.__watchers__={}),u.constructor.__watchers__[o]||(u.constructor.__watchers__[o]=[]),u.constructor.__watchers__[o].includes(c)||u.constructor.__watchers__[o].push(c);});return}let s=r;if(!n)throw new Error("@watch requires a property descriptor");let a=e.constructor;return a.__watchers__||(a.__watchers__={}),a.__watchers__[o]||(a.__watchers__[o]=[]),a.__watchers__[o].includes(s)||a.__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 i=n.custom(r);if(i!==true)return typeof i=="string"?i:"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 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 html`
|
|
14
14
|
<div class="form-field ${e.className||""}">
|
|
15
15
|
${e.label?html`<label for=${e.name}>${e.label}</label>`:""}
|
|
16
16
|
<textarea
|
|
@@ -34,7 +34,7 @@ import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMEle
|
|
|
34
34
|
name=${e.name}
|
|
35
35
|
value=${String(r)}
|
|
36
36
|
disabled=${String(e.disabled||this.isSubmitting)}
|
|
37
|
-
onchange=${a=>{let
|
|
37
|
+
onchange=${a=>{let c=a.target;this.handleChange(e.name,c.value);}}
|
|
38
38
|
onblur=${()=>this.handleBlur(e.name)}
|
|
39
39
|
>
|
|
40
40
|
<option value="">Select...</option>
|
|
@@ -94,7 +94,7 @@ import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMEle
|
|
|
94
94
|
${this.isSubmitting?e.loadingLabel||"Submitting...":e.label||"Submit"}
|
|
95
95
|
</button>
|
|
96
96
|
</form>
|
|
97
|
-
`}styles(){return
|
|
97
|
+
`}styles(){return L`
|
|
98
98
|
.smart-form {
|
|
99
99
|
max-width: 100%;
|
|
100
100
|
}
|
|
@@ -168,9 +168,9 @@ import {setConfig,patch,createElement,html}from'@je-es/vdom';export{createDOMEle
|
|
|
168
168
|
background: #d1fae5;
|
|
169
169
|
color: #065f46;
|
|
170
170
|
}
|
|
171
|
-
`}};w([_],g.prototype,"fields"),w([_],g.prototype,"formData"),w([_],g.prototype,"isSubmitting"),w([_],g.prototype,"submitError"),w([_],g.prototype,"submitSuccess");function Pt(o){return new g(o).render()}function G(o,t){let e=null;return (...r)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,o(...r);},t);}}function J(o,t){let e=0,r=null;return (...n)=>{let s=Date.now(),i=s-e;i>=t?(e=s,o(...n)):r||(r=setTimeout(()=>{e=Date.now(),r=null,o(...n);},t-i));}}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 Y(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"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),
|
|
171
|
+
`}};w([_],g.prototype,"fields"),w([_],g.prototype,"formData"),w([_],g.prototype,"isSubmitting"),w([_],g.prototype,"submitError"),w([_],g.prototype,"submitSuccess");function Pt(o){return new g(o).render()}function G(o,t){let e=null;return (...r)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,o(...r);},t);}}function J(o,t){let e=0,r=null;return (...n)=>{let s=Date.now(),i=s-e;i>=t?(e=s,o(...n)):r||(r=setTimeout(()=>{e=Date.now(),r=null,o(...n);},t-i));}}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 Y(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"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0");return t.replace("YYYY",String(r)).replace("MM",n).replace("DD",s).replace("HH",i).replace("mm",a).replace("ss",c)}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 M(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]={}),M(o[r],n)):o[r]=n);}}return M(o,...t)}function $(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}var H=0;function Z(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 X(o){if(o<0)throw new Error("Sleep duration must be non-negative");return new Promise(t=>setTimeout(t,o))}function tt(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 et(o){return o?o.charAt(0).toUpperCase()+o.slice(1):""}function rt(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 nt(o){if(!o)return "";let t=I(o);return t.charAt(0).toUpperCase()+t.slice(1)}function ot(o,t,e="..."){return !o||o.length<=t?o:o.substring(0,t-e.length)+e}function st(o){let t={},e=o.replace(/^\?/,"");if(!e)return t;let r=e.split("&");for(let n of r){let[s,i]=n.split("=").map(decodeURIComponent);if(!s)continue;let a=i||"";if(s.endsWith("[]")){let c=s.slice(0,-2);t[c]||(t[c]=[]),t[c].push(a);}else t[s]=a;}return t}function it(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 at(o,t,e){return Math.min(Math.max(o,t),e)}function ut(){return typeof window<"u"&&typeof document<"u"}function ct(o,t){try{return JSON.parse(o)}catch{return t}}var $t={debounce:G,throttle:J,classNames:Q,formatDate:Y,deepClone:y,deepMerge:M,uniqueId:Z,sleep:X,isEmpty:tt,capitalize:et,kebabCase:rt,camelCase:I,pascalCase:nt,truncate:ot,parseQuery:st,stringifyQuery:it,clamp:at,isBrowser:ut,safeJsonParse:ct};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 Ft(o){return new k(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`
|
|
172
172
|
<div class="context-provider" style="display: contents;">
|
|
173
173
|
${t}
|
|
174
174
|
</div>
|
|
175
|
-
`}};function
|
|
175
|
+
`}};function Vt(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 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 Nt(o){return new F(o)}var f=null,S=0,U=new WeakMap;function lt(o){f=o,S=0;}function dt(){f=null,S=0;}function V(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=S++,r=V(t);r[e]===void 0&&(r[e]={value:typeof o=="function"?o():o});let n=s=>{let i=r[e],a=typeof s=="function"?s(i.value):s;i.value!==a&&(i.value=a,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=S++,n=V(e),s=n[r];if(!s||!t||!pt(s.deps,t)){if(s?.value&&typeof s.value=="function")try{s.value();}catch(a){console.error("Error in effect cleanup:",a);}Promise.resolve().then(()=>{try{let a=o();n[r]={value:a,deps:t?[...t]:void 0};}catch(a){console.error("Error in effect:",a);}});}}function ht(o,t){if(!f)throw new Error("useMemo must be called inside a component");let e=S++,r=V(f),n=r[e];return (!n||!pt(n.deps,t))&&(r[e]={value:o(),deps:[...t]}),r[e].value}function N(o,t){return ht(()=>o,t)}function D(o){if(!f)throw new Error("useRef must be called inside a component");let t=S++,e=V(f);return e[t]===void 0&&(e[t]={value:{current:o}}),e[t].value}function Dt(o,t){let[e,r]=v(t),n=N(s=>{r(i=>o(i,s));},[o]);return [e,n]}function Lt(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(i=>{let a=s instanceof Function?s(i):s;try{window.localStorage.setItem(o,JSON.stringify(a));}catch(c){console.error("Error saving to localStorage:",c);}return a});}]}function At(o,t){let[e,r]=v(o);return b(()=>{let n=setTimeout(()=>{r(o);},t);return ()=>{clearTimeout(n);}},[o,t]),e}function Ht(o){let t=D(void 0);return b(()=>{t.current=o;}),t.current}function It(o=false){let[t,e]=v(o),r=N(()=>{e(n=>!n);},[]);return [t,r]}function Ot(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 Ut(o,t){let[e,r]=v(null),[n,s]=v(true),[i,a]=v(null),c=N(async()=>{s(true),a(null);try{let u=await fetch(o,t);if(!u.ok)throw new Error(`HTTP error! status: ${u.status}`);let l=await u.json();r(l);}catch(u){a(u);}finally{s(false);}},[o]);return b(()=>{c();},[c]),{data:e,loading:n,error:i,refetch:c}}function Kt(){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 Bt(o,t,e=window){let r=D(t);b(()=>{r.current=t;},[t]),b(()=>{if(!(e&&"addEventListener"in e))return;let s=i=>{r.current(i);};return e.addEventListener(o,s),()=>{e.removeEventListener(o,s);}},[o,e]);}function zt(o,t){class e extends m{render(){lt(this);try{return o(this.props)}finally{dt();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function pt(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,k as Context,O as Provider,E as Router,Pt as SmartForm,g as SmartFormComponent,P as Store,C as StyleManager,I as camelCase,et as capitalize,at as clamp,Q as classNames,dt as clearHookContext,Tt as client,kt as computed,xt as connect,Nt as createCombinedContext,St as createComputedStore,Ft as createContext,zt as createFunctionalComponent,j as createStore,L as css,G as debounce,y as deepClone,M as deepMerge,Y as formatDate,ut as isBrowser,tt as isEmpty,rt as kebabCase,st as parseQuery,nt as pascalCase,T as router,ct as safeJsonParse,x as scheduler,lt as setHookContext,X as sleep,_ as state,it as stringifyQuery,J as throttle,ot as truncate,Z as uniqueId,N as useCallback,Vt as useContext,At as useDebounce,b as useEffect,Bt as useEventListener,Ut as useFetch,Ot as useInterval,Lt as useLocalStorage,ht as useMemo,Ht as usePrevious,Dt as useReducer,D as useRef,v as useState,It as useToggle,Kt as useWindowSize,$t as utils,Et as watch};//# sourceMappingURL=main.js.map
|
|
176
176
|
//# sourceMappingURL=main.js.map
|