@gp-grid/core 0.10.3 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +347 -180
- package/dist/index.js +136 -261
- package/dist/styles.css +950 -0
- package/package.json +9 -3
package/dist/index.js
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
|
-
const e=e=>{let t=[0],n=0;for(let r of e)n+=r.width,t.push(n);return t},t=e=>e.at(-1)??0,n=(n,r)=>{let i=e(n),a=t(i);if(r<=a||a===0)return{positions:i,widths:n.map(e=>e.width)};let o=r/a,s=n.map(e=>e.width*o),c=[0],l=0;for(let e of s)l+=e,c.push(l);return{positions:c,widths:s}},r=(e,t)=>{for(let n=0;n<t.length-1;n++)if(e>=t[n]&&e<t[n+1])return n;return e>=t.at(-1)?t.length-2:0},i=e=>({minRow:Math.min(e.startRow,e.endRow),maxRow:Math.max(e.startRow,e.endRow),minCol:Math.min(e.startCol,e.endCol),maxCol:Math.max(e.startCol,e.endCol)}),a=(e,t,n)=>e>=n.minRow&&e<=n.maxRow&&t>=n.minCol&&t<=n.maxCol,o=(e,t,n)=>n?a(e,t,i(n)):!1,s=(e,t,n)=>n?.row===e&&n?.col===t,c=(e,t)=>!t||t.end<0||t.start>t.end?!0:e>=t.start&&e<=t.end,l=(e,t,n)=>n?.row===e&&n?.col===t,u=(e,t,n,r,a)=>{if(!n||!r||!a)return!1;let{minRow:o,maxRow:s,minCol:c,maxCol:l}=i(r),u=a.row>s,d=a.row<o;return u?e>s&&e<=a.row&&t>=c&&t<=l:d?e<o&&e>=a.row&&t>=c&&t<=l:!1},d=(e,t,n,r)=>{let i=[`gp-grid-cell`];return e&&i.push(`gp-grid-cell--active`),t&&!e&&i.push(`gp-grid-cell--selected`),n&&i.push(`gp-grid-cell--editing`),r&&i.push(`gp-grid-cell--fill-preview`),i.join(` `)},f=(e,t)=>{if(!t)return!1;let{minRow:n,maxRow:r}=i(t);return e>=n&&e<=r},p=(e,t)=>{if(!t)return!1;let{minCol:n,maxCol:r}=i(t);return e>=n&&e<=r};function m(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}function h(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];if(typeof i!=`object`||!i)return;i=i[t]}typeof i==`object`&&i&&(i[r.at(-1)]=n)}const g=()=>{let e=[];return{onInstruction:t=>(e.push(t),()=>{e=e.filter(e=>e!==t)}),emit:t=>{for(let n of e)n(t)},clearListeners:()=>{e=[]}}},_=()=>{let e=g(),t=[];return{onInstruction:e.onInstruction,onBatchInstruction:e=>(t.push(e),()=>{t=t.filter(t=>t!==e)}),emit:n=>{e.emit(n);for(let e of t)e([n])},emitBatch:n=>{if(n.length!==0){for(let e of t)e(n);for(let t of n)e.emit(t)}},clearListeners:()=>{e.clearListeners(),t=[]}}},v=(e,t)=>{for(let n of e.values())if(n.rowIndex===t)return n;return null},ee=(e,t,n,r,i,a=0)=>{let o=v(i,n);if(!o){t.scrollTop=e.getScrollTopForRow(n);return}let s=a+o.translateY-t.scrollTop,c=s+r;if(s<0)t.scrollTop=e.getScrollTopForRow(n);else if(c>t.clientHeight){let i=Math.floor(t.clientHeight/r),a=Math.max(0,n-i+1);t.scrollTop=e.getScrollTopForRow(a)}},y=(e,t)=>e==null?``:t?t(e):Array.isArray(e)?e.join(`, `):typeof e==`object`?e instanceof Date?String(e):JSON.stringify(e):String(e),te=e=>{let{activeCell:t,selectionRange:n,slots:r,columns:i,visibleColumnsWithIndices:a,columnPositions:o,columnWidths:s,rowHeight:c}=e;if(!t&&!n)return null;let l,u,d,f;if(n)l=Math.max(n.startRow,n.endRow),u=Math.max(n.startCol,n.endCol),d=Math.min(n.startCol,n.endCol),f=Math.max(n.startCol,n.endCol);else if(t)l=t.row,u=t.col,d=u,f=u;else return null;for(let e=d;e<=f;e++){let t=i[e];if(!(!t||t.hidden)&&t.editable!==!0)return null}let p=a.findIndex(e=>e.originalIndex===u);if(p===-1)return null;let m=null;for(let e of r.values())if(e.rowIndex===l){m=e.translateY;break}if(m===null)return null;let h=o[p]??0,g=s[p]??0;return{top:m+c-5,left:h+g-20}},ne=(e,t,n=8)=>{let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=r.bottom+4,o=r.left,s=Math.max(200,r.width);return o+i.width>window.innerWidth-n&&(o=window.innerWidth-i.width-n),o=Math.max(n,o),a+i.height>window.innerHeight-n&&(a=r.top-i.height-4),a=Math.max(n,a),{top:a,left:o,minWidth:s}};var b=class{state={activeCell:null,range:null,anchor:null,selectionMode:!1};options;emitter=g();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getState(){return{...this.state}}getActiveCell(){return this.state.activeCell}getSelectionRange(){return this.state.range}isSelected(e,t){let{range:n}=this.state;if(!n)return!1;let{minRow:r,maxRow:a,minCol:o,maxCol:s}=i(n);return e>=r&&e<=a&&t>=o&&t<=s}isActiveCell(e,t){let{activeCell:n}=this.state;return n?.row===e&&n?.col===t}startSelection(e,t={}){let{shift:n=!1,ctrl:r=!1}=t,{row:i,col:a}=this.clampPosition(e);n&&this.state.anchor?(this.state.range={startRow:this.state.anchor.row,startCol:this.state.anchor.col,endRow:i,endCol:a},this.state.activeCell={row:i,col:a}):(this.state.activeCell={row:i,col:a},this.state.anchor={row:i,col:a},this.state.range=null),this.state.selectionMode=r,this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range})}moveFocus(e,t=!1){if(!this.state.activeCell){this.startSelection({row:0,col:0});return}let{row:n,col:r}=this.state.activeCell,i=n,a=r;switch(e){case`up`:i=Math.max(0,n-1);break;case`down`:i=Math.min(this.options.getRowCount()-1,n+1);break;case`left`:a=Math.max(0,r-1);break;case`right`:a=Math.min(this.options.getColumnCount()-1,r+1);break}t?(this.state.anchor??={row:n,col:r},this.state.range={startRow:this.state.anchor.row,startCol:this.state.anchor.col,endRow:i,endCol:a},this.state.activeCell={row:i,col:a},this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range})):(this.state.activeCell={row:i,col:a},this.state.anchor={row:i,col:a},this.state.range=null,this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:null}))}selectAll(){let e=this.options.getRowCount(),t=this.options.getColumnCount();e===0||t===0||(this.state.range={startRow:0,startCol:0,endRow:e-1,endCol:t-1},this.state.activeCell||(this.state.activeCell={row:0,col:0},this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell})),this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range}))}clearSelection(){this.state.activeCell=null,this.state.range=null,this.state.anchor=null,this.state.selectionMode=!1,this.emit({type:`SET_ACTIVE_CELL`,position:null}),this.emit({type:`SET_SELECTION_RANGE`,range:null})}setActiveCell(e,t){let n=this.clampPosition({row:e,col:t});this.state.activeCell=n,this.state.anchor=n,this.state.range=null,this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:null})}setSelectionRange(e){this.state.range=e,this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range})}getSelectedData(){let{range:e,activeCell:t}=this.state;if(!e&&!t)return[];let{minRow:n,maxRow:r,minCol:a,maxCol:o}=i(e||{startRow:t.row,startCol:t.col,endRow:t.row,endCol:t.col}),s=[];for(let e=n;e<=r;e++){let t=[];for(let n=a;n<=o;n++)t.push(this.options.getCellValue(e,n));s.push(t)}return s}async copySelectionToClipboard(){if(typeof navigator>`u`||typeof document>`u`)return;let e=this.getSelectedData();if(e.length===0)return;let t=e.map(e=>e.map(e=>y(e)).join(` `)).join(`
|
|
2
|
-
`);await navigator.clipboard.writeText(t)}destroy(){this.emitter.clearListeners(),this.state={activeCell:null,range:null,anchor:null,selectionMode:!1}}clampPosition(e){let t=this.options.getRowCount(),n=this.options.getColumnCount();return{row:Math.max(0,Math.min(e.row,t-1)),col:Math.max(0,Math.min(e.col,n-1))}}},x=class{state=null;options;emitter=g();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getState(){return this.state?{...this.state}:null}isActive(){return this.state!==null}startFillDrag(e){this.state={sourceRange:e,targetRow:e.endRow,targetCol:e.endCol},this.emit({type:`START_FILL`,sourceRange:e})}updateFillDrag(e,t){if(!this.state)return;let n=this.options.getRowCount(),r=this.options.getColumnCount();e=Math.max(0,Math.min(e,n-1)),t=Math.max(0,Math.min(t,r-1)),this.state.targetRow=e,this.state.targetCol=t,this.emit({type:`UPDATE_FILL`,targetRow:e,targetCol:t})}commitFillDrag(){if(!this.state)return;let{sourceRange:e,targetRow:t}=this.state,n=this.calculateFilledCells(e,t);for(let{row:e,col:t,value:r}of n)this.options.setCellValue(e,t,r);this.emit({type:`COMMIT_FILL`,filledCells:n}),this.state=null}cancelFillDrag(){this.state&&(this.state=null,this.emit({type:`CANCEL_FILL`}))}destroy(){this.emitter.clearListeners(),this.state=null}calculateFilledCells(e,t){let n=[],{minRow:r,maxRow:a,minCol:o,maxCol:s}=i(e),c=t>a,l=t<r;if(c||l)for(let e=o;e<=s;e++){let i=this.getSourceColumnValues(r,a,e),o=this.detectPattern(i);if(c)for(let r=a+1;r<=t;r++){let t=r-a-1,s=this.applyPattern(o,i,t);n.push({row:r,col:e,value:s})}else if(l)for(let a=r-1;a>=t;a--){let t=r-a-1,s=this.applyPattern(o,i,t,!0);n.push({row:a,col:e,value:s})}}return n}getSourceColumnValues(e,t,n){let r=[];for(let i=e;i<=t;i++)r.push(this.options.getCellValue(i,n));return r}detectPattern(e){if(e.length===0)return{type:`constant`,value:null};if(e.length===1)return{type:`constant`,value:e[0]??null};let t=e.map(e=>typeof e==`number`?e:Number(e));if(t.every(e=>!Number.isNaN(e))){let e=[];for(let n=1;n<t.length;n++)e.push(t[n]-t[n-1]);if(e.every(t=>t===e[0])&&e[0]!==void 0)return{type:`arithmetic`,start:t[0],step:e[0]}}return{type:`repeat`,values:e}}applyPattern(e,t,n,r=!1){switch(e.type){case`constant`:return e.value;case`arithmetic`:{let i=r?-(n+1):n+1;return(r?e.start:e.start+e.step*(t.length-1))+e.step*i}case`repeat`:{let t=e.values.length;if(t===0)return null;if(r){let r=(t-1-n%t+t)%t;return e.values[r]??null}return e.values[n%t]??null}}}},re=class{state={slots:new Map,rowToSlot:new Map,nextSlotId:0};options;emitter=_();isDestroyed=!1;onInstruction=this.emitter.onInstruction;onBatchInstruction=this.emitter.onBatchInstruction;emit=this.emitter.emit;emitBatch=this.emitter.emitBatch;constructor(e){this.options=e}getSlotForRow(e){return this.state.rowToSlot.get(e)}getSlots(){return this.state.slots}syncSlots(){let e=this.options.getScrollTop(),t=this.options.getRowHeight(),n=this.options.getViewportHeight(),r=this.options.getTotalRows(),i=this.options.getOverscan(),a=n,o=Math.max(0,Math.floor(e/t)-i),s=Math.min(r-1,Math.ceil((e+a)/t)+i);if(r===0||s<o){this.destroyAllSlots();return}let c=new Set;for(let e=o;e<=s;e++)c.add(e);let l=[],u=this.partitionSlots(c),d=0;for(let e of c){let t=this.options.getRowData(e);if(t===void 0)continue;let n=d<u.length?u[d++]:void 0;this.assignSlotToRow(e,t,n,l)}for(let e=d;e<u.length;e++){let t=u[e];this.state.slots.delete(t),l.push({type:`DESTROY_SLOT`,slotId:t})}this.updateSlotPositions(l),this.emitBatch(l)}partitionSlots(e){let t=[];for(let[n,r]of this.state.slots)e.has(r.rowIndex)?e.delete(r.rowIndex):(t.push(n),this.state.rowToSlot.delete(r.rowIndex));return t}assignSlotToRow(e,t,n,r){let i;if(n===void 0)i=`slot-${this.state.nextSlotId++}`,this.state.slots.set(i,{slotId:i,rowIndex:e,rowData:t,translateY:this.getRowTranslateY(e)}),r.push({type:`CREATE_SLOT`,slotId:i});else{i=n;let r=this.state.slots.get(i);r.rowIndex=e,r.rowData=t,r.translateY=this.getRowTranslateY(e)}this.state.rowToSlot.set(e,i),r.push({type:`ASSIGN_SLOT`,slotId:i,rowIndex:e,rowData:t},{type:`MOVE_SLOT`,slotId:i,translateY:this.getRowTranslateY(e)})}updateSlotPositions(e){for(let[t,n]of this.state.slots){let r=this.getRowTranslateY(n.rowIndex);n.translateY!==r&&(n.translateY=r,e.push({type:`MOVE_SLOT`,slotId:t,translateY:r}))}}destroyAllSlots(){let e=[];for(let t of this.state.slots.keys())e.push({type:`DESTROY_SLOT`,slotId:t});this.state.slots.clear(),this.state.rowToSlot.clear(),this.emitBatch(e)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.state.slots.clear(),this.state.rowToSlot.clear(),this.emitter.clearListeners())}refreshAllSlots(){let e=[],t=this.options.getTotalRows();for(let[n,r]of this.state.slots)if(r.rowIndex>=0&&r.rowIndex<t){let t=this.options.getRowData(r.rowIndex);if(t===void 0)continue;let i=this.getRowTranslateY(r.rowIndex);r.rowData=t,r.translateY=i,e.push({type:`ASSIGN_SLOT`,slotId:n,rowIndex:r.rowIndex,rowData:t},{type:`MOVE_SLOT`,slotId:n,translateY:i})}this.emitBatch(e),this.syncSlots()}updateSlot(e){let t=this.state.rowToSlot.get(e);if(t){let n=this.options.getRowData(e);n&&this.emit({type:`ASSIGN_SLOT`,slotId:t,rowIndex:e,rowData:n})}}getRowTranslateY(e){let t=this.options.getRowHeight(),n=this.options.getScrollRatio(),r=this.options.getScrollTop(),i=e*t;return n>=1?i:i-Math.floor(r/t)*t}getRowTranslateYForIndex(e){return this.getRowTranslateY(e)}getRowsWrapperOffset(){let e=this.options.getScrollRatio(),t=this.options.getScrollTop(),n=this.options.getRowHeight();return e>=1?0:Math.floor(t/n)*n*e}},S=class{editState=null;options;emitter=g();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getState(){return this.editState?{...this.editState}:null}isEditing(){return this.editState!==null}isEditingCell(e,t){return this.editState!==null&&this.editState.row===e&&this.editState.col===t}startEdit(e,t){if(!this.options.getColumn(t)?.editable)return!1;let n=this.options.getCellValue(e,t);return this.editState={row:e,col:t,initialValue:n,currentValue:n},this.emit({type:`START_EDIT`,row:e,col:t,initialValue:n}),!0}updateValue(e){this.editState&&(this.editState.currentValue=e)}commit(){if(!this.editState)return;let{row:e,col:t,currentValue:n}=this.editState;this.options.setCellValue(e,t,n),this.emit({type:`COMMIT_EDIT`,row:e,col:t,value:n}),this.editState=null,this.emit({type:`STOP_EDIT`}),this.options.onCommit?.(e,t,n)}cancel(){this.editState=null,this.emit({type:`STOP_EDIT`})}destroy(){this.emitter.clearListeners(),this.editState=null}},C=class{core;deps;isDraggingSelection=!1;isDraggingFill=!1;fillSourceRange=null;fillTarget=null;isDraggingColumnResize=!1;resizeColIndex=-1;resizeStartX=0;resizeInitialWidth=0;resizeCurrentWidth=0;isDraggingColumnMove=!1;moveSourceColIndex=-1;moveStartX=0;moveStartY=0;moveThresholdMet=!1;moveShiftKey=!1;moveGhostWidth=0;moveGhostHeight=0;moveCurrentX=0;moveCurrentY=0;moveDropTargetIndex=null;isDraggingRow=!1;rowDragSourceIndex=-1;rowDragStartX=0;rowDragStartY=0;rowDragThresholdMet=!1;rowDragCurrentX=0;rowDragCurrentY=0;rowDragDropTargetIndex=null;pendingRowDrag=null;constructor(e,t){this.core=e,this.deps=t}updateDeps(e){this.deps={...this.deps,...e}}getDragState(){let e=this.getDragType(),t=e===`column-resize`?{colIndex:this.resizeColIndex,initialWidth:this.resizeInitialWidth,currentWidth:this.resizeCurrentWidth}:null,n=e===`column-move`?{sourceColIndex:this.moveSourceColIndex,currentX:this.moveCurrentX,currentY:this.moveCurrentY,dropTargetIndex:this.moveDropTargetIndex,ghostWidth:this.moveGhostWidth,ghostHeight:this.moveGhostHeight}:null,r=e===`row-drag`?{sourceRowIndex:this.rowDragSourceIndex,currentX:this.rowDragCurrentX,currentY:this.rowDragCurrentY,dropTargetIndex:this.rowDragDropTargetIndex,dropIndicatorY:this.rowDragDropTargetIndex===null?0:this.core.getRowTranslateY(this.rowDragDropTargetIndex)}:null;return{isDragging:e!==null,dragType:e,fillSourceRange:this.fillSourceRange,fillTarget:this.fillTarget,columnResize:t,columnMove:n,rowDrag:r}}getDragType(){return this.isDraggingFill?`fill`:this.isDraggingColumnResize?`column-resize`:this.isDraggingColumnMove&&this.moveThresholdMet?`column-move`:this.isDraggingRow&&this.rowDragThresholdMet?`row-drag`:this.isDraggingSelection?`selection`:null}handleCellMouseDown(e,t,n){if(n.button!==0||this.core.getEditState()!==null)return{preventDefault:!1,stopPropagation:!1};let r=this.core.getColumns()[t],i=this.core.isRowDragEntireRow();return(r?.rowDrag===!0||i)&&!n.shiftKey?n.pointerType===`touch`?(this.pendingRowDrag={rowIndex:e,colIndex:t,clientX:n.clientX,clientY:n.clientY},this.core.selection.startSelection({row:e,col:t},{shift:!1,ctrl:!1}),{preventDefault:!1,stopPropagation:!1,focusContainer:!0,startDrag:`row-drag-pending`}):(this.isDraggingRow=!0,this.rowDragSourceIndex=e,this.rowDragStartX=n.clientX,this.rowDragStartY=n.clientY,this.rowDragThresholdMet=!1,this.rowDragCurrentX=n.clientX,this.rowDragCurrentY=n.clientY,this.rowDragDropTargetIndex=null,this.core.selection.startSelection({row:e,col:t},{shift:!1,ctrl:!1}),{preventDefault:!0,stopPropagation:!0,focusContainer:!0,startDrag:`row-drag`}):(this.core.selection.startSelection({row:e,col:t},{shift:n.shiftKey,ctrl:n.ctrlKey||n.metaKey}),{preventDefault:!1,stopPropagation:!1,focusContainer:!0,startDrag:n.shiftKey?void 0:`selection`})}handleCellDoubleClick(e,t){this.core.startEdit(e,t)}handleCellMouseEnter(e,t){this.core.highlight?.setHoverPosition({row:e,col:t})}handleCellMouseLeave(){this.core.highlight?.setHoverPosition(null)}handleFillHandleMouseDown(e,t,n){if(!e&&!t)return{preventDefault:!1,stopPropagation:!1};let r=t??{startRow:e.row,startCol:e.col,endRow:e.row,endCol:e.col};return this.core.fill.startFillDrag(r),this.fillSourceRange=r,this.fillTarget={row:Math.max(r.startRow,r.endRow),col:Math.max(r.startCol,r.endCol)},this.isDraggingFill=!0,{preventDefault:!0,stopPropagation:!0,startDrag:`fill`}}handleHeaderClick(e,t){let n=this.core.getSortModel().find(t=>t.colId===e)?.direction,r=this.cycleSortDirection(n);this.core.setSort(e,r,t)}handleHeaderResizeMouseDown(e,t,n){return n.button!==0||this.core.getColumns()[e]?.resizable===!1?{preventDefault:!1,stopPropagation:!1}:(this.isDraggingColumnResize=!0,this.resizeColIndex=e,this.resizeStartX=n.clientX,this.resizeInitialWidth=t,this.resizeCurrentWidth=t,{preventDefault:!0,stopPropagation:!0,startDrag:`column-resize`})}handleHeaderMouseDown(e,t,n,r){return r.button!==0||this.core.getColumns()[e]?.movable===!1?{preventDefault:!1,stopPropagation:!1}:(this.isDraggingColumnMove=!0,this.moveSourceColIndex=e,this.moveStartX=r.clientX,this.moveStartY=r.clientY,this.moveThresholdMet=!1,this.moveShiftKey=r.shiftKey,this.moveGhostWidth=t,this.moveGhostHeight=n,this.moveCurrentX=r.clientX,this.moveCurrentY=r.clientY,this.moveDropTargetIndex=null,{preventDefault:!0,stopPropagation:!0,startDrag:`column-move`})}startSelectionDrag(){this.isDraggingSelection=!0}confirmPendingRowDrag(){let e=this.pendingRowDrag;return e?(this.pendingRowDrag=null,this.isDraggingRow=!0,this.rowDragSourceIndex=e.rowIndex,this.rowDragStartX=e.clientX,this.rowDragStartY=e.clientY,this.rowDragThresholdMet=!1,this.rowDragCurrentX=e.clientX,this.rowDragCurrentY=e.clientY,this.rowDragDropTargetIndex=null,!0):!1}cancelPendingRowDrag(){this.pendingRowDrag=null}handleDragMove(e,t){return this.isDraggingColumnResize?this.handleColumnResizeDragMove(e,t):this.isDraggingColumnMove?this.handleColumnMoveDragMove(e,t):this.isDraggingRow?this.handleRowDragDragMove(e,t):this.handleSelectionFillDragMove(e,t)}handleColumnResizeDragMove(e,t){let n=this.core.getColumns()[this.resizeColIndex],r=n?.minWidth??50,i=n?.maxWidth,a=this.resizeInitialWidth+(e.clientX-this.resizeStartX);a=Math.max(r,a),i!==void 0&&(a=Math.min(i,a)),this.resizeCurrentWidth=a;let o=e.clientX-t.left,s=0;o>t.width-40&&(s=10);let c=s===0?null:{dx:s,dy:0};return{targetRow:0,targetCol:this.resizeColIndex,autoScroll:c}}handleColumnMoveDragMove(e,t){let n=e.clientX-this.moveStartX,i=e.clientY-this.moveStartY;if(this.moveThresholdMet===!1){if(!(Math.abs(n)>5||Math.abs(i)>5))return null;this.moveThresholdMet=!0}this.moveCurrentX=e.clientX,this.moveCurrentY=e.clientY;let{left:a,width:o,scrollLeft:s}=t,c=e.clientX-a+s,l=this.deps.getColumnPositions(),u=this.deps.getColumnCount();this.moveDropTargetIndex=Math.max(0,Math.min(r(c,l),u));let d=e.clientX-a,f=0;d<40?f=-10:d>o-40&&(f=10);let p=f===0?null:{dx:f,dy:0};return{targetRow:0,targetCol:this.moveDropTargetIndex??0,autoScroll:p}}handleRowDragDragMove(e,t){let n=e.clientX-this.rowDragStartX,r=e.clientY-this.rowDragStartY;if(this.rowDragThresholdMet===!1){if(!(Math.abs(n)>5||Math.abs(r)>5))return null;this.rowDragThresholdMet=!0}this.rowDragCurrentX=e.clientX,this.rowDragCurrentY=e.clientY;let{top:i,height:a,width:o,scrollTop:s}=t,c=this.deps.getHeaderHeight(),l=e.clientY-i,u=this.core.getRowCount(),d=Math.max(0,Math.min(this.core.getRowIndexAtDisplayY(l,s),u));this.rowDragDropTargetIndex=d;let f=e.clientY-i,p=e.clientX-t.left;return{targetRow:d,targetCol:0,autoScroll:this.calculateAutoScroll(f,p,a,o,c)}}handleSelectionFillDragMove(e,t){if((this.isDraggingSelection||this.isDraggingFill)===!1)return null;let{top:n,left:i,width:a,height:o,scrollTop:s,scrollLeft:c}=t,l=this.deps.getHeaderHeight(),u=this.deps.getColumnPositions(),d=this.deps.getColumnCount(),f=e.clientX-i+c,p=e.clientY-n,m=Math.max(0,Math.min(this.core.getRowIndexAtDisplayY(p,s),this.core.getRowCount()-1)),h=Math.max(0,Math.min(r(f,u),d-1)),g=this.deps.getOriginalColumnIndex?this.deps.getOriginalColumnIndex(h):h;this.isDraggingSelection&&this.core.selection.startSelection({row:m,col:g},{shift:!0}),this.isDraggingFill&&(this.core.fill.updateFillDrag(m,g),this.fillTarget={row:m,col:g});let _=e.clientY-n,v=e.clientX-i;return{targetRow:m,targetCol:g,autoScroll:this.calculateAutoScroll(_,v,o,a,l)}}handleDragEnd(){if(this.isDraggingColumnResize)return this.endColumnResizeDrag();if(this.isDraggingColumnMove)return this.endColumnMoveDrag();if(this.isDraggingRow)return this.endRowDrag();this.endSelectionFillDrag()}endColumnResizeDrag(){this.core.setColumnWidth(this.resizeColIndex,this.resizeCurrentWidth),this.isDraggingColumnResize=!1,this.resizeColIndex=-1}endColumnMoveDrag(){if(this.moveThresholdMet){if(this.moveDropTargetIndex!==null){let e=this.moveSourceColIndex,t=this.deps.getOriginalColumnIndex?this.deps.getOriginalColumnIndex(Math.min(this.moveDropTargetIndex,this.deps.getColumnCount()-1)):this.moveDropTargetIndex;e!==t&&this.core.moveColumn(e,t)}}else{let e=this.core.getColumns()[this.moveSourceColIndex];if(e){let t=e.colId??e.field;this.handleHeaderClick(t,this.moveShiftKey)}}this.isDraggingColumnMove=!1,this.moveSourceColIndex=-1,this.moveThresholdMet=!1,this.moveShiftKey=!1,this.moveDropTargetIndex=null}endRowDrag(){this.rowDragThresholdMet&&this.rowDragDropTargetIndex!==null&&this.rowDragDropTargetIndex!==this.rowDragSourceIndex&&this.core.commitRowDrag(this.rowDragSourceIndex,this.rowDragDropTargetIndex),this.isDraggingRow=!1,this.rowDragSourceIndex=-1,this.rowDragThresholdMet=!1,this.rowDragDropTargetIndex=null}endSelectionFillDrag(){this.isDraggingFill&&(this.core.fill.commitFillDrag(),this.core.refreshSlotData()),this.isDraggingSelection=!1,this.isDraggingFill=!1,this.fillSourceRange=null,this.fillTarget=null}handleWheel(e,t,n){return this.core.isScalingActive()?{dy:e*n,dx:t*n}:null}handleKeyDown(e,t,n,r){return r||n&&e.key!==`Enter`&&e.key!==`Escape`&&e.key!==`Tab`?{preventDefault:!1}:this.handleKeyAction(e,t,n)}handleKeyAction(e,t,n){let{selection:r}=this.core,i=e.shiftKey,a=e.ctrlKey||e.metaKey,o=this.keyToDirection(e.key);if(o)return r.moveFocus(o,i),{preventDefault:!0,scrollToCell:r.getActiveCell()??void 0};switch(e.key){case`Enter`:return n?this.core.commitEdit():t&&this.core.startEdit(t.row,t.col),{preventDefault:!0};case`Escape`:return n?this.core.cancelEdit():r.clearSelection(),{preventDefault:!0};case`Tab`:return n&&this.core.commitEdit(),r.moveFocus(i?`left`:`right`,!1),{preventDefault:!0};default:return this.handleNonEditingKey(e.key,t,n,a)}}handleNonEditingKey(e,t,n,r){let{selection:i}=this.core;switch(e){case`a`:if(r)return i.selectAll(),{preventDefault:!0};break;case`c`:if(r)return i.copySelectionToClipboard(),{preventDefault:!0};break;case`F2`:return t&&!n&&this.core.startEdit(t.row,t.col),{preventDefault:!0};case`Delete`:case`Backspace`:if(t&&!n)return this.core.startEdit(t.row,t.col),{preventDefault:!0};break;default:t&&!n&&!r&&e.length===1&&this.core.startEdit(t.row,t.col);break}return{preventDefault:!1}}keyToDirection(e){switch(e){case`ArrowUp`:return`up`;case`ArrowDown`:return`down`;case`ArrowLeft`:return`left`;case`ArrowRight`:return`right`;default:return null}}cycleSortDirection(e){return e==null?`asc`:e===`asc`?`desc`:null}calculateAutoScroll(e,t,n,r,i){let a=0,o=0;return e<40+i?o=-10:e>n-40&&(o=10),t<40?a=-10:t>r-40&&(a=10),a!==0||o!==0?{dx:a,dy:o}:null}},ie=class{options;highlightingOptions;hoverPosition=null;emitter=g();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;rowClassCache=new Map;columnClassCache=new Map;cellClassCache=new Map;constructor(e,t={}){this.options=e,this.highlightingOptions=t}isEnabled(){return!!(this.highlightingOptions.computeRowClasses||this.highlightingOptions.computeColumnClasses||this.highlightingOptions.computeCellClasses)}updateOptions(e){this.highlightingOptions=e,this.clearAllCaches()}setHoverPosition(e){this.isEnabled()&&(this.hoverPosition?.row===e?.row&&this.hoverPosition?.col===e?.col||(this.rowClassCache.clear(),this.columnClassCache.clear(),this.cellClassCache.clear(),this.hoverPosition=e,this.emit({type:`SET_HOVER_POSITION`,position:e})))}getHoverPosition(){return this.hoverPosition}onSelectionChange(){this.clearAllCaches()}buildRowContext(e,t){let n=this.options.getActiveCell(),r=this.options.getSelectionRange();return{rowIndex:e,colIndex:null,column:void 0,rowData:t,hoverPosition:this.hoverPosition,activeCell:n,selectionRange:r,isHovered:this.hoverPosition?.row===e,isActive:n?.row===e,isSelected:f(e,r)}}buildColumnContext(e,t){let n=this.options.getActiveCell(),r=this.options.getSelectionRange();return{rowIndex:null,colIndex:e,column:t,rowData:void 0,hoverPosition:this.hoverPosition,activeCell:n,selectionRange:r,isHovered:this.hoverPosition?.col===e,isActive:n?.col===e,isSelected:p(e,r)}}buildCellContext(e,t,n,r){let a=this.options.getActiveCell(),o=this.options.getSelectionRange(),s=this.hoverPosition?.row===e&&this.hoverPosition?.col===t,c=!1;if(o){let{minRow:n,maxRow:r,minCol:a,maxCol:s}=i(o);c=e>=n&&e<=r&&t>=a&&t<=s}return{rowIndex:e,colIndex:t,column:n,rowData:r,hoverPosition:this.hoverPosition,activeCell:a,selectionRange:o,isHovered:s,isActive:a?.row===e&&a?.col===t,isSelected:c}}computeRowClasses(e,t){let n=this.highlightingOptions.computeRowClasses;if(!n)return[];let r=this.rowClassCache.get(e);if(r!==void 0)return r;let i=n(this.buildRowContext(e,t));return this.rowClassCache.set(e,i),i}computeColumnClasses(e,t){let n=this.columnClassCache.get(e);if(n!==void 0)return n;let r=this.buildColumnContext(e,t),i;if(t.computeColumnClasses)i=t.computeColumnClasses(r);else if(this.highlightingOptions.computeColumnClasses)i=this.highlightingOptions.computeColumnClasses(r);else return[];return this.columnClassCache.set(e,i),i}computeCellClasses(e,t,n,r){let i=`${e},${t}`,a=this.cellClassCache.get(i);if(a!==void 0)return a;let o=this.buildCellContext(e,t,n,r),s;if(n.computeCellClasses)s=n.computeCellClasses(o);else if(this.highlightingOptions.computeCellClasses)s=this.highlightingOptions.computeCellClasses(o);else return[];return this.cellClassCache.set(i,s),s}computeCombinedCellClasses(e,t,n,r){let i=this.computeColumnClasses(t,n),a=this.computeCellClasses(e,t,n,r);return[...i,...a]}clearAllCaches(){this.rowClassCache.clear(),this.columnClassCache.clear(),this.cellClassCache.clear()}destroy(){this.emitter.clearListeners(),this.clearAllCaches(),this.hoverPosition=null}},ae=class{options;emitter=g();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getRow(e){return this.options.getCachedRows().get(e)}addRows(e,t){if(e.length===0)return;let n=this.options.getCachedRows(),r=this.options.getTotalRows(),i=t??r,a=r+e.length;if(i<r){let t=new Map;for(let[r,a]of n)r>=i?t.set(r+e.length,a):t.set(r,a);this.options.setCachedRows(t)}let o=this.options.getCachedRows();e.forEach((e,t)=>{o.set(i+t,e)}),this.options.setTotalRows(a);let s=e.map((e,t)=>i+t);this.emit({type:`ROWS_ADDED`,indices:s,count:s.length,totalRows:a}),this.options.emitContentSize(),this.options.refreshAllSlots()}updateRows(e){if(e.length===0)return;let t=this.options.getCachedRows(),n=[];for(let r of e){let e=t.get(r.index);e&&(t.set(r.index,{...e,...r.data}),n.push(r.index))}if(n.length!==0){this.emit({type:`ROWS_UPDATED`,indices:n});for(let e of n)this.options.updateSlot(e)}}deleteRows(e){if(e.length===0)return;let t=this.options.getCachedRows(),n=this.options.getTotalRows(),r=[...e].sort((e,t)=>t-e);for(let e of r){if(e<0||e>=n)continue;t.delete(e);let r=new Map;for(let[n,i]of t)n>e?r.set(n-1,i):r.set(n,i);this.options.setCachedRows(r),n--}this.options.setTotalRows(n),this.options.clearSelectionIfInvalid(n),this.emit({type:`ROWS_REMOVED`,indices:r,totalRows:n}),this.options.emitContentSize(),this.options.refreshAllSlots()}setRow(e,t){let n=this.options.getTotalRows();e<0||e>=n||(this.options.getCachedRows().set(e,t),this.emit({type:`ROWS_UPDATED`,indices:[e]}),this.options.updateSlot(e))}destroy(){this.emitter.clearListeners()}};const w=1e7;var T=class{naturalContentHeight=0;virtualContentHeight=0;scrollRatio=1;options;constructor(e){this.options=e}updateContentSize(){let e=this.options.getTotalRows(),t=this.options.getRowHeight(),n=this.options.getHeaderHeight();return this.naturalContentHeight=e*t+n,this.naturalContentHeight>w?(this.virtualContentHeight=w,this.scrollRatio=w/this.naturalContentHeight):(this.virtualContentHeight=this.naturalContentHeight,this.scrollRatio=1),{naturalHeight:this.naturalContentHeight,virtualHeight:this.virtualContentHeight,scrollRatio:this.scrollRatio}}isScalingActive(){return this.scrollRatio<1}getNaturalHeight(){let e=this.options.getTotalRows(),t=this.options.getRowHeight(),n=this.options.getHeaderHeight();return this.naturalContentHeight||e*t+n}getVirtualHeight(){let e=this.options.getTotalRows(),t=this.options.getRowHeight(),n=this.options.getHeaderHeight();return this.virtualContentHeight||e*t+n}getScrollRatio(){return this.scrollRatio}getVisibleRowRange(){let e=this.options.getViewportHeight(),t=this.options.getScrollTop(),n=this.options.getRowHeight(),r=this.options.getTotalRows(),i=e,a=Math.max(0,Math.floor(t/n)),o=Math.min(r-1,Math.ceil((t+i)/n)-1);return{start:a,end:Math.max(a,o)}}getScrollTopForRow(e){return e*this.options.getRowHeight()*this.scrollRatio}getRowIndexAtDisplayY(e,t){let n=this.options.getRowHeight(),r=e+(this.scrollRatio<1?t/this.scrollRatio:t);return Math.floor(r/n)}getVirtualContentHeight(){return this.virtualContentHeight}},E=class{options;emitter=g();sortModel=[];filterModel={};openFilterColIndex=null;onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}async setSort(e,t,n=!1){if(!this.options.isSortingEnabled()||this.options.getColumns().find(t=>(t.colId??t.field)===e)?.sortable===!1)return;let r=this.sortModel.findIndex(t=>t.colId===e);n?t===null&&r>=0?this.sortModel.splice(r,1):r>=0?this.sortModel[r].direction=t:this.sortModel.push({colId:e,direction:t}):this.sortModel=t===null?[]:[{colId:e,direction:t}],await this.options.onSortFilterChange(),this.options.onDataRefreshed()}getSortModel(){return[...this.sortModel]}async setFilter(e,t){this.options.getColumns().find(t=>(t.colId??t.field)===e)?.filterable!==!1&&(t===null||typeof t==`string`&&t.trim()===``||typeof t==`object`&&t.conditions?.length===0?delete this.filterModel[e]:typeof t==`string`?this.filterModel[e]={conditions:[{type:`text`,operator:`contains`,value:t}],combination:`and`}:this.filterModel[e]=t,await this.options.onSortFilterChange(),this.options.onDataRefreshed())}getFilterModel(){return{...this.filterModel}}hasActiveFilter(e){let t=this.filterModel[e];return t?t.conditions.length>0:!1}isColumnSortable(e){return this.options.isSortingEnabled()?this.options.getColumns()[e]?.sortable!==!1:!1}isColumnFilterable(e){return this.options.getColumns()[e]?.filterable!==!1}getDistinctValuesForColumn(e,t=500,n=1e5){let r=this.options.getColumns().find(t=>(t.colId??t.field)===e);if(!r)return[];let i=this.options.getCachedRows(),a=new Map,o=0;for(let e of i.values()){if(++o>n)break;let i=m(e,r.field),[s,c]=this.normalizeDistinctValue(i);if(!a.has(s)&&(a.set(s,c),a.size>=t))break}let s=Array.from(a.values());return s.sort((e,t)=>{let n=y(e),r=y(t);return n.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})}),s}normalizeDistinctValue(e){if(Array.isArray(e)){let t=[...e].sort((e,t)=>{let n=String(e),r=String(t);return n===r?0:n<r?-1:1});return[JSON.stringify(t),t]}return[JSON.stringify(e),e]}openFilterPopup(e,t){if(this.openFilterColIndex===e){this.closeFilterPopup();return}let n=this.options.getColumns()[e];if(!n||!this.isColumnFilterable(e))return;let r=n.colId??n.field,i=this.getDistinctValuesForColumn(r);this.openFilterColIndex=e,this.emit({type:`OPEN_FILTER_POPUP`,colIndex:e,column:n,anchorRect:t,distinctValues:i,currentFilter:this.filterModel[r]})}closeFilterPopup(){this.openFilterColIndex=null,this.emit({type:`CLOSE_FILTER_POPUP`})}getSortInfoMap(){let e=new Map;return this.sortModel.forEach((t,n)=>{e.set(t.colId,{direction:t.direction,index:n+1})}),e}destroy(){this.emitter.clearListeners(),this.sortModel=[],this.filterModel={},this.openFilterColIndex=null}},D=class{queue=[];debounceTimer=null;pendingPromise=null;options;constructor(e){this.options=e}add(e){e.length!==0&&(this.queue.push({type:`ADD`,rows:e}),this.scheduleProcessing())}remove(e){e.length!==0&&(this.queue.push({type:`REMOVE`,rowIds:e}),this.scheduleProcessing())}updateCell(e,t,n){this.queue.push({type:`UPDATE_CELL`,rowId:e,field:t,value:n}),this.scheduleProcessing()}updateRow(e,t){Object.keys(t).length!==0&&(this.queue.push({type:`UPDATE_ROW`,rowId:e,data:t}),this.scheduleProcessing())}flush(){return this.queue.length===0?Promise.resolve():(this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingPromise?new Promise((e,t)=>{let n=this.pendingPromise,r=n.resolve,i=n.reject;n.resolve=()=>{r(),e()},n.reject=e=>{i(e),t(e)}}):new Promise((e,t)=>{this.pendingPromise={resolve:e,reject:t},this.processQueue()}))}hasPending(){return this.queue.length>0}getPendingCount(){return this.queue.length}clear(){this.queue=[],this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingPromise&&=(this.pendingPromise.resolve(),null)}scheduleProcessing(){if(this.options.debounceMs===0){this.processQueue();return}this.debounceTimer===null&&(this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.processQueue()},this.options.debounceMs))}processQueue(){if(this.queue.length===0){this.pendingPromise&&=(this.pendingPromise.resolve(),null);return}let e=this.queue;this.queue=[];let t={added:0,removed:0,updated:0};try{for(let n of e)switch(n.type){case`ADD`:this.options.store.addRows(n.rows),t.added+=n.rows.length;break;case`REMOVE`:this.options.store.removeRows(n.rowIds),t.removed+=n.rowIds.length;break;case`UPDATE_CELL`:this.options.store.updateCell(n.rowId,n.field,n.value),t.updated++;break;case`UPDATE_ROW`:this.options.store.updateRow(n.rowId,n.data),t.updated++;break}this.options.onProcessed&&this.options.onProcessed(t),this.pendingPromise&&=(this.pendingPromise.resolve(),null)}catch(e){this.pendingPromise&&=(this.pendingPromise.reject(e instanceof Error?e:Error(String(e))),null)}}},oe=class{columns;dataSource;rowHeight;headerHeight;overscan;sortingEnabled;getRowId;onCellValueChanged;rowDragEntireRow;onRowDragEnd;onColumnResized;onColumnMoved;scrollTop=0;scrollLeft=0;viewportWidth=800;viewportHeight=600;currentPageIndex=0;pageSize=2**53-1;cachedRows=new Map;totalRows=0;selection;fill;input;highlight;sortFilter;rowMutation;slotPool;editManager;columnPositions=[];batchListeners=[];instructionBuffer=null;scrollVirtualization;isDestroyed=!1;_isDataLoading=!1;constructor(e){if(this.columns=e.columns,this.dataSource=e.dataSource,this.rowHeight=e.rowHeight,this.headerHeight=e.headerHeight??e.rowHeight,this.overscan=e.overscan??3,this.sortingEnabled=e.sortingEnabled??!0,this.getRowId=e.getRowId,this.onCellValueChanged=e.onCellValueChanged,this.rowDragEntireRow=e.rowDragEntireRow??!1,this.onRowDragEnd=e.onRowDragEnd,this.onColumnResized=e.onColumnResized,this.onColumnMoved=e.onColumnMoved,this.onCellValueChanged&&!this.getRowId)throw Error(`getRowId is required when onCellValueChanged is provided`);this.computeColumnPositions(),this.selection=new b({getRowCount:()=>this.totalRows,getColumnCount:()=>this.columns.length,getCellValue:(e,t)=>this.getCellValue(e,t),getRowData:e=>this.cachedRows.get(e),getColumn:e=>this.columns[e]}),this.selection.onInstruction(e=>{this.emit(e),this.highlight?.onSelectionChange()}),e.highlighting?(this.highlight=new ie({getActiveCell:()=>this.selection.getActiveCell(),getSelectionRange:()=>this.selection.getSelectionRange(),getColumn:e=>this.columns[e]},e.highlighting),this.highlight.onInstruction(e=>this.emit(e))):this.highlight=null,this.fill=new x({getRowCount:()=>this.totalRows,getColumnCount:()=>this.columns.length,getCellValue:(e,t)=>this.getCellValue(e,t),getColumn:e=>this.columns[e],setCellValue:(e,t,n)=>this.setCellValue(e,t,n)}),this.fill.onInstruction(e=>this.emit(e)),this.scrollVirtualization=new T({getRowHeight:()=>this.rowHeight,getHeaderHeight:()=>this.headerHeight,getTotalRows:()=>this.totalRows,getScrollTop:()=>this.scrollTop,getViewportHeight:()=>this.viewportHeight}),this.slotPool=new re({getRowHeight:()=>this.rowHeight,getHeaderHeight:()=>this.headerHeight,getOverscan:()=>this.overscan,getScrollTop:()=>this.scrollTop,getViewportHeight:()=>this.viewportHeight,getTotalRows:()=>this.totalRows,getScrollRatio:()=>this.scrollVirtualization.getScrollRatio(),getVirtualContentHeight:()=>this.scrollVirtualization.getVirtualContentHeight(),getRowData:e=>this.cachedRows.get(e)}),this.slotPool.onBatchInstruction(e=>this.emitBatch(e)),this.editManager=new S({getColumn:e=>this.columns[e],getCellValue:(e,t)=>this.getCellValue(e,t),setCellValue:(e,t,n)=>this.setCellValue(e,t,n),onCommit:e=>{this.slotPool.updateSlot(e)}}),this.editManager.onInstruction(e=>this.emit(e)),this.sortFilter=new E({getColumns:()=>this.columns,isSortingEnabled:()=>this.sortingEnabled,getCachedRows:()=>this.cachedRows,onSortFilterChange:async()=>{await this.fetchData(),this.highlight?.clearAllCaches(),this.scrollTop=0,this.startBatch();try{this.emit({type:`SCROLL_TO`,scrollTop:0}),this.emitContentSize(),this.emitHeaders(),this.slotPool.refreshAllSlots()}finally{this.flushBatch()}},onDataRefreshed:()=>{}}),this.sortFilter.onInstruction(e=>this.emit(e)),this.rowMutation=new ae({getCachedRows:()=>this.cachedRows,setCachedRows:e=>{this.cachedRows=e},getTotalRows:()=>this.totalRows,setTotalRows:e=>{this.totalRows=e},updateSlot:e=>this.slotPool.updateSlot(e),refreshAllSlots:()=>this.slotPool.refreshAllSlots(),emitContentSize:()=>this.emitContentSize(),clearSelectionIfInvalid:e=>this.clearSelectionIfInvalid(e)}),this.rowMutation.onInstruction(e=>this.emit(e)),this.input=new C(this,{getHeaderHeight:()=>this.headerHeight,getRowHeight:()=>this.rowHeight,getColumnPositions:()=>this.columnPositions,getColumnCount:()=>this.columns.length})}onBatchInstruction(e){return this.batchListeners.push(e),()=>{this.batchListeners=this.batchListeners.filter(t=>t!==e)}}startBatch(){this.instructionBuffer=[]}flushBatch(){let e=this.instructionBuffer;if(this.instructionBuffer=null,e&&e.length>0)for(let t of this.batchListeners)t(e)}emit(e){this.instructionBuffer?this.instructionBuffer.push(e):this.emitBatch([e])}emitBatch(e){if(e.length!==0){if(this.instructionBuffer){this.instructionBuffer.push(...e);return}for(let t of this.batchListeners)t(e)}}async initialize(){await this.fetchData(),this.slotPool.syncSlots(),this.emitContentSize(),this.emitHeaders()}setViewport(e,t,n,r){let i=this.scrollVirtualization.getScrollRatio(),a=i<1?e/i:e,o=this.viewportWidth!==n||this.viewportHeight!==r;if(!(this.scrollTop!==a||this.scrollLeft!==t||o))return;this.scrollTop=a,this.scrollLeft=t,this.viewportWidth=n,this.viewportHeight=r,this.slotPool.syncSlots();let s=this.getVisibleRowRange();this.emit({type:`UPDATE_VISIBLE_RANGE`,start:s.start,end:s.end,rowsWrapperOffset:this.slotPool.getRowsWrapperOffset()}),o&&this.emitContentSize()}async fetchData(){this._isDataLoading=!0,this.emit({type:`DATA_LOADING`});try{let e=this.sortFilter.getSortModel(),t=this.sortFilter.getFilterModel(),n={pagination:{pageIndex:this.currentPageIndex,pageSize:this.pageSize},sort:e.length>0?e:void 0,filter:Object.keys(t).length>0?t:void 0},r=await this.dataSource.fetch(n);this.cachedRows.clear();let i=this.currentPageIndex*this.pageSize;r.rows.forEach((e,t)=>{this.cachedRows.set(i+t,e)}),this.totalRows=r.totalRows,this.emit({type:`DATA_LOADED`,totalRows:this.totalRows})}catch(e){this.emit({type:`DATA_ERROR`,error:e instanceof Error?e.message:String(e)})}finally{this._isDataLoading=!1}}async setSort(e,t,n=!1){if(!this._isDataLoading)return this.sortFilter.setSort(e,t,n)}async setFilter(e,t){if(!this._isDataLoading)return this.sortFilter.setFilter(e,t)}hasActiveFilter(e){return this.sortFilter.hasActiveFilter(e)}getDistinctValuesForColumn(e,t=500){return this.sortFilter.getDistinctValuesForColumn(e,t)}openFilterPopup(e,t){this._isDataLoading||this.sortFilter.openFilterPopup(e,t)}closeFilterPopup(){this.sortFilter.closeFilterPopup()}getSortModel(){return this.sortFilter.getSortModel()}getFilterModel(){return this.sortFilter.getFilterModel()}startEdit(e,t){this.editManager.startEdit(e,t)}updateEditValue(e){this.editManager.updateValue(e)}commitEdit(){this.editManager.commit()}cancelEdit(){this.editManager.cancel()}getEditState(){return this.editManager.getState()}getCellValue(e,t){let n=this.cachedRows.get(e);if(!n)return null;let r=this.columns[t];return r?m(n,r.field):null}setCellValue(e,t,n){let r=this.cachedRows.get(e);if(!r||typeof r!=`object`)return;let i=this.columns[t];if(!i)return;let a=this.onCellValueChanged?m(r,i.field):void 0;h(r,i.field,n),this.onCellValueChanged&&this.onCellValueChanged({rowId:this.getRowId(r),colIndex:t,field:i.field,oldValue:a,newValue:n,rowData:r})}clearSelectionIfInvalid(e){let t=this.selection.getActiveCell();t&&t.row>=e&&this.selection.clearSelection()}computeColumnPositions(){this.columnPositions=[0];let e=0;for(let t of this.columns)t.hidden||(e+=t.width,this.columnPositions.push(e))}emitContentSize(){let e=this.columnPositions.at(-1)??0;this.scrollVirtualization.updateContentSize(),this.emit({type:`SET_CONTENT_SIZE`,width:e,height:this.scrollVirtualization.getVirtualHeight(),viewportWidth:this.viewportWidth,viewportHeight:this.viewportHeight,rowsWrapperOffset:this.slotPool.getRowsWrapperOffset()})}emitHeaders(){let e=this.sortFilter.getSortInfoMap();for(let t=0;t<this.columns.length;t++){let n=this.columns[t],r=n.colId??n.field,i=e.get(r);this.emit({type:`UPDATE_HEADER`,colIndex:t,column:n,sortDirection:i?.direction,sortIndex:i?.index,hasFilter:this.sortFilter.hasActiveFilter(r)})}}setColumnWidth(e,t){let n=this.columns[e];if(n){n.width=t,this.computeColumnPositions(),this.startBatch();try{this.emitContentSize(),this.emitHeaders(),this.emit({type:`COLUMNS_CHANGED`,columns:[...this.columns]}),this.slotPool.syncSlots()}finally{this.flushBatch()}this.onColumnResized?.(e,t)}}moveColumn(e,t){if(e===t||e<0||e>=this.columns.length)return;let n=t>e?t-1:t;if(n<0||n>=this.columns.length||e===n)return;console.log(`[gp-grid] moveColumn`,e,`->`,n,`batching:`,this.instructionBuffer!==null);let[r]=this.columns.splice(e,1);this.columns.splice(n,0,r),this.computeColumnPositions(),this.startBatch();try{this.emitContentSize(),this.emitHeaders(),this.emit({type:`COLUMNS_CHANGED`,columns:[...this.columns]}),this.slotPool.refreshAllSlots(),console.log(`[gp-grid] moveColumn batch size:`,this.instructionBuffer?.length)}finally{this.flushBatch(),console.log(`[gp-grid] moveColumn batch flushed`)}this.onColumnMoved?.(e,n)}commitRowDrag(e,t){let n=this.dataSource;if(n.moveRow){n.moveRow(e,t),this.reorderCachedRows(e,t),this.highlight?.clearAllCaches();let r=Math.min(e,t),i=Math.max(e,t);for(let e=r;e<=i;e++)this.slotPool.updateSlot(e)}this.onRowDragEnd?.(e,t)}reorderCachedRows(e,t){let n=this.cachedRows.get(e);if(n!==void 0)if(e<t){let r=t-1;for(let t=e;t<r;t++){let e=this.cachedRows.get(t+1);e===void 0?this.cachedRows.delete(t):this.cachedRows.set(t,e)}this.cachedRows.set(r,n)}else{for(let n=e;n>t;n--){let e=this.cachedRows.get(n-1);e===void 0?this.cachedRows.delete(n):this.cachedRows.set(n,e)}this.cachedRows.set(t,n)}}isRowDragEntireRow(){return this.rowDragEntireRow}getColumns(){return this.columns}getColumnPositions(){return[...this.columnPositions]}getRowCount(){return this.totalRows}getRowHeight(){return this.rowHeight}getHeaderHeight(){return this.headerHeight}getTotalWidth(){return this.columnPositions.at(-1)??0}getTotalHeight(){return this.scrollVirtualization.getVirtualHeight()}isScalingActive(){return this.scrollVirtualization.isScalingActive()}getNaturalHeight(){return this.scrollVirtualization.getNaturalHeight()}getScrollRatio(){return this.scrollVirtualization.getScrollRatio()}getVisibleRowRange(){return this.scrollVirtualization.getVisibleRowRange()}getScrollTopForRow(e){return this.scrollVirtualization.getScrollTopForRow(e)}getRowIndexAtDisplayY(e,t){return this.scrollVirtualization.getRowIndexAtDisplayY(e,t)}getRowTranslateY(e){return this.slotPool.getRowTranslateYForIndex(e)}getRowData(e){return this.cachedRows.get(e)}async refresh(){await this.fetchData(),this.highlight?.clearAllCaches(),this.slotPool.refreshAllSlots(),this.emitContentSize();let e=this.getVisibleRowRange();this.emit({type:`UPDATE_VISIBLE_RANGE`,start:e.start,end:e.end,rowsWrapperOffset:this.slotPool.getRowsWrapperOffset()})}async refreshFromTransaction(){let e=this.getVisibleRowRange(),t=Math.max(0,e.start-this.overscan),n=e.end+this.overscan,r=this.sortFilter.getSortModel(),i=this.sortFilter.getFilterModel(),a=await this.dataSource.fetch({pagination:{pageIndex:0,pageSize:n+1},sort:r.length>0?r:void 0,filter:Object.keys(i).length>0?i:void 0});this.totalRows=a.totalRows;for(let e=t;e<Math.min(n+1,a.rows.length);e++){let t=a.rows[e];t!==void 0&&this.cachedRows.set(e,t)}this.highlight?.clearAllCaches(),this.slotPool.refreshAllSlots(),this.emitContentSize(),this.emit({type:`UPDATE_VISIBLE_RANGE`,start:e.start,end:e.end,rowsWrapperOffset:this.slotPool.getRowsWrapperOffset()})}refreshSlotData(){this.slotPool.refreshAllSlots()}addRows(e,t){this.rowMutation.addRows(e,t)}updateRows(e){this.rowMutation.updateRows(e)}deleteRows(e){this.rowMutation.deleteRows(e)}getRow(e){return this.rowMutation.getRow(e)}setRow(e,t){this.rowMutation.setRow(e,t)}async setDataSource(e){this.editManager.getState()&&this.editManager.cancel(),this.dataSource=e,await this.refresh(),this.clearSelectionIfInvalid(this.totalRows)}setColumns(e){this.columns=e,this.computeColumnPositions(),this.emitContentSize(),this.emitHeaders(),this.slotPool.syncSlots()}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.slotPool.destroy(),this.highlight?.destroy(),this.sortFilter.destroy(),this.rowMutation.destroy(),this.cachedRows.clear(),this.batchListeners=[],this.totalRows=0)}},O=class{workerCode;maxWorkers;workers=[];workerUrl=null;nextRequestId=0;isTerminated=!1;constructor(e,t={}){this.workerCode=e;let n=typeof navigator>`u`?4:navigator.hardwareConcurrency;this.maxWorkers=Math.max(1,t.maxWorkers??n??4),t.preWarm&&this.preWarmWorkers()}getPoolSize(){return this.workers.length}getMaxWorkers(){return this.maxWorkers}isAvailable(){return!this.isTerminated&&typeof Worker<`u`}async execute(e,t){if(this.isTerminated)throw Error(`WorkerPool has been terminated`);if(typeof Worker>`u`)throw TypeError(`Web Workers are not available in this environment`);let n=this.getAvailableWorker(),r=this.nextRequestId++,i={...e,id:r};return new Promise((e,a)=>{n.pendingRequests.set(r,{resolve:e,reject:a}),n.busy=!0,t&&t.length>0?n.worker.postMessage(i,t):n.worker.postMessage(i)})}async executeParallel(e){if(this.isTerminated)throw Error(`WorkerPool has been terminated`);if(e.length===0)return[];let t=Math.min(e.length,this.maxWorkers);this.ensureWorkers(t);let n=e.map((e,t)=>{let n=t%this.workers.length,r=this.workers[n],i=this.nextRequestId++,a={...e.request,id:i};return new Promise((t,n)=>{r.pendingRequests.set(i,{resolve:t,reject:n}),r.busy=!0,e.transferables&&e.transferables.length>0?r.worker.postMessage(a,e.transferables):r.worker.postMessage(a)})});return Promise.all(n)}terminate(){for(let e of this.workers){e.worker.terminate();for(let[,t]of e.pendingRequests)t.reject(Error(`Worker pool terminated`));e.pendingRequests.clear()}this.workers=[],this.workerUrl&&=(URL.revokeObjectURL(this.workerUrl),null),this.isTerminated=!0}preWarmWorkers(){this.ensureWorkers(this.maxWorkers)}ensureWorkers(e){let t=Math.min(e,this.maxWorkers)-this.workers.length;for(let e=0;e<t;e++)this.createWorker()}getAvailableWorker(){return this.workers.find(e=>!e.busy)||(this.workers.length<this.maxWorkers?this.createWorker():this.workers.reduce((e,t)=>t.pendingRequests.size<e.pendingRequests.size?t:e,this.workers[0]))}createWorker(){if(!this.workerUrl){let e=new Blob([this.workerCode],{type:`application/javascript`});this.workerUrl=URL.createObjectURL(e)}let e=new Worker(this.workerUrl),t={worker:e,busy:!1,pendingRequests:new Map};return e.onmessage=e=>{let{id:n}=e.data,r=t.pendingRequests.get(n);r&&(t.pendingRequests.delete(n),t.pendingRequests.size===0&&(t.busy=!1),e.data.type===`error`?r.reject(Error(e.data.error)):r.resolve(e.data))},e.onerror=e=>{for(let[,n]of t.pendingRequests)n.reject(Error(`Worker error: ${e.message}`));t.pendingRequests.clear(),t.busy=!1,this.respawnWorker(t)},this.workers.push(t),t}respawnWorker(e){let t=this.workers.indexOf(e);if(t!==-1){try{e.worker.terminate()}catch{}this.workers.splice(t,1),this.workers.length<this.maxWorkers&&!this.isTerminated&&this.createWorker()}}};function k(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}const A=e=>e==null?``:Array.isArray(e)?e.join(`, `):typeof e==`object`&&!(e instanceof Date)?JSON.stringify(e):String(e);function se(e,t){if(e==null&&t==null)return 0;if(e==null)return 1;if(t==null)return-1;let n=Number(e),r=Number(t);return!Number.isNaN(n)&&!Number.isNaN(r)?n-r:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():A(e).localeCompare(A(t))}function ce(e,t){return[...e].sort((e,n)=>{for(let{colId:r,direction:i}of t){let t=se(k(e,r),k(n,r));if(t!==0)return i===`asc`?t:-t}return 0})}const j=globalThis;j.onmessage!==void 0&&(j.onmessage=e=>{let{type:t,id:n,data:r,sortModel:i}=e.data;if(t===`sort`)try{let e=ce(r,i);j.postMessage?.({type:`sorted`,id:n,data:e})}catch(e){j.postMessage?.({type:`error`,id:n,error:String(e)})}});var M=class{heap=[];compare;constructor(e){this.compare=e}push(e){this.heap.push(e),this.bubbleUp(this.heap.length-1)}pop(){if(this.heap.length===0)return;let e=this.heap[0],t=this.heap.pop();return this.heap.length>0&&t&&(this.heap[0]=t,this.bubbleDown(0)),e}size(){return this.heap.length}bubbleUp(e){for(;e>0;){let t=Math.floor((e-1)/2);if(this.compare(this.heap[e],this.heap[t])>=0)break;this.swap(e,t),e=t}}bubbleDown(e){let t=this.heap.length;for(;;){let n=2*e+1,r=2*e+2,i=e;if(n<t&&this.compare(this.heap[n],this.heap[i])<0&&(i=n),r<t&&this.compare(this.heap[r],this.heap[i])<0&&(i=r),i===e)break;this.swap(e,i),e=i}}swap(e,t){let n=this.heap[e];this.heap[e]=this.heap[t],this.heap[t]=n}};const N=(e,t,n)=>{let r=[];for(let i=0;i<n;i++)r.push(e.columns[i][t]);return r};function P(e,t){if(e.length===0)return new Uint32Array;if(e.length===1){let t=e[0],n=new Uint32Array(t.indices.length);for(let e=0;e<t.indices.length;e++)n[e]=t.indices[e]+t.offset;return n}let n=0;for(let t of e)n+=t.indices.length;let r=new Uint32Array(n),i=t===`asc`?1:-1,a=new M((e,t)=>(e.value-t.value)*i);for(let t=0;t<e.length;t++){let n=e[t];if(n.indices.length>0){let e=n.indices[0];a.push({chunkIndex:t,positionInChunk:0,value:n.values[0],globalIndex:e+n.offset})}}let o=0;for(;a.size()>0;){let t=a.pop();r[o++]=t.globalIndex;let n=e[t.chunkIndex],i=t.positionInChunk+1;if(i<n.indices.length){let e=n.indices[i];a.push({chunkIndex:t.chunkIndex,positionInChunk:i,value:n.values[i],globalIndex:e+n.offset})}}return r}function F(e){if(e.length===0)return new Uint32Array;if(e.length===1){let t=e[0],n=new Uint32Array(t.indices.length);for(let e=0;e<t.indices.length;e++)n[e]=t.indices[e]+t.offset;return n}let t=e[0].directions,n=t.length,r=0;for(let t of e)r+=t.indices.length;let i=new Uint32Array(r),a=new M((e,n)=>{for(let r=0;r<t.length;r++){let i=(e.values[r]-n.values[r])*t[r];if(i!==0)return i}return 0});for(let t=0;t<e.length;t++){let r=e[t];if(r.indices.length>0){let e=r.indices[0];a.push({chunkIndex:t,positionInChunk:0,values:N(r,0,n),globalIndex:e+r.offset})}}let o=0;for(;a.size()>0;){let t=a.pop();i[o++]=t.globalIndex;let r=e[t.chunkIndex],s=t.positionInChunk+1;if(s<r.indices.length){let e=r.indices[s];a.push({chunkIndex:t.chunkIndex,positionInChunk:s,values:N(r,s,n),globalIndex:e+r.offset})}}return i}function le(e,t){if(e.length<=1)return new Uint32Array;let n=[],r=0;for(let t=0;t<e.length-1;t++){let i=e[t],a=e[t+1];if(i.indices.length===0||a.indices.length===0){r+=i.indices.length;continue}let o=i.indices.length-1,s=i.values[o],c=a.values[0];if(s===c){let e=o;for(;e>0&&i.values[e-1]===s;)e--;let t=0;for(;t<a.indices.length-1&&a.values[t+1]===c;)t++;let l=r+e,u=r+i.indices.length+t+1;n.push(l,u)}r+=i.indices.length}return new Uint32Array(n)}var I=class{pool;parallelThreshold;minChunkSize;isTerminated=!1;constructor(e={}){this.pool=new O(`
|
|
3
|
-
//
|
|
1
|
+
const e=(e,t,n,r,i)=>{let a=0,o=0;return e<40+i?o=-10:e>n-40&&(o=10),t<40?a=-10:t>r-40&&(a=10),a!==0||o!==0?{dx:a,dy:o}:null};var t=class{active=!1;colIndex=-1;startX=0;initialWidth=0;currentWidth=0;core;constructor(e){this.core=e}get isActive(){return this.active}start(e,t,n){return n.button!==0||this.core.getColumns()[e]?.resizable===!1?{preventDefault:!1,stopPropagation:!1}:(this.active=!0,this.colIndex=e,this.startX=n.clientX,this.initialWidth=t,this.currentWidth=t,{preventDefault:!0,stopPropagation:!0,startDrag:`column-resize`})}move(e,t){let n=this.core.getColumns()[this.colIndex],r=n?.minWidth??50,i=n?.maxWidth,a=this.initialWidth+(e.clientX-this.startX);a=Math.max(r,a),i!==void 0&&(a=Math.min(i,a)),this.currentWidth=a;let o=e.clientX-t.left>t.width-40?10:0,s=o===0?null:{dx:o,dy:0};return{targetRow:0,targetCol:this.colIndex,autoScroll:s}}end(){this.active&&this.core.setColumnWidth(this.colIndex,this.currentWidth),this.active=!1,this.colIndex=-1}getState(){return this.active===!1?null:{colIndex:this.colIndex,initialWidth:this.initialWidth,currentWidth:this.currentWidth}}};const n=e=>{let t=[0],n=0;for(let r of e)n+=r.width,t.push(n);return t},r=e=>e.at(-1)??0,i=(e,t)=>{let i=n(e),a=r(i);if(t<=a||a===0)return{positions:i,widths:e.map(e=>e.width)};let o=t/a,s=e.map(e=>e.width*o),c=[0],l=0;for(let e of s)l+=e,c.push(l);return{positions:c,widths:s}},a=(e,t)=>{for(let n=0;n<t.length-1;n++)if(e>=t[n]&&e<t[n+1])return n;return e>=t.at(-1)?t.length-2:0},o=e=>({minRow:Math.min(e.startRow,e.endRow),maxRow:Math.max(e.startRow,e.endRow),minCol:Math.min(e.startCol,e.endCol),maxCol:Math.max(e.startCol,e.endCol)}),s=(e,t,n)=>e>=n.minRow&&e<=n.maxRow&&t>=n.minCol&&t<=n.maxCol,c=(e,t,n)=>n?s(e,t,o(n)):!1,l=(e,t,n)=>n?.row===e&&n?.col===t,u=(e,t)=>!t||t.end<0||t.start>t.end?!0:e>=t.start&&e<=t.end,d=(e,t,n)=>n?.row===e&&n?.col===t,f=(e,t,n,r,i)=>{if(!n||!r||!i)return!1;let{minRow:a,maxRow:s,minCol:c,maxCol:l}=o(r),u=i.row>s,d=i.row<a;return u?e>s&&e<=i.row&&t>=c&&t<=l:d?e<a&&e>=i.row&&t>=c&&t<=l:!1},p=(e,t,n,r)=>{let i=[`gp-grid-cell`];return e&&i.push(`gp-grid-cell--active`),t&&!e&&i.push(`gp-grid-cell--selected`),n&&i.push(`gp-grid-cell--editing`),r&&i.push(`gp-grid-cell--fill-preview`),i.join(` `)},m=(e,t)=>{if(!t)return!1;let{minRow:n,maxRow:r}=o(t);return e>=n&&e<=r},h=(e,t)=>{if(!t)return!1;let{minCol:n,maxCol:r}=o(t);return e>=n&&e<=r};function g(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}function _(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];if(typeof i!=`object`||!i)return;i=i[t]}typeof i==`object`&&i&&(i[r.at(-1)]=n)}const v=()=>{let e=[];return{onInstruction:t=>(e.push(t),()=>{e=e.filter(e=>e!==t)}),emit:t=>{for(let n of e)n(t)},clearListeners:()=>{e=[]}}},ee=()=>{let e=v(),t=[];return{onInstruction:e.onInstruction,onBatchInstruction:e=>(t.push(e),()=>{t=t.filter(t=>t!==e)}),emit:n=>{e.emit(n);for(let e of t)e([n])},emitBatch:n=>{if(n.length!==0){for(let e of t)e(n);for(let t of n)e.emit(t)}},clearListeners:()=>{e.clearListeners(),t=[]}}},y=(e,t)=>{for(let n of e.values())if(n.rowIndex===t)return n;return null},te=(e,t,n,r,i,a=0)=>{let o=y(i,n);if(!o){t.scrollTop=e.getScrollTopForRow(n);return}let s=a+o.translateY-t.scrollTop,c=s+r;if(s<0)t.scrollTop=e.getScrollTopForRow(n);else if(c>t.clientHeight){let i=Math.floor(t.clientHeight/r),a=Math.max(0,n-i+1);t.scrollTop=e.getScrollTopForRow(a)}},b=(e,t)=>e==null?``:t?t(e):Array.isArray(e)?e.join(`, `):typeof e==`object`?e instanceof Date?String(e):JSON.stringify(e):String(e),ne=e=>{let{activeCell:t,selectionRange:n,slots:r,columns:i,visibleColumnsWithIndices:a,columnPositions:o,columnWidths:s,rowHeight:c}=e;if(!t&&!n)return null;let l,u,d,f;if(n)l=Math.max(n.startRow,n.endRow),u=Math.max(n.startCol,n.endCol),d=Math.min(n.startCol,n.endCol),f=Math.max(n.startCol,n.endCol);else if(t)l=t.row,u=t.col,d=u,f=u;else return null;for(let e=d;e<=f;e++){let t=i[e];if(!(!t||t.hidden)&&t.editable!==!0)return null}let p=a.findIndex(e=>e.originalIndex===u);if(p===-1)return null;let m=null;for(let e of r.values())if(e.rowIndex===l){m=e.translateY;break}if(m===null)return null;let h=o[p]??0,g=s[p]??0;return{top:m+c-5,left:h+g-20}},re=(e,t,n=8)=>{let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=r.bottom+4,o=r.left,s=Math.max(200,r.width);return o+i.width>window.innerWidth-n&&(o=window.innerWidth-i.width-n),o=Math.max(n,o),a+i.height>window.innerHeight-n&&(a=r.top-i.height-4),a=Math.max(n,a),{top:a,left:o,minWidth:s}},x=e=>({pagination:{pageIndex:e.pageIndex,pageSize:e.pageSize},sort:e.sortModel.length>0?e.sortModel:void 0,filter:Object.keys(e.filterModel).length>0?e.filterModel:void 0}),ie=(e,t,n)=>{let r=e.get(t);if(r!==void 0){if(t<n){let i=n-1;for(let n=t;n<i;n++){let t=e.get(n+1);t===void 0?e.delete(n):e.set(n,t)}e.set(i,r);return}for(let r=t;r>n;r--){let t=e.get(r-1);t===void 0?e.delete(r):e.set(r,t)}e.set(n,r)}},ae=e=>{let t=[0],n=0;for(let r of e)r.hidden||(n+=r.width,t.push(n));return t},oe=(e,t,n,r)=>{let i=e.get(n);if(!i)return null;let a=t[r];return a?g(i,a.field):null},se=(e,t,n,r,i,a)=>{let o=e.get(n);if(!o||typeof o!=`object`)return;let s=t[r];if(!s)return;let c=a.onCellValueChanged!==void 0,l=c?g(o,s.field):void 0;_(o,s.field,i),c&&a.onCellValueChanged({rowId:a.getRowId(o),colIndex:r,field:s.field,oldValue:l,newValue:i,rowData:o})};var ce=class{active=!1;sourceColIndex=-1;startX=0;startY=0;thresholdMet=!1;shiftKey=!1;ghostWidth=0;ghostHeight=0;currentX=0;currentY=0;dropTargetIndex=null;core;deps;constructor(e,t){this.core=e,this.deps=t}updateDeps(e){this.deps=e}get isActive(){return this.active}get isDraggingForDisplay(){return this.active&&this.thresholdMet}start(e,t,n,r){return r.button!==0||this.core.getColumns()[e]?.movable===!1?{preventDefault:!1,stopPropagation:!1}:(this.active=!0,this.sourceColIndex=e,this.startX=r.clientX,this.startY=r.clientY,this.thresholdMet=!1,this.shiftKey=r.shiftKey,this.ghostWidth=t,this.ghostHeight=n,this.currentX=r.clientX,this.currentY=r.clientY,this.dropTargetIndex=null,{preventDefault:!0,stopPropagation:!0,startDrag:`column-move`})}move(e,t){let n=e.clientX-this.startX,r=e.clientY-this.startY;if(this.thresholdMet===!1){if(!(Math.abs(n)>5||Math.abs(r)>5))return null;this.thresholdMet=!0}this.currentX=e.clientX,this.currentY=e.clientY;let{left:i,width:o,scrollLeft:s}=t,c=e.clientX-i+s,l=this.deps.getColumnPositions(),u=this.deps.getColumnCount();this.dropTargetIndex=Math.max(0,Math.min(a(c,l),u));let d=e.clientX-i,f=0;d<40?f=-10:d>o-40&&(f=10);let p=f===0?null:{dx:f,dy:0};return{targetRow:0,targetCol:this.dropTargetIndex??0,autoScroll:p}}end(e){this.thresholdMet?this.commitMove():this.treatAsHeaderClick(e),this.reset()}commitMove(){if(this.dropTargetIndex===null)return;let e=this.sourceColIndex,t=this.deps.getOriginalColumnIndex?this.deps.getOriginalColumnIndex(Math.min(this.dropTargetIndex,this.deps.getColumnCount()-1)):this.dropTargetIndex;e!==t&&this.core.moveColumn(e,t)}treatAsHeaderClick(e){let t=this.core.getColumns()[this.sourceColIndex];if(!t)return;let n=t.colId??t.field,r=this.core.getSortModel().find(e=>e.colId===n)?.direction;this.core.setSort(n,e(r),this.shiftKey)}reset(){this.active=!1,this.sourceColIndex=-1,this.thresholdMet=!1,this.shiftKey=!1,this.dropTargetIndex=null}getState(){return this.active===!1?null:{sourceColIndex:this.sourceColIndex,currentX:this.currentX,currentY:this.currentY,dropTargetIndex:this.dropTargetIndex,ghostWidth:this.ghostWidth,ghostHeight:this.ghostHeight}}},le=class{active=!1;sourceRowIndex=-1;startX=0;startY=0;thresholdMet=!1;currentX=0;currentY=0;dropTargetIndex=null;core;deps;constructor(e,t){this.core=e,this.deps=t}updateDeps(e){this.deps=e}get isActive(){return this.active}get isDraggingForDisplay(){return this.active&&this.thresholdMet}start(e,t,n){this.active=!0,this.sourceRowIndex=e,this.startX=t,this.startY=n,this.thresholdMet=!1,this.currentX=t,this.currentY=n,this.dropTargetIndex=null}move(t,n){let r=t.clientX-this.startX,i=t.clientY-this.startY;if(this.thresholdMet===!1){if(!(Math.abs(r)>5||Math.abs(i)>5))return null;this.thresholdMet=!0}this.currentX=t.clientX,this.currentY=t.clientY;let{top:a,left:o,height:s,width:c,scrollTop:l}=n,u=this.deps.getHeaderHeight(),d=t.clientY-a,f=this.core.getRowCount(),p=Math.max(0,Math.min(this.core.getRowIndexAtDisplayY(d,l),f));return this.dropTargetIndex=p,{targetRow:p,targetCol:0,autoScroll:e(t.clientY-a,t.clientX-o,s,c,u)}}end(){this.thresholdMet&&this.dropTargetIndex!==null&&this.dropTargetIndex!==this.sourceRowIndex&&this.core.commitRowDrag(this.sourceRowIndex,this.dropTargetIndex),this.active=!1,this.sourceRowIndex=-1,this.thresholdMet=!1,this.dropTargetIndex=null}getState(){return this.active===!1?null:{sourceRowIndex:this.sourceRowIndex,currentX:this.currentX,currentY:this.currentY,dropTargetIndex:this.dropTargetIndex,dropIndicatorY:this.dropTargetIndex===null?0:this.core.getRowTranslateY(this.dropTargetIndex)}}},ue=class{active=!1;core;constructor(e){this.core=e}get isActive(){return this.active}start(){this.active=!0}moveToTarget(e,t){this.active!==!1&&this.core.selection.startSelection({row:e,col:t},{shift:!0})}end(){this.active=!1}},de=class{active=!1;sourceRange=null;target=null;core;constructor(e){this.core=e}get isActive(){return this.active}get stateSnapshot(){return{sourceRange:this.sourceRange,target:this.target}}start(e,t){if(!e&&!t)return{preventDefault:!1,stopPropagation:!1};let n=t??{startRow:e.row,startCol:e.col,endRow:e.row,endCol:e.col};return this.core.fill.startFillDrag(n),this.sourceRange=n,this.target={row:Math.max(n.startRow,n.endRow),col:Math.max(n.startCol,n.endCol)},this.active=!0,{preventDefault:!0,stopPropagation:!0,startDrag:`fill`}}moveToTarget(e,t){this.active!==!1&&(this.core.fill.updateFillDrag(e,t),this.target={row:e,col:t})}end(){this.active&&(this.core.fill.commitFillDrag(),this.core.refreshSlotData()),this.active=!1,this.sourceRange=null,this.target=null}},fe=class{record=null;set(e){this.record=e}clear(){this.record=null}consume(){let e=this.record;return this.record=null,e}};const pe=e=>{switch(e){case`ArrowUp`:return`up`;case`ArrowDown`:return`down`;case`ArrowLeft`:return`left`;case`ArrowRight`:return`right`;default:return null}};var me=class{core;constructor(e){this.core=e}handle(e,t,n,r){if(r||n!==null&&e.key!==`Enter`&&e.key!==`Escape`&&e.key!==`Tab`)return{preventDefault:!1};let i=pe(e.key);if(i!==null)return this.moveFocus(i,e.shiftKey);let a=e.ctrlKey||e.metaKey;return this.handleAction(e.key,t,n,e.shiftKey,a)}moveFocus(e,t){let{selection:n}=this.core;return n.moveFocus(e,t),{preventDefault:!0,scrollToCell:n.getActiveCell()??void 0}}handleAction(e,t,n,r,i){switch(e){case`Enter`:return this.handleEnter(t,n);case`Escape`:return this.handleEscape(n);case`Tab`:return this.handleTab(n,r);default:return this.handleNonSpecialKey(e,t,n,i)}}handleEnter(e,t){return t?this.core.commitEdit():e&&this.core.startEdit(e.row,e.col),{preventDefault:!0}}handleEscape(e){return e?this.core.cancelEdit():this.core.selection.clearSelection(),{preventDefault:!0}}handleTab(e,t){return e&&this.core.commitEdit(),this.core.selection.moveFocus(t?`left`:`right`,!1),{preventDefault:!0}}handleNonSpecialKey(e,t,n,r){let{selection:i}=this.core;return e===`a`&&r?(i.selectAll(),{preventDefault:!0}):e===`c`&&r?(i.copySelectionToClipboard(),{preventDefault:!0}):e===`F2`?(t&&!n&&this.core.startEdit(t.row,t.col),{preventDefault:!0}):e===`Delete`||e===`Backspace`?t&&!n?(this.core.startEdit(t.row,t.col),{preventDefault:!0}):{preventDefault:!1}:(t&&!n&&!r&&e.length===1&&this.core.startEdit(t.row,t.col),{preventDefault:!1})}};const he=(t,n,r,i)=>{let{top:o,left:s,width:c,height:l,scrollTop:u,scrollLeft:d}=i,f=n.getColumnPositions(),p=n.getColumnCount(),m=r.clientY-o,h=r.clientX-s+d,g=Math.max(0,Math.min(t.getRowIndexAtDisplayY(m,u),t.getRowCount()-1)),_=Math.max(0,Math.min(a(h,f),p-1));return{row:g,col:n.getOriginalColumnIndex?n.getOriginalColumnIndex(_):_,autoScroll:e(r.clientY-o,r.clientX-s,l,c,n.getHeaderHeight())}},S=e=>e==null?`asc`:e===`asc`?`desc`:null;var C=class{core;deps;columnResize;columnMove;rowDrag;selectionDrag;fillDrag;pendingRowDrag=new fe;keyboard;constructor(e,n){this.core=e,this.deps=n,this.columnResize=new t(e),this.columnMove=new ce(e,n),this.rowDrag=new le(e,n),this.selectionDrag=new ue(e),this.fillDrag=new de(e),this.keyboard=new me(e)}updateDeps(e){this.deps={...this.deps,...e},this.columnMove.updateDeps(this.deps),this.rowDrag.updateDeps(this.deps)}getDragState(){let e=this.getDragType(),t=this.fillDrag.stateSnapshot;return{isDragging:e!==null,dragType:e,fillSourceRange:t.sourceRange,fillTarget:t.target,columnResize:this.columnResize.getState(),columnMove:this.columnMove.getState(),rowDrag:this.rowDrag.getState()}}getDragType(){return this.fillDrag.isActive?`fill`:this.columnResize.isActive?`column-resize`:this.columnMove.isDraggingForDisplay?`column-move`:this.rowDrag.isDraggingForDisplay?`row-drag`:this.selectionDrag.isActive?`selection`:null}handleHeaderMouseDown(e,t,n,r){return this.columnMove.start(e,t,n,r)}handleHeaderResizeMouseDown(e,t,n){return this.columnResize.start(e,t,n)}handleCellMouseDown(e,t,n){if(n.button!==0||this.core.getEditState()!==null)return ge;let r=(this.core.getColumns()[t]?.rowDrag===!0||this.core.isRowDragEntireRow())&&!n.shiftKey;return r&&n.pointerType===`touch`?this.startPendingRowDrag(e,t,n):r?this.startRowDrag(e,t,n):this.startSelectionClick(e,t,n)}startPendingRowDrag(e,t,n){return this.pendingRowDrag.set({rowIndex:e,colIndex:t,clientX:n.clientX,clientY:n.clientY}),this.core.selection.startSelection({row:e,col:t},{shift:!1,ctrl:!1}),{preventDefault:!1,stopPropagation:!1,focusContainer:!0,startDrag:`row-drag-pending`}}startRowDrag(e,t,n){return this.rowDrag.start(e,n.clientX,n.clientY),this.core.selection.startSelection({row:e,col:t},{shift:!1,ctrl:!1}),{preventDefault:!0,stopPropagation:!0,focusContainer:!0,startDrag:`row-drag`}}startSelectionClick(e,t,n){return this.core.selection.startSelection({row:e,col:t},{shift:n.shiftKey,ctrl:n.ctrlKey||n.metaKey}),{preventDefault:!1,stopPropagation:!1,focusContainer:!0,startDrag:n.shiftKey?void 0:`selection`}}handleCellDoubleClick(e,t){this.core.startEdit(e,t)}handleCellMouseEnter(e,t){this.core.highlight?.setHoverPosition({row:e,col:t})}handleCellMouseLeave(){this.core.highlight?.setHoverPosition(null)}handleFillHandleMouseDown(e,t,n){return this.fillDrag.start(e,t)}handleHeaderClick(e,t){let n=this.core.getSortModel().find(t=>t.colId===e)?.direction;this.core.setSort(e,S(n),t)}startSelectionDrag(){this.selectionDrag.start()}confirmPendingRowDrag(){let e=this.pendingRowDrag.consume();return e===null?!1:(this.rowDrag.start(e.rowIndex,e.clientX,e.clientY),!0)}cancelPendingRowDrag(){this.pendingRowDrag.clear()}handleDragMove(e,t){return this.columnResize.isActive?this.columnResize.move(e,t):this.columnMove.isActive?this.columnMove.move(e,t):this.rowDrag.isActive?this.rowDrag.move(e,t):this.selectionFillMove(e,t)}selectionFillMove(e,t){if((this.selectionDrag.isActive||this.fillDrag.isActive)===!1)return null;let n=he(this.core,this.deps,e,t);return this.selectionDrag.moveToTarget(n.row,n.col),this.fillDrag.moveToTarget(n.row,n.col),{targetRow:n.row,targetCol:n.col,autoScroll:n.autoScroll}}handleDragEnd(){if(this.columnResize.isActive)return this.columnResize.end();if(this.columnMove.isActive)return this.columnMove.end(S);if(this.rowDrag.isActive)return this.rowDrag.end();this.selectionDrag.end(),this.fillDrag.end()}handleWheel(e,t,n){return this.core.isScalingActive()?{dy:e*n,dx:t*n}:null}handleKeyDown(e,t,n,r){return this.keyboard.handle(e,t,n,r)}};const ge={preventDefault:!1,stopPropagation:!1};var w=class{options;highlightingOptions;hoverPosition=null;emitter=v();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;rowClassCache=new Map;columnClassCache=new Map;cellClassCache=new Map;constructor(e,t={}){this.options=e,this.highlightingOptions=t}isEnabled(){return!!(this.highlightingOptions.computeRowClasses||this.highlightingOptions.computeColumnClasses||this.highlightingOptions.computeCellClasses)}updateOptions(e){this.highlightingOptions=e,this.clearAllCaches()}setHoverPosition(e){this.isEnabled()&&(this.hoverPosition?.row===e?.row&&this.hoverPosition?.col===e?.col||(this.rowClassCache.clear(),this.columnClassCache.clear(),this.cellClassCache.clear(),this.hoverPosition=e,this.emit({type:`SET_HOVER_POSITION`,position:e})))}getHoverPosition(){return this.hoverPosition}onSelectionChange(){this.clearAllCaches()}buildRowContext(e,t){let n=this.options.getActiveCell(),r=this.options.getSelectionRange();return{rowIndex:e,colIndex:null,column:void 0,rowData:t,hoverPosition:this.hoverPosition,activeCell:n,selectionRange:r,isHovered:this.hoverPosition?.row===e,isActive:n?.row===e,isSelected:m(e,r)}}buildColumnContext(e,t){let n=this.options.getActiveCell(),r=this.options.getSelectionRange();return{rowIndex:null,colIndex:e,column:t,rowData:void 0,hoverPosition:this.hoverPosition,activeCell:n,selectionRange:r,isHovered:this.hoverPosition?.col===e,isActive:n?.col===e,isSelected:h(e,r)}}buildCellContext(e,t,n,r){let i=this.options.getActiveCell(),a=this.options.getSelectionRange(),s=this.hoverPosition?.row===e&&this.hoverPosition?.col===t,c=!1;if(a){let{minRow:n,maxRow:r,minCol:i,maxCol:s}=o(a);c=e>=n&&e<=r&&t>=i&&t<=s}return{rowIndex:e,colIndex:t,column:n,rowData:r,hoverPosition:this.hoverPosition,activeCell:i,selectionRange:a,isHovered:s,isActive:i?.row===e&&i?.col===t,isSelected:c}}computeRowClasses(e,t){let n=this.highlightingOptions.computeRowClasses;if(!n)return[];let r=this.rowClassCache.get(e);if(r!==void 0)return r;let i=n(this.buildRowContext(e,t));return this.rowClassCache.set(e,i),i}computeColumnClasses(e,t){let n=this.columnClassCache.get(e);if(n!==void 0)return n;let r=this.buildColumnContext(e,t),i;if(t.computeColumnClasses)i=t.computeColumnClasses(r);else if(this.highlightingOptions.computeColumnClasses)i=this.highlightingOptions.computeColumnClasses(r);else return[];return this.columnClassCache.set(e,i),i}computeCellClasses(e,t,n,r){let i=`${e},${t}`,a=this.cellClassCache.get(i);if(a!==void 0)return a;let o=this.buildCellContext(e,t,n,r),s;if(n.computeCellClasses)s=n.computeCellClasses(o);else if(this.highlightingOptions.computeCellClasses)s=this.highlightingOptions.computeCellClasses(o);else return[];return this.cellClassCache.set(i,s),s}computeCombinedCellClasses(e,t,n,r){let i=this.computeColumnClasses(t,n),a=this.computeCellClasses(e,t,n,r);return[...i,...a]}clearAllCaches(){this.rowClassCache.clear(),this.columnClassCache.clear(),this.cellClassCache.clear()}destroy(){this.emitter.clearListeners(),this.clearAllCaches(),this.hoverPosition=null}},T=class{options;emitter=v();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getRow(e){return this.options.getCachedRows().get(e)}addRows(e,t){if(e.length===0)return;let n=this.options.getCachedRows(),r=this.options.getTotalRows(),i=t??r,a=r+e.length;if(i<r){let t=new Map;for(let[r,a]of n)r>=i?t.set(r+e.length,a):t.set(r,a);this.options.setCachedRows(t)}let o=this.options.getCachedRows();e.forEach((e,t)=>{o.set(i+t,e)}),this.options.setTotalRows(a);let s=e.map((e,t)=>i+t);this.emit({type:`ROWS_ADDED`,indices:s,count:s.length,totalRows:a}),this.options.emitContentSize(),this.options.refreshAllSlots()}updateRows(e){if(e.length===0)return;let t=this.options.getCachedRows(),n=[];for(let r of e){let e=t.get(r.index);e&&(t.set(r.index,{...e,...r.data}),n.push(r.index))}if(n.length!==0){this.emit({type:`ROWS_UPDATED`,indices:n});for(let e of n)this.options.updateSlot(e)}}deleteRows(e){if(e.length===0)return;let t=this.options.getCachedRows(),n=this.options.getTotalRows(),r=[...e].sort((e,t)=>t-e);for(let e of r){if(e<0||e>=n)continue;t.delete(e);let r=new Map;for(let[n,i]of t)n>e?r.set(n-1,i):r.set(n,i);this.options.setCachedRows(r),n--}this.options.setTotalRows(n),this.options.clearSelectionIfInvalid(n),this.emit({type:`ROWS_REMOVED`,indices:r,totalRows:n}),this.options.emitContentSize(),this.options.refreshAllSlots()}setRow(e,t){let n=this.options.getTotalRows();e<0||e>=n||(this.options.getCachedRows().set(e,t),this.emit({type:`ROWS_UPDATED`,indices:[e]}),this.options.updateSlot(e))}destroy(){this.emitter.clearListeners()}};const _e=1e7;var ve=class{naturalContentHeight=0;virtualContentHeight=0;scrollRatio=1;options;constructor(e){this.options=e}updateContentSize(){let e=this.options.getTotalRows(),t=this.options.getRowHeight(),n=this.options.getHeaderHeight(),r=this.options.getViewportHeight(),i=e*t;if(this.naturalContentHeight=i+n,this.naturalContentHeight>_e){this.virtualContentHeight=_e;let e=this.virtualContentHeight-n-r,a=Math.ceil((i-r)/t)*t;this.scrollRatio=a>0?e/a:1}else this.virtualContentHeight=this.naturalContentHeight,this.scrollRatio=1;return{naturalHeight:this.naturalContentHeight,virtualHeight:this.virtualContentHeight,scrollRatio:this.scrollRatio}}isScalingActive(){return this.scrollRatio<1}getNaturalHeight(){let e=this.options.getTotalRows(),t=this.options.getRowHeight(),n=this.options.getHeaderHeight();return this.naturalContentHeight||e*t+n}getVirtualHeight(){let e=this.options.getTotalRows(),t=this.options.getRowHeight(),n=this.options.getHeaderHeight();return this.virtualContentHeight||e*t+n}getScrollRatio(){return this.scrollRatio}getVisibleRowRange(){let e=this.options.getViewportHeight(),t=this.options.getScrollTop(),n=this.options.getRowHeight(),r=this.options.getTotalRows(),i=e,a=Math.max(0,Math.floor(t/n)),o=Math.min(r-1,Math.ceil((t+i)/n)-1);return{start:a,end:Math.max(a,o)}}getScrollTopForRow(e){return e*this.options.getRowHeight()*this.scrollRatio}getRowIndexAtDisplayY(e,t){let n=this.options.getRowHeight(),r=e+(this.scrollRatio<1?t/this.scrollRatio:t);return Math.floor(r/n)}getVirtualContentHeight(){return this.virtualContentHeight}},ye=class{options;emitter=v();sortModel=[];filterModel={};openFilterColIndex=null;onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}async setSort(e,t,n=!1){if(!this.options.isSortingEnabled()||this.options.getColumns().find(t=>(t.colId??t.field)===e)?.sortable===!1)return;let r=this.sortModel.findIndex(t=>t.colId===e);n?t===null&&r>=0?this.sortModel.splice(r,1):r>=0?this.sortModel[r].direction=t:this.sortModel.push({colId:e,direction:t}):this.sortModel=t===null?[]:[{colId:e,direction:t}],await this.options.onSortFilterChange(),this.options.onDataRefreshed()}getSortModel(){return[...this.sortModel]}async setFilter(e,t){this.options.getColumns().find(t=>(t.colId??t.field)===e)?.filterable!==!1&&(t===null||typeof t==`string`&&t.trim()===``||typeof t==`object`&&t.conditions?.length===0?delete this.filterModel[e]:typeof t==`string`?this.filterModel[e]={conditions:[{type:`text`,operator:`contains`,value:t}],combination:`and`}:this.filterModel[e]=t,await this.options.onSortFilterChange(),this.options.onDataRefreshed())}getFilterModel(){return{...this.filterModel}}hasActiveFilter(e){let t=this.filterModel[e];return t?t.conditions.length>0:!1}isColumnSortable(e){return this.options.isSortingEnabled()?this.options.getColumns()[e]?.sortable!==!1:!1}isColumnFilterable(e){return this.options.getColumns()[e]?.filterable!==!1}getDistinctValuesForColumn(e,t=500,n=1e5){let r=this.options.getColumns().find(t=>(t.colId??t.field)===e);if(!r)return[];let i=this.options.getCachedRows(),a=i.size,o=a>n?Math.ceil(a/n):1,s=new Map;for(let e=0;e<a;e+=o){let n=i.get(e);if(n===void 0)continue;let a=g(n,r.field),[o,c]=this.normalizeDistinctValue(a);if(!s.has(o)&&(s.set(o,c),s.size>=t))break}let c=Array.from(s.values());return c.sort((e,t)=>{let n=b(e),r=b(t);return n.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})}),c}normalizeDistinctValue(e){if(Array.isArray(e)){let t=[...e].sort((e,t)=>{let n=String(e),r=String(t);return n===r?0:n<r?-1:1});return[JSON.stringify(t),t]}return[JSON.stringify(e),e]}openFilterPopup(e,t){if(this.openFilterColIndex===e){this.closeFilterPopup();return}let n=this.options.getColumns()[e];if(!n||!this.isColumnFilterable(e))return;let r=n.colId??n.field,i=this.getDistinctValuesForColumn(r);this.openFilterColIndex=e,this.emit({type:`OPEN_FILTER_POPUP`,colIndex:e,column:n,anchorRect:t,distinctValues:i,currentFilter:this.filterModel[r]})}closeFilterPopup(){this.openFilterColIndex=null,this.emit({type:`CLOSE_FILTER_POPUP`})}getSortInfoMap(){let e=new Map;return this.sortModel.forEach((t,n)=>{e.set(t.colId,{direction:t.direction,index:n+1})}),e}destroy(){this.emitter.clearListeners(),this.sortModel=[],this.filterModel={},this.openFilterColIndex=null}},E=class{queue=[];debounceTimer=null;pendingPromise=null;options;constructor(e){this.options=e}add(e){e.length!==0&&(this.queue.push({type:`ADD`,rows:e}),this.scheduleProcessing())}remove(e){e.length!==0&&(this.queue.push({type:`REMOVE`,rowIds:e}),this.scheduleProcessing())}updateCell(e,t,n){this.queue.push({type:`UPDATE_CELL`,rowId:e,field:t,value:n}),this.scheduleProcessing()}updateRow(e,t){Object.keys(t).length!==0&&(this.queue.push({type:`UPDATE_ROW`,rowId:e,data:t}),this.scheduleProcessing())}flush(){return this.queue.length===0?Promise.resolve():(this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingPromise?new Promise((e,t)=>{let n=this.pendingPromise,r=n.resolve,i=n.reject;n.resolve=()=>{r(),e()},n.reject=e=>{i(e),t(e)}}):new Promise((e,t)=>{this.pendingPromise={resolve:e,reject:t},this.processQueue()}))}hasPending(){return this.queue.length>0}getPendingCount(){return this.queue.length}clear(){this.queue=[],this.debounceTimer!==null&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingPromise&&=(this.pendingPromise.resolve(),null)}scheduleProcessing(){if(this.options.debounceMs===0){this.processQueue();return}this.debounceTimer===null&&(this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.processQueue()},this.options.debounceMs))}processQueue(){if(this.queue.length===0){this.pendingPromise&&=(this.pendingPromise.resolve(),null);return}let e=this.queue;this.queue=[];let t={added:0,removed:0,updated:0};try{for(let n of e)switch(n.type){case`ADD`:this.options.store.addRows(n.rows),t.added+=n.rows.length;break;case`REMOVE`:t.removed+=this.options.store.removeRows(n.rowIds);break;case`UPDATE_CELL`:this.options.store.updateCell(n.rowId,n.field,n.value),t.updated++;break;case`UPDATE_ROW`:this.options.store.updateRow(n.rowId,n.data),t.updated++;break}this.options.onProcessed&&this.options.onProcessed(t),this.pendingPromise&&=(this.pendingPromise.resolve(),null)}catch(e){this.pendingPromise&&=(this.pendingPromise.reject(e instanceof Error?e:Error(String(e))),null)}}},be=class{listeners=[];buffer=null;subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}start(){this.buffer=[]}flush(){let e=this.buffer;if(this.buffer=null,e!==null&&e.length>0)for(let t of this.listeners)t(e)}emit(e){if(this.buffer!==null){this.buffer.push(e);return}this.notify([e])}emitBatch(e){if(e.length!==0){if(this.buffer!==null){this.buffer.push(...e);return}this.notify(e)}}clearListeners(){this.listeners=[]}notify(e){for(let t of this.listeners)t(e)}},xe=class{scrollTop=0;scrollLeft=0;viewportWidth=800;viewportHeight=600;getScrollRatio;constructor(e){this.getScrollRatio=e}getScrollTop(){return this.scrollTop}getScrollLeft(){return this.scrollLeft}getViewportWidth(){return this.viewportWidth}getViewportHeight(){return this.viewportHeight}resetScrollTop(){this.scrollTop=0}update(e,t,n,r){let i=this.getScrollRatio(),a=i<1?e/i:e,o=this.viewportWidth!==n||this.viewportHeight!==r,s=this.scrollTop!==a||this.scrollLeft!==t||o;return s&&(this.scrollTop=a,this.scrollLeft=t,this.viewportWidth=n,this.viewportHeight=r),{changed:s,viewportSizeChanged:o}}},D=class{state={activeCell:null,range:null,anchor:null,selectionMode:!1};options;emitter=v();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getState(){return{...this.state}}getActiveCell(){return this.state.activeCell}getSelectionRange(){return this.state.range}isSelected(e,t){let{range:n}=this.state;if(!n)return!1;let{minRow:r,maxRow:i,minCol:a,maxCol:s}=o(n);return e>=r&&e<=i&&t>=a&&t<=s}isActiveCell(e,t){let{activeCell:n}=this.state;return n?.row===e&&n?.col===t}startSelection(e,t={}){let{shift:n=!1,ctrl:r=!1}=t,{row:i,col:a}=this.clampPosition(e);n&&this.state.anchor?(this.state.range={startRow:this.state.anchor.row,startCol:this.state.anchor.col,endRow:i,endCol:a},this.state.activeCell={row:i,col:a}):(this.state.activeCell={row:i,col:a},this.state.anchor={row:i,col:a},this.state.range=null),this.state.selectionMode=r,this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range})}moveFocus(e,t=!1){if(!this.state.activeCell){this.startSelection({row:0,col:0});return}let{row:n,col:r}=this.state.activeCell,i=n,a=r;switch(e){case`up`:i=Math.max(0,n-1);break;case`down`:i=Math.min(this.options.getRowCount()-1,n+1);break;case`left`:a=Math.max(0,r-1);break;case`right`:a=Math.min(this.options.getColumnCount()-1,r+1);break}t?(this.state.anchor??={row:n,col:r},this.state.range={startRow:this.state.anchor.row,startCol:this.state.anchor.col,endRow:i,endCol:a},this.state.activeCell={row:i,col:a},this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range})):(this.state.activeCell={row:i,col:a},this.state.anchor={row:i,col:a},this.state.range=null,this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:null}))}selectAll(){let e=this.options.getRowCount(),t=this.options.getColumnCount();e===0||t===0||(this.state.range={startRow:0,startCol:0,endRow:e-1,endCol:t-1},this.state.activeCell||(this.state.activeCell={row:0,col:0},this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell})),this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range}))}clearSelection(){this.state.activeCell=null,this.state.range=null,this.state.anchor=null,this.state.selectionMode=!1,this.emit({type:`SET_ACTIVE_CELL`,position:null}),this.emit({type:`SET_SELECTION_RANGE`,range:null})}setActiveCell(e,t){let n=this.clampPosition({row:e,col:t});this.state.activeCell=n,this.state.anchor=n,this.state.range=null,this.emit({type:`SET_ACTIVE_CELL`,position:this.state.activeCell}),this.emit({type:`SET_SELECTION_RANGE`,range:null})}setSelectionRange(e){this.state.range=e,this.emit({type:`SET_SELECTION_RANGE`,range:this.state.range})}getSelectedData(){let{range:e,activeCell:t}=this.state;if(!e&&!t)return[];let{minRow:n,maxRow:r,minCol:i,maxCol:a}=o(e||{startRow:t.row,startCol:t.col,endRow:t.row,endCol:t.col}),s=[];for(let e=n;e<=r;e++){let t=[];for(let n=i;n<=a;n++)t.push(this.options.getCellValue(e,n));s.push(t)}return s}async copySelectionToClipboard(){if(typeof navigator>`u`||typeof document>`u`)return;let e=this.getSelectedData();if(e.length===0)return;let t=e.map(e=>e.map(e=>b(e)).join(` `)).join(`
|
|
2
|
+
`);await navigator.clipboard.writeText(t)}destroy(){this.emitter.clearListeners(),this.state={activeCell:null,range:null,anchor:null,selectionMode:!1}}clampPosition(e){let t=this.options.getRowCount(),n=this.options.getColumnCount();return{row:Math.max(0,Math.min(e.row,t-1)),col:Math.max(0,Math.min(e.col,n-1))}}},O=class{state=null;options;emitter=v();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getState(){return this.state?{...this.state}:null}isActive(){return this.state!==null}startFillDrag(e){this.state={sourceRange:e,targetRow:e.endRow,targetCol:e.endCol},this.emit({type:`START_FILL`,sourceRange:e})}updateFillDrag(e,t){if(!this.state)return;let n=this.options.getRowCount(),r=this.options.getColumnCount();e=Math.max(0,Math.min(e,n-1)),t=Math.max(0,Math.min(t,r-1)),this.state.targetRow=e,this.state.targetCol=t,this.emit({type:`UPDATE_FILL`,targetRow:e,targetCol:t})}commitFillDrag(){if(!this.state)return;let{sourceRange:e,targetRow:t}=this.state,n=this.calculateFilledCells(e,t);for(let{row:e,col:t,value:r}of n)this.options.setCellValue(e,t,r);this.emit({type:`COMMIT_FILL`,filledCells:n}),this.state=null}cancelFillDrag(){this.state&&(this.state=null,this.emit({type:`CANCEL_FILL`}))}destroy(){this.emitter.clearListeners(),this.state=null}calculateFilledCells(e,t){let n=[],{minRow:r,maxRow:i,minCol:a,maxCol:s}=o(e),c=t>i,l=t<r;if(c||l)for(let e=a;e<=s;e++){let a=this.getSourceColumnValues(r,i,e),o=this.detectPattern(a);if(c)for(let r=i+1;r<=t;r++){let t=r-i-1,s=this.applyPattern(o,a,t);n.push({row:r,col:e,value:s})}else if(l)for(let i=r-1;i>=t;i--){let t=r-i-1,s=this.applyPattern(o,a,t,!0);n.push({row:i,col:e,value:s})}}return n}getSourceColumnValues(e,t,n){let r=[];for(let i=e;i<=t;i++)r.push(this.options.getCellValue(i,n));return r}detectPattern(e){if(e.length===0)return{type:`constant`,value:null};if(e.length===1)return{type:`constant`,value:e[0]??null};let t=e.map(e=>typeof e==`number`?e:Number(e));if(t.every(e=>!Number.isNaN(e))){let e=[];for(let n=1;n<t.length;n++)e.push(t[n]-t[n-1]);if(e.every(t=>t===e[0])&&e[0]!==void 0)return{type:`arithmetic`,start:t[0],step:e[0]}}return{type:`repeat`,values:e}}applyPattern(e,t,n,r=!1){switch(e.type){case`constant`:return e.value;case`arithmetic`:{let i=r?-(n+1):n+1;return(r?e.start:e.start+e.step*(t.length-1))+e.step*i}case`repeat`:{let t=e.values.length;if(t===0)return null;if(r){let r=(t-1-n%t+t)%t;return e.values[r]??null}return e.values[n%t]??null}}}},k=class{state={slots:new Map,rowToSlot:new Map,nextSlotId:0};options;emitter=ee();isDestroyed=!1;onInstruction=this.emitter.onInstruction;onBatchInstruction=this.emitter.onBatchInstruction;emit=this.emitter.emit;emitBatch=this.emitter.emitBatch;constructor(e){this.options=e}getSlotForRow(e){return this.state.rowToSlot.get(e)}getSlots(){return this.state.slots}syncSlots(){let e=this.options.getScrollTop(),t=this.options.getRowHeight(),n=this.options.getViewportHeight(),r=this.options.getTotalRows(),i=this.options.getOverscan(),a=n,o=Math.max(0,Math.floor(e/t)-i),s=Math.min(r-1,Math.ceil((e+a)/t)+i);if(r===0||s<o){this.destroyAllSlots();return}let c=new Set;for(let e=o;e<=s;e++)c.add(e);let l=[],u=this.partitionSlots(c),d=0;for(let e of c){let t=this.options.getRowData(e);if(t===void 0)continue;let n=d<u.length?u[d++]:void 0;this.assignSlotToRow(e,t,n,l)}for(let e=d;e<u.length;e++){let t=u[e];this.state.slots.delete(t),l.push({type:`DESTROY_SLOT`,slotId:t})}this.updateSlotPositions(l),this.emitBatch(l)}partitionSlots(e){let t=[];for(let[n,r]of this.state.slots)e.has(r.rowIndex)?e.delete(r.rowIndex):(t.push(n),this.state.rowToSlot.delete(r.rowIndex));return t}assignSlotToRow(e,t,n,r){let i;if(n===void 0)i=`slot-${this.state.nextSlotId++}`,this.state.slots.set(i,{slotId:i,rowIndex:e,rowData:t,translateY:this.getRowTranslateY(e)}),r.push({type:`CREATE_SLOT`,slotId:i});else{i=n;let r=this.state.slots.get(i);r.rowIndex=e,r.rowData=t,r.translateY=this.getRowTranslateY(e)}this.state.rowToSlot.set(e,i),r.push({type:`ASSIGN_SLOT`,slotId:i,rowIndex:e,rowData:t},{type:`MOVE_SLOT`,slotId:i,translateY:this.getRowTranslateY(e)})}updateSlotPositions(e){for(let[t,n]of this.state.slots){let r=this.getRowTranslateY(n.rowIndex);n.translateY!==r&&(n.translateY=r,e.push({type:`MOVE_SLOT`,slotId:t,translateY:r}))}}destroyAllSlots(){let e=[];for(let t of this.state.slots.keys())e.push({type:`DESTROY_SLOT`,slotId:t});this.state.slots.clear(),this.state.rowToSlot.clear(),this.emitBatch(e)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.state.slots.clear(),this.state.rowToSlot.clear(),this.emitter.clearListeners())}refreshAllSlots(){let e=[],t=this.options.getTotalRows();for(let[n,r]of this.state.slots)if(r.rowIndex>=0&&r.rowIndex<t){let t=this.options.getRowData(r.rowIndex);if(t===void 0)continue;let i=this.getRowTranslateY(r.rowIndex);r.rowData=t,r.translateY=i,e.push({type:`ASSIGN_SLOT`,slotId:n,rowIndex:r.rowIndex,rowData:t},{type:`MOVE_SLOT`,slotId:n,translateY:i})}this.emitBatch(e),this.syncSlots()}updateSlot(e){let t=this.state.rowToSlot.get(e);if(t){let n=this.options.getRowData(e);n&&this.emit({type:`ASSIGN_SLOT`,slotId:t,rowIndex:e,rowData:n})}}getRowTranslateY(e){let t=this.options.getRowHeight(),n=this.options.getScrollRatio(),r=this.options.getScrollTop(),i=e*t;return n>=1?i:i-Math.floor(r/t)*t}getRowTranslateYForIndex(e){return this.getRowTranslateY(e)}getRowsWrapperOffset(){let e=this.options.getScrollRatio(),t=this.options.getScrollTop(),n=this.options.getRowHeight();return e>=1?0:Math.floor(t/n)*n*e}},A=class{editState=null;options;emitter=v();onInstruction=this.emitter.onInstruction;emit=this.emitter.emit;constructor(e){this.options=e}getState(){return this.editState?{...this.editState}:null}isEditing(){return this.editState!==null}isEditingCell(e,t){return this.editState!==null&&this.editState.row===e&&this.editState.col===t}startEdit(e,t){if(!this.options.getColumn(t)?.editable)return!1;let n=this.options.getCellValue(e,t);return this.editState={row:e,col:t,initialValue:n,currentValue:n},this.emit({type:`START_EDIT`,row:e,col:t,initialValue:n}),!0}updateValue(e){this.editState&&(this.editState.currentValue=e)}commit(){if(!this.editState)return;let{row:e,col:t,currentValue:n}=this.editState;this.options.setCellValue(e,t,n),this.emit({type:`COMMIT_EDIT`,row:e,col:t,value:n}),this.editState=null,this.emit({type:`STOP_EDIT`}),this.options.onCommit?.(e,t,n)}cancel(){this.editState=null,this.emit({type:`STOP_EDIT`})}destroy(){this.emitter.clearListeners(),this.editState=null}};const Se=e=>{let{batcher:t}=e,n,r=new ve({getRowHeight:e.getRowHeight,getHeaderHeight:e.getHeaderHeight,getTotalRows:e.getTotalRows,getScrollTop:()=>n.getScrollTop(),getViewportHeight:()=>n.getViewportHeight()});n=new xe(()=>r.getScrollRatio());let i=null,a=new D({getRowCount:e.getTotalRows,getColumnCount:()=>e.getColumns().length,getCellValue:e.getCellValue,getRowData:t=>e.getCachedRows().get(t),getColumn:t=>e.getColumns()[t]});a.onInstruction(e=>{t.emit(e),i?.onSelectionChange()}),e.highlighting&&(i=new w({getActiveCell:()=>a.getActiveCell(),getSelectionRange:()=>a.getSelectionRange(),getColumn:t=>e.getColumns()[t]},e.highlighting),i.onInstruction(e=>t.emit(e)));let o=new O({getRowCount:e.getTotalRows,getColumnCount:()=>e.getColumns().length,getCellValue:e.getCellValue,getColumn:t=>e.getColumns()[t],setCellValue:e.setCellValue});o.onInstruction(e=>t.emit(e));let s=new k({getRowHeight:e.getRowHeight,getHeaderHeight:e.getHeaderHeight,getOverscan:e.getOverscan,getScrollTop:()=>n.getScrollTop(),getViewportHeight:()=>n.getViewportHeight(),getTotalRows:e.getTotalRows,getScrollRatio:()=>r.getScrollRatio(),getVirtualContentHeight:()=>r.getVirtualContentHeight(),getRowData:t=>e.getCachedRows().get(t)});s.onBatchInstruction(e=>t.emitBatch(e));let c=new A({getColumn:t=>e.getColumns()[t],getCellValue:e.getCellValue,setCellValue:e.setCellValue,onCommit:e=>s.updateSlot(e)});c.onInstruction(e=>t.emit(e));let l=new ye({getColumns:e.getColumns,isSortingEnabled:e.getSortingEnabled,getCachedRows:e.getCachedRows,onSortFilterChange:async()=>{await e.fetchData(),i?.clearAllCaches(),n.resetScrollTop(),t.start();try{t.emit({type:`SCROLL_TO`,scrollTop:0}),e.emitContentSize(),e.emitHeaders(),s.refreshAllSlots()}finally{t.flush()}},onDataRefreshed:()=>{}});l.onInstruction(e=>t.emit(e));let u=new T({getCachedRows:e.getCachedRows,setCachedRows:e.setCachedRows,getTotalRows:e.getTotalRows,setTotalRows:e.setTotalRows,updateSlot:e=>s.updateSlot(e),refreshAllSlots:()=>s.refreshAllSlots(),emitContentSize:e.emitContentSize,clearSelectionIfInvalid:e.clearSelectionIfInvalid});return u.onInstruction(e=>t.emit(e)),{selection:a,highlight:i,fill:o,scrollVirtualization:r,viewport:n,slotPool:s,editManager:c,sortFilter:l,rowMutation:u}},Ce=e=>{let t=e.columnPositions.at(-1)??0;e.scrollVirtualization.updateContentSize(),e.batcher.emit({type:`SET_CONTENT_SIZE`,width:t,height:e.scrollVirtualization.getVirtualHeight(),viewportWidth:e.viewport.getViewportWidth(),viewportHeight:e.viewport.getViewportHeight(),rowsWrapperOffset:e.slotPool.getRowsWrapperOffset()})},we=e=>{let t=e.sortFilter.getSortInfoMap();for(let n=0;n<e.columns.length;n++){let r=e.columns[n],i=r.colId??r.field,a=t.get(i);e.batcher.emit({type:`UPDATE_HEADER`,colIndex:n,column:r,sortDirection:a?.direction,sortIndex:a?.index,hasFilter:e.sortFilter.hasActiveFilter(i)})}},Te=e=>{let t=e.scrollVirtualization.getVisibleRowRange();e.batcher.emit({type:`UPDATE_VISIBLE_RANGE`,start:t.start,end:t.end,rowsWrapperOffset:e.slotPool.getRowsWrapperOffset()})},j=e=>{e.computeColumnPositions(),e.batcher.start();try{e.emitContentSize(),e.emitHeaders(),e.batcher.emit({type:`COLUMNS_CHANGED`,columns:[...e.columns]}),e.refreshSlots===`sync`?e.slotPool.syncSlots():e.slotPool.refreshAllSlots()}finally{e.batcher.flush()}e.onComplete()},Ee=(e,t,n)=>{let r=n.columns[e];r&&(r.width=t,j({...n,refreshSlots:`sync`}))},De=(e,t,n)=>{if(e===t||e<0||e>=n.columns.length)return null;let r=t>e?t-1:t;if(r<0||r>=n.columns.length||e===r)return null;let[i]=n.columns.splice(e,1);return n.columns.splice(r,0,i),j({...n,refreshSlots:`all`}),r},Oe=(e,t,n)=>{let r=n.dataSource;if(!r.moveRow)return;r.moveRow(e,t),ie(n.cachedRows,e,t),n.highlight?.clearAllCaches();let i=Math.min(e,t),a=Math.max(e,t);for(let e=i;e<=a;e++)n.slotPool.updateSlot(e)},ke=async e=>{let t=await e.dataSource.fetch(x({pageIndex:0,pageSize:2**53-1,sortModel:e.sortFilter.getSortModel(),filterModel:e.sortFilter.getFilterModel()}));e.cachedRows.clear();for(let n=0;n<t.rows.length;n++){let r=t.rows[n];r!==void 0&&e.cachedRows.set(n,r)}return e.setTotalRows(t.totalRows),{totalRows:t.totalRows}};var Ae=class{columns;dataSource;rowHeight;headerHeight;overscan;sortingEnabled;getRowId;onCellValueChanged;rowDragEntireRow;onRowDragEnd;onColumnResized;onColumnMoved;viewport;currentPageIndex=0;pageSize=2**53-1;cachedRows=new Map;totalRows=0;selection;fill;input;highlight;sortFilter;rowMutation;slotPool;editManager;columnPositions=[];batcher=new be;scrollVirtualization;isDestroyed=!1;_isDataLoading=!1;constructor(e){if(this.columns=e.columns,this.dataSource=e.dataSource,this.rowHeight=e.rowHeight,this.headerHeight=e.headerHeight??e.rowHeight,this.overscan=e.overscan??3,this.sortingEnabled=e.sortingEnabled??!0,this.getRowId=e.getRowId,this.onCellValueChanged=e.onCellValueChanged,this.rowDragEntireRow=e.rowDragEntireRow??!1,this.onRowDragEnd=e.onRowDragEnd,this.onColumnResized=e.onColumnResized,this.onColumnMoved=e.onColumnMoved,this.onCellValueChanged&&!this.getRowId)throw Error(`getRowId is required when onCellValueChanged is provided`);this.computeColumnPositions();let t=Se({batcher:this.batcher,highlighting:e.highlighting,getColumns:()=>this.columns,getCachedRows:()=>this.cachedRows,setCachedRows:e=>{this.cachedRows=e},getTotalRows:()=>this.totalRows,setTotalRows:e=>{this.totalRows=e},getRowHeight:()=>this.rowHeight,getHeaderHeight:()=>this.headerHeight,getOverscan:()=>this.overscan,getSortingEnabled:()=>this.sortingEnabled,getCellValue:(e,t)=>this.getCellValue(e,t),setCellValue:(e,t,n)=>this.setCellValue(e,t,n),emitContentSize:()=>this.emitContentSize(),emitHeaders:()=>this.emitHeaders(),fetchData:()=>this.fetchData(),clearSelectionIfInvalid:e=>this.clearSelectionIfInvalid(e)});this.selection=t.selection,this.highlight=t.highlight,this.fill=t.fill,this.scrollVirtualization=t.scrollVirtualization,this.viewport=t.viewport,this.slotPool=t.slotPool,this.editManager=t.editManager,this.sortFilter=t.sortFilter,this.rowMutation=t.rowMutation,this.input=new C(this,{getHeaderHeight:()=>this.headerHeight,getRowHeight:()=>this.rowHeight,getColumnPositions:()=>this.columnPositions,getColumnCount:()=>this.columns.length})}onBatchInstruction(e){return this.batcher.subscribe(e)}async initialize(){await this.fetchData(),this.slotPool.syncSlots(),this.emitContentSize(),this.emitHeaders()}setViewport(e,t,n,r){let{changed:i,viewportSizeChanged:a}=this.viewport.update(e,t,n,r);i&&(this.slotPool.syncSlots(),this.emitVisibleRange(),a&&this.emitContentSize())}async fetchData(){this._isDataLoading=!0,this.batcher.emit({type:`DATA_LOADING`});try{let e=x({pageIndex:this.currentPageIndex,pageSize:this.pageSize,sortModel:this.sortFilter.getSortModel(),filterModel:this.sortFilter.getFilterModel()}),t=await this.dataSource.fetch(e);this.cachedRows.clear();let n=this.currentPageIndex*this.pageSize;t.rows.forEach((e,t)=>{this.cachedRows.set(n+t,e)}),this.totalRows=t.totalRows,this.batcher.emit({type:`DATA_LOADED`,totalRows:this.totalRows})}catch(e){this.batcher.emit({type:`DATA_ERROR`,error:e instanceof Error?e.message:String(e)})}finally{this._isDataLoading=!1}}async setSort(e,t,n=!1){if(!this._isDataLoading)return this.sortFilter.setSort(e,t,n)}async setFilter(e,t){if(!this._isDataLoading)return this.sortFilter.setFilter(e,t)}hasActiveFilter(e){return this.sortFilter.hasActiveFilter(e)}getDistinctValuesForColumn(e,t=500){return this.sortFilter.getDistinctValuesForColumn(e,t)}openFilterPopup(e,t){this._isDataLoading||this.sortFilter.openFilterPopup(e,t)}closeFilterPopup(){this.sortFilter.closeFilterPopup()}getSortModel(){return this.sortFilter.getSortModel()}getFilterModel(){return this.sortFilter.getFilterModel()}startEdit(e,t){this.editManager.startEdit(e,t)}updateEditValue(e){this.editManager.updateValue(e)}commitEdit(){this.editManager.commit()}cancelEdit(){this.editManager.cancel()}getEditState(){return this.editManager.getState()}getCellValue(e,t){return oe(this.cachedRows,this.columns,e,t)}setCellValue(e,t,n){se(this.cachedRows,this.columns,e,t,n,{onCellValueChanged:this.onCellValueChanged,getRowId:this.getRowId})}clearSelectionIfInvalid(e){let t=this.selection.getActiveCell();t&&t.row>=e&&this.selection.clearSelection()}computeColumnPositions(){this.columnPositions=ae(this.columns)}emitContentSize(){Ce({batcher:this.batcher,scrollVirtualization:this.scrollVirtualization,slotPool:this.slotPool,viewport:this.viewport,columnPositions:this.columnPositions})}emitHeaders(){we({batcher:this.batcher,sortFilter:this.sortFilter,columns:this.columns})}emitVisibleRange(){Te({batcher:this.batcher,scrollVirtualization:this.scrollVirtualization,slotPool:this.slotPool})}setColumnWidth(e,t){Ee(e,t,{batcher:this.batcher,slotPool:this.slotPool,refreshSlots:`sync`,computeColumnPositions:()=>this.computeColumnPositions(),emitContentSize:()=>this.emitContentSize(),emitHeaders:()=>this.emitHeaders(),columns:this.columns,onComplete:()=>this.onColumnResized?.(e,t)})}moveColumn(e,t){let n=De(e,t,{batcher:this.batcher,slotPool:this.slotPool,refreshSlots:`all`,computeColumnPositions:()=>this.computeColumnPositions(),emitContentSize:()=>this.emitContentSize(),emitHeaders:()=>this.emitHeaders(),columns:this.columns,onComplete:()=>{}});n!==null&&this.onColumnMoved?.(e,n)}commitRowDrag(e,t){Oe(e,t,{dataSource:this.dataSource,cachedRows:this.cachedRows,slotPool:this.slotPool,highlight:this.highlight}),this.onRowDragEnd?.(e,t)}isRowDragEntireRow(){return this.rowDragEntireRow}getColumns(){return this.columns}getColumnPositions(){return[...this.columnPositions]}getRowCount(){return this.totalRows}getRowHeight(){return this.rowHeight}getHeaderHeight(){return this.headerHeight}getTotalWidth(){return this.columnPositions.at(-1)??0}getTotalHeight(){return this.scrollVirtualization.getVirtualHeight()}isScalingActive(){return this.scrollVirtualization.isScalingActive()}getNaturalHeight(){return this.scrollVirtualization.getNaturalHeight()}getScrollRatio(){return this.scrollVirtualization.getScrollRatio()}getVisibleRowRange(){return this.scrollVirtualization.getVisibleRowRange()}getScrollTopForRow(e){return this.scrollVirtualization.getScrollTopForRow(e)}getRowIndexAtDisplayY(e,t){return this.scrollVirtualization.getRowIndexAtDisplayY(e,t)}getRowTranslateY(e){return this.slotPool.getRowTranslateYForIndex(e)}getRowData(e){return this.cachedRows.get(e)}async refresh(){await this.fetchData(),this.highlight?.clearAllCaches(),this.slotPool.refreshAllSlots(),this.emitContentSize(),this.emitVisibleRange()}async refreshFromTransaction(){await ke({dataSource:this.dataSource,sortFilter:this.sortFilter,cachedRows:this.cachedRows,setTotalRows:e=>{this.totalRows=e}}),this.highlight?.clearAllCaches(),this.slotPool.refreshAllSlots(),this.emitContentSize(),this.emitVisibleRange()}refreshSlotData(){this.slotPool.refreshAllSlots()}addRows(e,t){this.rowMutation.addRows(e,t)}updateRows(e){this.rowMutation.updateRows(e)}deleteRows(e){this.rowMutation.deleteRows(e)}getRow(e){return this.rowMutation.getRow(e)}setRow(e,t){this.rowMutation.setRow(e,t)}async setDataSource(e){this.editManager.getState()&&this.editManager.cancel(),this.dataSource=e,await this.refresh(),this.clearSelectionIfInvalid(this.totalRows)}setColumns(e){this.columns=e,this.computeColumnPositions(),this.emitContentSize(),this.emitHeaders(),this.slotPool.syncSlots()}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.slotPool.destroy(),this.highlight?.destroy(),this.sortFilter.destroy(),this.rowMutation.destroy(),this.cachedRows.clear(),this.batcher.clearListeners(),this.totalRows=0)}},M=class{workerCode;maxWorkers;workers=[];workerUrl=null;nextRequestId=0;isTerminated=!1;constructor(e,t={}){this.workerCode=e;let n=typeof navigator>`u`?4:navigator.hardwareConcurrency;this.maxWorkers=Math.max(1,t.maxWorkers??n??4),t.preWarm&&this.preWarmWorkers()}getPoolSize(){return this.workers.length}getMaxWorkers(){return this.maxWorkers}isAvailable(){return!this.isTerminated&&typeof Worker<`u`}async execute(e,t){if(this.isTerminated)throw Error(`WorkerPool has been terminated`);if(typeof Worker>`u`)throw TypeError(`Web Workers are not available in this environment`);let n=this.getAvailableWorker(),r=this.nextRequestId++,i={...e,id:r};return new Promise((e,a)=>{n.pendingRequests.set(r,{resolve:e,reject:a}),n.busy=!0,t&&t.length>0?n.worker.postMessage(i,t):n.worker.postMessage(i)})}async executeParallel(e){if(this.isTerminated)throw Error(`WorkerPool has been terminated`);if(e.length===0)return[];let t=Math.min(e.length,this.maxWorkers);this.ensureWorkers(t);let n=e.map((e,t)=>{let n=t%this.workers.length,r=this.workers[n],i=this.nextRequestId++,a={...e.request,id:i};return new Promise((t,n)=>{r.pendingRequests.set(i,{resolve:t,reject:n}),r.busy=!0,e.transferables&&e.transferables.length>0?r.worker.postMessage(a,e.transferables):r.worker.postMessage(a)})});return Promise.all(n)}terminate(){for(let e of this.workers){e.worker.terminate();for(let[,t]of e.pendingRequests)t.reject(Error(`Worker pool terminated`));e.pendingRequests.clear()}this.workers=[],this.workerUrl&&=(URL.revokeObjectURL(this.workerUrl),null),this.isTerminated=!0}preWarmWorkers(){this.ensureWorkers(this.maxWorkers)}ensureWorkers(e){let t=Math.min(e,this.maxWorkers)-this.workers.length;for(let e=0;e<t;e++)this.createWorker()}getAvailableWorker(){return this.workers.find(e=>!e.busy)||(this.workers.length<this.maxWorkers?this.createWorker():this.workers.reduce((e,t)=>t.pendingRequests.size<e.pendingRequests.size?t:e,this.workers[0]))}createWorker(){if(!this.workerUrl){let e=new Blob([this.workerCode],{type:`application/javascript`});this.workerUrl=URL.createObjectURL(e)}let e=new Worker(this.workerUrl),t={worker:e,busy:!1,pendingRequests:new Map};return e.onmessage=e=>{let{id:n}=e.data,r=t.pendingRequests.get(n);r&&(t.pendingRequests.delete(n),t.pendingRequests.size===0&&(t.busy=!1),e.data.type===`error`?r.reject(Error(e.data.error)):r.resolve(e.data))},e.onerror=e=>{for(let[,n]of t.pendingRequests)n.reject(Error(`Worker error: ${e.message}`));t.pendingRequests.clear(),t.busy=!1,this.respawnWorker(t)},this.workers.push(t),t}respawnWorker(e){let t=this.workers.indexOf(e);if(t!==-1){try{e.worker.terminate()}catch{}this.workers.splice(t,1),this.workers.length<this.maxWorkers&&!this.isTerminated&&this.createWorker()}}};function N(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}const P=e=>e==null?``:Array.isArray(e)?e.join(`, `):typeof e==`object`&&!(e instanceof Date)?JSON.stringify(e):String(e);function je(e,t){if(e==null&&t==null)return 0;if(e==null)return 1;if(t==null)return-1;let n=Number(e),r=Number(t);return!Number.isNaN(n)&&!Number.isNaN(r)?n-r:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():P(e).localeCompare(P(t))}function Me(e,t){return[...e].sort((e,n)=>{for(let{colId:r,direction:i}of t){let t=je(N(e,r),N(n,r));if(t!==0)return i===`asc`?t:-t}return 0})}const F=globalThis;F.onmessage!==void 0&&(F.onmessage=e=>{let{type:t,id:n,data:r,sortModel:i}=e.data;if(t===`sort`)try{let e=Me(r,i);F.postMessage?.({type:`sorted`,id:n,data:e})}catch(e){F.postMessage?.({type:`error`,id:n,error:String(e)})}});var I=class{heap=[];compare;constructor(e){this.compare=e}push(e){this.heap.push(e),this.bubbleUp(this.heap.length-1)}pop(){if(this.heap.length===0)return;let e=this.heap[0],t=this.heap.pop();return this.heap.length>0&&t&&(this.heap[0]=t,this.bubbleDown(0)),e}size(){return this.heap.length}bubbleUp(e){for(;e>0;){let t=Math.floor((e-1)/2);if(this.compare(this.heap[e],this.heap[t])>=0)break;this.swap(e,t),e=t}}bubbleDown(e){let t=this.heap.length;for(;;){let n=2*e+1,r=2*e+2,i=e;if(n<t&&this.compare(this.heap[n],this.heap[i])<0&&(i=n),r<t&&this.compare(this.heap[r],this.heap[i])<0&&(i=r),i===e)break;this.swap(e,i),e=i}}swap(e,t){let n=this.heap[e];this.heap[e]=this.heap[t],this.heap[t]=n}};const L=(e,t,n)=>{let r=[];for(let i=0;i<n;i++)r.push(e.columns[i][t]);return r};function R(e,t){if(e.length===0)return new Uint32Array;if(e.length===1){let t=e[0],n=new Uint32Array(t.indices.length);for(let e=0;e<t.indices.length;e++)n[e]=t.indices[e]+t.offset;return n}let n=0;for(let t of e)n+=t.indices.length;let r=new Uint32Array(n),i=t===`asc`?1:-1,a=new I((e,t)=>(e.value-t.value)*i);for(let t=0;t<e.length;t++){let n=e[t];if(n.indices.length>0){let e=n.indices[0];a.push({chunkIndex:t,positionInChunk:0,value:n.values[0],globalIndex:e+n.offset})}}let o=0;for(;a.size()>0;){let t=a.pop();r[o++]=t.globalIndex;let n=e[t.chunkIndex],i=t.positionInChunk+1;if(i<n.indices.length){let e=n.indices[i];a.push({chunkIndex:t.chunkIndex,positionInChunk:i,value:n.values[i],globalIndex:e+n.offset})}}return r}function z(e){if(e.length===0)return new Uint32Array;if(e.length===1){let t=e[0],n=new Uint32Array(t.indices.length);for(let e=0;e<t.indices.length;e++)n[e]=t.indices[e]+t.offset;return n}let t=e[0].directions,n=t.length,r=0;for(let t of e)r+=t.indices.length;let i=new Uint32Array(r),a=new I((e,n)=>{for(let r=0;r<t.length;r++){let i=(e.values[r]-n.values[r])*t[r];if(i!==0)return i}return 0});for(let t=0;t<e.length;t++){let r=e[t];if(r.indices.length>0){let e=r.indices[0];a.push({chunkIndex:t,positionInChunk:0,values:L(r,0,n),globalIndex:e+r.offset})}}let o=0;for(;a.size()>0;){let t=a.pop();i[o++]=t.globalIndex;let r=e[t.chunkIndex],s=t.positionInChunk+1;if(s<r.indices.length){let e=r.indices[s];a.push({chunkIndex:t.chunkIndex,positionInChunk:s,values:L(r,s,n),globalIndex:e+r.offset})}}return i}function Ne(e,t){if(e.length<=1)return new Uint32Array;let n=[],r=0;for(let t=0;t<e.length-1;t++){let i=e[t],a=e[t+1];if(i.indices.length===0||a.indices.length===0){r+=i.indices.length;continue}let o=i.indices.length-1,s=i.values[o],c=a.values[0];if(s===c){let e=o;for(;e>0&&i.values[e-1]===s;)e--;let t=0;for(;t<a.indices.length-1&&a.values[t+1]===c;)t++;let l=r+e,u=r+i.indices.length+t+1;n.push(l,u)}r+=i.indices.length}return new Uint32Array(n)}const Pe=(e,t,n)=>{let r=Math.max(n,Math.ceil(e/t)),i=[];for(let t=0;t<e;t+=r)i.push({offset:t,length:Math.min(r,e-t)});return i},Fe=e=>{if(e.length<=1)return[];let t=[],n=0;for(let r=0;r<e.length-1;r++){let i=e[r],a=e[r+1];if(i.indices.length===0||a.indices.length===0){n+=i.indices.length;continue}let o=i.values[i.indices.length-1],s=a.values[0];if(o===s){let e=i.indices.length-1;for(;e>0&&i.values[e-1]===o;)e--;let r=0;for(;r<a.indices.length-1&&a.values[r+1]===s;)r++;t.push(n+e,n+i.indices.length+r+1)}n+=i.indices.length}return t},B=(e,t,n,r)=>{let i=r===`asc`?1:-1;for(let r=0;r<t.length;r+=2){let a=t[r],o=t[r+1];o<=a||o>e.length||Ie(e,a,o,n,i)}},Ie=(e,t,n,r,i)=>{let a=Array.from(e.slice(t,n));if(!Le(a,r)){a.sort((e,t)=>i*r[e].localeCompare(r[t]));for(let n=0;n<a.length;n++)e[t+n]=a[n]}},Le=(e,t)=>{let n=t[e[0]];for(let r=1;r<e.length;r++)if(t[e[r]]!==n)return!1;return!0};var V=class{pool;parallelThreshold;minChunkSize;isTerminated=!1;constructor(e={}){this.pool=new M(`
|
|
3
|
+
// ---- Shared helpers (inlined for worker isolation) ----------------------
|
|
4
4
|
function getFieldValue(row, field) {
|
|
5
5
|
const parts = field.split(".");
|
|
6
6
|
let value = row;
|
|
7
|
-
|
|
8
7
|
for (const part of parts) {
|
|
9
|
-
if (value == null || typeof value !== "object")
|
|
10
|
-
return null;
|
|
11
|
-
}
|
|
8
|
+
if (value == null || typeof value !== "object") return null;
|
|
12
9
|
value = value[part];
|
|
13
10
|
}
|
|
14
|
-
|
|
15
11
|
return value ?? null;
|
|
16
12
|
}
|
|
17
13
|
|
|
@@ -26,307 +22,186 @@ function compareValues(a, b) {
|
|
|
26
22
|
if (a == null && b == null) return 0;
|
|
27
23
|
if (a == null) return 1;
|
|
28
24
|
if (b == null) return -1;
|
|
29
|
-
|
|
30
25
|
const aNum = Number(a);
|
|
31
26
|
const bNum = Number(b);
|
|
32
|
-
if (!isNaN(aNum) && !isNaN(bNum))
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
if (a instanceof Date && b instanceof Date) {
|
|
37
|
-
return a.getTime() - b.getTime();
|
|
38
|
-
}
|
|
39
|
-
|
|
27
|
+
if (!isNaN(aNum) && !isNaN(bNum)) return aNum - bNum;
|
|
28
|
+
if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
|
|
40
29
|
return toDisplayString(a).localeCompare(toDisplayString(b));
|
|
41
30
|
}
|
|
42
31
|
|
|
43
32
|
function sortData(data, sortModel) {
|
|
44
33
|
return [...data].sort((a, b) => {
|
|
45
34
|
for (const { colId, direction } of sortModel) {
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
const comparison = compareValues(aVal, bVal);
|
|
49
|
-
|
|
50
|
-
if (comparison !== 0) {
|
|
51
|
-
return direction === "asc" ? comparison : -comparison;
|
|
52
|
-
}
|
|
35
|
+
const cmp = compareValues(getFieldValue(a, colId), getFieldValue(b, colId));
|
|
36
|
+
if (cmp !== 0) return direction === "asc" ? cmp : -cmp;
|
|
53
37
|
}
|
|
54
38
|
return 0;
|
|
55
39
|
});
|
|
56
40
|
}
|
|
57
41
|
|
|
58
|
-
|
|
59
|
-
// Uses Transferable typed arrays for zero-copy transfer
|
|
60
|
-
function sortIndices(values, direction) {
|
|
61
|
-
const len = values.length;
|
|
42
|
+
function initIndices(len) {
|
|
62
43
|
const indices = new Uint32Array(len);
|
|
63
44
|
for (let i = 0; i < len; i++) indices[i] = i;
|
|
45
|
+
return indices;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function reorderFloat64(values, indices) {
|
|
49
|
+
const out = new Float64Array(indices.length);
|
|
50
|
+
for (let i = 0; i < indices.length; i++) out[i] = values[indices[i]];
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Find runs of consecutive sorted indices whose hash tuples are identical.
|
|
55
|
+
// Emits flat pairs: [start1, end1, start2, end2, ...].
|
|
56
|
+
function detectCollisionRuns(indices, hashChunks) {
|
|
57
|
+
const len = indices.length;
|
|
58
|
+
const numChunks = hashChunks.length;
|
|
59
|
+
const runs = [];
|
|
60
|
+
let runStart = 0;
|
|
61
|
+
for (let i = 1; i <= len; i++) {
|
|
62
|
+
let diff = i === len;
|
|
63
|
+
if (!diff) {
|
|
64
|
+
const p = indices[i - 1];
|
|
65
|
+
const c = indices[i];
|
|
66
|
+
for (let k = 0; k < numChunks; k++) {
|
|
67
|
+
if (hashChunks[k][p] !== hashChunks[k][c]) { diff = true; break; }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (diff) {
|
|
71
|
+
if (i - runStart > 1) runs.push(runStart, i);
|
|
72
|
+
runStart = i;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return new Uint32Array(runs);
|
|
76
|
+
}
|
|
64
77
|
|
|
65
|
-
|
|
78
|
+
// ---- Base sort primitives ----------------------------------------------
|
|
79
|
+
function sortIndices(values, direction) {
|
|
80
|
+
const indices = initIndices(values.length);
|
|
66
81
|
const mult = direction === "asc" ? 1 : -1;
|
|
67
82
|
indices.sort((a, b) => {
|
|
68
|
-
const va = values[a];
|
|
69
|
-
const vb = values[b];
|
|
83
|
+
const va = values[a], vb = values[b];
|
|
70
84
|
if (va < vb) return -1 * mult;
|
|
71
85
|
if (va > vb) return 1 * mult;
|
|
72
86
|
return 0;
|
|
73
87
|
});
|
|
74
|
-
|
|
75
88
|
return indices;
|
|
76
89
|
}
|
|
77
90
|
|
|
78
|
-
// Multi-column sorting - compares columns in priority order
|
|
79
91
|
function sortMultiColumn(columns, directions) {
|
|
80
|
-
const len = columns[0].length;
|
|
81
92
|
const numCols = columns.length;
|
|
82
|
-
const indices =
|
|
83
|
-
for (let i = 0; i < len; i++) indices[i] = i;
|
|
84
|
-
|
|
93
|
+
const indices = initIndices(columns[0].length);
|
|
85
94
|
indices.sort((a, b) => {
|
|
86
95
|
for (let c = 0; c < numCols; c++) {
|
|
87
|
-
const va = columns[c][a];
|
|
88
|
-
const vb = columns[c][b];
|
|
96
|
+
const va = columns[c][a], vb = columns[c][b];
|
|
89
97
|
if (va < vb) return -1 * directions[c];
|
|
90
98
|
if (va > vb) return 1 * directions[c];
|
|
91
|
-
// Equal - continue to next column
|
|
92
99
|
}
|
|
93
100
|
return 0;
|
|
94
101
|
});
|
|
95
|
-
|
|
96
102
|
return indices;
|
|
97
103
|
}
|
|
98
104
|
|
|
99
|
-
// String hash sorting with collision detection
|
|
100
105
|
function sortStringHashes(hashChunks, direction) {
|
|
101
|
-
const len = hashChunks[0].length;
|
|
102
106
|
const numChunks = hashChunks.length;
|
|
103
|
-
const indices =
|
|
104
|
-
for (let i = 0; i < len; i++) indices[i] = i;
|
|
105
|
-
|
|
107
|
+
const indices = initIndices(hashChunks[0].length);
|
|
106
108
|
const mult = direction === "asc" ? 1 : -1;
|
|
107
|
-
|
|
108
|
-
// Sort by hash only (no collision tracking during sort)
|
|
109
109
|
indices.sort((a, b) => {
|
|
110
110
|
for (let c = 0; c < numChunks; c++) {
|
|
111
|
-
const va = hashChunks[c][a];
|
|
112
|
-
const vb = hashChunks[c][b];
|
|
111
|
+
const va = hashChunks[c][a], vb = hashChunks[c][b];
|
|
113
112
|
if (va < vb) return -1 * mult;
|
|
114
113
|
if (va > vb) return 1 * mult;
|
|
115
114
|
}
|
|
116
|
-
return 0;
|
|
115
|
+
return 0;
|
|
117
116
|
});
|
|
118
|
-
|
|
119
|
-
// Detect collision runs AFTER sorting (much more efficient)
|
|
120
|
-
// Find runs of consecutive indices with identical hashes
|
|
121
|
-
const collisionRuns = []; // [start1, end1, start2, end2, ...]
|
|
122
|
-
let runStart = 0;
|
|
123
|
-
|
|
124
|
-
for (let i = 1; i <= len; i++) {
|
|
125
|
-
// Check if current element has different hash than previous
|
|
126
|
-
let isDifferent = i === len; // End of array is always "different"
|
|
127
|
-
if (!isDifferent) {
|
|
128
|
-
const prevIdx = indices[i - 1];
|
|
129
|
-
const currIdx = indices[i];
|
|
130
|
-
for (let c = 0; c < numChunks; c++) {
|
|
131
|
-
if (hashChunks[c][prevIdx] !== hashChunks[c][currIdx]) {
|
|
132
|
-
isDifferent = true;
|
|
133
|
-
break;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (isDifferent) {
|
|
139
|
-
// End of a run - only record if run has more than 1 element
|
|
140
|
-
if (i - runStart > 1) {
|
|
141
|
-
collisionRuns.push(runStart, i);
|
|
142
|
-
}
|
|
143
|
-
runStart = i;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
return { indices, collisionRuns: new Uint32Array(collisionRuns) };
|
|
117
|
+
return { indices, collisionRuns: detectCollisionRuns(indices, hashChunks) };
|
|
148
118
|
}
|
|
149
119
|
|
|
150
|
-
// Chunk
|
|
120
|
+
// ---- Chunk variants (base sort + reorder for merge) --------------------
|
|
151
121
|
function sortChunk(values, direction) {
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
for (let i = 0; i < len; i++) indices[i] = i;
|
|
155
|
-
|
|
156
|
-
const mult = direction === "asc" ? 1 : -1;
|
|
157
|
-
indices.sort((a, b) => {
|
|
158
|
-
const va = values[a];
|
|
159
|
-
const vb = values[b];
|
|
160
|
-
if (va < vb) return -1 * mult;
|
|
161
|
-
if (va > vb) return 1 * mult;
|
|
162
|
-
return 0;
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
// Create sorted values array for merge comparison
|
|
166
|
-
const sortedValues = new Float64Array(len);
|
|
167
|
-
for (let i = 0; i < len; i++) {
|
|
168
|
-
sortedValues[i] = values[indices[i]];
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
return { indices, sortedValues };
|
|
122
|
+
const indices = sortIndices(values, direction);
|
|
123
|
+
return { indices, sortedValues: reorderFloat64(values, indices) };
|
|
172
124
|
}
|
|
173
125
|
|
|
174
126
|
function sortStringChunk(hashChunks, direction) {
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
indices.sort((a, b) => {
|
|
183
|
-
for (let c = 0; c < numChunks; c++) {
|
|
184
|
-
const va = hashChunks[c][a];
|
|
185
|
-
const vb = hashChunks[c][b];
|
|
186
|
-
if (va < vb) return -1 * mult;
|
|
187
|
-
if (va > vb) return 1 * mult;
|
|
188
|
-
}
|
|
189
|
-
return 0;
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
// Detect collision runs
|
|
193
|
-
const collisionRuns = [];
|
|
194
|
-
let runStart = 0;
|
|
195
|
-
|
|
196
|
-
for (let i = 1; i <= len; i++) {
|
|
197
|
-
let isDifferent = i === len;
|
|
198
|
-
if (!isDifferent) {
|
|
199
|
-
const prevIdx = indices[i - 1];
|
|
200
|
-
const currIdx = indices[i];
|
|
201
|
-
for (let c = 0; c < numChunks; c++) {
|
|
202
|
-
if (hashChunks[c][prevIdx] !== hashChunks[c][currIdx]) {
|
|
203
|
-
isDifferent = true;
|
|
204
|
-
break;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
if (isDifferent) {
|
|
210
|
-
if (i - runStart > 1) {
|
|
211
|
-
collisionRuns.push(runStart, i);
|
|
212
|
-
}
|
|
213
|
-
runStart = i;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// Create sorted hashes for merge (use first hash chunk)
|
|
218
|
-
const sortedHashes = new Float64Array(len);
|
|
219
|
-
for (let i = 0; i < len; i++) {
|
|
220
|
-
sortedHashes[i] = hashChunks[0][indices[i]];
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
return { indices, sortedHashes, collisionRuns: new Uint32Array(collisionRuns) };
|
|
127
|
+
const result = sortStringHashes(hashChunks, direction);
|
|
128
|
+
return {
|
|
129
|
+
indices: result.indices,
|
|
130
|
+
sortedHashes: reorderFloat64(hashChunks[0], result.indices),
|
|
131
|
+
collisionRuns: result.collisionRuns,
|
|
132
|
+
};
|
|
224
133
|
}
|
|
225
134
|
|
|
226
135
|
function sortMultiColumnChunk(columns, directions) {
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
return
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
}
|
|
136
|
+
const indices = sortMultiColumn(columns, directions);
|
|
137
|
+
return { indices, sortedColumns: columns.map(col => reorderFloat64(col, indices)) };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ---- Dispatch table: type → handler(data) → { type, payload, transfer }
|
|
141
|
+
const HANDLERS = {
|
|
142
|
+
sort: (d) => ({
|
|
143
|
+
type: "sorted",
|
|
144
|
+
payload: { data: sortData(d.data, d.sortModel) },
|
|
145
|
+
}),
|
|
146
|
+
sortIndices: (d) => {
|
|
147
|
+
const indices = sortIndices(d.values, d.direction);
|
|
148
|
+
return { type: "sortedIndices", payload: { indices }, transfer: [indices.buffer] };
|
|
149
|
+
},
|
|
150
|
+
sortMultiColumn: (d) => {
|
|
151
|
+
const indices = sortMultiColumn(d.columns, d.directions);
|
|
152
|
+
return { type: "sortedMultiColumn", payload: { indices }, transfer: [indices.buffer] };
|
|
153
|
+
},
|
|
154
|
+
sortStringHashes: (d) => {
|
|
155
|
+
const r = sortStringHashes(d.hashChunks, d.direction);
|
|
156
|
+
return {
|
|
157
|
+
type: "sortedStringHashes",
|
|
158
|
+
payload: { indices: r.indices, collisionRuns: r.collisionRuns },
|
|
159
|
+
transfer: [r.indices.buffer, r.collisionRuns.buffer],
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
sortChunk: (d) => {
|
|
163
|
+
const r = sortChunk(d.values, d.direction);
|
|
164
|
+
return {
|
|
165
|
+
type: "sortedChunk",
|
|
166
|
+
payload: { indices: r.indices, sortedValues: r.sortedValues, chunkOffset: d.chunkOffset },
|
|
167
|
+
transfer: [r.indices.buffer, r.sortedValues.buffer],
|
|
168
|
+
};
|
|
169
|
+
},
|
|
170
|
+
sortStringChunk: (d) => {
|
|
171
|
+
const r = sortStringChunk(d.hashChunks, d.direction);
|
|
172
|
+
return {
|
|
173
|
+
type: "sortedStringChunk",
|
|
174
|
+
payload: {
|
|
175
|
+
indices: r.indices,
|
|
176
|
+
sortedHashes: r.sortedHashes,
|
|
177
|
+
collisionRuns: r.collisionRuns,
|
|
178
|
+
chunkOffset: d.chunkOffset,
|
|
179
|
+
},
|
|
180
|
+
transfer: [r.indices.buffer, r.sortedHashes.buffer, r.collisionRuns.buffer],
|
|
181
|
+
};
|
|
182
|
+
},
|
|
183
|
+
sortMultiColumnChunk: (d) => {
|
|
184
|
+
const r = sortMultiColumnChunk(d.columns, d.directions);
|
|
185
|
+
return {
|
|
186
|
+
type: "sortedMultiColumnChunk",
|
|
187
|
+
payload: { indices: r.indices, sortedColumns: r.sortedColumns, chunkOffset: d.chunkOffset },
|
|
188
|
+
transfer: [r.indices.buffer, ...r.sortedColumns.map(c => c.buffer)],
|
|
189
|
+
};
|
|
190
|
+
},
|
|
191
|
+
};
|
|
253
192
|
|
|
254
193
|
self.onmessage = function(e) {
|
|
255
194
|
const { type, id } = e.data;
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
264
|
-
}
|
|
265
|
-
} else if (type === "sortIndices") {
|
|
266
|
-
try {
|
|
267
|
-
const { values, direction } = e.data;
|
|
268
|
-
const indices = sortIndices(values, direction);
|
|
269
|
-
// Transfer the indices buffer back (zero-copy)
|
|
270
|
-
self.postMessage({ type: "sortedIndices", id, indices }, [indices.buffer]);
|
|
271
|
-
} catch (error) {
|
|
272
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
273
|
-
}
|
|
274
|
-
} else if (type === "sortMultiColumn") {
|
|
275
|
-
try {
|
|
276
|
-
const { columns, directions } = e.data;
|
|
277
|
-
const indices = sortMultiColumn(columns, directions);
|
|
278
|
-
self.postMessage({ type: "sortedMultiColumn", id, indices }, [indices.buffer]);
|
|
279
|
-
} catch (error) {
|
|
280
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
281
|
-
}
|
|
282
|
-
} else if (type === "sortStringHashes") {
|
|
283
|
-
try {
|
|
284
|
-
const { hashChunks, direction } = e.data;
|
|
285
|
-
const result = sortStringHashes(hashChunks, direction);
|
|
286
|
-
self.postMessage(
|
|
287
|
-
{ type: "sortedStringHashes", id, indices: result.indices, collisionRuns: result.collisionRuns },
|
|
288
|
-
[result.indices.buffer, result.collisionRuns.buffer]
|
|
289
|
-
);
|
|
290
|
-
} catch (error) {
|
|
291
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
292
|
-
}
|
|
293
|
-
} else if (type === "sortChunk") {
|
|
294
|
-
try {
|
|
295
|
-
const { values, direction, chunkOffset } = e.data;
|
|
296
|
-
const result = sortChunk(values, direction);
|
|
297
|
-
self.postMessage(
|
|
298
|
-
{ type: "sortedChunk", id, indices: result.indices, sortedValues: result.sortedValues, chunkOffset },
|
|
299
|
-
[result.indices.buffer, result.sortedValues.buffer]
|
|
300
|
-
);
|
|
301
|
-
} catch (error) {
|
|
302
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
303
|
-
}
|
|
304
|
-
} else if (type === "sortStringChunk") {
|
|
305
|
-
try {
|
|
306
|
-
const { hashChunks, direction, chunkOffset } = e.data;
|
|
307
|
-
const result = sortStringChunk(hashChunks, direction);
|
|
308
|
-
self.postMessage(
|
|
309
|
-
{ type: "sortedStringChunk", id, indices: result.indices, sortedHashes: result.sortedHashes, collisionRuns: result.collisionRuns, chunkOffset },
|
|
310
|
-
[result.indices.buffer, result.sortedHashes.buffer, result.collisionRuns.buffer]
|
|
311
|
-
);
|
|
312
|
-
} catch (error) {
|
|
313
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
314
|
-
}
|
|
315
|
-
} else if (type === "sortMultiColumnChunk") {
|
|
316
|
-
try {
|
|
317
|
-
const { columns, directions, chunkOffset } = e.data;
|
|
318
|
-
const result = sortMultiColumnChunk(columns, directions);
|
|
319
|
-
const transferables = [result.indices.buffer, ...result.sortedColumns.map(c => c.buffer)];
|
|
320
|
-
self.postMessage(
|
|
321
|
-
{ type: "sortedMultiColumnChunk", id, indices: result.indices, sortedColumns: result.sortedColumns, chunkOffset },
|
|
322
|
-
transferables
|
|
323
|
-
);
|
|
324
|
-
} catch (error) {
|
|
325
|
-
self.postMessage({ type: "error", id, error: String(error) });
|
|
326
|
-
}
|
|
195
|
+
const handler = HANDLERS[type];
|
|
196
|
+
if (!handler) return;
|
|
197
|
+
try {
|
|
198
|
+
const result = handler(e.data);
|
|
199
|
+
self.postMessage({ type: result.type, id, ...result.payload }, result.transfer || []);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
self.postMessage({ type: "error", id, error: String(error) });
|
|
327
202
|
}
|
|
328
203
|
};
|
|
329
|
-
`,{maxWorkers:e.maxWorkers??(navigator===void 0?4:navigator.hardwareConcurrency)??4}),this.parallelThreshold=e.parallelThreshold??4e5,this.minChunkSize=e.minChunkSize??5e4}isAvailable(){return this.isTerminated?!1:this.pool.isAvailable()}terminate(){this.pool.terminate(),this.isTerminated=!0}async sortIndices(e,t){if(this.isTerminated)throw Error(`ParallelSortManager has been terminated`);return e.length<this.parallelThreshold?this.sortIndicesSingle(e,t):this.sortIndicesParallel(e,t)}async sortStringHashes(e,t,n){if(this.isTerminated)throw Error(`ParallelSortManager has been terminated`);return(e[0]?.length??0)<this.parallelThreshold?this.sortStringHashesSingle(e,t,n):this.sortStringHashesParallel(e,t,n)}async sortMultiColumn(e,t){if(this.isTerminated)throw Error(`ParallelSortManager has been terminated`);return(e[0]?.length??0)<this.parallelThreshold?this.sortMultiColumnSingle(e,t):this.sortMultiColumnParallel(e,t)}async sortIndicesSingle(e,t){let n=new Float64Array(e),r={type:`sortIndices`,id:0,values:n,direction:t};return(await this.pool.execute(r,[n.buffer])).indices}async sortStringHashesSingle(e,t,n){let r={type:`sortStringHashes`,id:0,hashChunks:e,direction:t},i=e.map(e=>e.buffer),a=await this.pool.execute(r,i);return a.collisionRuns.length>0&&this.resolveCollisions(a.indices,a.collisionRuns,n,t),a.indices}async sortMultiColumnSingle(e,t){let n=e.map(e=>new Float64Array(e)),r=new Int8Array(t.map(e=>e===`asc`?1:-1)),i={type:`sortMultiColumn`,id:0,columns:n,directions:r},a=[...n.map(e=>e.buffer),r.buffer];return(await this.pool.execute(i,a)).indices}async sortIndicesParallel(e,t){let n=this.splitIntoChunks(e).map(e=>{let n=new Float64Array(e.data);return{request:{type:`sortChunk`,id:0,values:n,direction:t,chunkOffset:e.offset},transferables:[n.buffer]}}),r=await this.pool.executeParallel(n);return r.sort((e,t)=>e.chunkOffset-t.chunkOffset),P(r.map(e=>({indices:e.indices,values:e.sortedValues,offset:e.chunkOffset})),t)}async sortStringHashesParallel(e,t,n){let r=e[0].length,i=this.calculateChunkBoundaries(r).map(n=>{let r=e.map(e=>new Float64Array(e.buffer,n.offset*8,n.length)).map(e=>{let t=new Float64Array(e.length);return t.set(e),t});return{request:{type:`sortStringChunk`,id:0,hashChunks:r,direction:t,chunkOffset:n.offset},transferables:r.map(e=>e.buffer)}}),a=await this.pool.executeParallel(i);a.sort((e,t)=>e.chunkOffset-t.chunkOffset);let o=a.map(e=>({indices:e.indices,values:e.sortedHashes,offset:e.chunkOffset})),s=[];for(let e of a)for(let t=0;t<e.collisionRuns.length;t+=2)s.push(e.collisionRuns[t]+e.chunkOffset,e.collisionRuns[t+1]+e.chunkOffset);let c=P(o,t),l=this.detectBoundaryCollisionsForStrings(o,t),u=new Uint32Array([...s,...l]);return u.length>0&&this.resolveCollisions(c,u,n,t),c}async sortMultiColumnParallel(e,t){let n=e[0].length,r=this.calculateChunkBoundaries(n),i=new Int8Array(t.map(e=>e===`asc`?1:-1)),a=r.map(t=>{let n=e.map(e=>{let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t.offset+r];return n}),r=new Int8Array(i);return{request:{type:`sortMultiColumnChunk`,id:0,columns:n,directions:r,chunkOffset:t.offset},transferables:[...n.map(e=>e.buffer),r.buffer]}}),o=await this.pool.executeParallel(a);return o.sort((e,t)=>e.chunkOffset-t.chunkOffset),F(o.map(e=>({indices:e.indices,columns:e.sortedColumns,directions:i,offset:e.chunkOffset})))}splitIntoChunks(e){let t=e.length,n=this.pool.getMaxWorkers(),r=Math.max(this.minChunkSize,Math.ceil(t/n)),i=[];for(let n=0;n<t;n+=r){let a=Math.min(n+r,t);i.push({data:e.slice(n,a),offset:n})}return i}calculateChunkBoundaries(e){let t=this.pool.getMaxWorkers(),n=Math.max(this.minChunkSize,Math.ceil(e/t)),r=[];for(let t=0;t<e;t+=n)r.push({offset:t,length:Math.min(n,e-t)});return r}detectBoundaryCollisionsForStrings(e,t){if(e.length<=1)return[];let n=[],r=0;for(let t=0;t<e.length-1;t++){let i=e[t],a=e[t+1];if(i.indices.length===0||a.indices.length===0){r+=i.indices.length;continue}let o=i.values[i.indices.length-1],s=a.values[0];if(o===s){let e=i.indices.length-1;for(;e>0&&i.values[e-1]===o;)e--;let t=0;for(;t<a.indices.length-1&&a.values[t+1]===s;)t++;n.push(r+e,r+i.indices.length+t+1)}r+=i.indices.length}return n}resolveCollisions(e,t,n,r){let i=r===`asc`?1:-1;for(let r=0;r<t.length;r+=2){let a=t[r],o=t[r+1];if(o<=a||o>e.length)continue;let s=Array.from(e.slice(a,o)),c=n[s[0]],l=!0;for(let e=1;e<s.length;e++)if(n[s[e]]!==c){l=!1;break}if(!l){s.sort((e,t)=>i*n[e].localeCompare(n[t]));for(let t=0;t<s.length;t++)e[a+t]=s[t]}}}};function L(e){let t=e.toLowerCase(),n=Math.min(t.length,10),r=0;for(let e=0;e<n;e++){let n=t.codePointAt(e)??200,i;i=n>=97&&n<=122?n-97:n>=48&&n<=57?n-48+26:0,r=r*36+i}for(let e=n;e<10;e++)r*=36;return r}function R(e,t){let n=e==null||Array.isArray(e)&&e.length===0,r=t==null||Array.isArray(t)&&t.length===0;if(n&&r)return 0;if(n)return 1;if(r)return-1;if(Array.isArray(e)||Array.isArray(t)){let n=Array.isArray(e)?e.join(`, `):y(e),r=Array.isArray(t)?t.join(`, `):y(t);return n.localeCompare(r)}let i=Number(e),a=Number(t);return!Number.isNaN(i)&&!Number.isNaN(a)?i-a:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():y(e).localeCompare(y(t))}function z(e){if(e==null)return Number.MAX_VALUE;if(typeof e==`number`)return e;if(e instanceof Date)return e.getTime();if(typeof e==`string`)return L(e);if(Array.isArray(e))return e.length===0?Number.MAX_VALUE:L(e.join(`, `));if(typeof e==`object`)return L(JSON.stringify(e));let t=Number(e);return Number.isNaN(t)?0:t}function ue(e,t){let n=[];for(let r of t.sortModel){let i=z(t.getFieldValue(e,r.colId));n.push(i)}return n}function de(e,t,n){if(!e||!t)return null;for(let r=0;r<n.length;r++){let i=e[r]-t[r];if(i!==0)return n[r].direction===`asc`?i:-i}return 0}function fe(e,t,n,r){for(let{colId:i,direction:a}of n){let n=R(r(e,i),r(t,i));if(n!==0)return a===`asc`?n:-n}return 0}function pe(e){let t=e.toLowerCase(),n=[];for(let e=0;e<3;e++){let r=e*10,i=0;for(let e=0;e<10;e++){let n=r+e,a=n<t.length?t.codePointAt(n)??200:0,o;o=a>=97&&a<=122?a-97:a>=48&&a<=57?a-48+26:0,i=i*36+o}n.push(i)}return n}function B(e){if(e==null)return Number.MAX_VALUE;if(Array.isArray(e))return e.length===0?Number.MAX_VALUE:L(e.join(`, `));if(typeof e==`number`)return e;if(e instanceof Date)return e.getTime();if(typeof e==`string`)return L(e);if(typeof e==`object`)return L(JSON.stringify(e));let t=Number(e);return Number.isNaN(t)?0:t}function V(e,t,n){return[...e].sort((e,r)=>{for(let{colId:i,direction:a}of t){let t=R(n(e,i),n(r,i));if(t!==0)return a===`asc`?t:-t}return 0})}const me=(e,t,n)=>{for(let r of e){let e=n(r,t);if(e!=null)return typeof e==`string`||Array.isArray(e)||typeof e==`object`&&!(e instanceof Date)?`string`:`numeric`}return`numeric`},he=(e,t,n)=>{let r=[],i=Array.from({length:3},()=>[]);for(let a of e){let e=y(n(a,t));r.push(e);let o=pe(e);for(let e=0;e<3;e++)i[e].push(o[e])}return{originalStrings:r,hashChunkArrays:i.map(e=>new Float64Array(e))}},ge=(e,t,n)=>e.map(e=>B(n(e,t))),_e=(e,t,n)=>{let r=[],i=[];for(let{colId:a,direction:o}of t)r.push(e.map(e=>B(n(e,a)))),i.push(o??`asc`);return{columnValues:r,directions:i}},ve=(e,t)=>{let n=Array(e.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n},ye=async(e,t,n,r)=>{let{colId:i,direction:a}=t,o=a??`asc`;if(me(e,i,r)===`string`){let{originalStrings:t,hashChunkArrays:a}=he(e,i,r);return n.sortStringHashes(a,o,t)}let s=ge(e,i,r);return n.sortIndices(s,o)},be=async(e,t,n,r)=>{let{columnValues:i,directions:a}=_e(e,t,r);return n.sortMultiColumn(i,a)},H=async(e,t,n,r)=>ve(e,t.length===1?await ye(e,t[0],n,r):await be(e,t,n,r));function U(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function xe(e){return e==null||e===``||Array.isArray(e)&&e.length===0}function W(e,t){let n=xe(e);if(t.selectedValues&&t.selectedValues.size>0){let r=t.includeBlank===!0&&n;if(Array.isArray(e)){let n=[...e].sort((e,t)=>{let n=String(e),r=String(t);return n===r?0:n<r?-1:1}).join(`, `);return t.selectedValues.has(n)||r}let i=y(e);return t.selectedValues.has(i)||r}let r=y(e).toLowerCase(),i=String(t.value??``).toLowerCase();switch(t.operator){case`contains`:return r.includes(i);case`notContains`:return!r.includes(i);case`equals`:return r===i;case`notEquals`:return r!==i;case`startsWith`:return r.startsWith(i);case`endsWith`:return r.endsWith(i);case`blank`:return n;case`notBlank`:return!n;default:return!0}}function G(e,t){let n=e==null||e===``;if(t.operator===`blank`)return n;if(t.operator===`notBlank`)return!n;if(n)return!1;let r=typeof e==`number`?e:Number(e);if(Number.isNaN(r))return!1;let i=t.value??0,a=t.valueTo??0;switch(t.operator){case`=`:return r===i;case`!=`:return r!==i;case`>`:return r>i;case`<`:return r<i;case`>=`:return r>=i;case`<=`:return r<=i;case`between`:return r>=i&&r<=a;default:return!0}}function K(e,t){let n=e==null||e===``;if(t.operator===`blank`)return n;if(t.operator===`notBlank`)return!n;if(n)return!1;let r=e instanceof Date?e:new Date(y(e));if(Number.isNaN(r.getTime()))return!1;let i=t.value instanceof Date?t.value:new Date(String(t.value??``)),a=t.valueTo instanceof Date?t.valueTo:new Date(String(t.valueTo??``)),o=r.getTime(),s=i.getTime(),c=a.getTime();switch(t.operator){case`=`:return U(r,i);case`!=`:return!U(r,i);case`>`:return o>s;case`<`:return o<s;case`between`:return o>=s&&o<=c;default:return!0}}function q(e,t){switch(t.type){case`text`:return W(e,t);case`number`:return G(e,t);case`date`:return K(e,t);default:return!0}}function J(e,t){if(!t.conditions||t.conditions.length===0)return!0;let n=t.conditions[0];if(!n)return!0;let r=q(e,n);for(let n=1;n<t.conditions.length;n++){let i=t.conditions[n-1],a=t.conditions[n],o=i.nextOperator??t.combination,s=q(e,a);o===`and`?r&&=s:r||=s}return r}function Y(e,t,n){let r=Object.entries(t).filter(([,e])=>e!=null);if(r.length===0)return!0;for(let[t,i]of r)if(!J(n(e,t),i))return!1;return!0}function X(e,t,n){let r=Object.entries(t).filter(([,e])=>typeof e==`string`?e.trim()!==``:e.conditions&&e.conditions.length>0);return r.length===0?e:e.filter(e=>{for(let[t,i]of r){let r=n(e,t);if(typeof i==`string`){if(!y(r).toLowerCase().includes(i.toLowerCase()))return!1;continue}if(!J(r,i))return!1}return!0})}function Z(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}function Se(e,t={}){let{getFieldValue:n=Z,useWorker:r=!0,parallelSort:i}=t,a=e,o=!1,s=r?new I(i===!1?{maxWorkers:1}:i):null;return{async fetch(e){let t=a?[...a]:[];e.filter&&Object.keys(e.filter).length>0&&(t=X(t,e.filter,n)),e.sort&&e.sort.length>0&&(t=s&&s.isAvailable()&&t.length>=2e5?await H(t,e.sort,s,n):V(t,e.sort,n));let r=t.length,{pageIndex:i,pageSize:o}=e.pagination,c=i*o;return{rows:t.slice(c,c+o),totalRows:r}},destroy(){o||(o=!0,a=null,s&&s.terminate())},moveRow(e,t){if(!a||e===t||e<0||e>=a.length||t<0||t>=a.length)return;let[n]=a.splice(e,1),r=t>e?t-1:t;a.splice(r,0,n)}}}function Ce(e){return Se(e)}function we(e){return{async fetch(t){return e(t)}}}var Te=class{rows=[];rowById=new Map;sortedIndices=[];sortModel=[];sortModelHash=``;filterModel={};filteredIndices=new Set;distinctValues=new Map;rowSortCache=new Map;options;constructor(e,t=[]){this.options={getRowId:e.getRowId,getFieldValue:e.getFieldValue??m},this.setData(t)}clear(){this.rows=[],this.rowById.clear(),this.sortedIndices=[],this.filterModel={},this.filteredIndices.clear(),this.rowSortCache.clear(),this.distinctValues.clear(),this.sortModel=[],this.sortModelHash=``}setData(e){this.rows=[...e],this.rowById.clear(),this.rowSortCache.clear(),this.distinctValues.clear();for(let e=0;e<this.rows.length;e++){let t=this.rows[e],n=this.options.getRowId(t);this.rowById.set(n,e)}this.rebuildSortedIndices(),this.rebuildFilteredIndices(),this.rebuildDistinctValues()}query(e){this.setSortModel(e.sort??[]),this.setFilterModel(e.filter??{});let t=this.getVisibleIndices(),n=t.length,{pageIndex:r,pageSize:i}=e.pagination,a=r*i,o=Math.min(a+i,n),s=[];for(let e=a;e<o;e++){let n=t[e];n!==void 0&&s.push(this.rows[n])}return{rows:s,totalRows:n}}getRowById(e){let t=this.rowById.get(e);return t===void 0?void 0:this.rows[t]}getRowByIndex(e){return this.rows[e]}getTotalRowCount(){return this.rows.length}getAllRows(){return[...this.rows]}moveRow(e,t){if(e===t||e<0||e>=this.rows.length||t<0||t>=this.rows.length)return;let[n]=this.rows.splice(e,1),r=t>e?t-1:t;this.rows.splice(r,0,n),this.rowById.clear();for(let e=0;e<this.rows.length;e++)this.rowById.set(this.options.getRowId(this.rows[e]),e);this.sortedIndices=Array.from({length:this.rows.length},(e,t)=>t),this.rowSortCache.clear()}getVisibleRowCount(){return Object.keys(this.filterModel).length===0?this.rows.length:this.filteredIndices.size}getDistinctValues(e){let t=this.distinctValues.get(e);return t?Array.from(t):[]}addRows(e){for(let t of e)this.addRow(t)}addRow(e){let t=this.options.getRowId(e);if(this.rowById.has(t)){console.warn(`Row with ID ${t} already exists. Skipping.`);return}let n=this.rows.length;if(this.rows.push(e),this.rowById.set(t,n),this.updateDistinctValuesForRow(e,`add`),this.sortModel.length>0&&this.computeRowHashes(n,e),this.sortModel.length>0){let e=this.binarySearchInsertPosition(n);this.sortedIndices.splice(e,0,n)}else this.sortedIndices.push(n);this.rowPassesFilter(e)&&this.filteredIndices.add(n)}removeRows(e){let t=[];for(let n of e){let e=this.rowById.get(n);e!==void 0&&t.push(e)}if(t.length!==0){t.sort((e,t)=>t-e);for(let e of t)this.removeRowByIndex(e)}}removeRowByIndex(e){let t=this.rows[e];if(!t)return;let n=this.options.getRowId(t);this.updateDistinctValuesForRow(t,`remove`);let r=this.sortedIndices.indexOf(e);r!==-1&&this.sortedIndices.splice(r,1),this.filteredIndices.delete(e),this.rowSortCache.delete(e),this.rowById.delete(n),this.rows.splice(e,1),this.reindexAfterRemoval(e)}reindexAfterRemoval(e){for(let[t,n]of this.rowById.entries())n>e&&this.rowById.set(t,n-1);for(let t=0;t<this.sortedIndices.length;t++)this.sortedIndices[t]>e&&this.sortedIndices[t]--;let t=new Set;for(let n of this.filteredIndices)n>e?t.add(n-1):t.add(n);this.filteredIndices=t;let n=new Map;for(let[t,r]of this.rowSortCache)t>e?n.set(t-1,r):n.set(t,r);this.rowSortCache=n}updateCell(e,t,n){let r=this.rowById.get(e);if(r===void 0){console.warn(`Row with ID ${e} not found.`);return}let i=this.rows[r],a=this.options.getFieldValue(i,t);if(h(i,t,n),this.updateDistinctValueForField(t,a,n),this.sortModel.some(e=>e.colId===t)&&this.sortModel.length>0){this.computeRowHashes(r,i);let e=this.sortedIndices.indexOf(r);e!==-1&&this.sortedIndices.splice(e,1);let t=this.binarySearchInsertPosition(r);this.sortedIndices.splice(t,0,r)}t in this.filterModel&&(this.rowPassesFilter(i)?this.filteredIndices.add(r):this.filteredIndices.delete(r))}updateRow(e,t){for(let[n,r]of Object.entries(t))this.updateCell(e,n,r)}setSortModel(e){let t=JSON.stringify(e);t!==this.sortModelHash&&(this.sortModelHash=t,this.sortModel=[...e],this.rebuildHashCache(),this.rebuildSortedIndices())}getSortModel(){return[...this.sortModel]}setFilterModel(e){JSON.stringify(e)!==JSON.stringify(this.filterModel)&&(this.filterModel={...e},this.rebuildFilteredIndices())}getFilterModel(){return{...this.filterModel}}rebuildSortedIndices(){this.sortedIndices=Array.from({length:this.rows.length},(e,t)=>t),this.sortModel.length!==0&&this.sortedIndices.sort((e,t)=>this.compareRows(e,t))}rebuildHashCache(){if(this.rowSortCache.clear(),this.sortModel.length!==0)for(let e=0;e<this.rows.length;e++)this.computeRowHashes(e,this.rows[e])}computeRowHashes(e,t){if(this.sortModel.length===0)return;let n=ue(t,{sortModel:this.sortModel,sortModelHash:this.sortModelHash,getFieldValue:this.options.getFieldValue}),r=this.rowSortCache.get(e);r||(r={hashes:new Map},this.rowSortCache.set(e,r)),r.hashes.set(this.sortModelHash,n)}compareRows(e,t){let n=this.rowSortCache.get(e),r=this.rowSortCache.get(t),i=n?.hashes.get(this.sortModelHash),a=r?.hashes.get(this.sortModelHash),o=de(i,a,this.sortModel);return o===null?fe(this.rows[e],this.rows[t],this.sortModel,this.options.getFieldValue):o}binarySearchInsertPosition(e){let t=0,n=this.sortedIndices.length;for(;t<n;){let r=t+n>>>1,i=this.sortedIndices[r];this.compareRows(e,i)>0?t=r+1:n=r}return t}rebuildFilteredIndices(){if(this.filteredIndices.clear(),Object.entries(this.filterModel).some(([,e])=>e!=null))for(let e=0;e<this.rows.length;e++)this.rowPassesFilter(this.rows[e])&&this.filteredIndices.add(e)}rowPassesFilter(e){return Y(e,this.filterModel,this.options.getFieldValue)}getVisibleIndices(){return Object.entries(this.filterModel).some(([,e])=>e!=null)?this.sortedIndices.filter(e=>this.filteredIndices.has(e)):this.sortedIndices}rebuildDistinctValues(){this.distinctValues.clear();for(let e of this.rows)this.updateDistinctValuesForRow(e,`add`)}updateDistinctValuesForRow(e,t){if(!(typeof e!=`object`||!e)&&t===`add`)for(let[t,n]of Object.entries(e))n!=null&&this.addToDistinctValues(t,n)}updateDistinctValueForField(e,t,n){n!=null&&this.addToDistinctValues(e,n)}addToDistinctValues(e,t){let n=this.distinctValues.get(e);if(n||(n=new Set,this.distinctValues.set(e,n)),Array.isArray(t))for(let e of t)e!=null&&n.add(e);else n.add(t)}};function Ee(e,t){let{getRowId:n,getFieldValue:r,debounceMs:i=50,onTransactionProcessed:a,useWorker:o=!0,parallelSort:s}=t,c=new Te({getRowId:n,getFieldValue:r??Z},e),l=new Set,u=g().emit,d=o&&s!==!1?new I(s):null,f=new D({debounceMs:i,store:c,onProcessed:e=>{a?.(e);for(let t of l)t(e)}});return{async fetch(e){if(f.hasPending()){u({type:`DATA_LOADING`});try{await f.flush()}finally{u({type:`DATA_LOADED`,totalRows:c.getTotalRowCount()})}}let t=c.getAllRows(),n=r??Z;if(e.filter&&Object.keys(e.filter).length>0&&(t=X(t,e.filter,n)),e.sort&&e.sort.length>0)if(d&&d.isAvailable()&&t.length>=2e5){u({type:`DATA_LOADING`});try{t=await H(t,e.sort,d,n)}finally{u({type:`DATA_LOADED`,totalRows:t.length})}}else t=V(t,e.sort,n);let i=t.length,{pageIndex:a,pageSize:o}=e.pagination,s=a*o;return{rows:t.slice(s,s+o),totalRows:i}},addRows(e){f.add(e)},removeRows(e){f.remove(e)},updateCell(e,t,n){f.updateCell(e,t,n)},updateRow(e,t){f.updateRow(e,t)},async flushTransactions(){await f.flush()},hasPendingTransactions(){return f.hasPending()},getDistinctValues(e){return c.getDistinctValues(e)},getRowById(e){return c.getRowById(e)},getTotalRowCount(){return c.getTotalRowCount()},subscribe(e){return l.add(e),()=>{l.delete(e)}},clear(){c.clear(),l.clear()},moveRow(e,t){c.moveRow(e,t)}}}const De=`
|
|
204
|
+
`,{maxWorkers:e.maxWorkers??(navigator===void 0?4:navigator.hardwareConcurrency)??4}),this.parallelThreshold=e.parallelThreshold??4e5,this.minChunkSize=e.minChunkSize??5e4}isAvailable(){return this.isTerminated?!1:this.pool.isAvailable()}terminate(){this.pool.terminate(),this.isTerminated=!0}async sortIndices(e,t){return this.assertNotTerminated(),e.length<this.parallelThreshold?this.sortIndicesSingle(e,t):this.sortIndicesParallel(e,t)}async sortStringHashes(e,t,n){return this.assertNotTerminated(),(e[0]?.length??0)<this.parallelThreshold?this.sortStringHashesSingle(e,t,n):this.sortStringHashesParallel(e,t,n)}async sortMultiColumn(e,t){return this.assertNotTerminated(),(e[0]?.length??0)<this.parallelThreshold?this.sortMultiColumnSingle(e,t):this.sortMultiColumnParallel(e,t)}assertNotTerminated(){if(this.isTerminated)throw Error(`ParallelSortManager has been terminated`)}async sortIndicesSingle(e,t){let n=new Float64Array(e),r={type:`sortIndices`,id:0,values:n,direction:t};return(await this.pool.execute(r,[n.buffer])).indices}async sortStringHashesSingle(e,t,n){let r={type:`sortStringHashes`,id:0,hashChunks:e,direction:t},i=e.map(e=>e.buffer),a=await this.pool.execute(r,i);return a.collisionRuns.length>0&&B(a.indices,a.collisionRuns,n,t),a.indices}async sortMultiColumnSingle(e,t){let n=e.map(e=>new Float64Array(e)),r=new Int8Array(t.map(e=>e===`asc`?1:-1)),i={type:`sortMultiColumn`,id:0,columns:n,directions:r},a=[...n.map(e=>e.buffer),r.buffer];return(await this.pool.execute(i,a)).indices}boundariesFor(e){return Pe(e,this.pool.getMaxWorkers(),this.minChunkSize)}async runChunks(e){let t=await this.pool.executeParallel(e);return t.sort((e,t)=>e.chunkOffset-t.chunkOffset),t}async sortIndicesParallel(e,t){let n=this.boundariesFor(e.length).map(n=>{let r=new Float64Array(e.slice(n.offset,n.offset+n.length));return{request:{type:`sortChunk`,id:0,values:r,direction:t,chunkOffset:n.offset},transferables:[r.buffer]}});return R((await this.runChunks(n)).map(e=>({indices:e.indices,values:e.sortedValues,offset:e.chunkOffset})),t)}async sortStringHashesParallel(e,t,n){let r=this.boundariesFor(e[0].length).map(n=>{let r=e.map(e=>{let t=new Float64Array(n.length);return t.set(new Float64Array(e.buffer,n.offset*8,n.length)),t});return{request:{type:`sortStringChunk`,id:0,hashChunks:r,direction:t,chunkOffset:n.offset},transferables:r.map(e=>e.buffer)}}),i=await this.runChunks(r),a=i.map(e=>({indices:e.indices,values:e.sortedHashes,offset:e.chunkOffset})),o=Re(i),s=R(a,t),c=Fe(a),l=new Uint32Array([...o,...c]);return l.length>0&&B(s,l,n,t),s}async sortMultiColumnParallel(e,t){let n=this.boundariesFor(e[0].length),r=new Int8Array(t.map(e=>e===`asc`?1:-1)),i=n.map(t=>{let n=e.map(e=>{let n=new Float64Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t.offset+r];return n}),i=new Int8Array(r);return{request:{type:`sortMultiColumnChunk`,id:0,columns:n,directions:i,chunkOffset:t.offset},transferables:[...n.map(e=>e.buffer),i.buffer]}});return z((await this.runChunks(i)).map(e=>({indices:e.indices,columns:e.sortedColumns,directions:r,offset:e.chunkOffset})))}};const Re=e=>{let t=[];for(let n of e)for(let e=0;e<n.collisionRuns.length;e+=2)t.push(n.collisionRuns[e]+n.chunkOffset,n.collisionRuns[e+1]+n.chunkOffset);return t};function H(e){let t=e.toLowerCase(),n=Math.min(t.length,10),r=0;for(let e=0;e<n;e++){let n=t.codePointAt(e)??200,i;i=n>=97&&n<=122?n-97:n>=48&&n<=57?n-48+26:0,r=r*36+i}for(let e=n;e<10;e++)r*=36;return r}function U(e,t){let n=e==null||Array.isArray(e)&&e.length===0,r=t==null||Array.isArray(t)&&t.length===0;if(n&&r)return 0;if(n)return 1;if(r)return-1;if(Array.isArray(e)||Array.isArray(t)){let n=Array.isArray(e)?e.join(`, `):b(e),r=Array.isArray(t)?t.join(`, `):b(t);return n.localeCompare(r)}let i=Number(e),a=Number(t);return!Number.isNaN(i)&&!Number.isNaN(a)?i-a:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():b(e).localeCompare(b(t))}function W(e){if(e==null)return Number.MAX_VALUE;if(typeof e==`number`)return e;if(e instanceof Date)return e.getTime();if(typeof e==`string`)return H(e);if(Array.isArray(e))return e.length===0?Number.MAX_VALUE:H(e.join(`, `));if(typeof e==`object`)return H(JSON.stringify(e));let t=Number(e);return Number.isNaN(t)?0:t}function ze(e,t){let n=[];for(let r of t.sortModel){let i=W(t.getFieldValue(e,r.colId));n.push(i)}return n}function Be(e,t,n){if(!e||!t)return null;for(let r=0;r<n.length;r++){let i=e[r]-t[r];if(i!==0)return n[r].direction===`asc`?i:-i}return 0}function Ve(e,t,n,r){for(let{colId:i,direction:a}of n){let n=U(r(e,i),r(t,i));if(n!==0)return a===`asc`?n:-n}return 0}function He(e){let t=e.toLowerCase(),n=[];for(let e=0;e<3;e++){let r=e*10,i=0;for(let e=0;e<10;e++){let n=r+e,a=n<t.length?t.codePointAt(n)??200:0,o;o=a>=97&&a<=122?a-97:a>=48&&a<=57?a-48+26:0,i=i*36+o}n.push(i)}return n}function G(e){if(e==null)return Number.MAX_VALUE;if(Array.isArray(e))return e.length===0?Number.MAX_VALUE:H(e.join(`, `));if(typeof e==`number`)return e;if(e instanceof Date)return e.getTime();if(typeof e==`string`)return H(e);if(typeof e==`object`)return H(JSON.stringify(e));let t=Number(e);return Number.isNaN(t)?0:t}function K(e,t,n){return[...e].sort((e,r)=>{for(let{colId:i,direction:a}of t){let t=U(n(e,i),n(r,i));if(t!==0)return a===`asc`?t:-t}return 0})}const Ue=(e,t,n)=>{for(let r of e){let e=n(r,t);if(e!=null)return typeof e==`string`||Array.isArray(e)||typeof e==`object`&&!(e instanceof Date)?`string`:`numeric`}return`numeric`},We=(e,t,n)=>{let r=[],i=Array.from({length:3},()=>[]);for(let a of e){let e=b(n(a,t));r.push(e);let o=He(e);for(let e=0;e<3;e++)i[e].push(o[e])}return{originalStrings:r,hashChunkArrays:i.map(e=>new Float64Array(e))}},Ge=(e,t,n)=>e.map(e=>G(n(e,t))),Ke=(e,t,n)=>{let r=[],i=[];for(let{colId:a,direction:o}of t)r.push(e.map(e=>G(n(e,a)))),i.push(o??`asc`);return{columnValues:r,directions:i}},qe=(e,t)=>{let n=Array(e.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n},Je=async(e,t,n,r)=>{let{colId:i,direction:a}=t,o=a??`asc`;if(Ue(e,i,r)===`string`){let{originalStrings:t,hashChunkArrays:a}=We(e,i,r);return n.sortStringHashes(a,o,t)}let s=Ge(e,i,r);return n.sortIndices(s,o)},Ye=async(e,t,n,r)=>{let{columnValues:i,directions:a}=Ke(e,t,r);return n.sortMultiColumn(i,a)},Xe=async(e,t,n,r)=>qe(e,t.length===1?await Je(e,t[0],n,r):await Ye(e,t,n,r));function q(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function Ze(e){return e==null||e===``||Array.isArray(e)&&e.length===0}const Qe={contains:(e,t)=>e.includes(t),notContains:(e,t)=>!e.includes(t),equals:(e,t)=>e===t,notEquals:(e,t)=>e!==t,startsWith:(e,t)=>e.startsWith(t),endsWith:(e,t)=>e.endsWith(t),blank:(e,t,n)=>n,notBlank:(e,t,n)=>!n};function J(e,t){let n=Ze(e);if(t.selectedValues&&t.selectedValues.size>0){let r=t.includeBlank===!0&&n;if(Array.isArray(e)){let n=[...e].sort((e,t)=>{let n=String(e),r=String(t);return n===r?0:n<r?-1:1}).join(`, `);return t.selectedValues.has(n)||r}let i=b(e);return t.selectedValues.has(i)||r}let r=b(e).toLowerCase(),i=String(t.value??``).toLowerCase();return Qe[t.operator](r,i,n)}const $e={"=":(e,t)=>e===t,"!=":(e,t)=>e!==t,">":(e,t)=>e>t,"<":(e,t)=>e<t,">=":(e,t)=>e>=t,"<=":(e,t)=>e<=t,between:(e,t,n)=>e>=t&&e<=n};function Y(e,t){let n=e==null||e===``;if(t.operator===`blank`)return n;if(t.operator===`notBlank`)return!n;if(n)return!1;let r=typeof e==`number`?e:Number(e);if(Number.isNaN(r))return!1;let i=t.value??0,a=t.valueTo??0;return $e[t.operator](r,i,a)}const et={"=":(e,t)=>q(e,t),"!=":(e,t)=>!q(e,t),">":(e,t)=>e.getTime()>t.getTime(),"<":(e,t)=>e.getTime()<t.getTime(),between:(e,t,n)=>{let r=e.getTime();return r>=t.getTime()&&r<=n.getTime()}};function tt(e,t){let n=e==null||e===``;if(t.operator===`blank`)return n;if(t.operator===`notBlank`)return!n;if(n)return!1;let r=e instanceof Date?e:new Date(b(e));if(Number.isNaN(r.getTime()))return!1;let i=t.value instanceof Date?t.value:new Date(String(t.value??``)),a=t.valueTo instanceof Date?t.valueTo:new Date(String(t.valueTo??``));return et[t.operator](r,i,a)}function nt(e,t){switch(t.type){case`text`:return J(e,t);case`number`:return Y(e,t);case`date`:return tt(e,t);default:return!0}}function X(e,t){if(!t.conditions||t.conditions.length===0)return!0;let n=t.conditions[0];if(!n)return!0;let r=nt(e,n);for(let n=1;n<t.conditions.length;n++){let i=t.conditions[n-1],a=t.conditions[n],o=i.nextOperator??t.combination,s=nt(e,a);o===`and`?r&&=s:r||=s}return r}function rt(e,t,n){let r=Object.entries(t).filter(([,e])=>e!=null);if(r.length===0)return!0;for(let[t,i]of r)if(!X(n(e,t),i))return!1;return!0}function it(e,t,n){let r=Object.entries(t).filter(([,e])=>typeof e==`string`?e.trim()!==``:e.conditions&&e.conditions.length>0);return r.length===0?e:e.filter(e=>{for(let[t,i]of r){let r=n(e,t);if(typeof i==`string`){if(!b(r).toLowerCase().includes(i.toLowerCase()))return!1;continue}if(!X(r,i))return!1}return!0})}function Z(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return null;r=r[e]}return r??null}function at(e,t={}){let{getFieldValue:n=Z,useWorker:r=!0,parallelSort:i}=t,a=e,o=!1,s=r?new V(i===!1?{maxWorkers:1}:i):null;return{async fetch(e){let t=a?[...a]:[];e.filter&&Object.keys(e.filter).length>0&&(t=it(t,e.filter,n)),e.sort&&e.sort.length>0&&(t=s&&s.isAvailable()&&t.length>=2e5?await Xe(t,e.sort,s,n):K(t,e.sort,n));let r=t.length,{pageIndex:i,pageSize:o}=e.pagination,c=i*o;return{rows:t.slice(c,c+o),totalRows:r}},destroy(){o||(o=!0,a=null,s&&s.terminate())},moveRow(e,t){if(!a||e===t||e<0||e>=a.length||t<0||t>=a.length)return;let[n]=a.splice(e,1),r=t>e?t-1:t;a.splice(r,0,n)}}}function Q(e){return at(e)}function ot(e){return{async fetch(t){return e(t)}}}var st=class{rows=[];rowById=new Map;sortedIndices=[];sortModel=[];sortModelHash=``;filterModel={};filteredIndices=new Set;distinctValues=new Map;rowSortCache=new Map;options;constructor(e,t=[]){this.options={getRowId:e.getRowId,getFieldValue:e.getFieldValue??g},this.setData(t)}clear(){this.rows=[],this.rowById.clear(),this.sortedIndices=[],this.filterModel={},this.filteredIndices.clear(),this.rowSortCache.clear(),this.distinctValues.clear(),this.sortModel=[],this.sortModelHash=``}setData(e){this.rows=[...e],this.rowById.clear(),this.rowSortCache.clear(),this.distinctValues.clear();for(let e=0;e<this.rows.length;e++){let t=this.rows[e],n=this.options.getRowId(t);this.rowById.set(n,e)}this.rebuildSortedIndices(),this.rebuildFilteredIndices(),this.rebuildDistinctValues()}query(e){this.setSortModel(e.sort??[]),this.setFilterModel(e.filter??{});let t=this.getVisibleIndices(),n=t.length,{pageIndex:r,pageSize:i}=e.pagination,a=r*i,o=Math.min(a+i,n),s=[];for(let e=a;e<o;e++){let n=t[e];n!==void 0&&s.push(this.rows[n])}return{rows:s,totalRows:n}}getRowById(e){let t=this.rowById.get(e);return t===void 0?void 0:this.rows[t]}getRowByIndex(e){return this.rows[e]}getTotalRowCount(){return this.rows.length}getAllRows(){return[...this.rows]}moveRow(e,t){if(e===t||e<0||e>=this.rows.length||t<0||t>=this.rows.length)return;let[n]=this.rows.splice(e,1),r=t>e?t-1:t;this.rows.splice(r,0,n),this.rowById.clear();for(let e=0;e<this.rows.length;e++)this.rowById.set(this.options.getRowId(this.rows[e]),e);this.sortedIndices=Array.from({length:this.rows.length},(e,t)=>t),this.rowSortCache.clear()}getVisibleRowCount(){return Object.keys(this.filterModel).length===0?this.rows.length:this.filteredIndices.size}getDistinctValues(e){let t=this.distinctValues.get(e);return t?Array.from(t.keys()):[]}addRows(e){for(let t of e)this.addRow(t)}addRow(e){let t=this.options.getRowId(e);if(this.rowById.has(t)){console.warn(`Row with ID ${t} already exists. Skipping.`);return}let n=this.rows.length;if(this.rows.push(e),this.rowById.set(t,n),this.updateDistinctValuesForRow(e,`add`),this.sortModel.length>0&&this.computeRowHashes(n,e),this.sortModel.length>0){let e=this.binarySearchInsertPosition(n);this.sortedIndices.splice(e,0,n)}else this.sortedIndices.push(n);this.rowPassesFilter(e)&&this.filteredIndices.add(n)}removeRows(e){let t=[];for(let n of e){let e=this.rowById.get(n);e!==void 0&&t.push(e)}if(t.length===0)return 0;t.sort((e,t)=>t-e);for(let e of t)this.removeRowByIndex(e);return t.length}removeRowByIndex(e){let t=this.rows[e];if(!t)return;let n=this.options.getRowId(t);this.updateDistinctValuesForRow(t,`remove`);let r=this.sortedIndices.indexOf(e);r!==-1&&this.sortedIndices.splice(r,1),this.filteredIndices.delete(e),this.rowSortCache.delete(e),this.rowById.delete(n),this.rows.splice(e,1),this.reindexAfterRemoval(e)}reindexAfterRemoval(e){for(let[t,n]of this.rowById.entries())n>e&&this.rowById.set(t,n-1);for(let t=0;t<this.sortedIndices.length;t++)this.sortedIndices[t]>e&&this.sortedIndices[t]--;let t=new Set;for(let n of this.filteredIndices)n>e?t.add(n-1):t.add(n);this.filteredIndices=t;let n=new Map;for(let[t,r]of this.rowSortCache)t>e?n.set(t-1,r):n.set(t,r);this.rowSortCache=n}updateCell(e,t,n){let r=this.rowById.get(e);if(r===void 0){console.warn(`Row with ID ${e} not found.`);return}let i=this.rows[r],a=this.options.getFieldValue(i,t);if(_(i,t,n),this.updateDistinctValueForField(t,a,n),this.sortModel.some(e=>e.colId===t)&&this.sortModel.length>0){this.computeRowHashes(r,i);let e=this.sortedIndices.indexOf(r);e!==-1&&this.sortedIndices.splice(e,1);let t=this.binarySearchInsertPosition(r);this.sortedIndices.splice(t,0,r)}t in this.filterModel&&(this.rowPassesFilter(i)?this.filteredIndices.add(r):this.filteredIndices.delete(r))}updateRow(e,t){for(let[n,r]of Object.entries(t))this.updateCell(e,n,r)}setSortModel(e){let t=JSON.stringify(e);t!==this.sortModelHash&&(this.sortModelHash=t,this.sortModel=[...e],this.rebuildHashCache(),this.rebuildSortedIndices())}getSortModel(){return[...this.sortModel]}setFilterModel(e){JSON.stringify(e)!==JSON.stringify(this.filterModel)&&(this.filterModel={...e},this.rebuildFilteredIndices())}getFilterModel(){return{...this.filterModel}}rebuildSortedIndices(){this.sortedIndices=Array.from({length:this.rows.length},(e,t)=>t),this.sortModel.length!==0&&this.sortedIndices.sort((e,t)=>this.compareRows(e,t))}rebuildHashCache(){if(this.rowSortCache.clear(),this.sortModel.length!==0)for(let e=0;e<this.rows.length;e++)this.computeRowHashes(e,this.rows[e])}computeRowHashes(e,t){if(this.sortModel.length===0)return;let n=ze(t,{sortModel:this.sortModel,sortModelHash:this.sortModelHash,getFieldValue:this.options.getFieldValue}),r=this.rowSortCache.get(e);r||(r={hashes:new Map},this.rowSortCache.set(e,r)),r.hashes.set(this.sortModelHash,n)}compareRows(e,t){let n=this.rowSortCache.get(e),r=this.rowSortCache.get(t),i=n?.hashes.get(this.sortModelHash),a=r?.hashes.get(this.sortModelHash),o=Be(i,a,this.sortModel);return o===null?Ve(this.rows[e],this.rows[t],this.sortModel,this.options.getFieldValue):o}binarySearchInsertPosition(e){let t=0,n=this.sortedIndices.length;for(;t<n;){let r=t+n>>>1,i=this.sortedIndices[r];this.compareRows(e,i)>0?t=r+1:n=r}return t}rebuildFilteredIndices(){if(this.filteredIndices.clear(),Object.entries(this.filterModel).some(([,e])=>e!=null))for(let e=0;e<this.rows.length;e++)this.rowPassesFilter(this.rows[e])&&this.filteredIndices.add(e)}rowPassesFilter(e){return rt(e,this.filterModel,this.options.getFieldValue)}getVisibleIndices(){return Object.entries(this.filterModel).some(([,e])=>e!=null)?this.sortedIndices.filter(e=>this.filteredIndices.has(e)):this.sortedIndices}rebuildDistinctValues(){this.distinctValues.clear();for(let e of this.rows)this.updateDistinctValuesForRow(e,`add`)}updateDistinctValuesForRow(e,t){if(!(typeof e!=`object`||!e))for(let[n,r]of Object.entries(e))r!=null&&(t===`add`?this.addToDistinctValues(n,r):this.decrementDistinctValues(n,r))}updateDistinctValueForField(e,t,n){t!=null&&this.decrementDistinctValues(e,t),n!=null&&this.addToDistinctValues(e,n)}addToDistinctValues(e,t){let n=this.distinctValues.get(e);if(n||(n=new Map,this.distinctValues.set(e,n)),Array.isArray(t)){for(let e of t)e!=null&&ct(n,e);return}ct(n,t)}decrementDistinctValues(e,t){let n=this.distinctValues.get(e);if(n!==void 0){if(Array.isArray(t)){for(let e of t)e!=null&<(n,e);return}lt(n,t)}}};const ct=(e,t)=>{e.set(t,(e.get(t)??0)+1)},lt=(e,t)=>{let n=e.get(t);if(n!==void 0){if(n<=1){e.delete(t);return}e.set(t,n-1)}};function ut(e,t){let{getRowId:n,getFieldValue:r,debounceMs:i=50,onTransactionProcessed:a,useWorker:o=!0,parallelSort:s}=t,c=new st({getRowId:n,getFieldValue:r??Z},e),l=new Set,u=v().emit,d=o&&s!==!1?new V(s):null,f=new E({debounceMs:i,store:c,onProcessed:e=>{a?.(e);for(let t of l)t(e)}});return{async fetch(e){if(f.hasPending()){u({type:`DATA_LOADING`});try{await f.flush()}finally{u({type:`DATA_LOADED`,totalRows:c.getTotalRowCount()})}}let t=c.getAllRows(),n=r??Z;if(e.filter&&Object.keys(e.filter).length>0&&(t=it(t,e.filter,n)),e.sort&&e.sort.length>0)if(d&&d.isAvailable()&&t.length>=2e5){u({type:`DATA_LOADING`});try{t=await Xe(t,e.sort,d,n)}finally{u({type:`DATA_LOADED`,totalRows:t.length})}}else t=K(t,e.sort,n);let i=t.length,{pageIndex:a,pageSize:o}=e.pagination,s=a*o;return{rows:t.slice(s,s+o),totalRows:i}},addRows(e){f.add(e)},removeRows(e){f.remove(e)},updateCell(e,t,n){f.updateCell(e,t,n)},updateRow(e,t){f.updateRow(e,t)},async flushTransactions(){await f.flush()},hasPendingTransactions(){return f.hasPending()},getDistinctValues(e){return c.getDistinctValues(e)},getRowById(e){return c.getRowById(e)},getTotalRowCount(){return c.getTotalRowCount()},subscribe(e){return l.add(e),()=>{l.delete(e)}},clear(){let e=c.getTotalRowCount();c.clear();let t={added:0,removed:e,updated:0};a?.(t);for(let e of l)e(t)},moveRow(e,t){c.moveRow(e,t)}}}const dt=`
|
|
330
205
|
/* =============================================================================
|
|
331
206
|
GP Grid - CSS Variables for Theming
|
|
332
207
|
============================================================================= */
|
|
@@ -410,7 +285,7 @@ self.onmessage = function(e) {
|
|
|
410
285
|
--gp-grid-scrollbar-thumb: #373a40;
|
|
411
286
|
--gp-grid-scrollbar-thumb-hover: #4a4d52;
|
|
412
287
|
}
|
|
413
|
-
`,
|
|
288
|
+
`,ft=`
|
|
414
289
|
/* =============================================================================
|
|
415
290
|
GP Grid - Clean Flat Design
|
|
416
291
|
============================================================================= */
|
|
@@ -433,7 +308,7 @@ self.onmessage = function(e) {
|
|
|
433
308
|
outline: none;
|
|
434
309
|
border-color: var(--gp-grid-primary);
|
|
435
310
|
}
|
|
436
|
-
`,
|
|
311
|
+
`,pt=`
|
|
437
312
|
/* =============================================================================
|
|
438
313
|
Header
|
|
439
314
|
============================================================================= */
|
|
@@ -555,7 +430,7 @@ self.onmessage = function(e) {
|
|
|
555
430
|
}
|
|
556
431
|
|
|
557
432
|
/* Touch device: larger tap target for filter icon */
|
|
558
|
-
@media (pointer: coarse) {
|
|
433
|
+
@media (pointer: coarse) and (hover: none) and (max-width: 768px) {
|
|
559
434
|
.gp-grid-filter-icon {
|
|
560
435
|
min-width: 44px;
|
|
561
436
|
min-height: 44px;
|
|
@@ -599,7 +474,7 @@ self.onmessage = function(e) {
|
|
|
599
474
|
}
|
|
600
475
|
|
|
601
476
|
/* Touch device: wider resize handle hit area */
|
|
602
|
-
@media (pointer: coarse) {
|
|
477
|
+
@media (pointer: coarse) and (hover: none) and (max-width: 768px) {
|
|
603
478
|
.gp-grid-header-resize-handle {
|
|
604
479
|
width: 24px;
|
|
605
480
|
right: -12px;
|
|
@@ -654,7 +529,7 @@ self.onmessage = function(e) {
|
|
|
654
529
|
pointer-events: none;
|
|
655
530
|
border-radius: 2px;
|
|
656
531
|
}
|
|
657
|
-
`,
|
|
532
|
+
`,mt=`
|
|
658
533
|
/* =============================================================================
|
|
659
534
|
Data Cells
|
|
660
535
|
============================================================================= */
|
|
@@ -752,7 +627,7 @@ self.onmessage = function(e) {
|
|
|
752
627
|
transform: scale(1.2);
|
|
753
628
|
}
|
|
754
629
|
|
|
755
|
-
@media (pointer: coarse) {
|
|
630
|
+
@media (pointer: coarse) and (hover: none) and (max-width: 768px) {
|
|
756
631
|
.gp-grid-fill-handle {
|
|
757
632
|
width: 24px;
|
|
758
633
|
height: 24px;
|
|
@@ -785,7 +660,7 @@ self.onmessage = function(e) {
|
|
|
785
660
|
.gp-grid-edit-input:focus {
|
|
786
661
|
outline: none;
|
|
787
662
|
}
|
|
788
|
-
`,
|
|
663
|
+
`,ht=`
|
|
789
664
|
/* =============================================================================
|
|
790
665
|
Loading & Error States
|
|
791
666
|
============================================================================= */
|
|
@@ -881,7 +756,7 @@ self.onmessage = function(e) {
|
|
|
881
756
|
font-size: 14px;
|
|
882
757
|
text-align: center;
|
|
883
758
|
}
|
|
884
|
-
`,
|
|
759
|
+
`,gt=`
|
|
885
760
|
/* =============================================================================
|
|
886
761
|
Scrollbar Styling
|
|
887
762
|
============================================================================= */
|
|
@@ -907,7 +782,7 @@ self.onmessage = function(e) {
|
|
|
907
782
|
.gp-grid-container::-webkit-scrollbar-corner {
|
|
908
783
|
background-color: var(--gp-grid-scrollbar-track);
|
|
909
784
|
}
|
|
910
|
-
`,
|
|
785
|
+
`,_t=`
|
|
911
786
|
/* =============================================================================
|
|
912
787
|
Filter Popup
|
|
913
788
|
============================================================================= */
|
|
@@ -1218,7 +1093,7 @@ self.onmessage = function(e) {
|
|
|
1218
1093
|
.gp-grid-filter-btn-apply:hover {
|
|
1219
1094
|
opacity: 0.9;
|
|
1220
1095
|
}
|
|
1221
|
-
`,
|
|
1096
|
+
`,vt=`
|
|
1222
1097
|
/* =============================================================================
|
|
1223
1098
|
Row Drag
|
|
1224
1099
|
============================================================================= */
|
|
@@ -1269,5 +1144,5 @@ self.onmessage = function(e) {
|
|
|
1269
1144
|
pointer-events: none;
|
|
1270
1145
|
border-radius: 2px;
|
|
1271
1146
|
}
|
|
1272
|
-
`,
|
|
1273
|
-
`);let $=!1;function Ie(){if($||typeof document>`u`)return;if(document.getElementById(Pe)){$=!0;return}let e=document.createElement(`style`);e.id=Pe,e.textContent=Fe,document.head.appendChild(e),$=!0}const Le=e=>({slots:new Map,activeCell:null,selectionRange:null,editingCell:null,contentWidth:0,contentHeight:e?.initialHeight??0,viewportWidth:e?.initialWidth??0,viewportHeight:e?.initialHeight??0,rowsWrapperOffset:0,headers:new Map,filterPopup:null,isLoading:!1,error:null,totalRows:0,visibleRowRange:null,hoverPosition:null,columns:null,pendingScrollTop:null}),Re=(e,t,n)=>{switch(e.type){case`CREATE_SLOT`:return t.set(e.slotId,{slotId:e.slotId,rowIndex:-1,rowData:{},translateY:0}),null;case`DESTROY_SLOT`:return t.delete(e.slotId),null;case`ASSIGN_SLOT`:{let n=t.get(e.slotId);return n&&t.set(e.slotId,{...n,rowIndex:e.rowIndex,rowData:e.rowData}),null}case`MOVE_SLOT`:{let n=t.get(e.slotId);return n&&t.set(e.slotId,{...n,translateY:e.translateY}),null}case`SCROLL_TO`:return{pendingScrollTop:e.scrollTop};case`SET_ACTIVE_CELL`:return{activeCell:e.position};case`SET_SELECTION_RANGE`:return{selectionRange:e.range};case`UPDATE_VISIBLE_RANGE`:return{visibleRowRange:{start:e.start,end:e.end},rowsWrapperOffset:e.rowsWrapperOffset};case`SET_HOVER_POSITION`:return{hoverPosition:e.position};case`START_EDIT`:return{editingCell:{row:e.row,col:e.col,initialValue:e.initialValue}};case`STOP_EDIT`:return{editingCell:null};case`SET_CONTENT_SIZE`:return{contentWidth:e.width,contentHeight:e.height,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,rowsWrapperOffset:e.rowsWrapperOffset};case`UPDATE_HEADER`:return n.set(e.colIndex,{column:e.column,sortDirection:e.sortDirection,sortIndex:e.sortIndex,hasFilter:e.hasFilter}),null;case`OPEN_FILTER_POPUP`:return{filterPopup:{isOpen:!0,colIndex:e.colIndex,column:e.column,anchorRect:e.anchorRect,distinctValues:e.distinctValues,currentFilter:e.currentFilter}};case`CLOSE_FILTER_POPUP`:return{filterPopup:null};case`DATA_LOADING`:return{isLoading:!0,error:null};case`DATA_LOADED`:return{isLoading:!1,totalRows:e.totalRows};case`DATA_ERROR`:return{isLoading:!1,error:e.error};case`ROWS_ADDED`:case`ROWS_REMOVED`:return{totalRows:e.totalRows};case`ROWS_UPDATED`:case`TRANSACTION_PROCESSED`:return null;case`COLUMNS_CHANGED`:return{columns:e.columns};default:return null}};export{S as EditManager,x as FillManager,oe as GridCore,ie as HighlightManager,Te as IndexedDataStore,C as InputHandler,I as ParallelSortManager,ae as RowMutationManager,T as ScrollVirtualizationManager,b as SelectionManager,re as SlotPoolManager,E as SortFilterManager,D as TransactionManager,O as WorkerPool,Re as applyInstruction,d as buildCellClasses,e as calculateColumnPositions,te as calculateFillHandlePosition,ne as calculateFilterPopupPosition,n as calculateScaledColumnPositions,ke as cellStyles,R as compareValues,z as computeValueHash,Oe as containerStyles,Se as createClientDataSource,Ce as createDataSourceFromArray,Le as createInitialState,Ee as createMutableClientDataSource,we as createServerDataSource,le as detectBoundaryCollisions,J as evaluateColumnFilter,K as evaluateDateCondition,G as evaluateNumberCondition,W as evaluateTextCondition,Me as filtersStyles,r as findColumnAtX,v as findSlotForRow,y as formatCellValue,m as getFieldValue,t as getTotalWidth,Fe as gridStyles,Q as headerStyles,Ie as injectStyles,s as isCellActive,l as isCellEditing,u as isCellInFillPreview,o as isCellSelected,p as isColumnInSelectionRange,f as isRowInSelectionRange,c as isRowVisible,U as isSameDay,P as kWayMerge,F as kWayMergeMultiColumn,Ne as rowDragStyles,Y as rowPassesFilter,ee as scrollCellIntoView,je as scrollbarStyles,h as setFieldValue,Ae as statesStyles,L as stringToSortableNumber,De as variablesStyles};
|
|
1147
|
+
`,yt=[dt,ft,pt,mt,ht,gt,_t,vt].join(`
|
|
1148
|
+
`),bt=e=>({slots:new Map,activeCell:null,selectionRange:null,editingCell:null,contentWidth:0,contentHeight:e?.initialHeight??0,viewportWidth:e?.initialWidth??0,viewportHeight:e?.initialHeight??0,rowsWrapperOffset:0,headers:new Map,filterPopup:null,isLoading:!1,error:null,totalRows:0,visibleRowRange:null,hoverPosition:null,columns:null,pendingScrollTop:null}),xt=(e,t,n)=>{switch(e.type){case`CREATE_SLOT`:return t.set(e.slotId,{slotId:e.slotId,rowIndex:-1,rowData:{},translateY:0}),null;case`DESTROY_SLOT`:return t.delete(e.slotId),null;case`ASSIGN_SLOT`:{let n=t.get(e.slotId);return n&&t.set(e.slotId,{...n,rowIndex:e.rowIndex,rowData:e.rowData}),null}case`MOVE_SLOT`:{let n=t.get(e.slotId);return n&&t.set(e.slotId,{...n,translateY:e.translateY}),null}case`SCROLL_TO`:return{pendingScrollTop:e.scrollTop};case`SET_ACTIVE_CELL`:return{activeCell:e.position};case`SET_SELECTION_RANGE`:return{selectionRange:e.range};case`UPDATE_VISIBLE_RANGE`:return{visibleRowRange:{start:e.start,end:e.end},rowsWrapperOffset:e.rowsWrapperOffset};case`SET_HOVER_POSITION`:return{hoverPosition:e.position};case`START_EDIT`:return{editingCell:{row:e.row,col:e.col,initialValue:e.initialValue}};case`STOP_EDIT`:return{editingCell:null};case`SET_CONTENT_SIZE`:return{contentWidth:e.width,contentHeight:e.height,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,rowsWrapperOffset:e.rowsWrapperOffset};case`UPDATE_HEADER`:return n.set(e.colIndex,{column:e.column,sortDirection:e.sortDirection,sortIndex:e.sortIndex,hasFilter:e.hasFilter}),null;case`OPEN_FILTER_POPUP`:return{filterPopup:{isOpen:!0,colIndex:e.colIndex,column:e.column,anchorRect:e.anchorRect,distinctValues:e.distinctValues,currentFilter:e.currentFilter}};case`CLOSE_FILTER_POPUP`:return{filterPopup:null};case`DATA_LOADING`:return{isLoading:!0,error:null};case`DATA_LOADED`:return{isLoading:!1,totalRows:e.totalRows};case`DATA_ERROR`:return{isLoading:!1,error:e.error};case`ROWS_ADDED`:case`ROWS_REMOVED`:return{totalRows:e.totalRows};case`ROWS_UPDATED`:case`TRANSACTION_PROCESSED`:return null;case`COLUMNS_CHANGED`:return{columns:e.columns};default:return null}},$=e=>({clientX:e.clientX,clientY:e.clientY,button:e.button,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,pointerId:e.pointerId,pointerType:e.pointerType});var St=class{intervalId=null;lastPointerEvent=null;getBodyEl;onTick;constructor(e,t){this.getBodyEl=e,this.onTick=t}recordPointer(e){this.lastPointerEvent=e}clearPointer(){this.lastPointerEvent=null}start(e,t){this.stop(),this.intervalId=setInterval(()=>{let n=this.getBodyEl();if(!n)return;n.scrollTop+=t,n.scrollLeft+=e;let r=this.lastPointerEvent;r&&this.onTick(r)},16)}stop(){this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null)}},Ct=class{timer=null;capture=null;savedContainerOverflow=null;blockTouchMove=e=>e.preventDefault();deps;constructor(e){this.deps=e}start(e){this.cancel(),this.capture={pointerId:e.pointerId,target:e.currentTarget};let t=e.clientX,n=e.clientY,r=e=>{let r=e.clientX-t,i=e.clientY-n;(Math.abs(r)>10||Math.abs(i)>10)&&(this.cancel(),a())},i=()=>{this.cancel(),a()},a=()=>{document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i),document.removeEventListener(`pointercancel`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i,{once:!0}),document.addEventListener(`pointercancel`,i,{once:!0}),this.timer=setTimeout(()=>{this.timer=null,a(),this.confirm()},300)}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.deps.getCore()?.input.cancelPendingRowDrag(),this.capture=null}releaseLocks(){if(!this.deps.isBrowser)return;let e=this.deps.getContainer();this.savedContainerOverflow!==null&&e&&(e.style.overflow=this.savedContainerOverflow),this.savedContainerOverflow=null,document.removeEventListener(`touchmove`,this.blockTouchMove)}confirm(){let e=this.deps.getCore(),t=this.capture;this.capture=null,e!==null&&e.input.confirmPendingRowDrag()&&(this.lockContainer(),document.addEventListener(`touchmove`,this.blockTouchMove,{passive:!1}),this.applyPointerCapture(t),this.deps.onDragConfirmed(e.input.getDragState()))}lockContainer(){let e=this.deps.getContainer();e&&(this.savedContainerOverflow=e.style.overflow,e.style.overflow=`hidden`)}applyPointerCapture(e){e&&e.target.setPointerCapture(e.pointerId)}};const wt=(e,t,n,r)=>{let i={slots:new Map(t),headers:new Map(n)};for(let t of e){let e=xt(t,i.slots,i.headers);e!==null&&Tt(e,i,r)}return i},Tt=(e,t,n)=>{e.slots!==void 0&&Dt(t.slots,e.slots),e.headers!==void 0&&Dt(t.headers,e.headers),Et(e,n),e.columns!==void 0&&e.columns!==null&&n.setColumnsOverride(e.columns),e.filterPopup!==void 0&&n.onFilterPopupChange(e.filterPopup)},Et=(e,t)=>{e.contentWidth!==void 0&&t.setContentWidth(e.contentWidth),e.contentHeight!==void 0&&t.setContentHeight(e.contentHeight),e.rowsWrapperOffset!==void 0&&t.setRowsWrapperOffset(e.rowsWrapperOffset),e.isLoading!==void 0&&t.setIsLoading(e.isLoading),e.error!==void 0&&t.setErrorMessage(e.error),e.pendingScrollTop!==void 0&&t.setPendingScrollTop(e.pendingScrollTop),e.activeCell!==void 0&&t.setActiveCell(e.activeCell),e.selectionRange!==void 0&&t.setSelectionRange(e.selectionRange),e.editingCell!==void 0&&t.setEditingCell(e.editingCell),e.hoverPosition!==void 0&&t.setHoverPosition(e.hoverPosition)},Dt=(e,t)=>{e.clear(),t.forEach((t,n)=>e.set(n,t))};var Ot=class{owned=null;lastAppliedRows=null;lastAppliedColumns=null;initialize(e,t){return e===null?(this.owned=Q(t),this.lastAppliedRows=t,this.owned):e}syncRows(e,t){return t!==null||this.lastAppliedRows===e?null:(this.lastAppliedRows=e,e.length>1e4&&console.warn(`[gp-grid] rows input changed with ${e.length} rows — this triggers a full rebuild. Use createGridData() for efficient updates.`),this.owned?.destroy?.(),this.owned=Q(e),this.owned)}syncColumns(e){return e.length===0||this.lastAppliedColumns===e?!1:(this.lastAppliedColumns=e,!0)}destroy(){this.owned?.destroy?.(),this.owned=null}},kt=class{deps;constructor(e){this.deps=e}headerPointerDown(e,t,n,r){let i=this.deps.getCore();return i===null?!1:i.input.handleHeaderMouseDown(e,t,n,$(r)).preventDefault}resizePointerDown(e,t,n){let r=this.deps.getCore();return r===null?!1:r.input.handleHeaderResizeMouseDown(e,t,$(n)).preventDefault}cellPointerDown(e,t,n){let r=this.deps.getCore();if(r===null)return{preventDefault:!1,focusContainer:!1};let i=r.input.handleCellMouseDown(e,t,$(n));return this.dispatchCellDragStart(i.startDrag,n),{preventDefault:i.preventDefault,focusContainer:i.focusContainer??!1}}cellPointerEnter(e,t){this.deps.getCore()?.input.handleCellMouseEnter(e,t)}cellPointerLeave(){this.deps.getCore()?.input.handleCellMouseLeave()}fillHandlePointerDown(e,t,n){let r=this.deps.getCore();if(r===null)return{preventDefault:!1,stopPropagation:!1};let i=r.input.handleFillHandleMouseDown(e,t,$(n));return i.startDrag===`fill`&&(At(n),this.deps.onDragStateChange(r.input.getDragState())),{preventDefault:i.preventDefault,stopPropagation:i.stopPropagation}}dragMove(e){let t=this.deps.getCore(),n=this.deps.getBodyEl();if(t===null||n===null)return;let r=n.getBoundingClientRect(),i=t.input.handleDragMove($(e),{top:r.top,left:r.left,width:r.width,height:r.height,scrollTop:n.scrollTop,scrollLeft:n.scrollLeft});this.deps.onDragStateChange(t.input.getDragState()),i?.autoScroll?this.deps.autoScroll.start(i.autoScroll.dx,i.autoScroll.dy):this.deps.autoScroll.stop()}documentPointerMove(e){let t=this.deps.getCore();if(t===null)return!1;let n=t.input.getDragState().isDragging;return this.deps.autoScroll.recordPointer(e),this.dragMove(e),n}documentPointerUp(){let e=this.deps.getCore();if(e===null)return{wasRowDrag:!1};let t=e.input.getDragState().dragType===`row-drag`;return this.deps.autoScroll.stop(),this.deps.autoScroll.clearPointer(),e.input.handleDragEnd(),this.deps.onDragStateChange(e.input.getDragState()),{wasRowDrag:t}}wheel(e,t,n){let r=this.deps.getCore();return r===null?null:r.input.handleWheel(e,t,n)}keyDown(e,t,n,r){let i=this.deps.getCore();return i===null?{preventDefault:!1}:i.input.handleKeyDown({key:e.key,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey},t,n,r)}dispatchCellDragStart(e,t){let n=this.deps.getCore();if(!(n===null||e===void 0)){if(e===`selection`){n.input.startSelectionDrag(),this.deps.onDragStateChange(n.input.getDragState());return}if(e===`row-drag`){this.deps.onDragStateChange(n.input.getDragState());return}e===`row-drag-pending`&&this.deps.pendingRowDrag.start(t)}}};const At=e=>{e.target.setPointerCapture(e.pointerId)};export{St as AutoScrollDriver,Ot as DataSourceOwner,A as EditManager,O as FillManager,Ae as GridCore,w as HighlightManager,st as IndexedDataStore,kt as InputEventAdapter,C as InputHandler,V as ParallelSortManager,Ct as PendingRowDragController,T as RowMutationManager,ve as ScrollVirtualizationManager,D as SelectionManager,k as SlotPoolManager,ye as SortFilterManager,E as TransactionManager,M as WorkerPool,wt as applyBatchInstructions,xt as applyInstruction,p as buildCellClasses,n as calculateColumnPositions,ne as calculateFillHandlePosition,re as calculateFilterPopupPosition,i as calculateScaledColumnPositions,mt as cellStyles,U as compareValues,W as computeValueHash,ft as containerStyles,at as createClientDataSource,Q as createDataSourceFromArray,bt as createInitialState,ut as createMutableClientDataSource,ot as createServerDataSource,Ne as detectBoundaryCollisions,X as evaluateColumnFilter,tt as evaluateDateCondition,Y as evaluateNumberCondition,J as evaluateTextCondition,_t as filtersStyles,a as findColumnAtX,y as findSlotForRow,b as formatCellValue,g as getFieldValue,r as getTotalWidth,yt as gridStyles,pt as headerStyles,l as isCellActive,d as isCellEditing,f as isCellInFillPreview,c as isCellSelected,h as isColumnInSelectionRange,m as isRowInSelectionRange,u as isRowVisible,q as isSameDay,R as kWayMerge,z as kWayMergeMultiColumn,vt as rowDragStyles,rt as rowPassesFilter,te as scrollCellIntoView,gt as scrollbarStyles,_ as setFieldValue,ht as statesStyles,H as stringToSortableNumber,$ as toPointerEventData,dt as variablesStyles};
|