1const MBL_CONTENT_CSS=``;const MBL_CONTENT_SHEET="adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype?(()=>{const e=undefined;return new CSSStyleSheet})():null;const MBL_UI_CSS=`\n :host{\n display:block; inline-size:100%;\n --line:#d0d7de; --bg:#fff; --fg:#24292f; --focus:#1f6feb;\n --hover: rgba(127,127,127,.12); --pressed: rgba(127,127,127,.18);\n --icon-size: 20px;\n --ui-line-height: 1.5;\n color:var(--fg); font:inherit;\n }\n @media (prefers-color-scheme: dark){\n :host{\n --bg:#111318; --fg:#e6e6e6; --line:#2b2f36; --focus:#7aa7ff;\n --hover: rgba(255,255,255,.06); --pressed: rgba(255,255,255,.12);\n }\n }\n\n .wrapper{ border:1px solid var(--line); border-radius:.6rem; background:var(--bg);\n display:grid; grid-template-rows:auto 1fr; overflow:hidden; inline-size:100%; position:relative; }\n @supports (container-type:inline-size){ .wrapper{ container-type:inline-size; } }\n\n .toolbar{\n user-select:none; display:flex; flex-wrap:wrap; gap:2px; padding:4px;\n align-items:center; border-bottom:1px solid var(--line); background:var(--bg); color:var(--fg);\n line-height: var(--ui-line-height, 1.5);\n }\n .toolbar .spacer{ flex:1 1 auto; }\n .toolbar button{\n border:0; background:transparent; appearance:none; color:inherit;\n padding:6px 8px; min-width:28px; min-height:28px; border-radius:6px; cursor:pointer;\n }\n .toolbar button:hover{ background:var(--hover); }\n .toolbar button[aria-pressed="true"]{ background:var(--pressed); }\n .toolbar button[disabled]{ opacity:.45; pointer-events:none; cursor:default; }\n .toolbar .sep{ width:1px; height:24px; background:var(--line); margin:0 4px; }\n .toolbar button:focus-visible{ outline: 2px solid var(--focus); outline-offset: 2px; }\n .toolbar svg{ display:block; width: var(--icon-size); height: var(--icon-size); }\n @supports (container-type:inline-size){\n @container (max-width:420px){ .toolbar button{ min-width:24px; padding:4px 6px; } }\n }\n\n .surfaceWrap{ min-height:180px; }\n .surfaceWrap ::slotted(.surface){ display:block; padding:10px 12px; min-height:180px; overflow:auto; }\n\n :host([readonly]) .toolbar{ display:none; }\n\n #linkPopover{ display:none; line-height: var(--ui-line-height, 1.5); }\n #linkPopover[data-open="true"]{\n position:absolute; left:0; top:0; padding:12px; border:1px solid var(--line); border-radius:8px; background:var(--bg); color:var(--fg);\n box-shadow:0 8px 24px rgba(0,0,0,.18); display:grid; gap:10px; box-sizing:border-box; overflow-x:hidden; overflow-y:auto;\n max-width:420px; width:max(240px, min(420px, 100% - 16px)); max-height: var(--pop-max, 70vh);\n z-index:10;\n }\n @media (hover: none){\n #linkPopover[data-open="true"]{\n position: fixed;\n inset: 8px 8px auto 8px;\n left: auto; top: 8px;\n }\n }\n #linkPopover input{ display:block; width:100%; min-width:0; box-sizing:border-box; padding:8px; border:1px solid var(--line); border-radius:6px; background:transparent; color:inherit; }\n #linkPopover .actions{ display:flex; gap:8px; justify-content:space-between; align-items:center; flex-wrap:wrap; }\n #linkPopover .right{ display:flex; gap:8px; flex-wrap:wrap; }\n\n .sr-only{ position:absolute !important; clip:rect(1px,1px,1px,1px); clip-path:inset(50%); width:1px; height:1px; overflow:hidden; white-space:nowrap; border:0; padding:0; margin:0; }\n`;class MBLRichText extends HTMLElement{static get observedAttributes(){return["value","readonly","aria-label","aria-labelledby"]}static#e=null;constructor(){super();const e=this.attachShadow({mode:"open",delegatesFocus:true});if(!MBLRichText.#e&&"replaceSync"in CSSStyleSheet.prototype)MBLRichText.#e=new CSSStyleSheet,MBLRichText.#e.replaceSync(MBL_UI_CSS);if(e.innerHTML=`\n <svg xmlns="http://www.w3.org/2000/svg" style="display:none;">\n \x3c!-- Text styles --\x3e\n <symbol id="i-bold" viewBox="0 0 24 24">\n <path fill="currentColor" d="M16.457 11.868A4.47 4.47 0 0 0 18 8.5 5.506 5.506 0 0 0 12.5 3H5v19h8.5a5.497 5.497 0 0 0 2.957-10.132zM8 6h4.5a2.5 2.5 0 0 1 0 5H8zm5.5 13H8v-5h5.5a2.5 2.5 0 0 1 0 5z"/>\n </symbol>
1\n <symbol id="i-italic" viewBox="0 0 24 24">\n <path fill="currentColor" d="M8,22a1,1,0,0,1,0-2H9.65L12.32,4H11a1,1,0,0,1,0-2h5a1,1,0,0,1,0,2H14.35L11.68,20H13a1,1,0,0,1,0,2Z"/>\n </symbol>\n <symbol id="i-underline" viewBox="0 0 24 24">\n <path fill="currentColor" d="M6 20h12v2H6zM6 4h3v7a3 3 0 0 0 6 0V4h3v7a6 6 0 1 1-12 0V4z"/>\n </symbol>\n <symbol id="i-strike" viewBox="0 0 24 24">\n <path fill="currentColor" d="M3 11h18v2H3zM6 9c0-2.6 2.9-5 6-5s6 1.6 6 4h-3c0-1.4-1.6-2.2-3-2.2s-3 .7-3 2c0 1 .9 1.6 2.6 2l2 .5c2.6 .6 4.4 1.8 4.4 4 0 2.7-2.8 4.7-6 4.7s-6-1.8-6-4.7h3c0 1.6 1.8 2.4 3 2.4 1.8 0 3-.8 3-2 0-1-.8-1.5-2.4-1.9l-2.1-.5C8.3 12.5 6 11.3 6 9z"/>\n </symbol>\n\n \x3c!-- Size --\x3e\n <symbol id="i-size" viewBox="0 0 24 24">\n <path fill="currentColor" d="M10.5 4h9.5v2H16.6v12h-2V6h-4.1zM3 10h6v2H6.9v6H4.9v-6H3z"/>\n </symbol>\n\n \x3c!-- Bulleted list --\x3e\n <symbol id="i-ul" viewBox="0 0 24 24">\n <circle cx="5" cy="4" r="1.5" fill="currentColor"/>\n <circle cx="5" cy="12" r="1.5" fill="currentColor"/>\n <circle cx="5" cy="20" r="1.5" fill="currentColor"/>\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M9 4h11M9 12h11M9 20h11"/>\n </symbol>\n\n \x3c!-- Numbered list (lines y=4,12,20; numerals 1px stroke, nudged left) --\x3e\n <symbol id="i-ol" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M9 4h11M9 12h11M9 20h11"/>\n <path fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" d="M4.8 6.5v3"/>\n <path fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" d="M3.4 14.5H6.4L3.5 17.5H6.5"/>\n </symbol>\n\n \x3c!-- Indentation --\x3e\n <symbol id="i-outdent" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 4h16M12 12h8M4 20h16"/>\n <path d="M9 10l-4 2 4 2z" fill="currentColor"/>\n </symbol>\n <symbol id="i-indent" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 4h16M4 12h8M4 20h16"/>\n <path d="M15 10l4 2-4 2z" fill="currentColor"/>\n </symbol>\n\n \x3c!-- Alignment --\x3e\n <symbol id="i-left" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 4h14M4 12h12M4 20h10"/>\n </symbol>\n <symbol id="i-center" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M5 4h14M7 12h10M5 20h14"/>\n </symbol>\n <symbol id="i-right" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M6 4H20M8 12H20M10 20H20"/>\n </symbol>\n\n \x3c!-- Links --\x3e\n <symbol id="i-link" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"\n d="M10.05 14c-1.5-1.51-1.36-4.1.32-5.78l4.85-4.86c1.67-1.67 4.25-1.8 5.76-.29 1.51 1.51 1.37 4.09-.31 5.77l-2.42 2.43M13.95 10c1.5 1.51 1.36 4.1-.32 5.78l-2.42 2.43-2.42 2.43c-1.67 1.67-4.25 1.8-5.76.29-1.51-1.51-1.37-4.09.31-5.77l2.42-2.43"/>\n </symbol>\n <symbol id="i-unlink" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M7 7l10 10M9.5 7H14a4 4 0 0 1 0 8h-1.5M10 17H9a4 4 0 1 1 0-8h1.5"/>\n </symbol>\n\n \x3c!-- History --\x3e\n <symbol id="i-undo" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"\n d="M9 7L5 11l4 4M5 11h8c4 0 7 3 7 7"/>\n </symbol>\n <symbol id="i-redo" viewBox="0 0 24 24">\n <path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"\n d="M15 7l4 4-4 4M19 11h-8c-4 0-7 3-7 7"/>\n </symbol>\n </svg>\n\n <div class="wrapper">\n <div class="toolbar" role="toolbar" aria-orientation="horizontal" aria-label="Text formatting toolbar">\n <button type="button" data-cmd="bold" aria-label="Make text bold" title="Bold (Ctrl/Cmd+B)"><svg viewBox="0 0 24 24"><use href="#i-bold"/></svg></button>\n <button type="button" data-cmd="italic" aria-label="Make text italic" title="Italic (Ctrl/Cmd+I)"><svg viewBox="0 0 24 24"><use href="#i-italic"/></svg></button>\n <button type="button" data-cmd="underline" aria-label="Underline text" title="Underline (Ctrl/Cmd+U)"><svg viewBox="0 0 24 24"><use href="#i-underline"/></svg></button>\n <button type="button" data-cmd="strikeThrough" aria-label="Str
1ikethrough text" title="Strikethrough (Alt+Shift+5)"><svg viewBox="0 0 24 24"><use href="#i-strike"/></svg></button>\n <span class="sep" aria-hidden="true"></span>\n <button type="button" data-cmd="size-large" aria-label="Toggle large text" title="Toggle Large"><svg viewBox="0 0 24 24"><use href="#i-size"/></svg></button>\n <span class="sep" aria-hidden="true"></span>\n <button type="button" data-cmd="insertUnorderedList" aria-label="Bulleted list" title="Bulleted list"><svg viewBox="0 0 24 24"><use href="#i-ul"/></svg></button>\n <button type="button" data-cmd="insertOrderedList" aria-label="Numbered list" title="Numbered list"><svg viewBox="0 0 24 24"><use href="#i-ol"/></svg></button>\n <button type="button" data-cmd="outdent" aria-label="Decrease indent" title="Outdent (Shift+Tab)"><svg viewBox="0 0 24 24"><use href="#i-outdent"/></svg></button>\n <button type="button" data-cmd="indent" aria-label="Increase indent" title="Indent (Tab)"><svg viewBox="0 0 24 24"><use href="#i-indent"/></svg></button>\n <span class="sep" aria-hidden="true"></span>\n <div role="group" aria-label="Alignment">\n <button type="button" data-cmd="align-left" aria-label="Align left" title="Align left"><svg viewBox="0 0 24 24"><use href="#i-left"/></svg></button>\n <button type="button" data-cmd="align-center" aria-label="Align center" title="Align center"><svg viewBox="0 0 24 24"><use href="#i-center"/></svg></button>\n <button type="button" data-cmd="align-right" aria-label="Align right" title="Align right"><svg viewBox="0 0 24 24"><use href="#i-right"/></svg></button>\n </div>\n <span class="sep" aria-hidden="true"></span>\n <button type="button" data-cmd="link" aria-label="Insert or edit link" title="Insert or edit link (Ctrl/Cmd+K)"><svg viewBox="0 0 24 24"><use href="#i-link"/></svg></button>\n <div class="spacer" aria-hidden="true"></div>\n <span class="sep" aria-hidden="true"></span>\n <div role="group" aria-label="History">\n <button type="button" data-cmd="undo" aria-label="Undo" title="Undo (Ctrl/Cmd+Z)"><svg viewBox="0 0 24 24"><use href="#i-undo"/></svg></button>\n <button type="button" data-cmd="redo" aria-label="Redo" title="Redo (Ctrl+Y or Shift+Ctrl/Cmd+Z)"><svg viewBox="0 0 24 24"><use href="#i-redo"/></svg></button>\n </div>\n </div>\n\n <div class="surfaceWrap">\n <slot name="surface"></slot>\n </div>\n\n <div id="linkPopover" role="dialog" aria-label="Insert or edit link">\n <label>URL / Email / Phone\n <input required type="text" id="linkUrl" aria-label="URL, email or US phone"\n placeholder="https://example.com | [email protected] | (555) 123â4567"\n inputmode="url" autocapitalize="off" autocomplete="off" spellcheck="false" />\n </label>\n <div class="actions">\n <button id="removeLink" type="button" style="display:flex;gap:6px;align-items:center;" aria-label="Remove link">\n <svg width="16" height="16" viewBox="0 0 24 24"><use href="#i-unlink"/></svg><span>Remove link</span>\n </button>\n <div class="right">\n <button id="cancelLink" type="button" aria-label="Cancel link editing">Cancel</button>\n <button id="saveLink" class="primary" type="button" aria-label="Save link"><strong>Save link</strong></button>\n </div>\n </div>\n </div>\n </div>\n\n <div id="status" class="sr-only" role="status" aria-live="polite"></div>\n <slot id="toolbarSlot" name="toolbar" hidden aria-hidden="true"></slot>\n `,this.shadowRoot.adoptedStyleSheets&&MBL_CONTENT_SHEET&&MBLRichText.#e)this.shadowRoot.adoptedStyleSheets=[MBLRichText.#e,MBL_CONTENT_SHEET];else{const e=document.createElement("style");e.textContent=MBL_UI_CSS+"\n"+MBL_CONTENT_CSS,this.shadowRoot.prepe
1nd(e)}this._toolbar=this.shadowRoot.querySelector(".toolbar"),this._wrapper=this.shadowRoot.querySelector(".wrapper"),this._toolbarSlot=this.shadowRoot.getElementById("toolbarSlot"),this._status=this.shadowRoot.getElementById("status"),this._pop=this.shadowRoot.getElementById("linkPopover"),this._linkInput=this.shadowRoot.getElementById("linkUrl"),this._unlinkBtn=this.shadowRoot.getElementById("removeLink"),this._cancelBtn=this.shadowRoot.getElementById("cancelLink"),this._saveBtn=this.shadowRoot.getElementById("saveLink"),this._undoStack=[],this._redoStack=[],this._isRestoring=false,this._surface=null,this._savedRange=null,this._lastRange=null,this._savedOffsets=null,this._savedBlockIx=0,this._savedPaths=null,this._freezeSel=false,this._hasBookmark=false,this._skipTabOnce=false,this._tabsSuspended=false,this._pending={value:null,readonly:null},this._abort=new AbortController,this._historyHtml="",this._sinceKeyframe=0,this._historyForceSnapshotOnce=false,this._lastEditWasPasteOrDrop=false,this._historySelBefore=null,this._histTimer=null,this._histDelay=120,this._announceCountTimer=null,this._lastAnnouncedCount=-1,this._resizeObs="undefined"!=typeof ResizeObserver?new ResizeObserver(()=>this._reposition()):null,this._handlers={toolbarPointerDown:e=>this._onToolbarPointerDown(e),toolbarMouseDown:e=>this._onToolbarPointerDown(e),toolbarClick:e=>this._onToolbarClick(e),toolbarKeydown:e=>this._onToolbarKeydown(e),slotChange:()=>this._applyToolbarConfigFromSlot(),surfaceBeforeInput:e=>this._onSurfaceBeforeInput(e),surfacePaste:e=>this._onPaste(e),surfaceDrop:e=>this._onDrop(e),surfaceInput:()=>this._onInput(),surfacePointerDown:e=>this._onSurfacePointerDown(e),surfaceMouseup:()=>this._saveSelection(),surfaceKeyup:()=>this._saveSelection(),surfaceFocusin:()=>{this._restoreTabbability(),this._saveSelection()},surfaceKeydown:e=>this._onSurfaceKeydown(e),surfaceScroll:()=>this._reposition(),windowKeydown:e=>this._onWindowKeydown(e),windowPointerDown:()=>this._restoreTabbability(),docPointerDownClose:e=>{if(!this._isPopoverOpen())return;const t=e.composedPath?e.composedPath():[];if(-1!==t.indexOf(this._pop))return;if(-1!==t.indexOf(this))return;this._hidePopover(true)},selectionChange:()=>this._onSelectionChange(),unlinkClick:e=>this._onUnlinkClick(e),cancelClick:()=>this._hidePopover(true),saveClick:e=>this._onPopoverSubmit(e),inputKeydown:e=>this._onPopoverKeydown(e),inputInput:()=>this._onLinkFieldInput(),resize:()=>this._reposition(),windowPointerUp:()=>{if(this._freezeSel&&!this._isPopoverOpen())this._freezeSel=false,this._onSelectionChange()}}}static normalizeTrix(e){const t=document.createElement("mbl-rich-text");const i=document.createElement("div");return i.className="surface",i.setAttribute("data-wc-content",""),t.appendChild(i),t._sanitize(e)}get value(){return this._getSanitizedHTML()}set value(e){this._setHTML(e,true),this._initHistory()}get readOnly(){return this.hasAttribute("readonly")}set readOnly(e){e?this.setAttribute("readonly",""):this.removeAttribute("readonly")}setReadOnly(e=true){this.readOnly=!!e,this.dispatchEvent(new Event("modechange"))}toggleReadOnly(){this.setReadOnly(!this.readOnly)}connectedCallback(){this._ensureSurface(),this._maybeInjectGlobalContentCSS();const e=this.getAttribute("value")||"";const t=(null!==this._pending.value?this._pending.value:e)||"<p><br></p>";this._pending.value=null,this.value=t;try{document.execCommand("defaultParagraphSeparator",false,"p"),document.execCommand("styleWithCSS",false,false)}catch{}if(this._toolbar.addEventListener("pointerdown",this._handlers.toolbarPointerDown,{capture:true,signal:this._abort.signal}),this._toolbar.addEventListener("mousedown",this._handlers.toolbarMouseDown,{capture:true,signal:this._abort.signal}),this._toolbar.addEventListener("click",this._handlers.toolbarClick,{signal:this._abort.signal}),this._toolbar.addEventListener("keydown",this._handlers.toolbarKeydown,{signal:this._abort.signal}),this._initToolbarRoving(),this._toolbarSlot)this._toolbarSlot.addEventListener("slotchange",this._handlers.slot
1Change,{signal:this._abort.signal});if(this._applyToolbarConfigFromSlot(),this._surface.addEventListener("beforeinput",this._handlers.surfaceBeforeInput,{signal:this._abort.signal,capture:true}),this._surface.addEventListener("paste",this._handlers.surfacePaste,{signal:this._abort.signal,capture:true}),this._surface.addEventListener("drop",this._handlers.surfaceDrop,{signal:this._abort.signal}),this._surface.addEventListener("input",this._handlers.surfaceInput,{signal:this._abort.signal}),this._surface.addEventListener("pointerdown",this._handlers.surfacePointerDown,{signal:this._abort.signal,capture:true}),this._surface.addEventListener("mouseup",this._handlers.surfaceMouseup,{signal:this._abort.signal}),this._surface.addEventListener("keyup",this._handlers.surfaceKeyup,{signal:this._abort.signal}),this._surface.addEventListener("focusin",this._handlers.surfaceFocusin,{signal:this._abort.signal}),this._surface.addEventListener("keydown",this._handlers.surfaceKeydown,{signal:this._abort.signal}),this._surface.addEventListener("scroll",this._handlers.surfaceScroll,{signal:this._abort.signal}),document.addEventListener("selectionchange",this._handlers.selectionChange,{signal:this._abort.signal}),window.addEventListener("resize",this._handlers.resize,{signal:this._abort.signal}),window.addEventListener("pointerup",this._handlers.windowPointerUp,{signal:this._abort.signal,capture:true}),window.addEventListener("pointerdown",this._handlers.windowPointerDown,{signal:this._abort.signal,capture:true}),window.addEventListener("keydown",this._handlers.windowKeydown,{signal:this._abort.signal}),document.addEventListener("pointerdown",this._handlers.docPointerDownClose,{signal:this._abort.signal,capture:true}),this._pop)this._pop.removeAttribute("data-open"),this._pop.setAttribute("role","dialog");if(this._unlinkBtn)this._unlinkBtn.addEventListener("click",this._handlers.unlinkClick,{signal:this._abort.signal});if(this._cancelBtn)this._cancelBtn.addEventListener("click",this._handlers.cancelClick,{signal:this._abort.signal});if(this._saveBtn)this._saveBtn.addEventListener("click",this._handlers.saveClick,{signal:this._abort.signal});if(this._linkInput)this._linkInput.addEventListener("keydown",this._handlers.inputKeydown,{signal:this._abort.signal}),this._linkInput.addEventListener("input",this._handlers.inputInput,{signal:this._abort.signal});if(this._resizeObs&&this._wrapper)this._resizeObs.observe(this._wrapper);this._applyMode(),this._syncSurfaceA11y(),this._onSelectionChange(),this._initHistory()}disconnectedCallback(){if(this._resizeObs)try{this._resizeObs.disconnect()}catch{}if(this._abort.abort(),this._histTimer)clearTimeout(this._histTimer),this._histTimer=null;if(this._announceCountTimer)clearTimeout(this._announceCountTimer),this._announceCountTimer=null}attributeChangedCallback(e,t,i){if(!this.isConnected||!this._surface)return void(this._pending[e]=i??("readonly"===e?"":null));if("value"===e)this._setHTML(i||"");if("readonly"===e)this._applyMode();if("aria-label"===e||"aria-labelledby"===e)this._syncSurfaceA11y()}_maybeInjectGlobalContentCSS(){if(this.hasAttribute("no-global-css"))return;if(MBLRichText._globalSheetInjected)return;if(MBL_CONTENT_SHEET&&document.adoptedStyleSheets){if(-1===document.adoptedStyleSheets.indexOf(MBL_CONTENT_SHEET))document.adoptedStyleSheets=[].concat(document.adoptedStyleSheets,MBL_CONTENT_SHEET);MBLRichText._globalSheetInjected=true}}_ensureSurface(){let e=this.querySelector('[slot="surface"]');if(!e)e=document.createElement("div"),e.setAttribute("slot","surface"),e.className="surface",e.setAttribute("data-wc-content",""),this.appendChild(e);this._surface=e}_syncSurfaceA11y(){if(!this._surface)return;const e=this.getAttribute("aria-labelledby");const t=this.getAttribute("aria-label");if(e)this._surface.setAttribute("aria-labelledby",e),this._surface.removeAttribute("aria-label");else{const e=t||"Rich text editor";this._surface.setAttribute("aria-label",e),this._surface.removeAttribute("aria-labelledby")}}_applyToolbarConfigFromSlot(){const e=this._toolbar;if(!e)return;
1e.querySelectorAll("[data-hidden-by-config]").forEach(e=>{e.hidden=false,e.removeAttribute("data-hidden-by-config")}),e.querySelectorAll(".sep").forEach(e=>{e.hidden=false});const t=undefined;const i=(this._toolbarSlot?.assignedNodes({flatten:true})||[]).find(e=>1===e.nodeType)||null;const n=undefined;const s=undefined;(i&&(i.getAttribute("data-remove")||i.dataset?.remove)||"").split(/[\s,]+/).map(e=>e.trim()).filter(Boolean).forEach(t=>{const i=e.querySelector(`[data-cmd="${t}"]`);if(i)i.hidden=true,i.setAttribute("data-hidden-by-config","")});const r=Array.from(e.children);let a=false;for(let e=0;e<r.length;e++){const t=r[e];if(t.classList?.contains("sep")){let i=false;for(let t=e+1;t<r.length;t++){const e=r[t];if(!e.hidden&&!e.classList?.contains("sep")){i=true;break}}t.hidden=!(a&&i)}else if(!t.hidden)a=true}this._initToolbarRoving()}_onToolbarPointerDown(e){const t=e.target?.closest?.("button[data-cmd]");if(!t)return;this._surface?.focus({preventScroll:true}),this._freezeSel=true,this._saveSelection(),e.preventDefault()}_onToolbarClick(e){if(this.readOnly)return;const t=e.target.closest?.("button[data-cmd]");if(!t)return;const i=t.dataset.cmd;if("link"===i){if(this._isPopoverOpen())this._hidePopover(true);else this._onBeforePopover(),this._showPopover();return}if("undo"===i||"redo"===i)return void this.exec(i);if(i.startsWith("align-"))return void this.exec("align",`align-${i.split("-")[1]}`);if("size-large"===i)return void this.exec("size-large");if("indent"===i||"outdent"===i)return void this.exec(i);if("insertOrderedList"===i||"insertUnorderedList"===i)return void this.exec(i);this.exec(i)}_onToolbarKeydown(e){const t=Array.from(this._toolbar.querySelectorAll("button:not([hidden])"));const i=t.indexOf(this.shadowRoot.activeElement);const move=e=>{if(e<0)e=t.length-1;if(e>=t.length)e=0;t.forEach((t,i)=>t.tabIndex=i===e?0:-1),t[e].focus()};if("ArrowRight"===e.key)e.preventDefault(),move(-1===i?0:i+1);else if("ArrowLeft"===e.key)e.preventDefault(),move(-1===i?0:i-1);else if("Home"===e.key)e.preventDefault(),move(0);else if("End"===e.key)e.preventDefault(),move(t.length-1)}_initToolbarRoving(){const e=undefined;Array.from(this._toolbar.querySelectorAll("button:not([hidden])")).forEach((e,t)=>e.tabIndex=0===t?0:-1)}_isCmdVisible(e){return!!this._toolbar?.querySelector(`[data-cmd="${e}"]:not([hidden])`)}exec(e,t){if(this.readOnly)return;const i="bold"===e||"italic"===e||"underline"===e||"strikeThrough"===e||"link"===e;const n=undefined;if(!this._ensureSelection({strict:i})&&i)return;if(this._historySelBefore=this._savedOffsets||this._getSelectionOffsets(),"insertOrderedList"===e||"insertUnorderedList"===e||"indent"===e||"outdent"===e)this._historyForceSnapshotOnce=true;if("undo"===e)return this._onUndo(),this._freezeSel=false,void this._onSelectionChange();if("redo"===e)return this._onRedo(),this._freezeSel=false,void this._onSelectionChange();if(i&&"link"!==e)this._bookmarkSelection();if("bold"===e||"italic"===e||"underline"===e||"strikeThrough"===e)this._normalizeInlineStylesInSelection(),this._manualToggleInline(e),this._cleanupInlineArtifacts();else if("insertOrderedList"===e||"insertUnorderedList"===e||"indent"===e||"outdent"===e){const t=this._areSelectedLIsLarge();document.execCommand(e,false,null),this._repairListSizes(true===t)}else if("align"===e)this._toggleAlignment(t);else if("size-large"===e){this._bookmarkSelection();const e=(()=>{const e=this._getRange();return e?e.cloneRange():null})();this._toggleSizeLargeSmart(e)}else if("link"===e&&t){let e=this._normalizeLinkInput(t);if(e)e=this._dedupeScheme(e),this._manualWrapLink(e),this._announce("Link saved")}let s=this._restoreSelectionFromBookmark();if(!s&&this._historySelBefore)s=this._restoreSelectionFromOffsets(this._historySelBefore);this._clearBookmark(),this._saveSelection(),this._freezeSel=false,this._onSelectionChange(),this._ensureParagraphScaffolding(false),this._canonicalizeEmptyContent(),this._emitInput()}_ensureSelection({strict:e=false}={}){const t=window.getSelection();if(t&&t.rangeCount){const e=t.getRangeAt(0);if(this._surface?.contains(e.startContainer)&&this._surface?.contains(e.endContainer))return this._surface?.focus({preventScroll:true}),this._savedRange=e.cloneRange(),this._lastRange=e.cloneRange(),this._savedOffsets=this._getSelectionOffsets(),this._savedPaths=this._serializeRange(e),true}if(this._restoreSelectionFromBookmark())return true;return this._restoreSelection({strict:e})}_blockEls(){return Array.from(this._surface?.querySelectorAll("p,li,blockquote,div")||[])}_blockAncestor(e){while(e&&e!==this._surface){if(1===e.nodeType&&/^(P|LI|BLOCKQUOTE|DIV|H[1-6])$/.test(e.tagName))return e;e=e.parentNode}return null}_nodePath(e){const t=[];let i=e;while(i&&i!==this._surface){const e=i.parentNode;if(!e)break;const n=Array.prototype.indexOf.call(e.childNodes,i);t.push(n),i=e}return t.reverse()}_nodeFromPath(e){let t=this._surface;for(const i of e){if(!t||!t.childNodes||i<0||i>=t.childNodes.length)return null;t=t.childNodes[i]}return t||null}_serializeRange(e){return{sp:this._nodePath(e.startContainer),so:e.startOffset,ep:this._nodePath(e.endContainer),eo:e.endOffset}}_deserializeRange(e){if(!e)return null;const t=this._nodeFromPath(e.sp),i=this._nodeFromPath(e.ep);if(!t||!i)return null;const n=document.createRange();try{return n.setStart(t,Math.min(e.so,3===t.nodeType?t.nodeValue.length:t.childNodes.length)),n.setEnd(i,Math.min(e.eo,3===i.nodeType?i.nodeValue.length:i.childNodes.length)),n}catch{return null}}_saveSelection(){const e=window.getSelection();if(!e||0===e.rangeCount)return;const t=e.getRangeAt(0);if(this._surface?.contains(t.startContainer)&&this._surface?.contains(t.endContainer))this._savedRange=t.cloneRange(),this._lastRange=t.cloneRange(),this._savedOffsets=this._getSelectionOffsets(),this._savedPaths=this._serializeRange(t)}_restoreSelection({strict:e=false}={}){if(!this._surface)return false;if(this._surface?.focus({preventScroll:true}),this._savedPaths){const e=this._deserializeRange(this._savedPaths);if(e){const t=window.getSelection();return t?.removeAllRanges(),t?.addRange(e),this._savedRange=e.cloneRange(),this._lastRange=e.cloneRange(),true}}if(e&&!this._savedPaths)return false;if(this._savedRange&&this._surface?.contains(this._savedRange.startContainer)&&this._surface?.contains(this._savedRange.endContainer)){const e=window.getSelection();return e?.removeAllRanges(),e?.addRange(this._savedRange),true}return false}_getRange(){const e=window.getSelection();if(e&&e.rangeCount){const t=e.getRangeAt(0);if(this._surface?.contains(t.startContainer)&&this._surface?.contains(t.endContainer))return t}if(this._savedRange&&this._surface?.contains(this._savedRange.startContainer)&&this._surface?.contains(this._savedRange.endContainer))return this._savedRange.cloneRange();return this._lastRange?this._lastRange.cloneRange():null}_getSelectionOffsets(){const e=window.getSelection();if(!e||0===e.rangeCount)return{start:0,end:0};const t=e.getRangeAt(0);if(!this._surface?.contains(t.startContainer)||!this._surface?.contains(t.endContainer))return{start:0,end:0};const i=document.createRange();i.setStart(this._surface,0),i.setEnd(t.startContainer,t.startOffset);const n=document.createRange();return n.setStart(this._surface,0),n.setEnd(t.endContainer,t.endOffset),{start:i.toString().length,end:n.toString().length}}_restoreSelectionFromOffsets(e={start:0,end:0}){const len=e=>3===e.nodeType?e.nodeValue.length:0;let t=this._surface,i=0,n=this._surface,s=0;let r=0;const a=document.createTreeWalker(this._surface,NodeFilter.SHOW_TEXT);let l,o=false,d=false;while(l=a.nextNode()){const a=r+len(l);if(!o&&e.start<=a)t=l,i=Math.max(0,e.start-r),o=true;if(!d&&e.end<=a){n=l,s=Math.max(0,e.end-r),d=true;break}r=a}if(!(o||d))return false;const c=document.createRange();try{c.setStart(t,i),c.setEnd(n,Math.max(s,i));const e=window.getSelection();return e?.removeAllRanges(),e?.addRange(c),this._savedRange=c.cloneRange(),this._lastRange=c.cloneRange(),true}catch{return false}}_bookmarkSelection(){if(!this._surface)return false;const e=window.getSelection();if(!e||0===e.rangeCount)return false;const t=e.getRangeAt(0);if(!this._surface.contains(t.startContainer)||!this._surface.contains(t.endContainer))return false;this._clearBookmark();const mk=e=>{const t=document.createElement("span");return t.setAttribute("data-wc-bm",e),t.style.cssText="display:inline-block;width:0;height:0;overflow:hidden;line-height:0;font-size:0;",t};const i=mk("e");const n=t.cloneRange();n.collapse(false),n.insertNode(i);const s=mk("s");const r=t.cloneRange();
1return r.collapse(true),r.insertNode(s),this._hasBookmark=true,true}_restoreSelectionFromBookmark(){if(!this._surface||!this._hasBookmark)return false;const e=this._surface.querySelector('span[data-wc-bm="s"]');const t=this._surface.querySelector('span[data-wc-bm="e"]');if(!e&&!t)return this._hasBookmark=false,false;const i=window.getSelection();i?.removeAllRanges();const n=document.createRange();if(e&&t)n.setStartAfter(e),n.setEndBefore(t);else if(e)n.setStartAfter(e),n.collapse(true);else n.setStartBefore(t),n.collapse(true);if(i?.addRange(n),this._savedRange=n.cloneRange(),this._lastRange=n.cloneRange(),e)e.remove();if(t)t.remove();return this._hasBookmark=false,true}_clearBookmark(){if(!this._surface)return;this._surface.querySelectorAll("span[data-wc-bm]").forEach(e=>e.remove()),this._hasBookmark=false}_normalizeInlineStylesInSelection(){const e=this._getRange();if(!e)return;const t=document.createTreeWalker(this._surface,NodeFilter.SHOW_ELEMENT,{acceptNode:t=>{if(!(t instanceof Element))return NodeFilter.FILTER_SKIP;try{if(!e.intersectsNode(t))return NodeFilter.FILTER_SKIP}catch{return NodeFilter.FILTER_SKIP}const i=(t.getAttribute("style")||"").toLowerCase();if(!i)return NodeFilter.FILTER_SKIP;return/font-weight\s*:\s*(bold|[6-9]00)/.test(i)||/font-style\s*:\s*italic/.test(i)||/line-through/.test(i)||/text-decoration-line\s*:\s*line-through/.test(i)||/underline/.test(i)||/text-decoration-line\s*:\s*underline/.test(i)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});const i=[];let n;while(n=t.nextNode())i.push(n);i.forEach(e=>{const t=(e.getAttribute("style")||"").toLowerCase();const i=/font-weight\s*:\s*(bold|[6-9]00)/.test(t);const n=/font-style\s*:\s*italic/.test(t);const s=/line-through/.test(t)||/text-decoration-line\s*:\s*line-through/.test(t);const r=/underline/.test(t)||/text-decoration-line\s*:\s*underline/.test(t);const a=e.ownerDocument;const l=[];if(i)l.push("strong");if(n)l.push("em");if(r)l.push("u");
1if(s)l.push("s");if("A"===e.tagName){let t=a.createDocumentFragment();while(e.firstChild)t.appendChild(e.firstChild);l.forEach(e=>{const i=a.createElement(e);i.appendChild(t),t=i}),e.appendChild(t),e.removeAttribute("style")}else{let t=a.createDocumentFragment();while(e.firstChild)t.appendChild(e.firstChild);l.forEach(e=>{const i=a.createElement(e);i.appendChild(t),t=i}),e.parentNode.insertBefore(t,e),e.remove()}}),this._surface.normalize()}_closestAncestorMatching(e,t){let i=e&&3===e.nodeType?e.parentNode:e;while(i&&i!==this._surface){if(1===i.nodeType&&i.matches&&i.matches(t))return i;i=i.parentNode}return null}_safeSurround(e,t){try{return e.surroundContents(t),true}catch{const i=e.extractContents();return t.appendChild(i),e.insertNode(t),false}}_splitSpanAroundNode(e,t){if(!e||!t||!e.contains(t))return;const i=e.ownerDocument;const n=i.createRange();if(n.setStart(e,0),n.setEndBefore(t),!n.collapsed){const t=i.createElement("span");t.className=e.className,this._safeSurround(n,t)}const s=i.createRange();if(s.setStartAfter(t),s.setEnd(e,e.childNodes.length),!s.collapsed){const t=i.createElement("span");t.className=e.className,this._safeSurround(s,t)}this._unwrapElement(e)}_toggleInlineSizeClass(e){if(!e||!/^size-(s|m|l)$/.test(e))return;const t=this._getRange();if(!t||t.collapsed)return;const i=this._getRange();if(!i)return;const n=document.createElement("span");n.setAttribute("data-selwrap",""),this._safeSurround(i,n);let s=null;{let t=n.parentElement;while(t&&t!==this._surface){if(t.matches&&t.matches(`span.${e}`)){s=t;break}t=t.parentElement}}let r=false;if(s)this._splitSpanAroundNode(s,n),n.querySelectorAll("span.size-l,span.size-m,span.size-s").forEach(e=>this._unwrapElement(e)),r=true;else{const t=undefined;if(n.querySelector(`span.${e}`))n.querySelectorAll(`span.${e}`).forEach(e=>this._unwrapElement(e)),r=true}if(!r)n.querySelectorAll("span.size-l,span.size-m,span.size-s").forEach(e=>this._unwrapElement(e)),n.classList.add(e);this._surface.normalize(),this._surface.querySelectorAll("span[data-selwrap]").forEach(e=>{if(e.removeAttribute("data-selwrap"),!e.getAttribute("class"))this._unwrapElement(e)}),this._cleanupInlineArtifacts(),this._surface.normalize()}_textNodesInRange(e){const t=document.createTreeWalker(this._surface,NodeFilter.SHOW_TEXT);const i=[];let n;while(n=t.nextNode()){if(0===n.nodeValue.length)continue;try{if(e.intersectsNode(n))i.push(n)}catch{}}return i}_isNodeInsideTag(e,t){const i=3===e.nodeType?e.parentNode:e;return i instanceof Element?!!i.closest(t):false}_inlineState(e){const t=this._getRange();if(!t)return false;if(t.collapsed)return this._isNodeInsideTag(t.startContainer,e);const i=this._textNodesInRange(t);if(0===i.length)return this._isNodeInsideTag(t.startContainer,e)&&this._isNodeInsideTag(t.endContainer,e);return i.every(t=>this._isNodeInsideTag(t,e))}_wrapRangeWithTag(e,t){const i=this._getRange();if(!i||i.collapsed)return;let n=false;let s=null;try{if("function"==typeof i.surroundContents){const r=this._blockAncestor(i.startContainer);const a=this._blockAncestor(i.endContainer);if(r&&a&&r===a){const r=document.createElement(e);if(t)r.className=t;i.surroundContents(r),s=r,n=true}}}catch{n=false}if(!n){const n=i.extractContents();const r=document.createElement(e);if(t)r.className=t;r.appendChild(n),i.insertNode(r),s=r}const r=window.getSelection();const a=document.createRange();if(a.selectNodeContents(s),r)r.removeAllRanges(),r.addRange(a);this._savedRange=a.cloneRange(),this._lastRange=a.cloneRange(),this._savedOffsets=this._getSelectionOffsets(),this._savedPaths=this._serializeRange(a)}_unwrapTagsInRange(e){const t=this._getRange();if(!t)return;const i=Array.isArray(e)?e.join(","):e;const n=[];this._surface?.querySelectorAll(i)?.forEach(e=>{try{if(t.intersectsNode(e))n.push(e)}catch{}}),n.forEach(e=>{while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove()}),this._surface?.normalize()}_manualToggleInline(e){const t=undefined;const i={bold:{tag:"strong",sel:"strong,b"},italic:{tag:"em",sel:"em,i"},underline:{tag:"u",sel:"u"},strikeThrough:{tag:"s",sel:"s,strike"}}[e];if(!i)return;const n=undefined;if(this._inlineState(i.sel))this._unwrapTagsInRange(i.sel.split(","));else this._wrapRangeWithTag(i.tag);this._surface?.normalize()}_selectedBlocks(e){const t=e||this._getRange();const i=this._blockEls();if(!t){const e=i[0];return e?[e]:[]}const n=this._blockAncestor(t.commonAncestorContainer);if(n&&n!==this._surface)try{const e=document.createRange();e.selectNodeContents(n);const i=t.compareBoundaryPoints(Range.START_TO_START,e)>=0;const s=t.compareBoundaryPoints(Range.END_TO_END,e)<=0;if(i&&s)return[n]}catch{}if(t.collapsed){const e=this._blockAncestor(t.startContainer);return e?[e]:[]}const s=this._blockAncestor(t.startContainer),r=this._blockAncestor(t.endContainer);if(s&&r){const e=i.indexOf(s),t=i.indexOf(r);if(-1!==e&&-1!==t){const n=Math.min(e,t),s=Math.max(e,t);return i.slice(n,s+1)}}const a=i.filter(e=>{try{return t.intersectsNode(e)}catch{return false}});if(a.length)return a;const l=this._blockAncestor(t.startContainer);return l?[l]:[]}_selectedTopLevelListItems(e){const t=e||this._getRange();if(!t)return[];const i=[];
1if(this._surface?.querySelectorAll("li")?.forEach(e=>{try{if(t.intersectsNode(e))i.push(e)}catch{}}),!i.length){const e=(this._blockAncestor(t.startContainer)||t.startContainer).closest?.("li")||null;if(e)i.push(e)}if(!i.length)return[];const n=new Set(i);return i.filter(e=>{let t=e.parentElement?.closest?.("li")||null;while(t){if(n.has(t))return false;t=t.parentElement?.closest?.("li")||null}return true})}_areSelectedLIsLarge(e){const t=this._selectedTopLevelListItems(e);if(!t.length)return null;return t.every(e=>e.classList.contains("size-l"))}_repairListSizes(e){const t=this._selectedTopLevelListItems();if(!t.length)return;if(true===e)t.forEach(e=>e.classList.add("size-l"));else if(false===e)t.forEach(e=>e.classList.remove("size-l"))}_selectionCoversAllText(e,t){if(!e||!t)return false;const i=(t.cloneContents().textContent||"").replace(/\s+/g," ").trim();const n=(e.textContent||"").replace(/\s+/g," ").trim();return!!i&&i===n}_toggleAlignment(e){const t=e;if(!t)return;const i=this._selectedBlocks();if(!i.length)return;for(const e of i){let i=e;if("LI"===e.tagName)i=e.closest("ul,ol")||e;const n=i.classList.contains(t);if(i.classList.remove("align-left","align-center","align-right"),!n)i.classList.add(t)}}_toggleBlockLarge(e){const t=this._blockFullyWrappedBy(e,"span.size-l");
1const i=undefined;if(e.classList.contains("size-l")||!!t){if(e.classList.remove("size-l"),t)this._unwrapElement(t);this._removeInlineSizeSpansWithin(e)}else e.classList.add("size-l"),this._removeInlineSizeSpansWithin(e)}_blockFullyWrappedBy(e,t){if(!e)return null;let i=null;for(const t of Array.from(e.childNodes))if(1===t.nodeType){if(i)return null;i=t}else if(3===t.nodeType)if(""!==(t.textContent||"").trim())return null;if(!i)return null;return i.matches(t)?i:null}_removeInlineSizeSpansWithin(e){if(!e)return;e.querySelectorAll("span.size-s, span.size-m, span.size-l").forEach(e=>this._unwrapElement(e))}_selectionCoversNodeContents(e,t){if(!e||!t)return false;const i=document.createRange();i.selectNodeContents(e);try{const e=t.compareBoundaryPoints(Range.START_TO_START,i)<=0;const n=t.compareBoundaryPoints(Range.END_TO_END,i)>=0;return e&&n}catch{return false}}_isInlineRange(e){if(!e||e.collapsed)return false;const t=this._blockAncestor(e.startContainer);const i=this._blockAncestor(e.endContainer);return!!(t&&i&&t===i)}_toggleSizeLargeSmart(e){const t=e||this._getRange();if(!t)return;const i=this._selectedTopLevelListItems(t);if(i.length){for(const e of i){const t=this._blockFullyWrappedBy(e,"span.size-l");
1const i=undefined;if(e.classList.contains("size-l")||!!t){if(e.classList.remove("size-l"),t)this._unwrapElement(t);this._removeInlineSizeSpansWithin(e)}else e.classList.add("size-l"),this._removeInlineSizeSpansWithin(e)}return}const n=this._selectedBlocks(t);if(!n.length)return;if(1===n.length&&!t.collapsed){const e=n[0];const i=e.classList.contains("size-l")||!!this._blockFullyWrappedBy(e,"span.size-l");const s=this._selectionCoversAllText(e,t)||this._selectionCoversNodeContents(e,t);if(i&&s)return void this._toggleBlockLarge(e);if(i)this._toggleInlineSizeClass("size-m");else this._toggleInlineSizeClass("size-l");return}const s=undefined;if(n.every(e=>e.classList.contains("size-l")||!!this._blockFullyWrappedBy(e,"span.size-l")))for(const e of n){e.classList.remove("size-l");const t=this._blockFullyWrappedBy(e,"span.size-l");if(t)this._unwrapElement(t);this._removeInlineSizeSpansWithin(e)}else for(const e of n){e.classList.add("size-l");const t=this._blockFullyWrappedBy(e,"span.size-l");if(t)this._unwrapElement(t);this._removeInlineSizeSpansWithin(e)}}_isPopoverOpen(){return"true"===this._pop?.getAttribute("data-open")}_showPopover(){if(!this._pop)return;this._freezeSel=true,this._pop.setAttribute("data-open","true"),this._positionPopover(),requestAnimationFrame(()=>{this._positionPopover(),this._linkInput?.focus({preventScroll:true});try{this._linkInput?.select()}catch{}this._onLinkFieldInput()})}_hidePopover(e=false){if(this._pop?.removeAttribute("data-open"),e)this._restoreSelectionFromBookmark()||this._historySelBefore&&this._restoreSelectionFromOffsets(this._historySelBefore);this._clearBookmark(),this._freezeSel=false,this._onSelectionChange()}_positionPopover(){const e=this._pop;if(!e||!this._isPopoverOpen())return;const t=this._toolbar?.querySelector('button[data-cmd="link"]:not([hidden])')||this._toolbar?.querySelector("button:not([hidden])");const i=this._wrapper.getBoundingClientRect();const n=(t||this._toolbar).getBoundingClientRect();const s=8;const r=Math.min(420,Math.max(240,i.width-2*s));e.style.width=`${Math.round(r)}px`;const a=Math.max(160,i.height-2*s);const l=Math.max(160,Math.floor(.9*window.innerHeight));const o=Math.min(a,l);e.style.setProperty("--pop-max",o+"px");const d=e.offsetWidth||r;const c=Math.min(e.offsetHeight||0,o);let u=n.left-i.left;let f=n.bottom-i.top+s;const h=s,p=i.width-d-s;if(u=Math.min(Math.max(u,h),Math.max(h,p)),c){const e=undefined;if(f+c+s>i.height){const e=n.top-i.top-c-s;f=Math.max(s,e)}if(f+c+s>i.height)f=i.height-c-s;if(f<s)f=s}e.style.left=`${Math.round(u)}px`,e.style.top=`${Math.round(f)}px`}_reposition(){if(this._isPopoverOpen())this._positionPopover()}_onBeforePopover(){if(this._saveSelection(),this._bookmarkSelection(),this._linkInput){const e=this._closestInSelection("A");this._linkInput.value=e?.getAttribute("href")||"",this._linkInput.setCustomValidity("")}}_onPopoverKeydown(e){if("Enter"===e.key&&!e.isComposing&&!e.shiftKey)e.preventDefault(),e.stopPropagation(),this._onPopoverSubmit(e);else if("Escape"===e.key)e.preventDefault(),e.stopPropagation(),this._hidePopover(true),Promise.resolve().then(()=>{this._restoreTabbability(),this._surface?.focus({preventScroll:true})})}_onLinkFieldInput(){if(!this._linkInput)return;const e=(this._linkInput.value||"").trim();const t=!!this._normalizeLinkInput(e);if(""===e||t)this._linkInput.setCustomValidity("");else this._linkInput.setCustomValidity("Enter a valid URL, email, or US phone number.");if(this._saveBtn)this._saveBtn.disabled=!t}_onPopoverSubmit(e){if(e?.preventDefault?.(),this.readOnly)return;const t=(this._linkInput?.value||"").trim();let i=this._normalizeLinkInput(t);if(!i){if(this._linkInput?.setCustomValidity("Enter a valid URL, email, or US phone number."),this._linkInput?.reportValidity(),this._status)this._status.textContent="Invalid URL";return}if(i=this._dedupeScheme(i),this._linkInput?.setCustomValidity(""),!this._restoreSelectionFromBookmark()){const e=this._getRange();if(e&&e.collapsed){const t=i.replace(/^mailto:|^tel:/,"");const n=document.createElement("a");n.href=i,n.setAttribute("target","_blank"),n.setAttribute("rel","noopener noreferrer"),n.textContent=t,e.insertN
1ode(n),e.setStartAfter(n),e.collapse(true);const s=window.getSelection();s?.removeAllRanges(),s?.addRange(e),this._savedRange=e.cloneRange(),this._lastRange=e.cloneRange()}else this._restoreSelection({strict:true})}this.exec("link",i),this._hidePopover(false),this._surface?.focus({preventScroll:true})}_closestInSelection(e){const t=this._getRange();if(!t)return null;let i=t.commonAncestorContainer;if(3===i.nodeType)i=i.parentNode;return i instanceof Element?i.closest(e):null}_elementsInRange(e,t){const i=[];return this._surface?.querySelectorAll(t)?.forEach(t=>{try{if(e.intersectsNode(t))i.push(t)}catch{}}),i}_manualWrapLink(e){const t=this._getRange();if(!t)return;const i=this._closestInSelection("A");const setAttrs=t=>{t.setAttribute("href",e),t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")};if(i)return void setAttrs(i);if(t.collapsed){const i=document.createElement("a");setAttrs(i),i.textContent=e.replace(/^mailto:|^tel:/,""),t.insertNode(i),t.setStartAfter(i),t.setEndAfter(i);const n=window.getSelection();return n?.removeAllRanges(),n?.addRange(t),this._savedRange=t.cloneRange(),this._lastRange=t.cloneRange(),this._savedOffsets=this._getSelectionOffsets(),this._savedPaths=this._serializeRange(t),void this._surface.normalize()}const n=t.extractContents();const s=document.createElement("a");
1setAttrs(s),s.appendChild(n),t.insertNode(s);const r=document.createRange();r.setStartAfter(s),r.setEndAfter(s);const a=window.getSelection();a?.removeAllRanges(),a?.addRange(r),this._savedRange=r.cloneRange(),this._lastRange=r.cloneRange(),this._savedOffsets=this._getSelectionOffsets(),this._savedPaths=this._serializeRange(r),this._surface.normalize()}_execRemoveLink(){const e=this._getRange();if(!e)return;const unwrap=e=>{while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove()};const t=new Set(this._elementsInRange(e,"A"));if(!t.size){const e=this._closestInSelection("A");if(e)t.add(e)}t.forEach(unwrap),this._surface.normalize()}_dedupeScheme(e){if(!e)return e;let t=String(e).trim();t=t.replace(/^(?:mailto:)+/i,"mailto:").replace(/^(?:tel:)+/i,"tel:"),t=t.replace(/^(https?):(?=https?:\/\/)/i,"https://");const i=t.match(/^((?:https?:\/\/)+)/i);if(i){const e=i[1];const n=/https:\/\//i.test(e);t=t.replace(/^((?:https?:\/\/)+)/i,n?"https://":"http://")}return t=t.replace(/^(https?:\/\/)\/+/i,"$1"),t}_normalizeLinkInput(e){if(!e)return null;let t=String(e).trim();if(t=this._dedupeScheme(t),t.startsWith("#")||t.startsWith("/"))return t;const i=t.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(.*)$/);if(i){const e=i[1].toLowerCase();let t=i[2];if("mailto"===e){while(/^mailto:/i.test(t))t=t.slice(7);const e=(t.split("?")[0]||"").trim();const i=undefined;if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e))return null;return this._dedupeScheme(`mailto:${t}`)}if("tel"===e){while(/^tel:/i.test(t))t=t.slice(4);const e=t.replace(/\D/g,"");if(10===e.length)return"tel:+1"+e;if(11===e.length&&e.startsWith("1"))return"tel:+"+e;return null}if("http"===e||"https"===e){let i=`${e}://${t.replace(/^\/+/,"")}`;i=this._dedupeScheme(i);try{const e=new URL(i);return["http:","https:"].includes(e.protocol)?i:null}catch{return null}}return null}const n=t.replace(/\D/g,"");const s=undefined;if(!/[a-zA-Z]/.test(t)&&n.length>=10){if(10===n.length)return`tel:+1${n}`;if(11===n.length&&n.startsWith("1"))return`tel:+${n}`}if(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(t))return`mailto:${t}`;if(/^[^\s]+\.[^\s]+/.test(t))return`https://${t}`;return null}_onInput(){this._ensureParagraphScaffolding(true),this._emitInput()}_emitInput(){const e=(this._surface?.innerText||"").length;if(e!==this._lastAnnouncedCount){if(this._lastAnnouncedCount=e,this._announceCountTimer)clearTimeout(this._announceCountTimer);this._announceCountTimer=setTimeout(()=>{this._announce(`${e} characters`)},300)}if(this._histTimer)clearTimeout(this._histTimer);this._histTimer=setTimeout(()=>{this._recordHistory()},this._histDelay),this.dispatchEvent(new Event("input",{bubbles:true})),this.dispatchEvent(new Event("change",{bubbles:true}))}_onSurfaceBeforeInput(e){const t=e.inputType||"";if("insertLineBreak"===t)return void e.preventDefault();if("insertFromPaste"===t&&e.dataTransfer){const t=e.dataTransfer.getData("text/html");if(t&&/<img[\s>]/i.test(t)){e.preventDefault();const i=this._sanitize(t);this._insertHTMLAtSelection(i),this._lastEditWasPasteOrDrop=true,this._emitInput()}}}_onPaste(e){if(!this._surface||this.readOnly)return;const t=e.clipboardData;if(!t)return;const i=t.getData("text/html")||"";const n=t.getData("text/plain")||"";if(i){e.preventDefault();const t=this._sanitize(i);return this._insertHTMLAtSelection(t),this._lastEditWasPasteOrDrop=true,void this._emitInput()}if(n){e.preventDefault();const t=n.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[e])).replace(/\r?\n/g,"<br>");this._insertHTMLAtSelection(t),this._lastEditWasPasteOrDrop=true,this._emitInput()}}_onDrop(e){if(!this._surface||this.readOnly)return;e.preventDefault();let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(e.clientX,e.clientY);else if(document.caretPositionFromPoint){const i=document.caretPositionFromPoint(e.clientX,e.clientY);if(i)t=document.createRange(),t.setStart(i.offsetNode,i.offset),t.collapse(true)}if(t&&this._surface.contains(t.startContainer)){const e=window.getSelection();e?.removeAllRanges(),e?.addRange(t)}
1const i=e.dataTransfer;let n=i?.getData("text/html")||"";const s=i?.getData("text/plain")||"";if(n)n=this._sanitize(n);const r=n||s.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[e]));if(r)this._insertHTMLAtSelection(r);this._lastEditWasPasteOrDrop=true,this._emitInput()}_insertHTMLAtSelection(e){const t=this._getRange();if(!t)return void document.execCommand("insertHTML",false,e);t.deleteContents();const i=t.createContextualFragment(e);t.insertNode(i);const n=window.getSelection();if(t.endContainer)t.collapse(false),n?.removeAllRanges(),n?.addRange(t)}_onSurfaceKeydown(e){const t=e.ctrlKey||e.metaKey;if("Escape"===e.key)return e.preventDefault(),this._armSkipTabOnce(),this._surface?.blur(),void this.blur();if(t&&!e.shiftKey&&("k"===e.key||"K"===e.key)){if(e.preventDefault(),this.readOnly||!this._isCmdVisible("link"))return;return this._onBeforePopover(),void this._showPopover()}if(this.readOnly)return;if(t&&!e.shiftKey&&("b"===e.key||"B"===e.key))return e.preventDefault(),void this.exec("bold");if(t&&!e.shiftKey&&("i"===e.key||"I"===e.key))return e.preventDefault(),void this.exec("italic");if(t&&!e.shiftKey&&("u"===e.key||"U"===e.key))return e.preventDefault(),void this.exec("underline");if(e.altKey&&e.shiftKey&&"5"===e.key)return e.preventDefault(),void this.exec("strikeThrough");if(t&&("z"===e.key||"Z"===e.key)){if(e.preventDefault(),e.shiftKey)this._onRedo();else this._onUndo();return this._freezeSel=false,void this._onSelectionChange()}if(e.ctrlKey&&!e.metaKey&&!e.shiftKey&&("y"===e.key||"Y"===e.key))return e.preventDefault(),this._onRedo(),this._freezeSel=false,void this._onSelectionChange();if("Tab"===e.key)e.preventDefault(),document.execCommand(e.shiftKey?"outdent":"indent",false,null),this._saveSelection(),this._emitInput(),this._freezeSel=false,this._onSelectionChange()}_onWindowKeydown(e){if(!this._skipTabOnce)return;if("Tab"===e.key){e.preventDefault();const t=!e.shiftKey;this._focusOutside(t?1:-1),this._restoreTabbability()}}_onSurfacePointerDown(e){if(this._restoreTabbability(),this._isPopoverOpen())return e.preventDefault(),e.stopPropagation(),void this._hidePopover(true)}_armSkipTabOnce(){if(!this._surface)return;if(this._skipTabOnce=true,this._tabsSuspended)return;this._surface.setAttribute("tabindex","-1");const e=undefined;(this._toolbar?Array.from(this._toolbar.querySelectorAll("button:not([hidden])")):[]).forEach(e=>{e.tabIndex=-1}),this._tabsSuspended=true}_restoreTabbability(){if("-1"===this._surface?.getAttribute("tabindex"))this._surface.removeAttribute("tabindex");if(this._tabsSuspended)this._initToolbarRoving();this._skipTabOnce=false,this._tabsSuspended=false}_focusOutside(e){const t=['a[href]:not([tabindex="-1"]):not([inert])','button:not([disabled]):not([tabindex="-1"])','input:not([disabled]):not([tabindex="-1"])','select:not([disabled]):not([tabindex="-1"])','textarea:not([disabled]):not([tabindex="-1"])','[tabindex]:not([tabindex="-1"])'].join(",");const i=Array.from(document.querySelectorAll(t)).filter(e=>{if(e.closest("mbl-rich-text"))return false;const t=e.getClientRects();if(!t||0===t.length)return false;const i=getComputedStyle(e);if("hidden"===i.visibility||"none"===i.display)return false;return true});if(!i.length)return;let n=null,s=null;for(const e of i){const t=e.compareDocumentPosition(this);if(t&Node.DOCUMENT_POSITION_FOLLOWING)n=e;else if(!s&&t&Node.DOCUMENT_POSITION_PRECEDING)s=e}const r=e<0?n||i[i.length-1]:s||i[0];if(r&&"function"==typeof r.focus)r.focus()}_queryState(){const e=this._inferBlockClass("align")||"align-left";const t=this._inferBlockClass("size")||"size-m";const i=this._getRange();const n=!!this._closestInSelection("A")||(i?this._elementsInRange(i,"A").length>0:false);const s=!!this._closestInSelection("UL")||(i?this._elementsInRange(i,"UL").length>0:false);const r=!!this._closestInSelection("OL")||(i?this._elementsInRange(i,"OL").length>0:false);const a=this._inlineState("strong,b");const l=this._inlineState("em,i");const o=this._inlineState("u");const d=this._inlineState("s,strike");let c="size-l"===t;if(i){const e=this._closestAncestorMatching(i.startContainer,"span.size-m")||this._closestAncestorMatching(i.endContainer,"span.size-m");const t=this._closestAncestorMatching(i.startContainer,"span.size-l")||this._closestAncestorMatching(i.endContainer,"span.size-l");if(e)c=false;else if(t)c=true}return{bold:a,italic:l,underline:o,strike:d,inUL:s,inOL:r,align:e,size:t,inLink:n,largePressed:c}}_inferBlockClass(e){const t=undefined;const i=this._selectedBlocks()[0];if(!i)return null;for(const t of i.classList)if(t.startsWith(e+"-"))return t;
1const n=i.closest?.("li");const s=n?.closest("ul,ol");if(s)for(const t of s.classList)if(t.startsWith(e+"-"))return t;return null}_onSelectionChange(){if(this._freezeSel)return;const e=window.getSelection();if(e&&e.rangeCount){const t=e.getRangeAt(0);if(this._surface?.contains(t.startContainer)&&this._surface?.contains(t.endContainer))this._lastRange=t.cloneRange(),this._savedRange=t.cloneRange(),this._savedOffsets=this._getSelectionOffsets()}const t=this._queryState();this._toolbar?.querySelectorAll("button[data-cmd]")?.forEach(e=>{const i=e.getAttribute("data-cmd");const set=t=>e.setAttribute("aria-pressed",String(t));if("bold"===i)set(t.bold);else if("italic"===i)set(t.italic);else if("underline"===i)set(t.underline);else if("strikeThrough"===i)set(t.strike);else if("insertOrderedList"===i)set(t.inOL);else if("insertUnorderedList"===i)set(t.inUL);else if("align-left"===i)set("align-left"===t.align);else if("align-center"===i)set("align-center"===t.align);else if("align-right"===i)set("align-right"===t.align);else if("link"===i)set(t.inLink);else if("size-large"===i)set(t.largePressed)}),this._updateUndoRedoButtons()}_announce(e){if(this._status)this._status.textContent=e}_initHistory(){const e=this._getSanitizedHTML();this._undoStack=[{html:e,sel:this._getSelectionOffsets()}],this._redoStack=[],this._historyHtml=e,this._sinceKeyframe=0,this._updateUndoRedoButtons()}_recordHistory(){if(this._isRestoring)return;const e=this._getSanitizedHTML();const t=this._savedOffsets||this._getSelectionOffsets();const i=this._undoStack[this._undoStack.length-1];if(!i||e!==i.html){const i=this._historyForceSnapshotOnce||this._lastEditWasPasteOrDrop||this._sinceKeyframe>=25;this._undoStack.push({html:e,sel:t,keyframe:true===i}),this._sinceKeyframe=i?0:this._sinceKeyframe+1,this._historyForceSnapshotOnce=false,this._lastEditWasPasteOrDrop=false,this._redoStack.length=0,this._updateUndoRedoButtons()}else i.sel=t;this._historyHtml=e}_onUndo(){if(this._undoStack.length<=1)return;const e=this._undoStack.pop();this._redoStack.push(e);const t=this._undoStack[this._undoStack.length-1];this._applySnapshot(t),this._updateUndoRedoButtons(),this._announce("Undid action"),this._checkStatus(),this.dispatchEvent(new Event("change",{bubbles:true}))}_onRedo(){if(!this._redoStack.length)return;const e=this._redoStack.pop();this._undoStack.push(e),this._applySnapshot(e),this._updateUndoRedoButtons(),this._announce("Redid action"),this._checkStatus(),this.dispatchEvent(new Event("change",{bubbles:true}))}_applySnapshot(e){this._isRestoring=true,this._setHTML(e.html),this._restoreSelectionFromOffsets(e.sel)||this._restoreSelection(),this._isRestoring=false}_updateUndoRedoButtons(){const e=this.shadowRoot.querySelector('button[data-cmd="undo"]');const t=this.shadowRoot.querySelector('button[data-cmd="redo"]');if(e)e.disabled=this._undoStack.length<=1;if(t)t.disabled=0===this._redoStack.length}_getSanitizedHTML(){return this._sanitize(this._surface?.innerHTML||"")}_setHTML(e,t){const i=this._sanitize(e||"");if(this._surface)this._surface.innerHTML=i,this._surface.normalize(),this._ensureParagraphScaffolding(true);if(true===t)this._originalValue=i;this._onSelectionChange()}_sanitize(e){if("string"==typeof e&&e.includes("\x3c!--"))e=e.replace(/<!--[\s\S]*?-->/g,"");const t=(new DOMParser).parseFromString(`<div>${e}</div>`,"text/html");const i=t.body.firstElementChild;this._normalizeLegacy(i),this._promoteInlineStyles(i);const n=new Set(["P","BR","STRONG","EM","U","S","SPAN","A","UL","OL","LI","BLOCKQUOTE","DIV"]);const s=new Set(["align-left","align-center","align-right","size-s","size-m","size-l"]);(function walk(e){for(const t of[...e.childNodes]){if(8===t.nodeType){t.remove();continue}if(3===t.nodeType)continue;if(1!==t.nodeType){t.remove();continue}const e=t;const i=e.tagName.toUpperCase();if(!n.has(i)){while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove();continue}for(const t of[...e.attributes]){const n=t.name.toLowerCase();if("href"===n&&"A"===i){const t=this._normalizeLinkInput(e.getAttribute("href")||"");if(t)e.setAttribute("href",t),e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer");else e.removeAttribute("href")}else if("class"===n){const t=(e.getAttribute("class")||"").split(/\s+/).filter(e=>s.has(e));t.length?e.setAttribute("class",t.join(" ")):e.removeAttribute("class")}else e.removeAttribute(t.name)}if("IMG"===i){e.remove();continue}if("SPAN"===i&&0===e.attributes.length){while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove();continue}if("A"===i&&!e.hasAttribute("href")){while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove();continue}walk.call(this,e)}}).call(this,i);for(const e of[...i.childNodes])if(3===e.nodeType&&e.textContent.trim()){const n=t.createElement("p");n.textContent=e.textContent,i.replaceChild(n,e)}this._convertBRRunsToParagraphs(i),i.querySelectorAll("a[href]").forEach(e
1=>{const t=e.getAttribute("href")||"";const i=this._dedupeScheme(t);if(i!==t)e.setAttribute("href",i);e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")});const r=undefined;return i.innerHTML||"<p><br></p>"}_convertBRRunsToParagraphs(e){const t="p,div,li,blockquote";e.querySelectorAll(t).forEach(e=>{const t=undefined;if(!Array.from(e.querySelectorAll("br")).length)return;const i=e.innerHTML;if(!/<br\s*\/?>\s*<br\s*\/?>/i.test(i))return;const n=document.createElement("div");n.innerHTML=i;const s=[];let r=document.createElement("span");const flush=()=>{s.push(r),r=document.createElement("span")};let a=false;if(Array.from(n.childNodes).forEach(e=>{if(1===e.nodeType&&"BR"===e.tagName)if(a)flush(),a=false;else a=true,r.appendChild(e.cloneNode(true));else a=false,r.appendChild(e.cloneNode(true))}),s.push(r),s.length>1){const t=e.parentNode;s.forEach(i=>{const n="LI"===e.tagName?document.createElement("li"):document.createElement("p");if(n.className=e.className,n.innerHTML=i.innerHTML.replace(/(?:\s*<br\s*\/?>\s*)+$/i,""),!n.innerHTML||!n.textContent.trim())n.innerHTML="<br>";if(t.insertBefore(n,e),"LI"===e.tagName&&"P"===n.tagName){const i=document.createElement("li");i.className=e.className,i.innerHTML=n.innerHTML,t.insertBefore(i,e),n.remove()}}),e.remove()}})}_normalizeLegacy(e){if(!e)return;e.querySelectorAll("b").forEach(e=>{const t=e.ownerDocument.createElement("strong");while(e.firstChild)t.appendChild(e.firstChild);e.replaceWith(t)}),e.querySelectorAll("i").forEach(e=>{const t=e.ownerDocument.createElement("em");while(e.firstChild)t.appendChild(e.firstChild);e.replaceWith(t)}),e.querySelectorAll("strike").forEach(e=>{const t=e.ownerDocument.createElement("s");while(e.firstChild)t.appendChild(e.firstChild);e.replaceWith(t)}),e.querySelectorAll("center").forEach(e=>{let t=e.closest("li,p,div,h1,h2,h3,h4,h5,h6,blockquote");if("LI"===t?.tagName)t=t.closest("ul,ol")||t;if(t)t.classList.add("align-center");while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove()}),e.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach(e=>{const t=e.ownerDocument.createElement("p");const i={H1:"size-l",H2:"size-l",H3:"size-m",H4:"size-m",H5:"size-s",H6:"size-s"};t.classList.add(i[e.tagName]||"size-m"),e.classList.forEach(e=>/^align-(left|center|right)$/.test(e)&&t.classList.add(e));while(e.firstChild)t.appendChild(e.firstChild);e.replaceWith(t)}),e.querySelectorAll("div").forEach(e=>{if(!e.querySelector("ul,ol,table,pre")){const t=e.ownerDocument.createElement("p");e.classList.forEach(e=>t.classList.add(e));while(e.firstChild)t.appendChild(e.firstChild);e.replaceWith(t)}}),e.querySelectorAll("a[href]").forEach(e=>{const t=this._normalizeLinkInput(e.getAttribute("href")||"");if(t)e.setAttribute("href",t),e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer");else e.removeAttribute("href")})}_promoteInlineStyles(e){if(!e)return;const t=undefined;e.querySelectorAll("[style]").forEach(e=>{const t=(e.getAttribute("style")||"").toLowerCase();if(!t)return;const i=/font-weight\s*:\s*(bold|[6-9]00)/.test(t);const n=/font-style\s*:\s*italic/.test(t);const s=/line-through/.test(t)||/text-decoration-line\s*:\s*line-through/.test(t);const r=/underline/.test(t)||/text-decoration-line\s*:\s*underline/.test(t);if(!(i||n||s||r))return;const a=e.ownerDocument;const l=[];if(i)l.push("strong");if(n)l.push("em");if(r)l.push("u");
1if(s)l.push("s");if("A"===e.tagName){let t=a.createDocumentFragment();while(e.firstChild)t.appendChild(e.firstChild);l.forEach(e=>{const i=a.createElement(e);i.appendChild(t),t=i}),e.appendChild(t),e.removeAttribute("style")}else{let t=a.createDocumentFragment();while(e.firstChild)t.appendChild(e.firstChild);l.forEach(e=>{const i=a.createElement(e);i.appendChild(t),t=i}),e.parentNode.insertBefore(t,e),e.remove()}})}_ensureParagraphScaffolding(e){if(!this._surface)return;const t=this._surface.innerHTML.trim();if(!t||""===t||"<br>"===t||"<p></p>"===t||"<p><br></p>"===t||"<p></p><p></p>"===t)return void(this._surface.innerHTML="<p><br></p>");if(e)if(this._surface.firstChild&&3===this._surface.firstChild.nodeType){const e=this._surface.firstChild.textContent;this._surface.removeChild(this._surface.firstChild);const t=document.createElement("p");t.textContent=e,this._surface.insertBefore(t,this._surface.firstChild)}}_canonicalizeEmptyContent(){const e=this._surface?.querySelector("p");if(!e)this._surface.innerHTML="<p><br></p>"}_applyMode(){if(!this._surface)return;const e=this.readOnly;if(e)this._hidePopover(false);if(this._surface.setAttribute("contenteditable",e?"false":"true"),this._surface.setAttribute("aria-readonly",String(e)),this._surface.setAttribute("spellcheck",e?"false":"true"),e)this._surface.setAttribute("role","document"),this._surface.removeAttribute("aria-multiline");else this._surface.setAttribute("role","textbox"),this._surface.setAttribute("aria-multiline","true");this._onSelectionChange()}_checkStatus(){try{const e=this.hasAttribute("required");let t;let i=this._originalValue;try{t=this.querySelector("div.surface").innerHTML}catch(e){t=String(this.getAttribute("value")||"<p></p>")}if(void 0===i)i=t,this._originalValue=i;const n=(()=>{const e=document.createElement("div");e.innerHTML=String(t);const i=undefined;return""!==(e.textContent||e.innerText||"").trim()})();const s=!e||n;const r=!e||n;const a=String(i)!==String(t);if(!a)this.classList.remove("dirty"),this.classList.remove("datadirty");else this.classList.add("dirty"),this.classList.add("datadirty");return{isDirty:a,isValid:r,isComplete:s}}catch(e){return console.error("MBLRichText _checkStatus error:",e),{isDirty:false,isValid:true,isComplete:true}}}_cleanupInlineArtifacts(){if(!this._surface)return;const e=this._getRange();const t=e&&this._blockAncestor(e.commonAncestorContainer)||this._surface;const i=undefined;t.querySelectorAll("strong,b,em,i,u,s,strike,span").forEach(e=>{if(e.matches("span")&&0===e.attributes.length){if(!e.textContent||""===e.textContent.replace(/[\s\u200B\u200C\u200D\u2060]/g,""))e.remove();else this._unwrapElement(e);return}const t=undefined;if(!(e.textContent||"").replace(/[\u200B\u200C\u200D\u2060\s]/g,"").length)return void e.remove()});const mergeTag=(e,t)=>
1{const i=undefined;t.querySelectorAll(e).forEach(e=>{let t=e.nextSibling;while(t&&3===t.nodeType&&""===(t.nodeValue||"").trim())t=t.nextSibling;if(t&&1===t.nodeType&&t.tagName===e.tagName&&e.className===t.className){while(t.firstChild)e.appendChild(t.firstChild);t.remove()}})};["STRONG","B","EM","I","U","S","STRIKE","SPAN"].forEach(e=>mergeTag(e,t));const n=undefined;t.querySelectorAll("strong strong, em em, u u, s s, b b, i i, strike strike, span.size-l span.size-l, span.size-m span.size-m, span.size-s span.size-s").forEach(e=>{while(e.firstChild)e.parentNode.insertBefore(e.firstChild,e);e.remove()}),this._surface.normalize()}_unwrapElement(e){const t=e.parentNode;if(!t)return;while(e.firstChild)t.insertBefore(e.firstChild,e);e.remove()}}class XTime extends HTMLElement{static get observedAttributes(){return["name","value","min","max","step","required","disabled","readonly","placeholder","aria-describedby","aria-errormessage","aria-label","displayFormat","timeStart","timeEnd"]}constructor(){super(),this._settingAttr=false,this._prevValue="";const e=this.attachShadow({mode:"open"});e.innerHTML=`\n <style>\n :host { \n display: block;\n width: 100%;\n }\n select { \n font: inherit; \n padding: var(--dt-space-xs, 0.25rem) var(--dt-space-sm, 0.5rem); \n border: 1px solid var(--error-border-color, var(--dt-gray-400, #ccc)); \n border-radius: var(--dt-radius-md, 0.35rem); \n background: var(--error-bg-color, #fff); \n min-inline-size: 12ch; \n min-block-size: 2.25rem;\n height: 2.25rem;\n width: 100%;\n font-size: var(--dt-font-size-base, 0.9rem);\n line-height: 1.4;\n }\n select:focus { \n outline: 2px solid var(--dt-color-primary, #005fcc); \n outline-offset: 2px; \n border-color: var(--dt-color-primary, #005fcc);\n }\n select:disabled { \n opacity: 0.6; \n cursor: not-allowed; \n background: var(--dt-gray-50, #f8f8f8);\n }\n </style>\n <select id="sel"></select>\n `,this.$s=e.getElementById("sel")}connectedCallback(){DateTimeUtils.ensureHidden(this),this._renderAll(),DateTimeUtils.syncAria(this,this.$s),DateTimeUtils.wireExternalLabel(this,this.$s),this.$s.addEventListener("change",()=>{this._onChange(),this._redispatch("input"),this._redispatch("change")}),this.$s.addEventListener("mousedown",e=>{if(this.hasAttribute("readonly"))e.preventDefault()},true),this.$s.addEventListener("keydown",e=>{if(this.hasAttribute("readonly")&&!["Tab","Shift","Alt","Meta","Control"].includes(e.key))e.preventDefault()},true),this._reflect()}attributeChangedCallback(e,t,i){if(t===i)return;if("value"===e){if(this._settingAttr)return;return this._applyValue(i||""),void DateTimeUtils.updateHidden(this,this.value||"")}if("name"===e)return void DateTimeUtils.updateHidden(this,this.value||"");if(["min","max","step","required","disabled","readonly","placeholder","displayFormat","timeStart","timeEnd"].includes(e))return this._renderAll(),void DateTimeUtils.updateHidden(this,this.value||"");if(e.startsWith("aria-"))DateTimeUtils.syncAria(this,this.$s)}get value(){return this.getAttribute("value")||""}set value(e){null==e?this.removeAttribute("value"):this.setAttribute("value",e)}get step(){return DateTimeUtils.stepMins(this.getAttribute("step"))}set step(e){null==e?this.removeAttribute("step"):this.setAttribute("step",String(e))}get displayFormat(){return"12h"===(this.getAttribute("displayFormat")||"24h").toLowerCase()?"12h":"24h"}set displayFormat(e){e&&"12h"===e.toLowerCase()?this.setAttribute("displayFormat","12h"):this.setAttribute("displayFormat","24h")}focus(e){this.$s?.focus(e)}checkValidity(){return this.$s.checkValidity()}reportValidity(){return this.$s.reportValidity()}_redispatch(e){this.dispatchEvent(new Event(e,{bubbles:true,composed:true}))}_renderAll(){this._buildOptions(),this.$s.required=this.hasAttribute("required"),this.$s.disabled=this.hasAttribute("disabled"),this.$s.setAttribute("aria-readonly",this.hasAttribute("readonly")?"true":"false"),this._applyValue(this.getAttribute("value")||"")}_buildOptions(){const e=this.getAttribute("placeholder");const t=this.step;const i=this.getAttribute("min")?DateTimeUtils.parseHHMM(this.getAttribute("min")):null;const n=this.getAttribute("max")?DateTimeUtils.parseHHMM(this.getAttribute("max")):null;const s=this.getAttribute("timeStart");const r=this.getAttribute("timeEnd");const a=s?DateTimeUtils.parseHHMM(s):null;const l=r?DateTimeUtils.parseHHMM(r):null;const o=null!=a?a:null!=i?i:0;let d=null!=a?a:0;d=o+Math.ceil((d-o)/t)*t;let c=null!=l?l:null!=n?n:24*60-1;c=o+Math.floor((c-o)/t)*t;const u=this.$s;if(u.innerHTML="",null!=e){const t=document.createElement("option");t.value="",t.textContent=e||"Select time",t.disabled=true,t.selected=true,t.hidden=true,u.appendChild(t)}if(d<=c)for(let e=d;e<=c;e+=t){const t=document.createElement("option");t.value=DateTimeUtils.fmtHHMM(e),t.textContent="12h"===this.displayFormat?DateTimeUtils.fmtHHMM12(e):DateTimeUtils.fmtHHMM(e),u.appendChild(t)}if(0===u.options.length){const e=document.createElement("option");e.value="",e.textContent="No valid times",e.disabled=true,e.selected=true,u.appendChild(e)}}_applyValue(e){const t=[...this.$s.options].some(t=>t.value===e);if(this._settingAttr=true,t)this.$s.value=e,this.setAttribute("value",e),this._prevValue=e;else{const e=[...this.$s.options].find(e=>e.value);if(e&&this.hasAttribute("required")&&null==this.getAttribute("placeholder"))this.$s.value=e.value,this.setAttribute("value",e.value),this._prevValue=e.value;else this.$s.value="",this.removeAttribute("value"),this._prevValue=""}this._settingAttr=false}_onChange(){if(this.hasAttribute("readonly"))return void(this.$s.value=this._prevValue||"");const e=this.$s.value||"";if(this._settingAttr=true,e)this.setAttribute("value",e);else this.removeAttribute("value");this._settingAttr=false,this._prevValue=e,DateTimeUtils.updateHidden(this,e)}_reflect(){const e=this.$s.value||"";const t=undefined;
1if(e!==(this.getAttribute("value")||"")){if(this._settingAttr=true,e)this.setAttribute("value",e);else this.removeAttribute("value");this._settingAttr=false}DateTimeUtils.updateHidden(this,e)}}class XDate extends HTMLElement{static get observedAttributes(){return["name","value","min","max","required","disabled","readonly","placeholder","autocomplete","aria-describedby","aria-errormessage","aria-label","twoDigitYear","yyPivot"]}constructor(){super();const e=this.attachShadow({mode:"open"});e.innerHTML=`\n <style>\n :host { \n display: block;\n width: 100%;\n }\n input { \n font: inherit; \n padding: var(--dt-space-xs, 0.25rem) var(--dt-space-sm, 0.5rem); \n border: 1px solid var(--error-border-color, var(--dt-gray-400, #ccc)); \n border-radius: var(--dt-radius-md, 0.35rem); \n background: var(--error-bg-color, #fff); \n min-inline-size: 12ch; \n min-block-size: 2.25rem;\n height: 2.25rem;\n width: calc(100% - 20px);\n font-size: var(--dt-font-size-base, 0.9rem);\n line-height: 1.4;\n }\n input:focus { \n outline: 2px solid var(--dt-color-primary, #005fcc); \n outline-offset: 2px; \n border-color: var(--dt-color-primary, #005fcc);\n }\n input:disabled { \n opacity: 0.6; \n cursor: not-allowed; \n background: var(--dt-gray-50, #f8f8f8);\n }\n </style>\n <input id="i" type="date" />\n `,this.$i=e.getElementById("i")}connectedCallback(){DateTimeUtils.ensureHidden(this),this._render(),DateTimeUtils.syncAria(this,this.$i),DateTimeUtils.wireExternalLabel(this,this.$i),this.$i.addEventListener("input",()=>{this._reflect(),this._redispatch("input")}),this.$i.addEventListener("change",()=>{this._reflect(),this._redispatch("change")}),this.$i.addEventListener("blur",()=>this.$i.reportValidity?.()),this.$i.addEventListener("paste",e=>
1{if(!this.hasAttribute("twoDigitYear"))return;const t=(e.clipboardData||window.clipboardData)?.getData("text")||"";const i=DateTimeUtils.toISODateMaybe2D(t,this._pivot());if(i)e.preventDefault(),this.$i.value=i,this._reflect(),this._redispatch("input"),this._redispatch("change"),this.$i.reportValidity?.()}),this._reflect()}_redispatch(e){this.dispatchEvent(new Event(e,{bubbles:true,composed:true}))}attributeChangedCallback(e,t,i){if(t===i)return;if("value"===e)return this.$i.value=this._coerceDate(i||""),void DateTimeUtils.updateHidden(this,this.$i.value);if("name"===e)return void DateTimeUtils.updateHidden(this,this.$i.value);if(["min","max","required","disabled","readonly","placeholder","autocomplete","twoDigitYear","yyPivot"].includes(e))return this._render(),void DateTimeUtils.updateHidden(this,this.$i.value);if(e.startsWith("aria-"))DateTimeUtils.syncAria(this,this.$i)}get value(){return this.getAttribute("value")||""}set value(e){null==e?this.removeAttribute("value"):this.setAttribute("value",e)}focus(e){this.$i?.focus(e)}checkValidity(){return this.$i.checkValidity()}reportValidity(){return this.$i.reportValidity()}_pivot(){const e=+this.getAttribute("yyPivot");return Number.isFinite(e)?e:1970}_coerceDate(e){if(!e)return"";if(this.hasAttribute("twoDigitYear")){const t=DateTimeUtils.toISODateMaybe2D(e,this._pivot());if(t)return t}return DateTimeUtils.isDate(e)?e:""}_render(){const e=this.getAttribute("min")||"",t=this.getAttribute("max")||"";const i=this.hasAttribute("twoDigitYear")?DateTimeUtils.toISODateMaybe2D(e,this._pivot())||(DateTimeUtils.isDate(e)?e:""):DateTimeUtils.isDate(e)?e:"";const n=this.hasAttribute("twoDigitYear")?DateTimeUtils.toISODateMaybe2D(t,this._pivot())||(DateTimeUtils.isDate(t)?t:""):DateTimeUtils.isDate(t)?t:"";this.$i.min=i||"",this.$i.max=n||"",this.$i.required=this.hasAttribute("required"),this.$i.disabled=this.hasAttribute("disabled"),this.$i.readOnly=this.hasAttribute("readonly");const s=this.getAttribute("placeholder");if(null!=s)this.$i.placeholder=s;else this.$i.removeAttribute("placeholder");const r=this.getAttribute("autocomplete");if(null!=r)this.$i.autocomplete=r;else this.$i.removeAttribute("autocomplete");this.$i.value=this._coerceDate(this.getAttribute("value")||"")}_reflect(){const e=this.$i.value||"",t=undefined;if(e!==(this.getAttribute("value")||""))if(e)this.setAttribute("value",e);else this.removeAttribute("value");DateTimeUtils.updateHidden(this,e)}}class XDateTimeWrap extends HTMLElement{static get observedAttributes(){return["name","value","min","max","step","required","disabled","readonly","twoDigitYear","yyPivot","displayFormat"]}constructor(){super(),this._setting=false,this._onFormSubmit=null;const e=this.attachShadow({mode:"open"});e.innerHTML=`\n <style>\n :host { \n display: block;\n width: 100%;\n }\n .grid { \n display: grid; \n grid-template-columns: 1fr 1fr; \n gap: var(--dt-space-sm, 0.5rem); \n align-items: stretch;\n width: 100%;\n }\n .col { \n display: flex; \n flex-direction: column; \n gap: var(--dt-space-xs, 0.25rem); \n }\n .col-label { \n font-size: var(--dt-font-size-xs, 0.7rem); \n font-weight: 500; \n color: var(--dt-gray-600, #6b7280);\n margin: 0;\n padding: 0;\n line-height: 1.2;\n }\n x-date, x-time {\n width: 100%;\n --error-border-color: var(--error-border-color);\n --error-bg-color: var(--error-bg-color);\n }\n </style>\n <div class="grid">\n <div class="col">\n <x-date id="d"></x-date>\n </div>\n <div class="col">\n <x-time id="t"></x-time>\n </div>\n </div>\n `,this.$d=e.getElementById("d"),this.$t=e.getElementById("t")}connectedCallback(){DateTimeUtils.ensureHidden(this),this._renderAll(),DateTimeUtils.wireExternalLabel(this,this.$d);const onAny=()=>{this._applyTimeRangeForDate(),this._reflectCombined()};for(const e of["input","change"])this.$d.addEventListener(e,onAny),this.$t.addEventListener(e,onAny);const e=this.closest("form");if(e)this._onFormSubmit=()=>{this._applyTimeRangeForDate(),this._reflectCombined()},e.addEventListener("submit",this._onFormSubmit,true);this._applyTimeRangeForDate(),this._reflectCombined()}disconnectedCallback(){const e=this.closest("form");if(e&&this._onFormSubmit)e.removeEventListener("submit",this._onFormSubmit,true)}attributeChangedCallback(e,t,i){if(t===i)return;if("value"===e){if(this._setting)return;if(i&&DateTimeUtils.isDT(i)){const[e,t]=i.split("T");this.$d.setAttribute("value",e),this.$t.setAttribute("value",t)}else this.$d.removeAttribute("value"),this.$t.removeAttribute("value");return this._applyTimeRangeForDate(),void DateTimeUtils.updateHidden(this,i||"")}if(["min","max","step","required","disabled","readonly","twoDigitYear","yyPivot","displayFormat"].includes(e))return this._renderAll(),this._applyTimeRangeForDate(),void this._reflectCombined();if("name"===e)DateTimeUtils.updateHidden(this,this.getAttribute("value")||"")}get value(){return this.getAttribute("value")||""}set value(e){null==e?this.removeAttribute("value"):this.setAttribute("value",e)}focus(e){this.$d?.focus(e)}checkValidity(){return this.$d.checkValidity()&&this.$t.checkValidity()}reportValidity(){return this.$d.reportValidity()&&this.$t.reportValidity()}_renderAll(){const e=this.hasAttribute("required"),t=this.hasAttribute("readonly"),i=this.hasAttribute("disabled");for(const n of[this.$d,this.$t])n.toggleAttribute("required",e),n.toggleAttribute("readonly",t),n.toggleAttribute("disabled",i);const n=this.getAttribute("step")||"1";this.$t.setAttribute("step",n);const s=this.getAttribute("timeStart");const r=this.getAttribute("timeEnd");if(null!=s)this.$t.setAttribute("timeStart",s);else this.$t.removeAttribute("timeStart");if(null!=r)this.$t.setAttribute("timeEnd",r);else this.$t.removeAttribute("timeEnd");if(this.$d.toggleAttribute("twoDigitYear",this.hasAttribute("twoDigitYear")),this.hasAttribute("yyPivot"))this.$d.setAttribute("yyPivot",this.getAttribute("yyPivot"));else this.$d.removeAttribute("yyPivot");if(this.getAttribute("displayFormat"))this.$t.setAttribute("displayFormat",this.getAttribute("displayFormat"));else this.$t.setAttribute("displayFormat","24h");const a=this.getAttribute("min")&&DateTimeUtils.isDT(this.getAttribute("min"))?this.getAttribute("min"):"";const l=this.getAttribute("max")&&DateTimeUtils.isDT(this.getAttribute("max"))?this.getAttribute("max"):"";const o=a?a.split("T")[0]:"";const d=l?l.split("T")[0]:"";if(o)this.$d.setAttribute("min",o);else this.$d.removeAttribute("min");if(d)this.$d.setAttribute("max",d);else this.$d.removeAttribute("max")}_applyTimeRangeForDate(){const e=this.$d.getAttribute("value")||"";const t=this.getAttribute("min")&&DateTimeUtils.isDT(this.getAttribute("min"))?this.getAttribute("min"):"";const i=this.getAttribute("max")&&DateTimeUtils.isDT(this.getAttribute("max"))?this.getAttribute("max"):"";let n="",s="";if(t){const[i,s]=t.split("T");if(e&&e===i)n=s}if(i){const[t,n]=i.split("T");if(e&&e===t)s=n}
1if(n)this.$t.setAttribute("min",n);else this.$t.removeAttribute("min");if(s)this.$t.setAttribute("max",s);else this.$t.removeAttribute("max")}_reflectCombined(){const e=this.$d.getAttribute("value")||"";const t=this.$t.getAttribute("value")||"";const i=e&&t?`${e}T${t}`:"";const n=undefined;if(i!==(this.getAttribute("value")||"")){if(this._setting=true,i)this.setAttribute("value",i);else this.removeAttribute("value");this._setting=false}DateTimeUtils.updateHidden(this,i),this.dispatchEvent(new Event("input",{bubbles:true,composed:true})),this.dispatchEvent(new Event("change",{bubbles:true,composed:true}))}}class XDateRange extends HTMLElement{static get observedAttributes(){return["name","value","min","max","required","disabled","readonly","placeholder","aria-describedby","aria-errormessage","aria-label"]}constructor(){super(),this._open=false,this._startDate=null,this._endDate=null,this._hoverDate=null,this._viewYear=null,this._viewMonth=null,this._settingAttr=false,this._onDocClick=this._onDocClick.bind(this),this._onDocKey=this._onDocKey.bind(this);const e=this.attachShadow({mode:"open"});e.innerHTML=`\n <style>\n :host { display: block; position: relative; width: 100%; }\n\n /* ---- Trigger button ---- */\n .trigger {\n font: inherit;\n padding: var(--dt-space-xs, 0.25rem) var(--dt-space-sm, 0.5rem);\n border: 2px solid var(--error-border-color, var(--dt-gray-400, #ccc));\n border-radius: var(--dt-radius-md, 0.35rem);\n background: var(--error-bg-color, #fff);\n min-inline-size: 12ch;\n min-block-size: 2.25rem;\n height: 2.25rem;\n width: 100%;\n font-size: var(--dt-font-size-base, 0.9rem);\n line-height: 1.4;\n text-align: left;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.5rem;\n color: inherit;\n box-sizing: border-box;\n padding: 22px 12px;\n }\n .trigger:focus {\n outline: 2px solid var(--dt-color-primary, #005fcc);\n outline-offset: 2px;\n border-color: var(--dt-color-primary, #005fcc);\n }\n .trigger:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n background: var(--dt-gray-50, #f8f8f8);\n }\n .ph { color: var(--dt-gray-400, #aaa); }\n .cal-ic { flex-shrink: 0; opacity: 0.45; }\n\n /* ---- Floating popup ---- */\n .popup {\n position: fixed;\n z-index: 9999;\n background: #fff;\n border: 1px solid var(--dt-gray-300, #d1d5db);\n border-radius: var(--dt-radius-md, 0.5rem);\n box-shadow: 0 8px 24px rgba(0,0,0,0.13);\n padding: 0.75rem;\n user-select: none;\n }\n .popup[hidden] { display: none !important; }\n\n /* ---- Nav row ---- */\n .nav-row {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n margin-bottom: 0.6rem;\n }\n .months-wrap { display: flex; gap: 1.25rem; flex: 1; }\n .nav-btn {\n background: none;\n border: 1px solid transparent;\n border-radius: var(--dt-radius-md, 0.35rem);\n cursor: pointer;\n padding: 0.15rem 0.5rem;\n font-size: 1.2rem;\n line-height: 1;\n color: inherit;\n flex-shrink: 0;\n }\n .nav-btn:hover { background: var(--dt-gray-100, #f3f4f6); border-color: var(--dt-gray-300, #d1d5db); }\n .nav-btn:focus { outline: 2px solid var(--dt-color-primary, #005fcc); outline-offset: 2px; }\n\n /* ---- Month grid ---- */\n .month { min-width: 210px; }\n .month-title {\n text-align: center;\n font-weight: 600;\n font-size: 0.85rem;\n margin-bottom: 0.35rem;\n }\n .weekdays {\n display: grid;\n grid-template-columns: repeat(7, 1fr);\n text-align: center;\n font-size: 0.68rem;\n font-weight: 600;\n color: var(--dt-gray-500, #6b7280);\n margin-bottom: 0.15rem;\n }\n .days { display: grid; grid-template-columns: repeat(7, 1fr); }\n .day {\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 0.78rem;\n height: 2rem;\n cursor: pointer;\n border: none;\n background: none;\n padding: 0;\n color: inherit;\n border-radius: var(--dt-radius-md, 0.35rem);\n }\n .day.empty { cursor: default; pointer-events: none; }\n .day.disabled { color: var(--dt-gray-300, #bbb);
1 cursor: not-allowed; pointer-events: none; }\n .day.today { font-weight: 700; }\n .day:not(.disabled):not(.empty):not(.sel):hover { background: var(--dt-gray-100, #f3f4f6); }\n\n /* Selected endpoints */\n .day.sel {\n background: var(--dt-color-primary, #005fcc);\n color: #fff;\n border-radius: var(--dt-radius-md, 0.35rem);\n }\n /* In-range strip (days between start and end) */\n .day.in-range {\n background: rgba(0,95,204,0.11);\n border-radius: 0;\n }\n /* Flatten sides where the range strip connects */\n .day.range-left { border-top-left-radius: var(--dt-radius-md, 0.35rem); border-bottom-left-radius: var(--dt-radius-md, 0.35rem); border-top-right-radius: 0; border-bottom-right-radius: 0; }\n .day.range-right { border-top-right-radius: var(--dt-radius-md, 0.35rem); border-bottom-right-radius: var(--dt-radius-md, 0.35rem); border-top-left-radius: 0; border-bottom-left-radius: 0; }\n /* Endpoints that border the range strip */\n .day.sel.range-left { border-top-right-radius: 0; border-bottom-right-radius: 0; }\n .day.sel.range-right { border-top-left-radius: 0; border-bottom-left-radius: 0; }\n /* Single selected date (no range) */\n .day.sel.alone { border-radius: var(--dt-radius-md, 0.35rem); }\n\n /* ---- Footer ---- */\n .footer {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-top: 0.65rem;\n padding-top: 0.5rem;\n border-top: 1px solid var(--dt-gray-200, #e5e7eb);\n font-size: 0.78rem;\n color: var(--dt-gray-500, #6b7280);\n }\n .clear-btn {\n background: none;\n border: none;\n color: var(--dt-color-primary, #005fcc);\n cursor: pointer;\n font: inherit;\n font-size: 0.78rem;\n padding: 0;\n text-decoration: underline;\n }\n .clear-btn:hover { opacity: 0.75; }\n </style>\n\n <button type="button" class="trigger" id="trig" aria-haspopup="dialog" aria-expanded="false">\n <span class="trigger-label"></span>\n <svg class="cal-ic" width="14" height="14" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">\n <path d="M3.5 0a.5.5 0 0 1 .5.5V1h8V.5a.5.5 0 0 1 1 0V1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h1V.5a.5.5 0 0 1 .5-.5zM2 2a1 1 0 0 0-1 1v1h14V3a1 1 0 0 0-1-1H2zm13 3H1v9a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V5z"/>\n </svg>\n </button>\n\n <div class="popup" id="pop" hidden role="dialog" aria-modal="false" aria-label="Choose date range">\n <div class="nav-row">\n <button type="button" class="nav-btn" id="prev" aria-label="Previous month">‹</button>\n <div class="months-wrap" id="mwrap"></div>\n <button type="button" class="nav-btn" id="next" aria-label="Next month">›</button>\n </div>\n <div class="footer">\n <span id="hint">Click a start date</span>\n <button type="button" class="clear-btn" id="clr">Clear</button>\n </div>\n </div>\n `,this.$trig=e.getElementById("trig"),this.$pop=e.getElementById("pop"),this.$mwrap=e.getElementById("mwrap"),this.$prev=e.getElementById("prev"),this.$next=e.getElementById("next"),this.$clr=e.getElementById("clr"),this.$hint=e.getElementById("hint"),this.$lbl=e.querySelector(".trigger-label")}connectedCallback(){DateTimeUtils.ensureHidden(this),this._initView(),this._renderTrigger(),DateTimeUtils.wireExternalLabel(this,this.$trig),DateTimeUtils.syncAria(this,this.$trig),this.$trig.addEventListener("click",()=>{if(!this.hasAttribute("disabled")&&!this.hasAttribute("readonly"))this._togglePopup()}),this.$pop.addEventListener("click",e=>e.stopPropagation()),this.$prev.addEventListener("click",e=>{e.stopPropagation(),this._nav(-1)}),this.$next.addEventListener("click",e=>{e.stopPropagation(),this._nav(1)}),this.$clr.addEventListener("click",e=>{e.stopPropagation(),this._clear()}),this.$mwrap.addEventListener("click",e=>{const t=e.target.closest(".day");if(!t||t.classList.contains("disabled")||t.classList.contains("empty")||!t.dataset.iso)return;
1this._onDayClick(t.dataset.iso)}),this.$mwrap.addEventListener("mousemove",e=>{const t=e.target.closest(".day:not(.disabled):not(.empty)");const i=t?t.dataset.iso||null:null;if(i!==this._hoverDate)if(this._hoverDate=i,this._startDate&&!this._endDate)this._renderCalendars()}),this.$mwrap.addEventListener("mouseleave",()=>{if(this._hoverDate)if(this._hoverDate=null,this._startDate&&!this._endDate)this._renderCalendars()})}disconnectedCallback(){document.removeEventListener("click",this._onDocClick),document.removeEventListener("keydown",this._onDocKey)}attributeChangedCallback(e,t,i){if(t===i)return;if("value"===e){if(this._settingAttr)return;return this._parseValue(i||""),this._renderTrigger(),void DateTimeUtils.updateHidden(this,i||"")}if("name"===e)return void DateTimeUtils.updateHidden(this,this.getAttribute("value")||"");if(["min","max","required","disabled","readonly","placeholder"].includes(e))return void this._renderTrigger();if(e.startsWith("aria-"))DateTimeUtils.syncAria(this,this.$trig)}get value(){return this.getAttribute("value")||""}set value(e){null==e?this.removeAttribute("value"):this.setAttribute("value",e)}focus(e){this.$trig?.focus(e)}checkValidity(){return!this.hasAttribute("required")||!!this.value}reportValidity(){return this.checkValidity()}_initView(){const e=new Date;if(this._viewYear=e.getFullYear(),this._viewMonth=e.getMonth(),this._parseValue(this.getAttribute("value")||""),this._startDate){const e=this._isoToYMD(this._startDate);if(e)this._viewYear=e.y,this._viewMonth=e.m}}_parseValue(e){if(this._startDate=null,this._endDate=null,!e)return;try{const t=JSON.parse(e);if(t&&DateTimeUtils.isDate(t.start))this._startDate=t.start;if(t&&DateTimeUtils.isDate(t.end))this._endDate=t.end}catch(e){}}_isoToYMD(e){if(!DateTimeUtils.isDate(e))return null;const[t,i,n]=e.split("-").map(Number);return{y:t,m:i-1,d:n}}_ymdToISO(e,t,i){return`${e}-${DateTimeUtils.pad2(t+1)}-${DateTimeUtils.pad2(i)}`}_togglePopup(){this._open?this._closePopup():this._openPopup()}_openPopup(){this._open=true,this.$trig.setAttribute("aria-expanded","true"),this._renderCalendars(),this.$pop.removeAttribute("hidden"),this._position(),document.addEventListener("click",this._onDocClick),document.addEventListener("keydown",this._onDocKey)}_closePopup(){this._open=false,this.$trig.setAttribute("aria-expanded","false"),this.$pop.setAttribute("hidden",""),this._hoverDate=null,document.removeEventListener("click",this._onDocClick),document.removeEventListener("keydown",this._onDocKey)}_position(){const e=this.$trig.getBoundingClientRect();const t=this.$pop.offsetHeight||320;const i=this.$pop.offsetWidth||540;const n=window.innerWidth;const s=window.innerHeight;const r=s-e.bottom>=t||s-e.bottom>=e.top?e.bottom+window.scrollY+4:e.top+window.scrollY-t-4;let a=e.left+window.scrollX;if(a+i>n+window.scrollX-8)a=Math.max(window.scrollX+8,n+window.scrollX-i-8);this.$pop.style.top=r+"px",this.$pop.style.left=a+"px"}_onDocClick(e){const t=undefined;if((e.composedPath?e.composedPath():[]).some(e=>e===this.$pop||e===this.$trig))return;this._closePopup()}_onDocKey(e){if("Escape"===e.key)this._closePopup(),this.$trig.focus()}_nav(e){if(this._viewMonth+=e,this._viewMonth<0)this._viewMonth=11,this._viewYear--;if(this._viewMonth>11)this._viewMonth=0,this._viewYear++;this._renderCalendars()}_renderCalendars(){this.$mwrap.innerHTML="";for(let e=0;e<2;e++){let t=this._viewMonth+e,i=this._viewYear;if(t>11)t-=12,i++;this.$mwrap.appendChild(this._buildMonth(i,t))}this._updateHint()}_buildMonth(e,t){const i=this.getAttribute("min")||"";const n=this.getAttribute("max")||"";const s=new Date;const r=this._ymdToISO(s.getFullYear(),s.getMonth(),s.getDate());let a=this._startDate,l=this._endDate;const o=undefined;if("end"===(this._startDate&&!this._endDate?"end":"start")&&this._hoverDate)if(this._hoverDate>=this._startDate)a=this._startDate,l=this._hoverDate;else a=this._hoverDate,l=this._startDate;const d=!!(a&&l&&a!==l);const c=document.createElement("div");c.className="month";const u=document.createElement("div");u.className="month-title",u.textContent=new Date(e,t,1).toLocaleDateString(void 0,{month:"long",year:"numeric"}),c.appendChild(u);const f=document.createElement("div");f.className="weekdays";
1for(const e of["Su","Mo","Tu","We","Th","Fr","Sa"]){const t=document.createElement("span");t.textContent=e,f.appendChild(t)}c.appendChild(f);const h=document.createElement("div");h.className="days";const p=new Date(e,t,1).getDay();const m=new Date(e,t+1,0).getDate();for(let e=0;e<p;e++){const e=document.createElement("div");e.className="day empty",h.appendChild(e)}for(let s=1;s<=m;s++){const o=this._ymdToISO(e,t,s);const c=(p+s-1)%7;const u=document.createElement("div");u.className="day",u.textContent=String(s);const f=undefined;if(i&&o<i||n&&o>n)u.classList.add("disabled");else u.dataset.iso=o;if(o===r)u.classList.add("today");const m=o===this._startDate||o===this._endDate;const g=d&&o>a&&o<l;const b=d&&o>=a&&o<=l;if(m)u.classList.add("sel");if(g)u.classList.add("in-range");if(!d&&m)u.classList.add("alone");if(b){if(o===a||0===c)u.classList.add("range-left");if(o===l||6===c)u.classList.add("range-right")}h.appendChild(u)}return c.appendChild(h),c}_onDayClick(e){const t=this.getAttribute("min")||"";const i=this.getAttribute("max")||"";if(t&&e<t||i&&e>i)return;if(!this._startDate||this._endDate)this._startDate=e,this._endDate=null,this._hoverDate=null,this._renderCalendars();else{let t=this._startDate,i=e;if(i<t)[t,i]=[i,t];this._startDate=t,this._endDate=i,this._commit(),this._closePopup()}}_commit(){if(!this._startDate||!this._endDate)return;const e=JSON.stringify({start:this._startDate,end:this._endDate});this._settingAttr=true,this.setAttribute("value",e),this._settingAttr=false,DateTimeUtils.updateHidden(this,e),this._renderTrigger(),this.dispatchEvent(new Event("input",{bubbles:true,composed:true})),this.dispatchEvent(new Event("change",{bubbles:true,composed:true}))}_clear(){this._startDate=null,this._endDate=null,this._hoverDate=null,this._settingAttr=true,this.removeAttribute("value"),this._settingAttr=false,DateTimeUtils.updateHidden(this,""),this._renderTrigger(),this._renderCalendars(),this.dispatchEvent(new Event("input",{bubbles:true,composed:true})),this.dispatchEvent(new Event("change",{bubbles:true,composed:true}))}_renderTrigger(){const e=this.getAttribute("placeholder")||"Select date range";if(this.$trig.disabled=this.hasAttribute("disabled"),this._startDate&&this._endDate)this.$lbl.textContent=this._formatRange(this._startDate,this._endDate),this.$lbl.classList.remove("ph");else this.$lbl.textContent=e,this.$lbl.classList.add("ph")}_formatRange(e,t){const i=this._isoToYMD(e),n=this._isoToYMD(t);if(!i||!n)return"";const s=new Date(i.y,i.m,i.d),r=new Date(n.y,n.m,n.d);const a={month:"short",day:"numeric"};const l={month:"short",day:"numeric",year:"numeric"};if(i.y===n.y)return s.toLocaleDateString(void 0,a)+" â "+r.toLocaleDateString(void 0,l);return s.toLocaleDateString(void 0,l)+" â "+r.toLocaleDateString(void 0,l)}_updateHint(){if(!this._startDate)this.$hint.textContent="Click a start date";else if(!this._endDate)this.$hint.textContent="Click an end date";else this.$hint.textContent=this._formatRange(this._startDate,this._endDate)}}var mainMbl="unset";!function(e){const t=e.mbl=e.mbl||{};const i=t.prototype=t.prototype||{};let n=null;let s=null;let r=null;let a=[];let l=[];let o=null;let d=null;function pushCurData(e,t){a.push(e),l.push(t),s=e,r=t}function popCurData(){if(a.length>0)a.pop(),l.pop(),s=a.length>0?a[a.length-1]:null,r=l.length>0?l[l.length-1]:null;else s=null,r=null}const c={pad2:e=>String(e).padStart(2,"0"),isDate:e=>/^\d{4}-\d{2}-\d{2}$/.test((e||"").trim()),isDT:e=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test((e||"").trim()),parseHHMM(e){const t=/^(\d{1,2}):([0-5]\d)$/.exec((e||"").trim());if(!t)return null;const i=+t[1],n=+t[2];if(i>23)return null;return 60*i+n},fmtHHMM:e=>(e=Math.max(0,Math.min(e,24*60-1)),`${c.pad2(Math.floor(e/60))}:${c.pad2(e%60)}`),fmtHHMM12(e){e=Math.max(0,Math.min(e,24*60-1));let t=Math.floor(e/60),i=e%60;const n=t>=12?"PM":"AM";let s=t%12;if(0===s)s=12;return`${s}:${c.pad2(i)} ${n}`},stepMins:e=>Math.max(1,Math.round(+e||1)),_expandYY(e,t=1970){e=+e;const i=t%100,n=Math.floor(t/100);return e>=i?100*(n-1)+e:100*n+e},toISODateMaybe2D(e,t=1970){if(!(e=(e||"").trim()))return"";if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let i=/^(\d{2})-(\d{2})-(\d{2})$/.exec(e);if(i){const e=c._expandYY(i[1],t),n=+i[2],s=+i[3];if(n>=1&&n<=12&&s>=1&&s<=31)return`${e}-${c.pad2(n)}-${c.pad2(s)}`;return""}if(i=/^(\d{1,2}
1)[\/-](\d{1,2})[\/-](\d{2})$/.exec(e),i){const e=+i[1],n=+i[2],s=c._expandYY(i[3],t);if(e>=1&&e<=12&&n>=1&&n<=31)return`${s}-${c.pad2(e)}-${c.pad2(n)}`;return""}return""},ensureHidden(e){if(e._hidden)return;const t=document.createElement("input");if(t.type="hidden",t.name=e.getAttribute("name")||e.id||"",e.id)t.id=e.id+"-hidden";e.insertAdjacentElement("beforebegin",t),e._hidden=t},updateHidden(e,t){if(!e._hidden)return;if(e._hidden.name=e.getAttribute("name")||e.id||"",e.id&&!e._hidden.id)e._hidden.id=e.id+"-hidden";e._hidden.disabled=e.hasAttribute("disabled"),e._hidden.value=t||""},wireExternalLabel(e,t){const i=e.id;if(!i)return;const n=document.querySelector(`label[for="${CSS.escape(i)}"]`);if(!n)return;if(!n.id)n.id=`lbl-${i}`;t.setAttribute("aria-labelledby",n.id),n.addEventListener("click",e=>{e.preventDefault(),t.focus()})},syncAria(e,t){const i=(e.getAttribute("aria-describedby")||"").trim(),n=(e.getAttribute("aria-errormessage")||"").trim(),s=(e.getAttribute("aria-label")||"").trim();if(i)t.setAttribute("aria-describedby",i);else t.removeAttribute("aria-describedby");if(n)t.setAttribute("aria-errormessage",n);else t.removeAttribute("aria-errormessage");if(s)t.setAttribute("aria-label",s);else t.removeAttribute("aria-label")}};e.DateTimeUtils=c;const u={debounce(e,t){let i;return function executedFunction(...n){const later=()=>{clearTimeout(i);try{e(...n)}catch(e){console.error("Debounced function error:",e)}};clearTimeout(i),i=setTimeout(later,t)}},throttle(e,t){let i;return function executedFunction(...n){if(!i){try{e.apply(this,n)}catch(e){console.error("Throttled function error:",e)}i=true,setTimeout(()=>i=false,t)}}},batchDOMOperations(e){const t=document.createDocumentFragment();const i=[];try{e.forEach(e=>{const n=e(t);i.push(n)})}catch(e){console.error("Batch DOM operations failed:",e)}return{fragment:t,results:i}},eventCleanup:new WeakMap,addCleanableEvent(e,t,i){try{if(!e)return;if(e.addEventListener(t,i),!this.eventCleanup.has(e))this.eventCleanup.set(e,[]);this.eventCleanup.get(e).push({type:t,handler:i})}catch(e){console.error("Failed to add event listener:",e)}},cleanupEvents(e){if(!e)return;const t=this.eventCleanup.get(e);if(t)t.forEach(({type:t,handler:i})=>{try{e.removeEventListener(t,i)}catch(e){console.error("Failed to remove event listener:",e)}}),this.eventCleanup.delete(e)},measurePerformance(e,t){const i=performance.now();try{const n=t();const s=performance.now();if(s-i>100)console.log(`Performance: ${e} took ${(s-i).toFixed(2)}ms`);return n}catch(t){throw console.error(`Performance measurement failed for ${e}:`,t),t}},withErrorBoundary:(e,t="Unknown")=>(...i)=>{try{return e(...i)}catch(e){return console.error(`Error in ${t}:`,e),null}}};const f={getNestedValue(e,t){if(!e||!t)return;if("string"!=typeof t)return e[t];if(!t.includes("."))return e[t];const i=t.split(".");let n=e;for(const e of i){if(null==n||"object"!=typeof n)return;n=n[e]}return n},setNestedValue(e,t,i){if(!e||!t)return e;if("string"!=typeof t)return e[t]=i,e;if(!t.includes("."))return e[t]=i,e;const n=t.split(".");let s=e;for(let e=0;e<n.length-1;e++){const t=n[e];if(null==s[t]||"object"!=typeof s[t])s[t]={};s=s[t]}const r=undefined;return s[n[n.length-1]]=i,e},hasNestedProperty(e,t){if(!e||!t)return false;if("string"!=typeof t)return e.hasOwnProperty(t);if(!t.includes("."))return e.hasOwnProperty(t);const i=t.split(".");let n=e;for(const e of i){if(null==n||"object"!=typeof n||!n.hasOwnProperty(e))return false;n=n[e]}return true}};if(!customElements.get("x-time"))customElements.define("x-time",XTime);if(!customElements.get("x-date"))customElements.define("x-date",XDate);if(!customElements.get("x-datetime-wrap"))customElements.define("x-datetime-wrap",XDateTimeWrap);if(!customElements.get("x-date-range"))customElements.define("x-date-range",XDateRange);if(!customElements.get("mbl-rich-text"))customElements.define("mbl-rich-text",MBLRichText);const h={patterns:new Map([["alpha",/^[A-Za-z]+$/],["alpha+space",/^[A-Za-z ]+$/],["alphanumeric",/^[A-Za-z0-9]+$/],["alphanumeric+space",/^[A-Za-z0-9 ]+$/],["alphaspecial",/^[A-Za-z\-'.&_]+$/],["alphaspecial+space",/^[A-Za-z\-'.&_ ]+$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["phone",/^[\+]?[1-9][\d]{0,15}$/],["url",/^https?:\/\/.+/]]),validate(e,t){if(!t||null==e)return true;try{const i=this.patterns.get(String(t).toLowerCase());return i?i.test(String(e)):true}catch(e){return console.error("Validation error:",e),false}}
1,getErrorMessage(e,t="field"){const i=undefined;return{alpha:`${t} must contain only letters`,"alpha+space":`${t} must contain only letters and spaces`,alphanumeric:`${t} must contain only letters and numbers`,"alphanumeric+space":`${t} must contain only letters, numbers, and spaces`,alphaspecial:`${t} must contain only letters and common punctuation`,"alphaspecial+space":`${t} must contain only letters, spaces, and common punctuation`,email:"Please enter a valid email address",phone:"Please enter a valid phone number",url:"Please enter a valid URL (must start with http:// or https://)"}[e]||`${t} contains invalid characters`},validateFields(e){const t=[];return e.forEach(({value:e,rule:i,fieldName:n})=>{const s=this.validate(e,i);t.push({fieldName:n,isValid:s,errorMessage:s?null:this.getErrorMessage(i,n)})}),t}};const p={defaults:{debounceTime:300,virtualScrollThreshold:1e3,maxRetries:3,timeout:3e4,batchSize:100},get(e,t=null){return this.defaults[e]??t},set(e,t){if("object"==typeof e)Object.assign(this.defaults,e);else this.defaults[e]=t},validate(e){const t=[];if(e.timeout&&("number"!=typeof e.timeout||e.timeout<0))t.push("timeout must be a positive number");if(e.debounceTime&&("number"!=typeof e.debounceTime||e.debounceTime<0))t.push("debounceTime must be a positive number");return t}};function showWaiting(e="Processing",t=0){if(o)clearTimeout(o),o=null;if(d&&"none"!==d.style.display&&document.body.contains(d)){const t=d.querySelector(".dt-wait-text");if(t)t.textContent=e+"...";return}const showNow=()=>{if(!d){d=document.createElement("div"),d.id="dt-wait-overlay",d.className="dt-wait-overlay",d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-live","polite"),d.tabIndex=-1;const t=document.createElement("div");t.className="dt-wait-box";const i=document.createElement("div");i.className="dt-wait-spinner",i.setAttribute("aria-hidden","true");const n=document.createElement("div");n.className="dt-wait-text",n.setAttribute("aria-live","polite"),n.textContent=e+"...",t.appendChild(i),t.appendChild(n),d.appendChild(t),document.body.appendChild(d)}else{const t=d.querySelector(".dt-wait-text");if(t)t.textContent=e+"..."}d.style.display="flex";const t=document.activeElement;if(t)t.setAttribute("data-previously-focused","true");d.focus()};if(t&&t>0)o=setTimeout(()=>{o=null,showNow()},Math.round(1e3*t));else showNow()}function renderFieldOptionsUI(e){if(!e.classList.contains("dt-field-options"))return;const t=e._fieldOptionsData||[];const i=e.closest(".dt-form-field");const n=i?.querySelector("label")?.textContent||"Options";if(e.innerHTML="",!e._liveRegion)e._liveRegion=document.createElement("div"),e._liveRegion.setAttribute("aria-live","polite"),e._liveRegion.setAttribute("aria-atomic","false"),e._liveRegion.className="dt-sr-only",e.appendChild(e._liveRegion);const s=document.createElement("div");s.className="dt-field-options-container",s.setAttribute("role","group"),s.setAttribute("aria-label",`${n} management`),s.setAttribute("aria-describedby",`${e.id}-instructions`),t.forEach((t,i)=>{const n=document.createElement("div");if(n.className="dt-field-option",n.dataset.optionIndex=i,n.setAttribute("role","group"),n.setAttribute("aria-label",`Option ${i+1}`),t.deleted)n.classList.add("dt-deleted"),n.setAttribute("aria-label",`Option ${i+1} (deleted)`);const r=`${e.id}-value-${i}`;const a=`${e.id}-option-${i}`;const l=document.createElement("input");if(l.type="text",l.id=r,l.value=t.fieldValue,l.placeholder="Value",l.className="dt-field-value-input",l.setAttribute("aria-describedby",`${r}-desc`),l.setAttribute("aria-required","true"),t.deleted)l.setAttribute("aria-disabled","true"),l.disabled=true;const o=document.createElement("input");if(o.type="text",o.id=a,o.value=t.fieldOption,o.placeholder="Display Text",o.className="dt-field-option-input",o.setAttribute("aria-describedby",`${a}-desc`),o.setAttribute("aria-required","true"),t.deleted)o.setAttribute("aria-disabled","true"),o.disabled=true;const d=document.createElement("label");if(d.textContent="Value",d.className="dt-value-label",d.setAttribute("for",r),i>0)d.classList.add("dt-sr-only");const c=document.createElement("label");if(c.textContent="Display Text",c.className="dt-option-label",c.setAttribute("for",a),i>0)c.classList.add("dt-sr-only");const u=document.createElement("span");u.id=`${r}-desc`,u.className="dt-sr-only",u.textContent=`Value for option ${i+1}, required`;const f=document.createElement("span");if(f.id=`${a}-desc`,f.className="dt-sr-only",f.textContent=`Value for option ${i+1}, required`,n.appendChild(c),n.appendChild(o),n.appendChild(u),n.appendChild(d),n.appendChild(l),n.appendChild(f),!t.inUse){const s=document.createElement("span");s.id=`${e.id}-toggle-desc-${i}`,s.className="dt-sr-only";const r=t.deleted;const a=r?"undo":"x";const l=r?"Restore option":"Delete option";const o=r?`Restore option ${i+1}`:`Delete option ${i+1}`;s.textContent=r?`Restore option ${i+1} to active state`:`Delete option ${i+1}`;const d=undefined;const c=createButton(null,null,`/ic?i=${a}
1&m=tr`,()=>{t.deleted=!t.deleted;const n=t.deleted?"deleted":"restored";e._liveRegion.textContent=`Option ${i+1} ${n}`,renderFieldOptionsUI(e),updateFieldOptionsValue(e),e.dispatchEvent(new Event("input",{bubbles:true}))},["dt-btn","dt-toggle-option-btn",r?"dt-restore-option-btn":null],[{name:"title",value:l},{name:"aria-label",value:o},{name:"aria-describedby",value:s.id}]);n.appendChild(s),n.appendChild(c)}l.addEventListener("blur",()=>{const i=t.fieldValue;t.fieldValue=l.value;const n=!t.fieldOption&&l.value;if(!t.fieldOption&&l.value)t.fieldOption=l.value,o.value=l.value;if(!l.value.trim())l.setCustomValidity("Value is required"),l.reportValidity();else l.setCustomValidity("");if(n)e._fieldOptionsData.sort((e,t)=>e.fieldOption.localeCompare(t.fieldOption,void 0,{sensitivity:"base",numeric:true})),renderFieldOptionsUI(e);updateFieldOptionsValue(e),e.dispatchEvent(new Event("input",{bubbles:true}))}),o.addEventListener("blur",()=>{const i=t.fieldOption;if(t.fieldOption=o.value,!o.value.trim())o.setCustomValidity("Display Text is required"),o.reportValidity();else o.setCustomValidity("");if(i!==o.value)e._fieldOptionsData.sort((e,t)=>e.fieldOption.localeCompare(t.fieldOption,void 0,{sensitivity:"base",numeric:true})),renderFieldOptionsUI(e);updateFieldOptionsValue(e),e.dispatchEvent(new Event("input",{bubbles:true}))}),o.addEventListener("input",()=>{if(o.value.trim())o.setCustomValidity("")}),l.addEventListener("input",()=>{if(l.value.trim())l.setCustomValidity("")}),s.appendChild(n)});const r=document.createElement("div");r.id=`${e.id}-instructions`,r.className="dt-sr-only",r.textContent="Manage options by filling in display text and values. Use delete buttons to remove options, or add new options with the add button.";const a=document.createElement("span");a.id=`${e.id}-add-desc`,a.className="dt-sr-only",a.textContent="Add a new option with empty value and display text fields";const onAddActivate=()=>{const t={fieldOption:"",fieldValue:"",inUse:false,deleted:false};e._fieldOptionsData.push(t),e._liveRegion.textContent=`New option added. Option ${e._fieldOptionsData.length}`,renderFieldOptionsUI(e);const i=e.querySelector(".dt-field-options-container");const n=i?.lastElementChild;const s=n?.querySelector(".dt-field-option-input");if(s)setTimeout(()=>{s.focus(),s.select()},10);e.dispatchEvent(new Event("input",{bubbles:true}))};const l=createButton(null,"Add Option","/ic?i=plus&m=tr",onAddActivate,["dt-btn","dt-add-option-btn"],[{name:"title",value:"Add new option"},{name:"aria-label",value:"Add new option"},{name:"aria-describedby",value:a.id}]);e.appendChild(r),e.appendChild(s),e.appendChild(a),e.appendChild(l)}function updateFieldOptionsValue(e){if(!e.classList.contains("dt-field-options"))return;const t=undefined;const i=(e._fieldOptionsData||[]).filter(e=>{if(e.deleted)return false;return e.fieldOption&&""!==e.fieldOption.trim()&&e.fieldValue&&""!==e.fieldValue.trim()});const n=JSON.stringify(i);e.setAttribute("value",n),e.dataset.fieldOptionsValue=n}function renderFileControlUI(e){if(!e.classList.contains("dt-file-control"))return;const t=e._fileData||[];const i=e.closest(".dt-form-field");const n=i?.querySelector("label")?.textContent||"Files";const s=e.classList.contains("dt-image-control");const r=undefined;const a=undefined;const l=e.getAttribute("data-accepts")||(s?".png,.jpg,.jpeg,.gif,.svg":"*");const o="true"===e.getAttribute("data-multiple");if(e.innerHTML="",!e._liveRegion)e._liveRegion=document.createElement("div"),e._liveRegion.setAttribute("aria-live","polite"),e._liveRegion.setAttribute("aria-atomic","false"),e._liveRegion.className="dt-sr-only",e.appendChild(e._liveRegion);let d=document.getElementById(e.id+"-hp");if(!d)d=document.createElement("input"),d.type="file",d.id=e.id+"-hp",d.style.display="none",d.setAttribute("aria-hidden","true"),e.appendChild(d);if(e._hiddenInput=d,d.accept=l,d.multiple=o,!d._mblBound)d.addEventListener("change",t=>{const i=Array.from(t.target.files||[]);if(i.length>0){i.forEach(t=>{const i={fileName:t.name,fileUrl:"",fileSize:t.size,fileType:t.type,deleted:false,_tempFile:t};e._fileData.push(i)}),e.classList.add("dirty"),e.classList.add("filedirty"),e.classList.add("datadirty"),_updateFormDirtyState(e);const t=1===i.length?"file":"files";e._liveRegion.textContent=`${i.length} ${t} selected`,renderFileControlUI(e),updateFileControlValue(e),e.dispatchEvent(new Event("input",{bubbles:true}))}t.target.value=""}),d._mblBound=true;const c=document.createElement("div");c.className="dt-file-control-container",c.setAttribute("role","group"),c.setAttribute("aria-label",`${n} management`);const u=document.createElement("div");u.className="dt-file-preview",t.forEach((t,i)=>{if(t.deleted)return;const n=document.createElement("div");
1n.className="dt-file-item",n.dataset.fileIndex=i;const r=document.createElement("div");if(r.className="dt-file-preview-item",r.style.maxHeight="60px",r.style.maxWidth="100px",r.style.display="inline-block",r.style.marginRight="8px",s&&(t.fileUrl||t._tempFile)){const e=document.createElement("img");if(e.style.maxHeight="60px",e.style.maxWidth="100px",e.style.objectFit="contain",e.alt=t.fileName,t._tempFile){const i=URL.createObjectURL(t._tempFile);e.src=i,e.onload=()=>URL.revokeObjectURL(i)}else if(t.fileUrl)e.src=t.fileUrl;r.appendChild(e)}else{const e=document.createElement("img");e.src="/ic?i=doc&m=tr",e.alt="",e.width=48,e.height=48,r.appendChild(e)}const a=document.createElement("div");a.className="dt-file-info",a.style.display="inline-block",a.style.verticalAlign="top",a.style.marginLeft="8px";const l=document.createElement("div");l.className="dt-file-name",l.textContent=t.fileName,l.style.fontWeight="bold",l.style.marginBottom="4px";const o=document.createElement("div");if(o.className="dt-file-size",o.style.fontSize="0.9em",o.style.color="#666",t.fileSize>0){const e=Math.round(t.fileSize/1024);const i=(t.fileSize/(1024*1024)).toFixed(1);o.textContent=e<1024?`${e} KB`:`${i} MB`}a.appendChild(l),a.appendChild(o);const d=createButton(null,null,"/ic?i=x&m=tr",()=>{t.deleted=true;try{e.classList.add("dirty"),e.classList.add("datadirty"),_updateFormDirtyState(e)}catch(e){}e._liveRegion.textContent=`${t.fileName} removed`,renderFileControlUI(e),updateFileControlValue(e),e.dispatchEvent(new Event("input",{bubbles:true}))},["dt-btn","dt-remove-file-btn"],[{name:"title",value:`Remove ${t.fileName}`},{name:"aria-label",value:`Remove ${t.fileName}`}]);d.style.marginLeft="8px",n.appendChild(r),n.appendChild(a),n.appendChild(d),u.appendChild(n)});const f=createButton(null,`Choose ${o?"":"a "}${s?"image":"file"}${o?"s":""}`,"/ic?i=folder-open&m=tr",()=>{const t=document.getElementById(e.id+"-hp");if(t)t.click()},["dt-btn","dt-upload-btn"],[{name:"title",value:`Choose ${o?"":"a "}${s?"image":"file"}${o?"s":""}`},{name:"aria-label",value:`Choose ${o?"":"a "}${s?"image":"file"}${o?"s":""}`}]);c.appendChild(u),c.appendChild(f),e.appendChild(c)}function updateFileControlValue(e){if(!e.classList.contains("dt-file-control"))return;const t=undefined;const i=(e._fileData||[]).filter(e=>!e.deleted);const n=JSON.stringify(i);e.setAttribute("value",n),e.dataset.fileValue=n}function updateInputControl(e,t,i=void 0,n=void 0,s=false){const r=getElement(e);if(!r)return console.warn("updateInputControl: element not found for",e),null;if(true===s&&r.classList.contains("dt-fielddata")&&(!Array.isArray(n)||0===n.length)&&null!=t)if(r.classList.contains("dt-multi-select")||"true"===r.getAttribute("data-mtp"))try{let e;if(Array.isArray(t))e=t;else if("string"==typeof t)try{const i=JSON.parse(t);e=Array.isArray(i)?i:[i]}catch{e=[t]}else if("object"==typeof t&&null!==t)e=[t];else e=[t];r.setAttribute("data-pending",JSON.stringify(e))}catch(e){console.warn("Failed to set pending value, using empty array:",e),r.setAttribute("data-pending","[]")}else if(""!==String(t)){const e="object"==typeof t&&t?t.fieldValue??t.newValue??"":String(t);r.setAttribute("data-pending",String(e))}const a=n&&true===n.forceDirty;const ensureWrap=e=>{let t=e.closest&&e.closest(".dt-form-field");if(!t)if(t=document.createElement("div"),t.id=e.id?`${e.id}-ctrl`:"",t.className="dt-form-field",e.parentNode)e.parentNode.insertBefore(t,e),t.appendChild(e);return t};const l=ensureWrap(r);const normalizeOpts=e=>{if(!Array.isArray(e))return[];return e.map(e=>({value:String(e.fieldValue??e.value??""),label:String(e.fieldOption??e.label??"")}))};const coerceMulti=(e,t)=>{const i=new Set(t.map(e=>e.value));const n=new Map(t.map(e=>[e.label,e.value]));let s=[];let r=[];if(null==e)s=[];else if(Array.isArray(e))if(e.length&&"object"==typeof e[0]&&null!=e[0])e.forEach(e=>{const t=String(e.fieldValue??e.value??"");const n=String(e.fieldOption??e.label??"");if(t){if(s.push(t),!i.has(t)&&n)r.push(n)}else if(n)r.push(n)});else s=e.map(e=>String(e));else if("string"==typeof e){const t=e.trim();let n=null;if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{n=JSON.parse(t)}catch{n=null}if(Array.isArray(n))if(n.length&&"object"==typeof n[0]&&null!=n[0])n.forEach(e
1=>{const t=String(e.fieldValue??e.value??"");const n=String(e.fieldOption??e.label??"");if(t){if(s.push(t),!i.has(t)&&n)r.push(n)}else if(n)r.push(n)});else s=n.map(e=>String(e));else if(i.has(t))s=[t]}else{const t=String(e);if(i.has(t))s=[t]}let a=s.filter(e=>i.has(e));if(r.length)r.forEach(e=>{const t=n.get(e);if(t&&!a.includes(t))a.push(t)});return Array.from(new Set(a))};const applyMulti=(e,t,i)=>{const n=normalizeOpts(i);e._multiOptions=n;const s=Array.isArray(e._multiSelected)?e._multiSelected.slice():[];const r=coerceMulti(t,n);e._multiSelected=r,e.dataset.selectedValues=JSON.stringify(r);const a=new Map(n.map(e=>[e.value,e.label]));const o=r.map(e=>({fieldOption:a.get(e)??e,fieldValue:e}));const d=JSON.stringify(o);e.setAttribute("value",d),e.dataset.valueJson=d;let c=l.querySelector(".dt-multi-selected");if(!c)c=document.createElement("div"),c.className="dt-multi-selected dt-filter-summary",c.setAttribute("role","list"),l.appendChild(c);else if(!c.hasAttribute("role"))c.setAttribute("role","list");c.style.order="5";const u=new Map(Array.from(c.children).map(e=>[e.getAttribute("data-value"),e]));if(u.forEach((e,t)=>{if(!r.includes(t))e.remove()}),r.forEach(t=>{if(u.has(t))return;const i=document.createElement("span");i.className="dt-filter-chip",i.setAttribute("role","listitem"),i.setAttribute("data-value",t);const s=document.createElement("span");s.textContent=a.get(t)??t;const announceRemoval=()=>announceSelectionChange(e,`Removed ${s.textContent}`);const r=undefined;const l=createButton(null,null,"/ic?i=x&m=tr",()=>{const i=(e._multiSelected||[]).filter(e=>e!==t);applyMulti(e,i,e._multiOptions||n),e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true})),announceRemoval()},[],[{name:"title",value:"Remove"},{name:"aria-label",value:`Remove ${s.textContent}`}]);i.appendChild(s),i.appendChild(l),c.appendChild(i)}),r.forEach(t=>{if(!s.includes(t))announceSelectionChange(e,`Added ${a.get(t)??t}`)}),s.length!==r.length)announceSelectionChange(e,`${r.length} selected`);if("select"===e.tagName.toLowerCase()){const t=n.filter(e=>!r.includes(e.value));const i=new Set(t.map(e=>e.value));Array.from(e.options).forEach(e=>{if(!i.has(e.value))e.remove()});const s=new Set(Array.from(e.options).map(e=>e.value));if(t.forEach(t=>{if(!s.has(t.value)){const i=document.createElement("option");i.value=t.value,i.textContent=t.label,e.appendChild(i)}}),e.selectedIndex=-1,"function"==typeof e._applyFieldFilter)try{e._applyFieldFilter()}catch(e){}}};let o=false;if(Array.isArray(i)&&i.length>0){const e=r.classList.contains("dt-segment-control");const n=r.classList.contains("dt-multi-select");if("select"===r.tagName.toLowerCase()&&!n){if(r.innerHTML="",i.forEach(e=>{const t=document.createElement("option");t.value=String(e.fieldValue??e.value??""),t.textContent=String(e.fieldOption??e.label??""),r.appendChild(t)}),null!=t){const e=String(t);if(Array.from(r.options).some(t=>String(t.value)===e))r.value=e}if("function"==typeof r._applyFieldFilter)try{r._applyFieldFilter()}catch(e){}}else if(n){if(void 0!==t)applyMulti(r,t,i),o=true;else{r._multiOptions=normalizeOpts(i);const e=r._multiSelected||[];applyMulti(r,e,i),o=true}if("function"==typeof r._applyFieldFilter)try{r._applyFieldFilter()}catch(e){}if(r.classList.contains("dt-fielddata")&&"true"===r.getAttribute("data-atp")){const e=r.closest&&r.closest(".dt-form-field");if(e){const t=e.querySelector(`#${CSS.escape(r.id)}-fd-filter`);if(t)t.value=""}}}else if(e){r.innerHTML="";const e=undefined;normalizeOpts(i).forEach(e=>{const onActivate=()=>{r.setAttribute("data-segment-value",e.value),r.querySelectorAll(".dt-segment-btn").forEach(t=>{const i=t.getAttribute("data-value")===e.value;t.classList.toggle("dt-segment-selected",i),t.setAttribute("aria-checked",String(i))}),r.dispatchEvent(new Event("input",{bubbles:true})),r.dispatchEvent(new Event("change",{bubbles:true}))};const t=createButton(null,e.label,null,onActivate,["dt-segment-btn"],[{name:"role",value:"radio"},{name:"data-value",value:e.value}]);r.appendChild(t)}),r._segmentButtons=r.querySelectorAll(".dt-segment-btn")}else if(r.classList.contains("dt-field-options"))r._fieldOptionsTemplate=i}if(void 0!==t){if(r.classList.contains("dt-content"))r.innerHTML=String(t||"");else if(r.classList.contains("dt-list-control")){let e=[];
1if("string"==typeof t&&t.trim())try{e=JSON.parse(t)}catch{e=[]}else if(Array.isArray(t))e=t;else if(t&&"object"==typeof t)e=[t];e=Array.isArray(e)?e.map(e=>"object"==typeof e&&e?e:{value:e}):[],r._listData=e;const i=JSON.stringify(e);r.setAttribute("value",i),r.dataset.listValue=i;const n=r._listConfig||{};n.data=e;const s=createTable(r.id+"-div",n);r.appendChild(s)}else if(r.classList.contains("dt-switch")){const e=true===t||"true"===String(t);r.checked=e,r.setAttribute("data-switch-value",e?"true":"false")}else if(r.tagName&&["X-DATE","X-TIME","X-DATETIME-WRAP","X-DATE-RANGE"].includes(r.tagName)){let e=t;if("X-DATE-RANGE"===r.tagName&&null!==e&&"object"==typeof e)e=JSON.stringify({start:String(e.start||""),end:String(e.end||"")});const i=null==e?"":String(e);try{r.value=i}catch(e){}if(""===i)r.removeAttribute("value");else r.setAttribute("value",i)}else if("mbl-rich-text"===r.tagName.toLowerCase()){const e=null==t?"<p></p>":String(t);try{r.value=e}catch(t){r.setAttribute("value",e)}}else if(r.classList.contains("dt-segment-control")){const e=String(t??"");r.setAttribute("data-segment-value",e),r.querySelectorAll(".dt-segment-btn").forEach(t=>{const i=t.getAttribute("data-value")===e;t.classList.toggle("dt-segment-selected",i),t.setAttribute("aria-checked",String(i))})}else if(r.classList.contains("dt-multi-select")){if(!o){const e=Array.isArray(i)?i:r._multiOptions||[];if(Array.isArray(t)&&t.length&&"object"==typeof t[0])r._multiOriginalObjects=t.map(e=>({fieldOption:e.fieldOption??e.label??e.text??e.fieldValue??e.value??"",fieldValue:e.fieldValue??e.value??e.id??""}));else if(t&&"object"==typeof t)r._multiOriginalObjects=[{fieldOption:t.fieldOption??t.label??t.text??t.fieldValue??t.value??"",fieldValue:t.fieldValue??t.value??t.id??""}];else if(!Array.isArray(t))r._multiOriginalObjects=void 0;let n;if(Array.isArray(t))n=t.map(e=>e&&"object"==typeof e?e.fieldValue??e.value??e.id??"":e).filter(
1Boolean);else if(t&&"object"==typeof t)n=[t.fieldValue??t.value??t.id??""];else if(false===Array.isArray(t))n=null==t||""===t?[]:[String(t)];applyMulti(r,n,e)}}else if(r.classList.contains("dt-field-options")){const applyFieldOptions=(e,t)=>{let i=[];if("string"==typeof t&&t.trim())try{i=JSON.parse(t)}catch{i=[]}else if(Array.isArray(t))i=t;i=i.map(e=>({fieldOption:String(e?.fieldOption||""),fieldValue:String(e?.fieldValue||""),inUse:Boolean(e?.inUse),deleted:Boolean(e?.deleted)})),i.sort((e,t)=>e.fieldOption.localeCompare(t.fieldOption,void 0,{sensitivity:"base",numeric:true})),e._fieldOptionsData=i;const n=JSON.stringify(i);e.setAttribute("value",n),e.dataset.fieldOptionsValue=n,renderFieldOptionsUI(e)};applyFieldOptions(r,t)}else if(r.classList.contains("dt-file-control")){const applyFileControl=(e,t)=>{let i=[];if("string"==typeof t&&t.trim())try{i=JSON.parse(t)}catch{i=[]}else if(Array.isArray(t))i=t;i=i.map(e=>({fileName:String(e?.fileName||""),fileUrl:String(e?.fileUrl||""),fileSize:Number(e?.fileSize)||0,fileType:String(e?.fileType||""),deleted:Boolean(e?.deleted)})),e._fileData=i;const n=JSON.stringify(i);e.setAttribute("value",n),e.dataset.fileValue=n,renderFileControlUI(e)};applyFileControl(r,t)}else if("select"===r.tagName.toLowerCase()){if(r.value=t,r.classList.contains("dt-fielddata")&&"true"===r.getAttribute("data-atp")&&!r.classList.contains("dt-multi-select")){const e=r.closest&&r.closest(".dt-form-field");if(e){const t=e.querySelector(`#${CSS.escape(r.id)}-fd-filter`);if(t){const e=r.options[r.selectedIndex]||null;const i=e?String(e.textContent||""):"";t.value=i}}}}else if("textarea"===r.tagName.toLowerCase()||"input"===r.tagName.toLowerCase())r.value=String(t??"");else r.setAttribute("data-value",String(t??""));if(!a&&void 0!==r._originalCanonicalValue)r._originalCanonicalValue=_canonicalControlValue(r);if(a)try{if(r.classList.add("dirty"),r.classList.contains("dt-file-control"))r.classList.add("filedirty"),r.classList.add("datadirty");else r.classList.add("datadirty");_updateFormDirtyState(r)}catch(e){}if(!r._suppressEvents&&!r.classList.contains("dt-content")&&a)r.dispatchEvent(new Event("input",{bubbles:true})),r.dispatchEvent(new Event("change",{bubbles:true}))}return l}function _canonicalControlValue(e){try{if(!e)return"";if(e.classList&&e.classList.contains("dt-switch"))return e.checked?true:false;if(e.classList&&e.classList.contains("dt-segment-control"))return String(e.getAttribute("data-segment-value")||"");if(e.classList&&e.classList.contains("dt-multi-select")){const t=Array.isArray(e._multiSelected)?e._multiSelected.slice():[];return t.sort(),JSON.stringify(t)}if(e.classList&&e.classList.contains("dt-list-control")){const t=Array.isArray(e._listData)?e._listData.filter(e=>!(e&&("Y"===e.deleted||true===e.deleted))):[];return JSON.stringify(t)}if(e.classList&&e.classList.contains("dt-field-options")){const t=Array.isArray(e._fieldOptionsData)?e._fieldOptionsData.filter(e=>e&&!e.deleted).map(e=>({fieldValue:String(e.fieldValue||""),fieldOption:String(e.fieldOption||""),inUse:!!e.inUse})):[];return t.sort((e,t)=>(e.fieldValue||"").localeCompare(t.fieldValue||"")),JSON.stringify(t)}if(e.classList&&e.classList.contains("dt-file-control")){const t=Array.isArray(e._fileData)?e._fileData.filter(e=>e&&!e.deleted):[];return t.sort((e,t)=>String(e.fileName||"").localeCompare(String(t.fileName||""))),JSON.stringify(t)}if(e.tagName&&["X-DATE","X-TIME","X-DATETIME-WRAP","X-DATE-RANGE"].includes(e.tagName)){const t=void 0!==e.value&&null!==e.value&&String(e.value).length?e.value:e.getAttribute("value")||"";return String(t)}if("mbl-rich-text"===e.tagName.toLowerCase())try{return String(e.value||"<p></p>")}catch(t){return String(e.getAttribute("value")||"<p></p>")}if("undefined"!=typeof e.value)return String(e.value??"");return String(e.getAttribute("data-value")||"")}catch(e){return""}}function _setElementEnabled(e,t){try{if(!e)return;if(t)e.disabled=false,e.classList.remove("disabled");else e.disabled=true,e.classList.add("disabled")}catch(e){}}function _updateFormDirtyState(e){try{const t=e.closest(".dt-form");if(!t)return;const i=validateForm(t);const n=i.isDirty;const s=!i.isComplete;if(n)t.classList.add("dirty");else t.classList.remove("dirty");if(s)t.classList.add("invalid");else t.classList.remove("invalid");_updateSaveButtonState(t,n,s)}catch(e){}}function _updateSaveButtonState(e,t,i){try{const n=e.querySelector(".dt-form-buttons");if(!n)return;const s=n.querySelector("button.dt-btn-save");if(!s)return;const r=undefined;_setElementEnabled(s,t&&!i)}catch(e){}}function _attachDirtyTracking(e){try{if(!e||e.classList&&e.classList.contains("dt-content"))return;const attachListeners=()=>{e._originalCanonicalValue=_canonicalControlValue(e);const mark=()=>
1{if(e._suppressEvents)return;const t=undefined;const i=undefined;if(_canonicalControlValue(e)!==e._originalCanonicalValue)if(e.classList.add("dirty"),e.classList.contains("dt-file-control"))e.classList.add("filedirty");else e.classList.add("datadirty");else e.classList.remove("dirty"),e.classList.remove("datadirty"),e.classList.remove("filedirty");_updateFormDirtyState(e)};if(e._dirtyHandler){try{e.removeEventListener("input",e._dirtyHandler)}catch(e){}try{e.removeEventListener("change",e._dirtyHandler)}catch(e){}}e._dirtyHandler=()=>mark(),e.addEventListener("input",e._dirtyHandler),e.addEventListener("change",e._dirtyHandler)};if(e.tagName&&"mbl-rich-text"===e.tagName.toLowerCase())if(e.isConnected&&e._surface)attachListeners();else{const t=new MutationObserver(i=>{if(e.isConnected&&e._surface)t.disconnect(),attachListeners()});t.observe(e,{childList:true,subtree:true}),setTimeout(()=>{if(!e._dirtyHandler&&e.isConnected)t.disconnect(),attachListeners()},100)}else attachListeners()}catch(e){}}function hideWaiting(){if(o)clearTimeout(o),o=null;if(d){d.style.display="none";const e=document.querySelector("[data-previously-focused]");if(e)e.focus(),e.removeAttribute("data-previously-focused")}}function getElement(e,t){try{return"string"==typeof e?!t?document.getElementById(e):t.querySelector("#"+CSS.escape(e)):e instanceof Element?e:null}catch(e){return console.error("getElement error:",e),null}}function getNearest(e,t){if(!e||"string"!=typeof t||!t)return null;try{if("function"==typeof e.closest)return e.closest(t);let i=e;while(i){if(i.matches&&i.matches(t))return i;if(i=i.parentElement||i.parentNode,i&&1!==i.nodeType)i=i.parentElement}return null}catch(e){return console.error("getNearest error:",e),null}}function createButton(e,t,i,n,s=[],r=[],a=false){return u.withErrorBoundary(()=>{const l=!(null==t||""===t);const o=!!i;if(!l&&!o||"function"!=typeof n)return console.warn("createButton: Missing required parameters"),null;let d=null;if(e&&"string"==typeof e)d=getElement(e);if(!d)if(d=document.createElement("button"),e&&!d.id)d.id=e;if(d.tagName&&"button"===d.tagName.toLowerCase())d.type="button";if(d.innerHTML="",Array.isArray(s))s.forEach(e=>{if(e&&"string"==typeof e)d.classList.add(e)});if(d.classList.toggle("noLabel",!l),d.classList.toggle("noIcon",!o),o){const e=document.createElement("img");if(e.alt="",e.src=i,e.onerror=()=>console.warn(`Failed to load icon: ${i}`),!(d.classList.contains("dt-sort-btn")||d.classList.contains("dt-filter-btn")))e.className="dt-btn-icon";d.appendChild(e)}if(l){const e=document.createElement("span");e.textContent=t,d.appendChild(e)}if(Array.isArray(r))r.forEach(e=>{if(e&&null!=e.name)d.setAttribute(e.name,String(e.value??""))});_setElementEnabled(d,!a),u.cleanupEvents(d);const c=u.withErrorBoundary(n,"button activation");const f=500;return u.addCleanableEvent(d,"pointerup",e=>{if(0!==e.button)return;const t=Date.now();if(d._lastActivated&&t-d._lastActivated<f)return;d._lastActivated=t,c(e)}),u.addCleanableEvent(d,"keydown",e=>{if("Enter"===e.key||" "===e.key){e.preventDefault();const t=Date.now();if(d._lastActivated&&t-d._lastActivated<f)return;d._lastActivated=t,c(e)}}),d},"createButton")()}function attachFieldDataBehaviors(e,t){if(!e||!t)return;const i="true"===e.getAttribute("data-atp");const n=undefined;if("true"===e.getAttribute("data-mtp")){if(!e.classList.contains("dt-multi-select"))e.classList.add("dt-multi-select");if(e._multiChangeHandler)e.removeEventListener("change",e._multiChangeHandler);e._multiChangeHandler=()=>{const t=Array.from(e.selectedOptions).map(e=>e.value);const i=Array.from(new Set([...e._multiSelected||[],...t]));e._suppressEvents=true,updateInputControl(e,i,e._multiOptions),e._suppressEvents=false,e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true}))},e.addEventListener("change",e._multiChangeHandler)}if(i){const i=`${e.id}-fd-filter`;const n=`${e.id}-fd-list`;let s=t.querySelector(`#${CSS.escape(i)}`);if(!s){s=document.createElement("input"),s.type="text",s.id=i,s.className="dt-fielddata-filter",s.setAttribute("placeholder","Type to search..."),s.setAttribute("autocomplete","off");const n=[];
1const r=t.querySelector(`label[for="${CSS.escape(e.id)}"]`);if(r){if(!r.id)r.id=`${e.id}-label`;n.push(r.id)}const a=t.querySelector(".dt-field-info");if(a){if(!a.id)a.id=`${e.id}-info`;s.setAttribute("aria-describedby",a.id)}if(n.length)s.setAttribute("aria-labelledby",n.join(" "));if(e.hasAttribute("required"))s.setAttribute("aria-required","true");if(r&&r.parentNode===t)t.insertBefore(s,r.nextSibling);else if(e.parentNode===t)t.insertBefore(s,e);else t.appendChild(s)}let r=t.querySelector(`#${CSS.escape(n)}`);if(!r)if(r=document.createElement("datalist"),r.id=n,s.nextSibling)s.parentNode.insertBefore(r,s.nextSibling);else s.parentNode.appendChild(r);s.setAttribute("list",n);const syncDatalist=()=>{if(!r)return;r.innerHTML="";const t=new Set;Array.from(e.options).forEach(e=>{const i=String(e.textContent||"").trim();const n=String(e.value||"").trim();const s=`${i}::${n}`;if(t.has(s))return;t.add(s);const a=document.createElement("option");a.innerHTML=i,a.setAttribute("fieldvalue",n),r.appendChild(a)})};e._applyFieldFilter=syncDatalist,syncDatalist();const chooseFromInput=()=>{const t=(s.value||"").trim();if(!t)return;const i=Array.from(e.options);let n=i.find(e=>(e.textContent||"").trim()===t)||i.find(e=>(e.value||"").trim()===t);if(!n){const e=t.toLowerCase();n=i.find(t=>(t.textContent||"").toLowerCase().includes(e))||i.find(t=>(t.value||"").toLowerCase().includes(e))}if(n){if(e.classList.contains("dt-multi-select")){const t=Array.from(new Set([...e._multiSelected||[],n.value]));e._suppressEvents=true,updateInputControl(e,t,e._multiOptions),e._suppressEvents=false,e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true}))}else e.value=n.value,e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true}));s.value="",syncDatalist()}};if(!s._fdBound)s.addEventListener("keydown",e=>{if("Enter"===e.key)e.preventDefault(),chooseFromInput()}),s.addEventListener("change",()=>{chooseFromInput()}),s._fdBound=true;if(!e.hasAttribute("data-atp-hidden"))e.setAttribute("data-atp-hidden","true"),e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e.style.display="none";const syncAriaDesc=()=>{const i=t.querySelector(".dt-field-error");const n=t.querySelector(".dt-field-info");const r=[];if(i){if(!i.id)i.id=`${e.id}-error`;r.push(i.id)}if(n)r.push(n.id||`${e.id}-info`);if(r.length)s.setAttribute("aria-describedby",r.join(" "));else s.removeAttribute("aria-describedby")};e._syncFieldFilterAria=syncAriaDesc,syncAriaDesc()}}function createInputControl(e,t,i={},n=null){const s=e instanceof Element?e:null;if(s)e=s.id||"";const mapValidator=e=>{const t=h.patterns.get(String(e||"").toLowerCase());return t?t.source:""};if(i&&i.dataCol&&i.dataCol.length>3){const t=i.dataCol.replace(/\./g,"_");if(!e||false===e.endsWith("-"+t)){if(!e)e="";else if(e.length>0)e+="-";e+=t}}const r=(e=>{const t=String(e||"text").toLowerCase();switch(t){case"content":return{tag:"div",type:null,isContent:true};case"list":return{tag:"div",type:null,isList:true};case"date":return{tag:"x-date",type:null,isCustom:true,customKind:"date"};case"time":return{tag:"x-time",type:null,isCustom:true,customKind:"time"};case"datetime":case"datetime-local":case"date-time":case"datetime-wrap":return{tag:"x-datetime-wrap",type:null,isCustom:true,customKind:"datetime"};case"date-range":return{tag:"x-date-range",type:null,isCustom:true,customKind:"daterange"};case"select":return{tag:"select",type:null};case"fielddata":return{tag:"select",type:null,isFieldData:true};case"textarea":return{tag:"textarea",type:null};case"richtext":return{tag:"mbl-rich-text",type:null,isRichText:true,isCustom:true};case"switch":return{tag:"input",type:"checkbox",isSwitch:true};case"segment":return{tag:"div",type:null,isSegment:true};case"multi-select":return{tag:"select",type:null,isMultiSelect:true};case"fieldoptions":return{tag:"div",type:null,isFieldOptions:true};case"file":return{tag:"div",type:null,isFile:true};case"image":return{tag:"div",type:null,isImage:true};default:return{tag:"input",type:t}}})(i?.type);const a="string"==typeof i.timeStart?i.timeStart:null;const l="string"==typeof i.timeEnd?i.timeEnd:null;const computeWidth=e=>
1{const t={cls:null,style:null};const i=Number(e);if(!isNaN(i))if(i>=1&&i<=5)t.cls="dt-width-"+i;else if(i>25&&i<=100)t.cls="dt-width-pct"+i,t.style=i+"%";else if(i>100)t.cls="dt-width-px"+i,t.style=i+"px";return t};const applyAttrs=(e,t)=>{if(Array.isArray(t))t.forEach(t=>{if(t&&null!=t.name)e.setAttribute(t.name,String(t.value??""))})};const ensureWrapper=e=>{let t=e.closest(".dt-form-field");if(!t)t=document.createElement("div"),t.id=e.id?`${e.id}-ctrl`:"",t.className="dt-form-field",e.parentNode?.insertBefore(t,e),t.appendChild(e);return t};const validateField=(t,n)=>{let s;let r;if(t.classList.contains("dt-multi-select")){const e=Array.isArray(t._multiSelected)?[...t._multiSelected]:[];r=e,s=i?.required?Array.isArray(e)&&e.length>0:true}else if(t.classList.contains("dt-list-control")){const e=Array.isArray(t._listData)?t._listData:[];r=e,s=i?.required?Array.isArray(e)&&e.length>0:true}else if(t.classList.contains("dt-field-options")){const e=t._fieldOptionsData||[];if(r=e,i?.required){const t=undefined;s=e.filter(e=>e&&!e.deleted&&e.fieldOption&&""!==e.fieldOption.trim()&&e.fieldValue&&""!==e.fieldValue.trim()).length>0}else s=true}else if(t.classList.contains("dt-file-control")){const e=t._fileData||[];if(r=e,i?.required){const t=undefined;s=e.filter(e=>e&&!e.deleted).length>0}else s=true}else if("function"==typeof t._checkStatus){const e=undefined;s=t._checkStatus().isValid}else if(t.tagName&&["X-DATE","X-TIME","X-DATETIME-WRAP","X-DATE-RANGE"].includes(t.tagName)){const e=void 0!==t.value&&null!==t.value?String(t.value):"";s=i?.required?e.length>0:true}else if("function"==typeof t.checkValidity)s=t.checkValidity();else s=i?.required?null!=t.value&&String(t.value).length>0:true;if(t.classList.contains("dt-switch"))r=t.checked?true:false;else if(t.classList.contains("dt-segment-control"))r=t.getAttribute("data-segment-value")||"";else r=t.value;const a=i?.validator&&!t.classList.contains("dt-multi-select")&&!t.classList.contains("dt-field-options")&&!t.classList.contains("dt-file-control")?h.validate(r,i.validator):true;const l=s&&a;n.classList.toggle("dt-invalid",!l),_updateFormDirtyState(t);let o=n.querySelector(".dt-field-error");if(!l){if(!o)o=document.createElement("div"),o.className="dt-field-error",o.setAttribute("role","alert"),o.setAttribute("aria-live","polite"),n.appendChild(o);if(t.classList.contains("dt-multi-select")&&i?.required&&(!Array.isArray(r)||0===r.length))o.textContent="Please select at least one option";else if(t.classList.contains("dt-list-control")&&i?.required)o.textContent="Please add at least one item";else if(t.classList.contains("dt-field-options")&&i?.required)o.textContent="Please add at least one option";else if(t.classList.contains("dt-file-control")&&i?.required)o.textContent="Please upload at least one file";else o.textContent=i?.validator?h.getErrorMessage(i.validator):"The field is required.";if(t.setAttribute("aria-describedby",o.id=`${e}-error`),t._syncFieldFilterAria)t._syncFieldFilterAria()}else if(o)if(o.remove(),t.removeAttribute("aria-describedby"),t._syncFieldFilterAria)t._syncFieldFilterAria();return l};const setSwitchValue=(e,t)=>{if(r.isSwitch){let i="false";if(true===t||"true"===t)i="true";else if(false===t||"false"===t)i="false";else if(null==t||void 0===t)i="false";else i="true"===String(t)?"true":"false";return e.checked="true"===i,e.setAttribute("data-switch-value",i),i}return t};const getSwitchValue=e=>{if(r.isSwitch)return e.checked?true:false;return e.value};const setSegmentValue=(e,t,n)=>{if(r.isSegment&&Array.isArray(n)){let s=t;if((null==t||void 0===t)&&i?.required&&n.length>0)s=n[0].fieldValue??n[0].value??"";const r=e.getAttribute("data-segment-value");if(String(r)===String(s))return s;if(!e._segmentButtons)e._segmentButtons=e.querySelectorAll(".dt-segment-btn");return e._segmentButtons.forEach(e=>{const t=e.getAttribute("data-value");const i=String(t)===String(s);e.classList.toggle("dt-segment-selected",i),e.setAttribute("aria-checked",String(i))}),e.setAttribute("data-segment-value",String(s)),s}return t};const getSegmentValue=e=>{if(r.isSegment)return e.getAttribute("data-segment-value")||"";return e.value};if(e||s){const a=s||getElement(e);
1if(a){let s=a;const l=ensureWrapper(a);if(i&&Object.keys(i).length){const t=r;if("input"===t.tag&&"input"!==s.tagName.toLowerCase()||"input"!==t.tag&&s.tagName.toLowerCase()!==t.tag){const n=document.createElement(t.tag);if(n.id=e,t.type)n.type=t.type;if(t.isSwitch)l.classList.add("dt-switch-field"),n.classList.add("dt-switch"),n.addEventListener("change",()=>{n.setAttribute("data-switch-value",n.checked?"true":"false")});if(t.isSegment)l.classList.add("dt-segment-field"),n.classList.add("dt-segment-control"),n.setAttribute("role","radiogroup"),n.setAttribute("tabindex","0"),n.addEventListener("keydown",e=>{const t=n.querySelectorAll(".dt-segment-btn");const i=Array.from(t).findIndex(e=>e.classList.contains("dt-segment-selected"));let s=i;if("ArrowLeft"===e.key||"ArrowUp"===e.key)e.preventDefault(),s=i>0?i-1:t.length-1;else if("ArrowRight"===e.key||"ArrowDown"===e.key)e.preventDefault(),s=i<t.length-1?i+1:0;if(s!==i&&t[s])t[s].click(),t[s].focus()});if(t.isContent)l.classList.add("dt-content-field"),n.classList.add("dt-content"),n.setAttribute("role","presentation"),n.setAttribute("data-form-exclude","true");if(t.isList)l.classList.add("dt-list-field"),n.classList.add("dt-list-control");if(t.isFieldData){n.classList.add("dt-fielddata");const e=i.opt&&"object"==typeof i.opt?i.opt:i.opts;if(e&&"object"==typeof e){if("string"==typeof e.tn)n.setAttribute("data-tableName",e.tn);if("string"==typeof e.fn)n.setAttribute("data-fieldName",e.fn);if(true===e.atp)n.setAttribute("data-atp",e.atp);if(true===e.mtp)n.setAttribute("data-mtp",e.mtp)}attachFieldDataBehaviors(n,l)}l.replaceChild(n,s),s=n}else{if("input"===t.tag&&t.type)s.setAttribute("type",t.type);if(t.isSwitch)l.classList.add("dt-switch-field"),s.classList.add("dt-switch"),s.removeEventListener("change",s._switchChangeHandler),s._switchChangeHandler=()=>{s.setAttribute("data-switch-value",s.checked?"true":"false")},s.addEventListener("change",s._switchChangeHandler);else if(l.classList.remove("dt-switch-field"),s.classList.remove("dt-switch"),s._switchChangeHandler)s.removeEventListener("change",s._switchChangeHandler),delete s._switchChangeHandler;if(t.isList)l.classList.add("dt-list-field"),s.classList.add("dt-list-control");else l.classList.remove("dt-list-field"),s.classList.remove("dt-list-control");if(t.isContent)l.classList.add("dt-content-field"),s.classList.add("dt-content"),s.setAttribute("role","presentation"),s.setAttribute("data-form-exclude","true");else l.classList.remove("dt-content-field"),s.classList.remove("dt-content"),s.removeAttribute("data-form-exclude");if(t.isSegment){if(l.classList.add("dt-segment-field"),s.classList.add("dt-segment-control"),s.setAttribute("role","radiogroup"),s.setAttribute("tabindex","0"),s._segmentKeyHandler)s.removeEventListener("keydown",s._segmentKeyHandler);s._segmentKeyHandler=e=>{const t=s.querySelectorAll(".dt-segment-btn");const i=Array.from(t).findIndex(e=>e.classList.contains("dt-segment-selected"));let n=i;if("ArrowLeft"===e.key||"ArrowUp"===e.key)e.preventDefault(),n=i>0?i-1:t.length-1;else if("ArrowRight"===e.key||"ArrowDown"===e.key)e.preventDefault(),n=i<t.length-1?i+1:0;if(n!==i&&t[n])t[n].click(),t[n].focus()},s.addEventListener("keydown",s._segmentKeyHandler)}else{if(l.classList.remove("dt-segment-field"),s.classList.remove("dt-segment-control"),s._segmentKeyHandler)s.removeEventListener("keydown",s._segmentKeyHandler),delete s._segmentKeyHandler;if(s._segmentButtons)delete s._segmentButtons}if(t.isMultiSelect){if(s.classList.add("dt-multi-select"),s._multiChangeHandler)s.removeEventListener("change",s._multiChangeHandler);s._multiChangeHandler=()=>{const e=Array.from(s.selectedOptions).map(e=>e.value);const t=Array.from(new Set([...s._multiSelected||[],...e]));s._suppressEvents=true,updateInputControl(s,t,s._multiOptions||(n&&Array.isArray(n)?n:i?.opts)),s._suppressEvents=false,s.dispatchEvent(new Event("input",{bubbles:true}))},s.addEventListener("change",s._multiChangeHandler);{const e=Array.isArray(s._multiSelected)?s._multiSelected:[];s._suppressEvents=true,updateInputControl(s,e,s._multiOptions||(n&&Array.isArray(n)?n:i?.opts)),s._suppressEvents=false}}else{if(s.classList.remove("dt-multi-select"),s._multiChangeHandler)s.removeEventListener("change",s._multiChangeHandler),delete s._multiChangeHandler;delete s._multiSelected,delete s._multiOptions;const e=undefined;const t=ensureWrapper(s).querySelector(".dt-multi-selected");if(t)t.remove()}if(t.isFieldOptions){if(s.classList.add("dt-field-options"),!s._fieldOptionsData)s._fieldOptionsData=[]}else s.classList.remove("dt-field-options"),delete s._fieldOptionsData;if(t.isFile){if(s.classList.add("dt-file-control"),!s._fileData)s._fileData=[]}else s.classList.remove("dt-file-control"),delete s._fileData;if(t.isImage){if(s.classList.add("dt-file-control","dt-image-control"),!s._fileData)s._fileData=[]}else if(s.classList.remove("dt-image-control"),!t.isFile)s.classList.remove("dt-file-control"),delete s._fileData;if(t.isFieldData){if(s.classList.add("dt-fielddata"),i.opt&&"object"==typeof i.opt){if("string"==typeof i.opt.tn)s.setAttribute("data-tableName",i.opt.tn);if("string"==typeof i.opt.fn)s.setAttribute("data-fieldName",i.opt.fn);if(true===i.opt.atp)s.setAttribute("data-atp",i.opt.atp);if(true===i.opt.mtp)s.setAttribute("data-mtp",i.opt.mtp)}attachFieldDataBehaviors(s,l)}else s.classList.remove("dt-fielddata"),s.removeAttribute("data-tableName"),s.removeAttribute("data-fieldName"),s.removeAttribute("data-atp"),s.removeAttribute("data-mtp")}if(!t.isContent){if(i.required)s.setAttribute("required",""),s.setAttribute("aria-required","true");else s.removeAttribute("required"),s.removeAttribute("aria-required");if(t.isCustom){if(null!=i.min)s.setAttribute("min",String(i.min));else s.removeAttribute("min");
1if(null!=i.max)s.setAttribute("max",String(i.max));else s.removeAttribute("max");if(null!=i.step)s.setAttribute("step",String(i.step));else s.removeAttribute("step");if(null!=i.displayFormat&&("time"===t.customKind||"datetime"===t.customKind))s.setAttribute("displayFormat",String(i.displayFormat));else if("time"===t.customKind||"datetime"===t.customKind)s.removeAttribute("displayFormat")}else{if(!(null==i.min||0===Number(i.min)||"select"===t.tag||t.isSegment||t.isMultiSelect||t.isFieldOptions||t.isFieldData||t.isFile||t.isImage))s.setAttribute("min",String(i.min));else s.removeAttribute("min");if(!(null==i.max||0===Number(i.max)||"select"===t.tag||t.isSegment||t.isMultiSelect||t.isFieldOptions||t.isFieldData||t.isFile||t.isImage))s.setAttribute("max",String(i.max));else s.removeAttribute("max")}const e=mapValidator(i.validator);if(e&&!t.isSwitch&&!t.isSegment&&!t.isMultiSelect&&!t.isFieldOptions&&!t.isFieldData&&!t.isCustom&&!t.isFile&&!t.isImage&&!t.isList)s.setAttribute("pattern",e);else s.removeAttribute("pattern");if(t.isRichText)s.addEventListener("change",()=>{validateField(s,l)});else s.onblur=()=>{validateField(s,l)};if(i.validator&&!t.isSwitch&&!t.isSegment&&!t.isMultiSelect&&!t.isFieldOptions&&!t.isFieldData&&!t.isCustom&&!t.isFile&&!t.isImage&&!t.isList){const e=u.debounce(()=>validateField(s,l),500);s.oninput=e}}else s.removeAttribute("required"),s.removeAttribute("aria-required"),s.removeAttribute("min"),s.removeAttribute("max"),s.removeAttribute("pattern"),s.onblur=null,s.oninput=null;applyAttrs(s,i.attr);let a=l.querySelector('label[for="'+e+'"]');if(!a)a=document.createElement("label"),a.setAttribute("for",e),l.insertBefore(a,l.firstChild);if(null!=i.label)a.textContent=String(i.label);const o=a.querySelector(".dt-required-indicator");if(i.required&&!t.isContent){if(!o){const e=document.createElement("span");e.className="dt-required-indicator",e.textContent="*",a.appendChild(e)}}else if(o)o.remove();let d=l.querySelector(".dt-field-info");if(!d)d=document.createElement("div"),d.className="dt-field-info",l.appendChild(d);if(d.textContent=i.info?String(i.info):"",n&&Array.isArray(n)||Array.isArray(i.opts))if(t.isMultiSelect){if(s.classList.add("dt-multi-select"),s._multiChangeHandler)s.removeEventListener("change",s._multiChangeHandler);s._multiChangeHandler=()=>{const t=Array.from(s.selectedOptions).map(e=>e.value);const i=Array.from(new Set([...s._multiSelected||[],...t]));s._suppressEvents=true,updateInputControl(e,i),s._suppressEvents=false,s.dispatchEvent(new Event("input",{bubbles:true}))},s.addEventListener("change",s._multiChangeHandler)}}const o=computeWidth(i?.width);if(Array.from(l.classList).filter(e=>e.startsWith("dt-width-")).forEach(e=>l.classList.remove(e)),o.cls)l.classList.add(o.cls);if(o.style)l.style.width=o.style;else l.style.removeProperty("width");if(i?.eventType&&"function"==typeof i?.eventCB){if(s._fieldEventCB&&s._fieldEventType)s.removeEventListener(s._fieldEventType,s._fieldEventCB);s._fieldEventType=i.eventType,s._fieldEventCB=i.eventCB,s.addEventListener(i.eventType,i.eventCB)}const d=n&&Array.isArray(n)?n:i?.opts;if(!s.closest(".dt-form-field")){const t=document.createElement("div");t.className="dt-form-field",t.id=e?`${e}-ctrl`:"",s.parentNode&&s.parentNode.insertBefore(t,s),t.appendChild(s)}return s._suppressEvents=true,updateInputControl(s,void 0!==t?t:void 0,d),s._suppressEvents=false,void _attachDirtyTracking(s)}}const o=document.createElement("div");o.className="dt-form-field",o.id=e?`${e}-ctrl`:"";const d=undefined;const c=computeWidth(null!=(i&&i.width)?i.width:null);if(c.cls)o.classList.add(c.cls);if(c.style)o.style.width=c.style;const f=document.createElement("label");if(f.setAttribute("for",e),!f.id)f.id=`${e}-label`;if(f.textContent=i?.label?String(i.label):"",i?.required&&!r.isContent){const e=document.createElement("span");e.className="dt-required-indicator",e.textContent="*",f.appendChild(e)}let p;if(o.appendChild(f),"select"===r.tag)p=document.createElement("select");else if("textarea"===r.tag)p=document.createElement("textarea");else if(r.isSegment||r.isFieldOptions||r.isContent||r.isFile||r.isImage||r.isList)p=document.createElement("div");else if(r.isCustom)p=document.createElement(r.tag);else if(p=document.createElement("input"),r.type)p.type=r.type;if(p.id=e,r.isSwitch)o.classList.add("dt-switch-field"),p.classList.add("dt-switch"),p.addEventListener("change",()=>{p.setAttribute("data-switch-value",p.checked?"true":"false")});if(r.isMultiSelect)p.classList.add("dt-multi-select");if(r.isFieldOptions)p.classList.add("dt-field-options"),p._fieldOptionsData=[],p.addEventListener("focusout",e=>{setTimeout(()=>{if(!p.contains(document.activeElement))validateField(p,o)},0)});if(r.isFile)p.classList.add("dt-file-control"),p._fileData=[],p.addEventListener("focusout",e=>{setTimeout(()=>{if(!p.contains(document.activeElement))validateField(p,o)},0)});if(r.isImage)p.classList.add("dt-file-control","dt-image-control"),p._fileData=[],p.addEventListener("focusout",e=>{setTimeout(()=>{if(!p.contains(document.activeElement))validateField(p,o)},0)});if(r.isList)p.classList.add("dt-list-control"),p.addEventListener("focusout",()=>{setTimeout(()=>{if(!p.contains(document.activeElement))validateField(p,o)},0)});if(r.isContent)o.classList.add("dt-content-field"),p.classList.add("dt-content"),p.setAttribute("role","presentation"),p.setAttribute("data-form-exclude","true");if(r.isFieldData){p.classList.add("dt-fielddata");const e=i?.opt&&"object"==typeof i.opt?i.opt:i?.opts;if(e&&"object"==typeof e){if("string"==typeof e.tn)p.setAttribute("data-tableName",e.tn);if("string"==typeof e.fn)p.setAttribute("data-fieldName",e.fn);if(true===e.atp)p.setAttribute("data-atp",e.atp);if(true===e.mtp)p.setAttribute("data-mtp",e.mtp)}attachFieldDataBehaviors(p,o)}if(r.isSegment)o.classList.add("dt-segment-field"),p.classList.add("dt-segment-control"),p.setAttribute("role","radiogroup"),p.setAttribute("tabindex","0"),p.addEventListener("keydown",e=>{if(!p._segmentButtons)p._segmentButtons=p.querySelectorAll(".dt-segment-btn");const t=p._segmentButtons;const i=Array.from(t).findIndex(e=>e.classList.contains("dt-segment-selected"));let n=i;if("ArrowLeft"===e.key||"ArrowUp"===e.key)e.preventDefault(),n=i>0?i-1:t.length-1;else if("ArrowRight"===e.key||"ArrowDown"===e.key)e.preventDefault(),n=i<t.length-1?i+1:0;if(n!==i&&t[n])t[n].click(),t[n].focus()});if(!r.isContent){if(i?.required)p.setAttribute("required",""),p.setAttribute("aria-required","true");if(r.isCustom){if(i&&null!=i.min)p.setAttribute("min",String(i.min));
1if(i&&null!=i.max)p.setAttribute("max",String(i.max));if(i&&null!=i.step)p.setAttribute("step",String(i.step));if(i&&null!=i.displayFormat&&("time"===r.customKind||"datetime"===r.customKind))p.setAttribute("displayFormat",String(i.displayFormat));if("time"===r.customKind||"datetime"===r.customKind){if(null!=a)p.setAttribute("timeStart",a);else p.removeAttribute("timeStart");if(null!=l)p.setAttribute("timeEnd",l);else p.removeAttribute("timeEnd")}}else{if(i&&null!=i.min&&0!==Number(i.min)&&"select"!==r.tag&&!r.isSegment&&!r.isMultiSelect&&!r.isFieldOptions&&!r.isFieldData&&!r.isFile&&!r.isImage)p.setAttribute("min",String(i.min));if(i&&null!=i.max&&0!==Number(i.max)&&"select"!==r.tag&&!r.isSegment&&!r.isMultiSelect&&!r.isFieldOptions&&!r.isFieldData&&!r.isFile&&!r.isImage)p.setAttribute("max",String(i.max))}const e=mapValidator(i?.validator);if(e&&!r.isSwitch&&!r.isSegment&&!r.isMultiSelect&&!r.isFieldOptions&&!r.isFieldData&&!r.isCustom&&!r.isFile&&!r.isImage&&!r.isList)p.setAttribute("pattern",e)}applyAttrs(p,i?.attr),o.appendChild(p);{const s=n&&Array.isArray(n)?n:i?.opts;if(p._suppressEvents=true,r.isList){if(p._listConfig=Object.assign({},i?.thisConfig||{}),!p._listConfig)p._listConfig={};
1const t=i&&"string"==typeof i.dataCol&&i.dataCol.length?i.dataCol.replace(/\./g,"_"):e||"list";if(!p._listConfig.id)p._listConfig.id=t;p._listGather=function gatherTableData(e,t){try{const t=p._listConfig||{};if(false===Array.isArray(p._listData))p._listData=[];let i=e[t.dataId];let n=false;if(p._listData.forEach(s=>{if(s[t.dataId]===i)n=true,s=Object.assign(s,e)}),false===n)p._listData.push(e);t.data=p._listData;const s=JSON.stringify(p._listData);p.setAttribute("value",s),p.dataset.listValue=s;const r=getElement(p.id+"-div");if(r&&"function"==typeof r._updateTable)r._updateTable(p._listData);if(!p._suppressEvents)p.dispatchEvent(new Event("input",{bubbles:true})),p.dispatchEvent(new Event("change",{bubbles:true}))}catch(e){console.error("gatherTableData error",e)}if("function"==typeof t)t()},p._listConfig.dataSaveCB=p._listGather}if(null!=t&&""!==t&&!("object"==typeof t&&!Object.keys(t).length))updateInputControl(p,t,s,void 0,p.classList.contains("dt-fielddata"));p._suppressEvents=false,_attachDirtyTracking(p)}if(r.isMultiSelect){if(p._multiChangeHandler)p.removeEventListener("change",p._multiChangeHandler);p._multiChangeHandler=()=>{const e=Array.from(p.selectedOptions).map(e=>e.value);const t=Array.from(new Set([...p._multiSelected||[],...e]));p._suppressEvents=true,updateInputControl(p,t),p._suppressEvents=false,p.dispatchEvent(new Event("input",{bubbles:true}))},p.addEventListener("change",p._multiChangeHandler)}if(!r.isContent){if(r.isRichText)p.addEventListener("blur",()=>{validateField(p,o)}),p.addEventListener("change",()=>{validateField(p,o)});else p.onblur=()=>{validateField(p,o)};if(i?.validator&&!r.isSwitch&&!r.isSegment&&!r.isMultiSelect&&!r.isFieldOptions&&!r.isFieldData&&!r.isCustom&&!r.isFile&&!r.isImage&&!r.isList){const e=u.debounce(()=>validateField(p,o),500);p.oninput=e}}if(i?.eventType&&"function"==typeof i?.eventCB)p.addEventListener(i.eventType,i.eventCB);const m=document.createElement("div");return m.className="dt-field-info",m.textContent=i?.info?String(i.info):"",m.id=`${e}-info`,o.appendChild(m),o}function createForm(e,t,i={}){let n=getElement(e,t);let r=false;if(n&&n.tagName)if("form"!==n.tagName.toLowerCase()){const e=document.createElement("form");if(n.id)e.id=n.id;n.replaceWith(e),n=e}else r=true;if(!n)if(n=document.createElement("form"),"string"==typeof e&&e)n.id=e;if(n.classList.add("dt-form"),false===hasClass(n.parentElement,"dt-root")||false===hasClass(t,"dt-root"))n.config=i;if(Array.isArray(i.classList))i.classList.forEach(e=>{if(e)n.classList.add(e)});if(Array.isArray(i.attr))i.attr.forEach(e=>{if(e&&null!=e.name)n.setAttribute(e.name,String(e.value??""))});if(i.eventType&&"function"==typeof i.eventCB)n.addEventListener(i.eventType,i.eventCB);let a=n.querySelector(".dt-form-title");if(null!=i.title&&"dialog"!==i.type){if(!a)a=document.createElement("div"),a.className="dt-title dt-form-title",n.prepend(a);a.textContent=String(i.title)}if(null!=i.description&&"dialog"!==i.type){let e=n.querySelector(".dt-form-desc");if(!e)if(e=document.createElement("p"),e.className="dt-desc dt-form-desc",a&&a.nextSibling)a.after(e);else n.appendChild(e);e.innerHTML=i.description}let l=n.querySelector(".dt-form-fields");if(!l)l=document.createElement("div"),l.className="dt-form-fields",n.appendChild(l);if(Array.isArray(i.fields)&&i.fields.length){l.innerHTML="";let t=[];i.fields.forEach(i=>{if(!i||"object"!=typeof i)return;if("break"===i.type)l.appendChild(document.createElement("br"));else{const n=i.dataCol.replace(/\./g,"_");const r=i.objId||e+"-"+n;const a=null!=i.value?i.value:f.getNestedValue(s,i.dataCol)??"";const o=r?{...i,objId:r}:{...i};t.push({objId:r,defaultValue:i.defaultValue});const d=createInputControl(r,a,o,Array.isArray(i.opts)?i.opts:void 0);if(d)l.appendChild(d)}}),n._fieldsConfig=t,fetchFieldDataControls(n)}if(Array.isArray(i.buttons)&&i.buttons.length){if(true===i.buttonsInline)n.classList.add("dt-form-buttons-inline");let e=n.querySelector(".dt-form-buttons");if(!e)e=document.createElement("div"),e.className="dt-form-buttons",n.appendChild(e);e.innerHTML='<div class="dt-form-actions-left"></div><div class="dt-form-actions-right"></div>';const t=e.querySelector(".dt-form-actions-left");const s=e.querySelector(".dt-form-actions-right");
1if(t)t.innerHTML="";if(s)s.innerHTML="";i.buttons.forEach(e=>{if("save"===e.onActivate)e.onActivate=e=>saveDataRow(e,i);if(!Array.isArray(e.clss))e.clss=[];if(!e.clss.includes("dt-btn"))e.clss.push("dt-btn");const n=createButton(e?.objId,e?.label,e?.iconUrl,e?.onActivate,e?.clss,e?.attr,e?.disabled);if(!n)return;if(e&&"string"==typeof e.align&&"left"===e.align.toLowerCase()&&t)t.appendChild(n);else if(s)s.appendChild(n)})}const o=getElement(t);if(o&&false===r)o.appendChild(n);return n}function processFieldDataResponse(e,t){try{const i=Array.isArray(e)?e:e&&Array.isArray(e.fields)?e.fields:[];if(!Array.isArray(i))return;i.forEach(e=>{if(!(e&&e.fi&&Array.isArray(e.fieldOptions)))return;const i=document.getElementById(e.fi)||(t&&"function"==typeof t.querySelector?t.querySelector("#"+CSS.escape(e.fi)):null);if(!(i&&i.classList&&i.classList.contains("dt-fielddata")))return;const n=i.getAttribute("data-pending");let s;if(i.classList.contains("dt-multi-select"))if(n){try{const e=JSON.parse(n);s=Array.isArray(e)?e:[e]}catch(e){console.error("Failed to parse pending value as JSON:",n,e),s=[]}i.removeAttribute("data-pending")}else if(Array.isArray(i._multiSelected))s=i._multiSelected.slice();else if(i.dataset&&i.dataset.selectedValues)try{s=JSON.parse(i.dataset.selectedValues)}catch{s=[]}else s=[];else{if(s=n?n:i.value,!s&&i.value&&i.value.startsWith("{")&&i.value.endsWith("}"))try{const e=JSON.parse(i.value);s=e.fieldValue??e.value??""}catch{}if(n)i.removeAttribute("data-pending")}updateInputControl(i,s,e.fieldOptions,void 0,false);const r=document.getElementById(e.fi)||(t&&"function"==typeof t.querySelector?t.querySelector("#"+CSS.escape(e.fi)):null);if(r){const t=Array.from(r.options||[]).map(e=>e.value);if(r.classList.contains("dt-multi-select")){const e=Array.isArray(s)?s.map(e=>e&&"object"==typeof e?String(e.fieldValue??e.value??""):String(e??"")):[];
1const i=undefined;if(e.filter(e=>t.includes(e)).length!==e.length);}else if(s&&!t.includes(String(s)))updateInputControl(e.fi,null,e.fieldOptions);else if("true"===r.getAttribute("data-atp")&&!r.classList.contains("dt-multi-select")){const e=r.closest&&r.closest(".dt-form-field");if(e){const t=e.querySelector(`#${CSS.escape(r.id)}-fd-filter`);if(t){const e=r.options[r.selectedIndex]||null;const i=e?String(e.textContent||""):"";t.value=i}}}try{if(!r.classList.contains("dt-multi-select")){const e=undefined;if(!Array.from(r.options||[]).some(e=>""===e.value)){const e=document.createElement("option");if(e.value="",e.textContent="select an option",e.disabled=true,!r.value)e.selected=true;r.insertBefore(e,r.firstChild||null)}else{const e=Array.from(r.options).find(e=>""===e.value);if(e)e.selected=!r.value}}}catch(e){}}})}catch(e){console.error("processFieldDataResponse error:",e)}}function fetchFieldDataControls(e){const t="string"==typeof e?document.getElementById(e):e;if(!t)return void console.warn("fetchFieldDataControls: Form element not found");const i=t.querySelectorAll("select.dt-fielddata");if(0===i.length)return;const n=[];const s=[];if(i.forEach(e=>{const t=e.getAttribute("data-tableName");const i=e.getAttribute("data-fieldName");const r=e.getAttribute("data-atp");const a=e.getAttribute("data-mtp");if(t&&e.id)if("fieldtypes"===t)s.push({fi:e.id,fieldOptions:g});else n.push({fi:e.id,tn:t,fn:i,rid:"",atp:"true"===r?true:false,mtp:"true"===a?true:false})}),s.length)processFieldDataResponse(s,t);if(0===n.length)return;const r={eTenantId:tId,fields:n};fetch("/api/common/GetFieldObj",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}).then(e=>{if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);return e.json()}).then(e=>processFieldDataResponse(e,t)).catch(e=>{console.error("Error fetching field data:",e)})}function processFileControlFields(e){const t="string"==typeof e?document.getElementById(e):e;if(!t)return console.warn("processFileControlFields: Form element not found"),[];const i=t.querySelectorAll(".dt-file-control");const n=[];return i.forEach(e=>{if(!e.id)return;const t=e._fileData||[];const i=undefined;if(t.some(e=>!e.deleted&&e._tempFile)){n.push(e.id),e.classList.add("dirty");let i=document.getElementById(e.id+"-hp");if(!i)i=document.createElement("input"),i.type="file",i.id=e.id+"-hp",i.style.display="none",i.multiple="true"===e.getAttribute("data-multiple"),e.appendChild(i);const s=new DataTransfer;t.forEach(e=>{if(!e.deleted&&e._tempFile)s.items.add(e._tempFile)}),i.files=s.files,updateFileControlValue(e)}}),n}function validateForm(e){const t=getElement(e);if(!t)return{isValid:false,isDirty:false,isComplete:false};const i=Array.isArray(n?.fields)?n.fields:Array.isArray(t?.config?.fields)?t.config.fields:[];const r=t.id||"";const a=r?r+"-":"";let l=true;let o=true;let d=false;let c=[];let u=[];return i.forEach(e=>{if(e.type&&"content"===String(e.type).toLowerCase())return;const i=a+e.dataCol.replace(/\./g,"_");const n=t.querySelector("#"+CSS.escape(i));if(!n)return;let r;let h=false;let p=null;if(n.classList.contains("dt-switch"))r=n.checked?true:false;else if(n.classList.contains("dt-segment-control"))r=n.getAttribute("data-segment-value")||"";else if(n.classList.contains("dt-multi-select"))r=Array.isArray(n._multiSelected)?[...n._multiSelected]:[];else if(n.classList.contains("dt-list-control"))r=Array.isArray(n._listData)?[...n._listData]:[];else if(n.classList.contains("dt-field-options"))r=Array.isArray(n._fieldOptionsData)?[...n._fieldOptionsData]:[];else if(n.tagName&&["X-DATE","X-TIME","X-DATETIME-WRAP"].includes(n.tagName)){const e=void 0!==n.value&&null!==n.value&&String(n.value).length?n.value:n.getAttribute("value")||"";r=String(e)}else if("mbl-rich-text"===n.tagName.toLowerCase())try{p=n._checkStatus(),r=String(n.value||"<p></p>"),h=true}catch(e){r=String(n.value||"<p></p>"),h=false}else r=(n.value??"").toString();let m;let g=true;if(h&&p){if(g=p.isValid,m=p.isComplete,p.isDirty)d=true,c.push(i)}else{if(m=!e.required||(n.classList.contains("dt-multi-select")?Array.isArray(r)&&r.length>0:n.classList.contains("dt-list-control")?Array.isArray(r)&&r.length>0:n.classList.contains("dt-field-options")?Array.isArray(r)&&r.filter(e=>e&&!e.deleted&&e.fieldOption&&""!==e.fieldOption.trim()).length>0:"mbl-rich-text"===n.tagName.toLowerCase()?(()=>{const e=document.createElement("div");e.innerHTML=String(r);const t=undefined;return""!==(e.textContent||e.innerText||"").trim()})():""!==String(r).trim()),"function"==typeof n.checkValidity&&!n.classList.contains("dt-multi-select")&&!n.classList.contains("dt-field-options"))g=n.checkValidity();if("function"==typeof n._checkStatus){const e=n._checkStatus();m=m&&e.isComplete,g=e.isComplete}g=g&&m;const t=s&&e&&e.dataCol?f.getNestedValue(s,e.dataCol)??(n.classList.contains("dt-multi-select")||n.classList.contains("dt-field-options")?[]:""):n.classList.contains("dt-multi-select")||n.classList.contains("dt-field-options")?[]:"";if(n.classList.contains("dt-multi-select")){const toVals=e=>Array.isArray(e)?e.map(e=>e&&"object"==typeof e?String(e.fieldValue??e.value??""):String(e??"")).filter(e=>""!==e).slice().sort():[];const e=toVals(t);const n=toVals(r);if(e.length!==n.length||e.some((e,t)=>e!==n[t]))d=true,c.push(i)}else if(n.classList.contains("dt-list-control")){const norm=e=>Array.isArray(e)?e.filter(e=>!(e&&("Y"===e.deleted||true===e.deleted))):[];const e=norm(t);const n=norm(r);if(JSON.stringify(e)!==JSON.stringify(n))d=true,c.push(i)}else if(n.classList.contains("dt-field-options")){const normalizeOptions=e=>Array.isArray(e)?e.filter(e=>e&&!e.deleted).map(e=>({fieldValue:String(e.fieldValue||""),fieldOption:String(e.fieldOption||""),inUse
1:Boolean(e.inUse)})).sort((e,t)=>e.fieldValue.localeCompare(t.fieldValue)):[];const e=normalizeOptions(t);const n=normalizeOptions(r);if(e.length!==n.length||e.some((e,t)=>e.fieldValue!==n[t].fieldValue||e.fieldOption!==n[t].fieldOption||e.inUse!==n[t].inUse))d=true,c.push(i)}else if(String(t)!==String(r))if(false===n.classList.contains("dt-switch")||n.classList.contains("dt-switch")&&(""!==String(t)||false!==r))d=true,c.push(i)}const b=n.closest(".dt-form-field");if(b)b.classList.toggle("dt-invalid",!g);if(!g)l=false;if(!m)o=false,u.push(i)}),{isValid:l,isDirty:d,isComplete:o,dirtyIds:c,incompleteIds:u}}function resetForm(e,t){const i=getElement(e);if(!i)return null;const n=t?t.fields:Array.isArray(i._fieldsConfig)?i._fieldsConfig:[];if(!n||0===n.length)return;n.forEach(e=>{updateInputControl(e.objId,e.defaultValue)});try{if(i.classList.contains("dt-form"))i.classList.remove("dirty"),i.classList.remove("invalid"),_updateSaveButtonState(i,false,false)}catch(e){}}function closeDialog(e,t=false){let i=e&&"DIALOG"===e.tagName?e:getNearest(e&&e.currentTarget?e.currentTarget:e,"dialog.dt-dialog");const n=true!==t&&e&&("cancel"===e.type||hasClass(e.currentTarget,"dt-btn-close"))&&true===e.isTrusted?true:false;if(!i)return;const s=i.getAttribute&&"false"!==i.getAttribute("data-preserve-body");const r=document.activeElement;if(r&&!i.contains(r))r.setAttribute("data-previously-focused","true");let a=i.querySelector("form.dt-form");if(n&&a){const e=undefined;if(true===validateForm(a).isDirty){let ignoreForm=function(e){closeDialog(e),closeDialog(i,true)};let e;return void msgDialog("Are you sure?","<p>You have unsaved changes.</p>",[{label:"Ignore Changes",onActivate:ignoreForm,align:"left"},{label:"Return to Form",onActivate:closeDialog,align:"right"}])}}const l="function"==typeof i._onClose?i._onClose:"function"==typeof i._onCLose?i._onCLose:null;if(l)try{const e=undefined;if(false===l(i))return}catch(e){console.error("Error in dialog onClose callback:",e)}try{if(!s){let e=i.querySelector("form.dt-form");if(e)u.cleanupEvents(e),e.remove()}else{let e=i.querySelector("form.dt-form");if(e)resetForm(e)}}finally{try{if(i.hasAttribute("open")&&"function"==typeof i.close)i.close();else i.removeAttribute("open")}catch(e){i.removeAttribute("open")}document.body.classList.remove("dt-modal-open"),u.cleanupEvents(i)}}function updateDialog(e,t,i,n,s,r){if(!(e=getElement(e))||"dialog"!==e.tagName.toLowerCase())return null;let a=e.querySelector(".dt-dlg-header");let l=e.querySelector(".dt-dlg-footer");if(null!=t&&a){let e=a.querySelector(".dt-dlg-title");if(e)e.textContent=String(t)}if(Array.isArray(i))i.forEach(t=>{if(t)e.classList.add(t)});if(Array.isArray(n))n.forEach(t=>{if(t&&null!=t.name)e.setAttribute(t.name,String(t.value??""))});if(l&&r){const e=l.querySelector(".dt-dlg-actions-detail");if(e)if(e.innerHTML="","object"==typeof r&&null!==r&&r instanceof Element)e.appendChild(r);else if("string"==typeof r&&r.length>0)e.innerHTML=r}if(l&&s){const e=l.querySelector(".dt-dlg-actions-left");const t=l.querySelector(".dt-dlg-actions-right");if(e)e.innerHTML="";if(t)t.innerHTML="";if(Array.isArray(s))s.forEach(i=>{if(!Array.isArray(i.clss))i.clss=[];if(!i.clss.includes("dt-btn"))i.clss.push("dt-btn");const n=createButton(i?.objId,i?.label,i?.iconUrl,i?.onActivate,i.clss,i?.attr,i?.disabled);if(!n)return;if(i&&"string"==typeof i.align&&"left"===i.align.toLowerCase()&&e)e.appendChild(n);else if(t)t.appendChild(n)})}}function msgDialog(e,t,i){const n="mbl-msg-dialog";if(!i||!Array.isArray(i)||0===i.length)i=[{objId:n+"-ok",label:"OK",iconUrl:null,onActivate:closeDialog,align:"right",clss:["dt-btn"]}];let s=getElement(n);if(s){updateDialog(s,e,void 0,void 0,i);const n=s.querySelector(".dt-dlg-body");if(n)n.innerHTML=t||""}else{s=createDialog({objId:n,parent:document.body,title:e,size:"mini",classList:void 0,attr:[{name:"data-prevent-close",value:"true"}],buttons:i,allowMaximize:false,onOpen:void 0,onClose:void 0});const r=s.querySelector(".dt-dlg-body");if(r)r.innerHTML=t||"";s.addEventListener("cancel",e=>{e.preventDefault()}),s.addEventListener("click",e=>{if(e.target===s)e.preventDefault()})}if(s&&"function"==typeof s.showModal)s.showModal();return s}function createDialog(e={}){const{objId:t,parent:i,title:n,size:s,classList:r,attr:a,buttons:l,allowMaximize:o,onOpen:d,onClose:c}=e;let u=getElement(t);if(u&&(!u.tagName||"dialog"!==u.tagName.toLowerCase())){const e=document.createElement("dialog");if(u.id)e.id=u.id;u.replaceWith(e),u=e}if(!u)if(u=document.createElement("dialog"),u.className="dt-dialog","string"==typeof t&&t)u.id=t;if(u.classList.add("dt-dialog"),["mini","small","medium","large"].forEach(e
1=>u.classList.remove(e)),"string"==typeof s&&["mini","small","medium","large"].includes(s))u.classList.add(s);let f=u.querySelector(".dt-dlg-header");let h=u.querySelector(".dt-dlg-body");let p=u.querySelector(".dt-dlg-footer");if(!f)f=document.createElement("div"),f.className="dt-dlg-header",u.appendChild(f);if(!h)h=document.createElement("div"),h.className="dt-dlg-body",u.appendChild(h);if(!p)p=document.createElement("div"),p.className="dt-dlg-footer",u.appendChild(p);let m=f.querySelector(".dt-dlg-title");if(!m)m=document.createElement("div"),m.className="dt-dlg-title",f.prepend(m);let g=f.querySelector(".dt-dlg-header-actions");if(!g)g=document.createElement("div"),g.className="dt-dlg-header-actions",f.appendChild(g);if(g.innerHTML="",false!==o){const setIcon=()=>u._maxBtnImg&&(u._maxBtnImg.src=u.classList.contains("dt-maximized")?"/ic?i=contract&m=tr":"/ic?i=expand&m=tr");const setAria=e=>{const t=u.classList.contains("dt-maximized");e.setAttribute("aria-pressed",String(t)),e.setAttribute("aria-label",t?"Restore dialog size":"Maximize dialog")};const toggleMax=e=>{if(e&&e.stopPropagation&&e.stopPropagation(),u.classList.toggle("dt-maximized"),setIcon(),u._maxBtn)setAria(u._maxBtn)};const e=createButton(u.id?u.id+"-max":void 0,"","/ic?i=expand&m=tr",toggleMax,["dt-btn","dt-dlg-max-toggle"],[{name:"aria-label",value:"Maximize dialog"},{name:"aria-pressed",value:"false"}]);if(e){const t=e.querySelector("img");u._maxBtnImg=t||null,u._maxBtn=e,setIcon(),setAria(e),g.appendChild(e)}}p.innerHTML="";const b=document.createElement("div");b.className="dt-dlg-actions-left";const y=document.createElement("div");y.className="dt-dlg-actions-right";const v=document.createElement("div");if(v.className="dt-dlg-actions-detail",p.appendChild(v),p.appendChild(b),p.appendChild(y),u.body=h,u.footerDetail=v,updateDialog(u,n,r,a,l,e.footerDetail),!u._bound)u.addEventListener("cancel",e=>{e.preventDefault(),closeDialog(e)}),u._bound=true;if(u.showModal=new Proxy(u.showModal,{apply(e,t,i){document.body.classList.add("dt-modal-open");const n=Reflect.apply(e,t,i);if("function"==typeof d)try{d(u)}catch(e){console.error("Error in dialog onOpen callback:",e)}return n}}),"function"==typeof c)u._onClose=c;const _=getElement(i);if(_&&!u.parentElement)_.appendChild(u);return u}function viewDataRow(e,t,i){let n=null;if(e&&e.currentTarget){const t=getNearest(e.currentTarget,".dt-root");if(t&&t._mblConfig)n=t._mblConfig}let s;editDataRow(e,i,true,n),updateDialog(getNearest(e&&e.currentTarget?e.currentTarget:e,"dialog.dt-dialog"),"View Row")}function editDataRow(e,t,i=false,r=null){let a=r;if(!a&&e&&e.currentTarget){const t=getNearest(e.currentTarget,".dt-root");if(t&&t._mblConfig)a=t._mblConfig}if(!a)a=n;if(!a||!Array.isArray(a.fields)||0===a.fields.length)return;const l=!!(e&&e.currentTarget&&e.currentTarget.classList&&e.currentTarget.classList.contains("dt-tbl-btn"));const o=a.id+"-dlg";const d=a.id+"-form";const c=i?"View Record":"Edit Record";const u=[{objId:o+"-close",label:"Close",iconUrl:null,onActivate:closeDialog,align:"left",clss:["dt-btn-close"]}];if(!i&&false!==t.canDelete)u.push({objId:a.id+"-delete",label:"Delete",iconUrl:null,onActivate:e=>{e.stopPropagation(),deleteDataRow(e,a)},align:"right",clss:["dt-btn-delete"]});if(!i)u.push({objId:o+"-save",label:"Save",iconUrl:null,onActivate:e=>saveDataRow(e,a),align:"right",clss:["dt-btn-save"]});let h=getElement(o);if(!h)h=createDialog({objId:o,parent:document.body,title:c,size:"large",classList:void 0,attr:void 0,buttons:u,allowMaximize:true,onOpen:e=>{const t=e.querySelector('input:not([type="hidden"]), select, textarea, .dt-segment-control');if(t&&!i)setTimeout(()=>t.focus(),100)},onClose:e=>{}});else updateDialog(h,c,void 0,void 0,u);const p=h.querySelector(".dt-dlg-body");if(p){pushCurData(t,l?"table":"form");const e=Array.isArray(a?.fields)?a.fields:[];let n=p.querySelector("#"+CSS.escape(d));if(!n)createForm(d,p,{fields:a.fields}),n=p.querySelector("#"+CSS.escape(d));else e.forEach(e=>{if(!e||!e.dataCol)return;const t=d+"-"+e.dataCol.replace(/\./g,"_");const i=n.querySelector("#"+CSS.escape(t));if(!i)return;const r=s&&e.dataCol?f.getNestedValue(s,e.dataCol):"";try{i._suppressEvents=true,updateInputControl(i,r)}finally{i._suppressEvents=false}_attachDirtyTracking(i),i.classList.remove("dirty","datadirty","filedirty"),i.parentElement.classList.remove("dt-invalid");let a=i.parentElement.querySelector(".dt-field-error");
1if(a)a.remove();i.removeAttribute("aria-describedby"),_updateFormDirtyState(i)});if(n){const e=undefined;(e=>{const t=undefined;n.querySelectorAll("input, select, textarea, .dt-segment-control").forEach(t=>{const i=t.tagName&&"select"===t.tagName.toLowerCase();const n=t.classList&&t.classList.contains("dt-segment-control");if(e){if(i||t.classList?.contains("dt-fielddata"))t.setAttribute("disabled","");else t.setAttribute("readonly","");t.setAttribute("aria-readonly","true")}else{if(t.removeAttribute("readonly"),i||t.classList?.contains("dt-fielddata"))t.removeAttribute("disabled");t.removeAttribute("aria-readonly")}if(n)t.setAttribute("tabindex",e?"-1":"0")});const i=undefined;n.querySelectorAll("mbl-rich-text").forEach(t=>{t.setReadOnly(e)})})(!!i)}}try{h.showModal()}catch(e){h.setAttribute("open","")}}function addDataRow(e){let t=null;if(e&&e.currentTarget){const i=getNearest(e.currentTarget,".dt-root");if(i&&i._mblConfig)t=i._mblConfig}if(!t)t=n;if(!t||!Array.isArray(t.fields))return;const i={};const s=String(t?.idPattern||"count");const r=Array.isArray(t?.data)?t.data:[];let a=null;if(t.dataId)if("DB"===s)a=eid();else if("ticks"===s)a=String(Date.now());else{const e=undefined;const t=[...new Set(r.map(e=>e&&null!=f.getNestedValue(e,idKey)?String(f.getNestedValue(e,idKey)):""))].map(e=>Number(e)).filter(e=>!isNaN(e));a=String(t.length>0?Math.max(...t)+1:1)}if(t.fields.forEach(e=>{const t=e.dataCol;if(!t)return;f.setNestedValue(i,t,void 0!==e.defaultValue?e.defaultValue:null)}),i[t.dataId]=a,i.canDelete=false,i._n=true,editDataRow(e,i,false,t),false!==t.table){let t;updateDialog(getElement(e.currentTarget.id.replace("-tbl-add","-dlg")),"Add Row")}}async function deleteDataRow(e,t=null){s.deleted="Y",await saveDataRow(e,t,true)}async function saveDataRow(e,t=null,i=false){if(e&&"function"==typeof e.preventDefault)e.preventDefault();const r=getNearest(e.currentTarget,"dialog.dt-dialog");const a=r?r.querySelector("form.dt-form"):getNearest(e.currentTarget,".dt-form");if(false===i&&a){const e=validateForm(a);if(!e.isValid||!e.isComplete){const e=a.querySelector(".dt-form-field.dt-invalid input, .dt-form-field.dt-invalid select, .dt-form-field.dt-invalid textarea, .dt-form-field.dt-invalid .dt-segment-control");if(e){e.scrollIntoView({block:"center"});try{if(e.focus(),"function"==typeof e.reportValidity)e.reportValidity()}catch(e){}}return}const t=undefined;if(!(e.isDirty||!!a.querySelector(".dirty"))){if(r)try{closeDialog(r)}catch(e){}try{if("function"==typeof popCurData)popCurData()}catch(e){}return}}const l=t||n;if(!s||"object"!=typeof s){s={};try{pushCurData(s,"form")}catch(e){}}if(l&&Array.isArray(l.fields)){const e=r?l.id+"-form":a&&a.id||l.id||"";if(false===i){let t=null;let i=false;if(l.fields.forEach(n=>{if(n.type&&"content"===String(n.type).toLowerCase())return;const s=n.dataCol.replace(/\./g,"_");const r=[];if(e)r.push(e+"-"+s);if(r.push(s),n.objId)r.push(String(n.objId));let l=null;for(const e of r)if(l=(a?a.querySelector("#"+CSS.escape(e)):null)||getElement(e),l)break;if(!l)return;let o;if(l.classList.contains("dt-switch"))o=l.checked?true:false;else if(l.classList.contains("dt-segment-control"))o=l.getAttribute("data-segment-value")||"";else if(l.classList.contains("dt-multi-select"))o=Array.isArray(l._multiSelected)?[...l._multiSelected]:[];else if(l.classList.contains("dt-field-options"))o=Array.isArray(l._fieldOptionsData)?[...l._fieldOptionsData]:[];else if(l.classList.contains("dt-file-control"))o=Array.isArray(l._fileData)?[...l._fileData]:[];else o=(l.value??"").toString();const d=!n.required||(l.classList.contains("dt-multi-select")?Array.isArray(o)&&o.length>0:l.classList.contains("dt-list-control")?Array.isArray(o)&&o.length>0:l.classList.contains("dt-field-options")?Array.isArray(o)&&o.filter(e=>e&&!e.deleted&&e.fieldOption&&""!==e.fieldOption.trim()).length>0:l.classList.contains("dt-file-control")?Array.isArray(o)&&o.filter(e=>e&&!e.deleted).length>0:l.tagName&&"mbl-rich-text"===l.tagName.toLowerCase()?(()=>{const e=document.createElement("div");e.innerHTML=String(o||"");const t=undefined;return""!==(e.textContent||e.innerText||"").trim()})():""!==String(o).trim());let c=true;if("function"==typeof l.checkValidity&&!l.classList.contains("dt-multi-select")&&!l.classList.contains("dt-field-options")&&!l.classList.contains("dt-file-control"))c=l.checkValidity()&&d;else c=d;if("function"==typeof l._checkStatus){const e=undefined;c=l._checkStatus().isValid&&d}const u=l.closest(".dt-form-field");if(u)u.classList.toggle("dt-invalid",!c);if(!c)if(i=true,!t)t=l}),i){if(t){t.scrollIntoView({block:"center"});try{if(t.focus(),"function"==typeof t.reportValidity)t.reportValidity()}catch(e){}}return}const ensureNestedPath=(e,t)=>{try{if(!e||"string"!=typeof t)return;const i=t.split(".");if(i.length<2)return;let n=e;for(let e=0;e<i.length-1;e++){const t=i[e];if(null==n[t]||"object"!=typeof n[t])n[t]={};n=n[t]}}catch(e){}};const parseNumber=(e,t=false)=>{if(null==e)return null;const i=t?parseInt(String(e).replace(/[,\s]/g,""),10):parseFloat(String(e).replace(/[,\s]/g,""));return Number.isFinite(i)?i:null};l.fields.forEach(t=>{if(t.type&&"content"===String(t.type).toLowerCase())return;const i=String(t.type||"").toLowerCase();const n=t.dataCol.replace(/\./g,"_");const r=[];if(e)r.push(e+"-"+n);if(r.push(n),t.objId)r.push(String(t.objId));let l=null;for(const e of r)if(l=(a?a.querySelector("#"+CSS.escape(e)):null)||getElement(e),l)break;
1if(!l)return;let o;if(l.classList.contains("dt-switch"))o=!!l.checked;else if(l.classList.contains("dt-segment-control"))o=l.getAttribute("data-segment-value")||"";else if(l.classList.contains("dt-multi-select"))o=Array.isArray(l._multiSelected)?[...l._multiSelected]:[];else if(l.classList.contains("dt-list-control")){const e=Array.isArray(l._listData)?l._listData.filter(e=>!(e&&("Y"===e.deleted||true===e.deleted))):[];return ensureNestedPath(s,t.dataCol),void f.setNestedValue(s,t.dataCol,e)}else if(l.classList.contains("dt-field-options"))o=Array.isArray(l._fieldOptionsData)?[...l._fieldOptionsData]:[];else if(l.classList.contains("dt-file-control")){const e=Array.isArray(l._fileData)?l._fileData.filter(e=>!e.deleted):[];return ensureNestedPath(s,t.dataCol),void f.setNestedValue(s,t.dataCol,e)}else if(l.tagName&&["X-DATE","X-TIME","X-DATETIME-WRAP"].includes(l.tagName))o=void 0!==l.value&&null!==l.value&&String(l.value).length?l.value:l.getAttribute("value")||"";else o=l.value;if(l.classList.contains("dt-fielddata")&&("true"===l.getAttribute("data-mtp")||l.classList.contains("dt-multi-select"))){const e=Array.isArray(l._multiSelected)?l._multiSelected:Array.isArray(o)?o:[];const i=Array.isArray(l._multiOptions)?l._multiOptions:[];const n=new Map;if(i&&i.length)i.forEach(e=>n.set(String(e.value),String(e.label)));else if(l&&l.options)Array.from(l.options).forEach(e=>n.set(String(e.value),String(e.text||e.label||e.value)));const r=e.filter(e=>null!=e&&""!==String(e)).map(e=>{const t=String(e);return{fieldValue:t,fieldOption:n.get(t)??t}});return ensureNestedPath(s,t.dataCol),void f.setNestedValue(s,t.dataCol,r)}let d=o;switch(i){case"toggle":case"switch":case"checkbox":d=Boolean(o);break;case"multi-select":d=Array.isArray(o)?o.map(e=>String(e)):[];break;case"number":case"numeric":case"float":case"decimal":case"currency":case"percent":d=parseNumber(o,false);break;case"int":case"integer":d=parseNumber(o,true);break;case"date":case"time":case"datetime":case"datetime-local":d=null==o?"":String(o);break;default:if(Array.isArray(o))d=o.map(e=>String(e));else if(null==o)d="";else d=String(o);break}if(l.classList.contains("dt-switch"))d=Boolean(o);if("string"==typeof t.dataCol&&t.dataCol.includes("."))ensureNestedPath(s,t.dataCol);f.setNestedValue(s,t.dataCol,d)})}let saveCompleted=async function(e){let i="";try{hideWaiting()}catch(e){}if(!Array.isArray(l.data))l.data=[];if(Array.isArray(e)){if("DB"===l.idPattern&&l.dataId){l.data.forEach(t=>{if(null!=t[l.dataId])e.forEach(e=>{if(null!=e[l.dataId]&&t[l.dataId]===e[l.dataId])e._oi=true})});let t=e.filter(e=>true!==e._oi);if(1===t.length)i=t[0][l.dataId]}l.data=[...e]}else{let t=e&&"object"==typeof e?e:null;if(t){if("DB"===l.idPattern&&l.dataId)i=t[l.dataId];if(!Array.isArray(l.data))l.data=[t];else l.data.push(t)}}if("function"==typeof l.dataProcessor)l.dataProcessor();if(false===isNothingOrEmpty(i)&&n&&t.length>0)try{showWaiting("Uploading Files...",2),await processFileFields(t,i)}catch(e){console.error("File upload error:",e)}finally{try{hideWaiting()}catch(e){}}if(popCurData(),r)closeDialog(r);if(false!==l.table){const e=getElement(l.id+"-tbl");if(e){const t=getNearest(e,".dt-root");if(t&&"function"==typeof t._updateTable)t._updateTable(l.data)}}if("function"==typeof l.dataSavedCB)try{l.dataSavedCB()}catch(e){}};const t=a&&false===i?processFileControlFields(a):[];const n="DB"===String(l.idPattern).toUpperCase()&&s._n;if(t.length>0&&!n)try{showWaiting("Uploading Files...",2),await processFileFields(t,s[l.dataId])}catch(e){console.error("Pre-save file upload error:",e)}finally{try{hideWaiting()}catch(e){}}if("function"==typeof l.dataSaveCB)showWaiting("Processing Changes...",2),l.dataSaveCB(s,saveCompleted,e);else try{if(delete s._n,delete s._oi,showWaiting("Processing Changes...",2),!l.saveUrl||""===l.saveUrl)l.saveUrl="/api/public/appdatasave";const e=l.saveUrl+(l.saveUrl.indexOf("?")>0?"&":"?")+"ak="+Date.now()+"&a="+l.appId+"&di="+encodeURIComponent(l.dataId);const t=new URLSearchParams({d:JSON.stringify(s)}).toString();const i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},body:t});if(!i.ok)throw new Error("Save failed: "+i.status);const n=await i.text();const r=undefined;const a=(e=>{try{const t=JSON.parse(e);if("string"==typeof t)try{return JSON.parse(t)}catch{return t}return t}catch{return null}})(n);if(true==a.error)console.log("API error",a.msg||"");saveCompleted(null!==a?a:s)}catch(e){console.error("saveDataRow API error",e),saveCompleted(s)}}}function createTable(e,t,i){const s=1e3;
1const r=40;function addActivate(e,t){u.addCleanableEvent(e,"pointerup",e=>{if(0!==e.button)return;t(e)}),u.addCleanableEvent(e,"keydown",e=>{if("Enter"===e.key||" "===e.key)e.preventDefault(),t(e)})}const a=!!i;if(!i){const n=getElement(e);if(n)u.cleanupEvents(n),(i=n).classList.add("dt-root"),i.innerHTML="";else{if(!i)(i=document.createElement("div")).className="dt-root",i.id="string"==typeof e&&e?e:t.id||"dt-"+Math.random().toString(36).slice(2);i._mblConfig=t}}const l=document.createElement("div");l.className="dt-table",l.setAttribute("role","table"),l.id=(hasClass(i,"mbl-inner-host")?i.parentElement.id:i.id)+"-tbl";const o=document.createElement("div");o.className="dt-headerbar";const d=document.createElement("div");if(d.className="dt-title",d.textContent=t.title||"",o.appendChild(d),t.description){const e=document.createElement("div");e.className="dt-desc",e.innerHTML=t.description,o.appendChild(e)}const c=document.createElement("div");if(c.className="dt-actions",false!==t.rowAdd){const e=createButton(l.id+"-tbl-add","Add Item","/ic?i=plus&m=tr",addDataRow,["dt-btn","dt-tbl-btn"]);if(e)c.appendChild(e)}let h="string"==typeof t.csv&&t.csv.length>3?t.csv:null;const p=t.fields||[];let m=Array.isArray(t.data)?[...t.data]:[];if("string"==typeof t.sort&&t.sort.trim())try{m=sortArray(m,t.sort)}catch(e){}const g="string"==typeof t.tableGroup&&t.tableGroup||"object"==typeof n&&"string"==typeof n.tableGroup&&n.tableGroup||null;const b=document.createElement("div");b.className="dt-wrapper";const y=document.createElement("div");if(y.className="dt-filter-summary",y.setAttribute("aria-live","polite"),c.children.length)o.appendChild(c);i.appendChild(o),i.appendChild(y),i.appendChild(b),b.appendChild(l),p.forEach(e=>{if(null!==e.width)e.width=Number(e.width);if(null!==e.colWidth)e.colWidth=Number(e.colWidth)});const v=p.filter(e=>false!==e.colShow);const _=p.filter(e=>false!==e.colShow&&true===e.colMobile);const A=v.filter(e=>false!==e.colShow&&false===e.colMobile);const isMultiLikeField=e=>{const t=String(e?.type||"").toLowerCase();if("multi-select"===t)return true;if("fielddata"===t)return true===e?.mtp||"true"===String(e?.mtp).toLowerCase();return false};const formatMultiLike=e=>{if(!Array.isArray(e))return"";return e.map(e=>{if(e&&"object"==typeof e)return String(e.fieldOption||e.fieldValue||"").trim();return String(e||"").trim()}).filter(Boolean).join(", ")};const isFieldData=e=>"fielddata"===String(e?.type||"").toLowerCase();const formatFieldDataValue=e=>{if(Array.isArray(e))return formatMultiLike(e);if(e&&"object"==typeof e)return String(e.fieldOption||e.fieldValue||"").trim();return String(e??"").trim()};function setGridTemplateForMode(e){const i=e?_.length?_:v:v;const n=[];if(i.forEach(e=>{let t=e.colWidth;let i="minmax(0,1fr)";if("number"==typeof t)if(t>50)i=`${t}px`;else if(-1===t)i="auto";else if(0===t)i="1fr";n.push(i)}),!e&&(false!==t.rowView||false!==t.rowEdit))n.push("auto");if(!e&&(false!==t.rowView||false!==t.rowEdit))n.pop(),n.push("max-content");l.style.gridTemplateColumns=n.join(" ")}setGridTemplateForMode(false);const S=document.createElement("div");S.className="dt-header",S.setAttribute("role","row"),l.appendChild(S);const C={};const w={col:null,dir:1};const makeFilterBtn=(e,t)=>createButton(void 0,e,null,t);function buildHead(){if(v.forEach(e=>{if(false===e.colShow)return;const t=document.createElement("div");t.className="dt-headcell dt-align-"+(e.colAlign||"left")+(false===e.colMobile?" col-nonmobile":""),t.setAttribute("role","columnheader"),t.tabIndex=-1;const i=e.colTitle||e.label||e.dataCol||"";const n=document.createElement("div");n.className="dt-headcell-inner";const s=document.createElement("span");if(s.textContent=i,n.appendChild(s),e.colSort){const t=createButton(void 0,"","/ic?i=up-down&m=tr",()=>{if(w.col===e.dataCol)w.dir*=-1;else w.col=e.dataCol,w.dir=1;applySortFilter(),updateSortIndicators()},["dt-sort-btn"],[{name:"aria-label",value:"Sort "+i},{name:"data-sort-col",value:e.dataCol}]);if(t)n.appendChild(t)}if(e.colFilter){const s=document.createElement("div");s.className="dt-filter-menu",s.setAttribute("role","listbox"),s.setAttribute("data-col",e.dataCol),s.hidden=true;const r=createButton(void 0,"","/ic?i=funnel&m=tr",e=>{e.stopPropagation();const t=s.hidden;closeAllMenus(s),s.hidden=!t,r.setAttribute("aria-expanded",String(!s.hidden))},["dt-filter-btn"],[{name:"aria-label",value:"Filter "+i},{name:"aria-haspopup",value:"listbox"},{name:"aria-expanded",value:"false"},{name:"data-col",value:e.dataCol}]);const a=makeFilterBtn("All",()=>{delete C[e.dataCol],applySortFilter(),updateFilterButtonStates(),updateFilterSummary(),s.hidden=true,r.setAttribute("aria-expanded","fal
1se")});if(a.setAttribute("role","option"),a.setAttribute("aria-selected","false"),s.appendChild(a),t.appendChild(s),r.addEventListener("keydown",e=>{if("Escape"===e.key)s.hidden=true,r.setAttribute("aria-expanded","false"),r.focus()}),r)n.appendChild(r);t.addEventListener("keydown",e=>{if("Escape"===e.key)s.hidden=true,r.setAttribute("aria-expanded","false")}),t.menu=s}t.appendChild(n),S.appendChild(t)}),false!==t.rowView||false!==t.rowEdit){const e=document.createElement("div");e.className="dt-headcell dt-align-center col-actions",e.textContent="Tools",S.appendChild(e)}}buildHead();const E=[];const L=new Map;let x={enabled:false,container:null,viewport:{start:0,end:0},buffer:10};if(m.length>s)x.enabled=true,console.log(`Large dataset detected (${m.length} rows). Virtual scrolling enabled.`);function buildGroupHeader(e){const t=String(e??"");if(L.has(t))return L.get(t);const i={value:e,header:document.createElement("div"),rows:[],collapsed:false,icon:null};const n=i.header;n.className="dt-row dt-group-row",n.setAttribute("role","row"),n.tabIndex=0,n.dataset.group=t,n.setAttribute("aria-expanded","true");const s=document.createElement("div");s.className="dt-cell dt-group-cell",s.setAttribute("role","cell"),s.style.gridColumn="1 / -1",s.style.display="flex",s.style.alignItems="center",s.style.gap=".4rem";const r=document.createElement("img");r.alt="",r.style.margin="2px 0",r.width=28,r.height=28,r.src="/ic?i=triangle-down&m=tr",r.setAttribute("aria-hidden","true");const a=document.createElement("span");const o=(p||[]).find(e=>e.dataCol===g)||{};const d=o.colTitle&&""!==String(o.colTitle).trim()?o.colTitle:o.label||g||"";a.textContent=String(d)+": "+String(e??"(none)"),s.appendChild(r),s.appendChild(a),n.appendChild(s);const toggle=()=>{i.collapsed=!i.collapsed,n.setAttribute("aria-expanded",String(!i.collapsed)),r.src=i.collapsed?"/ic?i=triangle-up&m=tr":"/ic?i=triangle-down&m=tr",i.rows.forEach(e=>e.classList.toggle("dt-group-hidden",i.collapsed)),renderAgg()};if(n.addEventListener("pointerup",e=>{if(0!==e.button)return;toggle()}),n.addEventListener("keydown",e=>{if("Enter"===e.key||" "===e.key)e.preventDefault(),toggle()}),"undefined"!=typeof k&&k&&k.parentElement===l)l.insertBefore(n,k);else l.appendChild(n);return i.icon=r,L.set(t,i),i}if(h){const csvHandler=()=>{const e=E.filter(e=>!e.classList.contains("dt-hidden-row")&&!e.classList.contains("dt-group-hidden"));let t=p.filter(e=>false!==e.colCSV&&e.dataCol);if(!t.length){const i=e[0]?._data||Array.isArray(m)&&m[0]||null;if(i)t=Object.keys(i).map(e=>({dataCol:e,colTitle:e}))}const i=undefined;let n='"'+t.map(e=>{let t=e.colTitle;if(null==t||""===String(t).trim())t=e.label;if(null==t||""===String(t).trim())t=e.dataCol;return String(t).replace(/"/g,'""')}).join('","')+'"\n';e.forEach(e=>{const i=e._data||{};n+=t.map(e=>{let t=f.getNestedValue(i,e.dataCol);if(null==t)t="";return t=String(t).replace(/"/g,'""'),'"'+t+'"'}).join(",")+"\n"});const s=new Blob([n],{type:"text/csv;charset=utf-8;"});const r=document.createElement("a");r.href=URL.createObjectURL(s),r.download=h.endsWith(".csv")?h:h+".csv",document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(r.href),r.remove()},0)};const e=createButton(l.id+"-csv","CSV","/ic?i=download&m=tr",csvHandler,["dt-btn"]);if(e)c.appendChild(e);if(!c.parentElement)o.appendChild(c)}function toggleRow(e){const t="true"===e.dataset.expanded;e.dataset.expanded=t?"false":"true",e.setAttribute("aria-expanded",String(!t)),e.classList.toggle("dt-row-expanded",!t)}function buildRow(e){const i=document.createElement("div");i.className="dt-row",i.setAttribute("role","row"),i.tabIndex=0,i.dataset.id=f.getNestedValue(e,t.dataId),i._data=e;let n=null;if(g){const t=f.getNestedValue(e,g);n=buildGroupHeader(t),i.dataset.group=String(t??"")}if(v.forEach(t=>{if(false===t.colShow)return;const n=document.createElement("div");n.className="dt-cell dt-align-"+(t.colAlign||"left")+(false===t.colMobile?" col-nonmobile":""),n.setAttribute("role","cell");let s=f.getNestedValue(e,t.dataCol);if(null==s)s="";if(isMultiLikeField(t)&&Array.isArray(s))n.textContent=formatMultiLike(s);else if(isFieldData(t))n.textContent=formatFieldDataValue(s);else n.textContent=s;i.appendChild(n)}),false!==t.rowView||false!==t.rowEdit){const n=document.createElement("div");if(n.className="dt-cell dt-align-center col-actions",n.setAttribute("role","cell"),false!==t.rowView&&e&&false!==e.canView){const i=createButton(void 0,"View",null,i=>{i.stopPropagation(),viewDataRow(i,f.getNestedValue(e,t.dataId),e)},["dt-btn","dt-tbl-btn"]);n.appendChild(i)}if(false!==t.rowEdit&&e&&false!==e.canView&&false!==e.canEdit){const t=createButton(void 0,"Edit",null,t=>{t.stopPropagation(),editDataRow(t,e)},["dt-btn","dt-tbl-btn"]);n.appendChild(t)}i.appendChild(n)}const s=document.createElement("div");
1if(s.className="row-details",s.setAttribute("role","group"),A.forEach(t=>{if(false===t.colShow)return;const i=document.createElement("div");i.className="row-details-item";const n=document.createElement("div");n.textContent=t.label||t.colTitle||t.dataCol||"";const r=document.createElement("div");let a=f.getNestedValue(e,t.dataCol);if(null==a)a="";if(isMultiLikeField(t)&&Array.isArray(a))r.textContent=formatMultiLike(a);else if(isFieldData(t))r.textContent=formatFieldDataValue(a);else r.textContent=a;i.appendChild(n),i.appendChild(r),s.appendChild(i)}),false!==t.rowView||false!==t.rowEdit){const i=document.createElement("div");i.className="row-details-item row-details-actions";const n=document.createElement("div");n.textContent="Tools";const r=document.createElement("div");if(false!==t.rowView&&e&&false!==e.canView){const i=createButton(void 0,"View",null,i=>{i.stopPropagation(),viewDataRow(i,e[t.dataId],e)},["dt-btn","dt-tbl-btn"]);r.appendChild(i)}if(false!==t.rowEdit&&e&&false!==e.canView&&false!==e.canEdit){const t=createButton(void 0,"Edit",null,t=>{t.stopPropagation(),editDataRow(t,e)},["dt-btn","dt-tbl-btn"]);r.appendChild(t)}i.appendChild(n),i.appendChild(r),s.appendChild(i)}if(i.appendChild(s),i.addEventListener("pointerup",e=>{if(l.classList.contains("dt-mobile")){if(0!==e.button)return;if(e.target.closest(".dt-btn,button"))return;toggleRow(i)}}),i.addEventListener("keydown",e=>{if("Enter"===e.key||" "===e.key)if(l.classList.contains("dt-mobile"))e.preventDefault(),toggleRow(i)}),n){const e=n.rows.length?n.rows[n.rows.length-1]:n.header;if(e&&e.parentElement===l)l.insertBefore(i,e.nextSibling);else l.appendChild(i);if(n.rows.push(i),n.collapsed)i.classList.add("dt-group-hidden")}else if(k&&k.parentElement===l)l.insertBefore(i,k);else l.appendChild(i);E.push(i)}const D=v.some(e=>false!==e.colShow&&!!e.colAgg);let k=null;function renderAgg(){if(!D||!k)return;if(k.innerHTML="",v.forEach(e=>{if(false===e.colShow)return;const t=document.createElement("div");if(t.className="dt-cell dt-align-"+(e.colAlign||"left")+(false===e.colMobile?" col-nonmobile":""),t.setAttribute("role","cell"),e.colAgg){const i=E.filter(e=>!e.classList.contains("dt-hidden-row")&&!e.classList.contains("dt-group-hidden")).map(t=>{const i=v.filter(e=>false!==e.colShow).indexOf(e);return t.children[i].textContent}).filter(e=>""!==e&&null!=e);const n=i.map(e=>parseFloat(e)).filter(e=>!isNaN(e));if("sum"===e.colAgg)t.textContent=n.reduce((e,t)=>e+t,0).toLocaleString();else if("avg"===e.colAgg){if(n.length)t.textContent=(n.reduce((e,t)=>e+t,0)/n.length).toFixed(2)}else if("count"===e.colAgg)t.textContent=i.length.toString()}k.appendChild(t)}),false!==t.rowView||false!==t.rowEdit){const e=document.createElement("div");e.className="dt-cell",k.appendChild(e)}}if(D)k=document.createElement("div"),k.className="dt-row dt-agg dt-no-order",k.setAttribute("role","row"),renderAgg(),l.appendChild(k);function updateTable(e){if(Array.isArray(e))if(m=[...e],"string"==typeof t.sort&&t.sort.trim())try{m=sortArray(m,t.sort)}catch(e){}if(E.splice(0,E.length),L.clear(),Array.from(l.querySelectorAll(".dt-row")).forEach(e=>{if(!e.classList.contains("dt-agg"))e.remove()}),m.forEach(e=>buildRow(e)),populateFilterMenus._cache)populateFilterMenus._cache={};if(S.querySelectorAll(".dt-filter-menu").forEach(e=>{e.dataset.built="false";const t=e.querySelector('button[role="option"]:first-child');if(e.innerHTML="",t&&"All"===t.textContent)e.appendChild(t)}),populateFilterMenus(),updateFilterButtonStates(),updateSortIndicators(),applySortFilter(),renderAgg(),k&&k.parentElement===l)l.appendChild(k);if(updateMobileMode(),true===t.allowOrdering)if(enableOrdering(l,".dt-row"),!l._orderListenerBound)l.addEventListener("orderChanged",e=>{const i=e.detail;if(!Array.isArray(i)||!Array.isArray(m))return;const n=l.closest(".dt-list-control");if(n){let e=n.getAttribute("data-list-value");if(e&&e.length>2&&0===e.indexOf("[")){try{e=JSON.parse(e)}catch(t){e=[]}let s=0;i.forEach(i=>{e.forEach(e=>{if(null!=e[t.dataId]&&e[t.dataId]===i)e._do=s}),s++});try{e=sortArray(e,"_do")}catch(e){}updateInputControl(n,JSON.stringify(e),void 0,{forceDirty:true})}}}),l._orderListenerBound=true}function updateFilterSummary(){y.innerHTML="",Object.keys(C).forEac
1h(e=>{const t=C[e];if(!t||!t.size)return;const i=p.find(t=>t.dataCol===e)?.colTitle||e;[...t].forEach(t=>{const n=document.createElement("div");n.className="dt-filter-chip",n.textContent=i+": "+t;const s=undefined;const r=createButton(void 0,null,"/ic?i=x&m=tr",()=>{const i=C[e];if(!i)return;if(i.delete(t),!i.size)delete C[e];applySortFilter(),updateFilterButtonStates()});r.setAttribute("aria-label","Remove filter "+i+" = "+t),n.appendChild(r),y.appendChild(n)})})}i._updateTable=updateTable;const T=u.debounce(applySortFilter,300);function applySortFilter(){const{fragment:e}=u.batchDOMOperations([()=>{E.forEach(e=>e.classList.remove("dt-hidden-row")),Object.entries(C).forEach(([e,t])=>{if(!t||!t.size)return;const i=v.find(t=>t.dataCol===e);E.forEach(n=>{const s=v.filter(e=>false!==e.colShow).findIndex(t=>t.dataCol===e);if(s>-1){const r=n.children[s];if(!r)return;let a=false;if(isMultiLikeField(i)){const i=n._data;if(i&&f.hasNestedProperty(i,e)){const n=f.getNestedValue(i,e);if(Array.isArray(n))a=n.some(e=>{if(e&&"object"==typeof e){const i=String(e.fieldOption||e.fieldValue||"");return t.has(i)}else return t.has(String(e||""))})}}
1else if(Array.isArray(f.getNestedValue(n._data,e))){const i=undefined;a=f.getNestedValue(n._data,e).some(e=>{if(e&&"object"==typeof e){const i=String(e.fieldOption||e.fieldValue||"");return t.has(i)}else return t.has(String(e||""))})}else if(isFieldData(i))a=t.has(formatFieldDataValue(f.getNestedValue(n._data,e)));else a=t.has(r.textContent);if(!a)n.classList.add("dt-hidden-row")}})})}]);if(w.col){const e=v.filter(e=>false!==e.colShow).findIndex(e=>e.dataCol===w.col);if(!g){const t=E.slice().sort((t,i)=>{const n=t.children[e].textContent;const s=i.children[e].textContent;const r=parseFloat(n);const a=parseFloat(s);let l;if(!isNaN(r)&&!isNaN(a))l=r-a;else l=n.localeCompare(s,void 0,{numeric:true,sensitivity:"base"});return l*w.dir});E.splice(0,E.length,...t),requestAnimationFrame(()=>{t.forEach(e=>l.insertBefore(e,k))})}else L.forEach(t=>{const i=t.rows.slice();i.sort((t,i)=>{const n=t.children[e].textContent;const s=i.children[e].textContent;const r=parseFloat(n);const a=parseFloat(s);let l;if(!isNaN(r)&&!isNaN(a))l=r-a;else l=n.localeCompare(s,void 0,{numeric:true,sensitivity:"base"});return l*w.dir});let n=t.header;i.forEach(e=>{if(n&&n.parentElement===l)l.insertBefore(e,n.nextSibling);else l.appendChild(e);n=e}),t.rows=i})}if(g)L.forEach(e=>{const t=e.rows.some(e=>!e.classList.contains("dt-hidden-row"));e.header.classList.toggle("dt-hidden-row",!t)});updateFilterSummary(),updateFilterButtonStates(),renderAgg()}function updateSortIndicators(){const e=undefined;S.querySelectorAll(".dt-sort-btn").forEach(e=>{const t=undefined;if(e.getAttribute("data-sort-col")===w.col)e.setAttribute("aria-sort",1===w.dir?"ascending":"descending"),e.classList.toggle("is-desc",-1===w.dir);else e.removeAttribute("aria-sort"),e.classList.remove("is-desc")})}function populateFilterMenus(){const e=populateFilterMenus._cache||(populateFilterMenus._cache={});v.forEach(t=>{if(!t.colFilter||false===t.colShow)return;const i=S.querySelector('.dt-filter-menu[data-col="'+t.dataCol+'"]');if(!i||"true"===i.dataset.built)return;if(i.setAttribute("aria-multiselectable","true"),!e[t.dataCol]){const i=new Set;m.forEach(e=>{let n=f.getNestedValue(e,t.dataCol);if(null==n)n="";if(Array.isArray(n))n.forEach(e=>{if(e&&"object"==typeof e){const t=String(e.fieldOption||e.fieldValue||"");if(""!==t)i.add(t)}else{const t=String(e||"");if(""!==t)i.add(t)}});else if(isFieldData(t)){const e=formatFieldDataValue(n);if(""!==e)i.add(e)}else i.add(String(n))});const n=i.has("");if(n)i.delete("");e[t.dataCol]={values:Array.from(i).sort((e,t)=>e.localeCompare(t,void 0,{numeric:true,sensitivity:"base"})),hasBlank:n}}const{values:n,hasBlank:s}=e[t.dataCol];if(n.forEach(e=>{const n=undefined;const s=createButton(null,e,null,()=>toggleFilterValue(t.dataCol,e,s),[],[{name:"role",value:"option"},{name:"data-val",value:e}]);if(s)i.appendChild(s)}),s){const e=undefined;const n=createButton(null,"None",null,()=>{delete C[t.dataCol],applySortFilter(),updateFilterButtonStates(),updateFilterSummary(),i.hidden=true;const e=S.querySelector('.dt-filter-btn[data-col="'+t.dataCol+'"]');e?.setAttribute("aria-expanded","false"),e?.focus()},[],[{name:"role",value:"option"},{name:"data-val",value:""}]);if(n)i.appendChild(n)}i.addEventListener("keydown",e=>handleMenuKey(e,t.dataCol,i)),i.dataset.built="true"})}function updateFilterButtonStates(){S.querySelectorAll(".dt-filter-btn").forEach(e=>{const t=e.getAttribute("data-col");const i=C[t];if(i&&i.size)e.classList.add("is-filtered");else e.classList.remove("is-filtered")}),S.querySelectorAll(".dt-filter-menu").forEach(e=>{const t=e.getAttribute("data-col");const i=C[t];e.querySelectorAll('button[role="option"]').forEach(e=>{if("All"===e.textContent)return;const t=!!(i&&i.has(e.dataset.val));e.classList.toggle("is-selected",t),e.setAttribute("aria-selected",String(t))})})}function toggleFilterValue(e,t,i){if(!C[e])C[e]=new Set;const n=C[e];if(n.has(t))n.delete(t);else n.add(t);if(!n.size)delete C[e];T(),updateFilterButtonStates(),updateFilterSummary();const s=S.querySelector('.dt-filter-menu[data-col="'+e+'"]');const r=S.querySelector('.dt-filter-btn[data-col="'+e+'"]');
1if(s&&r)s.hidden=true,r.setAttribute("aria-expanded","false"),r.focus()}function handleMenuKey(e,t,i){const n=[...i.querySelectorAll('button[role="option"]')];const s=n.indexOf(document.activeElement);switch(e.key){case"ArrowDown":e.preventDefault(),n[(s+1)%n.length].focus();break;case"ArrowUp":e.preventDefault(),n[(s-1+n.length)%n.length].focus();break;case"Home":e.preventDefault(),n[0].focus();break;case"End":e.preventDefault(),n[n.length-1].focus();break;case" ":case"Enter":{e.preventDefault();const i=document.activeElement;if(!i)break;if("All"===i.textContent||"None"===i.textContent){delete C[t],applySortFilter(),updateFilterButtonStates(),updateFilterSummary(),i.focus();break}if(null!=i.dataset.val)toggleFilterValue(t,i.dataset.val,i);break}case"Escape":closeAllMenus();const i=S.querySelector('.dt-filter-btn[data-col="'+t+'"]');i?.focus();break}}function closeAllMenus(e){document.querySelectorAll(".dt-filter-menu").forEach(t=>{if(t!==e){t.hidden=true;const e=t.parentElement.querySelector(".dt-filter-btn");if(e)e.setAttribute("aria-expanded","false")}})}function refreshLayout(){setGridTemplateForMode(l.classList.contains("dt-mobile"))}function estimateMinWidth(){const e=120;let i=0;if(v.forEach(t=>{if(false===t.colShow)return;let n=e;if("number"==typeof t.colWidth&&t.colWidth>50)n=t.colWidth;else if("number"==typeof t.colMinWidth&&t.colMinWidth>0)n=t.colMinWidth;i+=n}),false!==t.rowView||false!==t.rowEdit)i+=120;return i+=32,i}function updateMobileMode(){const e=estimateMinWidth();const t=i.clientWidth||l.clientWidth||0;const n=t>0&&t<e;const s=l.classList.contains("dt-mobile");if(l.classList.toggle("dt-mobile",n),n!==s)setGridTemplateForMode(n);if(!n)E.forEach(e=>{e.dataset.expanded="false",e.setAttribute("aria-expanded","false"),e.classList.remove("dt-row-expanded")})}if(updateTable(),document.addEventListener("pointerup",e=>{if(!e.target.closest(".dt-headcell"))closeAllMenus()}),document.addEventListener("keydown",e=>{if("Escape"===e.key)closeAllMenus()}),window.addEventListener("resize",refreshLayout),"function"==typeof ResizeObserver){const e=undefined;new ResizeObserver(()=>updateMobileMode()).observe(i)}else window.addEventListener("resize",updateMobileMode);if(updateMobileMode(),false===a)return i}function updateTableData(e,t){const i=getElement(e);if(i&&"function"==typeof i._updateTable)i._updateTable(Array.isArray(t)?t:[])}function sortArray(e,t){return u.withErrorBoundary(()=>{if(!Array.isArray(e))return console.warn("sortArray: Expected array, got:",typeof e),[];const i=[...e];if("string"!=typeof t||!t.trim())return console.warn("sortArray: Invalid sortKey:",t),i;const n=t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>({key:e.startsWith("-")?e.slice(1):e,dir:e.startsWith("-")?-1:1}));if(0===n.length||i.length<=1)return i;const s=new WeakMap;const getVal=(e,t)=>{if(!e||!t)return null;let i=s.get(e);if(!i)i=new Map,s.set(e,i);if(i.has(t))return i.get(t);const n=t.includes(".")?t.split(".").reduce((e,t)=>e?.[t],e):e[t];return i.set(t,n),n};const asNum=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("boolean"==typeof e)return+e;const t=Number(e);return Number.isFinite(t)?t:NaN};return u.measurePerformance(`sortArray (${i.length} items)`,()=>i.sort((e,t)=>{for(const{key:i,dir:s}of n){const n=getVal(e,i);const r=getVal(t,i);if(n===r)continue;if(null==n&&null!=r)return 1*s;if(null==r&&null!=n)return-1*s;const a=asNum(n);const l=asNum(r);if(Number.isFinite(a)&&Number.isFinite(l)){const e=a-l;if(0!==e)return e*s;continue}const o=String(n);const d=String(r);const c=o.localeCompare(d,void 0,{numeric:true,sensitivity:"base"});if(0!==c)return c*s}return 0}))},"sortArray")()}async function fetchWithRetry(e,t={},i=p.get("maxRetries")){let n;for(let s=0;s<=i;s++)try{const i=new AbortController;const n=setTimeout(()=>i.abort(),p.get("timeout"));const s=await fetch(e,{...t,signal:i.signal});if(clearTimeout(n),!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);return s}catch(e){if(n=e,console.warn(`Fetch attempt ${s+1} failed:`,e.message),s<i&&!e.name?.includes("Abort"))await new Promise(e=>setTimeout(e,1e3*Math.pow(2,s)))}throw new Error(`Failed to fetch after ${i+1} attempts: ${n?.message||"Unknown error"}`)}async function fetchConfig(e){showWaiting("Loading Config...",2);try{const t=await fetchWithRetry(e);const i=await t.json();if(i&&"object"==typeof i){if(true==i.error)console.log("Config API error",i.msg||"");const e=p.validate(i);if(e.length>0)console.warn("Config validation warnings:",e)}return i}catch(e){throw console.error("fetchConfig error:",e),e}finally{hideWaiting()}}async function fetchData(e,t="Getting the Latest Data..."){showWaiting(t,2);try{const t=await fetchWithRetry(e);const i=await t.json();if(i&&"object"==typeof i)if(true==i.error)console.log("Data API error",i.msg||"");return await i}catch(e){throw console.error("fetchData error:",e),e}finally{hideWaiting()}}function isNothingOrEmpty(e){return null==e||""===e||Array.isArray(e)&&0===e.length||"string"==typeof e&&""===e.trim()}function formatDateString(e,t="yyyy-MM-dd-HH-mm-ssss"){const i=new Date(e);const n=i.getFullYear();const s=String(i.getMonth()+1).padStart(2,"0");const r=String(i.getDate()).padStart(2,"0");const a=String(i.getHours()).padStart(2,"0");const l=String(i.getMinutes()).padStart(2,"0");const o=String(i.getSeconds()).padStart(2,"0");const d=String(i.getMilliseconds()).padStart(4,"0");return t.replace("yyyy",n).replace("MM",s).replace("dd",r).replace("HH",a).replace("mm",l).replace("ssss",o+d.slice(0,2))}async function createAjaxRequest(e){const{onSuccess:t,onFailure:i,jsonRequest:n=true,jsonResponse:s=true,async:r=true,headers:a=[],checkOffline:l=false,chunkSize:o=1*1024*1024}=e;const d=undefined;
1return{async post(e,t){return this.makeRequest("POST",e,t)},async put(e,t){return this.makeRequest("PUT",e,t)},async makeRequest(e,r,l){try{const i=new Headers;a.forEach(e=>{if(e.name&&e.value)i.append(e.name,e.value)});const o=document.querySelector('input[name="__RequestVerificationToken"]');if(("PUT"===e||"POST"===e)&&o)i.append("RequestVerificationToken",o.value);let d=null;let c=r;if(n&&l)i.append("Content-Type","application/json"),d=JSON.stringify(l);else if(l)if(l instanceof FormData)d=l;else if("object"==typeof l){const t=new URLSearchParams;if(Object.keys(l).forEach(e=>{t.append(e,l[e])}),"GET"===e)c+=(r.includes("?")?"&":"?")+t.toString();else i.append("Content-Type","application/x-www-form-urlencoded"),d=t.toString()}const u=await fetch(c,{method:e,headers:i,body:d});if(!u.ok){const e=new Error(`HTTP ${u.status}: ${u.statusText}`);throw e.status=u.status,e.statusText=u.statusText,e}const f=s?await u.json():await u.text();if(t)t(f,this);return f}catch(e){if(console.error("Ajax request failed:",e),i)i(e.status||0,e.statusText||e.message,this);throw e}},async fileUpload(e,n,s,r=[],a=[]){try{const i=Array.isArray(n)?n:Array.from(n);const l=[];showWaiting(`Uploading ${i.length} file(s)...`);for(let t=0;t<i.length;t++){const n=i[t];const d=Math.ceil(n.size/o);const c=formatDateString(new Date);const u=a.find(e=>e&&e.fileNo===t&&e.fileId<0)||{};for(let t=0;t<d;t++){const i=t*o;const a=Math.min(i+o,n.size);const f=n.slice(i,a);const h=undefined;const p={chunkStr:await new Promise((e,t)=>{const i=new FileReader;i.onload=()=>e(i.result),i.onerror=t,i.readAsDataURL(f)}),fileName:n.name,chunkDate:c,chunkCount:d,chunkIndex:t+1,blobType:s,fileOrder:u.fileOrder||null,fileCaption:u.fileCaption||null,fileId:n.fileId||u.fileId||null};let m=e;if(r.length>0)r.forEach(e=>{m+=(m.includes("?")?"&":"?")+e.replace(/^\?/,"")});const g=await this.makeRequest("POST",m,p);const b=Math.floor((t+1)/d*100);if(showWaiting(`${n.name} is ${b}% done`),t===d-1){if(g&&g.file)l.push(g.file);else l.push({error:true,eFileId:null});showWaiting(`${n.name} is done`)}}}if(showWaiting("All file(s) are done"),t)t(l);return l}catch(e){if(console.error("File upload failed:",e),i)i(e.status||0,e.statusText||e.message,this);throw e}finally{hideWaiting()}}}}async function processFileFields(e,t,i,n=false,s=null,r=null){if(!Array.isArray(e)||0===e.length)return false;const a=[];let l=false;const o=i?(e,t)=>{const n=a.find(e=>e.fieldId===t);if(n)n.done=true,n.error=!e||true===e.error,n.data=e;const s=undefined;if(a.every(e=>e.done)&&i)i(a)}:null;for(let i=0;i<e.length;i++){const d=e[i];const c=Array.isArray(t)?t[i]:t;if(await processFileField(d,c,o,n,s,r)){if(!n)a.push({fieldId:d,done:false,error:false});l=true}}return l}async function processFileField(e,t,i,n=false,s=null,r=null){const a=document.getElementById(e);const l=document.getElementById(e+"-hp");if(!a||!isFieldVisible(e)||!hasClass(e,"dirty"))return false;if(!hasAnyClasses(e,["filedirty","datadirty"]))return false;let o=null;let d=null;if(hasClass(e,"ocpdfviewer"))return console.warn("PDF viewer file processing not yet implemented in mbl-Library"),false;else{const e=a.value;if("[]"===e||'[""]'===e)a.value="";o=isNothingOrEmpty(e)?[]:JSON.parse(e),d=l?.files}if((!d||0===d.length)&&isNothingOrEmpty(o))return false;if(!n){let n=a?.getAttribute("data-blobtype");await callFileAPI(d,o,n,t,i,e,tId,s,r)}return true}async function callFileAPI(e,t,i,n,s,r,a,l,o){if(!e&&!t)return;try{const d=await createAjaxRequest({onSuccess:e=>{if(r)removeClass(r,"dirty");if(s)s(e,r)},onFailure:(e,t)=>{if(console.error(`File API call failed: ${e} (${t})`),s)s(null,r)}});let c="";if(l)c+="&dl="+l;if(o)c+="&it="+o;if(t&&("string"==typeof t&&t.length>10||Array.isArray(t)&&t.length>0))if(Array.isArray(t)&&null!==t[0]){for(const e of t)if(e.eFileId&&e.eFileId<0)e.fileId=e.eFileId;const e="/api/Blob/UploadFileData?ii="+encodeURIComponent(n)+"&b="+i+(a?"&et="+encodeURIComponent(a):"")+c;await d.post(e,t)}if(e&&e.length>0){if(Array.isArray(t))for(const i of t)if(i)for(const t of e)if(i.fileTitle===t.name&&i.eFileId<0)t.fileId=i.eFileId;const s=[`ii=${encodeURIComponent(n)}${a?"&t="+encodeURIComponent(a):""}${c}`];await d.fileUpload("/api/Blob/UploadFileChunk",e,i,s,t)}}catch(e){if(console.error("callFileAPI error:",e),s)s(null,r)}}function isFieldVisible(e){const t=document.getElementById(e);return t&&null!==t.offsetParent}function hasClass(e,t){const i=getElement(e);return i&&i.classList.contains(t)}function hasAnyClasses(e,t){const i=document.getElementById(e);if(!i)return false;return t.some(e=>i.classList.contains(e))}function removeClass(e,t){const i=document.getElementById(e);if(i)i.classList.remove(t)}function mountConfig(e,t="tableHost"){const i=getElement(t);if(!i)return void console.error("mountConfig host not found",t);if(null==e)return i.innerHTML="",void(i._mblConfig=null);n=e||n;try{let t;if(i._mblConfig=e,i.classList.add("dt-root"),"dialog"===e?.type){const n=undefined;const s=createDialog({objId:e.id?e.id+"-dlg":void 0,parent:i,title:e.title||"",size:void 0,classList:void 0,attr:void 0,buttons:e.dlgButtons,allowMaximize:true,onOpen:e.onOpen?e.onOpen:t=>
1{if(true===e.form){const e=t.querySelector('.dt-row, input:not([type="hidden"]), select, textarea, button, [tabindex]:not([tabindex="-1"])');if(e)setTimeout(()=>e.focus(),100)}},onClose:e=>{}});if(t=s.querySelector(".dt-dlg-body"),t)if(t.innerHTML="",e.description){const i=document.createElement(0===e.description.indexOf("<")?"div":"p");i.className="dt-desc",i.style.marginBottom=".75rem",i.innerHTML=e.description,t.appendChild(i)}e.btnTitle=e.btnTitle||e.title||"Open";const r=createButton(e.id+"-launch",e.btnTitle||"",null,()=>{s.showModal(),s.querySelector(".dt-row")?.focus()},["dt-btn","dt-launch"]);if(r)i.appendChild(r);s.addEventListener("close",()=>{r?.focus()})}if(e.fields&&Array.isArray(e.fields)&&e.fields.length>0){if(i.classList.remove("dt-no-fields"),false!==e.table)createTable(e.id,e||{},"dialog"===e?.type?t:i);if(true===e.form)createForm(e.id+"-form"||void 0,"dialog"===e?.type?t:i,e||{})}else{i.classList.add("dt-no-fields");let e=document.createElement("h2");e.classList.add("dt-no-fields"),e.textContent="No fields defined in config",i.appendChild(e)}}catch(e){console.error("mountConfig error",e);try{const e=document.createElement("div");e.className="dt-no-data",e.textContent="Error rendering control",i.innerHTML="",i.appendChild(e)}catch(e){}}}const m={logError(e,t="Unknown",i={}){const n={message:e?.message||"Unknown error",stack:e?.stack,context:t,timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,url:window.location.href,...i};console.error("mbl-Library Error:",n)},createErrorBoundary(e,t="Unknown"){return(...i)=>{try{return e(...i)}catch(e){return this.logError(e,t,{args:i}),null}}},createAsyncErrorBoundary(e,t="Unknown"){return async(...i)=>{try{return await e(...i)}catch(e){throw this.logError(e,t,{args:i}),e}}}};function enableOrdering(e,t){try{const i=getElement(e);if(!i)return void console.error("enableOrdering: Parent element not found");i.classList.add("dt-orderable");let n=t?[...i.querySelectorAll(t)]:[...i.children];if(n=n.filter(e=>!e.classList.contains("dt-no-order")),n.length<=1)return;function getCurrentChildren(){const e=undefined;return(t?[...i.querySelectorAll(t)]:[...i.children]).filter(e=>e.classList.contains("dt-orderable-item")&&!e.classList.contains("dt-no-order"))}function getCurrentIndex(e){return getCurrentChildren().indexOf(e)}function moveElement(e,t,n){const s=getCurrentChildren();if(n<0||n>=s.length)return;const r=s[n];i.insertBefore(e,t<n?r.nextSibling:r),e.classList.remove("dt-item-moved-flash"),e.offsetHeight,e.classList.add("dt-item-moved-flash"),setTimeout(()=>{e.classList.remove("dt-item-moved-flash")},1200),refreshOrderControls(),dispatchOrderChanged()}function refreshOrderControls(){const e=getCurrentChildren();for(const[t,i]of e.entries()){let n=i.querySelector(".dt-order-up");let s=i.querySelector(".dt-order-down");if(!n&&i.classList.contains("dt-row")){const e=i.querySelector(".col-actions");n=e?.querySelector(".dt-order-up"),s=e?.querySelector(".dt-order-down")}if(n)n.disabled=0===t;if(s)s.disabled=t===e.length-1}}function dispatchOrderChanged(){const e=getCurrentChildren().map(e=>e.getAttribute("data-id")||e.getAttribute("data-eid")).filter(e=>e?.length>0);const t=new CustomEvent("orderChanged",{detail:e,bubbles:true});i.dispatchEvent(t)}n.forEach((e,t)=>
1{const i=undefined;if(e.querySelector(".dt-order-controls")||e.classList.contains("dt-row")&&e.querySelector(".col-actions")?.classList.contains("dt-has-order-controls"))return;const s=undefined;const r=e.classList.contains("dt-row")?e.querySelector(".col-actions"):null;let a;if(r)a=r,a.classList.add("dt-has-order-controls"),e.classList.add("dt-orderable-item");else a=document.createElement("div"),a.className="dt-order-controls";const l=createButton(void 0,"","",t=>{t.preventDefault(),t.stopPropagation();const i=undefined;if(!t.currentTarget.disabled){const t=getCurrentIndex(e);if(t>0)moveElement(e,t,t-1)}},["dt-order-up"],[{name:"title",value:"Move up"},{name:"aria-label",value:"Move up"}]);if(l)l.disabled=0===t,a.appendChild(l);const o=createButton(void 0,"","",t=>{t.preventDefault(),t.stopPropagation();const i=undefined;if(!t.currentTarget.disabled){const t=getCurrentIndex(e);const i=undefined;if(t<getCurrentChildren().length-1)moveElement(e,t,t+1)}},["dt-order-down"],[{name:"title",value:"Move down"},{name:"aria-label",value:"Move down"}]);if(o)o.disabled=t===n.length-1,a.appendChild(o);if(!r){if("static"===getComputedStyle(e).position)e.style.position="relative";e.appendChild(a),e.classList.add("dt-orderable-item")}})}catch(s){console.error("enableOrdering error:",s)}}function eid(e=3){try{const t=Math.max(1,Math.min(10,parseInt(e)||3));const i=String(Date.now());if(i.length<=2*t)return"-"+i;const n=Math.max(0,t);const s=Math.max(n+1,i.length-t);return"-"+i.substring(n,s)}catch(e){return console.error("eid generation error:",e),"-"+Math.random().toString(36).substring(2,8)}}const g=[{fieldOption:"Content Block",fieldValue:"content"},{fieldOption:"Line Break",fieldValue:"break"},{fieldOption:"Date Only",fieldValue:"date"},{fieldOption:"Time Only",fieldValue:"time"},{fieldOption:"Date & Time",fieldValue:"datetime"},{fieldOption:"Text",fieldValue:"text"},{fieldOption:"Text - multiline",fieldValue:"textarea"},{fieldOption:"Text - with Formatting",fieldValue:"richtext"},{fieldOption:"Switch",fieldValue:"switch"},{fieldOption:"Upload File",fieldValue:"file"},{fieldOption:"Upload Image",fieldValue:"image"}];function checkGSM(e){const t=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","@","£","$","Â¥","è","é","ù","ì","ò","Ã","\n","Ã","ø","\r","Ã
","Ã¥","Î","_","Φ","Î","Î","Ω","Î ","Ψ","Σ","Î","Î"," ","!","'","#","¤","%","&",'"',"*","+",",","-",".","/",":",";","<","=",">","?","^","{","}","\\","[","]","~","|","â¬"];let i="";for(let n=0;n<e.length;n++)if(!t.includes(e[n])){if(""!=i)i+=" , ";i+=e[n]}if(""!=i)i="The following characters are not supported in SMS: "+i;return i}function getOrCreateLiveRegion(){let e=document.getElementById("dt-live-region");if(!e)e=document.createElement("div"),e.id="dt-live-region",e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","false"),e.style.position="absolute",e.style.left="-9999px",e.style.width="1px",e.style.height="1px",document.body.appendChild(e);return e}function announceSelectionChange(e,t){try{const e=getOrCreateLiveRegion();requestAnimationFrame(()=>{e.textContent=t})}catch(e){}}function getMultiSelected(e){const t=document.getElementById(e);if(!t||!t.classList.contains("dt-multi-select"))return[];return Array.isArray(t._multiSelected)?t._multiSelected.slice():[]}function getMultiSelectedObjects(e){const t=document.getElementById(e);if(!t||!t.classList.contains("dt-multi-select"))return[];try{return JSON.parse(t.dataset.valueJson||"[]")}catch{return[]}}function setMultiSelected(e,t){const i=document.getElementById(e);if(!i||!i.classList.contains("dt-multi-select"))return;let n=[];if(Array.isArray(t))if(t.length&&"object"==typeof t[0])n=t.map(e=>e.fieldValue||e.value||"");else n=t.map(e=>String(e));i._suppressEvents=true,updateInputControl(i,n,i._multiOptions),i._suppressEvents=false,i.dispatchEvent(new Event("input",{bubbles:true})),i.dispatchEvent(new Event("change",{bubbles:true}))}
1if(i.addDataRow=addDataRow,i.saveDataRow=saveDataRow,i.closeDialog=closeDialog,i.getNearest=getNearest,i.getElement=getElement,i.createButton=createButton,i.createInputControl=createInputControl,i.updateInputControl=updateInputControl,i.createForm=createForm,i.fetchFieldDataControls=fetchFieldDataControls,i.validateForm=validateForm,i.resetForm=resetForm,i.updateFormDirtyState=function(e){const t=getElement(e);if(t)_updateFormDirtyState(t)},i.createDialog=createDialog,i.msgDialog=msgDialog,i.createTable=createTable,i.mountConfig=mountConfig,i.fetchConfig=fetchConfig,i.fetchData=fetchData,i.showWaiting=showWaiting,i.hideWaiting=hideWaiting,i.sortArray=sortArray,i.eid=eid,i.enableOrdering=enableOrdering,i.hasClass=hasClass,window.announceSelectionChange=announceSelectionChange,i.getMultiSelected=getMultiSelected,i.getMultiSelectedObjects=getMultiSelectedObjects,i.setMultiSelected=setMultiSelected,i.createAjaxRequest=createAjaxRequest,i.processFileFields=processFileFields,i.processFileField=processFileField,i.callFileAPI=callFileAPI,i.processFileControlFields=processFileControlFields,i.renderFileControlUI=renderFileControlUI,i.updateFileControlValue=updateFileControlValue,i.pushCurData=pushCurData,i.popCurData=popCurData,i.checkGSM=checkGSM,"unset"===mainMbl)mainMbl=window.mbl.prototype}(window);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.