@toolbox-web/grid 3.5.1 → 3.5.3

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.
Files changed (36) hide show
  1. package/README.md +17 -17
  2. package/all.js +1 -1
  3. package/all.js.map +1 -1
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/features/registry.js +1 -1
  7. package/lib/plugins/clipboard/index.js +1 -1
  8. package/lib/plugins/column-virtualization/index.js +1 -1
  9. package/lib/plugins/context-menu/index.js +1 -1
  10. package/lib/plugins/editing/index.js +1 -1
  11. package/lib/plugins/export/index.js +1 -1
  12. package/lib/plugins/filtering/index.js +1 -1
  13. package/lib/plugins/grouping-columns/index.js +1 -1
  14. package/lib/plugins/grouping-rows/index.js +1 -1
  15. package/lib/plugins/master-detail/index.js +1 -1
  16. package/lib/plugins/multi-sort/index.js +1 -1
  17. package/lib/plugins/pinned-columns/index.js +1 -1
  18. package/lib/plugins/pinned-rows/index.js +1 -1
  19. package/lib/plugins/pivot/index.js +1 -1
  20. package/lib/plugins/print/index.js +1 -1
  21. package/lib/plugins/reorder-columns/index.js +1 -1
  22. package/lib/plugins/responsive/index.js +1 -1
  23. package/lib/plugins/row-drag-drop/index.js +1 -1
  24. package/lib/plugins/selection/index.js +1 -1
  25. package/lib/plugins/server-side/index.js +1 -1
  26. package/lib/plugins/shell/index.js +1 -1
  27. package/lib/plugins/sticky-rows/index.js +1 -1
  28. package/lib/plugins/tooltip/index.js +1 -1
  29. package/lib/plugins/tree/index.js +1 -1
  30. package/lib/plugins/undo-redo/index.js +1 -1
  31. package/lib/plugins/visibility/index.js +1 -1
  32. package/package.json +1 -1
  33. package/umd/grid.all.umd.js +1 -1
  34. package/umd/grid.all.umd.js.map +1 -1
  35. package/umd/grid.umd.js +1 -1
  36. package/umd/grid.umd.js.map +1 -1
