web-mojo 2.2.77 → 2.2.79
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/CHANGELOG.md +21 -0
- package/dist/admin.cjs.js +1 -1
- package/dist/admin.cjs.js.map +1 -1
- package/dist/admin.css +880 -0
- package/dist/admin.es.js +1 -1
- package/dist/admin.es.js.map +1 -1
- package/dist/auth.cjs.js +1 -1
- package/dist/auth.es.js +1 -1
- package/dist/charts.cjs.js +1 -1
- package/dist/charts.es.js +1 -1
- package/dist/chunks/ChatView-CJAGPu_V.js +2 -0
- package/dist/chunks/{ChatView-DqOcQ7X3.js.map → ChatView-CJAGPu_V.js.map} +1 -1
- package/dist/chunks/ChatView-DeYslqq6.js +2 -0
- package/dist/chunks/{ChatView-CAiYnmUh.js.map → ChatView-DeYslqq6.js.map} +1 -1
- package/dist/chunks/Dialog-Blz5pT9W.js +3 -0
- package/dist/chunks/Dialog-Blz5pT9W.js.map +1 -0
- package/dist/chunks/Dialog-_LaV3jy1.js +3 -0
- package/dist/chunks/Dialog-_LaV3jy1.js.map +1 -0
- package/dist/chunks/FormView-8YcQbicn.js +3 -0
- package/dist/chunks/FormView-8YcQbicn.js.map +1 -0
- package/dist/chunks/FormView-BJO7sGAG.js +3 -0
- package/dist/chunks/FormView-BJO7sGAG.js.map +1 -0
- package/dist/chunks/{MetricsMiniChartWidget-CAw34pnw.js → MetricsMiniChartWidget-BuoPd6Ri.js} +2 -2
- package/dist/chunks/{MetricsMiniChartWidget-CAw34pnw.js.map → MetricsMiniChartWidget-BuoPd6Ri.js.map} +1 -1
- package/dist/chunks/{MetricsMiniChartWidget-DzIavZX8.js → MetricsMiniChartWidget-C0MaUMxB.js} +2 -2
- package/dist/chunks/{MetricsMiniChartWidget-DzIavZX8.js.map → MetricsMiniChartWidget-C0MaUMxB.js.map} +1 -1
- package/dist/chunks/MiniPieChart-BP1bYCGv.js +2 -0
- package/dist/chunks/MiniPieChart-BP1bYCGv.js.map +1 -0
- package/dist/chunks/MiniPieChart-yRGFM7Yn.js +2 -0
- package/dist/chunks/MiniPieChart-yRGFM7Yn.js.map +1 -0
- package/dist/chunks/MiniSeriesChart-CNNEnNnK.js +2 -0
- package/dist/chunks/MiniSeriesChart-CNNEnNnK.js.map +1 -0
- package/dist/chunks/MiniSeriesChart-DTlUluHV.js +2 -0
- package/dist/chunks/MiniSeriesChart-DTlUluHV.js.map +1 -0
- package/dist/chunks/Modal-BHRX_nwz.js +2 -0
- package/dist/chunks/{Modal-DrNQaqOa.js.map → Modal-BHRX_nwz.js.map} +1 -1
- package/dist/chunks/{Modal--Ob_H2iO.js → Modal-f18CuodE.js} +2 -2
- package/dist/chunks/{Modal--Ob_H2iO.js.map → Modal-f18CuodE.js.map} +1 -1
- package/dist/chunks/{PDFViewer-DIBj2O8e.js → PDFViewer-BYOuiYWu.js} +2 -2
- package/dist/chunks/{PDFViewer-DIBj2O8e.js.map → PDFViewer-BYOuiYWu.js.map} +1 -1
- package/dist/chunks/{PDFViewer-DA6kz3_E.js → PDFViewer-CQGLxxe6.js} +2 -2
- package/dist/chunks/{PDFViewer-DA6kz3_E.js.map → PDFViewer-CQGLxxe6.js.map} +1 -1
- package/dist/chunks/{Passkeys-B2cgwp7Z.js → Passkeys-BKj8hXj5.js} +2 -2
- package/dist/chunks/{Passkeys-B2cgwp7Z.js.map → Passkeys-BKj8hXj5.js.map} +1 -1
- package/dist/chunks/Passkeys-GXFL6xrU.js +2 -0
- package/dist/chunks/{Passkeys-BjdXmjlu.js.map → Passkeys-GXFL6xrU.js.map} +1 -1
- package/dist/chunks/{TokenManager-3sHXNyGO.js → TokenManager-DI79oM25.js} +2 -2
- package/dist/chunks/{TokenManager-3sHXNyGO.js.map → TokenManager-DI79oM25.js.map} +1 -1
- package/dist/chunks/{TokenManager-B98Y3D44.js → TokenManager-fjSO1cdB.js} +2 -2
- package/dist/chunks/{TokenManager-B98Y3D44.js.map → TokenManager-fjSO1cdB.js.map} +1 -1
- package/dist/chunks/{UserProfileView-CObNuOj-.js → UserProfileView-CkDqEHlF.js} +2 -2
- package/dist/chunks/{UserProfileView-CObNuOj-.js.map → UserProfileView-CkDqEHlF.js.map} +1 -1
- package/dist/chunks/{UserProfileView-D7hSFgr-.js → UserProfileView-vBbWK7yp.js} +2 -2
- package/dist/chunks/{UserProfileView-D7hSFgr-.js.map → UserProfileView-vBbWK7yp.js.map} +1 -1
- package/dist/chunks/WebApp-Bu01LHe3.js +2 -0
- package/dist/chunks/{WebApp-D6rnlV2T.js.map → WebApp-Bu01LHe3.js.map} +1 -1
- package/dist/chunks/WebApp-Do6JjXuj.js +2 -0
- package/dist/chunks/{WebApp-BCWzyUqi.js.map → WebApp-Do6JjXuj.js.map} +1 -1
- package/dist/chunks/{index-DnD4XyK9.js → index-D6-NC5vF.js} +2 -2
- package/dist/chunks/{index-DnD4XyK9.js.map → index-D6-NC5vF.js.map} +1 -1
- package/dist/chunks/{index-DKAZI8Tr.js → index-DrRY_Ggo.js} +2 -2
- package/dist/chunks/{index-DKAZI8Tr.js.map → index-DrRY_Ggo.js.map} +1 -1
- package/dist/chunks/{version-Di_mTsi1.js → version-C0bPZQNt.js} +2 -2
- package/dist/chunks/{version-Di_mTsi1.js.map → version-C0bPZQNt.js.map} +1 -1
- package/dist/chunks/{version-DcHmzGeU.js → version-yeiLhs1d.js} +2 -2
- package/dist/chunks/{version-DcHmzGeU.js.map → version-yeiLhs1d.js.map} +1 -1
- package/dist/css/web-mojo.css +1 -1
- package/dist/docit.cjs.js +1 -1
- package/dist/docit.es.js +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.es.js.map +1 -1
- package/dist/lightbox.cjs.js +1 -1
- package/dist/lightbox.es.js +1 -1
- package/dist/map.cjs.js +1 -1
- package/dist/map.es.js +1 -1
- package/dist/user-profile.cjs.js +1 -1
- package/dist/user-profile.es.js +1 -1
- package/dist/web-mojo.lite.iife.js +120 -1
- package/dist/web-mojo.lite.iife.js.map +1 -1
- package/dist/web-mojo.lite.iife.min.js +5 -5
- package/dist/web-mojo.lite.iife.min.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/ChatView-CAiYnmUh.js +0 -2
- package/dist/chunks/ChatView-DqOcQ7X3.js +0 -2
- package/dist/chunks/Dialog-BzvvJnK1.js +0 -3
- package/dist/chunks/Dialog-BzvvJnK1.js.map +0 -1
- package/dist/chunks/Dialog-Fu9AEl7W.js +0 -3
- package/dist/chunks/Dialog-Fu9AEl7W.js.map +0 -1
- package/dist/chunks/FormView-BdYPU1Px.js +0 -3
- package/dist/chunks/FormView-BdYPU1Px.js.map +0 -1
- package/dist/chunks/FormView-DP-iCm9r.js +0 -3
- package/dist/chunks/FormView-DP-iCm9r.js.map +0 -1
- package/dist/chunks/Modal-DrNQaqOa.js +0 -2
- package/dist/chunks/Passkeys-BjdXmjlu.js +0 -2
- package/dist/chunks/WebApp-BCWzyUqi.js +0 -2
- package/dist/chunks/WebApp-D6rnlV2T.js +0 -2
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const o=require("./Dialog-BzvvJnK1.js");class Modal{static async show(a,n={}){return o.Dialog.showDialog({header:void 0!==n.title&&!!n.title,title:n.title||void 0,body:a,size:"lg",centered:!1,buttons:[{text:"Close",class:"btn-secondary",dismiss:!0}],...n})}static async showModel(o,a={}){const n=o.constructor,e=n?.VIEW_CLASS;if(!e)throw new Error(`Modal.showModel: No VIEW_CLASS defined on ${n?.name||"model"}. Set ${n?.name||"Model"}.VIEW_CLASS = YourView to use this method.`);const l=new e({model:o});return Modal.show(l,a)}static async showModelById(a,n,e={}){const l=new a({id:n});return await l.fetch(),l.id?Modal.showModel(l,e):(o.Dialog.alert({message:`Could not find ${a.name||"record"} with ID: ${n}`,type:"warning"}),null)}static confirm(a,n,e){return o.Dialog.confirm(a,n,e)}static alert(a,n,e){return o.Dialog.alert(a,n,e)}static prompt(a,n,e){return o.Dialog.prompt(a,n,e)}static form(a){return o.Dialog.showForm(a)}static modelForm(a){return o.Dialog.showModelForm(a)}static data(a){return o.Dialog.showData(a)}static dialog(a){return o.Dialog.showDialog(a)}static showError(a){return o.Dialog.alert(a,"Error",{type:"danger"})}static _loadingEl=null;static _loadingCounter=0;static _loadingTimeout=null;static loading(o){"string"==typeof o&&(o={message:o});const{message:a="Loading...",timeout:n=3e4}=o||{};if(Modal._loadingCounter++,1===Modal._loadingCounter){Modal._loadingTimeout&&clearTimeout(Modal._loadingTimeout),Modal._loadingEl||(Modal._loadingEl=document.createElement("div"),Modal._loadingEl.className="mojo-loading-overlay",Modal._loadingEl.innerHTML=`\n <div class="mojo-loading-card">\n <div class="mojo-loading-spinner"></div>\n <div class="mojo-loading-message">${a}</div>\n </div>\n <style>\n .mojo-loading-overlay {\n position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;\n background: rgba(255, 255, 255, 0.4);\n backdrop-filter: blur(2px);\n -webkit-backdrop-filter: blur(2px);\n z-index: 99999;\n display: flex; align-items: center; justify-content: center;\n opacity: 0; transition: opacity 0.2s ease;\n }\n .mojo-loading-overlay.show { opacity: 1; }\n .mojo-loading-card {\n display: flex; align-items: center; gap: 0.85rem;\n background: #fff;\n border: 1px solid #e9ecef;\n border-radius: 12px;\n padding: 1rem 1.5rem;\n box-shadow: 0 4px 24px rgba(0,0,0,0.08), 0 1px 4px rgba(0,0,0,0.04);\n }\n .mojo-loading-spinner {\n width: 22px; height: 22px;\n border: 2.5px solid #e9ecef;\n border-top-color: #0d6efd;\n border-radius: 50%;\n animation: mojo-spin 0.7s linear infinite;\n flex-shrink: 0;\n }\n .mojo-loading-message {\n font-size: 0.88rem;\n font-weight: 500;\n color: #495057;\n white-space: nowrap;\n }\n @keyframes mojo-spin {\n to { transform: rotate(360deg); }\n }\n </style>\n `,document.body.appendChild(Modal._loadingEl));const o=Modal._loadingEl.querySelector(".mojo-loading-message");o&&(o.textContent=a),requestAnimationFrame(()=>{Modal._loadingEl&&Modal._loadingEl.classList.add("show")}),n>0&&(Modal._loadingTimeout=setTimeout(()=>{console.error("Modal.loading timed out."),Modal.hideLoading(!0)},n))}else if(Modal._loadingEl){const o=Modal._loadingEl.querySelector(".mojo-loading-message");o&&(o.textContent=a)}}static hideLoading(o){o?Modal._loadingCounter=0:Modal._loadingCounter--,Modal._loadingCounter<=0&&(Modal._loadingCounter=0,Modal._loadingTimeout&&(clearTimeout(Modal._loadingTimeout),Modal._loadingTimeout=null),Modal._loadingEl&&(Modal._loadingEl.classList.remove("show"),setTimeout(()=>{Modal._loadingEl&&0===Modal._loadingCounter&&(Modal._loadingEl.remove(),Modal._loadingEl=null)},200)))}static showBusy(o){return Modal.loading(o)}static hideBusy(o){return Modal.hideLoading(o)}}exports.Modal=Modal;
|
|
2
|
-
//# sourceMappingURL=Modal-DrNQaqOa.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{C as t,M as e,d as i,a as s,r as n}from"./Collection-CaiT8TbF.js";import{L as l,a}from"./ListView-C6VNTO4C.js";import{M as o}from"./Modal--Ob_H2iO.js";import{F as r}from"./FormView-BdYPU1Px.js";class Log extends e{constructor(t={}){super(t,{endpoint:"/api/logs"})}}class LogList extends t{constructor(t={}){super({ModelClass:Log,endpoint:"/api/logs",size:10,...t})}}class Member extends e{constructor(t={}){super(t,{endpoint:"/api/group/member"})}hasPermission(t){if(Array.isArray(t))return t.some(t=>this.hasPermission(t));const e=this.get("permissions");return!!e&&1==e[t]}async fetchForGroup(t){return await this.fetch({url:`/api/group/${t}/member`})}}class MemberList extends t{constructor(t={}){super({ModelClass:Member,endpoint:"/api/group/member",size:10,...t})}}const c={edit:{title:"Edit Membership",fields:[{name:"user.display_name",type:"text",label:"Display Name",placeholder:"Enter Display Name"},{name:"metadata.role",type:"text",label:"Role",placeholder:"Enter role"},{name:"is_active",type:"switch",label:"Is Enabled",columns:12}]}};Member.PERMISSIONS=[{name:"manage_group",label:"Group Admin"},{name:"view_metrics",label:"View Metrics"},{name:"view_logs",label:"View Logs"},{name:"view_tickets",label:"View Tickets"},{name:"view_members",label:"View Members"},{name:"manage_members",label:"Manage Members"},{name:"view_billing",label:"View Billing"}],Member.PERMISSION_FIELDS=[...Member.PERMISSIONS.map(t=>({name:`permissions.${t.name}`,type:"switch",label:t.label,columns:6}))],Member.EDIT_FORM=c.edit,Member.ADD_FORM=c.create;class TableRow extends l{constructor(t={}){super({tagName:"tr",className:"table-row",enableTooltips:!0,...t}),this.columns=t.columns||[],this.actions=t.actions||null,this.contextMenu=t.contextMenu||null,this.batchActions=t.batchActions||null,this.tableView=t.tableView||t.listView||null,this.editingCells=/* @__PURE__ */new Set,this.template=this.buildRowTemplate()}getResponsiveClasses(t){if(!t)return"";const e=["sm","md","lg","xl","xxl"];if("string"==typeof t)return e.includes(t)?`d-none d-${t}-table-cell`:(console.warn(`Invalid visibility breakpoint: ${t}. Valid options are: ${e.join(", ")}`),"");if("object"==typeof t){const i=[];if(t.hide){if(!e.includes(t.hide))return console.warn(`Invalid hide breakpoint: ${t.hide}. Valid options are: ${e.join(", ")}`),"";i.push(`d-table-cell d-${t.hide}-none`)}if(t.show){if(!e.includes(t.show))return console.warn(`Invalid show breakpoint: ${t.show}. Valid options are: ${e.join(", ")}`),"";t.hide?i.push(`d-${t.show}-table-cell`):i.push(`d-none d-${t.show}-table-cell`)}return i.join(" ")}return""}buildRowTemplate(){let t="";return this.tableView&&this.tableView.isSelectable()&&(t+='\n <td style="padding: 0;">\n <div class="mojo-select-cell {{#selected}}selected{{/selected}}"\n data-action="select">\n <div class="mojo-checkbox">\n <i class="bi bi-check"></i>\n </div>\n </div>\n </td>\n '),this.columns.forEach((e,i)=>{const s=[e.class||e.className||"",this.getResponsiveClasses(e.visibility),e.editable?"editable-cell":""].filter(t=>t).join(" "),n=this.buildCellTemplate(e,i);let l=e.action;!l&&e.editable?l="edit-cell":!l&&this.tableView.rowAction&&(l=this.tableView.rowAction),t+=l?`<td class="${s}" data-action="${l}" data-column="${e.key}">${n}</td>`:`<td class="${s}" data-column="${e.key}">${n}</td>`}),this.actions?t+=this.buildActionsTemplate():this.contextMenu&&(t+=this.buildContextMenuTemplate()),t}buildCellTemplate(t,e=0){const i=`model.${t.key}`,s=t.formatter||t.format;if(s){if("string"==typeof s)return`{{{${i}|${s}}}}`;if("function"==typeof s)return`<span data-formatter="${t.key}" data-formatter-id="${e}">{{${i}}}</span>`}return t.template?t.template:t.editable?`<span class="cell-content" data-field="${t.key}">{{{${i}}}}</span>`:`{{{${i}}}}`}buildActionsTemplate(){return this.actions&&0!==this.actions.length?`<td><div class="btn-group btn-group-sm">${this.actions.map(t=>{if("string"==typeof t)switch(t){case"view":return'\n <button class="btn btn-sm btn-outline-primary"\n data-action="view"\n title="View">\n <i class="bi bi-eye"></i>\n </button>\n ';case"edit":return'\n <button class="btn btn-sm btn-outline-secondary"\n data-action="edit"\n title="Edit">\n <i class="bi bi-pencil"></i>\n </button>\n ';case"delete":return'\n <button class="btn btn-sm btn-outline-danger"\n data-action="delete"\n title="Delete">\n <i class="bi bi-trash"></i>\n </button>\n ';default:return""}else if("object"==typeof t)return`\n <button class="btn btn-sm ${t.class||"btn-outline-primary"}"\n data-id="${this.model.id}"\n data-action="${t.action}"\n title="${t.label||""}">\n ${t.icon?`<i class="${t.icon}"></i>`:""}\n ${t.label&&!t.icon?t.label:""}\n </button>\n `;return""}).join("")}</div></td>`:""}buildContextMenuTemplate(){return this.contextMenu&&0!==this.contextMenu.length?`\n <td class="text-end" style="width: 1px;">\n <div class="dropdown">\n <button class="btn btn-sm btn-link border-0"\n type="button"\n data-bs-toggle="dropdown"\n aria-expanded="false"\n style="color: #6c757d;">\n <i class="bi bi-three-dots-vertical"></i>\n </button>\n <ul class="dropdown-menu dropdown-menu-end shadow-sm">\n ${this.buildContextMenuItems()}\n </ul>\n </div>\n </td>\n `:""}buildContextMenuItems(){return this.contextMenu.map(t=>{if(t.separator||t.divider)return'<li><hr class="dropdown-divider"></li>';let e="dropdown-item";return("delete"===t.action||t.danger)&&(e+=" text-danger"),t.disabled&&(e+=" disabled"),`\n <li>\n <a class="${e}" href="#"\n data-id="{{model.id}}"\n data-action="${t.action}"\n ${t.disabled?'aria-disabled="true" tabindex="-1"':""}>\n ${t.icon?`<i class="${t.icon} me-2"></i>`:""}\n ${t.label}\n </a>\n </li>\n `}).join("")}async onAfterRender(){await super.onAfterRender(),this.columns.forEach((t,e)=>{if(t.formatter&&"function"==typeof t.formatter){let s=this.element.querySelector(`[data-formatter-id="${e}"]`);if(s||(s=this.element.querySelector(`[data-formatter="${t.key}"]`)),s){const e=this.model.get?this.model.get(t.key):this.model[t.key],n={value:e,row:this.model,model:this.model,column:t,table:this.tableView,index:this.index};try{s.innerHTML=t.formatter(e,n)}catch(i){console.error(`Error formatting cell for column ${t.key}:`,i)}}}}),this.selected&&this.element.classList.add("selected");const t=this.model.get?this.model.get("id"):this.model.id;t&&this.element.setAttribute("data-id",t)}async onActionEditCell(t,e){t.stopPropagation();const i=e.getAttribute("data-column"),s=this.columns.find(t=>t.key===i);s&&s.editable&&(this.editingCells.has(i)||await this.enterEditMode(i,s,e))}async onActionRowClick(t,e){t.target.closest(".btn-group")||t.target.closest(".dropdown")||t.target.closest(".cell-editor")||(this.emit("row:click",{row:this,model:this.model,column:e.getAttribute("data-column"),event:t}),this.tableView&&this.tableView.emit("row:click",{row:this,model:this.model,column:e.getAttribute("data-column"),event:t}))}async onActionView(t,e){t.stopPropagation(),this.emit("row:view",{row:this,model:this.model,event:t}),this.tableView&&this.tableView.emit("row:view",{row:this,model:this.model,event:t})}async onActionEdit(t,e){return t.stopPropagation(),this.emit("row:edit",{row:this,model:this.model,event:t}),this.tableView&&this.tableView.emit("row:edit",{row:this,model:this.model,event:t}),!0}async onActionDelete(t,e){t.stopPropagation(),this.emit("row:delete",{row:this,model:this.model,event:t}),this.tableView&&this.tableView.emit("row:delete",{row:this,model:this.model,event:t})}async enterEditMode(t,e,i){const s=i.querySelector(".cell-content");if(!s)return;this.editingCells.add(t);const n=this.model.get?this.model.get(t):this.model[t],l=this.createCellEditor(e,n),a=s.innerHTML;s.style.display="none";const o=document.createElement("div");o.className="cell-editor",o.innerHTML=l,i.appendChild(o);const r=o.querySelector("input, select, .form-check-input");r&&(r.focus(),"text"!==r.type&&"textarea"!==r.type||r.select()),o.dataset.originalContent=a,o.dataset.columnKey=t,this.setupEditorEvents(o,t,e),this.emit("cell:edit",{row:this,model:this.model,column:t,originalValue:n})}createCellEditor(t,e){const i=t.editableOptions||{};switch(i.type){case"select":return this.createSelectEditor(i,e);case"switch":case"checkbox":return this.createSwitchEditor(i,e);case"textarea":return this.createTextareaEditor(i,e);default:return this.createTextEditor(i,e)}}createTextEditor(t,e){const i=t.placeholder||"";return`\n <div class="d-flex gap-1 align-items-center">\n <input type="${t.inputType||"text"}"\n class="form-control form-control-sm cell-input"\n value="${this.escapeHtml(e||"")}"\n placeholder="${i}">\n <button type="button" class="btn btn-sm btn-success cell-save" title="Save">\n <i class="bi bi-check"></i>\n </button>\n <button type="button" class="btn btn-sm btn-outline-secondary cell-cancel" title="Cancel">\n <i class="bi bi-x"></i>\n </button>\n </div>\n `}createTextareaEditor(t,e){const i=t.placeholder||"";return`\n <div class="d-flex gap-1">\n <textarea class="form-control form-control-sm cell-input"\n rows="${t.rows||2}"\n placeholder="${i}">${this.escapeHtml(e||"")}</textarea>\n <div class="d-flex flex-column gap-1">\n <button type="button" class="btn btn-sm btn-success cell-save" title="Save">\n <i class="bi bi-check"></i>\n </button>\n <button type="button" class="btn btn-sm btn-outline-secondary cell-cancel" title="Cancel">\n <i class="bi bi-x"></i>\n </button>\n </div>\n </div>\n `}createSelectEditor(t,e){const i=t.options||[];let s="";return i.forEach(t=>{if("string"==typeof t)s+=`<option value="${t}" ${t===e?"selected":""}>${t}</option>`;else if("object"==typeof t&&void 0!==t.value){const i=t.value===e?"selected":"";s+=`<option value="${t.value}" ${i}>${t.label||t.value}</option>`}}),`\n <div class="d-flex gap-1 align-items-center">\n <select class="form-select form-select-sm cell-input">\n ${s}\n </select>\n <button type="button" class="btn btn-sm btn-success cell-save" title="Save">\n <i class="bi bi-check"></i>\n </button>\n <button type="button" class="btn btn-sm btn-outline-secondary cell-cancel" title="Cancel">\n <i class="bi bi-x"></i>\n </button>\n </div>\n `}createSwitchEditor(t,e){const i=e?"checked":"";return`\n <div class="d-flex gap-2 align-items-center">\n <div class="form-check ${"switch"===t.type?"form-switch":""}">\n <input class="form-check-input cell-input" type="checkbox" ${i}>\n </div>\n <div class="d-flex gap-1">\n <button type="button" class="btn btn-sm btn-success cell-save" title="Save">\n <i class="bi bi-check"></i>\n </button>\n <button type="button" class="btn btn-sm btn-outline-secondary cell-cancel" title="Cancel">\n <i class="bi bi-x"></i>\n </button>\n </div>\n </div>\n `}setupEditorEvents(t,e,i){const s=t.querySelector(".cell-input"),n=t.querySelector(".cell-save"),l=t.querySelector(".cell-cancel");!s||"text"!==s.type&&"email"!==s.type&&"number"!==s.type||s.addEventListener("keydown",s=>{"Enter"===s.key?(s.preventDefault(),this.saveCellEdit(t,e,i)):"Escape"===s.key&&(s.preventDefault(),this.cancelCellEdit(t,e))}),!s||"checkbox"!==s.type&&"SELECT"!==s.tagName||!1===i.autoSave||s.addEventListener("change",()=>{this.saveCellEdit(t,e,i)}),n?.addEventListener("click",()=>{this.saveCellEdit(t,e,i)}),l?.addEventListener("click",()=>{this.cancelCellEdit(t,e)})}async saveCellEdit(t,e,i){const s=t.querySelector(".cell-input");if(!s)return;let n;n="checkbox"===s.type?s.checked:(s.tagName,s.value);const l=this.model.get?this.model.get(e):this.model[e];try{this.model.save?await this.model.save({[e]:n}):this.model[e]=n,this.exitEditMode(t,e,n),this.emit("cell:save",{row:this,model:this.model,column:e,oldValue:l,newValue:n})}catch(a){console.error("Failed to save cell edit:",a),this.emit("cell:save:error",{row:this,model:this.model,column:e,oldValue:l,newValue:n,error:a}),t.classList.add("saving-error"),setTimeout(()=>t.classList.remove("saving-error"),3e3)}}cancelCellEdit(t,e){const i=t.dataset.originalContent;this.exitEditMode(t,e,null,i),this.emit("cell:cancel",{row:this,model:this.model,column:e})}exitEditMode(t,e,s=null,n=null){const l=t.closest("td").querySelector(".cell-content");if(l){if(null!==s){const t=this.columns.find(t=>t.key===e);let n=s;t&&t.formatter&&"string"==typeof t.formatter&&(n=i.pipe(s,t.formatter)),l.innerHTML=this.escapeHtml(n)}else n&&(l.innerHTML=n);l.style.display=""}t.remove(),this.editingCells.delete(e)}escapeHtml(t){if(null==t)return"";const e=document.createElement("div");return e.textContent=t,e.innerHTML}select(){super.select(),this.addClass("selected");const t=this.element?.querySelector(".mojo-select-cell");t&&t.classList.add("selected")}deselect(){super.deselect(),this.removeClass("selected");const t=this.element?.querySelector(".mojo-select-cell");t&&t.classList.remove("selected")}}const d={exact:{display:"is",description:"Exact match"},in:{display:"in",description:"Match any of the values (comma-separated)"},not:{display:"is not",description:"Does not match"},not_in:{display:"not in",description:"Does not match any of the values"},gt:{display:">",description:"Greater than"},gte:{display:">=",description:"Greater than or equal to"},lt:{display:"<",description:"Less than"},lte:{display:"<=",description:"Less than or equal to"},contains:{display:"contains",description:"Contains substring (case-sensitive)"},icontains:{display:"contains",description:"Contains substring (case-insensitive)"},startswith:{display:"starts with",description:"Starts with substring (case-sensitive)"},istartswith:{display:"starts with",description:"Starts with substring (case-insensitive)"},endswith:{display:"ends with",description:"Ends with substring (case-sensitive)"},iendswith:{display:"ends with",description:"Ends with substring (case-insensitive)"},isnull:{display:t=>"true"===t||!0===t?"is null":"is not null",description:"Check if value is null or not"},range:{display:"between",description:"Between two values (comma-separated)"}};function h(t){if(!t||"string"!=typeof t)return{field:t,lookup:null};const e=t.split("__");if(1===e.length)return{field:t,lookup:null};const i=e[e.length-1];return d[i]?{field:e.slice(0,-1).join("__"),lookup:i}:{field:t,lookup:null}}function u(t,e,i){if(!t||null==e)return"";const{field:s,lookup:n}=h(t),l=d[n];if(e&&"object"==typeof e&&!Array.isArray(e)){const t=void 0!==e.start&&null!==e.start&&""!==e.start,s=void 0!==e.end&&null!==e.end&&""!==e.end;return t||s?t&&s?`${i} between '${e.start}' and '${e.end}'`:t?`${i} from '${e.start}'`:`${i} until '${e.end}'`:`${i} is '${JSON.stringify(e)}'`}const a=Array.isArray(e)?e.join(","):String(e);if(!n||"exact"===n)return`${i} is '${a}'`;if("in"===n||"not_in"===n){const t=a.split(",").map(t=>t.trim()).filter(t=>t);if(0===t.length)return`${i} ${l.display}`;const e=t.map(t=>`'${t}'`).join(", ");return`${i} ${l.display} ${e}`}if("range"===n){const t=a.split(",").map(t=>t.trim()).filter(t=>t);return 2===t.length?`${i} between '${t[0]}' and '${t[1]}'`:`${i} ${l.display} '${a}'`}return"isnull"===n?`${i} ${"function"==typeof l.display?l.display(a):l.display}`:l?`${i} ${l.display} '${a}'`:`${i} is '${a}'`}const m={LOOKUPS:d,parseFilterKey:h,formatFilterDisplay:u,getLookupDescription:function(t){const e=d[t];return e?e.description:"Exact match"},isValidLookup:function(t){return t&&d.hasOwnProperty(t)},getAvailableLookups:function(){return Object.keys(d)},buildFilterKey:function(t,e=null){return t?e?`${t}__${e}`:t:""}};class TableView extends a{constructor(t={}){super({className:"table-view-component",itemClass:t.itemClass||TableRow,selectionMode:t.selectable?"multiple":"none",emptyMessage:t.emptyMessage||"No data available",addButtonIcon:t.addButtonIcon||"bi bi-plus-circle",...t}),this.isFullscreen=!1,this.columns=t.columns||[],this.actions=t.actions||null,this.contextMenu=t.contextMenu||null,this.batchActions=t.batchActions||null,this.searchable=!1!==t.searchable,this.sortable=!1!==t.sortable,this.filterable=!1!==t.filterable,this.paginated=!1!==t.paginated,this.clickAction=t.clickAction||"view",this.itemView=t.itemView,this.addForm=t.addForm,this.editForm=t.editForm,this.deleteTemplate=t.deleteTemplate,this.formDialogConfig=t.formDialogConfig||{},this.viewDialogOptions=t.viewDialogOptions||{},this.exportOptions=t.exportOptions||null,this.options.showExport&&!this.exportOptions&&(this.exportOptions=[{format:"csv",label:"Export as CSV",icon:"bi bi-file-earmark-spreadsheet"},{format:"json",label:"Export as JSON",icon:"bi bi-file-earmark-code"}]),this.exportSource=t.exportSource||"remote",this.filters={},this.additionalFilters=t.filters||[],this.hideActivePills=!0===t.hideActivePills,this.hideActivePillNames=t.hideActivePillNames||[],this.rowAction=t.rowAction||"row-click",this.batchBarLocation=t.batchBarLocation||"bottom",this.options.addButtonLabel=t.addButtonLabel||"Add",this.toolbarButtons=t.toolbarButtons||[],this.tableOptions={striped:!0,bordered:!1,hover:!0,responsive:!1,size:null,...t.tableOptions},this.searchPlacement=t.searchPlacement||"toolbar",this.searchPlaceholder=t.searchPlaceholder||"Search...",this.initializeColumns(),this.extractColumnFilters(),this.footerTotalColumns=this.columns.filter(t=>!0===t.footer_total),this.hasFooterTotals=this.footerTotalColumns.length>0,this.template=this.buildTableTemplate(),this.setupCollectionListeners()}setupCollectionListeners(){this.hasFooterTotals&&this.collection&&this.collection.on("reset add remove change",()=>{this.updateFooterTotals()})}initializeColumns(){this.columns.forEach(t=>{!t.key&&t.name&&(t.key=t.name),t.label||t.title||(t.label=t.key.charAt(0).toUpperCase()+t.key.slice(1))})}getResponsiveClasses(t){if(!t)return"";const e=["sm","md","lg","xl","xxl"];if("string"==typeof t)return e.includes(t)?`d-none d-${t}-table-cell`:(console.warn(`Invalid visibility breakpoint: ${t}. Valid options are: ${e.join(", ")}`),"");if("object"==typeof t){const i=[];if(t.hide){if(!e.includes(t.hide))return console.warn(`Invalid hide breakpoint: ${t.hide}. Valid options are: ${e.join(", ")}`),"";i.push(`d-table-cell d-${t.hide}-none`)}if(t.show){if(!e.includes(t.show))return console.warn(`Invalid show breakpoint: ${t.show}. Valid options are: ${e.join(", ")}`),"";t.hide?i.push(`d-${t.show}-table-cell`):i.push(`d-none d-${t.show}-table-cell`)}return i.join(" ")}return""}parseColumnKey(t){const e=t.split("|");return{fieldKey:e[0],formatter:e[1]||null}}updateFooterTotals(){if(!this.hasFooterTotals||!this.element)return;const t=this.calculateFooterTotals();let e=0;this.columns.forEach(i=>{if(i.footer_total){const s=`col_${e}`,n=this.element.querySelector(`[data-total-column="${s}"]`);if(n&&t[s]){const e=this.parseColumnKey(i.key).formatter||i.formatter;let l;l=e&&"string"==typeof e?this.formatValue(t[s].value,e):t[s].value,n.textContent=l}e++}})}formatValue(t,e){try{return i.pipe(t,e)}catch(s){return console.warn("Error formatting value:",s),t}}calculateFooterTotals(){if(!this.hasFooterTotals||!this.collection||0===this.collection.length)return{};const t={};return this.footerTotalColumns.forEach((e,i)=>{const{fieldKey:s,formatter:n}=this.parseColumnKey(e.key);let l=0;this.collection.forEach(t=>{const e=t.get?t.get(s):t[s],i=parseFloat(e)||0;l+=i}),e.key,this.collection.length,t[`col_${i}`]={value:l,formatter:n||e.formatter,fieldKey:s,originalKey:e.key}}),t}extractColumnFilters(){this.filters={},this.columns.forEach(t=>{if(t.filter){const{fieldKey:e}=this.parseColumnKey(t.key);this.filters[e]=t.filter}})}isSelectable(){return this.batchActions&&this.batchActions.length>0&&"multiple"==this.selectionMode}buildTableTemplate(){const t="top"===this.batchBarLocation?this.buildBatchActionsPanel():"",e="bottom"===this.batchBarLocation?this.buildBatchActionsPanel():"";return`\n <div class="mojo-table-wrapper">\n ${this.buildToolbarTemplate()}\n ${t}\n <div class="table-container"${(()=>{const t=this.tableOptions&&null!=this.tableOptions.fontSize?this.tableOptions.fontSize:this.options&&this.options.fontSize,e="sm"===t?"0.9rem":"xs"===t?"0.8rem":t?String(t):null;return e?` style="font-size: ${e};"`:""})()}>\n {{#loading}}\n <div class="mojo-table-loading d-flex justify-content-center align-items-center py-5">\n <div class="spinner-border" role="status">\n <span class="visually-hidden">Loading...</span>\n </div>\n </div>\n {{/loading}}\n {{^loading}}\n {{#isEmpty}}\n <div class="table-empty text-center py-5">\n <i class="bi bi-inbox fa-2x mb-2 text-muted"></i>\n <p class="text-muted">{{emptyMessage}}</p>\n </div>\n {{/isEmpty}}\n {{^isEmpty}}\n <table class="${this.buildTableClasses()}">\n ${this.buildTableHeaderTemplate()}\n <tbody data-container="items"></tbody>\n ${this.hasFooterTotals?this.buildTableFooterTemplate():""}\n </table>\n {{/isEmpty}}\n {{/loading}}\n </div>\n ${e}\n ${this.buildPaginationTemplate()}\n </div>\n `}buildTableClasses(){let t=["table"];return this.tableOptions.striped&&t.push("table-striped"),this.tableOptions.bordered&&t.push("table-bordered"),this.tableOptions.hover&&t.push("table-hover"),this.tableOptions.responsive&&t.push("table-responsive"),this.tableOptions.background&&t.push(`table-${this.tableOptions.background}`),"sm"===this.tableOptions.size&&t.push("table-sm"),"lg"===this.tableOptions.size&&t.push("table-lg"),t.join(" ")}buildToolbarTemplate(){return this.searchable||this.filterable?`\n <div class="table-action-buttons mb-3">\n <div class="d-flex align-items-center gap-2">\n ${this.buildActionButtonsTemplate()}\n ${this.filterable?this.buildFilterDropdownTemplate():""}\n ${this.searchable&&"toolbar"===this.searchPlacement?this.buildSearchTemplate():""}\n\n </div>\n <div data-container="filter-pills"></div>\n </div>\n `:""}buildActionButtonsTemplate(){let t=[];if(t.push('\n <button class="btn btn-sm btn-outline-secondary btn-refresh"\n data-action="refresh"\n title="Refresh">\n <i class="bi bi-arrow-clockwise"></i>\n </button>\n '),this.isFullscreenSupported()&&t.push('\n <button class="btn btn-sm btn-outline-secondary btn-fullscreen"\n data-action="toggle-fullscreen"\n title="Toggle Fullscreen">\n <i class="bi bi-fullscreen"></i>\n </button>\n '),this.options.showAdd&&t.push(`\n <button class="btn btn-sm btn-success btn-add"\n data-action="add"\n title="${this.options.addButtonLabel}">\n <i class="${this.options.addButtonIcon} me-1"></i>\n <span class="d-none d-lg-inline">${this.options.addButtonLabel}</span>\n </button>\n `),this.options.showExport)if(this.exportOptions&&this.exportOptions.length>1){const e=this.exportOptions.map(t=>`\n <li>\n <a class="dropdown-item" href="#" data-action="export" data-format="${t.format}">\n <i class="${t.icon||"bi bi-file-earmark-arrow-down"} me-2"></i>${t.label}\n </a>\n </li>\n `).join("");t.push(`\n <div class="dropdown">\n <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button"\n data-bs-toggle="dropdown" aria-expanded="false" title="Export">\n <i class="bi bi-download me-1"></i>\n <span class="d-none d-lg-inline">Export</span>\n </button>\n <ul class="dropdown-menu">\n ${e}\n </ul>\n </div>\n `)}else{const e=this.exportOptions&&1===this.exportOptions.length?this.exportOptions[0].format:"json";t.push(`\n <button class="btn btn-sm btn-outline-secondary btn-export"\n data-action="export"\n data-format="${e}"\n title="Export">\n <i class="bi bi-download me-1"></i>\n <span class="d-none d-lg-inline">Export</span>\n </button>\n `)}return this.toolbarButtons&&this.toolbarButtons.length>0&&this.toolbarButtons.forEach((e,i)=>{const{label:s="Button",icon:n="",action:l="",handler:a=null,variant:o="outline-secondary",title:r=s,className:c="",permissions:d=null}=e;if(d&&!this.checkPermissions(d))return;const h=n?`<i class="${n} me-1"></i>`:"",u=`<span class="d-none d-lg-inline">${s}</span>`;let m="";a?m=`data-action="custom-toolbar-button" data-button-index="${i}"`:l&&(m=`data-action="${l}"`);const p=`btn btn-sm btn-${o} ${c}`.trim();t.push(`\n <button class="${p}"\n ${m}\n title="${r}">\n ${h}${u}\n </button>\n `)}),t.join("")}buildSearchTemplate(){return'\n <div class="flex-grow-1" style="max-width: 400px;">\n <div class="input-group input-group-sm">\n <span class="input-group-text">\n <i class="bi bi-search"></i>\n </span>\n <input type="search"\n class="form-control"\n placeholder="{{searchPlaceholder}}"\n data-filter="search"\n data-change-action="apply-search"\n value="{{collection.params.search}}"\n aria-label="Search">\n {{#searchValue}}\n <button class="btn btn-outline-secondary" type="button"\n data-action="clear-search"\n title="Clear search">\n <i class="bi bi-x"></i>\n </button>\n {{/searchValue}}\n </div>\n </div>\n '}buildFilterDropdownTemplate(){return this.filters&&Object.keys(this.filters).length>0||this.additionalFilters&&this.additionalFilters.length>0?`\n <div class="dropdown">\n <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button"\n data-bs-toggle="dropdown" aria-expanded="false">\n <i class="bi bi-filter me-1"></i>\n <span class="d-none d-lg-inline">Add Filter</span>\n </button>\n <div class="dropdown-menu" style="min-width: 250px;">\n ${this.buildFilterList()}\n </div>\n </div>\n `:""}buildFilterList(){const t=this.getAllAvailableFilters(),e=this.getActiveFilters();return 0===t.length?'<div class="dropdown-item-text text-muted">No filters available</div>':`\n ${t.map(t=>{const i=e.hasOwnProperty(t.key),s=i?"active":"",n=this.getFilterIcon(t.type||t.config?.type);return`\n <button class="dropdown-item ${s}"\n data-action="add-filter"\n data-filter-key="${t.key}">\n <i class="bi bi-${n} me-2"></i>\n ${t.label}\n ${i?'<i class="bi bi-check-circle ms-auto"></i>':""}\n </button>\n `}).join("")}\n ${Object.keys(e).length>0?'\n <div class="dropdown-divider"></div>\n <button class="dropdown-item text-danger" data-action="clear-all-filters">\n <i class="bi bi-x-circle me-2"></i>Clear All Filters\n </button>\n ':""}\n `}updateFilterPills(){const t=this.element?.querySelector('[data-container="filter-pills"]');if(!t)return;this.getActiveFilters();const e=this.buildActivePills();t.innerHTML=e}updateSearchInputs(t){const e=this.element?.querySelectorAll('[data-filter="search"]');e&&e.forEach(e=>{e.value=t||""})}buildActivePills(){if(this.hideActivePills)return"";const t=this.getActiveFilters(),e=t.search&&""!==t.search.toString().trim();let i=Object.entries(t).filter(([t,e])=>e&&""!==e.toString().trim()&&"search"!==t);return this.hideActivePillNames&&this.hideActivePillNames.length>0&&(i=i.filter(([t])=>!this.hideActivePillNames.includes(t))),0!==i.length||e?`\n <div class="row mt-2">\n <div class="col-12">\n <div class="d-flex flex-wrap align-items-center">\n ${i.map(([t,e])=>{const{field:i}=h(t);return`\n <span class="badge bg-primary me-1 mb-1 py-1 px-2 position-relative" style="font-size: 0.75rem;">\n <i class="bi bi-filter me-1" style="font-size: 0.65rem;"></i>\n\n <button type="button" class="btn btn-link text-white p-0 ms-1"\n style="font-size: 0.65rem; line-height: 1;"\n data-action="edit-filter"\n data-filter="${t}"\n title="Edit filter">\n ${u(t,e,this.getFilterLabel(i))}\n </button>\n\n <button type="button" class="btn-close btn-close-white ms-1"\n style="font-size: 0.6rem; width: 0.5rem; height: 0.5rem;"\n data-action="remove-filter"\n data-filter="${t}"\n title="Remove filter">\n </button>\n </span>\n `}).join("")}\n ${i.length>1||i.length>0&&e||0===i.length&&e?'\n <button class="btn btn-sm btn-outline-secondary mb-1 py-0 px-2" style="font-size: 0.75rem;" data-action="clear-all-filters">\n <i class="bi bi-x-circle me-1" style="font-size: 0.7rem;"></i>\n <small>Clear All</small>\n </button>\n ':""}\n </div>\n </div>\n </div>\n `:""}buildTableHeaderTemplate(){let t="";return this.isSelectable()&&(t+='\n <th style="width: 40px; padding: 0;">\n <div class="mojo-select-all-cell" data-action="select-all">\n <div class="mojo-checkbox">\n <i class="bi bi-check"></i>\n </div>\n </div>\n </th>\n '),this.columns.forEach(e=>{const{fieldKey:i}=this.parseColumnKey(e.key),s=this.sortable&&!1!==e.sortable,n=this.getSortBy()===i?this.getSortDirection():null,l=this.getSortIcon(n),a=e.label||e.title||i,o=this.getResponsiveClasses(e.visibility);t+=`\n <th class="${s?"sortable":""} ${o}">\n <div class="d-flex align-items-center">\n <span>${a}</span>\n ${s?`\n <div class="dropdown d-inline-block ms-2">\n <button class="btn btn-sm btn-link p-0 text-decoration-none" type="button"\n data-bs-toggle="dropdown" aria-expanded="false"\n data-column="${i}">\n ${l}\n </button>\n <ul class="dropdown-menu dropdown-menu-end">\n <li><a class="dropdown-item ${"asc"===n?"active":""}"\n data-action="sort" data-field="${i}" data-direction="asc">\n <i class="bi bi-sort-alpha-down me-2"></i>Sort A-Z\n </a></li>\n <li><a class="dropdown-item ${"desc"===n?"active":""}"\n data-action="sort" data-field="${i}" data-direction="desc">\n <i class="bi bi-sort-alpha-down-alt me-2"></i>Sort Z-A\n </a></li>\n <li><a class="dropdown-item ${null===n?"active":""}"\n data-action="sort" data-field="${i}" data-direction="none">\n <i class="bi bi-x-circle me-2"></i>No Sort\n </a></li>\n </ul>\n </div>\n `:""}\n </div>\n </th>\n `}),this.actions?t+="<th>Actions</th>":this.contextMenu&&(t+='<th style="width: 1px;"></th>'),`\n <thead>\n <tr>\n ${t}\n </tr>\n </thead>\n `}buildTableFooterTemplate(){let t="";this.isSelectable()&&(t+="<td></td>");let e=0;return this.columns.forEach((i,s)=>{const n=this.getResponsiveClasses(i.visibility);if(i.footer_total){const s=`col_${e}`,l=this.parseColumnKey(i.key).formatter||i.formatter;let a;a=l&&"string"==typeof l?`{{{footerTotals.${s}.value|${l}}}}`:`{{footerTotals.${s}.value}}`,t+=`<td class="table-footer-total ${n}" data-total-column="${s}">${a}</td>`,e++}else t+=0===s?`<td class="table-footer-label ${n}"><strong>Totals</strong></td>`:`<td class="${n}"></td>`}),(this.actions||this.contextMenu)&&(t+="<td></td>"),`\n <tfoot>\n <tr class="table-totals-row">\n ${t}\n </tr>\n </tfoot>\n `}buildBatchActionsPanel(){if(!this.batchActions||0===this.batchActions.length)return"";if("top"===this.batchBarLocation){let t="";return this.batchActions.forEach(e=>{t+=`\n <button class="btn btn-sm btn-outline-secondary" data-action="batch-${e.action}" title="${e.label}">\n <i class="${e.icon} me-1"></i>\n <span class="d-none d-lg-inline">${e.label}</span>\n </button>\n `}),`\n <div class="batch-actions-panel-top alert alert-info d-none mb-3" role="alert">\n <div class="d-flex justify-content-between align-items-center">\n <div class="d-flex align-items-center">\n <strong class="me-2">\n <span class="batch-select-count">0</span> ${this.options.batchPanelTitle||"items"} selected\n </strong>\n </div>\n <div class="d-flex gap-2 align-items-center">\n ${t}\n <button class="btn btn-sm btn-outline-secondary" data-action="clear-selection" title="Clear Selection">\n <i class="bi bi-x-circle me-1"></i>\n <span class="d-none d-lg-inline">Clear</span>\n </button>\n </div>\n </div>\n </div>\n `}{let t="";return this.batchActions.forEach(e=>{t+=`\n <div class="batch-select-action text-center px-2" data-action="batch-${e.action}">\n <div class="batch-action-icon fs-3">\n <i class="${e.icon}"></i>\n </div>\n <div class="batch-action-title small">${e.label}</div>\n </div>\n `}),`\n <div class="batch-actions-panel rounded-start rounded-end" style="display: none;">\n <div class="batch-select-panel rounded-start rounded-end">\n <div class="row g-0">\n <div class="col-auto">\n <div class="batch-select-count rounded-start">0</div>\n </div>\n <div class="col">\n <div class="ps-2 batch-select-title">${this.options.batchPanelTitle||"Rows"}</div>\n </div>\n <div class="col">\n <div class="batch-select-actions d-flex justify-content-end">\n ${t}\n </div>\n </div>\n <div class="col-auto">\n <div class="batch-select-end rounded-end"></div>\n </div>\n </div>\n </div>\n </div>\n `}}buildPaginationTemplate(){return this.paginated?'\n <div class="table-status-bar mt-3">\n <div class="d-flex flex-column flex-lg-row justify-content-center justify-content-lg-between align-items-center gap-3">\n <div class="d-flex flex-column flex-sm-row align-items-center gap-2 gap-sm-3 text-center text-lg-start">\n <span class="text-muted">\n Showing <span data-value="start">0</span> to <span data-value="end">0</span>\n of <span data-value="total">0</span> entries\n </span>\n <div class="d-flex align-items-center">\n <label class="form-label me-2 mb-0">Show:</label>\n <select class="form-select form-select-sm" style="width: auto;" data-change-action="page-size">\n <option value="5">5</option>\n <option value="10">10</option>\n <option value="25">25</option>\n <option value="50">50</option>\n <option value="100">100</option>\n </select>\n </div>\n </div>\n <nav aria-label="Table pagination">\n <ul class="pagination pagination-sm mb-0 justify-content-center" data-container="pagination">\n \x3c!-- Pagination will be rendered here --\x3e\n </ul>\n </nav>\n </div>\n </div>\n ':""}_createItemView(t,e){const i=new this.itemClass({model:t,index:e,listView:this,tableView:this,template:this.itemTemplate,columns:this.columns,actions:this.actions,contextMenu:this.contextMenu,batchActions:this.batchActions,containerId:"items"});return this.itemViews.set(t.id,i),i.on("item:select",t=>{this._onItemSelect(t),this.updateBatchActionsPanel()}),i.on("item:deselect",t=>{this._onItemDeselect(t),this.updateBatchActionsPanel()}),i.on("row:click",this._onRowClick.bind(this)),i.on("row:view",this._onRowView.bind(this)),i.on("row:edit",this._onRowEdit.bind(this)),i.on("row:delete",this._onRowDelete.bind(this)),i.on("cell:edit",this._onCellEdit.bind(this)),i.on("cell:save",this._onCellSave.bind(this)),i.on("cell:cancel",this._onCellCancel.bind(this)),i}async onMounted(){await super.onMounted();const t=this.getActiveFilters();this.collection&&Object.keys(t).length>0&&this.updateFilterPills(),this.setupSearchClearListener()}setupSearchClearListener(){this.element&&this.element.querySelectorAll('input[type="search"][data-filter="search"]').forEach(t=>{t.addEventListener("input",t=>{""===t.target.value&&this.getActiveFilters().search&&this.onActionClearSearch(t,t.target)})})}_onRowClick(t){if(this.emit("row:click",t),this.options.onRowClick)return this.options.onRowClick(t.model,t.event);"view"===this.clickAction?this._onRowView(t):"edit"===this.clickAction&&this._onRowEdit(t)}getModelClass(t){return this.collection?.ModelClass?this.collection.ModelClass:this.collection?.model?this.collection.model:t?.constructor?t.constructor:null}getModelName(t){const e=this.getModelClass(t);return e&&(e.MODEL_NAME||e.name.replace(/Model$/,""))||"Item"}getItemViewClass(t){if(this.itemView)return this.itemView;const e=this.getModelClass(t);return e?.VIEW_CLASS?e.VIEW_CLASS:null}getAddFormConfig(t){return this.addForm||t?.ADD_FORM||this.editForm||t?.EDIT_FORM}getEditFormConfig(t){return this.editForm||t?.EDIT_FORM||this.addForm||t?.ADD_FORM}getFormDialogConfig(t){return{...t?.FORM_DIALOG_CONFIG,...this.formDialogConfig}}renderTemplateString(t,e){return t?s.render(t,e):""}async _onRowView(t){if(this.emit("row:view",t),this.options.onItemView)return void(await this.options.onItemView(t.model,t.event));const e=this.getItemViewClass(t.model);if(e){const i=new e({model:t.model,collection:this.collection});await o.dialog({header:!1,body:i,size:"lg",centered:!1,...this.getFormDialogConfig(this.getModelClass(t.model)),...this.viewDialogOptions})}else await o.data({title:`View ${this.getModelName(t.model)} #${t.model.id}`,model:t.model})}async _onRowEdit(t){if(this.emit("row:edit",t),this.options.onItemEdit)return void(await this.options.onItemEdit(t.model,t.event));const e=this.getModelClass(t.model);let i=this.getEditFormConfig(e);if(i){i.fields||(i={title:`Edit ${this.getModelName(t.model)}`,fields:i});const s=await o.modelForm({model:t.model,...i,...this.getFormDialogConfig(e)});if(!s)return;if(!s.success||!s?.result?.data.status)return void o.showError(s?.result?.data?.error||s?.result?.message||"An error occurred")}else{const e=await o.dialog({title:`Edit ${this.getModelName(t.model)} #${t.model.id}`,body:new r({model:t.model,fields:this.options.formFields||[]})});if(e){const i=await t.model.save(e);if(!i.data?.status)return void o.showError(i.data.error||"An error occurred");await this.refresh()}}}async _onRowDelete(t){if(this.emit("row:delete",t),this.options.onItemDelete)return void(await this.options.onItemDelete(t.model,t.event));const e=this.getModelClass(t.model),i=this.deleteTemplate||e?.DELETE_TEMPLATE||'Are you sure you want to delete this {{name||"item"}}?',s=this.renderTemplateString(i,t.model);await o.confirm({message:s||"Are you sure you want to delete this item?",title:"Confirm Delete",confirmText:"Delete",confirmClass:"btn-danger"})&&(await t.model.destroy(),this.collection.fetch())}_onCellEdit(t){this.emit("cell:edit",t)}async _onCellSave(t){this.emit("cell:save",t)}_onCellCancel(t){this.emit("cell:cancel",t)}isFullscreenSupported(){return!!(document.fullscreenEnabled||document.mozFullScreenEnabled||document.webkitFullscreenEnabled||document.msFullscreenEnabled)}async onActionToggleFullscreen(t,e){this.isFullscreen?await this.exitFullscreen():await this.enterFullscreen()}async enterFullscreen(){try{this.element.requestFullscreen?await this.element.requestFullscreen():this.element.mozRequestFullScreen?await this.element.mozRequestFullScreen():this.element.webkitRequestFullscreen?await this.element.webkitRequestFullscreen():this.element.msRequestFullscreen&&await this.element.msRequestFullscreen(),this.isFullscreen=!0,this.element.classList.add("table-fullscreen"),this.updateFullscreenButton(),this.setupFullscreenListeners(),this.emit("table:fullscreen:enter")}catch(t){console.warn("Could not enter fullscreen:",t)}}async exitFullscreen(){try{document.exitFullscreen?await document.exitFullscreen():document.mozCancelFullScreen?await document.mozCancelFullScreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen(),this.isFullscreen=!1,this.element.classList.remove("table-fullscreen"),this.updateFullscreenButton(),this.emit("table:fullscreen:exit")}catch(t){console.warn("Could not exit fullscreen:",t)}}updateFullscreenButton(){const t=this.element?.querySelector(".btn-fullscreen"),e=t?.querySelector("i");t&&e&&(this.isFullscreen?(e.className="bi bi-fullscreen-exit",t.title="Exit Fullscreen"):(e.className="bi bi-fullscreen",t.title="Enter Fullscreen"))}setupFullscreenListeners(){if(this._fullscreenHandler)return;const t=()=>{!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)&&this.isFullscreen&&(this.isFullscreen=!1,this.element.classList.remove("table-fullscreen"),this.updateFullscreenButton(),this.emit("table:fullscreen:exit"))};document.addEventListener("fullscreenchange",t),document.addEventListener("mozfullscreenchange",t),document.addEventListener("webkitfullscreenchange",t),document.addEventListener("msfullscreenchange",t),this._fullscreenHandler=t}cleanupFullscreenListeners(){this._fullscreenHandler&&(document.removeEventListener("fullscreenchange",this._fullscreenHandler),document.removeEventListener("mozfullscreenchange",this._fullscreenHandler),document.removeEventListener("webkitfullscreenchange",this._fullscreenHandler),document.removeEventListener("msfullscreenchange",this._fullscreenHandler),this._fullscreenHandler=null)}destroy(){this.cleanupFullscreenListeners(),super.destroy()}async onActionRefresh(t,e){await this.refresh()}async onActionAdd(t,e){if(this.options.onAdd)return this.emit("table:add",{event:t}),void(await this.options.onAdd(t));this.emit("table:add",{event:t});const i=this.getModelClass();if(!i)return void console.warn("Cannot determine Model class for add operation");let s=this.getAddFormConfig(i);if(s){const t=new i;s.fields||(s={title:`Add ${this.getModelName()}`,fields:s});const e=await o.form({model:t,...s,...this.getFormDialogConfig(i)});if(e){this.options.addRequiresActiveGroup&&(e.group=this.getApp().activeGroup.id),this.options.addRequiresActiveUser&&(e.user=this.getApp().activeUser.id),this.options.addFormDefaults&&Object.assign(e,this.options.addFormDefaults);const i=await t.save(e);if(!i?.data.status)return void o.showError(i?.data.error||"An error occurred");this.collection&&this.collection.add(t),await this.refresh()}}else{const t=new i,e=await o.dialog({title:`Add ${this.getModelName()}`,body:new r({model:t,fields:this.options.formFields||[]})});if(e){const i=await t.save(e);if(!i?.data.status)return void o.showError(i.data.error||"An error occurred");this.collection&&this.collection.add(t),await this.refresh()}}}async onActionExport(t,e){const i=e.getAttribute("data-format")||"json";this.emit("table:export",{format:i,source:this.exportSource,event:t}),"remote"===this.exportSource?this.collection?await this.collection.download(i):console.warn("TableView: Cannot export from remote without a collection."):this.options.onExport?await this.options.onExport(this.collection?.toJSON()||[],i):console.warn("TableView: onExport handler not implemented for local export.")}async onActionApplySearch(t,e){const i=e.value.trim();this.collection&&(this.setFilter("search",i),this.collection.params.start=0,this.collection.restEnabled?await this.collection.fetch():await this.render()),this.updateFilterPills(),this.emit("table:search",{searchTerm:i,event:t}),this.emit("params-changed")}async onActionClearSearch(t,e){this.setFilter("search",null),this.collection&&(this.collection.params.start=0,this.collection.restEnabled&&await this.collection.fetch()),await this.render(),this.updateFilterPills(),this.emit("table:search",{searchTerm:"",event:t}),this.emit("params-changed")}getSortBy(){const t=this.collection?.params?.sort;return t?t.startsWith("-")?t.slice(1):t:null}getSortDirection(){const t=this.collection?.params?.sort;return t&&t.startsWith("-")?"desc":"asc"}getSortIcon(t){return"asc"===t?'<i class="bi bi-sort-alpha-down text-primary"></i>':"desc"===t?'<i class="bi bi-sort-alpha-down-alt text-primary"></i>':'<i class="bi bi-three-dots-vertical text-muted"></i>'}async onActionSort(t,e){t.preventDefault();const i=e.getAttribute("data-field"),s=e.getAttribute("data-direction");if(this.collection){let t;if(t="none"===s?void 0:"desc"===s?`-${i}`:i,this.collection.setParams({...this.collection.params,sort:t,start:0}),this.collection.restEnabled)await this.collection.fetch();else{if(t){const e=t.startsWith("-"),i=e?t.slice(1):t;this.collection.sort((t,s)=>{const n=t.get(i),l=s.get(i);return n<l?e?1:-1:n>l?e?-1:1:0})}this.render()}}this.updateSortIcons(),this.emit("table:sort",{field:i,event:t}),this.emit("params-changed")}updateSortIcons(){if(!this.element)return;const t=this.getSortBy(),e=this.getSortDirection();this.columns.forEach(i=>{if(this.sortable&&!1!==i.sortable){const{fieldKey:s}=this.parseColumnKey(i.key),n=this.element.querySelector(`[data-bs-toggle="dropdown"][data-column="${s}"]`);if(n){const i=t===s,l=this.getSortIcon(i?e:null);n.innerHTML=l;const a=n.nextElementSibling;if(a){const n=a.querySelector(`[data-field="${s}"][data-direction="asc"]`),l=a.querySelector(`[data-field="${s}"][data-direction="desc"]`),o=a.querySelector(`[data-field="${s}"][data-direction="none"]`);n&&n.classList.toggle("active",i&&"asc"===e),l&&l.classList.toggle("active",i&&"desc"===e),o&&o.classList.toggle("active",!i||t!==s)}}}})}async onActionSelectAll(t,e){t.stopPropagation();const i=this.itemViews.size>0&&Array.from(this.itemViews.values()).every(t=>t.selected);i?this.clearSelection():this.forEachItem(t=>{t.selected||t.select()});const s=this.element?.querySelector(".mojo-select-all-cell");s&&s.classList.toggle("selected",!i),this.updateBatchActionsPanel()}async onBeforeRender(){this.searchValue=this.getActiveFilters().search||"",this.footerTotals=this.calculateFooterTotals()}async onAfterRender(){if(await super.onAfterRender(),this.hasFooterTotals&&this.updateFooterTotals(),this.paginated&&this.collection){const t=this.collection.meta?.count||this.collection.length(),e=this.collection.params?.start||0,i=this.collection.params?.size||10,s=Math.min(e+i,t),n=this.element.querySelector('[data-value="start"]'),l=this.element.querySelector('[data-value="end"]'),a=this.element.querySelector('[data-value="total"]');n&&(n.textContent=e+1),l&&(l.textContent=s),a&&(a.textContent=t);const o=this.element.querySelector('[data-change-action="page-size"]');o&&(o.value=i),this.renderPagination()}this.updateSortIcons(),this.updateFilterPills(),this.setupSearchClearListener()}renderPagination(){const t=this.element.querySelector('[data-container="pagination"]');if(!t||!this.collection)return;const e=this.collection.meta?.count||this.collection.length(),i=this.collection.params?.size||10,s=this.collection.params?.start||0,n=Math.floor(s/i)+1,l=Math.ceil(e/i);if(l<=1)return void(t.innerHTML="");const a=n>1?n-1:l,o=n<l?n+1:1,r=[];r.push(`\n <li class="page-item">\n <a class="page-link" href="#" data-action="page" data-page="${a}">\n <i class="bi bi-chevron-left"></i>\n </a>\n </li>\n `);const c=/* @__PURE__ */new Set([1,l]);for(let u=n-1;u<=n+1;u++)u>=1&&u<=l&&c.add(u);const d=Array.from(c).sort((t,e)=>t-e);let h=0;for(const u of d)h&&u-h>1&&r.push('\n <li class="page-item disabled"><span class="page-link">…</span></li>\n '),r.push(`\n <li class="page-item ${u===n?"active":""}">\n <a class="page-link" href="#" data-action="page" data-page="${u}">${u}</a>\n </li>\n `),h=u;r.push(`\n <li class="page-item">\n <a class="page-link" href="#" data-action="page" data-page="${o}">\n <i class="bi bi-chevron-right"></i>\n </a>\n </li>\n `),t.innerHTML=r.join("")}async onActionPage(t,e){t.preventDefault();const i=parseInt(e.getAttribute("data-page"),10),s=this.collection.params?.size||10,n=this.collection.meta?.count||this.collection.length(),l=Math.max(1,Math.ceil(n/s));let a=isNaN(i)?1:i;a<1&&(a=l),a>l&&(a=1),this.collection.setParams({...this.collection.params,start:(a-1)*s}),this.collection.restEnabled?await this.collection.fetch():this.render(),this.emit("table:page",{page:a,event:t}),this.emit("params-changed")}async onChangePageSize(t,e){const i=parseInt(e.value);this.collection&&(this.collection.setParams({...this.collection.params,start:0,size:i}),this.collection.restEnabled&&await this.collection.fetch(),this.render()),this.emit("table:pagesize",{size:i,event:t}),this.emit("params-changed")}getActiveFilters(){if(!this.collection?.params)return{};const{start:t,size:e,sort:i,...s}=this.collection.params,n={},l=/* @__PURE__ */new Set;return this.getAllAvailableFilters().forEach(t=>{if("daterange"===t.config.type){const e=t.key,i=t.config.startName||"dr_start",a=t.config.endName||"dr_end",o=t.config.fieldName||"dr_field";s[o]===e&&(s[i]||s[a])&&(n[e]={start:s[i]||"",end:s[a]||""},l.add(i),l.add(a),l.add(o))}}),Object.keys(s).forEach(t=>{l.has(t)||(n[t]=s[t])}),Object.keys(n).forEach(t=>{if(n.hasOwnProperty(t)){const e=`${t}__in`;n.hasOwnProperty(e)&&(delete n[t],n[e]=n[e])}}),n}setFilter(t,e){if(!this.collection)return;const i=this.getFilterConfig(t);if(i&&"daterange"===i.type){const s=i.startName||"dr_start",n=i.endName||"dr_end",l=i.fieldName||"dr_field";delete this.collection.params[s],delete this.collection.params[n],delete this.collection.params[l],e&&"object"==typeof e&&(e.start||e.end)&&(e.start&&(this.collection.params[s]=e.start),e.end&&(this.collection.params[n]=e.end),this.collection.params[l]=t)}else{const{field:i,lookup:s}=h(t);if(delete this.collection.params[t],delete this.collection.params[i],delete this.collection.params[`${i}__in`],!e||Array.isArray(e)&&0===e.length)return;Array.isArray(e)?1===e.length?this.collection.params[i]=e[0]:this.collection.params[`${i}__in`]=e.join(","):this.collection.params[t]=e}}getAllAvailableFilters(){const t=[];return this.columns.forEach(e=>{if(e.filter){const{fieldKey:i}=this.parseColumnKey(e.key);t.push({key:i,label:e.filter.label||e.label||i,type:e.filter.type,config:e.filter})}}),this.additionalFilters&&Array.isArray(this.additionalFilters)&&this.additionalFilters.forEach(e=>{t.push({key:e.name||e.key,label:e.label,type:e.type,config:e})}),t}getFilterConfig(t){const e=this.columns.find(e=>{const{fieldKey:i}=this.parseColumnKey(e.key);return i===t});if(e&&e.filter)return e.filter;if(this.additionalFilters&&Array.isArray(this.additionalFilters)){const e=this.additionalFilters.find(e=>(e.name||e.key)===t);if(e)return e}return null}getFilterLabel(t){if("search"===t)return"Search";const e=this.filters[t];if(e&&e.label)return e.label;const i=this.additionalFilters.find(e=>(e.name||e.key)===t);return i&&i.label?i.label:t.charAt(0).toUpperCase()+t.slice(1)}getFilterDisplayValue(t,e){if("search"===t)return`"${e}"`;const i=this.filters[t]||this.additionalFilters.find(e=>(e.name||e.key)===t);if(i&&"daterange"===i.type&&"object"==typeof e)return`${e.start||""} to ${e.end||""}`;if(i&&"select"===i.type&&i.options){if("object"==typeof i.options[0]){const t=i.options.find(t=>t.value===e);return t?t.label:e}return e}return e}getFilterIcon(t){return{text:"search",select:"funnel",date:"calendar",daterange:"calendar-range",number:"123",boolean:"toggle-on"}[t]||"filter"}async onActionAddFilter(t,e){const i=e.getAttribute("data-filter-key"),s=this.getFilterConfig(i),n=this.getActiveFilters()[i];if(!s)return void console.warn("No filter config found for key:",i);const l=await o.form({title:`${void 0!==n&&""!==n?"Edit":"Add"} ${this.getFilterLabel(i)} Filter`,size:"md",fields:[this.buildFilterDialogField(s,n,i)]});if(l){const t=this.extractFilterValue(s,l);this.setFilter(i,t),await this.applyFilters()}}buildFilterDialogField(t,e,i){const s={name:"filter_value",label:t.label,value:e,...t,placeholder:t.placeholder||t.placeHolder};if("daterange"===t.type){if(s.startName=s.startName||"dr_start",s.endName=s.endName||"dr_end",s.fieldName=s.fieldName||"dr_field",s.format=s.format||"YYYY-MM-DD",s.displayFormat=s.displayFormat||"MMM DD, YYYY",s.separator=s.separator||" to ",s.label=s.label||"Date Range",e&&"object"==typeof e){const t=t=>{if(!t&&0!==t)return"";if(t instanceof Date&&!isNaN(t))return t.toISOString().slice(0,10);const e=String(t).trim();if(!e)return"";if(/^-?\d+$/.test(e)){const t=Number(e),i=e.length<=10?1e3*t:t,s=new Date(i);if(!isNaN(s))return s.toISOString().slice(0,10)}const i=new Date(e);return isNaN(i)?e:i.toISOString().slice(0,10)};s.startDate=t(e.start||e.from||e.begin||""),s.endDate=t(e.end||e.to||e.finish||"")}}else if("multiselect"===t.type){let i=[];e&&(Array.isArray(e)?i=e:"string"==typeof e&&(i=e.split(",").map(t=>t.trim()).filter(t=>t))),s.value=i,s.placeholder||s.placeHolder||(t.placeholder||t.placeHolder?s.placeholder=t.placeholder||t.placeHolder:t.label&&(s.placeholder=`Select ${t.label}...`))}return s}extractFilterValue(t,e){if("daterange"===t.type){const i=t.startName||"dr_start",s=t.endName||"dr_end";return{start:e[i],end:e[s]}}return t.type,e.filter_value}async applyFilters(){if(this.collection&&(this.collection.params.start=0),this.collection?.restEnabled)try{await this.collection.fetch(),await this.render()}catch(t){console.error("Failed to fetch filtered data:",t),await this.render()}else await this.render();this.updateFilterPills(),this.emit("params-changed")}async onActionEditFilter(t,e){const i=e.getAttribute("data-filter"),{field:s}=h(i);let n=this.getFilterConfig(s)||this.getFilterConfig(i);const l=this.getActiveFilters(),a=l[i]||l[s];if(!n)return void console.warn("No filter config found for key:",i,"or field:",s);const r={filter_value:a};if("daterange"===n.type&&a&&"object"==typeof a){const t=n.startName||"dr_start",e=n.endName||"dr_end";r[t]=a.start||"",r[e]=a.end||""}const c=await o.form({title:`Edit ${this.getFilterLabel(s)} Filter`,size:"md",data:r,fields:[this.buildFilterDialogField(n,a,s)]});if(c){const t=this.extractFilterValue(n,c);this.setFilter(i,t),await this.applyFilters()}}async onActionRemoveFilter(t,e){const i=e.getAttribute("data-filter"),{field:s}=h(i);this.setFilter(i,null),"search"===i&&this.updateSearchInputs(""),this.collection.restEnabled&&await this.collection.fetch(),this.render(),this.updateFilterPills(),this.emit("filter:remove",{key:i,field:s}),this.emit("params-changed")}async onActionClearAllFilters(t,e){if(!this.collection)return;const{start:i,size:s,sort:n}=this.collection.params;this.collection.params={start:i,size:s},n&&(this.collection.params.sort=n),this.updateSearchInputs(""),this.collection.restEnabled&&await this.collection.fetch(),this.render(),this.updateFilterPills(),this.emit("filters:clear"),this.emit("params-changed")}updateBatchActionsPanel(){if(!this.batchActions||0===this.batchActions.length)return;const t=this.getSelectedItems().length;if("top"===this.batchBarLocation){const e=this.element?.querySelector(".batch-actions-panel-top"),i=this.element?.querySelector(".batch-select-count");e&&i&&(i.textContent=t,t>0?e.classList.remove("d-none"):e.classList.add("d-none"))}else{const e=this.element?.querySelector(".batch-actions-panel"),i=this.element?.querySelector(".batch-select-count");e&&i&&(i.textContent=t,e.style.display=t>0?"block":"none")}const e=this.element?.querySelector(".mojo-select-all-cell");if(e){const t=this.itemViews.size>0&&Array.from(this.itemViews.values()).every(t=>t.selected),i=Array.from(this.itemViews.values()).some(t=>t.selected);e.classList.toggle("selected",t),e.classList.toggle("indeterminate",!t&&i);const s=e.querySelector("i");s&&(s.className=!t&&i?"bi bi-dash":"bi bi-check")}}async onActionBatch(t,e){const i=e.getAttribute("data-action").replace("batch-",""),s=this.getSelectedItems();this.emit("batch:action",{action:i,items:s,event:t})}async onActionClearSelection(t,e){this.clearSelection(),this.updateBatchActionsPanel()}async onActionCustomToolbarButton(t,e){const i=parseInt(e.getAttribute("data-button-index"),10),s=this.toolbarButtons[i];s&&"function"==typeof s.handler&&await s.handler.call(this,t,e)}}function p(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),i=e+"=".repeat((4-e.length%4)%4);return Uint8Array.from(atob(i),t=>t.charCodeAt(0))}function b(t){return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}class Passkey extends e{constructor(t={},e={}){super(t,{endpoint:"/api/account/passkeys",...e})}static suggestName(){const t=navigator.userAgent;let e="Device";/iPad/.test(t)?e="iPad":/iPhone/.test(t)?e="iPhone":/Macintosh|MacIntel/.test(t)?e="Mac":/Android/.test(t)?e="Android":/Windows/.test(t)?e="Windows PC":/Linux/.test(t)&&(e="Linux");let i="";return/Edg\//.test(t)?i="Edge":/Chrome\//.test(t)&&!/Chromium/.test(t)?i="Chrome":/Safari\//.test(t)&&!/Chrome/.test(t)?i="Safari":/Firefox\//.test(t)&&(i="Firefox"),i?`${e} — ${i}`:e}static async register(t){const e=await Passkey.registerBegin();if(!e?.data?.challenge_id||!e?.data?.publicKey)return{success:!1,error:e?.error||"Could not start registration."};const{challenge_id:i,publicKey:s}=e.data;"string"==typeof s.challenge&&(s.challenge=p(s.challenge)),"string"==typeof s.user?.id&&(s.user.id=p(s.user.id)),s.excludeCredentials&&(s.excludeCredentials=s.excludeCredentials.map(t=>({...t,id:"string"==typeof t.id?p(t.id):t.id})));const n=await navigator.credentials.create({publicKey:s});if(!n)return{success:!1,error:"Passkey creation was cancelled."};const l={id:n.id,rawId:b(n.rawId),type:n.type,response:{clientDataJSON:b(n.response.clientDataJSON),attestationObject:b(n.response.attestationObject)}};n.response.getTransports&&(l.transports=n.response.getTransports());const a=await Passkey.registerComplete({challenge_id:i,credential:l,friendly_name:t||"My Passkey"});return a?.data?.id?{success:!0,passkey:a.data}:{success:!1,error:a?.error||"Registration could not be completed."}}static async registerBegin(t={}){try{return await n.POST("/api/account/passkeys/register/begin",{},t.params,{dataOnly:!0})}catch(e){return{success:!1,error:e?.message||"Failed to begin passkey registration"}}}static async registerComplete(t={},e={}){if(!t.challenge_id||!t.credential)return{success:!1,error:"Missing challenge_id or credential data"};try{return await n.POST("/api/account/passkeys/register/complete",t,e.params,{dataOnly:!0})}catch(i){return{success:!1,error:i?.message||"Failed to complete passkey registration"}}}}class PasskeyList extends t{constructor(t={}){super({ModelClass:Passkey,endpoint:"/api/account/passkeys",size:10,...t})}}const f={edit:{fields:[{name:"friendly_name",type:"text",label:"Name",placeholder:"My iPhone",required:!0,columns:12,help:"A friendly name to identify this passkey"},{name:"is_enabled",type:"switch",label:"Enabled",columns:12,help:"Disable to prevent this passkey from being used for authentication"}]}};export{m as D,d as L,MemberList as M,Passkey as P,TableView as T,PasskeyList as a,f as b,TableRow as c,Member as d,Log as e,LogList as f,c as g,u as h,h as p};
|
|
2
|
-
//# sourceMappingURL=Passkeys-BjdXmjlu.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./Collection-CaiT8TbF.js";import{M as t}from"./Modal--Ob_H2iO.js";class Router{constructor(e={}){this.defaultRoute=e.defaultRoute||"home",this.routes=[],this.currentRoute=null,this.eventEmitter=e.eventEmitter||null,this.boundHandlePopState=this.handlePopState.bind(this)}start(){window.addEventListener("popstate",this.boundHandlePopState),this.handleCurrentLocation()}stop(){window.removeEventListener("popstate",this.boundHandlePopState)}addRoute(e,t){this.routes.push({pattern:this.normalizePattern(e),regex:this.patternToRegex(e),pageName:t,paramNames:this.extractParamNames(e)})}async navigate(e,t={}){const{replace:s=!1,state:r=null,trigger:i=!0}=t,{pageName:n,queryParams:o}=this.parseInput(e);i&&await this.handleRouteChange(n,o)}back(){window.history.back()}forward(){window.history.forward()}getCurrentRoute(){return this.currentRoute}getCurrentPath(){const{pageName:e,queryParams:t}=this.parseCurrentUrl();return this.buildPublicUrl(e,t)}handlePopState(e){this.allowPopState?this.handleCurrentLocation():console.warn("PopStateEvent is not allowed")}async handleCurrentLocation(){const{pageName:e,queryParams:t}=this.parseCurrentUrl();await this.handleRouteChange(e,t)}async handleRouteChange(e,t){const s="/"+e,r=this.matchRoute(s),i=this.buildPublicUrl(e,t);return r?(this.currentRoute=r,this.eventEmitter&&this.eventEmitter.emit("route:changed",{path:i,pageName:r.pageName,params:r.params,query:t,route:r}),r):(this.eventEmitter&&this.eventEmitter.emit("route:notfound",{path:i}),null)}matchRoute(e){for(const t of this.routes){const s=e.match(t.regex);if(s){const r={};return t.paramNames.forEach((e,t)=>{r[e]=s[t+1]}),{...t,params:r,path:e}}}return null}parseInput(e){let t=this.defaultRoute,s={};if(!e)return{pageName:t,queryParams:s};try{if(e.includes("?")){const[r,i]=e.split("?",2),n=new URLSearchParams(i);if(n.has("page")){t=n.get("page")||this.defaultRoute;for(const[e,t]of n)"page"!==e&&(s[e]=t)}else{t=r.startsWith("/")?r.substring(1)||this.defaultRoute:r||this.defaultRoute;for(const[e,t]of n)s[e]=t}}else t=e.startsWith("/")?e.substring(1)||this.defaultRoute:e}catch(r){console.warn("Failed to parse input:",e,r),t=this.defaultRoute,s={}}return{pageName:t,queryParams:s}}parseCurrentUrl(){const e=new URLSearchParams(window.location.search),t=e.get("page")||this.defaultRoute,s={};for(const[r,i]of e)"page"!==r&&(s[r]=i);return{pageName:t,queryParams:s}}buildPublicUrl(e,t={}){const s=new URLSearchParams;return s.set("page",e),Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&s.set(e,String(t))}),"?"+s.toString()}updateBrowserUrl(e,t,s,r){const i=new URL(window.location.origin+window.location.pathname);i.searchParams.set("page",e),Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&i.searchParams.set(e,String(t))});const n=i.toString();s?window.history.replaceState(r,"",n):window.history.pushState(r,"",n)}patternToRegex(e){let t=e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&").replace(/\/:([^/?]+)\?/g,"(?:/([^/]+))?").replace(/:([^/]+)/g,"([^/]+)");return new RegExp(`^${t}$`)}extractParamNames(e){return(e.match(/:([^/?]+)\??/g)||[]).map(e=>e.replace(/[:?]/g,""))}normalizePattern(e){return e.startsWith("/")?e:`/${e}`}updateUrl(e={},t={}){const{replace:s=!1}=t,{pageName:r}=this.parseCurrentUrl();this.updateBrowserUrl(r,e,s)}buildUrl(e,t={}){return this.buildPublicUrl(e,t)}doRoutesMatch(e,t){if(!e||!t)return!1;const{pageName:s}=this.parseInput(e),{pageName:r}=this.parseInput(t);return s===r}}class EventBus{constructor(){this.listeners={},this.onceListeners={},this.maxListeners=100,this.debugMode=!1,this.eventStats={}}on(e,t){if("function"!=typeof t)throw new Error("Callback must be a function");return Array.isArray(e)?(e.forEach(e=>this.on(e,t)),this):(this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].length>=this.maxListeners&&console.warn(`Max listeners (${this.maxListeners}) exceeded for event: ${e}`),this.listeners[e].push(t),this)}once(e,t){if("function"!=typeof t)throw new Error("Callback must be a function");return Array.isArray(e)?(e.forEach(e=>this.once(e,t)),this):(this.onceListeners[e]||(this.onceListeners[e]=[]),this.onceListeners[e].push(t),this)}off(e,t){if(Array.isArray(e))return e.forEach(e=>this.off(e,t)),this;if(!t)return delete this.listeners[e],delete this.onceListeners[e],this;if(this.listeners[e]){const s=this.listeners[e].indexOf(t);-1!==s&&(this.listeners[e].splice(s,1),0===this.listeners[e].length&&delete this.listeners[e])}if(this.onceListeners[e]){const s=this.onceListeners[e].indexOf(t);-1!==s&&(this.onceListeners[e].splice(s,1),0===this.onceListeners[e].length&&delete this.onceListeners[e])}return this}emit(e,t){this.updateEventStats(e),this.debugMode;const s=[];return this.listeners[e]&&s.push(...this.listeners[e]),this.listeners["*"]&&s.push(...this.listeners["*"]),this.onceListeners[e]&&(s.push(...this.onceListeners[e]),delete this.onceListeners[e]),this.onceListeners["*"]&&(s.push(...this.onceListeners["*"]),delete this.onceListeners["*"]),this.debugMode&&s.length>0&&s.length,s.forEach(s=>{try{s(t,e)&&(e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault())}catch(r){console.error(`Error in event listener for '${e}':`,r),this.emitError(r,e,s)}}),this}async emitAsync(e,t){const s=[];this.listeners[e]&&s.push(...this.listeners[e]),this.listeners["*"]&&s.push(...this.listeners["*"]),this.onceListeners[e]&&(s.push(...this.onceListeners[e]),delete this.onceListeners[e]),this.onceListeners["*"]&&(s.push(...this.onceListeners["*"]),delete this.onceListeners["*"]);const r=s.map(s=>new Promise(r=>{try{r(s(t,e))}catch(i){console.error(`Error in async event listener for '${e}':`,i),this.emitError(i,e,s),r()}}));return await Promise.all(r),this}removeAllListeners(){return this.listeners={},this.onceListeners={},this}listenerCount(e){return(this.listeners[e]?this.listeners[e].length:0)+(this.onceListeners[e]?this.onceListeners[e].length:0)}eventNames(){const e=Object.keys(this.listeners),t=Object.keys(this.onceListeners);return[.../* @__PURE__ */new Set([...e,...t])]}setMaxListeners(e){if("number"!=typeof e||e<0)throw new Error("Max listeners must be a non-negative number");return this.maxListeners=e,this}namespace(e){const t=t=>`${e}:${t}`;return{on:(e,s)=>this.on(t(e),s),once:(e,s)=>this.once(t(e),s),off:(e,s)=>this.off(t(e),s),emit:(e,s)=>this.emit(t(e),s),emitAsync:(e,s)=>this.emitAsync(t(e),s)}}use(e){if("function"!=typeof e)throw new Error("Middleware must be a function");const t=this.emit;return this.emit=(s,r)=>{try{const i=e(s,r);if(!1===i)return this;const n=void 0!==i?i:r;return t.call(this,s,n)}catch(i){return console.error("Error in event middleware:",i),t.call(this,s,r)}},this}emitError(e,t,s){"error"!==t&&setTimeout(()=>{this.emit("error",{error:e,originalEvent:t,callback:s.toString()})},0)}waitFor(e,t=null){return new Promise((s,r)=>{let i=null;const n=e=>{i&&clearTimeout(i),s(e)};this.once(e,n),t&&(i=setTimeout(()=>{this.off(e,n),r(new Error(`Timeout waiting for event: ${e}`))},t))})}debug(e=!0){return this.debugMode=e,this}getStats(){const e=this.eventNames(),t={totalEvents:e.length,totalListeners:0,events:{},emissions:{...this.eventStats}};return e.forEach(e=>{const s=this.listenerCount(e);t.events[e]=s,t.totalListeners+=s}),t}updateEventStats(e){this.eventStats[e]||(this.eventStats[e]={count:0,firstEmission:Date.now(),lastEmission:null}),this.eventStats[e].count++,this.eventStats[e].lastEmission=Date.now()}getEventStats(e){const t=this.eventStats[e];return t?{...t,listenerCount:this.listenerCount(e),avgEmissionsPerMinute:this.calculateEmissionRate(t)}:null}calculateEmissionRate(e){if(!e.firstEmission||!e.lastEmission)return 0;const t=e.lastEmission-e.firstEmission;if(0===t)return 0;const s=t/6e4;return Math.round(e.count/s*100)/100}resetStats(){return this.eventStats={},this}getTopEvents(e=10){return Object.entries(this.eventStats).map(([e,t])=>({event:e,count:t.count,rate:this.calculateEmissionRate(t),listeners:this.listenerCount(e)})).sort((e,t)=>t.count-e.count).slice(0,e)}debugInfo(){this.debugMode,this.maxListeners;const e=this.getStats();return e.totalEvents,e.totalListeners,Object.keys(this.eventStats).length>0&&this.getTopEvents(5),this}}class WebApp{constructor(s={}){this.config=s,this.initPluginRegistry(),this.name=s.name||"MOJO App",this.version=s.version||"1.0.0",this.debug=s.debug||!1,this.container=s.container||"#app",this.layoutType=s.layout||"portal",this.layoutConfig=s.layoutConfig||{},s.sidebar&&(this.layoutConfig.sidebarConfig=s.sidebar),s.topbar&&(this.layoutConfig.topbarConfig=s.topbar),this.layout=null,this.layoutConfig.containerId=this.container||this.containerId||"#app",this.pageContainer=s.pageContainer||"#page-container",this.basePath=s.basePath||"",this.routerMode=s.routerMode||s.router?.mode||"param",this.basePath=s.basePath||s.router?.base||"",this.defaultRoute=s.defaultRoute||"home",this.session=s.session||{},this.router=null,this.navigation=s.navigation||{},this.state={currentPage:null,previousPage:null,loading:!1},this.events=new EventBus,this.rest=e,this.modal=t,s.api&&this.rest.configure(s.api),this.router=new Router({mode:"param"===this.routerMode?"params":this.routerMode,basePath:this.basePath,defaultRoute:this.defaultRoute,eventEmitter:this.events}),this.events.on("route:changed",async e=>{const{pageName:t,params:s,query:r}=e;await this.showPage(t,r,s,{fromRouter:!0})}),"undefined"!=typeof window&&(window.MOJO=window.MOJO||{},window.MOJO.router=this.router),this.setupFocusTracking(),this.pageCache=/* @__PURE__ */new Map,this.pageClasses=/* @__PURE__ */new Map,this.componentClasses=/* @__PURE__ */new Map,this.modelClasses=/* @__PURE__ */new Map,this.currentPage=null,this.isStarted=!1,window.matchUUID?window[window.matchUUID]=this:window.MOJO?window.MOJO.app=this:window.__app__=this}async start(){if(this.isStarted)console.warn("WebApp already started");else try{this.setupPageContainer(),this.validateDefaultRoute(),await this.setupRouter(),this.isStarted=!0,this.router.allowPopState=!1,this.events.emit("app:ready",{app:this})}catch(e){throw console.error(`Failed to start ${this.name}:`,e),this.showError("Failed to start application"),e}}async setupRouter(){this.router?(this.events.on("route:notfound",async e=>{console.warn(`Route not found: ${e.path}`),this._show404(e.path)}),this.router.start(),this.routerMode):console.error("Router not initialized")}setupPageContainer(){const e="string"==typeof this.container?document.querySelector(this.container):this.container;e&&!e.querySelector("#page-container")&&(e.innerHTML='<div id="page-container"></div>'),this.pageContainer="#page-container"}registerPage(e,t,s={}){if("string"!=typeof e||!e)return console.error("registerPage: pageName must be a non-empty string"),this;if("function"!=typeof t)return console.error("registerPage: PageClass must be a constructor function"),this;if(s.containerId||(s.containerId=this.pageContainer),this.pageClasses.set(e,{PageClass:t,constructorOptions:s}),this.router){let t=s.route||`/${e}`;t.startsWith("/")||(t=`/${t}`),s.route=t,this.router.addRoute(t,e)}return this}getPage(e){return this.pageCache.get(e)}getPagePermissions(e){if(this.pageCache.has(e))return this.pageCache.get(e).permissions;const t=this.pageClasses.get(e);if(!t)return null;const{PageClass:s,constructorOptions:r}=t;return r?r.permissions:null}getOrCreatePage(e){if(this.pageCache.has(e))return this.pageCache.get(e);const t=this.pageClasses.get(e);if(!t)return console.error(`Page not registered: ${e}`),null;const{PageClass:s,constructorOptions:r}=t;try{const t=new s({pageName:e,...r,app:this});return r.route&&(t.route=r.route),this.pageCache.set(e,t),t.route,t}catch(i){return console.error(`Failed to create page ${e}:`,i),null}}async showPage(e,t={},s={},r={}){const{fromRouter:i=!1,replace:n=!1,force:o=!1}=r;try{let r,n;"string"==typeof e?(n=e,r=this.getOrCreatePage(e)):e&&"object"==typeof e&&(r=e,n=e.pageName);const o=this.currentPage;if(!r)return void this._show404(n,s,t,i);if(this.events.emit("page:showing",{page:r,pageName:r.pageName,params:s,query:t,fromRouter:i}),!r.canEnter())return void this._showDeniedPage(r,s,t,i);o&&o!==r&&await this._exitOldPage(o),await r.onParams(s,t),o!==r&&await r.onEnter(),r.syncUrl(),this.events.emit("page:show",{page:r,pageName:r.pageName,params:s,query:t,fromRouter:i}),await r.render(),this.currentPage=r,r.pageName}catch(a){console.error("Error in showPage:",a),this.showError(`Failed to load page: ${a.message}`),"error"!==e&&await this.showPage("error",{},{error:a,originalPage:e},{fromRouter:i})}}async _show404(e,t,s,r){const i=this.getOrCreatePage("404");i&&(i.setInfo&&i.setInfo(e),await this._exitOldPage(this.currentPage),await i.render(),this.currentPage=i,this.events.emit("page:404",{page:null,pageName:e,params:t,query:s,fromRouter:r}))}async _showDeniedPage(e,t,s,r){const i=this.getOrCreatePage("denied");i.setDeniedPage&&i.setDeniedPage(e),await this._exitOldPage(this.currentPage),await i.render(),this.currentPage=i,this.events.emit("page:denied",{page:e,pageName:e.pageName,params:t,query:s,fromRouter:r})}async _exitOldPage(e){if(e)try{await e.onExit(),await e.unmount(),this.events.emit("page:hide",{page:e})}catch(t){console.error(`Error exiting page ${e.pageName}:`,t)}}async navigate(e,t={},s={}){if(!this.router)return void console.error("Router not initialized");let r=e;if(Object.keys(t).length>0){const s=new URLSearchParams(t).toString();r+=(e.includes("?")?"&":"?")+s}return await this.router.navigate(r,s)}async navigateToDefault(e={}){return await this.showPage(this.defaultRoute,{},{},e)}back(){this.router?this.router.back():console.warn("Router not initialized")}forward(){this.router?this.router.forward():console.warn("Router not initialized")}getCurrentPage(){return this.currentPage}getPageContainer(){return this.layout&&this.layout.getPageContainer?this.layout.getPageContainer():"string"==typeof this.pageContainer?document.querySelector(this.pageContainer):this.pageContainer}async showError(e){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;await t.alert(e,"Error",{size:"md",class:"text-danger"})}catch(t){this.events.emit("notification",{message:e,type:"error"}),"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showError fallback:",t),"undefined"!=typeof window&&alert(`Error: ${e}`)}}async showSuccess(e){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;await t.alert(e,"Success",{size:"md",class:"text-success"})}catch(t){this.events.emit("notification",{message:e,type:"success"}),"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] showSuccess fallback:",t),"undefined"!=typeof window&&alert(`Success: ${e}`)}}async showInfo(e){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;await t.alert(e,"Information",{size:"md",class:"text-info"})}catch(t){this.events.emit("notification",{message:e,type:"info"}),"undefined"!=typeof window&&window,"undefined"!=typeof window&&alert(`Info: ${e}`)}}async showWarning(e){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;await t.alert(e,"Warning",{size:"md",class:"text-warning"})}catch(t){this.events.emit("notification",{message:e,type:"warning"}),"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] showWarning fallback:",t),"undefined"!=typeof window&&alert(`Warning: ${e}`)}}showNotification(e,t="info"){this.events.emit("notification",{message:e,type:t})}async showLoading(e={}){"string"==typeof e&&(e={message:e});try{(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default.showBusy(e)}catch(t){"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] showLoading fallback:",t,e),this.events.emit("notification",{message:e.message||"Loading...",type:"info"})}}async hideLoading(){try{(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default.hideBusy()}catch(e){"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] hideLoading fallback:",e)}}async showModelView(e,t={}){try{const s=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;return await s.showModelView(e,t)}catch(s){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showModelForm failed:",s),s}}async showModelForm(e={}){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;return await t.showModelForm(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showModelForm failed:",t),t}}async showForm(e={}){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;return await t.showForm(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showForm failed:",t),t}}async showDialog(e={}){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;return await t.showDialog(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showDialog failed:",t),t}}async showAlert(e={}){try{const t=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;return await t.showDialog(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showDialog failed:",t),t}}async confirm(e,t="Confirm",s={}){const r=(await import("./Dialog-Fu9AEl7W.js").then(e=>e.r)).default;return await r.confirm(e,t,s)}setupFocusTracking(){if("undefined"==typeof window)return;this.isFocused=!document.hidden;const e=()=>{const e=this.isFocused;this.isFocused=!document.hidden,e!==this.isFocused&&(this.isFocused?this.events.emit("browser:focus"):this.events.emit("browser:blur"))},t=()=>{this.isFocused||(this.isFocused=!0,this.events.emit("browser:focus"))},s=()=>{this.isFocused&&(this.isFocused=!1,this.events.emit("browser:blur"))};document.addEventListener("visibilitychange",e),window.addEventListener("focus",t),window.addEventListener("blur",s),this._focusHandlers={visibilitychange:e,focus:t,blur:s}}setupErrorHandling(){window.addEventListener("error",e=>{console.error("Global error:",e.error),this.debug&&this.showError(`Error: ${e.error?.message||"Unknown error"}`)}),window.addEventListener("unhandledrejection",e=>{console.error("Unhandled promise rejection:",e.reason),this.debug&&this.showError(`Promise rejected: ${e.reason?.message||"Unknown error"}`)})}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}getState(e){return e?this.state[e]:this.state}setState(e){const t={...this.state};Object.assign(this.state,e),this.events.emit("state:changed",{oldState:t,newState:this.state,updates:e})}registerComponent(e,t){this.componentClasses.set(e,t)}getComponent(e){return this.componentClasses.get(e)}registerModel(e,t){this.modelClasses.set(e,t)}getModel(e){return this.modelClasses.get(e)}setupRest(){this.rest=e,e.configure(this.api)}async destroy(){this.router&&this.router.stop(),this._focusHandlers&&"undefined"!=typeof window&&(document.removeEventListener("visibilitychange",this._focusHandlers.visibilitychange),window.removeEventListener("focus",this._focusHandlers.focus),window.removeEventListener("blur",this._focusHandlers.blur));const e=Array.from(this.pageCache.values());if(await Promise.allSettled(e.map(async e=>{try{e.destroy&&await e.destroy()}catch(t){console.error("Error destroying page:",t)}})),this.layout&&this.layout.destroy)try{await this.layout.destroy()}catch(t){console.error("Error destroying layout:",t)}this.pageCache.clear(),this.pageClasses.clear(),this.componentClasses.clear(),this.modelClasses.clear(),"undefined"!=typeof window&&window.MOJO&&delete window.MOJO.router,this.isStarted=!1,this.name}buildPagePath(e,t,s){let r=e.route||`/${e.pageName.toLowerCase()}`;if(Object.keys(t).forEach(e=>{"string"!=typeof t[e]&&"number"!=typeof t[e]||(r=r.replace(`:${e}`,t[e]))}),s&&Object.keys(s).length>0){const e=new URLSearchParams(s).toString();r+=(r.includes("?")?"&":"?")+e}return r}validateDefaultRoute(){this.pageClasses.has(this.defaultRoute)?this.defaultRoute:(console.warn(`⚠️ Default route '${this.defaultRoute}' is not registered!`),console.warn(` Please register a page: app.registerPage('${this.defaultRoute}', YourPageClass);`),console.warn(" Or change default route: new WebApp({ defaultRoute: 'your-page' });"))}findFallbackPage(){const e=["404","error","denied"];for(const[t]of this.pageClasses.entries())if(!e.includes(t))return t;return null}static create(e={}){return new WebApp(e)}initPluginRegistry(){"undefined"!=typeof window&&(window.MOJO||(window.MOJO={}),window.MOJO.plugins||(window.MOJO.plugins={}),window.MOJO.app=this)}static registerPlugin(e,t){"undefined"!=typeof window&&(window.MOJO||(window.MOJO={}),window.MOJO.plugins||(window.MOJO.plugins={}),window.MOJO.plugins[e]=t)}}export{EventBus as E,Router as R,WebApp as W};
|
|
2
|
-
//# sourceMappingURL=WebApp-BCWzyUqi.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const e=require("./Collection-TfoOMCWQ.js"),t=require("./Modal-DrNQaqOa.js");class Router{constructor(e={}){this.defaultRoute=e.defaultRoute||"home",this.routes=[],this.currentRoute=null,this.eventEmitter=e.eventEmitter||null,this.boundHandlePopState=this.handlePopState.bind(this)}start(){window.addEventListener("popstate",this.boundHandlePopState),this.handleCurrentLocation()}stop(){window.removeEventListener("popstate",this.boundHandlePopState)}addRoute(e,t){this.routes.push({pattern:this.normalizePattern(e),regex:this.patternToRegex(e),pageName:t,paramNames:this.extractParamNames(e)})}async navigate(e,t={}){const{replace:s=!1,state:r=null,trigger:i=!0}=t,{pageName:n,queryParams:o}=this.parseInput(e);i&&await this.handleRouteChange(n,o)}back(){window.history.back()}forward(){window.history.forward()}getCurrentRoute(){return this.currentRoute}getCurrentPath(){const{pageName:e,queryParams:t}=this.parseCurrentUrl();return this.buildPublicUrl(e,t)}handlePopState(e){this.allowPopState?this.handleCurrentLocation():console.warn("PopStateEvent is not allowed")}async handleCurrentLocation(){const{pageName:e,queryParams:t}=this.parseCurrentUrl();await this.handleRouteChange(e,t)}async handleRouteChange(e,t){const s="/"+e,r=this.matchRoute(s),i=this.buildPublicUrl(e,t);return r?(this.currentRoute=r,this.eventEmitter&&this.eventEmitter.emit("route:changed",{path:i,pageName:r.pageName,params:r.params,query:t,route:r}),r):(this.eventEmitter&&this.eventEmitter.emit("route:notfound",{path:i}),null)}matchRoute(e){for(const t of this.routes){const s=e.match(t.regex);if(s){const r={};return t.paramNames.forEach((e,t)=>{r[e]=s[t+1]}),{...t,params:r,path:e}}}return null}parseInput(e){let t=this.defaultRoute,s={};if(!e)return{pageName:t,queryParams:s};try{if(e.includes("?")){const[r,i]=e.split("?",2),n=new URLSearchParams(i);if(n.has("page")){t=n.get("page")||this.defaultRoute;for(const[e,t]of n)"page"!==e&&(s[e]=t)}else{t=r.startsWith("/")?r.substring(1)||this.defaultRoute:r||this.defaultRoute;for(const[e,t]of n)s[e]=t}}else t=e.startsWith("/")?e.substring(1)||this.defaultRoute:e}catch(r){console.warn("Failed to parse input:",e,r),t=this.defaultRoute,s={}}return{pageName:t,queryParams:s}}parseCurrentUrl(){const e=new URLSearchParams(window.location.search),t=e.get("page")||this.defaultRoute,s={};for(const[r,i]of e)"page"!==r&&(s[r]=i);return{pageName:t,queryParams:s}}buildPublicUrl(e,t={}){const s=new URLSearchParams;return s.set("page",e),Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&s.set(e,String(t))}),"?"+s.toString()}updateBrowserUrl(e,t,s,r){const i=new URL(window.location.origin+window.location.pathname);i.searchParams.set("page",e),Object.entries(t).forEach(([e,t])=>{null!=t&&""!==t&&i.searchParams.set(e,String(t))});const n=i.toString();s?window.history.replaceState(r,"",n):window.history.pushState(r,"",n)}patternToRegex(e){let t=e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&").replace(/\/:([^/?]+)\?/g,"(?:/([^/]+))?").replace(/:([^/]+)/g,"([^/]+)");return new RegExp(`^${t}$`)}extractParamNames(e){return(e.match(/:([^/?]+)\??/g)||[]).map(e=>e.replace(/[:?]/g,""))}normalizePattern(e){return e.startsWith("/")?e:`/${e}`}updateUrl(e={},t={}){const{replace:s=!1}=t,{pageName:r}=this.parseCurrentUrl();this.updateBrowserUrl(r,e,s)}buildUrl(e,t={}){return this.buildPublicUrl(e,t)}doRoutesMatch(e,t){if(!e||!t)return!1;const{pageName:s}=this.parseInput(e),{pageName:r}=this.parseInput(t);return s===r}}class EventBus{constructor(){this.listeners={},this.onceListeners={},this.maxListeners=100,this.debugMode=!1,this.eventStats={}}on(e,t){if("function"!=typeof t)throw new Error("Callback must be a function");return Array.isArray(e)?(e.forEach(e=>this.on(e,t)),this):(this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].length>=this.maxListeners&&console.warn(`Max listeners (${this.maxListeners}) exceeded for event: ${e}`),this.listeners[e].push(t),this)}once(e,t){if("function"!=typeof t)throw new Error("Callback must be a function");return Array.isArray(e)?(e.forEach(e=>this.once(e,t)),this):(this.onceListeners[e]||(this.onceListeners[e]=[]),this.onceListeners[e].push(t),this)}off(e,t){if(Array.isArray(e))return e.forEach(e=>this.off(e,t)),this;if(!t)return delete this.listeners[e],delete this.onceListeners[e],this;if(this.listeners[e]){const s=this.listeners[e].indexOf(t);-1!==s&&(this.listeners[e].splice(s,1),0===this.listeners[e].length&&delete this.listeners[e])}if(this.onceListeners[e]){const s=this.onceListeners[e].indexOf(t);-1!==s&&(this.onceListeners[e].splice(s,1),0===this.onceListeners[e].length&&delete this.onceListeners[e])}return this}emit(e,t){this.updateEventStats(e),this.debugMode;const s=[];return this.listeners[e]&&s.push(...this.listeners[e]),this.listeners["*"]&&s.push(...this.listeners["*"]),this.onceListeners[e]&&(s.push(...this.onceListeners[e]),delete this.onceListeners[e]),this.onceListeners["*"]&&(s.push(...this.onceListeners["*"]),delete this.onceListeners["*"]),this.debugMode&&s.length>0&&s.length,s.forEach(s=>{try{s(t,e)&&(e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault())}catch(r){console.error(`Error in event listener for '${e}':`,r),this.emitError(r,e,s)}}),this}async emitAsync(e,t){const s=[];this.listeners[e]&&s.push(...this.listeners[e]),this.listeners["*"]&&s.push(...this.listeners["*"]),this.onceListeners[e]&&(s.push(...this.onceListeners[e]),delete this.onceListeners[e]),this.onceListeners["*"]&&(s.push(...this.onceListeners["*"]),delete this.onceListeners["*"]);const r=s.map(s=>new Promise(r=>{try{r(s(t,e))}catch(i){console.error(`Error in async event listener for '${e}':`,i),this.emitError(i,e,s),r()}}));return await Promise.all(r),this}removeAllListeners(){return this.listeners={},this.onceListeners={},this}listenerCount(e){return(this.listeners[e]?this.listeners[e].length:0)+(this.onceListeners[e]?this.onceListeners[e].length:0)}eventNames(){const e=Object.keys(this.listeners),t=Object.keys(this.onceListeners);return[.../* @__PURE__ */new Set([...e,...t])]}setMaxListeners(e){if("number"!=typeof e||e<0)throw new Error("Max listeners must be a non-negative number");return this.maxListeners=e,this}namespace(e){const t=t=>`${e}:${t}`;return{on:(e,s)=>this.on(t(e),s),once:(e,s)=>this.once(t(e),s),off:(e,s)=>this.off(t(e),s),emit:(e,s)=>this.emit(t(e),s),emitAsync:(e,s)=>this.emitAsync(t(e),s)}}use(e){if("function"!=typeof e)throw new Error("Middleware must be a function");const t=this.emit;return this.emit=(s,r)=>{try{const i=e(s,r);if(!1===i)return this;const n=void 0!==i?i:r;return t.call(this,s,n)}catch(i){return console.error("Error in event middleware:",i),t.call(this,s,r)}},this}emitError(e,t,s){"error"!==t&&setTimeout(()=>{this.emit("error",{error:e,originalEvent:t,callback:s.toString()})},0)}waitFor(e,t=null){return new Promise((s,r)=>{let i=null;const n=e=>{i&&clearTimeout(i),s(e)};this.once(e,n),t&&(i=setTimeout(()=>{this.off(e,n),r(new Error(`Timeout waiting for event: ${e}`))},t))})}debug(e=!0){return this.debugMode=e,this}getStats(){const e=this.eventNames(),t={totalEvents:e.length,totalListeners:0,events:{},emissions:{...this.eventStats}};return e.forEach(e=>{const s=this.listenerCount(e);t.events[e]=s,t.totalListeners+=s}),t}updateEventStats(e){this.eventStats[e]||(this.eventStats[e]={count:0,firstEmission:Date.now(),lastEmission:null}),this.eventStats[e].count++,this.eventStats[e].lastEmission=Date.now()}getEventStats(e){const t=this.eventStats[e];return t?{...t,listenerCount:this.listenerCount(e),avgEmissionsPerMinute:this.calculateEmissionRate(t)}:null}calculateEmissionRate(e){if(!e.firstEmission||!e.lastEmission)return 0;const t=e.lastEmission-e.firstEmission;if(0===t)return 0;const s=t/6e4;return Math.round(e.count/s*100)/100}resetStats(){return this.eventStats={},this}getTopEvents(e=10){return Object.entries(this.eventStats).map(([e,t])=>({event:e,count:t.count,rate:this.calculateEmissionRate(t),listeners:this.listenerCount(e)})).sort((e,t)=>t.count-e.count).slice(0,e)}debugInfo(){this.debugMode,this.maxListeners;const e=this.getStats();return e.totalEvents,e.totalListeners,Object.keys(this.eventStats).length>0&&this.getTopEvents(5),this}}class WebApp{constructor(s={}){this.config=s,this.initPluginRegistry(),this.name=s.name||"MOJO App",this.version=s.version||"1.0.0",this.debug=s.debug||!1,this.container=s.container||"#app",this.layoutType=s.layout||"portal",this.layoutConfig=s.layoutConfig||{},s.sidebar&&(this.layoutConfig.sidebarConfig=s.sidebar),s.topbar&&(this.layoutConfig.topbarConfig=s.topbar),this.layout=null,this.layoutConfig.containerId=this.container||this.containerId||"#app",this.pageContainer=s.pageContainer||"#page-container",this.basePath=s.basePath||"",this.routerMode=s.routerMode||s.router?.mode||"param",this.basePath=s.basePath||s.router?.base||"",this.defaultRoute=s.defaultRoute||"home",this.session=s.session||{},this.router=null,this.navigation=s.navigation||{},this.state={currentPage:null,previousPage:null,loading:!1},this.events=new EventBus,this.rest=e.rest,this.modal=t.Modal,s.api&&this.rest.configure(s.api),this.router=new Router({mode:"param"===this.routerMode?"params":this.routerMode,basePath:this.basePath,defaultRoute:this.defaultRoute,eventEmitter:this.events}),this.events.on("route:changed",async e=>{const{pageName:t,params:s,query:r}=e;await this.showPage(t,r,s,{fromRouter:!0})}),"undefined"!=typeof window&&(window.MOJO=window.MOJO||{},window.MOJO.router=this.router),this.setupFocusTracking(),this.pageCache=/* @__PURE__ */new Map,this.pageClasses=/* @__PURE__ */new Map,this.componentClasses=/* @__PURE__ */new Map,this.modelClasses=/* @__PURE__ */new Map,this.currentPage=null,this.isStarted=!1,window.matchUUID?window[window.matchUUID]=this:window.MOJO?window.MOJO.app=this:window.__app__=this}async start(){if(this.isStarted)console.warn("WebApp already started");else try{this.setupPageContainer(),this.validateDefaultRoute(),await this.setupRouter(),this.isStarted=!0,this.router.allowPopState=!1,this.events.emit("app:ready",{app:this})}catch(e){throw console.error(`Failed to start ${this.name}:`,e),this.showError("Failed to start application"),e}}async setupRouter(){this.router?(this.events.on("route:notfound",async e=>{console.warn(`Route not found: ${e.path}`),this._show404(e.path)}),this.router.start(),this.routerMode):console.error("Router not initialized")}setupPageContainer(){const e="string"==typeof this.container?document.querySelector(this.container):this.container;e&&!e.querySelector("#page-container")&&(e.innerHTML='<div id="page-container"></div>'),this.pageContainer="#page-container"}registerPage(e,t,s={}){if("string"!=typeof e||!e)return console.error("registerPage: pageName must be a non-empty string"),this;if("function"!=typeof t)return console.error("registerPage: PageClass must be a constructor function"),this;if(s.containerId||(s.containerId=this.pageContainer),this.pageClasses.set(e,{PageClass:t,constructorOptions:s}),this.router){let t=s.route||`/${e}`;t.startsWith("/")||(t=`/${t}`),s.route=t,this.router.addRoute(t,e)}return this}getPage(e){return this.pageCache.get(e)}getPagePermissions(e){if(this.pageCache.has(e))return this.pageCache.get(e).permissions;const t=this.pageClasses.get(e);if(!t)return null;const{PageClass:s,constructorOptions:r}=t;return r?r.permissions:null}getOrCreatePage(e){if(this.pageCache.has(e))return this.pageCache.get(e);const t=this.pageClasses.get(e);if(!t)return console.error(`Page not registered: ${e}`),null;const{PageClass:s,constructorOptions:r}=t;try{const t=new s({pageName:e,...r,app:this});return r.route&&(t.route=r.route),this.pageCache.set(e,t),t.route,t}catch(i){return console.error(`Failed to create page ${e}:`,i),null}}async showPage(e,t={},s={},r={}){const{fromRouter:i=!1,replace:n=!1,force:o=!1}=r;try{let r,n;"string"==typeof e?(n=e,r=this.getOrCreatePage(e)):e&&"object"==typeof e&&(r=e,n=e.pageName);const o=this.currentPage;if(!r)return void this._show404(n,s,t,i);if(this.events.emit("page:showing",{page:r,pageName:r.pageName,params:s,query:t,fromRouter:i}),!r.canEnter())return void this._showDeniedPage(r,s,t,i);o&&o!==r&&await this._exitOldPage(o),await r.onParams(s,t),o!==r&&await r.onEnter(),r.syncUrl(),this.events.emit("page:show",{page:r,pageName:r.pageName,params:s,query:t,fromRouter:i}),await r.render(),this.currentPage=r,r.pageName}catch(a){console.error("Error in showPage:",a),this.showError(`Failed to load page: ${a.message}`),"error"!==e&&await this.showPage("error",{},{error:a,originalPage:e},{fromRouter:i})}}async _show404(e,t,s,r){const i=this.getOrCreatePage("404");i&&(i.setInfo&&i.setInfo(e),await this._exitOldPage(this.currentPage),await i.render(),this.currentPage=i,this.events.emit("page:404",{page:null,pageName:e,params:t,query:s,fromRouter:r}))}async _showDeniedPage(e,t,s,r){const i=this.getOrCreatePage("denied");i.setDeniedPage&&i.setDeniedPage(e),await this._exitOldPage(this.currentPage),await i.render(),this.currentPage=i,this.events.emit("page:denied",{page:e,pageName:e.pageName,params:t,query:s,fromRouter:r})}async _exitOldPage(e){if(e)try{await e.onExit(),await e.unmount(),this.events.emit("page:hide",{page:e})}catch(t){console.error(`Error exiting page ${e.pageName}:`,t)}}async navigate(e,t={},s={}){if(!this.router)return void console.error("Router not initialized");let r=e;if(Object.keys(t).length>0){const s=new URLSearchParams(t).toString();r+=(e.includes("?")?"&":"?")+s}return await this.router.navigate(r,s)}async navigateToDefault(e={}){return await this.showPage(this.defaultRoute,{},{},e)}back(){this.router?this.router.back():console.warn("Router not initialized")}forward(){this.router?this.router.forward():console.warn("Router not initialized")}getCurrentPage(){return this.currentPage}getPageContainer(){return this.layout&&this.layout.getPageContainer?this.layout.getPageContainer():"string"==typeof this.pageContainer?document.querySelector(this.pageContainer):this.pageContainer}async showError(e){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;await t.alert(e,"Error",{size:"md",class:"text-danger"})}catch(t){this.events.emit("notification",{message:e,type:"error"}),"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showError fallback:",t),"undefined"!=typeof window&&alert(`Error: ${e}`)}}async showSuccess(e){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;await t.alert(e,"Success",{size:"md",class:"text-success"})}catch(t){this.events.emit("notification",{message:e,type:"success"}),"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] showSuccess fallback:",t),"undefined"!=typeof window&&alert(`Success: ${e}`)}}async showInfo(e){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;await t.alert(e,"Information",{size:"md",class:"text-info"})}catch(t){this.events.emit("notification",{message:e,type:"info"}),"undefined"!=typeof window&&window,"undefined"!=typeof window&&alert(`Info: ${e}`)}}async showWarning(e){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;await t.alert(e,"Warning",{size:"md",class:"text-warning"})}catch(t){this.events.emit("notification",{message:e,type:"warning"}),"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] showWarning fallback:",t),"undefined"!=typeof window&&alert(`Warning: ${e}`)}}showNotification(e,t="info"){this.events.emit("notification",{message:e,type:t})}async showLoading(e={}){"string"==typeof e&&(e={message:e});try{(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default.showBusy(e)}catch(t){"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] showLoading fallback:",t,e),this.events.emit("notification",{message:e.message||"Loading...",type:"info"})}}async hideLoading(){try{(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default.hideBusy()}catch(e){"undefined"!=typeof window&&window?.console&&console.warn("[WebApp] hideLoading fallback:",e)}}async showModelView(e,t={}){try{const s=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;return await s.showModelView(e,t)}catch(s){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showModelForm failed:",s),s}}async showModelForm(e={}){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;return await t.showModelForm(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showModelForm failed:",t),t}}async showForm(e={}){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;return await t.showForm(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showForm failed:",t),t}}async showDialog(e={}){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;return await t.showDialog(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showDialog failed:",t),t}}async showAlert(e={}){try{const t=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;return await t.showDialog(e)}catch(t){throw"undefined"!=typeof window&&window?.console&&console.error("[WebApp] showDialog failed:",t),t}}async confirm(e,t="Confirm",s={}){const r=(await Promise.resolve().then(()=>require("./Dialog-BzvvJnK1.js")).then(e=>e.Dialog$1)).default;return await r.confirm(e,t,s)}setupFocusTracking(){if("undefined"==typeof window)return;this.isFocused=!document.hidden;const e=()=>{const e=this.isFocused;this.isFocused=!document.hidden,e!==this.isFocused&&(this.isFocused?this.events.emit("browser:focus"):this.events.emit("browser:blur"))},t=()=>{this.isFocused||(this.isFocused=!0,this.events.emit("browser:focus"))},s=()=>{this.isFocused&&(this.isFocused=!1,this.events.emit("browser:blur"))};document.addEventListener("visibilitychange",e),window.addEventListener("focus",t),window.addEventListener("blur",s),this._focusHandlers={visibilitychange:e,focus:t,blur:s}}setupErrorHandling(){window.addEventListener("error",e=>{console.error("Global error:",e.error),this.debug&&this.showError(`Error: ${e.error?.message||"Unknown error"}`)}),window.addEventListener("unhandledrejection",e=>{console.error("Unhandled promise rejection:",e.reason),this.debug&&this.showError(`Promise rejected: ${e.reason?.message||"Unknown error"}`)})}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}getState(e){return e?this.state[e]:this.state}setState(e){const t={...this.state};Object.assign(this.state,e),this.events.emit("state:changed",{oldState:t,newState:this.state,updates:e})}registerComponent(e,t){this.componentClasses.set(e,t)}getComponent(e){return this.componentClasses.get(e)}registerModel(e,t){this.modelClasses.set(e,t)}getModel(e){return this.modelClasses.get(e)}setupRest(){this.rest=e.rest,e.rest.configure(this.api)}async destroy(){this.router&&this.router.stop(),this._focusHandlers&&"undefined"!=typeof window&&(document.removeEventListener("visibilitychange",this._focusHandlers.visibilitychange),window.removeEventListener("focus",this._focusHandlers.focus),window.removeEventListener("blur",this._focusHandlers.blur));const e=Array.from(this.pageCache.values());if(await Promise.allSettled(e.map(async e=>{try{e.destroy&&await e.destroy()}catch(t){console.error("Error destroying page:",t)}})),this.layout&&this.layout.destroy)try{await this.layout.destroy()}catch(t){console.error("Error destroying layout:",t)}this.pageCache.clear(),this.pageClasses.clear(),this.componentClasses.clear(),this.modelClasses.clear(),"undefined"!=typeof window&&window.MOJO&&delete window.MOJO.router,this.isStarted=!1,this.name}buildPagePath(e,t,s){let r=e.route||`/${e.pageName.toLowerCase()}`;if(Object.keys(t).forEach(e=>{"string"!=typeof t[e]&&"number"!=typeof t[e]||(r=r.replace(`:${e}`,t[e]))}),s&&Object.keys(s).length>0){const e=new URLSearchParams(s).toString();r+=(r.includes("?")?"&":"?")+e}return r}validateDefaultRoute(){this.pageClasses.has(this.defaultRoute)?this.defaultRoute:(console.warn(`⚠️ Default route '${this.defaultRoute}' is not registered!`),console.warn(` Please register a page: app.registerPage('${this.defaultRoute}', YourPageClass);`),console.warn(" Or change default route: new WebApp({ defaultRoute: 'your-page' });"))}findFallbackPage(){const e=["404","error","denied"];for(const[t]of this.pageClasses.entries())if(!e.includes(t))return t;return null}static create(e={}){return new WebApp(e)}initPluginRegistry(){"undefined"!=typeof window&&(window.MOJO||(window.MOJO={}),window.MOJO.plugins||(window.MOJO.plugins={}),window.MOJO.app=this)}static registerPlugin(e,t){"undefined"!=typeof window&&(window.MOJO||(window.MOJO={}),window.MOJO.plugins||(window.MOJO.plugins={}),window.MOJO.plugins[e]=t)}}exports.EventBus=EventBus,exports.Router=Router,exports.WebApp=WebApp;
|
|
2
|
-
//# sourceMappingURL=WebApp-D6rnlV2T.js.map
|