@toolbox-web/grid 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/all.js +1 -1
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/lib/core/internal/dom-builder.d.ts +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/editing/index.js.map +1 -1
  12. package/lib/plugins/export/index.js +1 -1
  13. package/lib/plugins/filtering/index.js +1 -1
  14. package/lib/plugins/filtering/index.js.map +1 -1
  15. package/lib/plugins/grouping-columns/index.js +1 -1
  16. package/lib/plugins/grouping-rows/index.js +1 -1
  17. package/lib/plugins/master-detail/index.js +1 -1
  18. package/lib/plugins/multi-sort/index.js +1 -1
  19. package/lib/plugins/pinned-columns/index.js +1 -1
  20. package/lib/plugins/pinned-rows/index.js +1 -1
  21. package/lib/plugins/pivot/index.js +1 -1
  22. package/lib/plugins/print/index.js +1 -1
  23. package/lib/plugins/print/index.js.map +1 -1
  24. package/lib/plugins/reorder-columns/index.js +1 -1
  25. package/lib/plugins/responsive/index.js +1 -1
  26. package/lib/plugins/responsive/index.js.map +1 -1
  27. package/lib/plugins/row-drag-drop/index.js +1 -1
  28. package/lib/plugins/selection/index.js +1 -1
  29. package/lib/plugins/selection/index.js.map +1 -1
  30. package/lib/plugins/server-side/index.js +1 -1
  31. package/lib/plugins/shell/index.js +1 -1
  32. package/lib/plugins/shell/index.js.map +1 -1
  33. package/lib/plugins/shell/types.d.ts +18 -2
  34. package/lib/plugins/sticky-rows/index.js +1 -1
  35. package/lib/plugins/tooltip/index.js +1 -1
  36. package/lib/plugins/tooltip/index.js.map +1 -1
  37. package/lib/plugins/tree/index.js +1 -1
  38. package/lib/plugins/undo-redo/index.js +1 -1
  39. package/lib/plugins/visibility/index.js +1 -1
  40. package/package.json +1 -1
  41. package/umd/grid.all.umd.js +1 -1
  42. package/umd/grid.all.umd.js.map +1 -1
  43. package/umd/grid.umd.js +1 -1
  44. package/umd/grid.umd.js.map +1 -1
  45. package/umd/plugins/editing.umd.js +1 -1
  46. package/umd/plugins/editing.umd.js.map +1 -1
  47. package/umd/plugins/filtering.umd.js +1 -1
  48. package/umd/plugins/filtering.umd.js.map +1 -1
  49. package/umd/plugins/print.umd.js +1 -1
  50. package/umd/plugins/print.umd.js.map +1 -1
  51. package/umd/plugins/responsive.umd.js +1 -1
  52. package/umd/plugins/responsive.umd.js.map +1 -1
  53. package/umd/plugins/selection.umd.js +1 -1
  54. package/umd/plugins/selection.umd.js.map +1 -1
  55. package/umd/plugins/shell.umd.js.map +1 -1
  56. package/umd/plugins/tooltip.umd.js +1 -1
  57. package/umd/plugins/tooltip.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){if(t._virtualization?.enabled){const{rowHeight:e,container:r,viewportEl:o,scrollMapping:i}=t._virtualization,n=r,s=o?.clientHeight??n?.clientHeight??0;if(n&&s>0){const r=t._focusRow*e,o=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(r<o)n.scrollTop=i?a(r,i):r;else if(r+e>o+s){const t=r-s+e;n.scrollTop=i?a(t,i):t}}}const o=void 0!==t._activeEditRows&&-1!==t._activeEditRows||!!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=t._focusRow,s=t._virtualization.start??0,d=t._virtualization.end??t._rows.length;if(n>=s&&n<d){const i=t._bodyEl.querySelectorAll(".data-grid-row")[n-s];let a=i?.children[t._focusCol];if(a&&a.classList?.contains("cell")||(a=i?.querySelector(`.cell[data-col="${t._focusCol}"]`)??i?.querySelector(".cell[data-col]")),a){a.classList.add("cell-focus"),a.setAttribute("aria-selected","true");const n=t.querySelector(".tbw-scroll-area");if(n&&a&&(!o||r?.forceHorizontalScroll))if(r?.forceScrollLeft)n.scrollLeft=0;else if(r?.forceScrollRight)n.scrollLeft=n.scrollWidth-n.clientWidth;else{const e=t._getHorizontalScrollOffsets?.(i??void 0,a)??{left:0,right:0};if(!e.skipScroll){const t=a.getBoundingClientRect(),r=n.getBoundingClientRect(),o=t.left-r.left+n.scrollLeft,i=o+t.width,s=n.scrollLeft+e.left,d=n.scrollLeft+n.clientWidth-e.right;o<s?n.scrollLeft=o-e.left:i>d&&(n.scrollLeft=i-n.clientWidth+e.right)}}if(o&&a.classList.contains(e)){const e=a.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}}else if(o&&!a.contains(document.activeElement)){a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1");try{a.focus({preventScroll:!0})}catch{}}else if(!o){const e=document.activeElement;e instanceof HTMLElement&&e!==t&&"function"==typeof t.contains&&t.contains(e)&&!e.classList.contains("cell")&&!e.closest(".cell")||e===t||t.focus({preventScroll:!0})}}}}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".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){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return 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):(h.has(e)&&p.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name)}r.forEach(e=>o.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}var m={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};var b=class{static dependencies;static manifest;aliases;version="3.0.0";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)}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}}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);void 0!==o?"string"==typeof o?e.innerHTML=w(o):o instanceof HTMLElement&&(e.innerHTML="",e.appendChild(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 I(){return v}function y(){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";aliases=["reorderRows","rowReorder"];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}.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),y(),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,o){const i=[];let n=!1;for(const r of t)null!==r&&"object"==typeof r?i.push(new WeakRef(r)):n=!0;r.set(e,{refs:i,hasPrimitives:n,meta:o})}(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=I(),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=I()?.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),y(),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){if(t._virtualization?.enabled){const{rowHeight:e,container:r,viewportEl:o,scrollMapping:i}=t._virtualization,n=r,s=o?.clientHeight??n?.clientHeight??0;if(n&&s>0){const r=t._focusRow*e,o=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(r<o)n.scrollTop=i?a(r,i):r;else if(r+e>o+s){const t=r-s+e;n.scrollTop=i?a(t,i):t}}}const o=void 0!==t._activeEditRows&&-1!==t._activeEditRows||!!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=t._focusRow,s=t._virtualization.start??0,d=t._virtualization.end??t._rows.length;if(n>=s&&n<d){const i=t._bodyEl.querySelectorAll(".data-grid-row")[n-s];let a=i?.children[t._focusCol];if(a&&a.classList?.contains("cell")||(a=i?.querySelector(`.cell[data-col="${t._focusCol}"]`)??i?.querySelector(".cell[data-col]")),a){a.classList.add("cell-focus"),a.setAttribute("aria-selected","true");const n=t.querySelector(".tbw-scroll-area");if(n&&a&&(!o||r?.forceHorizontalScroll))if(r?.forceScrollLeft)n.scrollLeft=0;else if(r?.forceScrollRight)n.scrollLeft=n.scrollWidth-n.clientWidth;else{const e=t._getHorizontalScrollOffsets?.(i??void 0,a)??{left:0,right:0};if(!e.skipScroll){const t=a.getBoundingClientRect(),r=n.getBoundingClientRect(),o=t.left-r.left+n.scrollLeft,i=o+t.width,s=n.scrollLeft+e.left,d=n.scrollLeft+n.clientWidth-e.right;o<s?n.scrollLeft=o-e.left:i>d&&(n.scrollLeft=i-n.clientWidth+e.right)}}if(o&&a.classList.contains(e)){const e=a.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}}else if(o&&!a.contains(document.activeElement)){a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1");try{a.focus({preventScroll:!0})}catch{}}else if(!o){const e=document.activeElement;e instanceof HTMLElement&&e!==t&&"function"==typeof t.contains&&t.contains(e)&&!e.classList.contains("cell")&&!e.closest(".cell")||e===t||t.focus({preventScroll:!0})}}}}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".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){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return 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):(h.has(e)&&p.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name)}r.forEach(e=>o.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}var m={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};var b=class{static dependencies;static manifest;aliases;version="3.1.0";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)}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}}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);void 0!==o?"string"==typeof o?e.innerHTML=w(o):o instanceof HTMLElement&&(e.innerHTML="",e.appendChild(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 I(){return v}function y(){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";aliases=["reorderRows","rowReorder"];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}.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),y(),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,o){const i=[];let n=!1;for(const r of t)null!==r&&"object"==typeof r?i.push(new WeakRef(r)):n=!0;r.set(e,{refs:i,hasPrimitives:n,meta:o})}(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=I(),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=I()?.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),y(),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`},s={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 s=e.querySelector?.(".tbw-sr-only");s&&(s.textContent="","function"==typeof requestAnimationFrame?requestAnimationFrame(()=>{s.textContent=t}):s.textContent=t)}function n(e,s,...i){const n=(e&&"effectiveConfig"in e?e.effectiveConfig:void 0)?.a11y?.messages?.[s];return n?n(...i):t[s](...i)}function o(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const s=e.closest(".data-grid-row");if(!s)return-1;const i=s.parentElement;if(!i)return-1;const n=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<n.length;o++)if(n[o]===s)return o;return-1}function r(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function l(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function c(e,t,s,i){return`${l(s,i)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}var a="__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("")),d=(new RegExp(`__(proto|defineGetter|defineSetter)|${a.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".split("|"))),h=/^on\w+$/i,u=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),g=/^\s*(javascript|vbscript|data|blob):/i;function m(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],s=e.querySelectorAll("*");for(const i of s){const e=i.tagName.toLowerCase();if(d.has(e)){t.push(i);continue}if(("svg"===e||"http://www.w3.org/2000/svg"===i.namespaceURI)&&Array.from(i.attributes).some(e=>h.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(i);continue}const s=[];for(const t of i.attributes){const e=t.name.toLowerCase();h.test(e)?s.push(t.name):(u.has(e)&&g.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&s.push(t.name)}s.forEach(e=>i.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}var f=class{static dependencies;static manifest;aliases;version="3.0.0";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},s={};for(const i of Object.keys(t))s[i]=this;for(const i of e){const e=i.userConfig;for(const[n,o]of Object.entries(e)){if(void 0===o)continue;if(!(n in t)){t[n]=o,s[n]=i;continue}if(t[n]===o)continue;const e=s[n]?.constructor.name??this.constructor.name,r=i.constructor.name,l=c("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" 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,s={...e.userConfig};for(const i of Object.keys(t))delete t[i];Object.assign(t,s)}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 s=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(s),s.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)}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{...s,...e}}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(),s=parseInt(t,10);if(!isNaN(s))return s}return 200}setIcon(e,t,s){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,s);void 0!==i?"string"==typeof i?e.innerHTML=m(i):i instanceof HTMLElement&&(e.innerHTML="",e.appendChild(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 s=document.createElement("span");s.setAttribute("part","sort-indicator"),s.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(s,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(s,"sortNone"));const i=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return i?e.insertBefore(s,i):e.appendChild(s),s}warn(e,t){void 0!==t?console.warn(c(e,t,this.gridElement.id,this.name)):console.warn(`${l(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(c(e,t,this.gridElement.id,this.name))}};function w(e){return"__tbw_expander"===e.field}function b(e){return!0===e.utility}function p(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 p(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 s=e.find(e=>"column"!==e);if("column"===s)throw new Error(`[SelectionPlugin] Invalid selection mode: [${e.join(", ")}].`);return{primary:s,columnEnabled:!0,bothAxes:!0}}function C(e){const t=[];for(const s of e)!0!==s.utility&&"string"==typeof s.field&&s.field.length>0&&t.push(s.field);return t}function v(e,t){return t.indexOf(e)}function y(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 S(e){const t=y(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function A(e,t,s){return s.some(s=>function(e,t,s){const i=y(s);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,s))}function R(e){const t=[],s=y(e);for(let i=s.startRow;i<=s.endRow;i++)for(let e=s.startCol;e<=s.endCol;e++)t.push({row:i,col:e});return t}function x(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function E(e,t){const s=y(e),i=y(t);return s.startRow===i.startRow&&s.startCol===i.startCol&&s.endRow===i.endRow&&s.endCol===i.endCol}function k(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 q="__tbw_checkbox";var I=class extends f{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"===k(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"!==k(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}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}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)}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}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";#s={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:s}=this.config;if(!s)return!0;const i=this.rows[e];return!!i&&s(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.#s=p(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.#s.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.#i()),this.requestAfterRender())))});let t=-1;e.addEventListener("data-change",e=>{const{sourceRowCount:s}=e.detail,i=this.selected.size>0||this.ranges.length>0||null!==this.selectedCell;-1!==t&&s!==t&&i&&this.clearSelectionSilent(),t=s},{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.#n(t),!0}}detach(){(this.gridElement?.querySelector(".rows-body"))?.removeAttribute("aria-multiselectable"),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()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:i}=e,{triggerOn:n="click"}=this.config,o=this.#s.primary;if(i.type!==n)return!1;const r=e.column,l=r&&b(r);if("cell"===o){if(l)return!1;if(!this.isCellSelectable(t,s))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#i()),this.requestAfterRender()),!1}if("row"===o){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,s=i.shiftKey&&e,n=(i.ctrlKey||i.metaKey)&&e,o=!0===r?.checkboxColumn;if(s&&null!==this.anchor){const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);n||this.selected.clear();for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(n||o&&e)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.#i()),this.requestAfterRender(),!1}if("range"===o){if(l)return!1;if(!this.isCellSelectable(t,s))return!1;const e=i.shiftKey,n=(i.ctrlKey||i.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=x(this.cellAnchor,{row:t,col:s}),i=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(i&&E(i,e))return!1;n?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(n){const e={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:s}}else{const e={startRow:t,startCol:s,endRow:t,endCol:s};if(1===this.ranges.length&&E(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#i()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const t=this.#s.primary,s=this.#s.columnEnabled,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(s&&(e.ctrlKey||e.metaKey)&&(" "===e.key||"Spacebar"===e.key)){const t=this.grid._focusCol,s=this.visibleColumns[t];if(s&&!b(s)&&"string"==typeof s.field)return e.preventDefault(),e.stopPropagation(),this.selectColumn(s.field,{toggle:!0}),!0}if(s&&"column"===this.activeAxis&&!1!==this.config.multiSelect&&(e.ctrlKey||e.metaKey)&&e.shiftKey&&("ArrowLeft"===e.key||"ArrowRight"===e.key)){const t=C(this.visibleColumns),s="ArrowLeft"===e.key?"left":"right",i=function(e,t,s){if(0===t.length)return null;if(null===e)return null;const i=v(e,t);if(i<0)return null;const n="left"===s?Math.max(0,i-1):Math.min(t.length-1,i+1);return n===i?null:t[n]}(this.columnHead,t,s);if(null!==i&&null!==this.columnAnchor)return e.preventDefault(),e.stopPropagation(),this.selectColumn(i,{range:!0}),!0}if("Escape"===e.key)return!this.grid.query("isEditing").some(Boolean)&&("column"===this.activeAxis?(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none",this.emit("selection-change",this.#i()),this.requestAfterRender(),!0):("cell"===t?this.selectedCell=null:"row"===t?(this.selected.clear(),this.anchor=null):"range"===t&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#i()),this.requestAfterRender(),!0));if("cell"===t&&i)return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.isCellSelectable(e,t)?this.selectedCell={row:e,col:t}:this.selectedCell=null,this.emit("selection-change",this.#i()),this.requestAfterRender()}),!1;if("row"===t){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 s=e.shiftKey&&t;return s&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey))return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}if("range"===t&&i){const t="Tab"===e.key,s=e.shiftKey&&!t;return s&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}return!("range"!==t||!1===this.config.multiSelect||"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("range"!==this.#s.primary)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(2===e.originalEvent.button&&A(e.rowIndex,e.colIndex,this.ranges))return;if(e.column&&b(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,s=e.colIndex,i=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,n={startRow:t,startCol:s,endRow:t,endCol:s};return!i&&1===this.ranges.length&&E(this.ranges[0],n)?(this.cellAnchor={row:t,col:s},!0):(this.cellAnchor={row:t,col:s},i||(this.ranges=[]),this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#i()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.#s.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 s=this.visibleColumns[t];if(s&&b(s)){const e=this.visibleColumns.findIndex(e=>!b(e));e>=0&&(t=e)}const i=x(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&E(n,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#i()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.#s.primary)return this.isDragging?(this.isDragging=!1,!0):void 0}onHeaderClick(e){if(!this.isSelectionEnabled())return!1;if(!this.#s.columnEnabled)return!1;if(e.column&&b(e.column))return!1;const t=e.originalEvent;if(!t.ctrlKey&&!t.metaKey)return!1;const s=e.field;if(!s)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(s,i?{range:!0}:{toggle:!0}),!0}processColumns(e){if(this.config.checkbox&&"row"===this.#s.primary){if(e.some(e=>e.field===q))return e;const t=this.#o(),s=e.findIndex(w),i=s>=0?s+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#o(){return{field:q,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 s=e.cellEl;if(s){const e=parseInt(s.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#r(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),s=t?o(t):-1;s>=0&&(e.checked=this.selected.has(s))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let s=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&s++;else s=e;const i=s>0&&this.selected.size>=s,n=this.selected.size>0;t.checked=i,t.indeterminate=n&&!i}}#l(){return this.gridElement?.hasAttribute("data-has-focus")??!1}#c(e){const t=this.grid._focusRow,s=this.grid._focusCol;if(!this.#l())return this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);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.#i()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const e=this.selectedCell;e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#i()))}}}#a(){const t=this.gridElement;if(!t)return;const s=this.#s.primary,i=this.#s.columnEnabled,n=!!this.config.isSelectable,l=t.querySelector(".rows-body");if(l){const e=!1!==this.config.multiSelect;l.setAttribute("aria-multiselectable",e?"true":"false")}t.querySelectorAll(".cell").forEach(t=>{const s=t.classList.contains(e)||t.classList.contains("column-selected");t.classList.remove(e,"top","bottom","first","last","column-selected"),s&&t.removeAttribute("aria-selected"),n&&t.removeAttribute("data-selectable")});const c=t.querySelectorAll(".data-grid-row");if(c.forEach(t=>{t.classList.remove(e,"row-focus"),t.setAttribute("aria-selected","false"),n&&t.removeAttribute("data-selectable")}),i&&t.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("column-selected"),e.removeAttribute("aria-selected")}),"row"===s&&(r(t),c.forEach(t=>{const s=o(t.querySelector(".cell[data-row]"));s>=0&&(n&&!this.isRowSelectable(s)&&t.setAttribute("data-selectable","false"),this.selected.has(s)&&(t.classList.add(e,"row-focus"),t.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#r(t)),"cell"!==s&&"range"!==s||!n||t.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&s>=0&&(this.isCellSelectable(t,s)||e.setAttribute("data-selectable","false"))}),"range"===s&&this.ranges.length>0){r(t);const s=this.ranges.map(y),i=(e,t)=>{for(const i of s)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 s=parseInt(t.getAttribute("data-row")??"-1",10),n=parseInt(t.getAttribute("data-col")??"-1",10);if(s>=0&&n>=0){const o=this.visibleColumns[n];if(o&&b(o))return;i(s,n)&&(t.classList.add(e),t.setAttribute("aria-selected","true"),i(s-1,n)||t.classList.add("top"),i(s+1,n)||t.classList.add("bottom"),i(s,n-1)||t.classList.add("first"),i(s,n+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 s=parseInt(t.getAttribute("data-col")??"-1",10),i=s>=0?e[s]: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 s=parseInt(t.getAttribute("data-col")??"-1",10);if(s<0)return;const i=this.visibleColumns[s];if(!i||b(i))return;const n=e[s];n&&this.selectedColumns.has(n)&&(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"),s=this.#s.primary;if(this.pendingRowKeyUpdate&&"row"===s){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),s=Math.max(this.anchor,t);for(let t=e;t<=s;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.#i())}if(this.pendingKeyboardUpdate&&"range"===s){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,s=this.grid._focusCol;if(e&&this.cellAnchor){const e=x(this.cellAnchor,{row:t,col:s});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:s});this.emit("selection-change",this.#i())}this.#c(s),this.gridElement.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#a()}onScrollRender(){this.isSelectionEnabled()&&this.#a()}getSelection(){const e=this.#i();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 s of e)for(const e of R(s))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return A(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.#i()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const s={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[s],this.activeRange=s,this.emit("selection-change",this.#i()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.#s.primary)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#i()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const e=this.#s.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 s of this.ranges){const i=Math.max(0,Math.min(s.startRow,s.endRow)),n=Math.min(t.length-1,Math.max(s.startRow,s.endRow));for(let t=i;t<=n;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}#n(e){if(!this.#s.columnEnabled)return;const t=C(this.visibleColumns),s=new Set(t),i=[],n=/* @__PURE__ */new Set;for(const r of e)s.has(r)&&!n.has(r)&&(n.add(r),i.push(r));this.#d("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.#i()),this.requestAfterRender()}selectColumn(e,t={}){if(!this.#s.columnEnabled)return;const s=C(this.visibleColumns);if(s.includes(e)){if(this.#d("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,s){const i=v(e,s),n=v(t,s);if(-1===i||-1===n)return[];const o=Math.min(i,n),r=Math.max(i,n);return s.slice(o,r+1)}(this.columnAnchor,e,s);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.#i()),this.requestAfterRender()}}deselectColumn(e){this.#s.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.#i()),this.requestAfterRender())}selectAllColumns(){if(!this.#s.columnEnabled)return;if(!1===this.config.multiSelect)return;const e=C(this.visibleColumns);if(0!==e.length){this.#d("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.#i()),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.#i()),this.requestAfterRender())}getSelectedColumns(){return 0===this.selectedColumns.size?[]:C(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.#i()),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.#i()),this.requestAfterRender()}#i(){const e=this.#s.primary,t="row"===e&&this.selected.size>0||"cell"===e&&null!==this.selectedCell||"range"===e&&this.ranges.length>0;let s;this.#s.bothAxes&&t&&this.selectedColumns.size>0&&(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.gridElement&&i(this.gridElement,n(this.gridElement,"selectionAxisChanged","row"))),s=t?"row"===e?"row":"cell"===e?"cell":"range":this.selectedColumns.size>0?"column":"none",this.activeAxis=s;const o=function(e,t,s,i,n,o){if("column"===t&&i.selectedColumns.size>0)return{mode:e,activeAxis:"column",ranges:[],selectedColumns:o.filter(e=>i.selectedColumns.has(e))};if("cell"===s&&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"===s&&i.selected.size>0){const t=[...i.selected].sort((e,t)=>e-t),s=[];let o=t[0],r=o;for(let e=1;e<t.length;e++)t[e]===r+1?r=t[e]:(s.push({from:{row:o,col:0},to:{row:r,col:n-1}}),o=t[e],r=o);return s.push({from:{row:o,col:0},to:{row:r,col:n-1}}),{mode:e,activeAxis:"row",ranges:s,selectedColumns:[]}}return"range"===s&&i.ranges.length>0?{mode:e,activeAxis:"range",ranges:(r=i.ranges,r.map(S)),selectedColumns:[]}:{mode:e,activeAxis:"none",ranges:[],selectedColumns:[]};var r}(this.config.mode,s,e,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges,selectedColumns:this.selectedColumns},this.columns.length,C(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],s=this.columns.find(e=>e.field===t),o="string"==typeof s?.header&&s.header||t;i(this.gridElement,n(this.gridElement,"columnSelected",o))}else e.length>1?i(this.gridElement,n(this.gridElement,"columnSelectionChanged",e.length)):i(this.gridElement,n(this.gridElement,"columnSelectionCleared"))}else{const e="row"===o.activeAxis?this.selected.size:o.ranges.length;e>0&&i(this.gridElement,n(this.gridElement,"selectionChanged",e))}},150),o}#d(e){if(this.#s.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,n(this.gridElement,"selectionAxisChanged","column"))}}};export{I 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`},s={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 s=e.querySelector?.(".tbw-sr-only");s&&(s.textContent="","function"==typeof requestAnimationFrame?requestAnimationFrame(()=>{s.textContent=t}):s.textContent=t)}function n(e,s,...i){const n=(e&&"effectiveConfig"in e?e.effectiveConfig:void 0)?.a11y?.messages?.[s];return n?n(...i):t[s](...i)}function o(e){if(!e)return-1;const t=e.getAttribute("data-row");if(t)return parseInt(t,10);const s=e.closest(".data-grid-row");if(!s)return-1;const i=s.parentElement;if(!i)return-1;const n=i.querySelectorAll(":scope > .data-grid-row");for(let o=0;o<n.length;o++)if(n[o]===s)return o;return-1}function r(e){e&&e.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus"))}function l(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function c(e,t,s,i){return`${l(s,i)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}var a="__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("")),d=(new RegExp(`__(proto|defineGetter|defineSetter)|${a.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".split("|"))),h=/^on\w+$/i,u=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),g=/^\s*(javascript|vbscript|data|blob):/i;function m(e){if(!e||"string"!=typeof e)return"";if(-1===e.indexOf("<"))return e;const t=document.createElement("template");return t.innerHTML=e,function(e){const t=[],s=e.querySelectorAll("*");for(const i of s){const e=i.tagName.toLowerCase();if(d.has(e)){t.push(i);continue}if(("svg"===e||"http://www.w3.org/2000/svg"===i.namespaceURI)&&Array.from(i.attributes).some(e=>h.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(i);continue}const s=[];for(const t of i.attributes){const e=t.name.toLowerCase();h.test(e)?s.push(t.name):(u.has(e)&&g.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&s.push(t.name)}s.forEach(e=>i.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}var f=class{static dependencies;static manifest;aliases;version="3.1.0";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},s={};for(const i of Object.keys(t))s[i]=this;for(const i of e){const e=i.userConfig;for(const[n,o]of Object.entries(e)){if(void 0===o)continue;if(!(n in t)){t[n]=o,s[n]=i;continue}if(t[n]===o)continue;const e=s[n]?.constructor.name??this.constructor.name,r=i.constructor.name,l=c("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${n}" 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,s={...e.userConfig};for(const i of Object.keys(t))delete t[i];Object.assign(t,s)}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 s=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(s),s.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)}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{...s,...e}}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(),s=parseInt(t,10);if(!isNaN(s))return s}return 200}setIcon(e,t,s){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,s);void 0!==i?"string"==typeof i?e.innerHTML=m(i):i instanceof HTMLElement&&(e.innerHTML="",e.appendChild(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 s=document.createElement("span");s.setAttribute("part","sort-indicator"),s.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(s,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(s,"sortNone"));const i=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return i?e.insertBefore(s,i):e.appendChild(s),s}warn(e,t){void 0!==t?console.warn(c(e,t,this.gridElement.id,this.name)):console.warn(`${l(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(c(e,t,this.gridElement.id,this.name))}};function w(e){return"__tbw_expander"===e.field}function b(e){return!0===e.utility}function p(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 p(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 s=e.find(e=>"column"!==e);if("column"===s)throw new Error(`[SelectionPlugin] Invalid selection mode: [${e.join(", ")}].`);return{primary:s,columnEnabled:!0,bothAxes:!0}}function C(e){const t=[];for(const s of e)!0!==s.utility&&"string"==typeof s.field&&s.field.length>0&&t.push(s.field);return t}function v(e,t){return t.indexOf(e)}function y(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 S(e){const t=y(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function A(e,t,s){return s.some(s=>function(e,t,s){const i=y(s);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,s))}function R(e){const t=[],s=y(e);for(let i=s.startRow;i<=s.endRow;i++)for(let e=s.startCol;e<=s.endCol;e++)t.push({row:i,col:e});return t}function x(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function E(e,t){const s=y(e),i=y(t);return s.startRow===i.startRow&&s.startCol===i.startCol&&s.endRow===i.endRow&&s.endCol===i.endCol}function k(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 q="__tbw_checkbox";var I=class extends f{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"===k(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"!==k(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}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)}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}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";#s={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:s}=this.config;if(!s)return!0;const i=this.rows[e];return!!i&&s(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.#s=p(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.#s.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.#i()),this.requestAfterRender())))});let t=-1;e.addEventListener("data-change",e=>{const{sourceRowCount:s}=e.detail,i=this.selected.size>0||this.ranges.length>0||null!==this.selectedCell;-1!==t&&s!==t&&i&&this.clearSelectionSilent(),t=s},{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.#n(t),!0}}detach(){(this.gridElement?.querySelector(".rows-body"))?.removeAttribute("aria-multiselectable"),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()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:i}=e,{triggerOn:n="click"}=this.config,o=this.#s.primary;if(i.type!==n)return!1;const r=e.column,l=r&&b(r);if("cell"===o){if(l)return!1;if(!this.isCellSelectable(t,s))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#i()),this.requestAfterRender()),!1}if("row"===o){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,s=i.shiftKey&&e,n=(i.ctrlKey||i.metaKey)&&e,o=!0===r?.checkboxColumn;if(s&&null!==this.anchor){const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);n||this.selected.clear();for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(n||o&&e)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.#i()),this.requestAfterRender(),!1}if("range"===o){if(l)return!1;if(!this.isCellSelectable(t,s))return!1;const e=i.shiftKey,n=(i.ctrlKey||i.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=x(this.cellAnchor,{row:t,col:s}),i=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(i&&E(i,e))return!1;n?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(n){const e={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:s}}else{const e={startRow:t,startCol:s,endRow:t,endCol:s};if(1===this.ranges.length&&E(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#i()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const t=this.#s.primary,s=this.#s.columnEnabled,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(s&&(e.ctrlKey||e.metaKey)&&(" "===e.key||"Spacebar"===e.key)){const t=this.grid._focusCol,s=this.visibleColumns[t];if(s&&!b(s)&&"string"==typeof s.field)return e.preventDefault(),e.stopPropagation(),this.selectColumn(s.field,{toggle:!0}),!0}if(s&&"column"===this.activeAxis&&!1!==this.config.multiSelect&&(e.ctrlKey||e.metaKey)&&e.shiftKey&&("ArrowLeft"===e.key||"ArrowRight"===e.key)){const t=C(this.visibleColumns),s="ArrowLeft"===e.key?"left":"right",i=function(e,t,s){if(0===t.length)return null;if(null===e)return null;const i=v(e,t);if(i<0)return null;const n="left"===s?Math.max(0,i-1):Math.min(t.length-1,i+1);return n===i?null:t[n]}(this.columnHead,t,s);if(null!==i&&null!==this.columnAnchor)return e.preventDefault(),e.stopPropagation(),this.selectColumn(i,{range:!0}),!0}if("Escape"===e.key)return!this.grid.query("isEditing").some(Boolean)&&("column"===this.activeAxis?(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.activeAxis="none",this.emit("selection-change",this.#i()),this.requestAfterRender(),!0):("cell"===t?this.selectedCell=null:"row"===t?(this.selected.clear(),this.anchor=null):"range"===t&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#i()),this.requestAfterRender(),!0));if("cell"===t&&i)return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.isCellSelectable(e,t)?this.selectedCell={row:e,col:t}:this.selectedCell=null,this.emit("selection-change",this.#i()),this.requestAfterRender()}),!1;if("row"===t){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 s=e.shiftKey&&t;return s&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey))return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}if("range"===t&&i){const t="Tab"===e.key,s=e.shiftKey&&!t;return s&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}return!("range"!==t||!1===this.config.multiSelect||"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("range"!==this.#s.primary)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(2===e.originalEvent.button&&A(e.rowIndex,e.colIndex,this.ranges))return;if(e.column&&b(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,s=e.colIndex,i=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,n={startRow:t,startCol:s,endRow:t,endCol:s};return!i&&1===this.ranges.length&&E(this.ranges[0],n)?(this.cellAnchor={row:t,col:s},!0):(this.cellAnchor={row:t,col:s},i||(this.ranges=[]),this.ranges.push(n),this.activeRange=n,this.emit("selection-change",this.#i()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.#s.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 s=this.visibleColumns[t];if(s&&b(s)){const e=this.visibleColumns.findIndex(e=>!b(e));e>=0&&(t=e)}const i=x(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&E(n,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#i()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.#s.primary)return this.isDragging?(this.isDragging=!1,!0):void 0}onHeaderClick(e){if(!this.isSelectionEnabled())return!1;if(!this.#s.columnEnabled)return!1;if(e.column&&b(e.column))return!1;const t=e.originalEvent;if(!t.ctrlKey&&!t.metaKey)return!1;const s=e.field;if(!s)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(s,i?{range:!0}:{toggle:!0}),!0}processColumns(e){if(this.config.checkbox&&"row"===this.#s.primary){if(e.some(e=>e.field===q))return e;const t=this.#o(),s=e.findIndex(w),i=s>=0?s+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#o(){return{field:q,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 s=e.cellEl;if(s){const e=parseInt(s.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#r(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const t=e.closest(".cell"),s=t?o(t):-1;s>=0&&(e.checked=this.selected.has(s))});const t=e.querySelector(".tbw-select-all-checkbox");if(t){const e=this.rows.length;let s=0;if(this.config.isSelectable)for(let t=0;t<e;t++)this.isRowSelectable(t)&&s++;else s=e;const i=s>0&&this.selected.size>=s,n=this.selected.size>0;t.checked=i,t.indeterminate=n&&!i}}#l(){return this.gridElement?.hasAttribute("data-has-focus")??!1}#c(e){const t=this.grid._focusRow,s=this.grid._focusCol;if(!this.#l())return this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);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.#i()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const e=this.selectedCell;e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#i()))}}}#a(){const t=this.gridElement;if(!t)return;const s=this.#s.primary,i=this.#s.columnEnabled,n=!!this.config.isSelectable,l=t.querySelector(".rows-body");if(l){const e=!1!==this.config.multiSelect;l.setAttribute("aria-multiselectable",e?"true":"false")}t.querySelectorAll(".cell").forEach(t=>{const s=t.classList.contains(e)||t.classList.contains("column-selected");t.classList.remove(e,"top","bottom","first","last","column-selected"),s&&t.removeAttribute("aria-selected"),n&&t.removeAttribute("data-selectable")});const c=t.querySelectorAll(".data-grid-row");if(c.forEach(t=>{t.classList.remove(e,"row-focus"),t.setAttribute("aria-selected","false"),n&&t.removeAttribute("data-selectable")}),i&&t.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("column-selected"),e.removeAttribute("aria-selected")}),"row"===s&&(r(t),c.forEach(t=>{const s=o(t.querySelector(".cell[data-row]"));s>=0&&(n&&!this.isRowSelectable(s)&&t.setAttribute("data-selectable","false"),this.selected.has(s)&&(t.classList.add(e,"row-focus"),t.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#r(t)),"cell"!==s&&"range"!==s||!n||t.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&s>=0&&(this.isCellSelectable(t,s)||e.setAttribute("data-selectable","false"))}),"range"===s&&this.ranges.length>0){r(t);const s=this.ranges.map(y),i=(e,t)=>{for(const i of s)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 s=parseInt(t.getAttribute("data-row")??"-1",10),n=parseInt(t.getAttribute("data-col")??"-1",10);if(s>=0&&n>=0){const o=this.visibleColumns[n];if(o&&b(o))return;i(s,n)&&(t.classList.add(e),t.setAttribute("aria-selected","true"),i(s-1,n)||t.classList.add("top"),i(s+1,n)||t.classList.add("bottom"),i(s,n-1)||t.classList.add("first"),i(s,n+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 s=parseInt(t.getAttribute("data-col")??"-1",10),i=s>=0?e[s]: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 s=parseInt(t.getAttribute("data-col")??"-1",10);if(s<0)return;const i=this.visibleColumns[s];if(!i||b(i))return;const n=e[s];n&&this.selectedColumns.has(n)&&(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"),s=this.#s.primary;if(this.pendingRowKeyUpdate&&"row"===s){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),s=Math.max(this.anchor,t);for(let t=e;t<=s;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.#i())}if(this.pendingKeyboardUpdate&&"range"===s){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,s=this.grid._focusCol;if(e&&this.cellAnchor){const e=x(this.cellAnchor,{row:t,col:s});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:s});this.emit("selection-change",this.#i())}this.#c(s),this.gridElement.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#a()}onScrollRender(){this.isSelectionEnabled()&&this.#a()}getSelection(){const e=this.#i();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 s of e)for(const e of R(s))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return A(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.#i()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const s={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[s],this.activeRange=s,this.emit("selection-change",this.#i()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.#s.primary)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#i()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const e=this.#s.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 s of this.ranges){const i=Math.max(0,Math.min(s.startRow,s.endRow)),n=Math.min(t.length-1,Math.max(s.startRow,s.endRow));for(let t=i;t<=n;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}#n(e){if(!this.#s.columnEnabled)return;const t=C(this.visibleColumns),s=new Set(t),i=[],n=/* @__PURE__ */new Set;for(const r of e)s.has(r)&&!n.has(r)&&(n.add(r),i.push(r));this.#d("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.#i()),this.requestAfterRender()}selectColumn(e,t={}){if(!this.#s.columnEnabled)return;const s=C(this.visibleColumns);if(s.includes(e)){if(this.#d("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,s){const i=v(e,s),n=v(t,s);if(-1===i||-1===n)return[];const o=Math.min(i,n),r=Math.max(i,n);return s.slice(o,r+1)}(this.columnAnchor,e,s);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.#i()),this.requestAfterRender()}}deselectColumn(e){this.#s.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.#i()),this.requestAfterRender())}selectAllColumns(){if(!this.#s.columnEnabled)return;if(!1===this.config.multiSelect)return;const e=C(this.visibleColumns);if(0!==e.length){this.#d("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.#i()),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.#i()),this.requestAfterRender())}getSelectedColumns(){return 0===this.selectedColumns.size?[]:C(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.#i()),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.#i()),this.requestAfterRender()}#i(){const e=this.#s.primary,t="row"===e&&this.selected.size>0||"cell"===e&&null!==this.selectedCell||"range"===e&&this.ranges.length>0;let s;this.#s.bothAxes&&t&&this.selectedColumns.size>0&&(this.selectedColumns.clear(),this.columnAnchor=null,this.columnHead=null,this.gridElement&&i(this.gridElement,n(this.gridElement,"selectionAxisChanged","row"))),s=t?"row"===e?"row":"cell"===e?"cell":"range":this.selectedColumns.size>0?"column":"none",this.activeAxis=s;const o=function(e,t,s,i,n,o){if("column"===t&&i.selectedColumns.size>0)return{mode:e,activeAxis:"column",ranges:[],selectedColumns:o.filter(e=>i.selectedColumns.has(e))};if("cell"===s&&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"===s&&i.selected.size>0){const t=[...i.selected].sort((e,t)=>e-t),s=[];let o=t[0],r=o;for(let e=1;e<t.length;e++)t[e]===r+1?r=t[e]:(s.push({from:{row:o,col:0},to:{row:r,col:n-1}}),o=t[e],r=o);return s.push({from:{row:o,col:0},to:{row:r,col:n-1}}),{mode:e,activeAxis:"row",ranges:s,selectedColumns:[]}}return"range"===s&&i.ranges.length>0?{mode:e,activeAxis:"range",ranges:(r=i.ranges,r.map(S)),selectedColumns:[]}:{mode:e,activeAxis:"none",ranges:[],selectedColumns:[]};var r}(this.config.mode,s,e,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges,selectedColumns:this.selectedColumns},this.columns.length,C(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],s=this.columns.find(e=>e.field===t),o="string"==typeof s?.header&&s.header||t;i(this.gridElement,n(this.gridElement,"columnSelected",o))}else e.length>1?i(this.gridElement,n(this.gridElement,"columnSelectionChanged",e.length)):i(this.gridElement,n(this.gridElement,"columnSelectionCleared"))}else{const e="row"===o.activeAxis?this.selected.size:o.ranges.length;e>0&&i(this.gridElement,n(this.gridElement,"selectionChanged",e))}},150),o}#d(e){if(this.#s.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,n(this.gridElement,"selectionAxisChanged","column"))}}};export{I as SelectionPlugin};
2
2
  //# sourceMappingURL=index.js.map