!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).FetchTable=t()}(this,function(){"use strict";function e(e,t,n){function s(n,s){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,s);for(const e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=s}const i=n?.Parent??Object;class a extends i{}function o(e){var t;const i=n?.Parent?new a:this;s(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}class t extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const n={};function s(e){return n}function i(e,t){return"bigint"==typeof t?t.toString():t}const a=Symbol("evaluating");function o(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==a)return void 0===s&&(s=a,s=n()),s},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const r="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function c(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function l(e){if(!1===c(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==c(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}const u=new Set(["string","number","symbol"]);function h(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function p(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function d(e){return"string"==typeof e?e:e?.message}function f(e,t,n){const s={...e,path:e.path??[]};if(!e.message){const i=d(e.inst?._zod.def?.error?.(e))??d(t?.error?.(e))??d(n.customError?.(e))??d(n.localeError?.(e))??"Invalid input";s.message=i}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}const g=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,i,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_=e("$ZodError",g),m=e("$ZodError",g,{Parent:Error}),b=(e=>(n,i,a,o)=>{const c=a?Object.assign(a,{async:!1}):{async:!1},l=n._zod.run({value:i,issues:[]},c);if(l instanceof Promise)throw new t;if(l.issues.length){const t=new(o?.Err??e)(l.issues.map(e=>f(e,c,s())));throw r(t,o?.callee),t}return l.value})(m),v=(e=>async(t,n,i,a)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let c=t._zod.run({value:n,issues:[]},o);if(c instanceof Promise&&(c=await c),c.issues.length){const t=new(a?.Err??e)(c.issues.map(e=>f(e,o,s())));throw r(t,a?.callee),t}return c.value})(m),y=(e=>(n,i,a)=>{const o=a?{...a,async:!1}:{async:!1},r=n._zod.run({value:i,issues:[]},o);if(r instanceof Promise)throw new t;return r.issues.length?{success:!1,error:new(e??_)(r.issues.map(e=>f(e,o,s())))}:{success:!0,data:r.value}})(m),z=(e=>async(t,n,i)=>{const a=i?Object.assign(i,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>f(e,a,s())))}:{success:!0,data:o.value}})(m),N=/^-?\d+(?:\.\d+)?/,w=/^(?:true|false)$/i,P={major:4,minor:1,patch:11},S=e("$ZodType",(e,n)=>{var s;e??(e={}),e._zod.def=n,e._zod.bag=e._zod.bag||{},e._zod.version=P;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const t of i)for(const n of t._zod.onattach)n(e);if(0===i.length)(s=e._zod).deferred??(s.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const n=(e,n,s)=>{let i,a=h(e);for(const o of n){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(a)continue;const n=e.issues.length,r=o._zod.check(e);if(r instanceof Promise&&!1===s?.async)throw new t;if(i||r instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await r;e.issues.length!==n&&(a||(a=h(e,n)))});else{if(e.issues.length===n)continue;a||(a=h(e,n))}}return i?i.then(()=>e):e},s=(s,a,o)=>{if(h(s))return s.aborted=!0,s;const r=n(a,i,o);if(r instanceof Promise){if(!1===o.async)throw new t;return r.then(t=>e._zod.parse(t,o))}return e._zod.parse(r,o)};e._zod.run=(a,o)=>{if(o.skipChecks)return e._zod.parse(a,o);if("backward"===o.direction){const t=e._zod.parse({value:a.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>s(e,a,o)):s(t,a,o)}const r=e._zod.parse(a,o);if(r instanceof Promise){if(!1===o.async)throw new t;return r.then(e=>n(e,i,o))}return n(r,i,o)}}e["~standard"]={validate:t=>{try{const n=y(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return z(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),C=e("$ZodString",(e,t)=>{var n;S.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),T=e("$ZodNumber",(e,t)=>{S.init(e,t),e._zod.pattern=e._zod.bag.pattern??N,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const a="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...a?{received:a}:{}}),n}}),E=e("$ZodBoolean",(e,t)=>{S.init(e,t),e._zod.pattern=w,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}});function j(e,t,n){e.issues.length&&t.issues.push(...p(n,e.issues)),t.value[n]=e.value}const L=e("$ZodArray",(e,t)=>{S.init(e,t),e._zod.parse=(n,s)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const a=[];for(let e=0;e<i.length;e++){const o=i[e],r=t.element._zod.run({value:o,issues:[]},s);r instanceof Promise?a.push(r.then(t=>j(t,n,e))):j(r,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function k(e,t,n,s){e.issues.length&&t.issues.push(...p(n,e.issues)),void 0===e.value?n in s&&(t.value[n]=void 0):t.value[n]=e.value}function O(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(s=e.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}const x=e("$ZodObject",(e,t)=>{S.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const s=(i=()=>O(t),{get value(){{const e=i();return Object.defineProperty(this,"value",{value:e}),e}}});var i;o(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});const a=c,r=t.catchall;let l;e._zod.parse=(t,n)=>{l??(l=s.value);const i=t.value;if(!a(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value={};const o=[],c=l.shape;for(const e of l.keys){const s=c[e]._zod.run({value:i[e],issues:[]},n);s instanceof Promise?o.push(s.then(n=>k(n,t,e,i))):k(s,t,e,i)}return r?function(e,t,n,s,i,a){const o=[],r=i.keySet,c=i.catchall._zod,l=c.def.type;for(const i of Object.keys(t)){if(r.has(i))continue;if("never"===l){o.push(i);continue}const a=c.run({value:t[i],issues:[]},s);a instanceof Promise?e.push(a.then(e=>k(e,n,i,t))):k(a,n,i,t)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}(o,i,t,n,s.value,e):o.length?Promise.all(o).then(()=>t):t}}),M=e("$ZodRecord",(e,t)=>{S.init(e,t),e._zod.parse=(n,i)=>{const a=n.value;if(!l(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:e}),n;const o=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;n.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:a[e],issues:[]},i);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&n.issues.push(...p(e,t.issues)),n.value[e]=t.value})):(s.issues.length&&n.issues.push(...p(e,s.issues)),n.value[e]=s.value)}let r;for(const e in a)s.has(e)||(r=r??[],r.push(e));r&&r.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:e,keys:r})}else{n.value={};for(const r of Reflect.ownKeys(a)){if("__proto__"===r)continue;const c=t.keyType._zod.run({value:r,issues:[]},i);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(e=>f(e,i,s())),input:r,path:[r],inst:e}),n.value[c.value]=c.value;continue}const l=t.valueType._zod.run({value:a[r],issues:[]},i);l instanceof Promise?o.push(l.then(e=>{e.issues.length&&n.issues.push(...p(r,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...p(r,l.issues)),n.value[c.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}}),D=e("$ZodEnum",(e,t)=>{S.init(e,t);const n=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(e=>u.has(typeof e)).map(e=>"string"==typeof e?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const a=t.value;return s.has(a)||t.issues.push({code:"invalid_value",values:n,input:a,inst:e}),t}});function $(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const H=e("$ZodOptional",(e,t)=>{S.init(e,t),e._zod.optin="optional",e._zod.optout="optional",o(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),o(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(t=>$(t,e.value)):$(s,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),R=e("$ZodDefault",(e,t)=>{S.init(e,t),e._zod.optin="optional",o(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Z(e,t)):Z(s,t)}});function Z(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const A=e("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");S.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>b(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>y(e,t,n),e.parseAsync=async(t,n)=>v(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>z(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,n)=>function(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e)}),B=e("ZodMiniString",(e,t)=>{C.init(e,t),A.init(e,t)});function q(e){return new B({type:"string"})}const I=e("ZodMiniNumber",(e,t)=>{T.init(e,t),A.init(e,t)});function U(e){return new I({type:"number",checks:[]})}const F=e("ZodMiniBoolean",(e,t)=>{E.init(e,t),A.init(e,t)});function V(e){return new F({type:"boolean"})}const K=e("ZodMiniArray",(e,t)=>{L.init(e,t),A.init(e,t)});function W(e,t){return new K({type:"array",element:e})}const X=e("ZodMiniObject",(e,t)=>{x.init(e,t),A.init(e,t),o(e,"shape",()=>t.shape)});function G(e,t){return new X({type:"object",shape:e??{}})}const J=e("ZodMiniRecord",(e,t)=>{M.init(e,t),A.init(e,t)});function Q(e,t,n){return new J({type:"record",keyType:e,valueType:t})}const Y=e("ZodMiniEnum",(e,t)=>{D.init(e,t),A.init(e,t),e.options=Object.values(t.entries)});function ee(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Y({type:"enum",entries:n})}const te=e("ZodMiniOptional",(e,t)=>{H.init(e,t),A.init(e,t)});function ne(e){return new te({type:"optional",innerType:e})}const se=e("ZodMiniDefault",(e,t)=>{R.init(e,t),A.init(e,t)});function ie(e,t){return new se({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():l(e=t)?{...e}:Array.isArray(e)?[...e]:e;var e}})}const ae=G({type:ee(["text","html"]),label:q(),className:ne(q()),sortable:V(),searchable:V()}),oe=G({ajaxURL:q(),ajaxMethod:ee(["GET","POST"]),ajaxHeaders:ie(Q(q(),q()),{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest","X-Requested-By":"fetch-table"}),debug:ie(V(),!1),columns:Q(q(),ae),elements:ne(G({container:ne(G({container:ne(G({className:ne(q()),querySelector:ne(q()),attributes:ne(Q(q(),q()))})),header:ne(G({className:ne(q()),querySelector:ne(q()),attributes:ne(Q(q(),q()))})),footer:ne(G({className:ne(q()),querySelector:ne(q()),attributes:ne(Q(q(),q()))}))})),table:ne(G({table:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),tableHead:ne(G({tableHead:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),tableRow:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),tableCell:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))}))})),tableBody:ne(G({tableBody:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),tableRow:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),tableCell:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))}))})),placeholder:ne(G({className:ne(q()),innerHTML:ne(q()),attributes:ne(Q(q(),q()))}))})),pagination:ne(G({container:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),button:ne(G({primary:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),active:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),ellipsis:ne(G({className:ne(q()),innerHTML:ne(q()),attributes:ne(Q(q(),q()))})),previous:ne(G({className:ne(q()),innerHTML:ne(q()),attributes:ne(Q(q(),q()))})),next:ne(G({className:ne(q()),innerHTML:ne(q()),attributes:ne(Q(q(),q()))}))})),sizeSelector:ne(G({container:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),select:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),option:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))}))}))})),search:ne(G({container:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))})),input:ne(G({className:ne(q()),attributes:ne(Q(q(),q()))}))}))})),components:G({pagination:G({active:V(),pageSize:U(),availableSizes:W(U()),style:ee(["standard","simple"])}),search:G({active:V()})})});function re(e,t={}){const n=document.createElement(e);return Object.entries(t).forEach(([e,t])=>{null!=t&&("attributes"===e?Object.entries(t).forEach(([e,t])=>{n.setAttribute(e,String(t))}):e in n?n[e]=t:n.setAttribute(e,String(t)))}),n}class ce{constructor(){this._handlers={}}register(e,t,n=1e3){this._handlers[e]||(this._handlers[e]=[]),this._handlers[e].push({callback:t,priority:n})}dispatch(e,t){this._handlers[e]?.sort((e,t)=>e.priority-t.priority).forEach(e=>{e.callback(t)})}}const le=G({pagination:ne(G({page:U(),pageSize:U(),totalPages:U()})),data:W(W(G({column:q(),className:ne(q()),value:q()})))});class ue{constructor(e,t){this._sort=null,this._pagination=null,this._search=null,this._config=e,this._eventDispatcher=t}refresh(){this._config.debug&&console.info("Refreshing data..");const e=this.generateRequest();this._eventDispatcher.dispatch("before-data-fetch",e),fetch(e).then(e=>{e.ok&&e.json().then(e=>{const t=le.parse(e);this._eventDispatcher.dispatch("data-fetch",t),this._eventDispatcher.dispatch("after-data-fetch")}).catch(e=>{this._config.debug&&console.error(e),this._eventDispatcher.dispatch("data-fetch-error",{error:e}),this._eventDispatcher.dispatch("after-data-fetch")})}).catch(e=>{this._config.debug&&console.error(e),this._eventDispatcher.dispatch("data-fetch-error",{error:e}),this._eventDispatcher.dispatch("after-data-fetch")})}get sort(){return this._sort}set sort(e){this._sort=e}get pagination(){return this._pagination}set pagination(e){this._pagination=e}get search(){return this._search}set search(e){this._search=e}generateRequest(){const e="GET"===this._config.ajaxMethod?this._config.ajaxURL+"?"+this.generateURLSearchParams():this._config.ajaxURL,t="POST"===this._config.ajaxMethod?JSON.stringify(this.generateRequestBody()):null;return new Request(e,{method:this._config.ajaxMethod,headers:this._config.ajaxHeaders,body:t})}generateRequestBody(){let e={};return null!==this._search&&(e={...e,search:this._search}),null!==this._pagination&&(e={...e,pagination:{page:this._pagination.page,size:this._pagination.pageSize}}),null!==this._sort&&(e={...e,sort:{column:this._sort.columnName,direction:this._sort.direction}}),e}generateURLSearchParams(){let e=new URLSearchParams;return null!==this._search&&e.append("search",this._search),null!==this._pagination&&(e.append("pagination[page]",this._pagination.page.toString()),e.append("pagination[size]",this._pagination.pageSize.toString())),null!==this._sort&&(e.append("sort[column]",this._sort.columnName),e.append("sort[direction]",this._sort.direction)),e}}class he{constructor(e,t,n,s){this._config=t,this._coreElement=e,this._eventDispatcher=n,this._client=s}}class pe extends he{constructor(e,t,n,s){super(e,t,n,s),this._isLoading=!1,this._sort=null,this._elements={table:null,head:null,body:null},this._eventDispatcher.register("before-data-fetch",()=>this._isLoading=!0),this._eventDispatcher.register("data-fetch",e=>this.render(e)),this._eventDispatcher.register("after-data-fetch",()=>this._isLoading=!1),this.init()}init(){this._config.debug&&console.info("[Table Component] Initializing.."),this._coreElement.innerHTML="",this._elements.table=re("table",{className:this._config.elements?.table?.table?.className,attributes:this._config.elements?.table?.table?.attributes}),this._elements.head=re("thead",{className:this._config.elements?.table?.tableHead?.tableHead?.className,attributes:this._config.elements?.table?.tableHead?.tableHead?.attributes}),this._elements.body=re("tbody",{className:this._config.elements?.table?.tableBody?.tableBody?.className,attributes:this._config.elements?.table?.tableBody?.tableBody?.attributes});const e=re("tr",{className:this._config.elements?.table?.tableHead?.tableRow?.className,attributes:this._config.elements?.table?.tableHead?.tableRow?.attributes});for(const[t,n]of Object.entries(this._config.columns)){const s=re("th",{scope:"col",className:n.className||this._config.elements?.table?.tableHead?.tableCell?.className,attributes:this._config.elements?.table?.tableHead?.tableCell?.attributes,innerHTML:n.label});n.sortable&&s.addEventListener("click",()=>{this._isLoading||(this._config.debug&&console.info(`[Table Component] Sort by the column: ${t}`),null===this._sort?this._sort={columnName:t,direction:"ASC"}:this._sort.columnName===t?this._sort.direction="ASC"===this._sort.direction?"DESC":"ASC":this._sort={columnName:t,direction:"ASC"},this._eventDispatcher.dispatch("sort-change",this._sort),this._client.sort=this._sort,this._client.refresh())}),e.appendChild(s)}this._elements.head.appendChild(e),this._elements.table.appendChild(this._elements.head),this._elements.table.appendChild(this._elements.body),this._coreElement.appendChild(this._elements.table)}render(e){if(this._config.debug&&console.info("[Table Component] Rendering data.."),null===this._elements.body)throw new Error("[Table Component] Body element couldn't be found. First, initialize the component with the init() method");if(this._elements.body.innerHTML="",0===e.data.length){const e=re("tr",{className:this._config.elements?.table?.tableBody?.tableRow?.className,attributes:this._config.elements?.table?.tableBody?.tableRow?.attributes}),t=re("td",{colSpan:this._config.columns.length,className:this._config.elements?.table?.placeholder?.className||this._config.elements?.table?.tableBody?.tableCell?.className,attributes:this._config.elements?.table?.placeholder?.attributes,innerHTML:this._config.elements?.table?.placeholder?.innerHTML});e.appendChild(t),this._elements.body?.appendChild(e)}else e.data.forEach(e=>{const t=re("tr",{className:this._config.elements?.table?.tableBody?.tableRow?.className,attributes:this._config.elements?.table?.tableBody?.tableRow?.attributes});for(const[n,s]of Object.entries(this._config.columns)){const i=e.find(function(e){return e.column===n});if(void 0===i)throw new Error(`[Table Component] Column ${n} not found`);const a=re("td",{className:i.className||this._config.elements?.table?.tableBody?.tableCell?.className,attributes:this._config.elements?.table?.tableBody?.tableCell?.attributes});"text"===s.type?a.innerText=i.value:"html"===s.type&&(a.innerHTML=i.value),t.appendChild(a)}this._elements.body?.appendChild(t)})}}class de extends he{constructor(e,t,n,s){super(e,t,n,s),this._isLoading=!1,this._elements={container:null,sizeContainer:null,sizeSelect:null},this._eventDispatcher.register("before-data-fetch",()=>this._isLoading=!0),this._eventDispatcher.register("data-fetch",e=>this.render(e)),this._eventDispatcher.register("after-data-fetch",()=>this._isLoading=!1),this.init()}init(){this._config.debug&&console.info("[Pagination Component] Initializing.."),this._coreElement.innerHTML="",this._elements.container=re("nav",{className:this._config.elements?.pagination?.container?.className,attributes:this._config.elements?.pagination?.container?.attributes,ariaLabel:"Pagination"}),this._elements.sizeContainer=re("div",{className:this._config.elements?.pagination?.sizeSelector?.container?.className,attributes:this._config.elements?.pagination?.sizeSelector?.container?.attributes});const e=re("select",{name:"at-size-selector",className:this._config.elements?.pagination?.sizeSelector?.select?.className,attributes:this._config.elements?.pagination?.sizeSelector?.select?.attributes});this._config.components?.pagination?.availableSizes?.forEach(t=>{const n=re("option",{value:t,innerText:t.toString(),selected:t===this._client.pagination?.pageSize?"selected":null});e.appendChild(n)}),e.addEventListener("change",()=>{if(!this._isLoading){this._config.debug&&console.info(`[Pagination Component] Changing page size to ${e.value}`);let t={page:1,pageSize:parseInt(e.value)};this._eventDispatcher.dispatch("pagination-size-change",t),this._client.pagination=t,this._client.refresh()}}),this._elements.sizeContainer.appendChild(e),this._coreElement.appendChild(this._elements.sizeContainer),this._coreElement.appendChild(this._elements.container)}render(e){if(this._config.debug&&console.info("[Pagination Component] Rendering data.."),null===this._elements.container)throw new Error("[Pagination Component] Container element couldn't be found. First, initialize the component with the init() method");const t=()=>{if(void 0===e.pagination)throw new Error("[Pagination Component] Pagination data is missing. Please check your API response");return e.pagination};this._elements.container.innerText="";const n=re("button",{className:this._config.elements?.pagination?.button?.previous?.className||this._config.elements?.pagination?.button?.primary?.className,attributes:this._config.elements?.pagination?.button?.previous?.attributes,innerHTML:this._config.elements?.pagination?.button?.previous?.innerHTML,disabled:1===t().page?"disabled":null,type:"button"});n.addEventListener("click",()=>{if(!this._isLoading&&t().page>1){this._config.debug&&console.info("[Pagination Component] Moving to the previous page");let e={page:t().page-1,pageSize:t().pageSize};this._eventDispatcher.dispatch("pagination-change",e),this._client.pagination=e,this._client.refresh()}});const s=re("button",{type:"button",className:this._config.elements?.pagination?.button?.next?.className||this._config.elements?.pagination?.button?.primary?.className,attributes:this._config.elements?.pagination?.button?.next?.attributes,innerHTML:this._config.elements?.pagination?.button?.next?.innerHTML,disabled:t().page===t().totalPages?"disabled":null});if(s.addEventListener("click",()=>{if(!this._isLoading&&t().page<t().totalPages){this._config.debug&&console.info("[Pagination Component] Moving to the next page");let e={page:t().page+1,pageSize:t().pageSize};this._eventDispatcher.dispatch("pagination-change",e),this._client.pagination=e,this._client.refresh()}}),this._elements.container?.appendChild(n),"simple"!==this._config.components?.pagination?.style){const e=(e,n=!1)=>{const s=re("button",{className:n&&this._config.elements?.pagination?.button?.active?.className||this._config.elements?.pagination?.button?.primary?.className,attributes:this._config.elements?.pagination?.button?.active?.attributes,innerText:e.toString(),type:"button"});return s.addEventListener("click",()=>{if(!this._isLoading){this._config.debug&&console.info(`[Pagination Component] Moving to page number: ${e}`);let n={page:e,pageSize:t().pageSize};this._eventDispatcher.dispatch("pagination-change",n),this._client.pagination={page:e,pageSize:t().pageSize},this._client.refresh()}}),s},n=()=>re("span",{className:this._config.elements?.pagination?.button?.ellipsis?.className||this._config.elements?.pagination?.button?.primary?.className,attributes:this._config.elements?.pagination?.button?.previous?.attributes,innerHTML:this._config.elements?.pagination?.button?.ellipsis?.innerHTML||".."}),s=e(1,1===t().page);if(this._elements.container?.appendChild(s),t().page>4&&this._elements.container?.appendChild(n()),t().page<5)for(let n=2;n<=Math.min(5,t().totalPages-1);n++){const s=e(n,n===t().page);this._elements.container?.appendChild(s)}else if(t().page>t().totalPages-4)for(let n=Math.max(t().totalPages-4,2);n<=t().totalPages-1;n++){const s=e(n,n===t().page);this._elements.container?.appendChild(s)}else for(let n=t().page-1;n<=t().page+1;n++){const s=e(n,n===t().page);this._elements.container?.appendChild(s)}if(t().page<=t().totalPages-4&&this._elements.container?.appendChild(n()),t().totalPages>1){const n=e(t().totalPages,t().totalPages===t().page);this._elements.container?.appendChild(n)}}this._elements.container?.appendChild(s)}}class fe extends he{constructor(e,t,n,s){super(e,t,n,s),this._isLoading=!1,this._eventDispatcher.register("before-data-fetch",()=>this._isLoading=!0),this._eventDispatcher.register("after-data-fetch",()=>this._isLoading=!1),this.init()}init(){this._config.debug&&console.info("[Search Component] Initializing.."),this._coreElement.innerHTML="";const e=re("div",{className:this._config.elements?.search?.container?.className,attributes:this._config.elements?.search?.container?.attributes}),t=re("input",{type:"text",className:this._config.elements?.search?.input?.className,attributes:this._config.elements?.search?.input?.attributes});let n=null;t.addEventListener("keyup",()=>{this._isLoading||(clearTimeout(n),n=setTimeout(()=>{this._config.debug&&console.info(`[Search Component] Searching for "${t.value}"`);let e=t.value;this._eventDispatcher.dispatch("search-change",e),this._client.search=e,this._client.refresh()},500))}),e.appendChild(t),this._coreElement.appendChild(e)}}return class{constructor(e,t){if(this._components={table:null,pagination:null,search:null},this._config=this.validateConfig(t),this._coreElement=document.querySelector(e),!this._coreElement)throw new Error("Container element couldn't be found.");this._coreElement.innerHTML="";let n=this.selectElement(this._config.elements?.container?.header?.querySelector);null===n&&(n=re("div",{className:this._config.elements?.container?.header?.className,attributes:this._config.elements?.container?.header?.attributes}),this._coreElement.appendChild(n));let s=this.selectElement(this._config.elements?.container?.container?.querySelector);null===s&&(s=re("div",{className:this._config.elements?.container?.container?.className,attributes:this._config.elements?.container?.container?.attributes}),this._coreElement.appendChild(s));let i=this.selectElement(this._config.elements?.container?.footer?.querySelector);null===i&&(i=re("div",{className:this._config.elements?.container?.footer?.className,attributes:this._config.elements?.container?.footer?.attributes}),this._coreElement.appendChild(i)),this._eventDispatcher=new ce,this._client=new ue(this._config,this._eventDispatcher),this._components.table=new pe(s,this._config,this._eventDispatcher,this._client),!0===this._config.components?.search?.active&&(this._components.search=new fe(n,this._config,this._eventDispatcher,this._client)),!0===this._config.components?.pagination?.active&&(this._client.pagination={page:1,pageSize:this._config.components.pagination.pageSize},this._components.pagination=new de(i,this._config,this._eventDispatcher,this._client))}on(e,t){this._eventDispatcher.register(e,t,1e3)}get config(){return this._config}get eventDispatcher(){return this._eventDispatcher}get client(){return this._client}refreshData(){this._client.refresh()}validateConfig(e){const t=oe.safeParse(e);if(t.success)return t.data;throw new Error(`Exception while config validation: ${t.error.message}`)}selectElement(e){return null!=e&&""!==e?document.querySelector(e):null}}});