@@ -1,2 +1,2 @@
1
- var e="editing",t="dragging",r=/* @__PURE__ */new Map;function o(e){const t=r.get(e);if(!t)return;if(t.hasPrimitives)return;const o=[];for(const r of t.refs){const e=r.deref();if(void 0===e)return;o.push(e)}return o}function i(e){r.delete(e)}function n(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const e=/* @__PURE__ */new Uint32Array(2);return crypto.getRandomValues(e),`drag-${Date.now().toString(36)}-${e[0].toString(36)}${e[1].toString(36)}`}return`drag-${Date.now().toString(36)}-${(++s).toString(36)}`}var s=0;function a(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,o=t.rawContentHeight-t.viewportHeight;return r<=0||o<=0?e:e*r/o}function d(t,r){!function(e){if(!e._virtualization?.enabled)return;const{rowHeight:t,container:r,viewportEl:o,scrollMapping:i}=e._virtualization,n=r,s=o?.clientHeight??n?.clientHeight??0;if(!n||s<=0)return;const d=e._focusRow*t,c=i?function(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,o=t.rawContentHeight-t.viewportHeight;if(r<=0||o<=0)return e;const i=e*o/r;return i<0?0:i>o?o:i}(n.scrollTop,i):n.scrollTop;if(d<c)n.scrollTop=i?a(d,i):d;else if(d+t>c+s){const e=d-s+t;n.scrollTop=i?a(e,i):e}}(t);const o=function(e){return void 0!==e._activeEditRows&&-1!==e._activeEditRows}(t)||!!t._isGridEditMode;var i;o||t.refreshVirtualWindow(!1),(i=t._bodyEl)&&i.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus")),Array.from(t._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const n=function(e){const t=e._focusRow,r=e._virtualization.start??0,o=e._virtualization.end??e._rows.length;if(t<r||t>=o)return;const i=e._bodyEl.querySelectorAll(".data-grid-row")[t-r];let n=i?.children[e._focusCol];return n&&n.classList?.contains("cell")||(n=i?.querySelector(`.cell[data-col="${e._focusCol}"]`)??i?.querySelector(".cell[data-col]")),n?{rowEl:i??null,cell:n}:void 0}(t);if(!n)return;const{rowEl:s,cell:d}=n;d.classList.add("cell-focus"),d.setAttribute("aria-selected","true"),o&&!r?.forceHorizontalScroll||function(e,t,r,o){const i=e.querySelector(".tbw-scroll-area");if(!i)return;if(o?.forceScrollLeft)return void(i.scrollLeft=0);if(o?.forceScrollRight)return void(i.scrollLeft=i.scrollWidth-i.clientWidth);const n=e._getHorizontalScrollOffsets?.(t??void 0,r)??{left:0,right:0};if(n.skipScroll)return;const s=r.getBoundingClientRect(),a=i.getBoundingClientRect(),d=s.left-a.left+i.scrollLeft,c=d+s.width,l=i.scrollLeft+n.left,g=i.scrollLeft+i.clientWidth-n.right;d<l?i.scrollLeft=d-n.left:c>g&&(i.scrollLeft=c-i.clientWidth+n.right)}(t,s,d,r),function(t,r,o){if(o&&r.classList.contains(e)){const e=r.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}return}if(o){if(r.contains(document.activeElement))return;r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1");try{r.focus({preventScroll:!0})}catch{}return}const i=document.activeElement;i instanceof HTMLElement&&i!==t&&"function"==typeof t.contains&&t.contains(i)&&!i.classList.contains("cell")&&!i.closest(".cell")||i===t||t.focus({preventScroll:!0})}(t,d,o)}function c(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function l(e,t,r,o){return`${c(r,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}var g="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join("")),u=(new RegExp(`__(proto|defineGetter|defineSetter)|${g.slice(3).join("|")}|this\\b`),new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math".split("|"))),f=/^on\w+$/i,h=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),p=/^\s*(javascript|vbscript|data|blob):/i;function w(e){const t=document.createElement("template");return e&&"string"==typeof e&&(t.innerHTML=e,function(e){const t=[],r=e.querySelectorAll("*");for(const o of r){const e=o.tagName.toLowerCase();if(u.has(e)){t.push(o);continue}if(("svg"===e||"http://www.w3.org/2000/svg"===o.namespaceURI)&&Array.from(o.attributes).some(e=>f.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(o);continue}const r=[];for(const t of o.attributes){const e=t.name.toLowerCase();f.test(e)?r.push(t.name):"is"!==e?(h.has(e)&&p.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name):r.push(t.name)}r.forEach(e=>o.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content)),t.content}var m={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};var b=class{static dependencies;static manifest;aliases;version="3.5.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},r={};for(const o of Object.keys(t))r[o]=this;for(const o of e){const e=o.userConfig;for(const[i,n]of Object.entries(e)){if(void 0===n)continue;if(!(i in t)){t[i]=n,r[i]=o;continue}if(t[i]===n)continue;const e=r[i]?.constructor.name??this.constructor.name,s=o.constructor.name,a=l("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${i}" supplied by both ${e} and ${s}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,r={...e.userConfig};for(const o of Object.keys(t))delete t[o];Object.assign(t,r)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}queryBoolean(e,t=null){const r=this.grid?.query?.(e,t);return Array.isArray(r)?r.some(Boolean):!!r}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...m,...e}}t(e,t){return this.grid?.effectiveConfig?.locale?.[e]??t}get translate(){return(e,t)=>this.t(e,t)}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;return!t||"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(t,10);if(!isNaN(r))return r}return 200}setIcon(e,t,r){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const o=this.#t(t,r);var i,n;void 0!==o?"string"==typeof o?(i=e,(n=o)&&"string"==typeof n?-1!==n.indexOf("<")||-1!==n.indexOf("&")?i.replaceChildren(w(n)):i.textContent=n:i.replaceChildren()):o instanceof HTMLElement&&e.replaceChildren(o.cloneNode(!0)):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const r=document.createElement("span");r.setAttribute("part","sort-indicator"),r.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(r,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(r,"sortNone"));const o=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return o?e.insertBefore(r,o):e.appendChild(r),r}warn(e,t){void 0!==t?console.warn(l(e,t,this.gridElement.id,this.name)):console.warn(`${c(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(l(e,t,this.gridElement.id,this.name))}},v=null;function y(){return v}function I(){v=null}var x="application/x-tbw-grid-rows+json";function R(e){const t=e.match(/^application\/x-tbw-grid-rows\+json;zone=(.*)$/);if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}}function C(e){return JSON.stringify(e)}function D(e,t,r,o){if(!e)return{overIndex:null,insertIndex:o,isBefore:!1};const i=r(e);if(i<0)return{overIndex:null,insertIndex:o,isBefore:!1};const n=e.getBoundingClientRect(),s=t<n.top+n.height/2;return{overIndex:i,insertIndex:s?i:i+1,isBefore:s}}var E="__tbw_row_drag",S=null,A=/* @__PURE__ */new Set;function _(){if("undefined"==typeof BroadcastChannel)return null;if(S)return S;try{(S=new BroadcastChannel("tbw-row-drag-drop")).addEventListener("message",e=>{const t=e.data;if(t&&"tbw-row-drag-drop:transfer"===t.type)for(const r of Array.from(A))try{r(t)}catch{}})}catch{S=null}return S}var L=class e extends b{name="rowDragDrop";styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{justify-content:center;align-items:center;display:flex}.dg-row-drag-handle{cursor:grab;-webkit-user-select:none;user-select:none;min-width:1em;min-height:1em;color:var(--tbw-row-reorder-handle-color,var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration,.12s) var(--tbw-transition-ease,ease);font-size:var(--tbw-font-size,1em);letter-spacing:-2px;justify-content:center;align-items:center;display:flex}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover,var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}@media (hover:none){.dg-row-drag-handle{color:var(--tbw-row-reorder-handle-hover,var(--tbw-color-fg))}}@media (pointer:coarse){.dg-row-drag-handle{min-width:var(--tbw-touch-target-min,24px);min-height:var(--tbw-touch-target-min,24px)}}.data-grid-row.dragging{opacity:.6}.data-grid-row[draggable=true]{cursor:grab}.data-grid-row[draggable=true].dragging{cursor:grabbing}.tbw-row-drag-clone{pointer-events:none;position:fixed;top:-10000px;left:-10000px}.tbw-row-drag-count{pointer-events:none;background:var(--tbw-row-reorder-indicator,var(--tbw-color-accent));color:var(--tbw-color-accent-fg);box-shadow:0 2px 6px var(--tbw-color-shadow);z-index:9999;border-radius:999px;padding:2px 8px;font:600 12px/1.4 system-ui,sans-serif;position:fixed;top:-1000px;left:-1000px}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before,.data-grid-row.drop-target.drop-after:after{content:"";height:var(--tbw-drop-indicator-width,2px);background-color:var(--tbw-drop-indicator-color,var(--tbw-row-reorder-indicator,var(--tbw-color-accent)));z-index:10;pointer-events:none;position:absolute;left:0;right:0}.data-grid-row.drop-target.drop-before:before{top:0}.data-grid-row.drop-target.drop-after:after{bottom:0}.tbw-grid--drop-target-active{outline:2px dashed var(--tbw-drop-indicator-color,var(--tbw-color-accent));outline-offset:-2px}.tbw-grid--drop-target-rejected{outline:2px dashed var(--tbw-color-danger);outline-offset:-2px}.tbw-grid--auto-scrolling{cursor:ns-resize}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration,.2s) ease-out;will-change:transform;z-index:1}}';static manifest={events:[{type:"row-move",description:"Intra-grid row reorder.",cancelable:!0},{type:"row-drag-start",description:"Cross-grid drag started on this grid.",cancelable:!0},{type:"row-drag-end",description:"Drag finished on this grid (regardless of outcome)."},{type:"row-drop",description:"Cross-grid drop landing on this grid.",cancelable:!0},{type:"row-transfer",description:"Cross-grid transfer completed (fires on both grids)."}]};get defaultConfig(){return{enableKeyboard:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip",operation:"move",autoScroll:!0,dragFrom:"handle"}}shouldRenderDragHandle(){const e=this.config.showDragHandle;return!1!==e&&(!0===e||"row"!==this.config.dragFrom)}get rowIsDraggable(){return"row"===this.config.dragFrom||"both"===this.config.dragFrom}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;draggedRows=[];draggedIndices=[];dragSessionId=null;dragAccepted=!1;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;autoScroller=null;gridId="";remoteTransferListener=e=>this.onRemoteTransfer(e);get internalGrid(){return this.grid}attach(e){super.attach(e);const t=this.gridElement;var r;t&&(this.gridId=t.id||`tbw-grid-${n().slice(0,8)}`,t.id||(t.id=this.gridId),this.setupDelegatedDragListeners(),r=this.remoteTransferListener,A.add(r),_())}detach(){this.clearDebounceTimer(),this.autoScroller?.stop(),this.autoScroller=null,function(e){if(A.delete(e),0===A.size&&S){try{S.close()}catch{}S=null}}(this.remoteTransferListener),this.dragSessionId&&i(this.dragSessionId),I(),this.resetDragState(),super.detach()}processColumns(e){if(!this.shouldRenderDragHandle())return[...e];const t={field:E,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,lockPosition:!0,utility:!0,viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,"dragHandle"),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){this.applyRowDraggable()}onScrollRender(){this.applyRowDraggable()}applyRowDraggable(){const e=this.internalGrid._bodyEl;if(!e)return;const t=this.rowIsDraggable,r=e.querySelectorAll(".data-grid-row");for(const o of r)t?"true"!==o.getAttribute("draggable")&&o.setAttribute("draggable","true"):o.hasAttribute("draggable")&&o.removeAttribute("draggable")}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.internalGrid,r=t._focusRow,o=t._rows??this.sourceRows;if(r<0||r>=o.length)return;const i="up"==("ArrowUp"===e.key?"up":"down")?r-1:r+1;if(i<0||i>=o.length)return;const n=o[r];return this.canMoveRow(r,i)?(this.handleKeyboardMove(n,r,i,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const r=[...this.sourceRows];e<0||e>=r.length||t<0||t>=r.length||e!==t&&this.canMoveRow(e,t)&&this.executeIntraGridMove(r[e],e,t,"keyboard")}canMoveRow(e,t){const r=this.internalGrid._rows??this.sourceRows;if(e<0||e>=r.length)return!1;if(t<0||t>=r.length)return!1;if(e===t)return!1;const o=r[e],i=this.grid?.query?.("canMoveRow",o);if(Array.isArray(i)&&i.includes(!1))return!1;if(this.config.canDrag&&!this.config.canDrag(o,e))return!1;if(this.config.canDrop){const r={sessionId:"intra",sourceGridId:this.gridId,dropZone:this.config.dropZone??"",rows:[o],rowIndices:[e],operation:"move"};if(!this.config.canDrop(r,t))return!1}return!0}setupDelegatedDragListeners(){const e=this.gridElement;if(!e)return;const t=this.disconnectSignal;e.addEventListener("dragstart",e=>this.onDragStart(e),{signal:t}),e.addEventListener("dragend",()=>this.onDragEnd(),{signal:t}),e.addEventListener("dragover",e=>this.onDragOver(e),{signal:t}),e.addEventListener("dragleave",e=>this.onDragLeave(e),{signal:t}),e.addEventListener("drop",e=>this.onDrop(e),{signal:t})}onDragStart(e){const o=e.target;if(!o)return;const i=o.closest(".dg-row-drag-handle");let s=null,a=!1;if(i)s=i.closest(".data-grid-row"),a=!0;else if(this.rowIsDraggable){if(this.isInteractiveDragOrigin(o))return;s=o.closest(".data-grid-row")}if(!s)return;const d=this.getRowIndex(s);if(d<0)return;const{rows:c,indices:l}=this.resolveDraggedRows(d);if(0===c.length)return;if(this.config.canDrag&&!this.config.canDrag(c[0],d))return void e.preventDefault();const g=this.config.operation??"move",u=this.config.dropZone??"",f=n(),h={rows:c,indices:l,operation:g,dropZone:u};if(this.emitCancelable("row-drag-start",h))return void e.preventDefault();this.isDragging=!0,this.draggedRowIndex=d,this.draggedRows=c,this.draggedIndices=l,this.dragSessionId=f,this.dragAccepted=!1;const p=this.config.serializeRow??(e=>e),w={sessionId:f,sourceGridId:this.gridId,dropZone:u,rows:c.map(p),rowIndices:l,operation:g};if(e.dataTransfer){e.dataTransfer.effectAllowed="copy"===g?"copyMove":"move";try{e.dataTransfer.setData(x,C(w)),u&&e.dataTransfer.setData(`${x};zone=${encodeURIComponent(u)}`,C(w)),e.dataTransfer.setData("text/plain",function(e,t){const r=t.filter(e=>!e.utility&&"string"==typeof e.field&&""!==e.field),o=[];for(const i of e){const e=r.map(e=>{const t=i[e.field];return null==t?"":String(t).replace(/[\t\r\n]+/g," ")});o.push(e.join("\t"))}return o.join("\n")}(c,this.columns))}catch{}if(c.length>1){const t=document.createElement("div");t.className="tbw-row-drag-count",t.textContent=`${c.length} rows`,document.body.appendChild(t);try{e.dataTransfer.setDragImage(t,10,10)}catch{}setTimeout(()=>t.remove(),0)}else this.attachRowCloneDragImage(e,s,a?i:null)}!function(e,t){const o=[];let i=!1;for(const r of t)null!==r&&"object"==typeof r?o.push(new WeakRef(r)):i=!0;r.set(e,{refs:o,hasPrimitives:i})}(f,c),function(e,t){v={sessionId:e,payload:t}}(f,w),s.classList.add(t),this.gridElement.classList.add("tbw-grid--drag-source")}static INTERACTIVE_DRAG_SELECTORS='input,textarea,select,button,a,[contenteditable=""],[contenteditable="true"],.dg-cell-editor,.tbw-checkbox-cell';isInteractiveDragOrigin(t){return null!==t.closest(e.INTERACTIVE_DRAG_SELECTORS)}attachRowCloneDragImage(e,t,r){if(!e.dataTransfer)return;const o=t.getBoundingClientRect(),i=t.cloneNode(!0);i.classList.add("tbw-row-drag-clone"),i.classList.remove("dragging","drop-target","drop-before","drop-after","flip-animating","row-focus"),i.removeAttribute("aria-selected"),i.style.width=`${o.width}px`,i.style.height=`${o.height}px`,this.gridElement.appendChild(i);let n=e.clientX-o.left,s=e.clientY-o.top;if(r){const e=r.getBoundingClientRect();n=e.left-o.left+e.width/2,s=e.top-o.top+e.height/2}n=Math.max(0,Math.min(o.width,n)),s=Math.max(0,Math.min(o.height,s));try{e.dataTransfer.setDragImage(i,n,s)}catch{}setTimeout(()=>i.remove(),0)}onDragOver(e){const t=e.dataTransfer;if(!t)return;const r=t.types?Array.from(t.types):[];if(!function(e){for(const t of e)if("application/x-tbw-grid-rows+json"===t||t.startsWith("application/x-tbw-grid-rows+json;"))return!0;return!1}(r)&&!this.isDragging)return;const o=this.config.dropZone??"",i=y(),n=this.isDragging&&i?.payload.sourceGridId===this.gridId;if(!n){if(!o)return;if(!(function(e,t){for(const r of e)if(R(r)===t)return r;return null}(r,o)||i&&i.payload.dropZone===o))return}e.preventDefault(),t&&(t.dropEffect=i?.payload.operation??this.config.operation??"move");const s=e.target.closest(".data-grid-row"),a=this.internalGrid._rows??[],d=D(s,e.clientY,e=>this.getRowIndex(e),a.length);if(n&&null!==d.overIndex&&d.overIndex===this.draggedRowIndex)this.clearDropTargetClasses();else{if(i&&this.config.canDrop){const e=this.config.canDrop(i.payload,d.insertIndex);if(this.gridElement.classList.toggle("tbw-grid--drop-target-active",e),this.gridElement.classList.toggle("tbw-grid--drop-target-rejected",!e),!e)return void this.clearDropTargetClasses()}else this.gridElement.classList.add("tbw-grid--drop-target-active");this.dropRowIndex=d.insertIndex,this.applyDropPositionClasses(s,d.isBefore),!1!==this.config.autoScroll&&(this.ensureAutoScroller(),this.autoScroller?.onPointerMove(e.clientY))}}onDragLeave(e){const t=e.target.closest(".data-grid-row");t&&t.classList.remove("drop-target","drop-before","drop-after"),e.currentTarget&&!this.gridElement.contains(e.relatedTarget)&&(this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.autoScroller?.stop())}onDrop(e){e.preventDefault(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.clearDropTargetClasses();const t=e.dataTransfer;if(!t)return;let r=y()?.payload??null,i=null;if(r){const e=o(r.sessionId);e&&(i=e)}else if(r=function(e){if(!e)return null;try{const t=JSON.parse(e);if("string"!=typeof t?.sessionId||"string"!=typeof t?.sourceGridId||"string"!=typeof t?.dropZone||!Array.isArray(t?.rows)||!Array.isArray(t?.rowIndices)||"move"!==t.operation&&"copy"!==t.operation)return null;for(const e of t.rowIndices)if("number"!=typeof e||!Number.isInteger(e)||e<0)return null;return t}catch{return null}}(t.getData(x)),r){const e=o(r.sessionId);e&&(i=e)}if(!r)return;const n=e.target.closest(".data-grid-row"),s=this.internalGrid._rows??[],a=D(n,e.clientY,e=>this.getRowIndex(e),s.length);let d=this.dropRowIndex??a.insertIndex;const c=r.sourceGridId===this.gridId,l=this.config.dropZone??"";if(c){const e=r.rowIndices[0];if(1===r.rowIndices.length&&d>e&&d--,e===d)return;const t=(i??r.rows)[0];if(!this.canMoveRow(e,d))return;return void this.executeIntraGridMove(t,e,d,"drag")}if(!l||l!==r.dropZone)return;if(this.config.canDrop&&!this.config.canDrop(r,d))return this.gridElement.classList.add("tbw-grid--drop-target-rejected"),void setTimeout(()=>this.gridElement.classList.remove("tbw-grid--drop-target-rejected"),200);const g=this.config.deserializeRow??(e=>e),u=i??r.rows.map(e=>g(e)),f={payload:r,sourceGridId:r.sourceGridId,targetIndex:d,operation:r.operation};if(this.emitCancelable("row-drop",f))return;const h=[...s];h.splice(d,0,...u),this.grid.rows=h;const p=this.findPeerOnGrid(r.sourceGridId);if("move"===r.operation&&p){const e=document.getElementById(r.sourceGridId);if(e){const t=(e._rows??e.rows??[]).slice(),o=[...r.rowIndices].sort((e,t)=>t-e);for(const e of o)e>=0&&e<t.length&&t.splice(e,1);e.rows=t}}p&&(p.dragAccepted=!0);const w={rows:u,fromGridId:r.sourceGridId,toGridId:this.gridId,fromIndices:r.rowIndices,toIndex:d,operation:r.operation};this.emit("row-transfer",w),p?p.emitTransfer(w):function(e){const t=_();if(t)try{t.postMessage(e)}catch{}}({type:"tbw-row-drag-drop:transfer",sessionId:r.sessionId,sourceGridId:r.sourceGridId,toGridId:this.gridId,dropZone:l,rowIndices:r.rowIndices,toIndex:d,operation:r.operation,serializedRows:r.rows})}onRemoteTransfer(e){if(e.sourceGridId!==this.gridId)return;const t=this.config.dropZone??"";if(!t||e.dropZone!==t)return;const r=this.config.deserializeRow??(e=>e),o=e.serializedRows.map(e=>r(e));if("move"===e.operation){const t=(this.internalGrid._rows??this.sourceRows).slice(),r=[...e.rowIndices].sort((e,t)=>t-e);for(const e of r)e>=0&&e<t.length&&t.splice(e,1);this.grid.rows=t}this.dragAccepted=!0,this.emit("row-transfer",{rows:o,fromGridId:e.sourceGridId,toGridId:e.toGridId,fromIndices:e.rowIndices,toIndex:e.toIndex,operation:e.operation})}onDragEnd(){if(this.dragSessionId&&i(this.dragSessionId),I(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drag-source"),this.isDragging){const e={rows:this.draggedRows,indices:this.draggedIndices,accepted:this.dragAccepted};this.emit("row-drag-end",e)}this.clearDragClasses(),this.resetDragState()}emitTransfer(e){this.emit("row-transfer",e)}findPeerOnGrid(e){const t=document.getElementById(e);return t?.getPluginByName?t.getPluginByName("rowDragDrop")??null:null}resolveDraggedRows(e){const t=this.internalGrid._rows??this.sourceRows,r=t[e],o=this.grid?.getPluginByName?.("selection");if(o?.getSelectedRowIndices){const r=o.getSelectedRowIndices();if(r.includes(e)&&r.length>1){const e=[...r].sort((e,t)=>e-t);return{rows:e.map(e=>t[e]),indices:e}}}return{rows:[r],indices:[e]}}ensureAutoScroller(){if(this.autoScroller)return;const e=this.gridElement.querySelector(".rows-viewport");if(!e)return;const t="object"==typeof this.config.autoScroll?this.config.autoScroll:void 0;this.autoScroller=function(e,t={},r){const o=t.edgeSize??60,i=t.speed??8,n=t.maxSpeed??24;let s=null,a=null,d=!1;const c=e=>{e!==d&&(d=e,r?.(e))},l=()=>{if(s=null,null===a)return void c(!1);const t=e.getBoundingClientRect();let r=0;if(a<t.top+o){const e=1-Math.max(0,a-t.top)/o;r=-Math.round(i+(n-i)*e)}else if(a>t.bottom-o){const e=1-Math.max(0,t.bottom-a)/o;r=Math.round(i+(n-i)*e)}if(0===r)return void c(!1);const d=e.scrollTop;e.scrollTop=d+r,e.scrollTop!==d?(c(!0),s=requestAnimationFrame(l)):c(!1)};return{onPointerMove(e){a=e,null===s&&(s=requestAnimationFrame(l))},stop(){null!==s&&(cancelAnimationFrame(s),s=null),a=null,c(!1)},get isScrolling(){return d}}}(e,t,e=>{this.gridElement.classList.toggle("tbw-grid--auto-scrolling",e)})}applyDropPositionClasses(e,t){this.clearDropTargetClasses(),e&&(e.classList.add("drop-target"),e.classList.toggle("drop-before",t),e.classList.toggle("drop-after",!t))}clearDropTargetClasses(){this.gridElement?.querySelectorAll(".data-grid-row.drop-target").forEach(e=>{e.classList.remove("drop-target","drop-before","drop-after")})}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove(t,"drop-target","drop-before","drop-after")})}resetDragState(){this.isDragging=!1,this.draggedRowIndex=null,this.draggedRows=[],this.draggedIndices=[],this.dragSessionId=null,this.dragAccepted=!1,this.dropRowIndex=null,this.pendingMove=null}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}handleKeyboardMove(e,t,r,o){this.pendingMove?this.pendingMove.currentIndex=r:this.pendingMove={originalIndex:t,currentIndex:r,row:e},this.lastFocusCol=o;const i=this.internalGrid,n=[...i._rows??this.sourceRows],[s]=n.splice(t,1);n.splice(r,0,s),i._rows=n,i._focusRow=r,i._focusCol=o,i.refreshVirtualWindow(!0),d(i),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>this.flushPendingMove(),this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:t,row:r}=this.pendingMove;if(this.pendingMove=null,e===t)return;const o=this.internalGrid,i={row:r,fromIndex:e,toIndex:t,rows:[...o._rows??this.sourceRows],source:"keyboard"};this.emitCancelable("row-move",i)&&(o._rows=[...this.sourceRows],o._focusRow=e,o._focusCol=this.lastFocusCol,o.refreshVirtualWindow(!0),d(o))}executeIntraGridMove(e,t,r,o){const i=[...this.sourceRows],[n]=i.splice(t,1);i.splice(r,0,n);const s={row:e,fromIndex:t,toIndex:r,rows:i,source:o};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=i,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,r)})}else this.grid.rows=i}captureRowPositions(){const e=/* @__PURE__ */new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const r=this.getRowIndex(t);r>=0&&e.set(r,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,r){const o=this.gridElement;if(!o||0===e.size)return;const i=Math.min(t,r),n=Math.max(t,r),s=[];if(o.querySelectorAll(".data-grid-row").forEach(o=>{const a=o,d=this.getRowIndex(a);if(d<0||d<i||d>n)return;let c;c=d===r?t:t<r?d+1:d-1;const l=e.get(c);if(void 0===l)return;const g=l-a.getBoundingClientRect().top;Math.abs(g)>1&&s.push({el:a,deltaY:g})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),o.offsetHeight;const a=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},a+50)})}};export{E as ROW_DRAG_HANDLE_FIELD,L as RowDragDropPlugin};
1
+ var e="editing",t="dragging",r=/* @__PURE__ */new Map;function o(e){const t=r.get(e);if(!t)return;if(t.hasPrimitives)return;const o=[];for(const r of t.refs){const e=r.deref();if(void 0===e)return;o.push(e)}return o}function i(e){r.delete(e)}function n(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const e=/* @__PURE__ */new Uint32Array(2);return crypto.getRandomValues(e),`drag-${Date.now().toString(36)}-${e[0].toString(36)}${e[1].toString(36)}`}return`drag-${Date.now().toString(36)}-${(++s).toString(36)}`}var s=0;function a(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,o=t.rawContentHeight-t.viewportHeight;return r<=0||o<=0?e:e*r/o}function d(t,r){!function(e){if(!e._virtualization?.enabled)return;const{rowHeight:t,container:r,viewportEl:o,scrollMapping:i}=e._virtualization,n=r,s=o?.clientHeight??n?.clientHeight??0;if(!n||s<=0)return;const d=e._focusRow*t,c=i?function(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,o=t.rawContentHeight-t.viewportHeight;if(r<=0||o<=0)return e;const i=e*o/r;return i<0?0:i>o?o:i}(n.scrollTop,i):n.scrollTop;if(d<c)n.scrollTop=i?a(d,i):d;else if(d+t>c+s){const e=d-s+t;n.scrollTop=i?a(e,i):e}}(t);const o=function(e){return void 0!==e._activeEditRows&&-1!==e._activeEditRows}(t)||!!t._isGridEditMode;var i;o||t.refreshVirtualWindow(!1),(i=t._bodyEl)&&i.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus")),Array.from(t._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const n=function(e){const t=e._focusRow,r=e._virtualization.start??0,o=e._virtualization.end??e._rows.length;if(t<r||t>=o)return;const i=e._bodyEl.querySelectorAll(".data-grid-row")[t-r];let n=i?.children[e._focusCol];return n&&n.classList?.contains("cell")||(n=i?.querySelector(`.cell[data-col="${e._focusCol}"]`)??i?.querySelector(".cell[data-col]")),n?{rowEl:i??null,cell:n}:void 0}(t);if(!n)return;const{rowEl:s,cell:d}=n;d.classList.add("cell-focus"),d.setAttribute("aria-selected","true"),o&&!r?.forceHorizontalScroll||function(e,t,r,o){const i=e.querySelector(".tbw-scroll-area");if(!i)return;if(o?.forceScrollLeft)return void(i.scrollLeft=0);if(o?.forceScrollRight)return void(i.scrollLeft=i.scrollWidth-i.clientWidth);const n=e._getHorizontalScrollOffsets?.(t??void 0,r)??{left:0,right:0};if(n.skipScroll)return;const s=r.getBoundingClientRect(),a=i.getBoundingClientRect(),d=s.left-a.left+i.scrollLeft,c=d+s.width,l=i.scrollLeft+n.left,g=i.scrollLeft+i.clientWidth-n.right;d<l?i.scrollLeft=d-n.left:c>g&&(i.scrollLeft=c-i.clientWidth+n.right)}(t,s,d,r),function(t,r,o){if(o&&r.classList.contains(e)){const e=r.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}return}if(o){if(r.contains(document.activeElement))return;r.hasAttribute("tabindex")||r.setAttribute("tabindex","-1");try{r.focus({preventScroll:!0})}catch{}return}const i=document.activeElement;i instanceof HTMLElement&&i!==t&&"function"==typeof t.contains&&t.contains(i)&&!i.classList.contains("cell")&&!i.closest(".cell")||i===t||t.focus({preventScroll:!0})}(t,d,o)}function c(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function l(e,t,r,o){return`${c(r,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}var g="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join("")),u=(new RegExp(`__(proto|defineGetter|defineSetter)|${g.slice(3).join("|")}|this\\b`),new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math".split("|"))),f=/^on\w+$/i,h=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),p=/^\s*(javascript|vbscript|data|blob):/i;function w(e){const t=document.createElement("template");return e&&"string"==typeof e&&(t.innerHTML=e,function(e){const t=[],r=e.querySelectorAll("*");for(const o of r){const e=o.tagName.toLowerCase();if(u.has(e)){t.push(o);continue}if(("svg"===e||"http://www.w3.org/2000/svg"===o.namespaceURI)&&Array.from(o.attributes).some(e=>f.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(o);continue}const r=[];for(const t of o.attributes){const e=t.name.toLowerCase();f.test(e)?r.push(t.name):"is"!==e?(h.has(e)&&p.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name):r.push(t.name)}r.forEach(e=>o.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content)),t.content}var m={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};var b=class{static dependencies;static manifest;aliases;version="3.5.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},r={};for(const o of Object.keys(t))r[o]=this;for(const o of e){const e=o.userConfig;for(const[i,n]of Object.entries(e)){if(void 0===n)continue;if(!(i in t)){t[i]=n,r[i]=o;continue}if(t[i]===n)continue;const e=r[i]?.constructor.name??this.constructor.name,s=o.constructor.name,a=l("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${i}" supplied by both ${e} and ${s}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(a)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,r={...e.userConfig};for(const o of Object.keys(t))delete t[o];Object.assign(t,r)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}queryBoolean(e,t=null){const r=this.grid?.query?.(e,t);return Array.isArray(r)?r.some(Boolean):!!r}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...m,...e}}t(e,t){return this.grid?.effectiveConfig?.locale?.[e]??t}get translate(){return(e,t)=>this.t(e,t)}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;return!t||"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(t,10);if(!isNaN(r))return r}return 200}setIcon(e,t,r){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const o=this.#t(t,r);var i,n;void 0!==o?"string"==typeof o?(i=e,(n=o)&&"string"==typeof n?-1!==n.indexOf("<")||-1!==n.indexOf("&")?i.replaceChildren(w(n)):i.textContent=n:i.replaceChildren()):o instanceof HTMLElement&&e.replaceChildren(o.cloneNode(!0)):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const r=document.createElement("span");r.setAttribute("part","sort-indicator"),r.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(r,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(r,"sortNone"));const o=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return o?e.insertBefore(r,o):e.appendChild(r),r}warn(e,t){void 0!==t?console.warn(l(e,t,this.gridElement.id,this.name)):console.warn(`${c(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(l(e,t,this.gridElement.id,this.name))}},v=null;function y(){return v}function I(){v=null}var x="application/x-tbw-grid-rows+json";function R(e){const t=e.match(/^application\/x-tbw-grid-rows\+json;zone=(.*)$/);if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}}function C(e){return JSON.stringify(e)}function D(e,t,r,o){if(!e)return{overIndex:null,insertIndex:o,isBefore:!1};const i=r(e);if(i<0)return{overIndex:null,insertIndex:o,isBefore:!1};const n=e.getBoundingClientRect(),s=t<n.top+n.height/2;return{overIndex:i,insertIndex:s?i:i+1,isBefore:s}}var E="__tbw_row_drag",S=null,A=/* @__PURE__ */new Set;function _(){if("undefined"==typeof BroadcastChannel)return null;if(S)return S;try{(S=new BroadcastChannel("tbw-row-drag-drop")).addEventListener("message",e=>{const t=e.data;if(t&&"tbw-row-drag-drop:transfer"===t.type)for(const r of Array.from(A))try{r(t)}catch{}})}catch{S=null}return S}var L=class e extends b{name="rowDragDrop";styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{justify-content:center;align-items:center;display:flex}.dg-row-drag-handle{cursor:grab;-webkit-user-select:none;user-select:none;min-width:1em;min-height:1em;color:var(--tbw-row-reorder-handle-color,var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration,.12s) var(--tbw-transition-ease,ease);font-size:var(--tbw-font-size,1em);letter-spacing:-2px;justify-content:center;align-items:center;display:flex}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover,var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}@media (hover:none){.dg-row-drag-handle{color:var(--tbw-row-reorder-handle-hover,var(--tbw-color-fg))}}@media (pointer:coarse){.dg-row-drag-handle{min-width:var(--tbw-touch-target-min,24px);min-height:var(--tbw-touch-target-min,24px)}}.data-grid-row.dragging{opacity:.6}.data-grid-row[draggable=true]{cursor:grab}.data-grid-row[draggable=true].dragging{cursor:grabbing}.tbw-row-drag-clone{pointer-events:none;position:fixed;top:-10000px;left:-10000px}.tbw-row-drag-count{pointer-events:none;background:var(--tbw-row-reorder-indicator,var(--tbw-color-accent));color:var(--tbw-color-accent-fg);box-shadow:0 2px 6px var(--tbw-color-shadow);z-index:9999;border-radius:999px;padding:2px 8px;font:600 12px/1.4 system-ui,sans-serif;position:fixed;top:-1000px;left:-1000px}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before,.data-grid-row.drop-target.drop-after:after{content:"";height:var(--tbw-drop-indicator-width,2px);background-color:var(--tbw-drop-indicator-color,var(--tbw-row-reorder-indicator,var(--tbw-color-accent)));z-index:10;pointer-events:none;position:absolute;left:0;right:0}.data-grid-row.drop-target.drop-before:before{top:0}.data-grid-row.drop-target.drop-after:after{bottom:0}.tbw-grid--drop-target-active{outline:2px dashed var(--tbw-drop-indicator-color,var(--tbw-color-accent));outline-offset:-2px}.tbw-grid--drop-target-rejected{outline:2px dashed var(--tbw-color-danger);outline-offset:-2px}.tbw-grid--auto-scrolling{cursor:ns-resize}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration,.2s) ease-out;will-change:transform;z-index:1}}';static manifest={events:[{type:"row-move",description:"Intra-grid row reorder.",cancelable:!0},{type:"row-drag-start",description:"Cross-grid drag started on this grid.",cancelable:!0},{type:"row-drag-end",description:"Drag finished on this grid (regardless of outcome)."},{type:"row-drop",description:"Cross-grid drop landing on this grid.",cancelable:!0},{type:"row-transfer",description:"Cross-grid transfer completed (fires on both grids)."}]};get defaultConfig(){return{enableKeyboard:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip",operation:"move",autoScroll:!0,dragFrom:"handle"}}shouldRenderDragHandle(){const e=this.config.showDragHandle;return!1!==e&&(!0===e||"row"!==this.config.dragFrom)}get rowIsDraggable(){return"row"===this.config.dragFrom||"both"===this.config.dragFrom}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;draggedRows=[];draggedIndices=[];dragSessionId=null;dragAccepted=!1;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;autoScroller=null;gridId="";remoteTransferListener=e=>this.onRemoteTransfer(e);get internalGrid(){return this.grid}attach(e){super.attach(e);const t=this.gridElement;var r;t&&(this.gridId=t.id||`tbw-grid-${n().slice(0,8)}`,t.id||(t.id=this.gridId),this.setupDelegatedDragListeners(),r=this.remoteTransferListener,A.add(r),_())}detach(){this.clearDebounceTimer(),this.autoScroller?.stop(),this.autoScroller=null,function(e){if(A.delete(e),0===A.size&&S){try{S.close()}catch{}S=null}}(this.remoteTransferListener),this.dragSessionId&&i(this.dragSessionId),I(),this.resetDragState(),super.detach()}processColumns(e){if(!this.shouldRenderDragHandle())return[...e];const t={field:E,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,lockPosition:!0,utility:!0,viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,"dragHandle"),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){this.applyRowDraggable()}onScrollRender(){this.applyRowDraggable()}applyRowDraggable(){const e=this.internalGrid._bodyEl;if(!e)return;const t=this.rowIsDraggable,r=e.querySelectorAll(".data-grid-row");for(const o of r)t?"true"!==o.getAttribute("draggable")&&o.setAttribute("draggable","true"):o.hasAttribute("draggable")&&o.removeAttribute("draggable")}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.internalGrid,r=t._focusRow,o=t._rows??this.sourceRows;if(r<0||r>=o.length)return;const i="up"==("ArrowUp"===e.key?"up":"down")?r-1:r+1;if(i<0||i>=o.length)return;const n=o[r];return this.canMoveRow(r,i)?(this.handleKeyboardMove(n,r,i,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const r=[...this.sourceRows];e<0||e>=r.length||t<0||t>=r.length||e!==t&&this.canMoveRow(e,t)&&this.executeIntraGridMove(r[e],e,t,"keyboard")}canMoveRow(e,t){const r=this.internalGrid._rows??this.sourceRows;if(e<0||e>=r.length)return!1;if(t<0||t>=r.length)return!1;if(e===t)return!1;const o=r[e],i=this.grid?.query?.("canMoveRow",o);if(Array.isArray(i)&&i.includes(!1))return!1;if(this.config.canDrag&&!this.config.canDrag(o,e))return!1;if(this.config.canDrop){const r={sessionId:"intra",sourceGridId:this.gridId,dropZone:this.config.dropZone??"",rows:[o],rowIndices:[e],operation:"move"};if(!this.config.canDrop(r,t))return!1}return!0}setupDelegatedDragListeners(){const e=this.gridElement;if(!e)return;const t=this.disconnectSignal;e.addEventListener("dragstart",e=>this.onDragStart(e),{signal:t}),e.addEventListener("dragend",()=>this.onDragEnd(),{signal:t}),e.addEventListener("dragover",e=>this.onDragOver(e),{signal:t}),e.addEventListener("dragleave",e=>this.onDragLeave(e),{signal:t}),e.addEventListener("drop",e=>this.onDrop(e),{signal:t})}onDragStart(e){const o=e.target;if(!o)return;const i=o.closest(".dg-row-drag-handle");let s=null,a=!1;if(i)s=i.closest(".data-grid-row"),a=!0;else if(this.rowIsDraggable){if(this.isInteractiveDragOrigin(o))return;s=o.closest(".data-grid-row")}if(!s)return;const d=this.getRowIndex(s);if(d<0)return;const{rows:c,indices:l}=this.resolveDraggedRows(d);if(0===c.length)return;if(this.config.canDrag&&!this.config.canDrag(c[0],d))return void e.preventDefault();const g=this.config.operation??"move",u=this.config.dropZone??"",f=n(),h={rows:c,indices:l,operation:g,dropZone:u};if(this.emitCancelable("row-drag-start",h))return void e.preventDefault();this.isDragging=!0,this.draggedRowIndex=d,this.draggedRows=c,this.draggedIndices=l,this.dragSessionId=f,this.dragAccepted=!1;const p=this.config.serializeRow??(e=>e),w={sessionId:f,sourceGridId:this.gridId,dropZone:u,rows:c.map(p),rowIndices:l,operation:g};if(e.dataTransfer){e.dataTransfer.effectAllowed="copy"===g?"copyMove":"move";try{e.dataTransfer.setData(x,C(w)),u&&e.dataTransfer.setData(`${x};zone=${encodeURIComponent(u)}`,C(w)),e.dataTransfer.setData("text/plain",function(e,t){const r=t.filter(e=>!e.utility&&"string"==typeof e.field&&""!==e.field),o=[];for(const i of e){const e=r.map(e=>{const t=i[e.field];return null==t?"":String(t).replace(/[\t\r\n]+/g," ")});o.push(e.join("\t"))}return o.join("\n")}(c,this.columns))}catch{}if(c.length>1){const t=document.createElement("div");t.className="tbw-row-drag-count",t.textContent=`${c.length} rows`,document.body.appendChild(t);try{e.dataTransfer.setDragImage(t,10,10)}catch{}setTimeout(()=>t.remove(),0)}else this.attachRowCloneDragImage(e,s,a?i:null)}!function(e,t){const o=[];let i=!1;for(const r of t)null!==r&&"object"==typeof r?o.push(new WeakRef(r)):i=!0;r.set(e,{refs:o,hasPrimitives:i})}(f,c),function(e,t){v={sessionId:e,payload:t}}(f,w),s.classList.add(t),this.gridElement.classList.add("tbw-grid--drag-source")}static INTERACTIVE_DRAG_SELECTORS='input,textarea,select,button,a,[contenteditable=""],[contenteditable="true"],.dg-cell-editor,.tbw-checkbox-cell';isInteractiveDragOrigin(t){return null!==t.closest(e.INTERACTIVE_DRAG_SELECTORS)}attachRowCloneDragImage(e,t,r){if(!e.dataTransfer)return;const o=t.getBoundingClientRect(),i=t.cloneNode(!0);i.classList.add("tbw-row-drag-clone"),i.classList.remove("dragging","drop-target","drop-before","drop-after","flip-animating","row-focus"),i.removeAttribute("aria-selected"),i.style.width=`${o.width}px`,i.style.height=`${o.height}px`,this.gridElement.appendChild(i);let n=e.clientX-o.left,s=e.clientY-o.top;if(r){const e=r.getBoundingClientRect();n=e.left-o.left+e.width/2,s=e.top-o.top+e.height/2}n=Math.max(0,Math.min(o.width,n)),s=Math.max(0,Math.min(o.height,s));try{e.dataTransfer.setDragImage(i,n,s)}catch{}setTimeout(()=>i.remove(),0)}onDragOver(e){const t=e.dataTransfer;if(!t)return;const r=t.types?Array.from(t.types):[];if(!function(e){for(const t of e)if("application/x-tbw-grid-rows+json"===t||t.startsWith("application/x-tbw-grid-rows+json;"))return!0;return!1}(r)&&!this.isDragging)return;const o=this.config.dropZone??"",i=y(),n=this.isDragging&&i?.payload.sourceGridId===this.gridId;if(!n){if(!o)return;if(!(function(e,t){for(const r of e)if(R(r)===t)return r;return null}(r,o)||i&&i.payload.dropZone===o))return}e.preventDefault(),t&&(t.dropEffect=i?.payload.operation??this.config.operation??"move");const s=e.target.closest(".data-grid-row"),a=this.internalGrid._rows??[],d=D(s,e.clientY,e=>this.getRowIndex(e),a.length);if(n&&null!==d.overIndex&&d.overIndex===this.draggedRowIndex)this.clearDropTargetClasses();else{if(i&&this.config.canDrop){const e=this.config.canDrop(i.payload,d.insertIndex);if(this.gridElement.classList.toggle("tbw-grid--drop-target-active",e),this.gridElement.classList.toggle("tbw-grid--drop-target-rejected",!e),!e)return void this.clearDropTargetClasses()}else this.gridElement.classList.add("tbw-grid--drop-target-active");this.dropRowIndex=d.insertIndex,this.applyDropPositionClasses(s,d.isBefore),!1!==this.config.autoScroll&&(this.ensureAutoScroller(),this.autoScroller?.onPointerMove(e.clientY))}}onDragLeave(e){const t=e.target.closest(".data-grid-row");t&&t.classList.remove("drop-target","drop-before","drop-after"),e.currentTarget&&!this.gridElement.contains(e.relatedTarget)&&(this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.autoScroller?.stop())}onDrop(e){e.preventDefault(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drop-target-active","tbw-grid--drop-target-rejected"),this.clearDropTargetClasses();const t=e.dataTransfer;if(!t)return;let r=y()?.payload??null,i=null;if(r){const e=o(r.sessionId);e&&(i=e)}else if(r=function(e){if(!e)return null;try{const t=JSON.parse(e);if("string"!=typeof t?.sessionId||"string"!=typeof t?.sourceGridId||"string"!=typeof t?.dropZone||!Array.isArray(t?.rows)||!Array.isArray(t?.rowIndices)||"move"!==t.operation&&"copy"!==t.operation)return null;for(const e of t.rowIndices)if("number"!=typeof e||!Number.isInteger(e)||e<0)return null;return t}catch{return null}}(t.getData(x)),r){const e=o(r.sessionId);e&&(i=e)}if(!r)return;const n=e.target.closest(".data-grid-row"),s=this.internalGrid._rows??[],a=D(n,e.clientY,e=>this.getRowIndex(e),s.length);let d=this.dropRowIndex??a.insertIndex;const c=r.sourceGridId===this.gridId,l=this.config.dropZone??"";if(c){const e=r.rowIndices[0];if(1===r.rowIndices.length&&d>e&&d--,e===d)return;const t=(i??r.rows)[0];if(!this.canMoveRow(e,d))return;return void this.executeIntraGridMove(t,e,d,"drag")}if(!l||l!==r.dropZone)return;if(this.config.canDrop&&!this.config.canDrop(r,d))return this.gridElement.classList.add("tbw-grid--drop-target-rejected"),void setTimeout(()=>this.gridElement.classList.remove("tbw-grid--drop-target-rejected"),200);const g=this.config.deserializeRow??(e=>e),u=i??r.rows.map(e=>g(e)),f={payload:r,sourceGridId:r.sourceGridId,targetIndex:d,operation:r.operation};if(this.emitCancelable("row-drop",f))return;const h=[...s];h.splice(d,0,...u),this.grid.rows=h;const p=this.findPeerOnGrid(r.sourceGridId);if("move"===r.operation&&p){const e=document.getElementById(r.sourceGridId);if(e){const t=(e._rows??e.rows??[]).slice(),o=[...r.rowIndices].sort((e,t)=>t-e);for(const e of o)e>=0&&e<t.length&&t.splice(e,1);e.rows=t}}p&&(p.dragAccepted=!0);const w={rows:u,fromGridId:r.sourceGridId,toGridId:this.gridId,fromIndices:r.rowIndices,toIndex:d,operation:r.operation};this.emit("row-transfer",w),p?p.emitTransfer(w):function(e){const t=_();if(t)try{t.postMessage(e)}catch{}}({type:"tbw-row-drag-drop:transfer",sessionId:r.sessionId,sourceGridId:r.sourceGridId,toGridId:this.gridId,dropZone:l,rowIndices:r.rowIndices,toIndex:d,operation:r.operation,serializedRows:r.rows})}onRemoteTransfer(e){if(e.sourceGridId!==this.gridId)return;const t=this.config.dropZone??"";if(!t||e.dropZone!==t)return;const r=this.config.deserializeRow??(e=>e),o=e.serializedRows.map(e=>r(e));if("move"===e.operation){const t=(this.internalGrid._rows??this.sourceRows).slice(),r=[...e.rowIndices].sort((e,t)=>t-e);for(const e of r)e>=0&&e<t.length&&t.splice(e,1);this.grid.rows=t}this.dragAccepted=!0,this.emit("row-transfer",{rows:o,fromGridId:e.sourceGridId,toGridId:e.toGridId,fromIndices:e.rowIndices,toIndex:e.toIndex,operation:e.operation})}onDragEnd(){if(this.dragSessionId&&i(this.dragSessionId),I(),this.autoScroller?.stop(),this.gridElement.classList.remove("tbw-grid--drag-source"),this.isDragging){const e={rows:this.draggedRows,indices:this.draggedIndices,accepted:this.dragAccepted};this.emit("row-drag-end",e)}this.clearDragClasses(),this.resetDragState()}emitTransfer(e){this.emit("row-transfer",e)}findPeerOnGrid(e){const t=document.getElementById(e);return t?.getPluginByName?t.getPluginByName("rowDragDrop")??null:null}resolveDraggedRows(e){const t=this.internalGrid._rows??this.sourceRows,r=t[e],o=this.grid?.getPluginByName?.("selection");if(o?.getSelectedRowIndices){const r=o.getSelectedRowIndices();if(r.includes(e)&&r.length>1){const e=[...r].sort((e,t)=>e-t);return{rows:e.map(e=>t[e]),indices:e}}}return{rows:[r],indices:[e]}}ensureAutoScroller(){if(this.autoScroller)return;const e=this.gridElement.querySelector(".rows-viewport");if(!e)return;const t="object"==typeof this.config.autoScroll?this.config.autoScroll:void 0;this.autoScroller=function(e,t={},r){const o=t.edgeSize??60,i=t.speed??8,n=t.maxSpeed??24;let s=null,a=null,d=!1;const c=e=>{e!==d&&(d=e,r?.(e))},l=()=>{if(s=null,null===a)return void c(!1);const t=e.getBoundingClientRect();let r=0;if(a<t.top+o){const e=1-Math.max(0,a-t.top)/o;r=-Math.round(i+(n-i)*e)}else if(a>t.bottom-o){const e=1-Math.max(0,t.bottom-a)/o;r=Math.round(i+(n-i)*e)}if(0===r)return void c(!1);const d=e.scrollTop;e.scrollTop=d+r,e.scrollTop!==d?(c(!0),s=requestAnimationFrame(l)):c(!1)};return{onPointerMove(e){a=e,null===s&&(s=requestAnimationFrame(l))},stop(){null!==s&&(cancelAnimationFrame(s),s=null),a=null,c(!1)},get isScrolling(){return d}}}(e,t,e=>{this.gridElement.classList.toggle("tbw-grid--auto-scrolling",e)})}applyDropPositionClasses(e,t){this.clearDropTargetClasses(),e&&(e.classList.add("drop-target"),e.classList.toggle("drop-before",t),e.classList.toggle("drop-after",!t))}clearDropTargetClasses(){this.gridElement?.querySelectorAll(".data-grid-row.drop-target").forEach(e=>{e.classList.remove("drop-target","drop-before","drop-after")})}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove(t,"drop-target","drop-before","drop-after")})}resetDragState(){this.isDragging=!1,this.draggedRowIndex=null,this.draggedRows=[],this.draggedIndices=[],this.dragSessionId=null,this.dragAccepted=!1,this.dropRowIndex=null,this.pendingMove=null}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}handleKeyboardMove(e,t,r,o){this.pendingMove?this.pendingMove.currentIndex=r:this.pendingMove={originalIndex:t,currentIndex:r,row:e},this.lastFocusCol=o;const i=this.internalGrid,n=[...i._rows??this.sourceRows],[s]=n.splice(t,1);n.splice(r,0,s),i._rows=n,i._focusRow=r,i._focusCol=o,i.refreshVirtualWindow(!0),d(i),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>this.flushPendingMove(),this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:t,row:r}=this.pendingMove;if(this.pendingMove=null,e===t)return;const o=this.internalGrid,i={row:r,fromIndex:e,toIndex:t,rows:[...o._rows??this.sourceRows],source:"keyboard"};this.emitCancelable("row-move",i)&&(o._rows=[...this.sourceRows],o._focusRow=e,o._focusCol=this.lastFocusCol,o.refreshVirtualWindow(!0),d(o))}executeIntraGridMove(e,t,r,o){const i=[...this.sourceRows],[n]=i.splice(t,1);i.splice(r,0,n);const s={row:e,fromIndex:t,toIndex:r,rows:i,source:o};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=i,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,r)})}else this.grid.rows=i}captureRowPositions(){const e=/* @__PURE__ */new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const r=this.getRowIndex(t);r>=0&&e.set(r,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,r){const o=this.gridElement;if(!o||0===e.size)return;const i=Math.min(t,r),n=Math.max(t,r),s=[];if(o.querySelectorAll(".data-grid-row").forEach(o=>{const a=o,d=this.getRowIndex(a);if(d<0||d<i||d>n)return;let c;c=d===r?t:t<r?d+1:d-1;const l=e.get(c);if(void 0===l)return;const g=l-a.getBoundingClientRect().top;Math.abs(g)>1&&s.push({el:a,deltaY:g})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),o.offsetHeight;const a=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},a+50)})}};export{E as ROW_DRAG_HANDLE_FIELD,L as RowDragDropPlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- var e="selected",t={sortApplied:(e,t)=>`Sorted by ${e}, ${t}`,sortCleared:()=>"Sort cleared",filterApplied:e=>`Filter applied on ${e}`,filterCleared:e=>`Filter cleared from ${e}`,allFiltersCleared:()=>"All filters cleared",groupExpanded:(e,t)=>`Group ${e} expanded, ${t} rows`,groupCollapsed:e=>`Group ${e} collapsed`,selectionChanged:e=>`${e} rows selected`,columnSelected:e=>`Column ${e} selected`,columnSelectionChanged:e=>`${e} columns selected`,columnSelectionCleared:()=>"Column selection cleared",selectionAxisChanged:e=>"column"===e?"Row selection cleared, column selection active":"Column selection cleared, row selection active",editingStarted:e=>`Editing row ${e+1}`,editingCommitted:e=>`Row ${e+1} saved`,dataLoaded:e=>`${e} rows loaded`},n={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function i(e,t){if(!e)return;if(!1===("effectiveConfig"in e?e.effectiveConfig:void 0)?.a11y?.announcements)return;const n=e.querySelector?.(".tbw-sr-only");n&&(n.textContent="","function"==typeof requestAnimationFrame?requestAnimationFrame(()=>{n.textContent=t}):n.textContent=t)}function s(e,n,...i){const s=(e&&"effectiveConfig"in e?e.effectiveConfig:void 0)?.a11y?.messages?.[n];return s?s(...i):t[n](...i)}var o=null,r=/* @__PURE__ */new Set;function l(e){const t=e.matches?"coarse":"fine";r.forEach(e=>e(t))}function c(){const e=o||("function"!=typeof globalThis.matchMedia?null:("function"==typeof(o=globalThis.matchMedia("(pointer: coarse)")).addEventListener?o.addEventListener("change",l):"function"==typeof o.addListener&&o.addListener(l),o));return e?function(e){return e.matches?"coarse":"fine"}(e):"fine"}function a(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const n=e.closest(".data-grid-row");if(!n)return-1;const i=n.parentElement;if(!i)return-1;const s=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<s.length;o++)if(s[o]===n)return o;return-1}function d(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function h(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function u(e,t,n,i){return`${h(n,i)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}var g="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join("")),m=(new RegExp(`__(proto|defineGetter|defineSetter)|${g.slice(3).join("|")}|this\\b`),new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math".split("|"))),f=/^on\w+$/i,w=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),b=/^\s*(javascript|vbscript|data|blob):/i;function p(e){const t=document.createElement("template");return e&&"string"==typeof e&&(t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const i of n){const e=i.tagName.toLowerCase();if(m.has(e)){t.push(i);continue}if(("svg"===e||"http://www.w3.org/2000/svg"===i.namespaceURI)&&Array.from(i.attributes).some(e=>f.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(i);continue}const n=[];for(const t of i.attributes){const e=t.name.toLowerCase();f.test(e)?n.push(t.name):"is"!==e?(w.has(e)&&b.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name):n.push(t.name)}n.forEach(e=>i.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content)),t.content}var v=class{static dependencies;static manifest;aliases;version="3.5.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},n={};for(const i of Object.keys(t))n[i]=this;for(const i of e){const e=i.userConfig;for(const[s,o]of Object.entries(e)){if(void 0===o)continue;if(!(s in t)){t[s]=o,n[s]=i;continue}if(t[s]===o)continue;const e=n[s]?.constructor.name??this.constructor.name,r=i.constructor.name,l=u("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${s}" supplied by both ${e} and ${r}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,n={...e.userConfig};for(const i of Object.keys(t))delete t[i];Object.assign(t,n)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}queryBoolean(e,t=null){const n=this.grid?.query?.(e,t);return Array.isArray(n)?n.some(Boolean):!!n}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...n,...e}}t(e,t){return this.grid?.effectiveConfig?.locale?.[e]??t}get translate(){return(e,t)=>this.t(e,t)}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;return!t||"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const i=this.#t(t,n);var s,o;void 0!==i?"string"==typeof i?(s=e,(o=i)&&"string"==typeof o?-1!==o.indexOf("<")||-1!==o.indexOf("&")?s.replaceChildren(p(o)):s.textContent=o:s.replaceChildren()):i instanceof HTMLElement&&e.replaceChildren(i.cloneNode(!0)):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const i=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return i?e.insertBefore(n,i):e.appendChild(n),n}warn(e,t){void 0!==t?console.warn(u(e,t,this.gridElement.id,this.name)):console.warn(`${h(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(u(e,t,this.gridElement.id,this.name))}};function C(e){return"__tbw_expander"===e.field}function y(e){return!0===e.utility}function S(e){const t=/* @__PURE__ */new Set(["cell","row","column","range"]);if("string"==typeof e){if(!t.has(e))throw new Error(`[SelectionPlugin] Invalid selection mode: "${e}". Expected one of: 'cell' | 'row' | 'column' | 'range'.`);return{primary:e,columnEnabled:"column"===e,bothAxes:!1}}if(!Array.isArray(e))throw new Error(`[SelectionPlugin] Invalid selection mode: expected string or array, got ${typeof e}.`);if(0===e.length)throw new Error("[SelectionPlugin] Invalid selection mode: array must contain at least one mode.");for(const i of e)if(!t.has(i))throw new Error(`[SelectionPlugin] Invalid selection mode in array: "${i}". Expected one of: 'cell' | 'row' | 'column' | 'range'.`);if(new Set(e).size!==e.length)throw new Error(`[SelectionPlugin] Invalid selection mode: array contains duplicate entries (${e.join(", ")}).`);if(1===e.length)return S(e[0]);if(e.length>2)throw new Error(`[SelectionPlugin] Invalid selection mode: arrays of more than 2 modes are not supported. Got [${e.join(", ")}].`);if(!e.includes("column"))throw new Error(`[SelectionPlugin] Invalid selection mode: [${e.join(", ")}]. Two-mode arrays must include 'column' (the only valid combinations are ['row','column'], ['cell','column'], ['range','column']). Other in-row modes don't compose meaningfully.`);const n=e.find(e=>"column"!==e);if("column"===n)throw new Error(`[SelectionPlugin] Invalid selection mode: [${e.join(", ")}].`);return{primary:n,columnEnabled:!0,bothAxes:!0}}function A(e){const t=[];for(const n of e)!0!==n.utility&&"string"==typeof n.field&&n.field.length>0&&t.push(n.field);return t}function x(e,t){return t.indexOf(e)}function E(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function R(e){const t=E(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function k(e,t,n){return n.some(n=>function(e,t,n){const i=E(n);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,n))}function q(e){const t=[],n=E(e);for(let i=n.startRow;i<=n.endRow;i++)for(let e=n.startCol;e<=n.endCol;e++)t.push({row:i,col:e});return t}function I(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function M(e,t){const n=E(e),i=E(t);return n.startRow===i.startRow&&n.startCol===i.startCol&&n.endRow===i.endRow&&n.endCol===i.endCol}var P=/* @__PURE__ */new WeakMap;function $(e,t,n,i){const{onMove:s,onEnd:o,onCancel:r,onPromote:l}=n,c=i?.threshold??0,a=i?.longPressDuration??0,d=i?.longPressSlop??8,h=e.pointerId;if(!function(e,t){let n=P.get(e);return n||(n=/* @__PURE__ */new Set,P.set(e,n)),!n.has(t)&&(n.add(t),!0)}(t,h))return()=>{};const u=e.clientX,g=e.clientY;let m=0===c&&0===a,f=!1,w=null,b=!1;function p(){return m=!0,function(){try{return t.setPointerCapture(h),!0}catch{return b=!0,!1}}()?(l?.(),!0):(C(),!1)}function v(){if(!f){var e,n;f=!0,null!==w&&(clearTimeout(w),w=null),t.removeEventListener("pointermove",y),t.removeEventListener("pointerup",S),t.removeEventListener("pointercancel",A),t.removeEventListener("lostpointercapture",x),document.removeEventListener("keydown",E,!0),e=t,n=h,P.get(e)?.delete(n);try{t.hasPointerCapture(h)&&t.releasePointerCapture(h)}catch{}}}function C(){f||(v(),r?.())}function y(e){const t=e;if(t.pointerId!==h||f)return;const n=t.clientX-u,i=t.clientY-g,o=Math.sqrt(n*n+i*i);if(!m){if(a>0)return o>d?void C():void 0;if(c>0&&o<c)return;if(!p())return}s(t)}function S(e){const t=e;if(t.pointerId!==h||f)return;const n=m;v(),n?o(t):r?.()}function A(e){e.pointerId!==h||f||C()}function x(e){e.pointerId!==h||f||C()}function E(e){"Escape"!==e.key||f||C()}return t.addEventListener("pointermove",y),t.addEventListener("pointerup",S),t.addEventListener("pointercancel",A),t.addEventListener("lostpointercapture",x),document.addEventListener("keydown",E,!0),m&&(p(),b)?()=>{}:(a>0&&(w=setTimeout(()=>{w=null,f||p()},a)),C)}var L="tbw-selection-toolbar",_=class{#n=null;#i=null;#s=null;#o=null;get mounted(){return null!==this.#n}get element(){return this.#n}show(e,t,n,i){this.#o=i,this.#n||this.#r(e),this.#i&&(this.#i.textContent=`${t} selected`),this.#n?.setAttribute("data-selected-count",String(t)),this.#s&&(this.#s.hidden=!n)}destroy(){this.#n?.remove(),this.#n=null,this.#i=null,this.#s=null,this.#o=null}#r(e){const t=e.ownerDocument.createElement("div");t.className=L,t.setAttribute("role","toolbar"),t.setAttribute("aria-label","Selection");const n=e.ownerDocument.createElement("span");n.className=`${L}-count`,n.setAttribute("aria-live","polite"),t.appendChild(n);const i=e.ownerDocument.createElement("div");i.className=`${L}-actions`,t.appendChild(i),i.appendChild(this.#l(e,"select-all","Select all",()=>this.#o?.selectAll())),i.appendChild(this.#l(e,"clear","Clear",()=>this.#o?.clear()));const s=this.#l(e,"more","More…",e=>this.#o?.more(e));s.setAttribute("aria-haspopup","menu"),i.appendChild(s),i.appendChild(this.#l(e,"done","Done",()=>this.#o?.done())),e.prepend(t),this.#n=t,this.#i=n,this.#s=s}#l(e,t,n,i){const s=e.ownerDocument.createElement("button");return s.type="button",s.className=`${L}-btn`,s.dataset.action=t,s.textContent=n,s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),i(s)}),s}},F="tbw-range-handle",K=class{#c=null;#a=null;#o=null;render(e,t,n,i){this.#o=i,t?(this.#c??=this.#d(e,"start"),this.#a??=this.#d(e,"end"),this.#h(e,this.#c,n(t.startRow,t.startCol),"start"),this.#h(e,this.#a,n(t.endRow,t.endCol),"end")):this.#u()}destroy(){this.#c?.remove(),this.#a?.remove(),this.#c=null,this.#a=null,this.#o=null}#u(){this.#c&&(this.#c.hidden=!0),this.#a&&(this.#a.hidden=!0)}#h(e,t,n,i){if(!t)return;if(!n)return void(t.hidden=!0);t.hidden=!1;const s=n.getBoundingClientRect?.(),o=e.getBoundingClientRect?.();if(!s||!o)return;const r="start"===i?s.left-o.left:s.right-o.left,l="start"===i?s.top-o.top:s.bottom-o.top;t.style.left=`${r}px`,t.style.top=`${l}px`}#d(e,t){const n=e.ownerDocument.createElement("div");return n.className=`${F} ${F}-${t}`,n.dataset.corner=t,n.setAttribute("role","presentation"),n.addEventListener("pointerdown",e=>this.#g(e,n,t)),e.appendChild(n),n}#g(e,t,n){if(0!==e.button&&"mouse"===e.pointerType)return;e.preventDefault(),e.stopPropagation();const i=this.#o;if(!i)return;t.classList.add("dragging");const s=()=>{t.classList.remove("dragging"),i.commit()};$(e,t,{onMove:e=>{const t=i.cellAt(e.clientX,e.clientY);t&&i.resize(n,t.row,t.col)},onEnd:s,onCancel:s})}};function T(e){if("string"==typeof e)return e;if(Array.isArray(e)){const t=e.find(e=>"column"!==e);if(t)return t;if(e.includes("column"))return"column"}return"cell"}var D="__tbw_checkbox",z=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"];var H=class extends v{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"},{type:"getSelectedColumns",description:"Get field names of selected columns (column mode only)"},{type:"selectColumns",description:"Select specific columns by field name (column mode only)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===T(e.mode)&&"dblclick"===e.triggerOn},{id:"selection/column-checkbox",severity:"warn",message:'"checkbox: true" only renders in row mode.\n → Column selection has no checkbox UI; activate columns via Ctrl+Click on a header or Ctrl+Space on a focused cell.',check:e=>!!e.checkbox&&"row"!==T(e.mode)}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}:is(tbw-grid:has(.selection)[data-selection-mode=row] .cell-focus,tbw-grid:has(.selection)[data-selection-mode=row] .row-focus,tbw-grid:has(.selection)[data-selection-mode=range] .cell-focus){outline:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background,rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style,var(--tbw-border-style));border-color:var(--tbw-range-border-color,var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width,var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width,var(--tbw-border-width));z-index:26;position:absolute;inset:0}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid .data-grid-row.row-focus>.cell.sticky-left,tbw-grid .data-grid-row.row-focus>.cell.sticky-right{background:linear-gradient(var(--tbw-focus-background,rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0), var(--tbw-color-panel-bg)}tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-left,tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-right{background:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";pointer-events:none;border:0 var(--tbw-selection-border-style,var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1;position:absolute;inset:0}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg,rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm,.8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;justify-content:center;align-items:center;padding:0;display:flex}tbw-grid .tbw-select-row-checkbox{pointer-events:none;cursor:pointer;margin:0}tbw-grid .tbw-checkbox-header{justify-content:center;align-items:center;height:100%;display:flex}tbw-grid .tbw-select-all-checkbox{cursor:pointer;margin:0}@media (pointer:coarse){tbw-grid .tbw-select-row-checkbox,tbw-grid .tbw-select-all-checkbox{min-width:var(--tbw-touch-target-min,24px);min-height:var(--tbw-touch-target-min,24px)}}tbw-grid .header-row>.cell.column-selected,tbw-grid .data-grid-row>.cell.column-selected,tbw-grid .data-grid-row>.cell.column-selected.sticky-left,tbw-grid .data-grid-row>.cell.column-selected.sticky-right,tbw-grid .header-row>.cell.column-selected.sticky-left,tbw-grid .header-row>.cell.column-selected.sticky-right{background:linear-gradient(var(--tbw-column-selection-bg,rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0), var(--tbw-color-panel-bg)}tbw-grid .tbw-selection-toolbar{z-index:30;background:var(--tbw-color-panel-bg);border-bottom:1px solid var(--tbw-color-border);justify-content:space-between;align-items:center;gap:8px;padding:4px 8px;font-size:13px;display:flex;position:sticky;top:0}tbw-grid .tbw-selection-toolbar-count{white-space:nowrap;font-weight:600}tbw-grid .tbw-selection-toolbar-actions{align-items:center;gap:4px;display:flex}tbw-grid .tbw-selection-toolbar-btn{min-height:var(--tbw-touch-target-min,24px);border-radius:var(--tbw-border-radius,4px);color:inherit;font:inherit;cursor:pointer;background:0 0;border:0;padding:0 10px}tbw-grid .tbw-selection-toolbar-btn:hover,tbw-grid .tbw-selection-toolbar-btn:focus-visible{background:var(--tbw-color-hover-bg)}tbw-grid .tbw-selection-toolbar-btn[data-action=done]{color:var(--tbw-color-accent);font-weight:600}tbw-grid .tbw-range-handle{z-index:25;width:var(--tbw-touch-target-min,24px);height:var(--tbw-touch-target-min,24px);background:radial-gradient(circle, var(--tbw-color-accent) 0 5px, transparent 5px);cursor:crosshair;touch-action:none;position:absolute;translate:-50% -50%}tbw-grid .tbw-range-handle[hidden]{display:none}tbw-grid .tbw-range-handle.dragging{scale:1.3}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0,touchMode:"transient"}}get touchSelectionActive(){return this.#m}#m=!1;#f=!1;#w=new _;#b=new K;selected=/* @__PURE__ */new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;pendingRowKeyUpdate=null;selectedCell=null;selectedColumns=/* @__PURE__ */new Set;columnAnchor=null;columnHead=null;activeAxis="none";#p={primary:"cell",columnEnabled:!1,bothAxes:!1};lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;announceTimer=null;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:n}=this.config;if(!n)return!0;const i=this.rows[e];return!!i&&n(i,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.#p=S(this.config.mode),this.on("filter-change",()=>this.clearSelectionSilent()),this.on("group-toggle",()=>this.clearSelectionSilent()),this.on("tree-expand",()=>this.clearSelectionSilent()),this.on("sort-change",()=>this.clearSelectionSilent()),this.on("edit-open",({rowIndex:e,row:t})=>{this.isSelectionEnabled()&&(null==t||e<0||"row"===this.#p.primary&&this.isRowSelectable(e)&&(this.selected.has(e)||(!1===this.config.multiSelect&&this.selected.clear(),this.selected.add(e),this.lastSelected=e,this.anchor=e,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender())))});let t=-1;e.addEventListener("data-change",e=>{const{sourceRowCount:n}=e.detail,i=this.selected.size>0||this.ranges.length>0||null!==this.selectedCell;-1!==t&&n!==t&&i&&this.clearSelectionSilent(),t=n},{signal:this.disconnectSignal})}handleQuery(e){if("getSelection"===e.type)return this.getSelection();if("getSelectedRowIndices"===e.type)return this.getSelectedRowIndices();if("getSelectedRows"===e.type)return this.getSelectedRows();if("selectRows"===e.type)return this.selectRows(e.context),!0;if("getSelectedColumns"===e.type)return this.getSelectedColumns();if("selectColumns"===e.type){const t=e.context;return this.#C(t),!0}}detach(){(this.gridElement?.querySelector(".rows-body"))?.removeAttribute("aria-multiselectable"),this.#w.destroy(),this.#b.destroy(),this.#m=!1,this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none",this.pendingKeyboardUpdate=null,this.pendingRowKeyUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.announceTimer&&(clearTimeout(this.announceTimer),this.announceTimer=null)}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,"column"!==this.activeAxis&&(this.activeAxis="none"),this.requestAfterRender()}#y(e){const t=e.pointerType;return"touch"===t||"pen"===t||"mouse"!==t&&"coarse"===c()}#S(e){return!!this.isRowSelectable(e)&&(this.#m=!0,this.selected.clear(),this.selected.add(e),this.anchor=e,this.lastSelected=e,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender(),!0)}exitTouchSelection(){this.#m&&(this.#m=!1,"transient"===(this.config.touchMode??"transient")&&(this.selected.clear(),this.anchor=null,this.lastSelected=null,this.emit("selection-change",this.#v())),this.requestAfterRender())}#A(e){const t=this.anchor??e,n=Math.min(t,e),i=Math.max(t,e);for(let s=n;s<=i;s++)this.isRowSelectable(s)&&this.selected.add(s);this.lastSelected=e,this.emit("selection-change",this.#v()),this.requestAfterRender()}#x(){const e=this.grid?.getPluginByName?.("contextMenu")??this.grid?.getPluginByName?.("context-menu");return"function"==typeof e?.showMenu?e:void 0}#E(e,t){return this.gridElement?.querySelector(`.cell[data-row="${e}"][data-col="${t}"]`)??null}#R(e,t){const n=this.gridElement,i=((n?.ownerDocument)?.elementFromPoint?.(e,t))?.closest?.(".cell[data-row][data-col]");if(!i||!n?.contains?.(i))return null;const s=parseInt(i.getAttribute("data-row")??"-1",10),o=parseInt(i.getAttribute("data-col")??"-1",10);return s>=0&&o>=0?{row:s,col:o}:null}#k(e,t,n){const i=this.ranges[this.ranges.length-1];if(!i)return;const s=E(i),o="start"===e?{row:s.endRow,col:s.endCol}:{row:s.startRow,col:s.startCol},r=I(o,{row:t,col:n});M(i,r)||(this.ranges[this.ranges.length-1]=r,this.activeRange=r,this.cellAnchor=o,this.emit("selection-change",this.#v()),this.requestAfterRender())}#q(e){if(!e)return;this.#m?this.#w.show(e,this.selected.size,void 0!==this.#x(),{selectAll:()=>this.selectAll(),clear:()=>this.clearSelection(),done:()=>this.exitTouchSelection(),more:e=>this.#I(e)}):this.#w.destroy();const t=this.#f&&"range"===this.#p.primary&&this.ranges.length>0?this.ranges[this.ranges.length-1]:null,n=t?E(t):null;this.#b.render(e,n,(e,t)=>this.#E(e,t),{cellAt:(e,t)=>this.#R(e,t),resize:(e,t,n)=>this.#k(e,t,n),commit:()=>this.requestAfterRender()})}#I(e){const t=this.#x();if(!t)return;const n=e.getBoundingClientRect?.(),i=this.lastSelected??-1;t.showMenu(n?.left??0,n?.bottom??0,{row:i>=0?this.rows[i]:null,rowIndex:i,selectedRows:this.getSelectedRowIndices()})}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{triggerOn:t="click"}=this.config;if(e.originalEvent.type!==t)return!1;switch(this.#p.primary){case"cell":return this.#M(e);case"row":return this.#P(e);case"range":return this.#$(e);default:return!1}}#M(e){const{rowIndex:t,colIndex:n}=e;if(e.column&&y(e.column))return!1;if(!this.isCellSelectable(t,n))return!1;const i=this.selectedCell;return i&&i.row===t&&i.col===n||(this.selectedCell={row:t,col:n},this.emit("selection-change",this.#v()),this.requestAfterRender()),!1}#P(e){const{rowIndex:t,originalEvent:n,column:i}=e;if(!this.isRowSelectable(t))return!1;const s=!1!==this.config.multiSelect,o=n.shiftKey&&s,r=(n.ctrlKey||n.metaKey||this.#m)&&s,l=!0===i?.checkboxColumn;if(o&&null!==this.anchor){const e=Math.min(this.anchor,t),n=Math.max(this.anchor,t);r||this.selected.clear();for(let t=e;t<=n;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(r||l&&s)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender(),!1}#$(e){const{rowIndex:t,colIndex:n,originalEvent:i}=e;if(e.column&&y(e.column))return!1;if(!this.isCellSelectable(t,n))return!1;this.#f=this.#y(i);const s=i.shiftKey,o=(i.ctrlKey||i.metaKey)&&!1!==this.config.multiSelect;if(s&&this.cellAnchor){const e=I(this.cellAnchor,{row:t,col:n}),i=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(i&&M(i,e))return!1;o?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else{const e={startRow:t,startCol:n,endRow:t,endCol:n};if(o)this.ranges.push(e);else{if(1===this.ranges.length&&M(this.ranges[0],e))return!1;this.ranges=[e]}this.activeRange=e,this.cellAnchor={row:t,col:n}}return this.emit("selection-change",this.#v()),this.requestAfterRender(),!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;if(this.#p.columnEnabled&&this.#L(e))return!0;const t=this.#p.primary;if("Escape"===e.key&&this.#m)return this.exitTouchSelection(),!0;if("Escape"===e.key)return this.#_(t);const n=z.includes(e.key);switch(t){case"cell":return!!n&&this.#F();case"row":return this.#K(e);case"range":return this.#T(e,n);default:return!1}}#L(e){if(!e.ctrlKey&&!e.metaKey)return!1;if(" "===e.key||"Spacebar"===e.key){const t=this.visibleColumns[this.grid._focusCol];return!(!t||y(t)||"string"!=typeof t.field)&&(e.preventDefault(),e.stopPropagation(),this.selectColumn(t.field,{toggle:!0}),!0)}if(e.shiftKey&&"column"===this.activeAxis&&!1!==this.config.multiSelect&&("ArrowLeft"===e.key||"ArrowRight"===e.key)){const t=A(this.visibleColumns),n="ArrowLeft"===e.key?"left":"right",i=function(e,t,n){if(0===t.length)return null;if(null===e)return null;const i=x(e,t);if(i<0)return null;const s="left"===n?Math.max(0,i-1):Math.min(t.length-1,i+1);return s===i?null:t[s]}(this.columnHead,t,n);return null!==i&&null!==this.columnAnchor&&(e.preventDefault(),e.stopPropagation(),this.selectColumn(i,{range:!0}),!0)}return!1}#_(e){return!this.grid.query("isEditing").some(Boolean)&&("column"===this.activeAxis?(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none"):"cell"===e?this.selectedCell=null:"row"===e?(this.selected.clear(),this.anchor=null):"range"===e&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#v()),this.requestAfterRender(),!0)}#F(){return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.selectedCell=this.isCellSelectable(e,t)?{row:e,col:t}:null,this.emit("selection-change",this.#v()),this.requestAfterRender()}),!1}#K(e){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key||"PageUp"===e.key||"PageDown"===e.key||(e.ctrlKey||e.metaKey)&&("Home"===e.key||"End"===e.key)){const n=e.shiftKey&&t;return n&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:n},queueMicrotask(()=>this.requestAfterRender()),!1}return this.#D(e,t)}#T(e,t){if(!t)return this.#D(e,!1!==this.config.multiSelect);const n=e.shiftKey&&"Tab"!==e.key;return n&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:n},queueMicrotask(()=>this.requestAfterRender()),!1}#D(e,t){return!(!t||"a"!==e.key||!e.ctrlKey&&!e.metaKey)&&(!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0))}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("row"===this.#p.primary){if(void 0===e.rowIndex||e.rowIndex<0)return;if(!1===this.config.multiSelect)return;if(!this.#y(e.originalEvent))return;if(e.column&&y(e.column))return;return this.#m?(this.#A(e.rowIndex),!0):this.#S(e.rowIndex)||void 0}if("range"!==this.#p.primary)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(this.#f=this.#y(e.originalEvent),2===e.originalEvent.button&&k(e.rowIndex,e.colIndex,this.ranges))return;if(e.column&&y(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,n=e.colIndex,i=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,s={startRow:t,startCol:n,endRow:t,endCol:n};return!i&&1===this.ranges.length&&M(this.ranges[0],s)?(this.cellAnchor={row:t,col:n},!0):(this.cellAnchor={row:t,col:n},i||(this.ranges=[]),this.ranges.push(s),this.activeRange=s,this.emit("selection-change",this.#v()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.#p.primary)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const n=this.visibleColumns[t];if(n&&y(n)){const e=this.visibleColumns.findIndex(e=>!y(e));e>=0&&(t=e)}const i=I(this.cellAnchor,{row:e.rowIndex,col:t}),s=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return s&&M(s,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#v()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.#p.primary)return this.isDragging?(this.isDragging=!1,!0):void 0}onHeaderClick(e){if(!this.isSelectionEnabled())return!1;if(!this.#p.columnEnabled)return!1;if(e.column&&y(e.column))return!1;const t=e.originalEvent;if(!t.ctrlKey&&!t.metaKey)return!1;const n=e.field;if(!n)return!1;t.preventDefault(),"function"==typeof t.stopPropagation&&t.stopPropagation();const i=!0===t.shiftKey&&!1!==this.config.multiSelect&&null!==this.columnAnchor;return this.selectColumn(n,i?{range:!0}:{toggle:!0}),!0}processColumns(e){if(this.config.checkbox&&"row"===this.#p.primary){if(e.some(e=>e.field===D))return e;const t=this.#z(),n=e.findIndex(C),i=n>=0?n+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#z(){return{field:D,header:"",width:32,resizable:!1,sortable:!1,lockPosition:!0,utility:!0,checkboxColumn:!0,headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const n=e.cellEl;if(n){const e=parseInt(n.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#H(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),n=t?a(t):-1;n>=0&&(e.checked=this.selected.has(n))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let n=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&n++;else n=e;const i=n>0&&this.selected.size>=n,s=this.selected.size>0;t.checked=i,t.indeterminate=s&&!i}}#U(){return this.gridElement?.hasAttribute("data-has-focus")??!1}#j(e){const t=this.grid._focusRow,n=this.grid._focusCol;if(!this.#U())return this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=n);if("row"===e){if(this.explicitSelection)return this.explicitSelection=!1,void(this.lastSyncedFocusRow=t);t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(this.selected.has(t)&&1===this.selected.size||(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#v()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=n);if((t!==this.lastSyncedFocusRow||n!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=n,this.isCellSelectable(t,n))){const e=this.selectedCell;e&&e.row===t&&e.col===n||(this.selectedCell={row:t,col:n},this.emit("selection-change",this.#v()))}}}#N(){const t=this.gridElement;if(!t)return;const n=this.#p.primary,i=this.#p.columnEnabled,s=!!this.config.isSelectable,o=t.querySelector(".rows-body");if(o){const e=!1!==this.config.multiSelect;o.setAttribute("aria-multiselectable",e?"true":"false")}t.querySelectorAll(".cell").forEach(t=>{const n=t.classList.contains(e)||t.classList.contains("column-selected");t.classList.remove(e,"top","bottom","first","last","column-selected"),n&&t.removeAttribute("aria-selected"),s&&t.removeAttribute("data-selectable")});const r=t.querySelectorAll(".data-grid-row");if(r.forEach(t=>{t.classList.remove(e,"row-focus"),t.setAttribute("aria-selected","false"),s&&t.removeAttribute("data-selectable")}),i&&t.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("column-selected"),e.removeAttribute("aria-selected")}),"row"===n&&(d(t),r.forEach(t=>{const n=a(t.querySelector(".cell[data-row]"));n>=0&&(s&&!this.isRowSelectable(n)&&t.setAttribute("data-selectable","false"),this.selected.has(n)&&(t.classList.add(e,"row-focus"),t.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#H(t)),"cell"!==n&&"range"!==n||!s||t.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),n=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&n>=0&&(this.isCellSelectable(t,n)||e.setAttribute("data-selectable","false"))}),"range"===n&&this.ranges.length>0){d(t);const n=this.ranges.map(E),i=(e,t)=>{for(const i of n)if(e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol)return!0;return!1};t.querySelectorAll(".cell[data-row][data-col]").forEach(t=>{const n=parseInt(t.getAttribute("data-row")??"-1",10),s=parseInt(t.getAttribute("data-col")??"-1",10);if(n>=0&&s>=0){const o=this.visibleColumns[s];if(o&&y(o))return;i(n,s)&&(t.classList.add(e),t.setAttribute("aria-selected","true"),i(n-1,s)||t.classList.add("top"),i(n+1,s)||t.classList.add("bottom"),i(n,s-1)||t.classList.add("first"),i(n,s+1)||t.classList.add("last"))}})}if(i&&this.selectedColumns.size>0){const e=this.visibleColumns.map(e=>"string"==typeof e.field?e.field:void 0);t.querySelectorAll(".header-row > .cell[data-col]").forEach(t=>{const n=parseInt(t.getAttribute("data-col")??"-1",10),i=n>=0?e[n]:void 0;i&&this.selectedColumns.has(i)&&(t.classList.add("column-selected"),t.setAttribute("aria-selected","true"))}),t.querySelectorAll(".cell[data-col]:not(.header-row .cell)").forEach(t=>{if(t.closest(".header-row"))return;const n=parseInt(t.getAttribute("data-col")??"-1",10);if(n<0)return;const i=this.visibleColumns[n];if(!i||y(i))return;const s=e[n];s&&this.selectedColumns.has(s)&&(t.classList.add("column-selected"),t.setAttribute("aria-selected","true"))})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root"),n=this.#p.primary;if(this.pendingRowKeyUpdate&&"row"===n){const{shiftKey:e}=this.pendingRowKeyUpdate;this.pendingRowKeyUpdate=null;const t=this.grid._focusRow;if(e&&null!==this.anchor){this.selected.clear();const e=Math.min(this.anchor,t),n=Math.max(this.anchor,t);for(let t=e;t<=n;t++)this.isRowSelectable(t)&&this.selected.add(t)}else this.isRowSelectable(t)?(this.selected.clear(),this.selected.add(t),this.anchor=t):this.selected.clear();this.lastSelected=t,this.emit("selection-change",this.#v())}if(this.pendingKeyboardUpdate&&"range"===n){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,n=this.grid._focusCol;if(e&&this.cellAnchor){const e=I(this.cellAnchor,{row:t,col:n});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:n});this.emit("selection-change",this.#v())}this.#j(n),this.gridElement.setAttribute("data-selection-mode",n),t&&t.classList.toggle("selecting",this.isDragging),this.#N(),this.#q(t)}onScrollRender(){this.isSelectionEnabled()&&this.#N()}getSelection(){const e=this.#v();return{mode:this.config.mode,activeAxis:e.activeAxis,ranges:e.ranges,selectedColumns:e.selectedColumns,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=/* @__PURE__ */new Map;for(const n of e)for(const e of q(n))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return k(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const n={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[n],this.activeRange=n,this.emit("selection-change",this.#v()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.#p.primary)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const n of t)n>=0&&n<this.rows.length&&this.isRowSelectable(n)&&this.selected.add(n);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const e=this.#p.primary,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=/* @__PURE__ */new Set;for(const n of this.ranges){const i=Math.max(0,Math.min(n.startRow,n.endRow)),s=Math.min(t.length-1,Math.max(n.startRow,n.endRow));for(let t=i;t<=s;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}#C(e){if(!this.#p.columnEnabled)return;const t=A(this.visibleColumns),n=new Set(t),i=[],s=/* @__PURE__ */new Set;for(const r of e)n.has(r)&&!s.has(r)&&(s.add(r),i.push(r));this.#O("column"),this.selectedColumns.clear();for(const r of i)this.selectedColumns.add(r);const o=i.length>0?i[i.length-1]:null;this.columnAnchor=o,this.columnHead=o,this.activeAxis=this.selectedColumns.size>0?"column":"none",this.emit("selection-change",this.#v()),this.requestAfterRender()}selectColumn(e,t={}){if(!this.#p.columnEnabled)return;const n=A(this.visibleColumns);if(n.includes(e)){if(this.#O("column"),!1===this.config.multiSelect)this.selectedColumns.clear(),this.selectedColumns.add(e),this.columnAnchor=e,this.columnHead=e;else if(t.range&&this.columnAnchor){const t=function(e,t,n){const i=x(e,n),s=x(t,n);if(-1===i||-1===s)return[];const o=Math.min(i,s),r=Math.max(i,s);return n.slice(o,r+1)}(this.columnAnchor,e,n);this.selectedColumns.clear();for(const e of t)this.selectedColumns.add(e);this.columnHead=e}else t.toggle?(this.selectedColumns.has(e)?this.selectedColumns.delete(e):this.selectedColumns.add(e),this.columnAnchor=e,this.columnHead=e):(this.selectedColumns.clear(),this.selectedColumns.add(e),this.columnAnchor=e,this.columnHead=e);this.activeAxis=this.selectedColumns.size>0?"column":"none",this.emit("selection-change",this.#v()),this.requestAfterRender()}}deselectColumn(e){this.#p.columnEnabled&&this.selectedColumns.delete(e)&&(0===this.selectedColumns.size&&(this.columnAnchor=null,this.columnHead=null,"column"===this.activeAxis&&(this.activeAxis="none")),this.emit("selection-change",this.#v()),this.requestAfterRender())}selectAllColumns(){if(!this.#p.columnEnabled)return;if(!1===this.config.multiSelect)return;const e=A(this.visibleColumns);if(0!==e.length){this.#O("column"),this.selectedColumns.clear();for(const t of e)this.selectedColumns.add(t);this.columnAnchor=e[0],this.columnHead=e[e.length-1],this.activeAxis="column",this.emit("selection-change",this.#v()),this.requestAfterRender()}}clearColumnSelection(){0!==this.selectedColumns.size&&(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,"column"===this.activeAxis&&(this.activeAxis="none"),this.emit("selection-change",this.#v()),this.requestAfterRender())}getSelectedColumns(){return 0===this.selectedColumns.size?[]:A(this.visibleColumns).filter(e=>this.selectedColumns.has(e))}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none",this.emit("selection-change",this.#v()),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",this.#v()),this.requestAfterRender()}#v(){const e=this.#p.primary,t="row"===e&&this.selected.size>0||"cell"===e&&null!==this.selectedCell||"range"===e&&this.ranges.length>0;let n;this.#p.bothAxes&&t&&this.selectedColumns.size>0&&(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.gridElement&&i(this.gridElement,s(this.gridElement,"selectionAxisChanged","row"))),n=t?"row"===e?"row":"cell"===e?"cell":"range":this.selectedColumns.size>0?"column":"none",this.activeAxis=n;const o=function(e,t,n,i,s,o){if("column"===t&&i.selectedColumns.size>0)return{mode:e,activeAxis:"column",ranges:[],selectedColumns:o.filter(e=>i.selectedColumns.has(e))};if("cell"===n&&i.selectedCell)return{mode:e,activeAxis:"cell",ranges:[{from:{row:i.selectedCell.row,col:i.selectedCell.col},to:{row:i.selectedCell.row,col:i.selectedCell.col}}],selectedColumns:[]};if("row"===n&&i.selected.size>0){const t=[...i.selected].sort((e,t)=>e-t),n=[];let o=t[0],r=o;for(let e=1;e<t.length;e++)t[e]===r+1?r=t[e]:(n.push({from:{row:o,col:0},to:{row:r,col:s-1}}),o=t[e],r=o);return n.push({from:{row:o,col:0},to:{row:r,col:s-1}}),{mode:e,activeAxis:"row",ranges:n,selectedColumns:[]}}return"range"===n&&i.ranges.length>0?{mode:e,activeAxis:"range",ranges:(r=i.ranges,r.map(R)),selectedColumns:[]}:{mode:e,activeAxis:"none",ranges:[],selectedColumns:[]};var r}(this.config.mode,n,e,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges,selectedColumns:this.selectedColumns},this.columns.length,A(this.visibleColumns));return this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{if("column"===o.activeAxis){const e=o.selectedColumns;if(1===e.length){const t=e[0],n=this.columns.find(e=>e.field===t),o="string"==typeof n?.header&&n.header||t;i(this.gridElement,s(this.gridElement,"columnSelected",o))}else e.length>1?i(this.gridElement,s(this.gridElement,"columnSelectionChanged",e.length)):i(this.gridElement,s(this.gridElement,"columnSelectionCleared"))}else{const e="row"===o.activeAxis?this.selected.size:o.ranges.length;e>0&&i(this.gridElement,s(this.gridElement,"selectionChanged",e))}},150),o}#O(e){if(this.#p.bothAxes&&"column"===e){if(!(this.selected.size>0||null!==this.selectedCell||this.ranges.length>0))return;this.selected.clear(),this.lastSelected=null,this.anchor=null,this.selectedCell=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.gridElement&&i(this.gridElement,s(this.gridElement,"selectionAxisChanged","column"))}}};export{H as SelectionPlugin};
1
+ var e="selected",t={sortApplied:(e,t)=>`Sorted by ${e}, ${t}`,sortCleared:()=>"Sort cleared",filterApplied:e=>`Filter applied on ${e}`,filterCleared:e=>`Filter cleared from ${e}`,allFiltersCleared:()=>"All filters cleared",groupExpanded:(e,t)=>`Group ${e} expanded, ${t} rows`,groupCollapsed:e=>`Group ${e} collapsed`,selectionChanged:e=>`${e} rows selected`,columnSelected:e=>`Column ${e} selected`,columnSelectionChanged:e=>`${e} columns selected`,columnSelectionCleared:()=>"Column selection cleared",selectionAxisChanged:e=>"column"===e?"Row selection cleared, column selection active":"Column selection cleared, row selection active",editingStarted:e=>`Editing row ${e+1}`,editingCommitted:e=>`Row ${e+1} saved`,dataLoaded:e=>`${e} rows loaded`},n={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};function i(e,t){if(!e)return;if(!1===("effectiveConfig"in e?e.effectiveConfig:void 0)?.a11y?.announcements)return;const n=e.querySelector?.(".tbw-sr-only");n&&(n.textContent="","function"==typeof requestAnimationFrame?requestAnimationFrame(()=>{n.textContent=t}):n.textContent=t)}function s(e,n,...i){const s=(e&&"effectiveConfig"in e?e.effectiveConfig:void 0)?.a11y?.messages?.[n];return s?s(...i):t[n](...i)}var o=null,r=/* @__PURE__ */new Set;function l(e){const t=e.matches?"coarse":"fine";r.forEach(e=>e(t))}function c(){const e=o||("function"!=typeof globalThis.matchMedia?null:("function"==typeof(o=globalThis.matchMedia("(pointer: coarse)")).addEventListener?o.addEventListener("change",l):"function"==typeof o.addListener&&o.addListener(l),o));return e?function(e){return e.matches?"coarse":"fine"}(e):"fine"}function a(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const n=e.closest(".data-grid-row");if(!n)return-1;const i=n.parentElement;if(!i)return-1;const s=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<s.length;o++)if(s[o]===n)return o;return-1}function d(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function h(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function u(e,t,n,i){return`${h(n,i)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}var g="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(e=>e.split("").reverse().join("")),m=(new RegExp(`__(proto|defineGetter|defineSetter)|${g.slice(3).join("|")}|this\\b`),new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math".split("|"))),f=/^on\w+$/i,w=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),b=/^\s*(javascript|vbscript|data|blob):/i;function p(e){const t=document.createElement("template");return e&&"string"==typeof e&&(t.innerHTML=e,function(e){const t=[],n=e.querySelectorAll("*");for(const i of n){const e=i.tagName.toLowerCase();if(m.has(e)){t.push(i);continue}if(("svg"===e||"http://www.w3.org/2000/svg"===i.namespaceURI)&&Array.from(i.attributes).some(e=>f.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(i);continue}const n=[];for(const t of i.attributes){const e=t.name.toLowerCase();f.test(e)?n.push(t.name):"is"!==e?(w.has(e)&&b.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&n.push(t.name):n.push(t.name)}n.forEach(e=>i.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content)),t.content}var v=class{static dependencies;static manifest;aliases;version="3.5.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},n={};for(const i of Object.keys(t))n[i]=this;for(const i of e){const e=i.userConfig;for(const[s,o]of Object.entries(e)){if(void 0===o)continue;if(!(s in t)){t[s]=o,n[s]=i;continue}if(t[s]===o)continue;const e=n[s]?.constructor.name??this.constructor.name,r=i.constructor.name,l=u("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${s}" supplied by both ${e} and ${r}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,n={...e.userConfig};for(const i of Object.keys(t))delete t[i];Object.assign(t,n)}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(n),n.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}broadcast(e,t){this.emitPluginEvent(e,t),this.emit(e,t)}queryBoolean(e,t=null){const n=this.grid?.query?.(e,t);return Array.isArray(n)?n.some(Boolean):!!n}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...n,...e}}t(e,t){return this.grid?.effectiveConfig?.locale?.[e]??t}get translate(){return(e,t)=>this.t(e,t)}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;return!t||"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),n=parseInt(t,10);if(!isNaN(n))return n}return 200}setIcon(e,t,n){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const i=this.#t(t,n);var s,o;void 0!==i?"string"==typeof i?(s=e,(o=i)&&"string"==typeof o?-1!==o.indexOf("<")||-1!==o.indexOf("&")?s.replaceChildren(p(o)):s.textContent=o:s.replaceChildren()):i instanceof HTMLElement&&e.replaceChildren(i.cloneNode(!0)):e.innerHTML=""}#t(e,t){return void 0!==t?t:this.grid?.gridConfig?.icons?.[e]}updateSortIndicator(e,t){e.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const n=document.createElement("span");n.setAttribute("part","sort-indicator"),n.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(n,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(n,"sortNone"));const i=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return i?e.insertBefore(n,i):e.appendChild(n),n}warn(e,t){void 0!==t?console.warn(u(e,t,this.gridElement.id,this.name)):console.warn(`${h(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(u(e,t,this.gridElement.id,this.name))}};function C(e){return"__tbw_expander"===e.field}function y(e){return!0===e.utility}function S(e){const t=/* @__PURE__ */new Set(["cell","row","column","range"]);if("string"==typeof e){if(!t.has(e))throw new Error(`[SelectionPlugin] Invalid selection mode: "${e}". Expected one of: 'cell' | 'row' | 'column' | 'range'.`);return{primary:e,columnEnabled:"column"===e,bothAxes:!1}}if(!Array.isArray(e))throw new Error(`[SelectionPlugin] Invalid selection mode: expected string or array, got ${typeof e}.`);if(0===e.length)throw new Error("[SelectionPlugin] Invalid selection mode: array must contain at least one mode.");for(const i of e)if(!t.has(i))throw new Error(`[SelectionPlugin] Invalid selection mode in array: "${i}". Expected one of: 'cell' | 'row' | 'column' | 'range'.`);if(new Set(e).size!==e.length)throw new Error(`[SelectionPlugin] Invalid selection mode: array contains duplicate entries (${e.join(", ")}).`);if(1===e.length)return S(e[0]);if(e.length>2)throw new Error(`[SelectionPlugin] Invalid selection mode: arrays of more than 2 modes are not supported. Got [${e.join(", ")}].`);if(!e.includes("column"))throw new Error(`[SelectionPlugin] Invalid selection mode: [${e.join(", ")}]. Two-mode arrays must include 'column' (the only valid combinations are ['row','column'], ['cell','column'], ['range','column']). Other in-row modes don't compose meaningfully.`);const n=e.find(e=>"column"!==e);if("column"===n)throw new Error(`[SelectionPlugin] Invalid selection mode: [${e.join(", ")}].`);return{primary:n,columnEnabled:!0,bothAxes:!0}}function A(e){const t=[];for(const n of e)!0!==n.utility&&"string"==typeof n.field&&n.field.length>0&&t.push(n.field);return t}function x(e,t){return t.indexOf(e)}function E(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function R(e){const t=E(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function k(e,t,n){return n.some(n=>function(e,t,n){const i=E(n);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,n))}function q(e){const t=[],n=E(e);for(let i=n.startRow;i<=n.endRow;i++)for(let e=n.startCol;e<=n.endCol;e++)t.push({row:i,col:e});return t}function I(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function M(e,t){const n=E(e),i=E(t);return n.startRow===i.startRow&&n.startCol===i.startCol&&n.endRow===i.endRow&&n.endCol===i.endCol}var P=/* @__PURE__ */new WeakMap;function $(e,t,n,i){const{onMove:s,onEnd:o,onCancel:r,onPromote:l}=n,c=i?.threshold??0,a=i?.longPressDuration??0,d=i?.longPressSlop??8,h=e.pointerId;if(!function(e,t){let n=P.get(e);return n||(n=/* @__PURE__ */new Set,P.set(e,n)),!n.has(t)&&(n.add(t),!0)}(t,h))return()=>{};const u=e.clientX,g=e.clientY;let m=0===c&&0===a,f=!1,w=null,b=!1;function p(){return m=!0,function(){try{return t.setPointerCapture(h),!0}catch{return b=!0,!1}}()?(l?.(),!0):(C(),!1)}function v(){if(!f){var e,n;f=!0,null!==w&&(clearTimeout(w),w=null),t.removeEventListener("pointermove",y),t.removeEventListener("pointerup",S),t.removeEventListener("pointercancel",A),t.removeEventListener("lostpointercapture",x),document.removeEventListener("keydown",E,!0),e=t,n=h,P.get(e)?.delete(n);try{t.hasPointerCapture(h)&&t.releasePointerCapture(h)}catch{}}}function C(){f||(v(),r?.())}function y(e){const t=e;if(t.pointerId!==h||f)return;const n=t.clientX-u,i=t.clientY-g,o=Math.sqrt(n*n+i*i);if(!m){if(a>0)return o>d?void C():void 0;if(c>0&&o<c)return;if(!p())return}s(t)}function S(e){const t=e;if(t.pointerId!==h||f)return;const n=m;v(),n?o(t):r?.()}function A(e){e.pointerId!==h||f||C()}function x(e){e.pointerId!==h||f||C()}function E(e){"Escape"!==e.key||f||C()}return t.addEventListener("pointermove",y),t.addEventListener("pointerup",S),t.addEventListener("pointercancel",A),t.addEventListener("lostpointercapture",x),document.addEventListener("keydown",E,!0),m&&(p(),b)?()=>{}:(a>0&&(w=setTimeout(()=>{w=null,f||p()},a)),C)}var L="tbw-selection-toolbar",_=class{#n=null;#i=null;#s=null;#o=null;get mounted(){return null!==this.#n}get element(){return this.#n}show(e,t,n,i){this.#o=i,this.#n||this.#r(e),this.#i&&(this.#i.textContent=`${t} selected`),this.#n?.setAttribute("data-selected-count",String(t)),this.#s&&(this.#s.hidden=!n)}destroy(){this.#n?.remove(),this.#n=null,this.#i=null,this.#s=null,this.#o=null}#r(e){const t=e.ownerDocument.createElement("div");t.className=L,t.setAttribute("role","toolbar"),t.setAttribute("aria-label","Selection");const n=e.ownerDocument.createElement("span");n.className=`${L}-count`,n.setAttribute("aria-live","polite"),t.appendChild(n);const i=e.ownerDocument.createElement("div");i.className=`${L}-actions`,t.appendChild(i),i.appendChild(this.#l(e,"select-all","Select all",()=>this.#o?.selectAll())),i.appendChild(this.#l(e,"clear","Clear",()=>this.#o?.clear()));const s=this.#l(e,"more","More…",e=>this.#o?.more(e));s.setAttribute("aria-haspopup","menu"),i.appendChild(s),i.appendChild(this.#l(e,"done","Done",()=>this.#o?.done())),e.prepend(t),this.#n=t,this.#i=n,this.#s=s}#l(e,t,n,i){const s=e.ownerDocument.createElement("button");return s.type="button",s.className=`${L}-btn`,s.dataset.action=t,s.textContent=n,s.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),i(s)}),s}},F="tbw-range-handle",K=class{#c=null;#a=null;#o=null;render(e,t,n,i){this.#o=i,t?(this.#c??=this.#d(e,"start"),this.#a??=this.#d(e,"end"),this.#h(e,this.#c,n(t.startRow,t.startCol),"start"),this.#h(e,this.#a,n(t.endRow,t.endCol),"end")):this.#u()}destroy(){this.#c?.remove(),this.#a?.remove(),this.#c=null,this.#a=null,this.#o=null}#u(){this.#c&&(this.#c.hidden=!0),this.#a&&(this.#a.hidden=!0)}#h(e,t,n,i){if(!t)return;if(!n)return void(t.hidden=!0);t.hidden=!1;const s=n.getBoundingClientRect?.(),o=e.getBoundingClientRect?.();if(!s||!o)return;const r="start"===i?s.left-o.left:s.right-o.left,l="start"===i?s.top-o.top:s.bottom-o.top;t.style.left=`${r}px`,t.style.top=`${l}px`}#d(e,t){const n=e.ownerDocument.createElement("div");return n.className=`${F} ${F}-${t}`,n.dataset.corner=t,n.setAttribute("role","presentation"),n.addEventListener("pointerdown",e=>this.#g(e,n,t)),e.appendChild(n),n}#g(e,t,n){if(0!==e.button&&"mouse"===e.pointerType)return;e.preventDefault(),e.stopPropagation();const i=this.#o;if(!i)return;t.classList.add("dragging");const s=()=>{t.classList.remove("dragging"),i.commit()};$(e,t,{onMove:e=>{const t=i.cellAt(e.clientX,e.clientY);t&&i.resize(n,t.row,t.col)},onEnd:s,onCancel:s})}};function T(e){if("string"==typeof e)return e;if(Array.isArray(e)){const t=e.find(e=>"column"!==e);if(t)return t;if(e.includes("column"))return"column"}return"cell"}var D="__tbw_checkbox",z=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"];var H=class extends v{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"},{type:"getSelectedColumns",description:"Get field names of selected columns (column mode only)"},{type:"selectColumns",description:"Select specific columns by field name (column mode only)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===T(e.mode)&&"dblclick"===e.triggerOn},{id:"selection/column-checkbox",severity:"warn",message:'"checkbox: true" only renders in row mode.\n → Column selection has no checkbox UI; activate columns via Ctrl+Click on a header or Ctrl+Space on a focused cell.',check:e=>!!e.checkbox&&"row"!==T(e.mode)}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}:is(tbw-grid:has(.selection)[data-selection-mode=row] .cell-focus,tbw-grid:has(.selection)[data-selection-mode=row] .row-focus,tbw-grid:has(.selection)[data-selection-mode=range] .cell-focus){outline:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background,rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style,var(--tbw-border-style));border-color:var(--tbw-range-border-color,var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width,var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width,var(--tbw-border-width));z-index:26;position:absolute;inset:0}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid .data-grid-row.row-focus>.cell.sticky-left,tbw-grid .data-grid-row.row-focus>.cell.sticky-right{background:linear-gradient(var(--tbw-focus-background,rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0), var(--tbw-color-panel-bg)}tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-left,tbw-grid .data-grid-row.row-focus[data-selectable=false]>.cell.sticky-right{background:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";pointer-events:none;border:0 var(--tbw-selection-border-style,var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1;position:absolute;inset:0}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width,var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg,rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm,.8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;justify-content:center;align-items:center;padding:0;display:flex}tbw-grid .tbw-select-row-checkbox{pointer-events:none;cursor:pointer;margin:0}tbw-grid .tbw-checkbox-header{justify-content:center;align-items:center;height:100%;display:flex}tbw-grid .tbw-select-all-checkbox{cursor:pointer;margin:0}@media (pointer:coarse){tbw-grid .tbw-select-row-checkbox,tbw-grid .tbw-select-all-checkbox{min-width:var(--tbw-touch-target-min,24px);min-height:var(--tbw-touch-target-min,24px)}}tbw-grid .header-row>.cell.column-selected,tbw-grid .data-grid-row>.cell.column-selected,tbw-grid .data-grid-row>.cell.column-selected.sticky-left,tbw-grid .data-grid-row>.cell.column-selected.sticky-right,tbw-grid .header-row>.cell.column-selected.sticky-left,tbw-grid .header-row>.cell.column-selected.sticky-right{background:linear-gradient(var(--tbw-column-selection-bg,rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0), var(--tbw-color-panel-bg)}tbw-grid .tbw-selection-toolbar{z-index:30;background:var(--tbw-color-panel-bg);border-bottom:1px solid var(--tbw-color-border);justify-content:space-between;align-items:center;gap:8px;padding:4px 8px;font-size:13px;display:flex;position:sticky;top:0}tbw-grid .tbw-selection-toolbar-count{white-space:nowrap;font-weight:600}tbw-grid .tbw-selection-toolbar-actions{align-items:center;gap:4px;display:flex}tbw-grid .tbw-selection-toolbar-btn{min-height:var(--tbw-touch-target-min,24px);border-radius:var(--tbw-border-radius,4px);color:inherit;font:inherit;cursor:pointer;background:0 0;border:0;padding:0 10px}tbw-grid .tbw-selection-toolbar-btn:hover,tbw-grid .tbw-selection-toolbar-btn:focus-visible{background:var(--tbw-color-hover-bg)}tbw-grid .tbw-selection-toolbar-btn[data-action=done]{color:var(--tbw-color-accent);font-weight:600}tbw-grid .tbw-range-handle{z-index:25;width:var(--tbw-touch-target-min,24px);height:var(--tbw-touch-target-min,24px);background:radial-gradient(circle, var(--tbw-color-accent) 0 5px, transparent 5px);cursor:crosshair;touch-action:none;position:absolute;translate:-50% -50%}tbw-grid .tbw-range-handle[hidden]{display:none}tbw-grid .tbw-range-handle.dragging{scale:1.3}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0,touchMode:"transient"}}get touchSelectionActive(){return this.#m}#m=!1;#f=!1;#w=new _;#b=new K;selected=/* @__PURE__ */new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;pendingRowKeyUpdate=null;selectedCell=null;selectedColumns=/* @__PURE__ */new Set;columnAnchor=null;columnHead=null;activeAxis="none";#p={primary:"cell",columnEnabled:!1,bothAxes:!1};lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;announceTimer=null;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:n}=this.config;if(!n)return!0;const i=this.rows[e];return!!i&&n(i,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.#p=S(this.config.mode),this.on("filter-change",()=>this.clearSelectionSilent()),this.on("group-toggle",()=>this.clearSelectionSilent()),this.on("tree-expand",()=>this.clearSelectionSilent()),this.on("sort-change",()=>this.clearSelectionSilent()),this.on("edit-open",({rowIndex:e,row:t})=>{this.isSelectionEnabled()&&(null==t||e<0||"row"===this.#p.primary&&this.isRowSelectable(e)&&(this.selected.has(e)||(!1===this.config.multiSelect&&this.selected.clear(),this.selected.add(e),this.lastSelected=e,this.anchor=e,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender())))});let t=-1;e.addEventListener("data-change",e=>{const{sourceRowCount:n}=e.detail,i=this.selected.size>0||this.ranges.length>0||null!==this.selectedCell;-1!==t&&n!==t&&i&&this.clearSelectionSilent(),t=n},{signal:this.disconnectSignal})}handleQuery(e){if("getSelection"===e.type)return this.getSelection();if("getSelectedRowIndices"===e.type)return this.getSelectedRowIndices();if("getSelectedRows"===e.type)return this.getSelectedRows();if("selectRows"===e.type)return this.selectRows(e.context),!0;if("getSelectedColumns"===e.type)return this.getSelectedColumns();if("selectColumns"===e.type){const t=e.context;return this.#C(t),!0}}detach(){(this.gridElement?.querySelector(".rows-body"))?.removeAttribute("aria-multiselectable"),this.#w.destroy(),this.#b.destroy(),this.#m=!1,this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none",this.pendingKeyboardUpdate=null,this.pendingRowKeyUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.announceTimer&&(clearTimeout(this.announceTimer),this.announceTimer=null)}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,"column"!==this.activeAxis&&(this.activeAxis="none"),this.requestAfterRender()}#y(e){const t=e.pointerType;return"touch"===t||"pen"===t||"mouse"!==t&&"coarse"===c()}#S(e){return!!this.isRowSelectable(e)&&(this.#m=!0,this.selected.clear(),this.selected.add(e),this.anchor=e,this.lastSelected=e,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender(),!0)}exitTouchSelection(){this.#m&&(this.#m=!1,"transient"===(this.config.touchMode??"transient")&&(this.selected.clear(),this.anchor=null,this.lastSelected=null,this.emit("selection-change",this.#v())),this.requestAfterRender())}#A(e){const t=this.anchor??e,n=Math.min(t,e),i=Math.max(t,e);for(let s=n;s<=i;s++)this.isRowSelectable(s)&&this.selected.add(s);this.lastSelected=e,this.emit("selection-change",this.#v()),this.requestAfterRender()}#x(){const e=this.grid?.getPluginByName?.("contextMenu")??this.grid?.getPluginByName?.("context-menu");return"function"==typeof e?.showMenu?e:void 0}#E(e,t){return this.gridElement?.querySelector(`.cell[data-row="${e}"][data-col="${t}"]`)??null}#R(e,t){const n=this.gridElement,i=((n?.ownerDocument)?.elementFromPoint?.(e,t))?.closest?.(".cell[data-row][data-col]");if(!i||!n?.contains?.(i))return null;const s=parseInt(i.getAttribute("data-row")??"-1",10),o=parseInt(i.getAttribute("data-col")??"-1",10);return s>=0&&o>=0?{row:s,col:o}:null}#k(e,t,n){const i=this.ranges[this.ranges.length-1];if(!i)return;const s=E(i),o="start"===e?{row:s.endRow,col:s.endCol}:{row:s.startRow,col:s.startCol},r=I(o,{row:t,col:n});M(i,r)||(this.ranges[this.ranges.length-1]=r,this.activeRange=r,this.cellAnchor=o,this.emit("selection-change",this.#v()),this.requestAfterRender())}#q(e){if(!e)return;this.#m?this.#w.show(e,this.selected.size,void 0!==this.#x(),{selectAll:()=>this.selectAll(),clear:()=>this.clearSelection(),done:()=>this.exitTouchSelection(),more:e=>this.#I(e)}):this.#w.destroy();const t=this.#f&&"range"===this.#p.primary&&this.ranges.length>0?this.ranges[this.ranges.length-1]:null,n=t?E(t):null;this.#b.render(e,n,(e,t)=>this.#E(e,t),{cellAt:(e,t)=>this.#R(e,t),resize:(e,t,n)=>this.#k(e,t,n),commit:()=>this.requestAfterRender()})}#I(e){const t=this.#x();if(!t)return;const n=e.getBoundingClientRect?.(),i=this.lastSelected??-1;t.showMenu(n?.left??0,n?.bottom??0,{row:i>=0?this.rows[i]:null,rowIndex:i,selectedRows:this.getSelectedRowIndices()})}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{triggerOn:t="click"}=this.config;if(e.originalEvent.type!==t)return!1;switch(this.#p.primary){case"cell":return this.#M(e);case"row":return this.#P(e);case"range":return this.#$(e);default:return!1}}#M(e){const{rowIndex:t,colIndex:n}=e;if(e.column&&y(e.column))return!1;if(!this.isCellSelectable(t,n))return!1;const i=this.selectedCell;return i&&i.row===t&&i.col===n||(this.selectedCell={row:t,col:n},this.emit("selection-change",this.#v()),this.requestAfterRender()),!1}#P(e){const{rowIndex:t,originalEvent:n,column:i}=e;if(!this.isRowSelectable(t))return!1;const s=!1!==this.config.multiSelect,o=n.shiftKey&&s,r=(n.ctrlKey||n.metaKey||this.#m)&&s,l=!0===i?.checkboxColumn;if(o&&null!==this.anchor){const e=Math.min(this.anchor,t),n=Math.max(this.anchor,t);r||this.selected.clear();for(let t=e;t<=n;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(r||l&&s)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender(),!1}#$(e){const{rowIndex:t,colIndex:n,originalEvent:i}=e;if(e.column&&y(e.column))return!1;if(!this.isCellSelectable(t,n))return!1;this.#f=this.#y(i);const s=i.shiftKey,o=(i.ctrlKey||i.metaKey)&&!1!==this.config.multiSelect;if(s&&this.cellAnchor){const e=I(this.cellAnchor,{row:t,col:n}),i=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(i&&M(i,e))return!1;o?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else{const e={startRow:t,startCol:n,endRow:t,endCol:n};if(o)this.ranges.push(e);else{if(1===this.ranges.length&&M(this.ranges[0],e))return!1;this.ranges=[e]}this.activeRange=e,this.cellAnchor={row:t,col:n}}return this.emit("selection-change",this.#v()),this.requestAfterRender(),!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;if(this.#p.columnEnabled&&this.#L(e))return!0;const t=this.#p.primary;if("Escape"===e.key&&this.#m)return this.exitTouchSelection(),!0;if("Escape"===e.key)return this.#_(t);const n=z.includes(e.key);switch(t){case"cell":return!!n&&this.#F();case"row":return this.#K(e);case"range":return this.#T(e,n);default:return!1}}#L(e){if(!e.ctrlKey&&!e.metaKey)return!1;if(" "===e.key||"Spacebar"===e.key){const t=this.visibleColumns[this.grid._focusCol];return!(!t||y(t)||"string"!=typeof t.field)&&(e.preventDefault(),e.stopPropagation(),this.selectColumn(t.field,{toggle:!0}),!0)}if(e.shiftKey&&"column"===this.activeAxis&&!1!==this.config.multiSelect&&("ArrowLeft"===e.key||"ArrowRight"===e.key)){const t=A(this.visibleColumns),n="ArrowLeft"===e.key?"left":"right",i=function(e,t,n){if(0===t.length)return null;if(null===e)return null;const i=x(e,t);if(i<0)return null;const s="left"===n?Math.max(0,i-1):Math.min(t.length-1,i+1);return s===i?null:t[s]}(this.columnHead,t,n);return null!==i&&null!==this.columnAnchor&&(e.preventDefault(),e.stopPropagation(),this.selectColumn(i,{range:!0}),!0)}return!1}#_(e){return!this.grid.query("isEditing").some(Boolean)&&("column"===this.activeAxis?(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none"):"cell"===e?this.selectedCell=null:"row"===e?(this.selected.clear(),this.anchor=null):"range"===e&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#v()),this.requestAfterRender(),!0)}#F(){return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.selectedCell=this.isCellSelectable(e,t)?{row:e,col:t}:null,this.emit("selection-change",this.#v()),this.requestAfterRender()}),!1}#K(e){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key||"PageUp"===e.key||"PageDown"===e.key||(e.ctrlKey||e.metaKey)&&("Home"===e.key||"End"===e.key)){const n=e.shiftKey&&t;return n&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:n},queueMicrotask(()=>this.requestAfterRender()),!1}return this.#D(e,t)}#T(e,t){if(!t)return this.#D(e,!1!==this.config.multiSelect);const n=e.shiftKey&&"Tab"!==e.key;return n&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:n},queueMicrotask(()=>this.requestAfterRender()),!1}#D(e,t){return!(!t||"a"!==e.key||!e.ctrlKey&&!e.metaKey)&&(!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0))}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("row"===this.#p.primary){if(void 0===e.rowIndex||e.rowIndex<0)return;if(!1===this.config.multiSelect)return;if(!this.#y(e.originalEvent))return;if(e.column&&y(e.column))return;return this.#m?(this.#A(e.rowIndex),!0):this.#S(e.rowIndex)||void 0}if("range"!==this.#p.primary)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(this.#f=this.#y(e.originalEvent),2===e.originalEvent.button&&k(e.rowIndex,e.colIndex,this.ranges))return;if(e.column&&y(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,n=e.colIndex,i=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,s={startRow:t,startCol:n,endRow:t,endCol:n};return!i&&1===this.ranges.length&&M(this.ranges[0],s)?(this.cellAnchor={row:t,col:n},!0):(this.cellAnchor={row:t,col:n},i||(this.ranges=[]),this.ranges.push(s),this.activeRange=s,this.emit("selection-change",this.#v()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.#p.primary)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const n=this.visibleColumns[t];if(n&&y(n)){const e=this.visibleColumns.findIndex(e=>!y(e));e>=0&&(t=e)}const i=I(this.cellAnchor,{row:e.rowIndex,col:t}),s=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return s&&M(s,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#v()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.#p.primary)return this.isDragging?(this.isDragging=!1,!0):void 0}onHeaderClick(e){if(!this.isSelectionEnabled())return!1;if(!this.#p.columnEnabled)return!1;if(e.column&&y(e.column))return!1;const t=e.originalEvent;if(!t.ctrlKey&&!t.metaKey)return!1;const n=e.field;if(!n)return!1;t.preventDefault(),"function"==typeof t.stopPropagation&&t.stopPropagation();const i=!0===t.shiftKey&&!1!==this.config.multiSelect&&null!==this.columnAnchor;return this.selectColumn(n,i?{range:!0}:{toggle:!0}),!0}processColumns(e){if(this.config.checkbox&&"row"===this.#p.primary){if(e.some(e=>e.field===D))return e;const t=this.#z(),n=e.findIndex(C),i=n>=0?n+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#z(){return{field:D,header:"",width:32,resizable:!1,sortable:!1,lockPosition:!0,utility:!0,checkboxColumn:!0,headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const n=e.cellEl;if(n){const e=parseInt(n.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#H(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),n=t?a(t):-1;n>=0&&(e.checked=this.selected.has(n))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let n=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&n++;else n=e;const i=n>0&&this.selected.size>=n,s=this.selected.size>0;t.checked=i,t.indeterminate=s&&!i}}#U(){return this.gridElement?.hasAttribute("data-has-focus")??!1}#j(e){const t=this.grid._focusRow,n=this.grid._focusCol;if(!this.#U())return this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=n);if("row"===e){if(this.explicitSelection)return this.explicitSelection=!1,void(this.lastSyncedFocusRow=t);t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(this.selected.has(t)&&1===this.selected.size||(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#v()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=n);if((t!==this.lastSyncedFocusRow||n!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=n,this.isCellSelectable(t,n))){const e=this.selectedCell;e&&e.row===t&&e.col===n||(this.selectedCell={row:t,col:n},this.emit("selection-change",this.#v()))}}}#N(){const t=this.gridElement;if(!t)return;const n=this.#p.primary,i=this.#p.columnEnabled,s=!!this.config.isSelectable,o=t.querySelector(".rows-body");if(o){const e=!1!==this.config.multiSelect;o.setAttribute("aria-multiselectable",e?"true":"false")}t.querySelectorAll(".cell").forEach(t=>{const n=t.classList.contains(e)||t.classList.contains("column-selected");t.classList.remove(e,"top","bottom","first","last","column-selected"),n&&t.removeAttribute("aria-selected"),s&&t.removeAttribute("data-selectable")});const r=t.querySelectorAll(".data-grid-row");if(r.forEach(t=>{t.classList.remove(e,"row-focus"),t.setAttribute("aria-selected","false"),s&&t.removeAttribute("data-selectable")}),i&&t.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("column-selected"),e.removeAttribute("aria-selected")}),"row"===n&&(d(t),r.forEach(t=>{const n=a(t.querySelector(".cell[data-row]"));n>=0&&(s&&!this.isRowSelectable(n)&&t.setAttribute("data-selectable","false"),this.selected.has(n)&&(t.classList.add(e,"row-focus"),t.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#H(t)),"cell"!==n&&"range"!==n||!s||t.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),n=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&n>=0&&(this.isCellSelectable(t,n)||e.setAttribute("data-selectable","false"))}),"range"===n&&this.ranges.length>0){d(t);const n=this.ranges.map(E),i=(e,t)=>{for(const i of n)if(e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol)return!0;return!1};t.querySelectorAll(".cell[data-row][data-col]").forEach(t=>{const n=parseInt(t.getAttribute("data-row")??"-1",10),s=parseInt(t.getAttribute("data-col")??"-1",10);if(n>=0&&s>=0){const o=this.visibleColumns[s];if(o&&y(o))return;i(n,s)&&(t.classList.add(e),t.setAttribute("aria-selected","true"),i(n-1,s)||t.classList.add("top"),i(n+1,s)||t.classList.add("bottom"),i(n,s-1)||t.classList.add("first"),i(n,s+1)||t.classList.add("last"))}})}if(i&&this.selectedColumns.size>0){const e=this.visibleColumns.map(e=>"string"==typeof e.field?e.field:void 0);t.querySelectorAll(".header-row > .cell[data-col]").forEach(t=>{const n=parseInt(t.getAttribute("data-col")??"-1",10),i=n>=0?e[n]:void 0;i&&this.selectedColumns.has(i)&&(t.classList.add("column-selected"),t.setAttribute("aria-selected","true"))}),t.querySelectorAll(".cell[data-col]:not(.header-row .cell)").forEach(t=>{if(t.closest(".header-row"))return;const n=parseInt(t.getAttribute("data-col")??"-1",10);if(n<0)return;const i=this.visibleColumns[n];if(!i||y(i))return;const s=e[n];s&&this.selectedColumns.has(s)&&(t.classList.add("column-selected"),t.setAttribute("aria-selected","true"))})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root"),n=this.#p.primary;if(this.pendingRowKeyUpdate&&"row"===n){const{shiftKey:e}=this.pendingRowKeyUpdate;this.pendingRowKeyUpdate=null;const t=this.grid._focusRow;if(e&&null!==this.anchor){this.selected.clear();const e=Math.min(this.anchor,t),n=Math.max(this.anchor,t);for(let t=e;t<=n;t++)this.isRowSelectable(t)&&this.selected.add(t)}else this.isRowSelectable(t)?(this.selected.clear(),this.selected.add(t),this.anchor=t):this.selected.clear();this.lastSelected=t,this.emit("selection-change",this.#v())}if(this.pendingKeyboardUpdate&&"range"===n){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,n=this.grid._focusCol;if(e&&this.cellAnchor){const e=I(this.cellAnchor,{row:t,col:n});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:n});this.emit("selection-change",this.#v())}this.#j(n),this.gridElement.setAttribute("data-selection-mode",n),t&&t.classList.toggle("selecting",this.isDragging),this.#N(),this.#q(t)}onScrollRender(){this.isSelectionEnabled()&&this.#N()}getSelection(){const e=this.#v();return{mode:this.config.mode,activeAxis:e.activeAxis,ranges:e.ranges,selectedColumns:e.selectedColumns,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=/* @__PURE__ */new Map;for(const n of e)for(const e of q(n))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return k(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const n={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[n],this.activeRange=n,this.emit("selection-change",this.#v()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.#p.primary)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const n of t)n>=0&&n<this.rows.length&&this.isRowSelectable(n)&&this.selected.add(n);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#v()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const e=this.#p.primary,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=/* @__PURE__ */new Set;for(const n of this.ranges){const i=Math.max(0,Math.min(n.startRow,n.endRow)),s=Math.min(t.length-1,Math.max(n.startRow,n.endRow));for(let t=i;t<=s;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}#C(e){if(!this.#p.columnEnabled)return;const t=A(this.visibleColumns),n=new Set(t),i=[],s=/* @__PURE__ */new Set;for(const r of e)n.has(r)&&!s.has(r)&&(s.add(r),i.push(r));this.#O("column"),this.selectedColumns.clear();for(const r of i)this.selectedColumns.add(r);const o=i.length>0?i[i.length-1]:null;this.columnAnchor=o,this.columnHead=o,this.activeAxis=this.selectedColumns.size>0?"column":"none",this.emit("selection-change",this.#v()),this.requestAfterRender()}selectColumn(e,t={}){if(!this.#p.columnEnabled)return;const n=A(this.visibleColumns);if(n.includes(e)){if(this.#O("column"),!1===this.config.multiSelect)this.selectedColumns.clear(),this.selectedColumns.add(e),this.columnAnchor=e,this.columnHead=e;else if(t.range&&this.columnAnchor){const t=function(e,t,n){const i=x(e,n),s=x(t,n);if(-1===i||-1===s)return[];const o=Math.min(i,s),r=Math.max(i,s);return n.slice(o,r+1)}(this.columnAnchor,e,n);this.selectedColumns.clear();for(const e of t)this.selectedColumns.add(e);this.columnHead=e}else t.toggle?(this.selectedColumns.has(e)?this.selectedColumns.delete(e):this.selectedColumns.add(e),this.columnAnchor=e,this.columnHead=e):(this.selectedColumns.clear(),this.selectedColumns.add(e),this.columnAnchor=e,this.columnHead=e);this.activeAxis=this.selectedColumns.size>0?"column":"none",this.emit("selection-change",this.#v()),this.requestAfterRender()}}deselectColumn(e){this.#p.columnEnabled&&this.selectedColumns.delete(e)&&(0===this.selectedColumns.size&&(this.columnAnchor=null,this.columnHead=null,"column"===this.activeAxis&&(this.activeAxis="none")),this.emit("selection-change",this.#v()),this.requestAfterRender())}selectAllColumns(){if(!this.#p.columnEnabled)return;if(!1===this.config.multiSelect)return;const e=A(this.visibleColumns);if(0!==e.length){this.#O("column"),this.selectedColumns.clear();for(const t of e)this.selectedColumns.add(t);this.columnAnchor=e[0],this.columnHead=e[e.length-1],this.activeAxis="column",this.emit("selection-change",this.#v()),this.requestAfterRender()}}clearColumnSelection(){0!==this.selectedColumns.size&&(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,"column"===this.activeAxis&&(this.activeAxis="none"),this.emit("selection-change",this.#v()),this.requestAfterRender())}getSelectedColumns(){return 0===this.selectedColumns.size?[]:A(this.visibleColumns).filter(e=>this.selectedColumns.has(e))}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none",this.emit("selection-change",this.#v()),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",this.#v()),this.requestAfterRender()}#v(){const e=this.#p.primary,t="row"===e&&this.selected.size>0||"cell"===e&&null!==this.selectedCell||"range"===e&&this.ranges.length>0;let n;this.#p.bothAxes&&t&&this.selectedColumns.size>0&&(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.gridElement&&i(this.gridElement,s(this.gridElement,"selectionAxisChanged","row"))),n=t?"row"===e?"row":"cell"===e?"cell":"range":this.selectedColumns.size>0?"column":"none",this.activeAxis=n;const o=function(e,t,n,i,s,o){if("column"===t&&i.selectedColumns.size>0)return{mode:e,activeAxis:"column",ranges:[],selectedColumns:o.filter(e=>i.selectedColumns.has(e))};if("cell"===n&&i.selectedCell)return{mode:e,activeAxis:"cell",ranges:[{from:{row:i.selectedCell.row,col:i.selectedCell.col},to:{row:i.selectedCell.row,col:i.selectedCell.col}}],selectedColumns:[]};if("row"===n&&i.selected.size>0){const t=[...i.selected].sort((e,t)=>e-t),n=[];let o=t[0],r=o;for(let e=1;e<t.length;e++)t[e]===r+1?r=t[e]:(n.push({from:{row:o,col:0},to:{row:r,col:s-1}}),o=t[e],r=o);return n.push({from:{row:o,col:0},to:{row:r,col:s-1}}),{mode:e,activeAxis:"row",ranges:n,selectedColumns:[]}}return"range"===n&&i.ranges.length>0?{mode:e,activeAxis:"range",ranges:(r=i.ranges,r.map(R)),selectedColumns:[]}:{mode:e,activeAxis:"none",ranges:[],selectedColumns:[]};var r}(this.config.mode,n,e,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges,selectedColumns:this.selectedColumns},this.columns.length,A(this.visibleColumns));return this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{if("column"===o.activeAxis){const e=o.selectedColumns;if(1===e.length){const t=e[0],n=this.columns.find(e=>e.field===t),o="string"==typeof n?.header&&n.header||t;i(this.gridElement,s(this.gridElement,"columnSelected",o))}else e.length>1?i(this.gridElement,s(this.gridElement,"columnSelectionChanged",e.length)):i(this.gridElement,s(this.gridElement,"columnSelectionCleared"))}else{const e="row"===o.activeAxis?this.selected.size:o.ranges.length;e>0&&i(this.gridElement,s(this.gridElement,"selectionChanged",e))}},150),o}#O(e){if(this.#p.bothAxes&&"column"===e){if(!(this.selected.size>0||null!==this.selectedCell||this.ranges.length>0))return;this.selected.clear(),this.lastSelected=null,this.anchor=null,this.selectedCell=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.gridElement&&i(this.gridElement,s(this.gridElement,"selectionAxisChanged","column"))}}};export{H as SelectionPlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- function t(t,e){return`[tbw-grid${t?`#${t}`:""}${e?`:${e}`:""}]`}var e="TBW140";function o(e,o,r,s){return`${t(r,s)} ${e}: ${o}\n\n → More info: ${function(t){return`https://toolboxjs.com/grid/errors#${t.toLowerCase()}`}(e)}`}function r(t,e,r,s){console.debug(o(t,e,r,s))}function s(t,e,r,s){console.error(o(t,e,r,s))}var n={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"},i=/* @__PURE__ */new WeakMap;function a(t){return"__proto__"===t||"constructor"===t||"prototype"===t}var l=/* @__PURE__ */new Map;function c(t){if(-1===t.indexOf("."))return null;let e=l.get(t);return void 0===e&&(e=Object.freeze(t.split(".")),l.set(t,e)),e}function d(t,e){let o=t;for(let r=0;r<e.length;r++){if(null==o||"object"!=typeof o)return;const t=e[r];if(a(t))return;o=o[t]}return o}function u(t){const e=c(t);return null===e?a(t)?()=>{}:e=>null==e?void 0:e[t]:o=>{if(null==o)return;const r=o;return Object.prototype.hasOwnProperty.call(r,t)?r[t]:d(r,e)}}function h(t,e,o=-1){if(!e.valueAccessor)return function(t,e){if(null==t)return;const o=c(e),r=t;return null===o?a(e)?void 0:r[e]:Object.prototype.hasOwnProperty.call(r,e)?r[e]:d(r,o)}(t,e.field);if("object"!=typeof t||null===t)return e.valueAccessor({row:t,column:e,rowIndex:o});const r=t,s=e.field;let n=i.get(r);if(n){const t=n.get(s);if(void 0!==t)return t.v}else n=/* @__PURE__ */new Map,i.set(r,n);const l=e.valueAccessor({row:t,column:e,rowIndex:o});return n.set(s,{v:l}),l}function g(t,e,o){const r=[...t];return function(t,e,o,r){const s=r.find(t=>t.field===e),n=s?.sortComparator;if(n)if(s?.valueAccessor)t.sort((t,e)=>n(h(t,s),h(e,s),t,e)*o);else{const r=u(e);t.sort((t,e)=>n(r(t),r(e),t,e)*o)}else s?.valueAccessor?function(t,e,o){f(t,t=>h(t,e),o)}(t,s,o):function(t,e,o){if(function(t){return-1===t.indexOf(".")&&!a(t)}(e))return void t.sort((t,r)=>{const s=function(t,e){const o=!0===t?.__loading;return o===(!0===e?.__loading)?0:o?1:-1}(t,r);if(0!==s)return s;const n=t[e],i=r[e];return null==n&&null==i?0:null==n?-o:null==i||n>i?o:n<i?-o:0});f(t,u(e),o)}(t,e,o)}(r,e.field,e.direction,o),r}function f(t,e,o){const r=t.length;if(r<2)return;const s=new Array(r),n=new Uint8Array(r),i=new Array(r);for(let l=0;l<r;l++){const o=t[l];i[l]=l,s[l]=e(o),n[l]=!0===o?.__loading?1:0}i.sort((t,e)=>{const r=n[t];if(r!==n[e])return r?1:-1;const i=s[t],a=s[e];return null==i&&null==a?0:null==i?-o:null==a||i>a?o:i<a?-o:0});const a=new Array(r);for(let l=0;l<r;l++)a[l]=t[i[l]];for(let l=0;l<r;l++)t[l]=a[l]}var m="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(t=>t.split("").reverse().join("")),p=(new RegExp(`__(proto|defineGetter|defineSetter)|${m.slice(3).join("|")}|this\\b`),new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math".split("|"))),b=/^on\w+$/i,w=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),C=/^\s*(javascript|vbscript|data|blob):/i;function v(t){const e=document.createElement("template");return t&&"string"==typeof t&&(e.innerHTML=t,function(t){const e=[],o=t.querySelectorAll("*");for(const r of o){const t=r.tagName.toLowerCase();if(p.has(t)){e.push(r);continue}if(("svg"===t||"http://www.w3.org/2000/svg"===r.namespaceURI)&&Array.from(r.attributes).some(t=>b.test(t.name)||"href"===t.name||"xlink:href"===t.name)){e.push(r);continue}const o=[];for(const e of r.attributes){const t=e.name.toLowerCase();b.test(t)?o.push(e.name):"is"!==t?(w.has(t)&&C.test(e.value)||"style"===t&&/expression\s*\(|javascript:|behavior\s*:/i.test(e.value))&&o.push(e.name):o.push(e.name)}o.forEach(t=>r.removeAttribute(t))}e.forEach(t=>t.remove())}(e.content)),e.content}var S=class{static dependencies;static manifest;aliases;version="3.5.1";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(t={}){this.userConfig=t}get resolvedConfig(){return this.#t?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(t){if(0===t.length)return;const e={...this.userConfig},r={};for(const o of Object.keys(e))r[o]=this;for(const s of t){const t=s.userConfig;for(const[n,i]of Object.entries(t)){if(void 0===i)continue;if(!(n in e)){e[n]=i,r[n]=s;continue}if(e[n]===i)continue;const t=r[n]?.constructor.name??this.constructor.name,a=s.constructor.name,l=o("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${t} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,e)}refreshUserConfigFrom(t){const e=this.userConfig,o={...t.userConfig};for(const r of Object.keys(e))delete e[r];Object.assign(e,o)}attach(t){this.#t?.abort(),this.#t=new AbortController,this.grid=t,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(t){return this.grid?.getPlugin(t)}emit(t,e){this.grid?.dispatchEvent?.(new CustomEvent(t,{detail:e,bubbles:!0}))}emitCancelable(t,e){const o=new CustomEvent(t,{detail:e,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(o),o.defaultPrevented}on(t,e){this.grid?._pluginManager?.subscribe(this,t,e)}off(t){this.grid?._pluginManager?.unsubscribe(this,t)}emitPluginEvent(t,e){this.grid?._pluginManager?.emitPluginEvent(t,e)}broadcast(t,e){this.emitPluginEvent(t,e),this.emit(t,e)}queryBoolean(t,e=null){const o=this.grid?.query?.(t,e);return Array.isArray(o)?o.some(Boolean):!!o}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const t=this.grid?.gridConfig?.icons??{};return{...n,...t}}t(t,e){return this.grid?.effectiveConfig?.locale?.[t]??e}get translate(){return(t,e)=>this.t(t,e)}get isAnimationEnabled(){const t=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===t||"off"===t)return!1;if(!0===t||"on"===t)return!0;const e=this.gridElement;return!e||"0"!==getComputedStyle(e).getPropertyValue("--tbw-animation-enabled").trim()}get animationDuration(){const t=this.gridElement;if(t){const e=getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(),o=parseInt(e,10);if(!isNaN(o))return o}return 200}setIcon(t,e,o){t.dataset.icon=e.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===e?t.dataset.expanded="":"expand"===e&&delete t.dataset.expanded;const r=this.#e(e,o);var s,n;void 0!==r?"string"==typeof r?(s=t,(n=r)&&"string"==typeof n?-1!==n.indexOf("<")||-1!==n.indexOf("&")?s.replaceChildren(v(n)):s.textContent=n:s.replaceChildren()):r instanceof HTMLElement&&t.replaceChildren(r.cloneNode(!0)):t.innerHTML=""}#e(t,e){return void 0!==e?e:this.grid?.gridConfig?.icons?.[t]}updateSortIndicator(t,e){t.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const o=document.createElement("span");o.setAttribute("part","sort-indicator"),o.className="sort-indicator",e?(t.setAttribute("aria-sort","asc"===e?"ascending":"descending"),t.setAttribute("data-sort",e),this.setIcon(o,"asc"===e?"sortAsc":"sortDesc")):(t.setAttribute("aria-sort","none"),t.removeAttribute("data-sort"),this.setIcon(o,"sortNone"));const r=t.querySelector(".tbw-filter-btn")??t.querySelector(".resize-handle");return r?t.insertBefore(o,r):t.appendChild(o),o}warn(e,r){void 0!==r?console.warn(o(e,r,this.gridElement.id,this.name)):console.warn(`${t(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(t,e){throw new Error(o(t,e,this.gridElement.id,this.name))}};function k(t,e){return Math.floor(t/e)}function N(){return new DOMException("Aborted","AbortError")}function y(t,e,o,r,s){const n=function(t,e){return{start:t*e,end:(t+1)*e}}(e,o);return function(t,e){return e.aborted?Promise.reject(N()):"object"!=typeof(o=t)||null===o||"function"!=typeof o.subscribe||"function"==typeof o.then?new Promise((o,r)=>{const s=()=>r(N());e.addEventListener("abort",s,{once:!0}),Promise.resolve(t).then(t=>{e.removeEventListener("abort",s),o(t)},t=>{e.removeEventListener("abort",s),r(t)})}):new Promise((o,r)=>{let s=!1;const n=t.subscribe({next:t=>{s||(s=!0,o(t),n.unsubscribe())},error:t=>{s||(s=!0,r(t))},complete:()=>{s||(s=!0,r(/* @__PURE__ */new Error("getRows observable completed without emitting a value")))}});s||e.addEventListener("abort",()=>{s||(s=!0,n.unsubscribe(),r(N()))},{once:!0})});var o}(t.getRows({startNode:n.start,endNode:n.end,pageSize:n.end-n.start,sortModel:r.sortModel,filterModel:r.filterModel,signal:s}),s)}function B(t,e,o){const r=k(t,e),s=o.get(r);if(s)return s[t%e]}function R(t){let e=null;return{async getRows({startNode:o,endNode:r,signal:s}){const{rows:n,total:i}=await(o=>(e||(e=fetch(t,{signal:o}).then(async e=>{if(!e.ok)throw new Error(`Failed to fetch "${t}": ${e.status} ${e.statusText}`);const o=await e.json();if(Array.isArray(o))return{rows:o,total:o.length};const r=o??{},s=Array.isArray(r.rows)?r.rows:[];return{rows:s,total:"number"==typeof r.totalNodeCount?r.totalNodeCount:s.length}}).catch(t=>{throw e=null,t})),e))(s);return{rows:n.slice(o,r),totalNodeCount:i}}}}var M=class extends S{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:-10},incompatibleWith:[{name:"pivot",reason:"PivotPlugin requires the full dataset to compute aggregations. ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side."}],events:[{type:"datasource:data",description:"Root data page/block loaded"},{type:"datasource:children",description:"Child data loaded for a parent context"},{type:"datasource:loading",description:"Loading state changed"},{type:"datasource:error",description:"Fetch operation failed"}],queries:[{type:"datasource:fetch-children",description:"Request child rows for a parent context"},{type:"datasource:is-active",description:"Check if ServerSide plugin has an active data source"}]};name="serverSide";get defaultConfig(){return{maxConcurrentRequests:2}}dataSource=null;totalNodeCount=0;infiniteScrollMode=!1;loadedBlocks=/* @__PURE__ */new Map;loadingBlocks=/* @__PURE__ */new Set;blockControllers=/* @__PURE__ */new Map;lastRequestId=0;scrollDebounceTimer;managedNodes=[];attach(t){if(super.attach(t),this.on("sort-change",()=>{"local"===this.config.sortMode?this.requestRender():this.onModelChange()}),this.on("filter-change",()=>{"local"===this.config.filterMode?this.requestRender():this.onModelChange()}),this.config.dataSource)return void this.setDataSource(this.config.dataSource);const e=this.gridElement?.getAttribute("data-src");e&&this.setDataSource(R(e))}detach(){this.dataSource=null,this.totalNodeCount=0,this.infiniteScrollMode=!1,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.abortAllBlocks(),this.managedNodes=[],this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}abortAllBlocks(){for(const t of this.blockControllers.values())t.abort();this.blockControllers.clear()}getEnrichmentParams(){const t="local"===this.config.sortMode,e="local"===this.config.filterMode,o=t?void 0:this.grid?.query?.("sort:get-model",null),r=e?void 0:this.grid?.query?.("filter:get-model",null);let s=o?.[0];const n=this.grid;if(!t&&!s&&n?._sortState){const{field:t,direction:e}=n._sortState;s=[{field:t,direction:1===e?"asc":"desc"}]}return{sortModel:s,filterModel:r?.[0]}}getViewportMapping(t,e){const o={viewportStart:t,viewportEnd:e},r=this.grid?.query?.("datasource:viewport-mapping",o);return r?.[0]?r[0]:{startNode:t,endNode:e,totalLoadedNodes:this.totalNodeCount}}onModelChange(){this.dataSource&&(this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.requestRender(),this.loadRequiredBlocks())}applyServerResult(t,e,o){void 0!==t.lastNode?(this.totalNodeCount=t.lastNode+1,this.infiniteScrollMode=!1):-1===t.totalNodeCount?this.infiniteScrollMode=!0:(this.totalNodeCount=t.totalNodeCount,this.infiniteScrollMode=!1),this.infiniteScrollMode&&t.rows.length<o&&(this.totalNodeCount=e*o+t.rows.length,this.infiniteScrollMode=!1)}getInfiniteScrollEstimate(t){let e=0;for(const[o,r]of this.loadedBlocks){const s=o*t+r.length;s>e&&(e=s)}return e+t}loadRequiredBlocks(){if(!this.dataSource)return;const{_virtualization:t}=this.grid,o=this.config.pageSize??100,n=this.getViewportMapping(t.start,t.end),i=Math.max(0,this.config.loadThreshold??0),a=Math.max(0,n.startNode-i),l=this.totalNodeCount>0?this.totalNodeCount:1/0,c=Math.min(l,n.endNode+i);if(c<=a)return;const d=function(t,e,o){const r=k(t,o),s=k(e-1,o),n=[];for(let i=r;i<=s;i++)n.push(i);return n}(a,c,o),u=this.getEnrichmentParams(),h=this.grid?.getAttribute?.("id")??void 0;for(const g of d){if(this.loadedBlocks.has(g)||this.loadingBlocks.has(g))continue;if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2)){r("TBW143","Concurrent request limit reached, deferring block load",h);break}this.loadingBlocks.add(g);const t=new AbortController;this.blockControllers.set(g,t),this.broadcast("datasource:loading",{loading:!0}),y(this.dataSource,g,o,u,t.signal).then(e=>{if(this.blockControllers.delete(g),t.signal.aborted)return this.loadingBlocks.delete(g),void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));this.loadedBlocks.set(g,e.rows);const r=this.managedNodes.length;this.applyServerResult(e,g,o),this.loadingBlocks.delete(g);const s=g*o;for(let t=0;t<e.rows.length;t++)s+t<this.managedNodes.length&&(this.managedNodes[s+t]=e.rows[t]);const n={rows:e.rows,totalNodeCount:e.totalNodeCount,startNode:s,endNode:s+e.rows.length,claimed:!1};this.broadcast("datasource:data",n),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}),0===r||this.managedNodes.length<(Number.isFinite(this.totalNodeCount)?this.totalNodeCount:0)?this.requestRender():this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(o=>{if(this.blockControllers.delete(g),this.loadingBlocks.delete(g),t.signal.aborted)return void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));const r=o instanceof Error?o:new Error(String(o));s(e,`getRows() failed: ${r.message}`,h),this.broadcast("datasource:error",{error:r}),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1})})}}processRows(t){if(!this.dataSource)return[...t];const e=this.config.pageSize??100,o=this.infiniteScrollMode?this.getInfiniteScrollEstimate(e):Number.isFinite(this.totalNodeCount)&&this.totalNodeCount>=0?this.totalNodeCount:0;for(;this.managedNodes.length<o;){const t=this.managedNodes.length;this.managedNodes.push({__loading:!0,__index:t})}this.managedNodes.length=o;for(let s=0;s<o;s++){const t=B(s,e,this.loadedBlocks);t&&(this.managedNodes[s]=t)}const r=this.grid;if("local"===this.config.sortMode&&r?._sortState){const t=r._columns??[],e=(r.effectiveConfig?.sortHandler??g)(this.managedNodes,r._sortState,t);return e&&"function"==typeof e.then?(e.catch(()=>{}),this.managedNodes):e}return this.managedNodes}onScroll(t){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}handleQuery(t){switch(t.type){case"datasource:is-active":return null!=this.dataSource;case"datasource:fetch-children":{const{context:e}=t.context;return void this.fetchChildren(e)}}}fetchChildren(t){if(!this.dataSource)return;const e=this.grid?.getAttribute?.("id")??void 0;if(!this.dataSource.getChildRows)return void function(t,e,r,s){console.warn(o(t,e,r,s))}("TBW142",`Plugin "${t.source}" requested child rows but getChildRows() is not implemented on the dataSource`,e);const r=this.getEnrichmentParams();this.broadcast("datasource:loading",{loading:!0,context:t}),this.dataSource.getChildRows({context:t,sortModel:r.sortModel,filterModel:r.filterModel}).then(e=>{const o={rows:e.rows,context:t,claimed:!1};this.broadcast("datasource:children",o),this.broadcast("datasource:loading",{loading:!1,context:t})}).catch(o=>{const r=o instanceof Error?o:new Error(String(o));s("TBW141",`getChildRows() failed: ${r.message}`,e),this.broadcast("datasource:error",{error:r,context:t}),this.broadcast("datasource:loading",{loading:!1,context:t})})}setDataSource(t){this.abortAllBlocks(),this.dataSource=t,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1;const o=this.config.pageSize??100,r=this.getEnrichmentParams(),n=this.grid?.getAttribute?.("id")??void 0,i=new AbortController;this.blockControllers.set(0,i),this.loadingBlocks.add(0),this.broadcast("datasource:loading",{loading:!0}),y(t,0,o,r,i.signal).then(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),i.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});this.loadedBlocks.set(0,t.rows),this.applyServerResult(t,0,o);const e={rows:t.rows,totalNodeCount:t.totalNodeCount,startNode:0,endNode:t.rows.length,claimed:!1};this.broadcast("datasource:data",e),this.broadcast("datasource:loading",{loading:!1}),this.requestRender(),(this.config.loadThreshold??0)>0&&this.loadRequiredBlocks()}).catch(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),i.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});const o=t instanceof Error?t:new Error(String(t));s(e,`getRows() failed: ${o.message}`,n),this.broadcast("datasource:error",{error:o}),this.broadcast("datasource:loading",{loading:!1})})}refresh(){if(!this.dataSource)return;const t=this.dataSource;this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.setDataSource(t)}purgeCache(){this.abortAllBlocks(),this.loadedBlocks.clear(),this.managedNodes=[]}getTotalNodeCount(){return this.totalNodeCount}isNodeLoaded(t){const e=k(t,this.config.pageSize??100);return this.loadedBlocks.has(e)}getLoadedBlockCount(){return this.loadedBlocks.size}};export{M as ServerSidePlugin};
1
+ function t(t,e){return`[tbw-grid${t?`#${t}`:""}${e?`:${e}`:""}]`}var e="TBW140";function o(e,o,r,s){return`${t(r,s)} ${e}: ${o}\n\n → More info: ${function(t){return`https://toolboxjs.com/grid/errors#${t.toLowerCase()}`}(e)}`}function r(t,e,r,s){console.debug(o(t,e,r,s))}function s(t,e,r,s){console.error(o(t,e,r,s))}var n={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"},i=/* @__PURE__ */new WeakMap;function a(t){return"__proto__"===t||"constructor"===t||"prototype"===t}var l=/* @__PURE__ */new Map;function c(t){if(-1===t.indexOf("."))return null;let e=l.get(t);return void 0===e&&(e=Object.freeze(t.split(".")),l.set(t,e)),e}function d(t,e){let o=t;for(let r=0;r<e.length;r++){if(null==o||"object"!=typeof o)return;const t=e[r];if(a(t))return;o=o[t]}return o}function u(t){const e=c(t);return null===e?a(t)?()=>{}:e=>null==e?void 0:e[t]:o=>{if(null==o)return;const r=o;return Object.prototype.hasOwnProperty.call(r,t)?r[t]:d(r,e)}}function h(t,e,o=-1){if(!e.valueAccessor)return function(t,e){if(null==t)return;const o=c(e),r=t;return null===o?a(e)?void 0:r[e]:Object.prototype.hasOwnProperty.call(r,e)?r[e]:d(r,o)}(t,e.field);if("object"!=typeof t||null===t)return e.valueAccessor({row:t,column:e,rowIndex:o});const r=t,s=e.field;let n=i.get(r);if(n){const t=n.get(s);if(void 0!==t)return t.v}else n=/* @__PURE__ */new Map,i.set(r,n);const l=e.valueAccessor({row:t,column:e,rowIndex:o});return n.set(s,{v:l}),l}function g(t,e,o){const r=[...t];return function(t,e,o,r){const s=r.find(t=>t.field===e),n=s?.sortComparator;if(n)if(s?.valueAccessor)t.sort((t,e)=>n(h(t,s),h(e,s),t,e)*o);else{const r=u(e);t.sort((t,e)=>n(r(t),r(e),t,e)*o)}else s?.valueAccessor?function(t,e,o){f(t,t=>h(t,e),o)}(t,s,o):function(t,e,o){if(function(t){return-1===t.indexOf(".")&&!a(t)}(e))return void t.sort((t,r)=>{const s=function(t,e){const o=!0===t?.__loading;return o===(!0===e?.__loading)?0:o?1:-1}(t,r);if(0!==s)return s;const n=t[e],i=r[e];return null==n&&null==i?0:null==n?-o:null==i||n>i?o:n<i?-o:0});f(t,u(e),o)}(t,e,o)}(r,e.field,e.direction,o),r}function f(t,e,o){const r=t.length;if(r<2)return;const s=new Array(r),n=new Uint8Array(r),i=new Array(r);for(let l=0;l<r;l++){const o=t[l];i[l]=l,s[l]=e(o),n[l]=!0===o?.__loading?1:0}i.sort((t,e)=>{const r=n[t];if(r!==n[e])return r?1:-1;const i=s[t],a=s[e];return null==i&&null==a?0:null==i?-o:null==a||i>a?o:i<a?-o:0});const a=new Array(r);for(let l=0;l<r;l++)a[l]=t[i[l]];for(let l=0;l<r;l++)t[l]=a[l]}var m="__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles".split("|").map(t=>t.split("").reverse().join("")),p=(new RegExp(`__(proto|defineGetter|defineSetter)|${m.slice(3).join("|")}|this\\b`),new Set("script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math".split("|"))),b=/^on\w+$/i,w=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),C=/^\s*(javascript|vbscript|data|blob):/i;function v(t){const e=document.createElement("template");return t&&"string"==typeof t&&(e.innerHTML=t,function(t){const e=[],o=t.querySelectorAll("*");for(const r of o){const t=r.tagName.toLowerCase();if(p.has(t)){e.push(r);continue}if(("svg"===t||"http://www.w3.org/2000/svg"===r.namespaceURI)&&Array.from(r.attributes).some(t=>b.test(t.name)||"href"===t.name||"xlink:href"===t.name)){e.push(r);continue}const o=[];for(const e of r.attributes){const t=e.name.toLowerCase();b.test(t)?o.push(e.name):"is"!==t?(w.has(t)&&C.test(e.value)||"style"===t&&/expression\s*\(|javascript:|behavior\s*:/i.test(e.value))&&o.push(e.name):o.push(e.name)}o.forEach(t=>r.removeAttribute(t))}e.forEach(t=>t.remove())}(e.content)),e.content}var S=class{static dependencies;static manifest;aliases;version="3.5.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#t;get defaultConfig(){return{}}constructor(t={}){this.userConfig=t}get resolvedConfig(){return this.#t?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(t){if(0===t.length)return;const e={...this.userConfig},r={};for(const o of Object.keys(e))r[o]=this;for(const s of t){const t=s.userConfig;for(const[n,i]of Object.entries(t)){if(void 0===i)continue;if(!(n in e)){e[n]=i,r[n]=s;continue}if(e[n]===i)continue;const t=r[n]?.constructor.name??this.constructor.name,a=s.constructor.name,l=o("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" supplied by both ${t} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,e)}refreshUserConfigFrom(t){const e=this.userConfig,o={...t.userConfig};for(const r of Object.keys(e))delete e[r];Object.assign(e,o)}attach(t){this.#t?.abort(),this.#t=new AbortController,this.grid=t,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#t?.abort(),this.#t=void 0}getPlugin(t){return this.grid?.getPlugin(t)}emit(t,e){this.grid?.dispatchEvent?.(new CustomEvent(t,{detail:e,bubbles:!0}))}emitCancelable(t,e){const o=new CustomEvent(t,{detail:e,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(o),o.defaultPrevented}on(t,e){this.grid?._pluginManager?.subscribe(this,t,e)}off(t){this.grid?._pluginManager?.unsubscribe(this,t)}emitPluginEvent(t,e){this.grid?._pluginManager?.emitPluginEvent(t,e)}broadcast(t,e){this.emitPluginEvent(t,e),this.emit(t,e)}queryBoolean(t,e=null){const o=this.grid?.query?.(t,e);return Array.isArray(o)?o.some(Boolean):!!o}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}requestVirtualRefresh(){this.grid?.requestVirtualRefresh?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid?._hostElement}get disconnectSignal(){return this.#t?.signal??this.grid?.disconnectSignal}get gridIcons(){const t=this.grid?.gridConfig?.icons??{};return{...n,...t}}t(t,e){return this.grid?.effectiveConfig?.locale?.[t]??e}get translate(){return(t,e)=>this.t(t,e)}get isAnimationEnabled(){const t=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===t||"off"===t)return!1;if(!0===t||"on"===t)return!0;const e=this.gridElement;return!e||"0"!==getComputedStyle(e).getPropertyValue("--tbw-animation-enabled").trim()}get animationDuration(){const t=this.gridElement;if(t){const e=getComputedStyle(t).getPropertyValue("--tbw-animation-duration").trim(),o=parseInt(e,10);if(!isNaN(o))return o}return 200}setIcon(t,e,o){t.dataset.icon=e.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===e?t.dataset.expanded="":"expand"===e&&delete t.dataset.expanded;const r=this.#e(e,o);var s,n;void 0!==r?"string"==typeof r?(s=t,(n=r)&&"string"==typeof n?-1!==n.indexOf("<")||-1!==n.indexOf("&")?s.replaceChildren(v(n)):s.textContent=n:s.replaceChildren()):r instanceof HTMLElement&&t.replaceChildren(r.cloneNode(!0)):t.innerHTML=""}#e(t,e){return void 0!==e?e:this.grid?.gridConfig?.icons?.[t]}updateSortIndicator(t,e){t.querySelector('[part~="sort-indicator"], .sort-indicator')?.remove();const o=document.createElement("span");o.setAttribute("part","sort-indicator"),o.className="sort-indicator",e?(t.setAttribute("aria-sort","asc"===e?"ascending":"descending"),t.setAttribute("data-sort",e),this.setIcon(o,"asc"===e?"sortAsc":"sortDesc")):(t.setAttribute("aria-sort","none"),t.removeAttribute("data-sort"),this.setIcon(o,"sortNone"));const r=t.querySelector(".tbw-filter-btn")??t.querySelector(".resize-handle");return r?t.insertBefore(o,r):t.appendChild(o),o}warn(e,r){void 0!==r?console.warn(o(e,r,this.gridElement.id,this.name)):console.warn(`${t(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(t,e){throw new Error(o(t,e,this.gridElement.id,this.name))}};function k(t,e){return Math.floor(t/e)}function N(){return new DOMException("Aborted","AbortError")}function y(t,e,o,r,s){const n=function(t,e){return{start:t*e,end:(t+1)*e}}(e,o);return function(t,e){return e.aborted?Promise.reject(N()):"object"!=typeof(o=t)||null===o||"function"!=typeof o.subscribe||"function"==typeof o.then?new Promise((o,r)=>{const s=()=>r(N());e.addEventListener("abort",s,{once:!0}),Promise.resolve(t).then(t=>{e.removeEventListener("abort",s),o(t)},t=>{e.removeEventListener("abort",s),r(t)})}):new Promise((o,r)=>{let s=!1;const n=t.subscribe({next:t=>{s||(s=!0,o(t),n.unsubscribe())},error:t=>{s||(s=!0,r(t))},complete:()=>{s||(s=!0,r(/* @__PURE__ */new Error("getRows observable completed without emitting a value")))}});s||e.addEventListener("abort",()=>{s||(s=!0,n.unsubscribe(),r(N()))},{once:!0})});var o}(t.getRows({startNode:n.start,endNode:n.end,pageSize:n.end-n.start,sortModel:r.sortModel,filterModel:r.filterModel,signal:s}),s)}function B(t,e,o){const r=k(t,e),s=o.get(r);if(s)return s[t%e]}function R(t){let e=null;return{async getRows({startNode:o,endNode:r,signal:s}){const{rows:n,total:i}=await(o=>(e||(e=fetch(t,{signal:o}).then(async e=>{if(!e.ok)throw new Error(`Failed to fetch "${t}": ${e.status} ${e.statusText}`);const o=await e.json();if(Array.isArray(o))return{rows:o,total:o.length};const r=o??{},s=Array.isArray(r.rows)?r.rows:[];return{rows:s,total:"number"==typeof r.totalNodeCount?r.totalNodeCount:s.length}}).catch(t=>{throw e=null,t})),e))(s);return{rows:n.slice(o,r),totalNodeCount:i}}}}var M=class extends S{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:-10},incompatibleWith:[{name:"pivot",reason:"PivotPlugin requires the full dataset to compute aggregations. ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side."}],events:[{type:"datasource:data",description:"Root data page/block loaded"},{type:"datasource:children",description:"Child data loaded for a parent context"},{type:"datasource:loading",description:"Loading state changed"},{type:"datasource:error",description:"Fetch operation failed"}],queries:[{type:"datasource:fetch-children",description:"Request child rows for a parent context"},{type:"datasource:is-active",description:"Check if ServerSide plugin has an active data source"}]};name="serverSide";get defaultConfig(){return{maxConcurrentRequests:2}}dataSource=null;totalNodeCount=0;infiniteScrollMode=!1;loadedBlocks=/* @__PURE__ */new Map;loadingBlocks=/* @__PURE__ */new Set;blockControllers=/* @__PURE__ */new Map;lastRequestId=0;scrollDebounceTimer;managedNodes=[];attach(t){if(super.attach(t),this.on("sort-change",()=>{"local"===this.config.sortMode?this.requestRender():this.onModelChange()}),this.on("filter-change",()=>{"local"===this.config.filterMode?this.requestRender():this.onModelChange()}),this.config.dataSource)return void this.setDataSource(this.config.dataSource);const e=this.gridElement?.getAttribute("data-src");e&&this.setDataSource(R(e))}detach(){this.dataSource=null,this.totalNodeCount=0,this.infiniteScrollMode=!1,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.abortAllBlocks(),this.managedNodes=[],this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}abortAllBlocks(){for(const t of this.blockControllers.values())t.abort();this.blockControllers.clear()}getEnrichmentParams(){const t="local"===this.config.sortMode,e="local"===this.config.filterMode,o=t?void 0:this.grid?.query?.("sort:get-model",null),r=e?void 0:this.grid?.query?.("filter:get-model",null);let s=o?.[0];const n=this.grid;if(!t&&!s&&n?._sortState){const{field:t,direction:e}=n._sortState;s=[{field:t,direction:1===e?"asc":"desc"}]}return{sortModel:s,filterModel:r?.[0]}}getViewportMapping(t,e){const o={viewportStart:t,viewportEnd:e},r=this.grid?.query?.("datasource:viewport-mapping",o);return r?.[0]?r[0]:{startNode:t,endNode:e,totalLoadedNodes:this.totalNodeCount}}onModelChange(){this.dataSource&&(this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.requestRender(),this.loadRequiredBlocks())}applyServerResult(t,e,o){void 0!==t.lastNode?(this.totalNodeCount=t.lastNode+1,this.infiniteScrollMode=!1):-1===t.totalNodeCount?this.infiniteScrollMode=!0:(this.totalNodeCount=t.totalNodeCount,this.infiniteScrollMode=!1),this.infiniteScrollMode&&t.rows.length<o&&(this.totalNodeCount=e*o+t.rows.length,this.infiniteScrollMode=!1)}getInfiniteScrollEstimate(t){let e=0;for(const[o,r]of this.loadedBlocks){const s=o*t+r.length;s>e&&(e=s)}return e+t}loadRequiredBlocks(){if(!this.dataSource)return;const{_virtualization:t}=this.grid,o=this.config.pageSize??100,n=this.getViewportMapping(t.start,t.end),i=Math.max(0,this.config.loadThreshold??0),a=Math.max(0,n.startNode-i),l=this.totalNodeCount>0?this.totalNodeCount:1/0,c=Math.min(l,n.endNode+i);if(c<=a)return;const d=function(t,e,o){const r=k(t,o),s=k(e-1,o),n=[];for(let i=r;i<=s;i++)n.push(i);return n}(a,c,o),u=this.getEnrichmentParams(),h=this.grid?.getAttribute?.("id")??void 0;for(const g of d){if(this.loadedBlocks.has(g)||this.loadingBlocks.has(g))continue;if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2)){r("TBW143","Concurrent request limit reached, deferring block load",h);break}this.loadingBlocks.add(g);const t=new AbortController;this.blockControllers.set(g,t),this.broadcast("datasource:loading",{loading:!0}),y(this.dataSource,g,o,u,t.signal).then(e=>{if(this.blockControllers.delete(g),t.signal.aborted)return this.loadingBlocks.delete(g),void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));this.loadedBlocks.set(g,e.rows);const r=this.managedNodes.length;this.applyServerResult(e,g,o),this.loadingBlocks.delete(g);const s=g*o;for(let t=0;t<e.rows.length;t++)s+t<this.managedNodes.length&&(this.managedNodes[s+t]=e.rows[t]);const n={rows:e.rows,totalNodeCount:e.totalNodeCount,startNode:s,endNode:s+e.rows.length,claimed:!1};this.broadcast("datasource:data",n),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}),0===r||this.managedNodes.length<(Number.isFinite(this.totalNodeCount)?this.totalNodeCount:0)?this.requestRender():this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(o=>{if(this.blockControllers.delete(g),this.loadingBlocks.delete(g),t.signal.aborted)return void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));const r=o instanceof Error?o:new Error(String(o));s(e,`getRows() failed: ${r.message}`,h),this.broadcast("datasource:error",{error:r}),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1})})}}processRows(t){if(!this.dataSource)return[...t];const e=this.config.pageSize??100,o=this.infiniteScrollMode?this.getInfiniteScrollEstimate(e):Number.isFinite(this.totalNodeCount)&&this.totalNodeCount>=0?this.totalNodeCount:0;for(;this.managedNodes.length<o;){const t=this.managedNodes.length;this.managedNodes.push({__loading:!0,__index:t})}this.managedNodes.length=o;for(let s=0;s<o;s++){const t=B(s,e,this.loadedBlocks);t&&(this.managedNodes[s]=t)}const r=this.grid;if("local"===this.config.sortMode&&r?._sortState){const t=r._columns??[],e=(r.effectiveConfig?.sortHandler??g)(this.managedNodes,r._sortState,t);return e&&"function"==typeof e.then?(e.catch(()=>{}),this.managedNodes):e}return this.managedNodes}onScroll(t){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}handleQuery(t){switch(t.type){case"datasource:is-active":return null!=this.dataSource;case"datasource:fetch-children":{const{context:e}=t.context;return void this.fetchChildren(e)}}}fetchChildren(t){if(!this.dataSource)return;const e=this.grid?.getAttribute?.("id")??void 0;if(!this.dataSource.getChildRows)return void function(t,e,r,s){console.warn(o(t,e,r,s))}("TBW142",`Plugin "${t.source}" requested child rows but getChildRows() is not implemented on the dataSource`,e);const r=this.getEnrichmentParams();this.broadcast("datasource:loading",{loading:!0,context:t}),this.dataSource.getChildRows({context:t,sortModel:r.sortModel,filterModel:r.filterModel}).then(e=>{const o={rows:e.rows,context:t,claimed:!1};this.broadcast("datasource:children",o),this.broadcast("datasource:loading",{loading:!1,context:t})}).catch(o=>{const r=o instanceof Error?o:new Error(String(o));s("TBW141",`getChildRows() failed: ${r.message}`,e),this.broadcast("datasource:error",{error:r,context:t}),this.broadcast("datasource:loading",{loading:!1,context:t})})}setDataSource(t){this.abortAllBlocks(),this.dataSource=t,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1;const o=this.config.pageSize??100,r=this.getEnrichmentParams(),n=this.grid?.getAttribute?.("id")??void 0,i=new AbortController;this.blockControllers.set(0,i),this.loadingBlocks.add(0),this.broadcast("datasource:loading",{loading:!0}),y(t,0,o,r,i.signal).then(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),i.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});this.loadedBlocks.set(0,t.rows),this.applyServerResult(t,0,o);const e={rows:t.rows,totalNodeCount:t.totalNodeCount,startNode:0,endNode:t.rows.length,claimed:!1};this.broadcast("datasource:data",e),this.broadcast("datasource:loading",{loading:!1}),this.requestRender(),(this.config.loadThreshold??0)>0&&this.loadRequiredBlocks()}).catch(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),i.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});const o=t instanceof Error?t:new Error(String(t));s(e,`getRows() failed: ${o.message}`,n),this.broadcast("datasource:error",{error:o}),this.broadcast("datasource:loading",{loading:!1})})}refresh(){if(!this.dataSource)return;const t=this.dataSource;this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.setDataSource(t)}purgeCache(){this.abortAllBlocks(),this.loadedBlocks.clear(),this.managedNodes=[]}getTotalNodeCount(){return this.totalNodeCount}isNodeLoaded(t){const e=k(t,this.config.pageSize??100);return this.loadedBlocks.has(e)}getLoadedBlockCount(){return this.loadedBlocks.size}};export{M as ServerSidePlugin};
2
2
  //# sourceMappingURL=index.js.map