@vii7/div-table-widget 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.DivTable=t():e.DivTable=t()}(this,()=>{return e={430:e=>{class t{constructor(e,t){this.monaco=e,this.options=t;const i=void 0!==t.data&&null!==t.data;this.data=i?t.data:[],this.columns=t.columns||[],this.columns.forEach(e=>{(e.subLabel||e.subField||e.subType||e.subRender)&&console.warn(`DivTable: Column '${e.field}' uses deprecated properties (subLabel, subField, subType, subRender). Please migrate to fieldCompositeName approach. See README for migration guide.`)}),this.showCheckboxes=!1!==t.showCheckboxes,this.multiSelect=!1!==t.multiSelect,this.onSelectionChange=t.onSelectionChange||(()=>{}),this.onRowFocus=t.onRowFocus||(()=>{}),this.showLoadingPlaceholder=!1!==t.showLoadingPlaceholder,this.isLoadingState=0===this.data.length&&this.showLoadingPlaceholder,this._shouldLoadFirstPage=!i&&"function"==typeof t.onNextPage,this.showRefreshButton=t.showRefreshButton||!1,this.onRefresh=t.onRefresh||(()=>{}),this.showAutoFetchButton=!1!==t.showAutoFetchButton,this.autoFetchDelay=t.autoFetchDelay||500,this.virtualScrolling=t.virtualScrolling||!1,this.pageSize=t.pageSize||100,this.totalRecords=t.totalRecords||(this.virtualScrolling?10*this.pageSize:this.data.length),this.onNextPage=t.onNextPage||(()=>{}),this.onPreviousPage=t.onPreviousPage||(()=>{}),this.loadingThreshold=t.loadingThreshold||Math.floor(.8*this.pageSize),this.scrollThreshold=t.scrollThreshold||.95,this.filteredData=[...this.data],this.sortColumn=null,this.sortDirection="asc",this.sortMode="value",this.groupByField=null,this.collapsedGroups=new Set,this.selectedRows=new Set,this.focusedRowId=null,this.currentQuery="",this._lastFocusCallback={rowId:null,groupKey:null},this.showOnlySelected=!1,this.currentPage=0,this.isLoading=!1,this.hasMoreData=!0,this.estimatedRowHeight=40,this.visibleStartIndex=0,this.visibleEndIndex=this.pageSize,this.isAutoFetching=!1,this.autoFetchPaused=!1,this.autoFetchTimeout=null,this.fixedColumns=t.fixedColumns||0,this.primaryKeyField=this.columns.find(e=>e.primaryKey)?.field||"id",this.queryEngine=new s(this.data,this.primaryKeyField),this.init(),t.group&&this.group(t.group),t.sort&&t.sort.field&&this.sort(t.sort.field,t.sort.direction)}init(){const e=this.options.tableWidgetElement;e?(this.showCheckboxes||e.classList.add("no-checkboxes"),this.multiSelect||e.classList.add("no-multiselect"),this.createTableStructure(e),this.setupQueryEditor(),this.render(),this.setupKeyboardNavigation(),this._shouldLoadFirstPage?setTimeout(()=>this.loadFirstPageAutomatically(),100):this.virtualScrolling&&this.data.length<this.totalRecords&&"function"==typeof this.onNextPage&&setTimeout(()=>this.loadNextPage(),100)):console.error("DivTable: tableWidgetElement is required")}async loadFirstPageAutomatically(){try{this.isLoading=!0,this.updateInfoSection();const e=await this.onNextPage(0,this.pageSize);this.isLoading=!1,e&&Array.isArray(e)&&e.length>0?this.replaceData(e):(this.isLoadingState=!1,this.hasMoreData=!1,this.render())}catch(e){console.error("❌ Error loading first page:",e),this.isLoading=!1,this.isLoadingState=!1,this.hasMoreData=!1,this.render()}}getOrderedColumns(){let e=this.columns.filter(e=>!e.hidden);if(!this.groupByField)return e;const t=[...e],s=t.findIndex(e=>e.field===this.groupByField);if(s>0){const[e]=t.splice(s,1);t.unshift(e)}return t}getCompositeColumns(){const e=this.getOrderedColumns(),t=new Map,s=[];return e.forEach(e=>{if(e.fieldCompositeName){if(!t.has(e.fieldCompositeName)){const i={compositeName:e.fieldCompositeName,columns:[]};t.set(e.fieldCompositeName,i),s.push(i)}t.get(e.fieldCompositeName).columns.push(e)}else s.push({compositeName:null,columns:[e]})}),s}getAllColumns(){return this.columns}createTableStructure(e){this.toolbar=e.querySelector(".div-table-toolbar"),this.toolbar||(this.toolbar=document.createElement("div"),this.toolbar.className="div-table-toolbar",e.appendChild(this.toolbar)),this.createToolbarElements(),this.tableContainer=document.createElement("div"),this.tableContainer.className="div-table-container",e.appendChild(this.tableContainer),this.fixedColumns>0?(this.tableContainer.classList.add("has-fixed-columns"),this.createFixedColumnsStructure()):(this.headerContainer=document.createElement("div"),this.headerContainer.className="div-table-header",this.tableContainer.appendChild(this.headerContainer),this.bodyContainer=document.createElement("div"),this.bodyContainer.className="div-table-body",this.tableContainer.appendChild(this.bodyContainer)),this.setupScrollShadow()}createFixedColumnsStructure(){this.columnsWrapper=document.createElement("div"),this.columnsWrapper.className="div-table-columns-wrapper",this.tableContainer.appendChild(this.columnsWrapper),this.fixedSection=document.createElement("div"),this.fixedSection.className="div-table-fixed-section",this.columnsWrapper.appendChild(this.fixedSection),this.fixedHeaderContainer=document.createElement("div"),this.fixedHeaderContainer.className="div-table-header div-table-fixed-header",this.fixedSection.appendChild(this.fixedHeaderContainer),this.fixedBodyContainer=document.createElement("div"),this.fixedBodyContainer.className="div-table-body div-table-fixed-body",this.fixedSection.appendChild(this.fixedBodyContainer),this.scrollSection=document.createElement("div"),this.scrollSection.className="div-table-scroll-section",this.columnsWrapper.appendChild(this.scrollSection),this.scrollHeaderContainer=document.createElement("div"),this.scrollHeaderContainer.className="div-table-header div-table-scroll-header",this.scrollSection.appendChild(this.scrollHeaderContainer),this.scrollBodyContainer=document.createElement("div"),this.scrollBodyContainer.className="div-table-body div-table-scroll-body",this.scrollSection.appendChild(this.scrollBodyContainer),this.headerContainer=this.scrollHeaderContainer,this.bodyContainer=this.scrollBodyContainer,this.setupFixedColumnsScrollSync()}setupFixedColumnsScrollSync(){let e=!1;this.scrollBodyContainer.addEventListener("scroll",()=>{e||(e=!0,this.fixedBodyContainer.scrollTop=this.scrollBodyContainer.scrollTop,this.scrollHeaderContainer.scrollLeft=this.scrollBodyContainer.scrollLeft,requestAnimationFrame(()=>{e=!1}))}),this.fixedBodyContainer.addEventListener("scroll",()=>{e||(e=!0,this.scrollBodyContainer.scrollTop=this.fixedBodyContainer.scrollTop,requestAnimationFrame(()=>{e=!1}))}),this.scrollHeaderContainer.addEventListener("scroll",()=>{e||(e=!0,this.scrollBodyContainer.scrollLeft=this.scrollHeaderContainer.scrollLeft,requestAnimationFrame(()=>{e=!1}))})}getEffectiveFixedColumnCount(){return this.fixedColumns}splitColumnsForFixedLayout(){const e=this.getCompositeColumns(),t=this.getEffectiveFixedColumnCount();return{fixedColumns:e.slice(0,t),scrollColumns:e.slice(t)}}createToolbarElements(){let e=this.toolbar.querySelector(".query-input-container");e||(e=document.createElement("div"),e.className="query-input-container",e.setAttribute("tabindex","0"),this.toolbar.appendChild(e));let t=this.toolbar.querySelector(".info-section");t||(t=document.createElement("div"),t.className="info-section",this.toolbar.appendChild(t)),this.infoSection=t}setupScrollShadow(){const e=this.fixedColumns>0?this.scrollBodyContainer:this.bodyContainer,t=this.fixedColumns>0?this.scrollHeaderContainer:this.headerContainer;e.addEventListener("scroll",()=>{e.scrollTop>0?(t.classList.add("scrolled"),this.fixedColumns>0&&this.fixedHeaderContainer&&this.fixedHeaderContainer.classList.add("scrolled")):(t.classList.remove("scrolled"),this.fixedColumns>0&&this.fixedHeaderContainer&&this.fixedHeaderContainer.classList.remove("scrolled")),this.virtualScrolling&&!this.isLoading&&this.handleVirtualScroll()})}setupQueryEditor(){const e=this.toolbar.querySelector(".query-input-container");if(!e)return;e.className="query-input-container query-inputfield";const t={},s=new Map;if(this.columns.forEach(e=>{e.field&&s.set(e.field,e)}),this.data.length>0){const e=this.data[0],i=new Set;Object.keys(e).forEach(o=>{if(i.has(o))return;const n=s.get(o);if(!n)return;if(n.hidden)return;let a,r;if(i.add(o),a=n.type?n.type:"boolean"==typeof e[o]?"boolean":"number"==typeof e[o]?"number":"string","string"===a){const e=[];this.data.forEach(t=>{const s=t[o];Array.isArray(s)?e.push(...s):e.push(s)});const t=[...new Set(e)],s=t.filter(e=>null!=e&&""!==e);r=t.some(e=>null==e||""===e)?[...s,"NULL"]:s}t[o]={type:a,values:r}}),this.columns.forEach(s=>{if(s.subField&&!s.hidden&&void 0!==e[s.subField]){const o=s.subField;if(i.has(o))return;let n,a;if(i.add(o),n=s.subType?s.subType:"boolean"==typeof e[o]?"boolean":"number"==typeof e[o]?"number":"string","string"===n){const e=[];this.data.forEach(t=>{const s=t[o];Array.isArray(s)?e.push(...s):e.push(s)});const t=[...new Set(e)],s=t.filter(e=>null!=e&&""!==e);a=t.some(e=>null==e||""===e)?[...s,"NULL"]:s}t[o]={type:n,values:a}}})}else this.columns.forEach(e=>{e.field&&!e.hidden&&(t[e.field]={type:e.type||"string",values:e.values||[]}),e.subField&&!e.hidden&&(t[e.subField]={type:e.subType||e.type||"string",values:e.values||[]})});"function"==typeof createQueryEditor&&(this.queryEditor=createQueryEditor(this.monaco,e,{fieldNames:t,initialValue:this.currentQuery,placeholder:this.generateDynamicPlaceholder(t)}),this.queryEditor.fieldNames=t,this.setupQueryEventHandlers())}handleQueryChange(e){void 0===e&&(e=this.queryEditor.model?.getValue()||"");const t=this.queryEditor.editor?.getModel();if(t){const s=this.monaco.editor.getModelMarkers({resource:t.uri}).some(e=>e.severity===this.monaco.MarkerSeverity.Error),i=this.toolbar.querySelector(".query-input-container");s?i.classList.add("error"):(i.classList.remove("error"),this.applyQuery(e))}else this.applyQuery(e)}_setupQueryListeners(){let e;this.queryEditor.model.onDidChangeContent(()=>{e&&clearTimeout(e),e=setTimeout(()=>this.handleQueryChange(),350)})}_shouldUpdateFieldNames(e,t){if(!e||0===Object.keys(e).length)return Object.keys(t).length>0;if(Object.keys(e).length!==Object.keys(t).length)return!0;for(const s in t){if(!e[s])return!0;if(e[s].type!==t[s].type)return!0;const i=e[s].values||[],o=t[s].values||[];if(i.length!==o.length)return!0;const n=[...i].sort(),a=[...o].sort();if(n.some((e,t)=>e!==a[t]))return!0}for(const s in e)if(!t[s])return!0;return!1}generateDynamicPlaceholder(e){if(!e||0===Object.keys(e).length)return"Filter data... (e.g., column > value)";const t=[],s=Object.keys(e);for(const i of s.slice(0,2)){const s=e[i];if("number"===s.type)t.push(`${i} > 100`);else if("boolean"===s.type)t.push(`${i} = true`);else if("string"===s.type)if(s.values&&s.values.length>0){const e=s.values.find(e=>"NULL"!==e)||s.values[0];e&&"NULL"!==e?t.push(`${i} = "${e}"`):t.push(`${i} LIKE "%text%"`)}else t.push(`${i} LIKE "%text%"`)}if(0===t.length)return"Filter data... (e.g., column = value)";const i="Filter data...";return 1===t.length?`${i} (e.g., ${t[0]})`:`${i} (e.g., ${t.slice(0,2).join(" AND ")})`}setupKeyboardNavigation(){const e=this.fixedColumns>0?this.fixedBodyContainer:this.bodyContainer;e.addEventListener("keydown",e=>{this.handleKeyDown(e)}),e.addEventListener("focus",()=>{this.focusedRowId||this.focusFirstRecord()})}getCurrentFocusedElement(){const e=document.activeElement;if(e&&"checkbox"===e.type){const t=e.closest(".div-table-row");if(t&&this.bodyContainer.contains(t))return{element:e,row:t,type:"checkbox"}}return e&&e.classList.contains("div-table-row")&&this.bodyContainer.contains(e)?{element:e,row:e,type:"row"}:null}getFocusableElementForRow(e){if(this.showCheckboxes){const t=e.querySelector('input[type="checkbox"]');if(t)return t}return e}handleKeyDown(e){const t=this.getAllFocusableElements();if(0===t.length)return;const s=this.getCurrentFocusedElement();if(!s)return;let i=t.indexOf(s.element);if(-1!==i)switch(e.key){case"ArrowDown":e.preventDefault(),this.focusElementAtIndex(Math.min(i+1,t.length-1));break;case"ArrowUp":e.preventDefault(),this.focusElementAtIndex(Math.max(i-1,0));break;case"ArrowRight":e.preventDefault(),this.handleRightArrow(s.row);break;case"ArrowLeft":e.preventDefault(),this.handleLeftArrow(s.row);break;case" ":case"Enter":e.preventDefault(),this.handleSelectionToggleForElement(s)}}getAllFocusableElements(){const e=this.fixedColumns>0?this.fixedBodyContainer:this.bodyContainer,t=[],s=Array.from(e.querySelectorAll(".div-table-row"));for(const e of s)if(e.classList.contains("group-header"))if(this.showCheckboxes){const s=e.querySelector('input[type="checkbox"]');s&&"0"===s.getAttribute("tabindex")&&t.push(s)}else t.push(e);else if(e.dataset.id){const s=this.getRowGroupKey(e);if(!s||!this.collapsedGroups.has(s))if(this.showCheckboxes){const s=e.querySelector('input[type="checkbox"]');s&&"0"===s.getAttribute("tabindex")&&t.push(s)}else t.push(e)}return t}focusElementAtIndex(e){const t=this.getAllFocusableElements();if(e>=0&&e<t.length){const s=t[e];s.focus();const i=s.closest(".div-table-row");i&&this.updateFocusState(i)}}updateFocusState(e){if(this.fixedColumns>0){this.fixedBodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>e.classList.remove("focused")),this.scrollBodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>e.classList.remove("focused")),e.classList.add("focused");const t=e.dataset.id||e.dataset.groupKey;if(t){const s=e.dataset.id?`[data-id="${t}"]`:`[data-group-key="${t}"]`;if(e.closest(".div-table-fixed-body")){const e=this.scrollBodyContainer.querySelector(s);e&&e.classList.add("focused")}else if(e.closest(".div-table-scroll-body")){const e=this.fixedBodyContainer.querySelector(s);e&&e.classList.add("focused")}}}else this.bodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>e.classList.remove("focused")),e.classList.add("focused");if(e.classList.contains("group-header")){if(this.focusedRowId=null,this.focusedGroupKey=e.dataset.groupKey,this._lastFocusCallback.groupKey!==e.dataset.groupKey){this._lastFocusCallback={rowId:null,groupKey:e.dataset.groupKey};const t=this.groupData(this.filteredData).find(t=>t.key===e.dataset.groupKey);if(t){const e=this.columns.find(e=>e.field===this.groupByField),s={key:t.key,value:t.value,field:this.groupByField,label:e?.label||this.groupByField,itemCount:t.items.length};"function"==typeof this.onRowFocus&&this.onRowFocus(void 0,s)}}}else if(e.dataset.id&&(this.focusedRowId=e.dataset.id,this.focusedGroupKey=null,this._lastFocusCallback.rowId!==e.dataset.id)){this._lastFocusCallback={rowId:e.dataset.id,groupKey:null};const t=this.findRowData(e.dataset.id);"function"==typeof this.onRowFocus&&this.onRowFocus(t,void 0)}}handleSelectionToggleForElement(e){const t=e.row;t.classList.contains("group-header")?this.toggleGroupSelection(t):t.dataset.id&&this.toggleIndividualRowSelection(t)}handleRightArrow(e){if(e&&e.classList.contains("group-header")&&e.classList.contains("collapsed")){const t=e.dataset.groupKey;this.collapsedGroups.delete(t),e.classList.remove("collapsed");const s={key:t};this.render(),this.restoreGroupFocus(s)}}handleLeftArrow(e){if(e&&e.classList.contains("group-header")&&!e.classList.contains("collapsed")){const t=e.dataset.groupKey;this.collapsedGroups.add(t),e.classList.add("collapsed");const s={key:t};this.render(),this.restoreGroupFocus(s)}}restoreGroupFocus(e){const t=this.bodyContainer.querySelector(`[data-group-key="${e.key}"]`);if(t){if(this.showCheckboxes){const e=t.querySelector('input[type="checkbox"]');e&&e.focus()}else t.focus();this.updateFocusState(t)}}getVisibleRows(){const e=this.fixedColumns>0?this.fixedBodyContainer:this.bodyContainer;return Array.from(e.querySelectorAll(".div-table-row[data-id]:not(.group-header):not(.group-collapsed)"))}getAllFocusableRows(){const e=this.fixedColumns>0?this.fixedBodyContainer:this.bodyContainer,t=Array.from(e.querySelectorAll(".div-table-row")),s=[];for(const e of t)if(e.classList.contains("group-header"))s.push(e);else if(e.dataset.id){const t=this.getRowGroupKey(e);t&&this.collapsedGroups.has(t)||s.push(e)}return s}getRowGroupKey(e){let t=e.previousElementSibling;for(;t;){if(t.classList.contains("group-header"))return t.dataset.groupKey;t=t.previousElementSibling}return null}focusRow(e){const t=this.getAllFocusableElements();e>=0&&e<t.length&&this.focusElementAtIndex(e)}focusFirstRecord(){this.getAllFocusableRows().length>0&&this.focusRow(0)}setFocusedRow(e,t=!1){if(this.bodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>{e.classList.remove("focused")}),e){const s=this.bodyContainer.querySelector(`[data-id="${e}"]`);if(s){if(s.classList.add("focused"),s.scrollIntoView({behavior:"smooth",block:"nearest"}),!t){const e=s.querySelector('input[type="checkbox"]');e&&document.activeElement!==e&&e.focus()}if(this._lastFocusCallback.rowId!==e){this._lastFocusCallback={rowId:e,groupKey:null};const t=this.findRowData(e);this.onRowFocus(t)}}}this.focusedRowId=e}setFocusedGroup(e){this.bodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>{e.classList.remove("focused")}),this.focusedRowId=null;const t=this.bodyContainer.querySelector(`[data-group-key="${e.key}"]`);if(t){t.classList.add("focused"),t.scrollIntoView({behavior:"smooth",block:"nearest"});const s=this.columns.find(e=>e.field===this.groupByField),i={key:e.key,value:e.value,field:this.groupByField,label:s?.label||this.groupByField,itemCount:e.items.length};this.onRowFocus(void 0,i)}}findRowData(e){let t=this.filteredData.find(t=>String(t[this.primaryKeyField])===String(e));return t||(t=this.data.find(t=>String(t[this.primaryKeyField])===String(e))),t}handleSelectionToggle(e){const t=this.getAllFocusableRows();if(e<0||e>=t.length)return;const s=t[e];s.classList.contains("group-header")?this.toggleGroupSelection(s):s.dataset.id&&this.toggleIndividualRowSelection(s)}toggleGroupSelection(e){const t=e.dataset.groupKey,s=this.groupData(this.filteredData).find(e=>e.key===t);if(!s)return;const i=s.items.map(e=>String(e[this.primaryKeyField])),o=i.filter(e=>this.selectedRows.has(e)).length<i.length;s.items.forEach(e=>{const t=String(e[this.primaryKeyField]);o?(this.selectedRows.add(t),e.selected=!0):(this.selectedRows.delete(t),e.selected=!1)}),this.updateSelectionStates(),this.updateInfoSection(),"function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean))}toggleIndividualRowSelection(e){const t=e.dataset.id;if(!t)return void console.warn("DivTable: Row missing data-id attribute");const s=this.findRowData(t);if(!s)return void console.warn("DivTable: Could not find data for row ID:",t);this.selectedRows.has(t)?(this.selectedRows.delete(t),s.selected=!1,e.classList.remove("selected")):(this.multiSelect||this.clearSelection(),this.selectedRows.add(t),s.selected=!0,e.classList.add("selected")),this.updateSelectionStates(),this.updateInfoSection();const i=Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean);"function"==typeof this.onSelectionChange&&this.onSelectionChange(i)}toggleRowSelection(e){const t=this.getVisibleRows();if(e<0||e>=t.length)return;const s=t[e],i=s.dataset.id,o=this.findRowData(i);o&&(this.selectedRows.has(i)?(this.selectedRows.delete(i),o.selected=!1,s.classList.remove("selected")):(this.multiSelect||this.clearSelection(),this.selectedRows.add(i),o.selected=!0,s.classList.add("selected")),this.updateCheckboxes(),"function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean)))}clearSelection(){this.selectedRows.clear(),this.filteredData.forEach(e=>e.selected=!1),this.updateSelectionStates(),this.updateInfoSection()}updateCheckboxes(){this.fixedColumns>0?this.fixedBodyContainer.querySelectorAll('.div-table-row[data-id] input[type="checkbox"]').forEach(e=>{const t=e.closest(".div-table-row").dataset.id;e.checked=this.selectedRows.has(t)}):this.bodyContainer.querySelectorAll('.div-table-row[data-id] input[type="checkbox"]').forEach(e=>{const t=e.closest(".div-table-row").dataset.id;e.checked=this.selectedRows.has(t)})}updateSelectionStates(){if(this.fixedColumns>0)this.updateSelectionStatesWithFixedColumns();else{if(this.bodyContainer.querySelectorAll(".div-table-row[data-id]").forEach(e=>{const t=e.dataset.id,s=e.querySelector('input[type="checkbox"]');this.selectedRows.has(t)?(e.classList.add("selected"),s&&(s.checked=!0)):(e.classList.remove("selected"),s&&(s.checked=!1))}),this.groupByField){const e=this.groupData(this.sortData(this.filteredData));this.bodyContainer.querySelectorAll(".div-table-row.group-header").forEach(t=>{const s=t.querySelector('input[type="checkbox"]');if(!s)return;const i=t.dataset.groupKey,o=e.find(e=>e.key===i);if(!o)return;const n=o.items.map(e=>String(e[this.primaryKeyField])),a=n.filter(e=>this.selectedRows.has(e));0===a.length?(s.checked=!1,s.indeterminate=!1):a.length===n.length?(s.checked=!0,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0)})}this.updateHeaderCheckbox()}}updateSelectionStatesWithFixedColumns(){if(this.fixedBodyContainer.querySelectorAll(".div-table-row[data-id]").forEach(e=>{const t=e.dataset.id,s=e.querySelector('input[type="checkbox"]');this.selectedRows.has(t)?(e.classList.add("selected"),s&&(s.checked=!0)):(e.classList.remove("selected"),s&&(s.checked=!1))}),this.scrollBodyContainer.querySelectorAll(".div-table-row[data-id]").forEach(e=>{const t=e.dataset.id;this.selectedRows.has(t)?e.classList.add("selected"):e.classList.remove("selected")}),this.groupByField){const e=this.groupData(this.sortData(this.filteredData));this.fixedBodyContainer.querySelectorAll(".div-table-row.group-header").forEach(t=>{const s=t.querySelector('input[type="checkbox"]');if(!s)return;const i=t.dataset.groupKey,o=e.find(e=>e.key===i);if(!o)return;const n=o.items.map(e=>String(e[this.primaryKeyField])),a=n.filter(e=>this.selectedRows.has(e));0===a.length?(s.checked=!1,s.indeterminate=!1):a.length===n.length?(s.checked=!0,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0)})}this.updateHeaderCheckbox()}updateHeaderCheckbox(){let e;if(e=this.fixedColumns>0?this.fixedHeaderContainer.querySelector('input[type="checkbox"]'):this.headerContainer.querySelector('input[type="checkbox"]'),!e)return;const t=this.filteredData.length,s=this.filteredData.filter(e=>this.selectedRows.has(String(e[this.primaryKeyField]))).length;0===s?(e.checked=!1,e.indeterminate=!1):s===t?(e.checked=!0,e.indeterminate=!1):(e.checked=!1,e.indeterminate=!0)}updateTabIndexes(){const e=this.fixedColumns>0?this.fixedBodyContainer:this.bodyContainer,t=Array.from(e.querySelectorAll(".div-table-row"));for(const e of t)if(e.classList.contains("group-header")){if(this.showCheckboxes){const t=e.querySelector('input[type="checkbox"]');t&&t.setAttribute("tabindex","0")}}else if(e.dataset.id){const t=this.getRowGroupKey(e),s=!t||!this.collapsedGroups.has(t);if(this.showCheckboxes){const t=e.querySelector('input[type="checkbox"]');t&&t.setAttribute("tabindex",s?"0":"-1")}}}render(){this.renderHeader(),this.renderBody(),this.updateInfoSection(),this.updateSelectionStates(),this.updateTabIndexes(),"undefined"==typeof process&&setTimeout(()=>this.verifyDataConsistency(),0)}renderHeader(){if(this.fixedColumns>0)return void this.renderHeaderWithFixedColumns();this.headerContainer.innerHTML="";const e=this.getCompositeColumns();let t="";if(this.showCheckboxes&&(t="40px "),e.forEach(e=>{switch((e.columns[0].responsive||{}).size){case"fixed-narrow":t+="80px ";break;case"fixed-medium":t+="120px ";break;case"flexible-small":default:t+="1fr ";break;case"flexible-medium":t+="2fr ";break;case"flexible-large":t+="3fr "}}),this.headerContainer.style.gridTemplateColumns=t.trim(),this.showCheckboxes){const e=document.createElement("div");if(e.className="div-table-header-cell checkbox-column",this.multiSelect){const t=document.createElement("input");t.type="checkbox",t.addEventListener("change",e=>{e.target.checked||e.target.indeterminate?this.selectAll():(this.clearSelection(),this.showOnlySelected&&(this.renderBody(),this.updateInfoSection()))}),e.appendChild(t)}this.headerContainer.appendChild(e)}e.forEach(e=>{const t=document.createElement("div");if(t.className="div-table-header-cell",e.compositeName)t.classList.add("composite-header"),this.renderCompositeHeaderCell(t,e);else{t.classList.add("sortable");const s=e.columns[0];this.renderSingleHeaderCell(t,s)}this.headerContainer.appendChild(t)}),this.updateScrollbarSpacer()}renderHeaderWithFixedColumns(){this.fixedHeaderContainer.innerHTML="",this.scrollHeaderContainer.innerHTML="";const{fixedColumns:e,scrollColumns:t}=this.splitColumnsForFixedLayout();let s="";this.showCheckboxes&&(s="40px "),e.forEach(e=>{s+=this.getColumnGridSize(e)+" "}),this.fixedHeaderContainer.style.gridTemplateColumns=s.trim();let i="";if(t.forEach(e=>{i+=this.getColumnGridSize(e)+" "}),this.scrollHeaderInner=document.createElement("div"),this.scrollHeaderInner.className="div-table-scroll-header-inner",this.scrollHeaderInner.style.gridTemplateColumns=i.trim(),this.scrollHeaderContainer.appendChild(this.scrollHeaderInner),this.showCheckboxes){const e=document.createElement("div");if(e.className="div-table-header-cell checkbox-column",this.multiSelect){const t=document.createElement("input");t.type="checkbox",t.addEventListener("change",e=>{e.target.checked||e.target.indeterminate?this.selectAll():(this.clearSelection(),this.showOnlySelected&&(this.renderBody(),this.updateInfoSection()))}),e.appendChild(t)}this.fixedHeaderContainer.appendChild(e)}e.forEach(e=>{const t=this.createHeaderCell(e);this.fixedHeaderContainer.appendChild(t)}),t.forEach(e=>{const t=this.createHeaderCell(e);this.scrollHeaderInner.appendChild(t)}),this.syncFixedColumnsHeaderHeights()}syncFixedColumnsHeaderHeights(){if(!this.fixedColumns||this.fixedColumns<=0)return;if(!this.fixedHeaderContainer||!this.scrollHeaderContainer)return;this.fixedHeaderContainer.style.height="",this.scrollHeaderContainer.style.height="";const e=this.fixedHeaderContainer.offsetHeight,t=this.scrollHeaderContainer.offsetHeight,s=Math.max(e,t);s>0&&(this.fixedHeaderContainer.style.height=`${s}px`,this.scrollHeaderContainer.style.height=`${s}px`)}syncFixedColumnsRowHeights(){if(!this.fixedColumns||this.fixedColumns<=0)return;if(!this.fixedBodyContainer||!this.scrollBodyContainer)return;const e=this.fixedBodyContainer.querySelectorAll(".div-table-row"),t=this.scrollBodyContainer.querySelectorAll(".div-table-row");e.length===t.length&&e.forEach((e,s)=>{const i=t[s];if(!i)return;e.style.height="",i.style.height="";const o=e.offsetHeight,n=i.offsetHeight,a=Math.max(o,n);a>0&&(e.style.height=`${a}px`,i.style.height=`${a}px`)})}syncFixedColumnsColumnWidths(){if(!this.fixedColumns||this.fixedColumns<=0)return;if(!this.scrollHeaderInner||!this.scrollBodyContainer)return;const{scrollColumns:e}=this.splitColumnsForFixedLayout(),t=e.length;if(0===t)return;const s=Array.from(this.scrollHeaderInner.querySelectorAll(".div-table-header-cell")),i=Array.from(this.scrollBodyContainer.querySelectorAll(".div-table-row:not(.group-header)")),o=[];for(let e=0;e<t;e++){let t=0;s[e]&&(s[e].style.minWidth="",s[e].style.width="",t=Math.max(t,s[e].scrollWidth)),i.forEach(s=>{const i=s.querySelectorAll(".div-table-cell");i[e]&&(i[e].style.minWidth="",i[e].style.width="",t=Math.max(t,i[e].scrollWidth))}),o.push(t+4)}const n=o.map(e=>`${e}px`).join(" "),a=o.reduce((e,t)=>e+t,0);this.scrollHeaderInner.style.gridTemplateColumns=n,this.scrollBodyContainer.querySelectorAll(".div-table-row").forEach(e=>{e.classList.contains("group-header")?(e.style.gridTemplateColumns="1fr",e.style.minWidth=`${a}px`):e.style.gridTemplateColumns=n}),this.updateFixedColumnsShadow()}updateFixedColumnsShadow(){!this.fixedColumns||this.fixedColumns<=0||this.scrollBodyContainer&&this.fixedSection&&(this.scrollBodyContainer.scrollWidth>this.scrollBodyContainer.clientWidth?this.fixedSection.classList.add("has-scroll-shadow"):this.fixedSection.classList.remove("has-scroll-shadow"))}getColumnGridSize(e){switch((e.columns[0].responsive||{}).size){case"fixed-narrow":return"80px";case"fixed-medium":return"120px";case"flexible-small":default:return"1fr";case"flexible-medium":return"2fr";case"flexible-large":return"3fr"}}createHeaderCell(e){const t=document.createElement("div");if(t.className="div-table-header-cell",e.compositeName)t.classList.add("composite-header"),this.renderCompositeHeaderCell(t,e);else{t.classList.add("sortable");const s=e.columns[0];this.renderSingleHeaderCell(t,s)}return t}updateScrollbarSpacer(){const e=this.headerContainer.querySelector(".scrollbar-spacer");if(e&&e.remove(),this.bodyContainer.scrollHeight>this.bodyContainer.clientHeight){const e=this.bodyContainer.offsetWidth-this.bodyContainer.clientWidth,t=document.createElement("div");t.className="scrollbar-spacer",t.style.width=`${e}px`;const s=this.headerContainer.style.gridTemplateColumns;this.headerContainer.style.gridTemplateColumns=`${s} ${e}px`,this.headerContainer.appendChild(t)}}renderSingleHeaderCell(e,t){if(t.subLabel){e.classList.add("composite-header"),e.style.display="flex",e.style.flexDirection="column",e.style.gap="0",e.style.padding="8px 12px",e.style.alignItems="flex-start";const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.width="100%",s.style.marginBottom="4px";const i=document.createElement("span");i.className="composite-main-header",i.innerHTML=t.label||t.field,i.style.fontWeight="600",i.style.color="#374151",i.style.textAlign="left",i.style.flex="1",s.appendChild(i);const o=document.createElement("div");if(o.className="header-right-content",o.style.display="flex",o.style.alignItems="center",o.style.gap="4px",o.style.marginLeft="auto",!1!==t.groupable&&!t.hidden){const e=document.createElement("span");e.className="group-indicator",this.groupByField===t.field&&e.classList.add("grouped"),e.textContent=this.groupByField===t.field?"☴":"☷",e.style.cursor="pointer",e.style.fontSize="1em";const s=t.label||t.field;e.title=this.groupByField===t.field?`Grouped by ${s} (click to ungroup)`:`Click to group by ${s}`,e.addEventListener("click",e=>{e.stopPropagation(),this.groupByField===t.field?this.group(""):this.group(t.field)}),o.appendChild(e)}const n=document.createElement("span");n.className="sort-indicator",n.style.marginLeft="4px",this.sortColumn===t.field?(n.classList.add("active"),n.textContent="asc"===this.sortDirection?"↑":"↓"):n.textContent="⇅",o.appendChild(n),s.appendChild(o),e.appendChild(s);const a=document.createElement("div");a.className="composite-sub-header sortable",a.style.display="flex",a.style.alignItems="center",a.style.width="100%",a.style.cursor="pointer",a.style.borderRadius="4px",a.style.transition="background-color 0.2s ease";const r=document.createElement("span");if(r.innerHTML=t.subLabel,r.style.color="#6b7280",r.style.textAlign="left",r.style.flex="1",a.appendChild(r),t.subField){const e=document.createElement("span");e.className="sub-sort-indicator",e.style.marginLeft="4px",this.sortColumn===t.subField?(e.classList.add("active"),e.textContent="asc"===this.sortDirection?"↑":"↓"):e.textContent="⇅",a.appendChild(e),a.addEventListener("mouseenter",()=>{a.style.backgroundColor="#f3f4f6"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"}),a.addEventListener("click",e=>{e.stopPropagation(),this.sort(t.subField)})}return e.appendChild(a),void s.addEventListener("click",e=>{e.target.classList.contains("group-indicator")||e.target.closest(".group-indicator")||this.sort(t.field)})}const s=document.createElement("div");if(s.className="header-left-content",this.groupByField===t.field){const e=this.groupData(this.filteredData),i=e.length,o=t.label||t.field,n=document.createElement("span");n.className="group-toggle-all";const a=e.every(e=>this.collapsedGroups.has(e.key));a&&n.classList.add("collapsed"),n.textContent="❯",n.title=a?"Expand all groups":"Collapse all groups",n.addEventListener("click",t=>{t.stopPropagation(),t.preventDefault(),a?this.collapsedGroups.clear():e.forEach(e=>{this.collapsedGroups.add(e.key)}),this.render()}),s.appendChild(n);const r=document.createElement("span");r.innerHTML=o,s.appendChild(r);const l=document.createElement("span");l.className="group-count",l.innerHTML=`&nbsp;(${i})`,l.style.opacity="0.8",l.style.fontSize="0.9em",l.style.fontWeight="normal",l.title=`${i} distinct value${1===i?"":"s"} in ${o}`,s.appendChild(l)}else{const e=document.createElement("span");e.innerHTML=t.label||t.field,s.appendChild(e)}e.appendChild(s);const i=document.createElement("div");if(i.className="header-right-content",!1!==t.groupable&&!t.hidden){const e=document.createElement("span");e.className="group-indicator",this.groupByField===t.field&&e.classList.add("grouped"),e.textContent=this.groupByField===t.field?"☴":"☷",e.style.cursor="pointer",e.style.fontSize="1em";const s=t.label||t.field;e.title=this.groupByField===t.field?`Grouped by ${s} (click to ungroup)`:`Click to group by ${s}`,e.addEventListener("click",e=>{e.stopPropagation(),this.groupByField===t.field?this.group(""):this.group(t.field)}),i.appendChild(e)}const o=document.createElement("span");if(o.className="sort-indicator",o.style.fontSize="12px",o.style.marginLeft="4px",this.sortColumn===t.field){o.classList.add("active");const s=this.groupByField&&t.field===this.groupByField;s&&"count"===this.sortMode?o.textContent="asc"===this.sortDirection?"↑1":"↓9":s&&"value"===this.sortMode?o.textContent="asc"===this.sortDirection?"↑A":"↓Z":o.textContent="asc"===this.sortDirection?"↑":"↓",e.classList.add("sorted",this.sortDirection)}else o.textContent="⇅";i.appendChild(o),e.appendChild(i),e.addEventListener("click",e=>{e.target.classList.contains("group-indicator")||e.target.classList.contains("group-toggle-all")||e.target.closest(".group-toggle-all")||e.target.closest(".group-indicator")||this.sort(t.field)})}renderCompositeHeaderCell(e,t){e.style.display="flex",e.style.flexDirection="column",e.style.gap="4px",e.style.padding="8px 12px",t.columns.find(e=>this.groupByField===e.field),t.columns.forEach((t,s)=>{const i=document.createElement("div");i.className="composite-sub-header sortable",i.style.display="flex",i.style.alignItems="center",i.style.gap="8px";const o=document.createElement("div");if(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.style.flex="1",this.groupByField===t.field){const e=this.groupData(this.filteredData),s=e.length,i=t.label||t.field,n=document.createElement("span");n.className="group-toggle-all";const a=e.every(e=>this.collapsedGroups.has(e.key));a&&n.classList.add("collapsed"),n.textContent="❯",n.title=a?"Expand all groups":"Collapse all groups",n.addEventListener("click",t=>{t.stopPropagation(),t.preventDefault(),a?this.collapsedGroups.clear():e.forEach(e=>{this.collapsedGroups.add(e.key)}),this.render()}),o.appendChild(n);const r=document.createElement("span");r.innerHTML=i,o.appendChild(r);const l=document.createElement("span");l.className="group-count",l.innerHTML=`&nbsp;(${s})`,l.style.opacity="0.8",l.style.fontSize="0.9em",l.style.fontWeight="normal",l.title=`${s} distinct value${1===s?"":"s"} in ${i}`,o.appendChild(l)}else{const e=document.createElement("span");e.innerHTML=t.label||t.field,o.appendChild(e)}i.appendChild(o);const n=document.createElement("div");if(n.style.display="flex",n.style.alignItems="center",n.style.gap="4px",!1!==t.groupable&&!t.hidden){const e=document.createElement("span");e.className="group-indicator",this.groupByField===t.field&&e.classList.add("grouped"),e.textContent=this.groupByField===t.field?"☴":"☷",e.style.cursor="pointer",e.style.fontSize="1em";const s=t.label||t.field;e.title=this.groupByField===t.field?`Grouped by ${s} (click to ungroup)`:`Click to group by ${s}`,e.addEventListener("click",e=>{e.stopPropagation(),this.groupByField===t.field?this.group(""):this.group(t.field)}),n.appendChild(e)}const a=document.createElement("span");if(a.className="sort-indicator",a.style.marginLeft="4px",this.sortColumn===t.field){a.classList.add("active");const e=this.groupByField&&t.field===this.groupByField;e&&"count"===this.sortMode?a.textContent="asc"===this.sortDirection?"↑1":"↓9":e&&"value"===this.sortMode?a.textContent="asc"===this.sortDirection?"↑A":"↓Z":a.textContent="asc"===this.sortDirection?"↑":"↓",i.classList.add("sorted",this.sortDirection)}else a.textContent="⇅";n.appendChild(a),i.appendChild(n),i.addEventListener("click",e=>{e.target.classList.contains("group-indicator")||e.target.classList.contains("group-toggle-all")||e.target.closest(".group-indicator")||e.target.closest(".group-toggle-all")||this.sort(t.field)}),e.appendChild(i)})}renderBody(){if(this.fixedColumns>0)return void this.renderBodyWithFixedColumns();if(this.bodyContainer.innerHTML="",this.isLoadingState)return void this.showLoadingPlaceholders();let e=this.filteredData;if(this.showOnlySelected&&0===this.selectedRows.size&&(this.showOnlySelected=!1,console.log("👁️ No rows selected - automatically showing all rows")),this.showOnlySelected&&this.selectedRows.size>0&&(e=this.filteredData.filter(e=>{const t=String(e[this.primaryKeyField]);return this.selectedRows.has(t)})),0===e.length){const e=document.createElement("div");return e.className="div-table-empty",e.textContent=this.showOnlySelected&&this.selectedRows.size>0?"No selected rows match current filters":"No data to display",void this.bodyContainer.appendChild(e)}this.groupByField?this.renderGroupedRows(e):this.renderRegularRows(e)}renderBodyWithFixedColumns(){if(this.fixedBodyContainer.innerHTML="",this.scrollBodyContainer.innerHTML="",this.isLoadingState)return void this.showLoadingPlaceholders();let e=this.filteredData;if(this.showOnlySelected&&0===this.selectedRows.size&&(this.showOnlySelected=!1),this.showOnlySelected&&this.selectedRows.size>0&&(e=this.filteredData.filter(e=>{const t=String(e[this.primaryKeyField]);return this.selectedRows.has(t)})),0===e.length){const e=document.createElement("div");return e.className="div-table-empty",e.textContent=this.showOnlySelected&&this.selectedRows.size>0?"No selected rows match current filters":"No data to display",void this.fixedBodyContainer.appendChild(e)}this.groupByField?this.renderGroupedRowsWithFixedColumns(e):this.renderRegularRowsWithFixedColumns(e),this.syncFixedColumnsColumnWidths(),this.syncFixedColumnsRowHeights()}renderRegularRowsWithFixedColumns(e=this.filteredData){this.sortData(e).forEach(e=>{const{fixedRow:t,scrollRow:s}=this.createRowWithFixedColumns(e);this.fixedBodyContainer.appendChild(t),this.scrollBodyContainer.appendChild(s)})}renderGroupedRowsWithFixedColumns(e=this.filteredData){let t=this.groupData(e);this.sortColumn===this.groupByField&&(t=t.sort((e,t)=>{if("count"===this.sortMode){const s=e.items.length-t.items.length;return"desc"===this.sortDirection?-s:s}{if(null==e.value&&null==t.value)return 0;if(null==e.value)return"asc"===this.sortDirection?-1:1;if(null==t.value)return"asc"===this.sortDirection?1:-1;let s=0;return s="number"==typeof e.value&&"number"==typeof t.value?e.value-t.value:String(e.value).localeCompare(String(t.value)),"desc"===this.sortDirection?-s:s}})),t.forEach(e=>{this.sortColumn!==this.groupByField&&(e.items=this.sortData(e.items));const{fixedGroupHeader:t,scrollGroupHeader:s}=this.createGroupHeaderWithFixedColumns(e);this.fixedBodyContainer.appendChild(t),this.scrollBodyContainer.appendChild(s),this.collapsedGroups.has(e.key)||e.items.forEach(e=>{const{fixedRow:t,scrollRow:s}=this.createRowWithFixedColumns(e);this.fixedBodyContainer.appendChild(t),this.scrollBodyContainer.appendChild(s)})})}renderRegularRows(e=this.filteredData){this.sortData(e).forEach(e=>{const t=this.createRow(e);this.bodyContainer.appendChild(t)})}renderGroupedRows(e=this.filteredData){let t=this.groupData(e);this.sortColumn===this.groupByField&&(t=t.sort((e,t)=>{if("count"===this.sortMode){const s=e.items.length-t.items.length;return"desc"===this.sortDirection?-s:s}{if(null==e.value&&null==t.value)return 0;if(null==e.value)return"asc"===this.sortDirection?-1:1;if(null==t.value)return"asc"===this.sortDirection?1:-1;let s=0;return s="number"==typeof e.value&&"number"==typeof t.value?e.value-t.value:String(e.value).localeCompare(String(t.value)),"desc"===this.sortDirection?-s:s}})),t.forEach(e=>{this.sortColumn!==this.groupByField&&(e.items=this.sortData(e.items));const t=this.createGroupHeader(e);this.bodyContainer.appendChild(t),this.collapsedGroups.has(e.key)||e.items.forEach(e=>{const t=this.createRow(e);this.bodyContainer.appendChild(t)})})}createRow(e){const t=document.createElement("div");t.className="div-table-row",t.dataset.id=e[this.primaryKeyField];const s=this.getCompositeColumns();let i="";this.showCheckboxes&&(i="40px "),s.forEach(e=>{switch((e.columns[0].responsive||{}).size){case"fixed-narrow":i+="80px ";break;case"fixed-medium":i+="120px ";break;case"flexible-small":default:i+="1fr ";break;case"flexible-medium":i+="2fr ";break;case"flexible-large":i+="3fr "}}),t.style.gridTemplateColumns=i.trim();const o=String(e[this.primaryKeyField]);if(this.selectedRows.has(o)&&t.classList.add("selected"),this.focusedRowId===o&&t.classList.add("focused"),this.showCheckboxes){const e=document.createElement("div");e.className="div-table-cell checkbox-column";const s=document.createElement("input");s.type="checkbox",s.checked=this.selectedRows.has(o),s.addEventListener("change",e=>{e.stopPropagation();const i=this.findRowData(o);if(!i)return void console.warn("DivTable: Could not find data for row ID:",o);if(s.checked)this.multiSelect||this.clearSelection(),this.selectedRows.add(o),i.selected=!0,t.classList.add("selected");else if(this.selectedRows.delete(o),i.selected=!1,t.classList.remove("selected"),this.showOnlySelected){this.renderBody(),this.updateInfoSection();const e=Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean);return void("function"==typeof this.onSelectionChange&&this.onSelectionChange(e))}this.updateSelectionStates(),this.updateInfoSection();const n=Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean);"function"==typeof this.onSelectionChange&&this.onSelectionChange(n)}),s.addEventListener("focus",e=>{this.updateFocusState(t)}),s.addEventListener("blur",e=>{}),e.appendChild(s),e.addEventListener("click",e=>{e.target!==s&&(e.stopPropagation(),s.click())}),t.appendChild(e)}return s.forEach(s=>{const i=document.createElement("div");if(i.className="div-table-cell",s.compositeName)i.classList.add("composite-cell"),i.style.display="flex",i.style.flexDirection="column",i.style.gap="4px",s.columns.forEach((t,s)=>{const o=document.createElement("div");if(o.className="composite-sub-cell",this.groupByField&&t.field===this.groupByField)o.classList.add("grouped-column"),o.textContent="";else if(t.subField){o.classList.add("composite-column"),o.style.display="flex",o.style.flexDirection="column",o.style.gap="2px";const s=document.createElement("div");s.className="composite-main","function"==typeof t.render?s.innerHTML=t.render(e[t.field],e):s.innerHTML=e[t.field]??"";const i=document.createElement("div");i.className="composite-sub","function"==typeof t.subRender?i.innerHTML=t.subRender(e[t.subField],e):i.innerHTML=e[t.subField]??"",o.appendChild(s),o.appendChild(i)}else"function"==typeof t.render?o.innerHTML=t.render(e[t.field],e):o.innerHTML=e[t.field]??"";i.appendChild(o)});else{const t=s.columns[0];if(this.groupByField&&t.field===this.groupByField)i.classList.add("grouped-column"),i.textContent="";else if(t.subField){i.classList.add("composite-column");const s=document.createElement("div");s.className="composite-main","function"==typeof t.render?s.innerHTML=t.render(e[t.field],e):s.innerHTML=e[t.field]??"";const o=document.createElement("div");o.className="composite-sub","function"==typeof t.subRender?o.innerHTML=t.subRender(e[t.subField],e):o.innerHTML=e[t.subField]??"",i.appendChild(s),i.appendChild(o)}else"function"==typeof t.render?i.innerHTML=t.render(e[t.field],e):i.innerHTML=e[t.field]??""}t.appendChild(i)}),t.addEventListener("click",e=>{if(e.target.closest(".checkbox-column"))return;if(window.getSelection().toString().length>0)return;const s=this.getFocusableElementForRow(t);if(s){if(this.getCurrentFocusedElement()===s)return;const e=this.getAllFocusableElements().indexOf(s);-1!==e&&this.focusElementAtIndex(e)}}),t.addEventListener("focus",e=>{this.updateFocusState(t)}),t}createRowWithFixedColumns(e){const{fixedColumns:t,scrollColumns:s}=this.splitColumnsForFixedLayout(),i=String(e[this.primaryKeyField]),o=document.createElement("div");o.className="div-table-row div-table-fixed-row",o.dataset.id=i;let n="";this.showCheckboxes&&(n="40px "),t.forEach(e=>{n+=this.getColumnGridSize(e)+" "}),o.style.gridTemplateColumns=n.trim();const a=document.createElement("div");a.className="div-table-row div-table-scroll-row",a.dataset.id=i;let r="";if(s.forEach(e=>{r+=this.getColumnGridSize(e)+" "}),a.style.gridTemplateColumns=r.trim(),this.selectedRows.has(i)&&(o.classList.add("selected"),a.classList.add("selected")),this.focusedRowId===i&&(o.classList.add("focused"),a.classList.add("focused")),this.showCheckboxes){const e=document.createElement("div");e.className="div-table-cell checkbox-column";const t=document.createElement("input");t.type="checkbox",t.checked=this.selectedRows.has(i),t.addEventListener("change",e=>{e.stopPropagation();const s=this.findRowData(i);if(!s)return void console.warn("DivTable: Could not find data for row ID:",i);if(t.checked)this.multiSelect||this.clearSelection(),this.selectedRows.add(i),s.selected=!0,o.classList.add("selected"),a.classList.add("selected");else if(this.selectedRows.delete(i),s.selected=!1,o.classList.remove("selected"),a.classList.remove("selected"),this.showOnlySelected){this.renderBody(),this.updateInfoSection();const e=Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean);return void("function"==typeof this.onSelectionChange&&this.onSelectionChange(e))}this.updateSelectionStates(),this.updateInfoSection();const n=Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean);"function"==typeof this.onSelectionChange&&this.onSelectionChange(n)}),t.addEventListener("focus",e=>{this.updateFocusStateForFixedRows(o,a)}),e.appendChild(t),e.addEventListener("click",e=>{e.target!==t&&(e.stopPropagation(),t.click())}),o.appendChild(e)}t.forEach(t=>{const s=this.createCellForComposite(t,e);o.appendChild(s)}),s.forEach(t=>{const s=this.createCellForComposite(t,e);a.appendChild(s)});const l=(e,t)=>{if(e.target.closest(".checkbox-column"))return;if(window.getSelection().toString().length>0)return;const s=this.getFocusableElementForRow(o);if(s){const e=this.getAllFocusableElements().indexOf(s);-1!==e&&this.focusElementAtIndex(e)}};return o.addEventListener("click",e=>l(e)),a.addEventListener("click",e=>l(e)),o.addEventListener("mouseenter",()=>{a.classList.add("hover")}),o.addEventListener("mouseleave",()=>{a.classList.remove("hover")}),a.addEventListener("mouseenter",()=>{o.classList.add("hover")}),a.addEventListener("mouseleave",()=>{o.classList.remove("hover")}),{fixedRow:o,scrollRow:a}}updateFocusStateForFixedRows(e,t){this.fixedBodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>e.classList.remove("focused")),this.scrollBodyContainer.querySelectorAll(".div-table-row.focused").forEach(e=>e.classList.remove("focused")),e.classList.add("focused"),t.classList.add("focused");const s=e.dataset.id;if(s&&(this.focusedRowId=s,this._lastFocusCallback.rowId!==s)){this._lastFocusCallback={rowId:s,groupKey:null};const e=this.findRowData(s);this.onRowFocus(e)}}createCellForComposite(e,t){const s=document.createElement("div");if(s.className="div-table-cell",e.compositeName)s.classList.add("composite-cell"),s.style.display="flex",s.style.flexDirection="column",s.style.gap="4px",e.columns.forEach((e,i)=>{const o=document.createElement("div");if(o.className="composite-sub-cell",this.groupByField&&e.field===this.groupByField)o.classList.add("grouped-column"),o.textContent="";else if(e.subField){o.classList.add("composite-column"),o.style.display="flex",o.style.flexDirection="column",o.style.gap="2px";const s=document.createElement("div");s.className="composite-main","function"==typeof e.render?s.innerHTML=e.render(t[e.field],t):s.innerHTML=t[e.field]??"";const i=document.createElement("div");i.className="composite-sub","function"==typeof e.subRender?i.innerHTML=e.subRender(t[e.subField],t):i.innerHTML=t[e.subField]??"",o.appendChild(s),o.appendChild(i)}else"function"==typeof e.render?o.innerHTML=e.render(t[e.field],t):o.innerHTML=t[e.field]??"";s.appendChild(o)});else{const i=e.columns[0];if(this.groupByField&&i.field===this.groupByField)s.classList.add("grouped-column"),s.textContent="";else if(i.subField){s.classList.add("composite-column");const e=document.createElement("div");e.className="composite-main","function"==typeof i.render?e.innerHTML=i.render(t[i.field],t):e.innerHTML=t[i.field]??"";const o=document.createElement("div");o.className="composite-sub","function"==typeof i.subRender?o.innerHTML=i.subRender(t[i.subField],t):o.innerHTML=t[i.subField]??"",s.appendChild(e),s.appendChild(o)}else"function"==typeof i.render?s.innerHTML=i.render(t[i.field],t):s.innerHTML=t[i.field]??""}return s}createGroupHeaderWithFixedColumns(e){const{fixedColumns:t,scrollColumns:s}=this.splitColumnsForFixedLayout(),i=document.createElement("div");i.className="div-table-row group-header div-table-fixed-row",i.dataset.groupKey=e.key;let o="";this.showCheckboxes&&(o="40px "),t.forEach(e=>{o+=this.getColumnGridSize(e)+" "}),i.style.gridTemplateColumns=o.trim();const n=document.createElement("div");n.className="div-table-row group-header div-table-scroll-row",n.dataset.groupKey=e.key;let a="";if(s.forEach(e=>{a+=this.getColumnGridSize(e)+" "}),n.style.gridTemplateColumns=a.trim(),this.collapsedGroups.has(e.key)&&(i.classList.add("collapsed"),n.classList.add("collapsed")),this.showCheckboxes){const t=document.createElement("div");t.className="div-table-cell checkbox-column";const s=document.createElement("input");s.type="checkbox";const o=e.items.map(e=>String(e[this.primaryKeyField])),a=o.filter(e=>this.selectedRows.has(e));0===a.length?(s.checked=!1,s.indeterminate=!1):a.length===o.length?(s.checked=!0,s.indeterminate=!1):(s.checked=!1,s.indeterminate=!0),s.addEventListener("change",t=>{t.stopPropagation();const s=0===o.filter(e=>this.selectedRows.has(e)).length;if(e.items.forEach(e=>{const t=String(e[this.primaryKeyField]);s?(this.selectedRows.add(t),e.selected=!0):(this.selectedRows.delete(t),e.selected=!1)}),this.showOnlySelected)return this.renderBody(),this.updateInfoSection(),void("function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean)));this.updateSelectionStates(),this.updateInfoSection(),"function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean))}),s.addEventListener("focus",e=>{this.updateFocusStateForFixedRows(i,n)}),t.appendChild(s),i.appendChild(t)}const r=document.createElement("div");r.className="div-table-cell",r.style.gridColumn=this.showCheckboxes?"2 / -1":"1 / -1",r.style.display="flex",r.style.alignItems="center",r.style.gap="8px";const l=document.createElement("span");l.className="group-toggle",this.collapsedGroups.has(e.key)&&l.classList.add("collapsed"),l.textContent="❯",l.title=this.collapsedGroups.has(e.key)?"Expand group":"Collapse group";const d=this.columns.find(e=>e.field===this.groupByField),c=d?.label||this.groupByField;let h;h=null==e.value||""===e.value?`${c} is undefined`:d&&"function"==typeof d.render?d.render(e.value,null):e.value,r.appendChild(l);const u=document.createElement("span");"string"==typeof h?u.innerHTML=h:u.textContent=h,r.appendChild(u);const p=document.createElement("span");p.className="group-item-count",p.innerHTML=`(${e.items.length})`,p.style.opacity="0.8",p.style.fontSize="0.9em",p.style.fontWeight="normal",p.title=`${e.items.length} item${1===e.items.length?"":"s"} in this group`,r.appendChild(p),i.appendChild(r);const f=document.createElement("div");return f.className="div-table-cell",f.style.gridColumn="1 / -1",n.appendChild(f),l.addEventListener("click",t=>{t.stopPropagation(),t.preventDefault(),this.collapsedGroups.has(e.key)?(this.collapsedGroups.delete(e.key),i.classList.remove("collapsed"),n.classList.remove("collapsed")):(this.collapsedGroups.add(e.key),i.classList.add("collapsed"),n.classList.add("collapsed")),this.render()}),i.addEventListener("mouseenter",()=>{n.classList.add("hover")}),i.addEventListener("mouseleave",()=>{n.classList.remove("hover")}),n.addEventListener("mouseenter",()=>{i.classList.add("hover")}),n.addEventListener("mouseleave",()=>{i.classList.remove("hover")}),{fixedGroupHeader:i,scrollGroupHeader:n}}createGroupHeader(e){const t=document.createElement("div");t.className="div-table-row group-header",t.dataset.groupKey=e.key;const s=this.getOrderedColumns();let i="";if(this.showCheckboxes&&(i="40px "),s.forEach(e=>{switch((e.responsive||{}).size){case"fixed-narrow":i+="80px ";break;case"fixed-medium":i+="120px ";break;case"flexible-small":default:i+="1fr ";break;case"flexible-medium":i+="2fr ";break;case"flexible-large":i+="3fr "}}),t.style.gridTemplateColumns=i.trim(),this.collapsedGroups.has(e.key)&&t.classList.add("collapsed"),this.showCheckboxes){const s=document.createElement("div");s.className="div-table-cell checkbox-column";const i=document.createElement("input");i.type="checkbox";const o=e.items.map(e=>String(e[this.primaryKeyField])),n=o.filter(e=>this.selectedRows.has(e));0===n.length?(i.checked=!1,i.indeterminate=!1):n.length===o.length?(i.checked=!0,i.indeterminate=!1):(i.checked=!1,i.indeterminate=!0),i.addEventListener("change",t=>{t.stopPropagation();const s=0===e.items.map(e=>String(e[this.primaryKeyField])).filter(e=>this.selectedRows.has(e)).length;if(e.items.forEach(e=>{const t=String(e[this.primaryKeyField]);s?(this.selectedRows.add(t),e.selected=!0):(this.selectedRows.delete(t),e.selected=!1)}),this.showOnlySelected)return this.renderBody(),this.updateInfoSection(),void("function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean)));this.updateSelectionStates(),this.updateInfoSection(),"function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean))}),i.addEventListener("focus",e=>{this.updateFocusState(t)}),s.appendChild(i),t.appendChild(s)}const o=document.createElement("div");o.className="div-table-cell",o.style.gridColumn=this.showCheckboxes?"2 / -1":"1 / -1",o.style.display="flex",o.style.alignItems="center",o.style.gap="8px";const n=document.createElement("span");n.className="group-toggle",this.collapsedGroups.has(e.key)&&n.classList.add("collapsed"),n.textContent="❯",n.title=this.collapsedGroups.has(e.key)?"Expand group":"Collapse group";const a=this.columns.find(e=>e.field===this.groupByField),r=a?.label||this.groupByField;let l;l=null==e.value||""===e.value?`${r} is undefined`:a&&"function"==typeof a.render?a.render(e.value,null):e.value,o.appendChild(n);const d=document.createElement("span");"string"==typeof l?d.innerHTML=l:d.textContent=l,o.appendChild(d);const c=document.createElement("span");return c.className="group-item-count",c.innerHTML=`(${e.items.length})`,c.style.opacity="0.8",c.style.fontSize="0.9em",c.style.fontWeight="normal",c.title=`${e.items.length} item${1===e.items.length?"":"s"} in this group`,o.appendChild(c),t.appendChild(o),n.addEventListener("click",s=>{s.stopPropagation(),s.preventDefault(),this.collapsedGroups.has(e.key)?(this.collapsedGroups.delete(e.key),t.classList.remove("collapsed")):(this.collapsedGroups.add(e.key),t.classList.add("collapsed")),this.render(),setTimeout(()=>{const t=this.bodyContainer.querySelector(`[data-group-key="${e.key}"]`);if(t){const e=this.getFocusableElementForRow(t);if(e){const t=this.getAllFocusableElements().indexOf(e);-1!==t&&this.focusElementAtIndex(t)}}},0)}),t.addEventListener("click",e=>{if(e.target.closest(".checkbox-column"))return;if(window.getSelection().toString().length>0)return;const s=this.getFocusableElementForRow(t);if(s){if(this.getCurrentFocusedElement()===s)return;const e=this.getAllFocusableElements().indexOf(s);-1!==e&&this.focusElementAtIndex(e)}}),t.addEventListener("focus",e=>{this.updateFocusState(t)}),t}groupData(e){const t=new Map;return e.forEach(e=>{const s=e[this.groupByField];let i,o;Array.isArray(s)?(i=s.length>0?s.join(", "):"__null__",o=s.length>0?s.join(", "):null):(i=s??"__null__",o=s),t.has(i)||t.set(i,{key:i,value:o,items:[]}),t.get(i).items.push(e)}),Array.from(t.values()).sort((e,t)=>null==e.value?1:null==t.value?-1:String(e.value).localeCompare(String(t.value)))}sortData(e){return this.sortColumn?[...e].sort((e,t)=>{const s=e[this.sortColumn],i=t[this.sortColumn];if(null==s&&null==i)return 0;if(null==s)return"asc"===this.sortDirection?-1:1;if(null==i)return"asc"===this.sortDirection?1:-1;let o=0;return o="number"==typeof s&&"number"==typeof i?s-i:String(s).localeCompare(String(i)),"desc"===this.sortDirection?-o:o}):e}selectAll(){this.selectedRows.clear(),this.filteredData.forEach(e=>{const t=String(e[this.primaryKeyField]);this.selectedRows.add(t),e.selected=!0}),this.updateSelectionStates(),this.updateInfoSection(),"function"==typeof this.onSelectionChange&&this.onSelectionChange(Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean))}updateInfoSection(){if(!this.infoSection)return;const e=this.virtualScrolling?this.totalRecords:this.data.length,t=this.data.length,s=this.filteredData.length,i=this.selectedRows.size;this.infoSection.innerHTML="";const o=document.createElement("div");if(o.className="info-line-container",i>0){const e=document.createElement("div");e.className="info-line";const t=this.createFilterSelectedOnlyToggleButton();e.appendChild(t);const s=document.createElement("span");s.className="info-selection",s.textContent=`${i} selected`,e.appendChild(s),o.appendChild(e)}if(this.showAutoFetchButton&&this.virtualScrolling&&(this.hasMoreData||this.isAutoFetching)){const e=this.createAutoFetchButton();e.disabled=!1,o.appendChild(e)}if(this.showRefreshButton){const e=this.createRefreshButton();this.isLoading||this.isLoadingState?(e.classList.add("refreshing"),e.disabled=!0,e.title="Loading data..."):(e.classList.remove("refreshing"),e.disabled=!1,e.title="Refresh data"),o.appendChild(e)}o.children.length>0&&this.infoSection.appendChild(o);const n=document.createElement("div");n.className="info-line secondary";const a=document.createElement("span");a.className="info-stats";let r="";r=this.virtualScrolling?s<t?t<e?`${s} filtered (${Math.round(t/e*100)}% of ${e} total)`:`${s} filtered (${e} total)`:t<e?`${Math.round(t/e*100)}% of ${e} total`:`${e} total`:s<e?`${s} filtered (${e} total)`:`${e} total`,a.textContent=r,n.appendChild(a),this.infoSection.appendChild(n),this.createProgressBar(t,e,s)}createProgressBar(e,t,s){const i=document.createElement("div");i.className="progress-line";const o=this.virtualScrolling?this.totalRecords:this.data.length,n=this.virtualScrolling&&e<o;if(n||s<o){const t=document.createElement("div");t.className="loading-progress";const a=Math.ceil(.1*o),r=this.pageSize||50,l=Math.max(r,Math.min(a,100)),d=e<o?Math.min(o,e+l):e,c=s/o*100,h=e/o*100,u=d/o*100,p=s<e&&this.currentQuery&&""!==this.currentQuery.trim();if(p){if(s>0){const e=document.createElement("div");e.className="progress-segment filtered-segment",e.style.width=`${c}%`,e.style.opacity="1",t.appendChild(e)}if(e>s){const e=document.createElement("div");e.className="progress-segment loaded-segment",e.style.left=`${c}%`,e.style.width=h-c+"%",e.style.opacity="0.8",t.appendChild(e)}}else if(e>0){const e=document.createElement("div");e.className="progress-segment loaded-segment",e.style.width=`${h}%`,e.style.opacity="1",t.appendChild(e)}if(this.hasMoreData&&(this.isLoading||this.isAutoFetching&&!this.autoFetchPaused)&&e<o&&d>e){const e=document.createElement("div");e.className="progress-segment loading-segment",e.style.left=`${h}%`,e.style.width=u-h+"%",t.appendChild(e)}p&&n?t.setAttribute("data-state","filtered-loading"):p?t.setAttribute("data-state","filtered"):n&&t.setAttribute("data-state","sequential-loading"),i.appendChild(t),this.infoSection.appendChild(i)}}createRefreshButton(){const e=document.createElement("button");return e.className="refresh-button",e.type="button",e.title="Refresh data",e.setAttribute("aria-label","Refresh table data"),e.innerHTML='\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M23 4v6h-6"></path>\n <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>\n </svg>\n ',e.addEventListener("click",async t=>{t.preventDefault(),t.stopPropagation(),e.classList.add("refreshing");try{await this.refresh()}catch(e){}finally{setTimeout(()=>{e.classList.remove("refreshing")},500)}}),e}createAutoFetchButton(){const e=document.createElement("button");e.className="auto-fetch-button",e.type="button",e.title="Auto-fetch all pages",e.setAttribute("aria-label","Automatically fetch all remaining pages");const t=t=>{this.isAutoFetching&&!t?(e.innerHTML='\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <rect x="6" y="4" width="4" height="16"></rect>\n <rect x="14" y="4" width="4" height="16"></rect>\n </svg>\n ',e.title="Pause auto-fetch",e.classList.add("active"),e.classList.remove("paused")):(e.innerHTML='\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="5 3 19 12 5 21 5 3"></polygon>\n </svg>\n ',e.classList.remove("active"),t?(e.title="Resume auto-fetch (waiting for current page to complete)",e.classList.add("paused")):(e.title="Auto-fetch all pages",e.classList.remove("paused")))};return t(this.autoFetchPaused),e.addEventListener("click",async e=>{e.preventDefault(),e.stopPropagation(),this.isAutoFetching?(this.autoFetchPaused=!this.autoFetchPaused,t(this.autoFetchPaused),this.autoFetchPaused||this.continueAutoFetch()):this.startAutoFetch(t)}),this.autoFetchButton=e,this.updateAutoFetchButtonIcon=t,e}async startAutoFetch(e){if(this.virtualScrolling&&this.hasMoreData&&!this.isAutoFetching){this.isAutoFetching=!0,this.autoFetchPaused=!1,e(!1),console.log("🚀 Starting auto-fetch...");try{await this.continueAutoFetch()}catch(e){console.error("❌ Auto-fetch error:",e),this.stopAutoFetch()}}}async continueAutoFetch(){for(;this.hasMoreData&&this.isAutoFetching&&!this.autoFetchPaused&&(await this.loadNextPage(),this.hasMoreData&&this.isAutoFetching&&!this.autoFetchPaused)&&(await new Promise(e=>{this.autoFetchTimeout=setTimeout(e,this.autoFetchDelay)}),!this.autoFetchPaused););this.hasMoreData?this.autoFetchPaused&&(this.updateAutoFetchButtonIcon&&this.updateAutoFetchButtonIcon(!0),this.updateInfoSection()):this.stopAutoFetch()}stopAutoFetch(){this.isAutoFetching=!1,this.autoFetchPaused=!1,this.autoFetchTimeout&&(clearTimeout(this.autoFetchTimeout),this.autoFetchTimeout=null),this.updateAutoFetchButtonIcon&&(this.updateAutoFetchButtonIcon(!1),this.autoFetchButton?.classList.remove("active","paused")),this.updateInfoSection()}createFilterSelectedOnlyToggleButton(){const e=document.createElement("button");e.className="filter-selected-only-toggle-button",e.type="button";const t=()=>{this.showOnlySelected?(e.innerHTML='\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>\n <circle cx="12" cy="12" r="3"></circle>\n </svg>\n ',e.title="Show all rows",e.classList.add("active")):(e.innerHTML='\n <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>\n <circle cx="12" cy="12" r="3"></circle>\n </svg>\n ',e.title="Show only selected rows",e.classList.remove("active"))};return t(),e.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.showOnlySelected=!this.showOnlySelected,t(),this.render(),console.log(this.showOnlySelected?"👁️ Showing only selected rows":"👁️ Showing all rows")}),e}updateInfoSectionWithAnticipatedProgress(){if(!this.infoSection||!this.virtualScrolling)return;const e=this.totalRecords,t=this.data.length,s=this.filteredData.length,i=this.selectedRows.size,o=Math.min(t+this.pageSize,e);this.infoSection.innerHTML="";const n=document.createElement("div");if(n.className="info-line-container",i>0){const e=document.createElement("div");e.className="info-line";const t=document.createElement("span");t.className="info-selection",t.textContent=`${i} selected`,e.appendChild(t),n.appendChild(e)}if(this.showAutoFetchButton&&this.virtualScrolling&&(this.hasMoreData||this.isAutoFetching)){const e=this.createAutoFetchButton();e.disabled=this.autoFetchPaused,n.appendChild(e)}if(this.showRefreshButton){const e=this.createRefreshButton();e.classList.add("refreshing"),e.disabled=!0,e.title="Loading data...",n.appendChild(e)}n.children.length>0&&this.infoSection.appendChild(n);const a=document.createElement("div");a.className="info-line secondary";const r=document.createElement("span");r.className="info-stats";let l="";l=s<t?o<e?`${s} filtered (${Math.round(o/e*100)}% of ${e} total)`:`${s} filtered (${e} total)`:o<e?`${Math.round(o/e*100)}% of ${e} total`:`${e} total`,r.textContent=l,a.appendChild(r),this.infoSection.appendChild(a),this.createProgressBar(o,e,s)}applyQuery(e){if(this.currentQuery=e,this.queryEditor?.editor&&this.queryEditor.editor.getValue()!==e&&this.queryEditor.editor.setValue(e),e.trim())try{const t=this.queryEngine.filterObjects(e);this.filteredData=this.data.filter(e=>t.includes(e[this.primaryKeyField]))}catch(e){this.filteredData=[...this.data]}else this.filteredData=[...this.data];this.render()}sort(e,t){this.groupByField&&e===this.groupByField?this.sortColumn===e?"value"===this.sortMode&&"asc"===this.sortDirection?this.sortDirection="desc":"value"===this.sortMode&&"desc"===this.sortDirection?(this.sortMode="count",this.sortDirection="asc"):"count"===this.sortMode&&"asc"===this.sortDirection?this.sortDirection="desc":(this.sortColumn=null,this.sortDirection="asc",this.sortMode="value"):(this.sortColumn=e,this.sortDirection="asc",this.sortMode="value"):this.sortColumn===e?this.sortDirection="asc"===this.sortDirection?"desc":"asc":(this.sortColumn=e,this.sortDirection=t||"asc",this.sortMode="value"),this.render()}group(e){if(e){const t=this.columns.find(t=>t.field===e);if(!t)return void console.warn(`DivTable: Cannot group by field '${e}' - field not found in columns`);if(t.hidden)return void console.warn(`DivTable: Cannot group by field '${e}' - hidden columns cannot be used for grouping`);if(!1===t.groupable)return void console.warn(`DivTable: Cannot group by field '${e}' - column is marked as not groupable`)}this.groupByField=e||null,e?(this.collapsedGroups.clear(),this.groupData(this.filteredData).forEach(e=>{this.collapsedGroups.add(e.key)})):this.collapsedGroups.clear(),this.render()}clearGrouping(){this.group(null)}addRecord(e){if(!e||"object"!=typeof e)return console.warn("addRecord requires a valid record object"),!1;if(!e[this.primaryKeyField])return console.warn(`addRecord: Record must have a ${this.primaryKeyField} field`),!1;const t=String(e[this.primaryKeyField]),s=this.data.findIndex(e=>String(e[this.primaryKeyField])===t);return s>=0?(this.data[s]={...e},console.log(`addRecord: Updated existing record with ${this.primaryKeyField} '${t}'`)):(this.data.push(e),console.log(`addRecord: Added new record with ${this.primaryKeyField} '${t}'`)),this.isLoadingState=!1,this.queryEngine.setObjects(this.data),this.updateQueryEditorIfNeeded(),this.applyQuery(this.currentQuery),!0}removeRecord(e){if(null==e)return console.warn("removeRecord requires a valid ID"),!1;const t=String(e),s=this.data.findIndex(e=>String(e[this.primaryKeyField])===t);if(s>=0){const e=this.data[s];return this.data.splice(s,1),this.selectedRows.delete(t),this.queryEngine.setObjects(this.data),this.updateQueryEditorIfNeeded(),this.applyQuery(this.currentQuery),e}return console.warn(`removeRecord: Record with ${this.primaryKeyField} '${t}' not found`),!1}getSelectedRows(){return Array.from(this.selectedRows).map(e=>this.findRowData(e)).filter(Boolean)}toggleSelectedRowsFilter(e){return this.showOnlySelected=void 0!==e?e:!this.showOnlySelected,this.render(),console.log(this.showOnlySelected?"👁️ Showing only selected rows":"👁️ Showing all rows"),this.showOnlySelected}async refresh(){this.isAutoFetching&&this.stopAutoFetch();try{if(this.virtualScrolling&&"function"==typeof this.onNextPage){this.currentQuery,this.queryEditor?.editor&&this.queryEditor.editor.getValue();const e=new Set(this.selectedRows);this.isLoadingState=!0,this.data=[],this.filteredData=[],this.currentPage=0,this.isLoading=!0,this.hasMoreData=!0,this.queryEngine.setObjects([]),this.render();const t=0,s=await this.onNextPage(t,this.pageSize);if(this.isLoading=!1,s&&Array.isArray(s)&&s.length>0){this.replaceData(s),this.selectedRows.clear();for(const t of e)this.data.some(e=>String(e[this.primaryKeyField])===t)&&this.selectedRows.add(t);this.render()}else this.isLoadingState=!1,this.render()}else"function"==typeof this.onRefresh?(this.showLoadingPlaceholder&&(this.isLoadingState=!0,this.render()),await Promise.resolve(this.onRefresh()),this.isLoadingState&&(this.isLoadingState=!1,this.render())):console.log("ℹ️ Refresh: No onRefresh callback provided for non-virtual scrolling table")}catch(e){throw console.error("❌ Refresh error:",e),this.isLoadingState=!1,this.render(),e}}updateQueryEditorIfNeeded(){if(!this.queryEditor||!this.queryEditor.editor)return;if(0===this.data.length)return;const e=this.queryEditor.editor.getFieldNames()||{},t=new Set(this.columns.filter(e=>e.field).map(e=>e.field)),s={};Object.keys(e).forEach(i=>{t.has(i)&&(s[i]=e[i])});const i={...s};if(this.data.length>0&&this.columns.forEach(e=>{const t=e.field;if(t&&s[t]){const o=s[t],n=e.type||o.type;if("string"===n&&void 0!==o.values){const e=[];this.data.forEach(s=>{const i=s[t];Array.isArray(i)?e.push(...i):e.push(i)});const s=[...new Set(e)],a=s.filter(e=>null!=e&&""!==e),r=s.some(e=>null==e||""===e),l=o.values.filter(e=>"NULL"!==e),d=[...new Set([...l,...a])];i[t]={type:n,values:r?[...d,"NULL"]:d}}else i[t]={type:n}}}),this._shouldUpdateFieldNames(s,i))try{this.queryEditor.editor.updateFieldNames(i)||console.warn("⚠️ Failed to update query editor field values - dynamic update not available")}catch(e){console.warn("⚠️ Error updating query editor field values:",e)}}setupQueryEventHandlers(){setTimeout(()=>{const e=this.queryEditor.model?.getValue();""===e&&this.monaco.editor.setModelMarkers(this.queryEditor.model,this.queryEditor.model.getLanguageId(),[])},10),this.queryEditor.model&&this.queryEditor.model.onDidChangeContent(()=>{const e=this.queryEditor.model.getValue();this.handleQueryChange(e)}),this._setupQueryListeners()}verifyDataConsistency(){const e=[];for(const t of this.selectedRows)this.findRowData(t)||e.push(`Selected row ${t} not found in data`);const t=Array.from(this.bodyContainer.querySelectorAll(".div-table-row[data-id]")).map(e=>e.dataset.id);for(const s of t)this.findRowData(s)||e.push(`Displayed row ${s} not found in data`);return e.length>0&&console.warn("DivTable data consistency issues:",e),0===e.length}testGroupSelectionStates(){if(!this.groupByField)return void console.log("No grouping applied");const e=this.groupData(this.sortData(this.filteredData));console.log("Group selection states:"),e.forEach(e=>{const t=e.items.map(e=>String(e[this.primaryKeyField])),s=t.filter(e=>this.selectedRows.has(e));let i="none";s.length===t.length?i="all":s.length>0&&(i="partial"),console.log(`Group "${e.value}": ${s.length}/${t.length} selected (${i})`)})}handleVirtualScroll(){const e=this.bodyContainer.scrollTop,t=this.bodyContainer.scrollHeight,s=(e+this.bodyContainer.clientHeight)/t,i=this.filteredData.length;Math.floor(s*i)>=i-this.loadingThreshold&&this.hasMoreData&&!this.isLoading&&this.loadNextPage()}async loadNextPage(){if(!this.isLoading&&this.hasMoreData){this.isLoading=!0,this.showLoadingPlaceholders(),this.updateInfoSectionWithAnticipatedProgress();try{const e=this.currentPage+1,t=await this.onNextPage(e,this.pageSize);if(this.isLoading=!1,this.hideLoadingPlaceholders(),t&&Array.isArray(t)&&t.length>0){const s=this.appendData(t,!0);(s.added>0||s.updated>0)&&(this.currentPage=e),this.totalRecords&&this.totalRecords>0?this.hasMoreData=this.data.length<this.totalRecords:this.hasMoreData=t.length===this.pageSize,t.length<this.pageSize&&(this.hasMoreData=!1)}else this.hasMoreData=!1}catch(e){console.error("❌ Error loading next page:",e),this.isLoading=!1,this.hideLoadingPlaceholders(),this.showErrorIndicator()}finally{this.updateInfoSection()}}}showErrorIndicator(){let e=this.bodyContainer.querySelector(".error-indicator");e||(e=document.createElement("div"),e.className="error-indicator",e.innerHTML='\n <span>Error loading data. Please try again.</span>\n <button class="retry-button">Retry</button>\n ',e.querySelector(".retry-button").addEventListener("click",()=>{this.hideErrorIndicator(),this.loadNextPage()}),this.bodyContainer.appendChild(e)),e.style.display="flex"}hideErrorIndicator(){const e=this.bodyContainer.querySelector(".error-indicator");e&&(e.style.display="none")}showLoadingPlaceholders(){if(this.showLoadingPlaceholder){this.hideLoadingPlaceholders();for(let e=0;e<3;e++){const e=this.createLoadingPlaceholderRow();this.bodyContainer.appendChild(e)}}}hideLoadingPlaceholders(){this.bodyContainer.querySelectorAll(".div-table-row.loading-placeholder").forEach(e=>e.remove())}createLoadingPlaceholderRow(){const e=document.createElement("div");e.className="div-table-row loading-placeholder";const t=this.getOrderedColumns();let s="";if(this.showCheckboxes&&(s="40px "),t.forEach(e=>{if(this.groupByField&&e.field===this.groupByField)s+="100px ";else switch((e.responsive||{}).size){case"fixed-narrow":s+="80px ";break;case"fixed-medium":s+="120px ";break;case"flexible-small":default:s+="1fr ";break;case"flexible-medium":s+="2fr ";break;case"flexible-large":s+="3fr "}}),e.style.gridTemplateColumns=s.trim(),this.showCheckboxes){const t=document.createElement("div");t.className="div-table-cell checkbox-column loading-cell",e.appendChild(t)}return t.forEach(t=>{const s=document.createElement("div");s.className="div-table-cell loading-cell";const i=document.createElement("div");i.className="loading-shimmer-content";const o=60+30*Math.random();i.style.width=`${o}%`,s.appendChild(i),e.appendChild(s)}),e}clearRefreshButtonLoadingState(){if(this.showRefreshButton){const e=this.infoSection.querySelector(".refresh-button");e&&(e.classList.remove("refreshing"),e.disabled=!1,e.title="Refresh data")}}setTotalRecords(e){"number"!=typeof e||e<0?console.warn("DivTable: totalRecords must be a non-negative number"):(this.totalRecords=e,this.hasMoreData=this.data.length<e,this.updateInfoSection(),console.log(`DivTable: Updated totalRecords to ${e}, hasMoreData: ${this.hasMoreData}`))}setPageSize(e){if("number"!=typeof e||e<=0)return void console.warn("DivTable: pageSize must be a positive number");const t=this.pageSize;this.pageSize=e,this.loadingThreshold=Math.floor(.8*this.pageSize),this.visibleEndIndex=Math.min(this.visibleStartIndex+this.pageSize,this.data.length),this.updateInfoSection(),console.log(`DivTable: Updated pageSize from ${t} to ${e}, loadingThreshold: ${this.loadingThreshold}`)}setVirtualScrollingConfig({totalRecords:e,pageSize:t,loadingThreshold:s}){let i=!1;"number"==typeof e&&e>=0&&(this.totalRecords=e,this.hasMoreData=this.data.length<e,i=!0),"number"==typeof t&&t>0&&(this.pageSize=t,this.visibleEndIndex=Math.min(this.visibleStartIndex+this.pageSize,this.data.length),i=!0),"number"==typeof s&&s>0?(this.loadingThreshold=s,i=!0):"number"==typeof t&&(this.loadingThreshold=Math.floor(.8*this.pageSize),i=!0),i&&(this.updateInfoSection(),console.log(`DivTable: Updated virtual scrolling config - totalRecords: ${this.totalRecords}, pageSize: ${this.pageSize}, loadingThreshold: ${this.loadingThreshold}`))}setHasMoreData(e){this.hasMoreData=e}resetPagination(){this.currentPage=0,this.isLoading=!1,this.hasMoreData=!0,this.data=this.data.slice(0,this.pageSize),this.filteredData=[...this.data],this.hideErrorIndicator(),this.render()}appendData(e,t=!1){if(!e||!Array.isArray(e))return console.warn("appendData requires a valid array"),{added:0,updated:0,skipped:0,invalid:[]};const s=[];let i=0,o=0;for(const t of e){if(!t||"object"!=typeof t){s.push(t),console.warn("appendData: Skipping invalid record",t);continue}if(!t[this.primaryKeyField]){s.push(t),console.warn(`appendData: Skipping record without ${this.primaryKeyField}`,t);continue}const e=String(t[this.primaryKeyField]),n=this.data.findIndex(t=>String(t[this.primaryKeyField])===e);n>=0?(this.data[n]={...t},o++):(this.data.push(t),i++)}return(i>0||o>0)&&(this.isLoadingState=!1,this.queryEngine.setObjects(this.data),this.updateQueryEditorIfNeeded(),this.currentQuery.trim()?this.applyQuery(this.currentQuery):this.filteredData=[...this.data],t||this.updateInfoSection(),this.render()),{added:i,updated:o,skipped:s.length,invalid:s}}replaceData(e){if(!e||!Array.isArray(e))return console.warn("replaceData requires a valid array"),{success:!1,message:"Invalid data provided"};const t=[],s=new Set,i=[];for(const o of e){if(!o||"object"!=typeof o){console.warn("replaceData: Skipping invalid record",o);continue}if(!o[this.primaryKeyField]){console.warn(`replaceData: Skipping record without ${this.primaryKeyField}`,o);continue}const e=String(o[this.primaryKeyField]);s.has(e)?(t.push(e),console.warn(`replaceData: Skipping duplicate ${this.primaryKeyField} '${e}' within new data`)):(s.add(e),i.push(o))}return this.data=i,this.isLoadingState=!1,this.clearRefreshButtonLoadingState(),this.queryEngine.setObjects(this.data),this.updateQueryEditorIfNeeded(),this.currentQuery&&this.currentQuery.trim()?this.applyQuery(this.currentQuery):this.filteredData=[...this.data],this.selectedRows.clear(),this.virtualScrollingState={scrollTop:0,displayStartIndex:0,displayEndIndex:Math.min(this.pageSize,this.data.length),isLoading:!1},this.currentPage=0,this.startId=1,this.virtualScrolling&&this.totalRecords&&(this.hasMoreData=i.length<this.totalRecords),this.updateInfoSection(),this.render(),{success:!0,totalProvided:e.length,validRecords:i.length,skipped:e.length-i.length,duplicates:t}}resetToLoading(){this.isLoadingState=!0,this.data=[],this.filteredData=[],this.selectedRows.clear(),this.currentQuery="",this.queryEditor?.editor&&this.queryEditor.editor.setValue(""),this.queryEngine.setObjects([]),this.render()}setLoadingState(e){this.isLoadingState=Boolean(e),this.render()}}class s{constructor(e=[],t="id"){this.objects=e,this.primaryKeyField=t}setObjects(e){this.objects=e}filterObjects(e){if(!e.trim())return this.objects.map(e=>e[this.primaryKeyField]);if(!/[=!<>()]|(\bAND\b|\bOR\b|\bIN\b)/i.test(e))return this.searchObjects(e);const t=[];for(const s of this.objects)try{this.evaluateExpression(s,e)&&t.push(s[this.primaryKeyField])}catch(e){throw new Error(`Query error: ${e.message}`)}return t}searchObjects(e){const t=e.trim().toLowerCase().split(/\s+/).filter(Boolean);if(0===t.length)return this.objects.map(e=>e[this.primaryKeyField]);const s=[];for(const e of this.objects){const i=Object.values(e).map(e=>null==e?"":String(e).toLowerCase()).join(" ");t.every(e=>i.includes(e))&&s.push(e[this.primaryKeyField])}return s}evaluateExpression(e,t){if(!t.trim())return!0;for(t=t.replace(/\s+/g," ").trim();/\(([^()]+)\)/.test(t);)t=t.replace(/\(([^()]+)\)/g,(t,s)=>this.processGroup(e,s)?"true":"false");return this.processGroup(e,t)}processGroup(e,t){return t.split(/\s+OR\s+/).some(t=>t.split(/\s+AND\s+/).every(t=>{const s=t.trim().toLowerCase();if("false"===s)return!1;if("true"===s)return!0;try{const s=this.parseCondition(t);return this.applyCondition(e,s)}catch{throw new Error(`Invalid condition: ${t}`)}}))}parseCondition(e){const t=e.match(/(\w+)\s+IN\s+\[([^\]]+)\]/);if(t){const[,e,s]=t;return{field:e,operator:"IN",value:s.split(",").map(e=>{const t=e.trim().replace(/"/g,"");return"NULL"===t?null:t})}}const s=e.match(/(\w+)\s*(=|!=|>=|<=|>|<)\s*(.+)/i);if(s){const[,e,t,i]=s;let o=i.trim();return o.startsWith('"')&&o.endsWith('"')?o=o.slice(1,-1):"NULL"===o?o=null:"true"===o.toLowerCase()?o=!0:"false"===o.toLowerCase()?o=!1:isNaN(o)||""===o||(o=parseFloat(o)),{field:e,operator:t,value:o}}throw new Error(`Invalid condition: ${e}`)}applyCondition(e,{field:t,operator:s,value:i}){const o=t in e?e[t]:null,n=e=>null==e||""===e;switch(s){case"=":return null===i?n(o):!n(o)&&(Array.isArray(o)?o.includes(i):o==i);case"!=":return null===i?!n(o):!!n(o)||(Array.isArray(o)?!o.includes(i):o!=i);case">":return!n(o)&&!Array.isArray(o)&&o>parseFloat(i);case"<":return!n(o)&&!Array.isArray(o)&&o<parseFloat(i);case">=":return!n(o)&&!Array.isArray(o)&&o>=parseFloat(i);case"<=":return!n(o)&&!Array.isArray(o)&&o<=parseFloat(i);case"IN":return i.includes(null)?n(o)||i.includes(o):!n(o)&&(Array.isArray(o)?o.some(e=>i.includes(e)):i.includes(o));default:return!1}}}e.exports&&(e.exports={DivTable:t,QueryEngine:s})}},t={},function s(i){var o=t[i];if(void 0!==o)return o.exports;var n=t[i]={exports:{}};return e[i](n,n.exports,s),n.exports}(430).default;var e,t});