@toolbox-web/grid 3.0.0-beta.2 → 3.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/all.js +2 -2
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/lib/features/registry.js +1 -1
  5. package/lib/plugins/clipboard/clipboard-payload.d.ts +47 -0
  6. package/lib/plugins/clipboard/copy.d.ts +9 -2
  7. package/lib/plugins/clipboard/index.js +1 -1
  8. package/lib/plugins/clipboard/index.js.map +1 -1
  9. package/lib/plugins/clipboard/types.d.ts +18 -0
  10. package/lib/plugins/column-virtualization/index.js +1 -1
  11. package/lib/plugins/context-menu/index.js +1 -1
  12. package/lib/plugins/editing/index.js +1 -1
  13. package/lib/plugins/export/index.js +1 -1
  14. package/lib/plugins/filtering/index.js +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/reorder-columns/index.js +1 -1
  24. package/lib/plugins/responsive/index.js +1 -1
  25. package/lib/plugins/row-drag-drop/index.js +1 -1
  26. package/lib/plugins/selection/index.js +1 -1
  27. package/lib/plugins/server-side/index.js +1 -1
  28. package/lib/plugins/shell/index.js +1 -1
  29. package/lib/plugins/sticky-rows/index.js +1 -1
  30. package/lib/plugins/tooltip/index.js +1 -1
  31. package/lib/plugins/tree/index.js +1 -1
  32. package/lib/plugins/undo-redo/index.js +1 -1
  33. package/lib/plugins/visibility/index.js +1 -1
  34. package/package.json +1 -1
  35. package/umd/grid.all.umd.js +1 -1
  36. package/umd/grid.all.umd.js.map +1 -1
  37. package/umd/grid.umd.js +1 -1
  38. package/umd/plugins/clipboard.umd.js +1 -1
  39. package/umd/plugins/clipboard.umd.js.map +1 -1
@@ -1,2 +1,2 @@
1
- const e="editing",t="dragging";function r(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function i(e,t,i,n){return`${r(i,n)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const n="__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(""));new RegExp(`__(proto|defineGetter|defineSetter)|${n.slice(3).join("|")}|this\\b`);const o=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("|")),s=/^on\w+$/i,a=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),l=/^\s*(javascript|vbscript|data|blob):/i;function d(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 i of r){const e=i.tagName.toLowerCase();if(o.has(e)){t.push(i);continue}if("svg"===e||"http://www.w3.org/2000/svg"===i.namespaceURI){if(Array.from(i.attributes).some(e=>s.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(i);continue}}const r=[];for(const t of i.attributes){const e=t.name.toLowerCase();s.test(e)?r.push(t.name):(a.has(e)&&l.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name)}r.forEach(e=>i.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function c(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,i=t.rawContentHeight-t.viewportHeight;return r<=0||i<=0?e:e*r/i}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const u={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class g{static dependencies;static manifest;aliases;version="3.0.0-beta.2";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 i of Object.keys(t))r[i]=this;for(const n of e){const e=n.userConfig;for(const[o,s]of Object.entries(e)){if(void 0===s)continue;if(!(o in t)){t[o]=s,r[o]=n;continue}if(t[o]===s)continue;const e=r[o]?.constructor.name??this.constructor.name,a=n.constructor.name,l=i("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${o}" supplied by both ${e} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,r={...e.userConfig};for(const i of Object.keys(t))delete t[i];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{...u,...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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}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 i=this.#t(t,r);void 0!==i?"string"==typeof i?e.innerHTML=d(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 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 i=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return i?e.insertBefore(r,i):e.appendChild(r),r}warn(e,t){void 0!==t?console.warn(i(e,t,this.gridElement.id,this.name)):console.warn(`${r(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(i(e,t,this.gridElement.id,this.name))}}function f(e){if(!0===e.lockPosition)return!1;if(!0===e.utility)return!1;const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}function h(e,t,r){if(t===r)return e;if(t<0||t>=e.length)return e;if(r<0||r>e.length)return e;const i=[...e],[n]=i.splice(t,1);return i.splice(r,0,n),i}const m="canMoveColumn";class p extends g{name="reorderColumns";aliases=["reorder"];styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';static manifest={queries:[{type:m,description:"Authoritative check for whether a column may be reordered (honors lockPosition)."}]};handleQuery(e){if(e.type===m){const t=e.context;return t?f(t):void 0}}get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupFields=[];originalColumnOrder=null;get#r(){return this.grid}canMoveColumnWithPlugins(e){if(!e||!f(e))return!1;return!this.grid.query(m,e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell, .header-group-row > .cell").forEach(e=>{e.classList.remove(t,"drop-target","drop-before","drop-after")})}attach(e){super.attach(e),this.gridElement.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[]}afterRender(){const e=this.gridElement;if(!e)return;this.originalColumnOrder||(this.originalColumnOrder=this.columns.map(e=>e.field));e.querySelectorAll(".header-row > .cell").forEach(e=>{const r=e,i=r.getAttribute("data-field");if(!i)return;const n=this.columns.find(e=>e.field===i);this.canMoveColumnWithPlugins(n)?(r.draggable=!0,r.getAttribute("data-dragstart-bound")||(r.setAttribute("data-dragstart-bound","true"),r.addEventListener("dragstart",e=>{const n=this.getColumnOrder().indexOf(i);this.isDragging=!0,this.draggedField=i,this.draggedIndex=n,this.draggedGroupFields=[],e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)),r.classList.add(t)}),r.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[],this.clearDragClasses()}),r.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedField===i&&0===this.draggedGroupFields.length)return;if(this.draggedGroupFields.includes(i))return;const n=r.getBoundingClientRect(),o=n.left+n.width/2,s=this.getColumnOrder().indexOf(i);if(this.dropIndex=e.clientX<o?s:s+1,this.clearDragClasses(),this.draggedGroupFields.length>0)for(const r of this.draggedGroupFields)this.gridElement?.querySelector(`.header-row > .cell[data-field="${r}"]`)?.classList.add(t);else this.draggedField&&this.gridElement?.querySelector(`.header-row > .cell[data-field="${this.draggedField}"]`)?.classList.add(t);r.classList.add("drop-target"),r.classList.toggle("drop-before",e.clientX<o),r.classList.toggle("drop-after",e.clientX>=o)}),r.addEventListener("dragleave",()=>{r.classList.remove("drop-target","drop-before","drop-after")}),r.addEventListener("drop",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length>0){if(this.draggedGroupFields.includes(i))return;const t=r.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;return void this.executeGroupBlockMove(this.draggedGroupFields,[i],n)}const t=this.draggedField,n=this.draggedIndex,o=this.dropIndex;if(!this.isDragging||null===t||null===n||null===o)return;const s=o>n?o-1:o,a=h(this.getColumnOrder(),n,s),l={field:t,fromIndex:n,toIndex:s,columnOrder:a};this.emitCancelable("column-move",l)||this.updateColumnOrder(a)}))):r.draggable=!1}),queueMicrotask(()=>this.setupGroupHeaderDrag(e))}setupGroupHeaderDrag(e){e.querySelectorAll(".header-group-row > .cell[data-group]").forEach(r=>{const i=r,n=i.getAttribute("data-group");if(!n||n.startsWith("__implicit__"))return;if(i.getAttribute("data-group-drag-bound"))return;i.setAttribute("data-group-drag-bound","true");const o=this.getGroupFragmentFields(i,n);if(0===o.length)return;o.every(e=>{const t=this.columns.find(t=>t.field===e);return this.canMoveColumnWithPlugins(t)})&&(i.draggable=!0,i.style.cursor="grab",i.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=null,this.draggedIndex=null,this.draggedGroupFields=[...o],r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",`group:${n}`)),i.classList.add(t);for(const i of o)e.querySelector(`.header-row > .cell[data-field="${i}"]`)?.classList.add(t)}),i.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[],this.clearDragClasses()}),i.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length>0&&this.draggedGroupFields.length===o.length&&this.draggedGroupFields.every(e=>o.includes(e)))return;const t=i.getBoundingClientRect(),r=t.left+t.width/2,n=e.clientX<r;this.clearDragClasses(),i.classList.add("drop-target"),i.classList.toggle("drop-before",n),i.classList.toggle("drop-after",!n)}),i.addEventListener("dragleave",()=>{i.classList.remove("drop-target","drop-before","drop-after")}),i.addEventListener("drop",e=>{if(e.preventDefault(),!this.isDragging)return;const t=i.getBoundingClientRect(),r=e.clientX<t.left+t.width/2;if(this.draggedGroupFields.length>0){if(this.draggedGroupFields.length===o.length&&this.draggedGroupFields.every(e=>o.includes(e)))return;this.executeGroupBlockMove(this.draggedGroupFields,o,r)}else if(this.draggedField){const e=this.getColumnOrder(),t=r?o[0]:o[o.length-1],i=e.indexOf(this.draggedField),n=r?e.indexOf(t):e.indexOf(t)+1;if(-1===i||-1===n)return;const s=n>i?n-1:n,a=h(e,i,s);this.emitCancelable("column-move",{field:this.draggedField,fromIndex:i,toIndex:s,columnOrder:a})||this.updateColumnOrder(a)}}))})}getGroupFragmentFields(e,t){const r=e.style.gridColumn,i=/(\d+)\s*\/\s*span\s+(\d+)/.exec(r);if(!i)return[];const n=parseInt(i[1],10),o=parseInt(i[2],10),s=this.visibleColumns,a=[];for(let l=n-1;l<n-1+o&&l<s.length;l++){const e=s[l];e&&a.push(e.field)}return a}executeGroupBlockMove(e,t,r){const i=this.getColumnOrder(),n=i.filter(t=>!e.includes(t)),o=r?t[0]:t[t.length-1],s=n.indexOf(o);if(-1===s)return;const a=r?s:s+1,l=i.filter(t=>e.includes(t));n.splice(a,0,...l);this.emitCancelable("column-move",{field:e[0],fromIndex:i.indexOf(e[0]),toIndex:a,columnOrder:n})||this.updateColumnOrder(n)}onKeyDown(t){if(!t.altKey||"ArrowLeft"!==t.key&&"ArrowRight"!==t.key)return;const r=this.#r,i=r._focusCol,n=r._visibleColumns;if(i<0||i>=n.length)return;const o=n[i];if(!this.canMoveColumnWithPlugins(o))return;const s=this.getColumnOrder(),a=s.indexOf(o.field);if(-1===a)return;const l="ArrowLeft"===t.key?a-1:a+1;if(l<0||l>=s.length)return;const d=n.find(e=>e.field===s[l]);return this.canMoveColumnWithPlugins(d)?(this.moveColumn(o.field,l),r._focusCol=l,function(t,r){if(t._virtualization?.enabled){const{rowHeight:e,container:r,viewportEl:i,scrollMapping:n}=t._virtualization,o=r,s=i?.clientHeight??o?.clientHeight??0;if(o&&s>0){const r=t._focusRow*e,i=n?function(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,i=t.rawContentHeight-t.viewportHeight;if(r<=0||i<=0)return e;const n=e*i/r;return n<0?0:n>i?i:n}(o.scrollTop,n):o.scrollTop;if(r<i)o.scrollTop=n?c(r,n):r;else if(r+e>i+s){const t=r-s+e;o.scrollTop=n?c(t,n):t}}}const i=void 0!==t._activeEditRows&&-1!==t._activeEditRows||!!t._isGridEditMode;var n;i||t.refreshVirtualWindow(!1),(n=t._bodyEl)&&n.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 o=t._focusRow,s=t._virtualization.start??0,a=t._virtualization.end??t._rows.length;if(o>=s&&o<a){const n=t._bodyEl.querySelectorAll(".data-grid-row")[o-s];let a=n?.children[t._focusCol];if(a&&a.classList?.contains("cell")||(a=n?.querySelector(`.cell[data-col="${t._focusCol}"]`)??n?.querySelector(".cell[data-col]")),a){a.classList.add("cell-focus"),a.setAttribute("aria-selected","true");const o=t.querySelector(".tbw-scroll-area");if(o&&a&&(!i||r?.forceHorizontalScroll)){const e=t._getHorizontalScrollOffsets?.(n??void 0,a)??{left:0,right:0};if(!e.skipScroll){const t=a.getBoundingClientRect(),r=o.getBoundingClientRect(),i=t.left-r.left+o.scrollLeft,n=i+t.width,s=o.scrollLeft+e.left,l=o.scrollLeft+o.clientWidth-e.right;i<s?o.scrollLeft=i-e.left:n>l&&(o.scrollLeft=n-o.clientWidth+e.right)}}if(i&&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(i&&!a.contains(document.activeElement)){a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1");try{a.focus({preventScroll:!0})}catch{}}else if(!i){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})}}}}(this.#r),t.preventDefault(),t.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const r=this.getColumnOrder(),i=r.indexOf(e);if(-1===i)return;const n=h(r,i,t);this.emitCancelable("column-move",{field:e,fromIndex:i,toIndex:t,columnOrder:n})||this.updateColumnOrder(n)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.originalColumnOrder??this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=/* @__PURE__ */new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");r&&e.set(r,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const r=/* @__PURE__ */new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");if(!i)return;const n=e.get(i);if(void 0===n)return;const o=n-t.getBoundingClientRect().left;Math.abs(o)>1&&r.set(i,o)}),0===r.size)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=r.get(e.getAttribute("data-field")??"");if(void 0!==t){const r=e;r.style.transform=`translateX(${t}px)`,i.push(r)}}),0===i.length)return;t.offsetHeight;const n=this.animationDuration;requestAnimationFrame(()=>{i.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{i.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},n+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const r=this.captureHeaderPositions();e();const i=/* @__PURE__ */new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const n=r.get(t);if(void 0===n)return;const o=e.getBoundingClientRect().left;Math.abs(n-o)>1&&i.add(t)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&i.has(t)){const t=e;t.classList.add("fade-animating"),n.push(t)}}),0===n.length)return;const o=this.animationDuration;setTimeout(()=>{n.forEach(e=>e.classList.remove("fade-animating"))},o+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),"function"==typeof this.grid.forceLayout?this.grid.forceLayout().then(()=>{this.animateFLIP(t)}):requestAnimationFrame(()=>{this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}}export{p as ReorderPlugin};
1
+ const e="editing",t="dragging";function r(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function i(e,t,i,n){return`${r(i,n)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const n="__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(""));new RegExp(`__(proto|defineGetter|defineSetter)|${n.slice(3).join("|")}|this\\b`);const o=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("|")),s=/^on\w+$/i,a=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),l=/^\s*(javascript|vbscript|data|blob):/i;function d(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 i of r){const e=i.tagName.toLowerCase();if(o.has(e)){t.push(i);continue}if("svg"===e||"http://www.w3.org/2000/svg"===i.namespaceURI){if(Array.from(i.attributes).some(e=>s.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(i);continue}}const r=[];for(const t of i.attributes){const e=t.name.toLowerCase();s.test(e)?r.push(t.name):(a.has(e)&&l.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&r.push(t.name)}r.forEach(e=>i.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function c(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,i=t.rawContentHeight-t.viewportHeight;return r<=0||i<=0?e:e*r/i}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const u={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class g{static dependencies;static manifest;aliases;version="3.0.0-beta.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},r={};for(const i of Object.keys(t))r[i]=this;for(const n of e){const e=n.userConfig;for(const[o,s]of Object.entries(e)){if(void 0===s)continue;if(!(o in t)){t[o]=s,r[o]=n;continue}if(t[o]===s)continue;const e=r[o]?.constructor.name??this.constructor.name,a=n.constructor.name,l=i("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${o}" supplied by both ${e} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(l)}}Object.assign(this.userConfig,t)}refreshUserConfigFrom(e){const t=this.userConfig,r={...e.userConfig};for(const i of Object.keys(t))delete t[i];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{...u,...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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}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 i=this.#t(t,r);void 0!==i?"string"==typeof i?e.innerHTML=d(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 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 i=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return i?e.insertBefore(r,i):e.appendChild(r),r}warn(e,t){void 0!==t?console.warn(i(e,t,this.gridElement.id,this.name)):console.warn(`${r(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(i(e,t,this.gridElement.id,this.name))}}function f(e){if(!0===e.lockPosition)return!1;if(!0===e.utility)return!1;const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}function h(e,t,r){if(t===r)return e;if(t<0||t>=e.length)return e;if(r<0||r>e.length)return e;const i=[...e],[n]=i.splice(t,1);return i.splice(r,0,n),i}const m="canMoveColumn";class p extends g{name="reorderColumns";aliases=["reorder"];styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';static manifest={queries:[{type:m,description:"Authoritative check for whether a column may be reordered (honors lockPosition)."}]};handleQuery(e){if(e.type===m){const t=e.context;return t?f(t):void 0}}get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupFields=[];originalColumnOrder=null;get#r(){return this.grid}canMoveColumnWithPlugins(e){if(!e||!f(e))return!1;return!this.grid.query(m,e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell, .header-group-row > .cell").forEach(e=>{e.classList.remove(t,"drop-target","drop-before","drop-after")})}attach(e){super.attach(e),this.gridElement.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[]}afterRender(){const e=this.gridElement;if(!e)return;this.originalColumnOrder||(this.originalColumnOrder=this.columns.map(e=>e.field));e.querySelectorAll(".header-row > .cell").forEach(e=>{const r=e,i=r.getAttribute("data-field");if(!i)return;const n=this.columns.find(e=>e.field===i);this.canMoveColumnWithPlugins(n)?(r.draggable=!0,r.getAttribute("data-dragstart-bound")||(r.setAttribute("data-dragstart-bound","true"),r.addEventListener("dragstart",e=>{const n=this.getColumnOrder().indexOf(i);this.isDragging=!0,this.draggedField=i,this.draggedIndex=n,this.draggedGroupFields=[],e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",i)),r.classList.add(t)}),r.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[],this.clearDragClasses()}),r.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedField===i&&0===this.draggedGroupFields.length)return;if(this.draggedGroupFields.includes(i))return;const n=r.getBoundingClientRect(),o=n.left+n.width/2,s=this.getColumnOrder().indexOf(i);if(this.dropIndex=e.clientX<o?s:s+1,this.clearDragClasses(),this.draggedGroupFields.length>0)for(const r of this.draggedGroupFields)this.gridElement?.querySelector(`.header-row > .cell[data-field="${r}"]`)?.classList.add(t);else this.draggedField&&this.gridElement?.querySelector(`.header-row > .cell[data-field="${this.draggedField}"]`)?.classList.add(t);r.classList.add("drop-target"),r.classList.toggle("drop-before",e.clientX<o),r.classList.toggle("drop-after",e.clientX>=o)}),r.addEventListener("dragleave",()=>{r.classList.remove("drop-target","drop-before","drop-after")}),r.addEventListener("drop",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length>0){if(this.draggedGroupFields.includes(i))return;const t=r.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;return void this.executeGroupBlockMove(this.draggedGroupFields,[i],n)}const t=this.draggedField,n=this.draggedIndex,o=this.dropIndex;if(!this.isDragging||null===t||null===n||null===o)return;const s=o>n?o-1:o,a=h(this.getColumnOrder(),n,s),l={field:t,fromIndex:n,toIndex:s,columnOrder:a};this.emitCancelable("column-move",l)||this.updateColumnOrder(a)}))):r.draggable=!1}),queueMicrotask(()=>this.setupGroupHeaderDrag(e))}setupGroupHeaderDrag(e){e.querySelectorAll(".header-group-row > .cell[data-group]").forEach(r=>{const i=r,n=i.getAttribute("data-group");if(!n||n.startsWith("__implicit__"))return;if(i.getAttribute("data-group-drag-bound"))return;i.setAttribute("data-group-drag-bound","true");const o=this.getGroupFragmentFields(i,n);if(0===o.length)return;o.every(e=>{const t=this.columns.find(t=>t.field===e);return this.canMoveColumnWithPlugins(t)})&&(i.draggable=!0,i.style.cursor="grab",i.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=null,this.draggedIndex=null,this.draggedGroupFields=[...o],r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",`group:${n}`)),i.classList.add(t);for(const i of o)e.querySelector(`.header-row > .cell[data-field="${i}"]`)?.classList.add(t)}),i.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.draggedGroupFields=[],this.clearDragClasses()}),i.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length>0&&this.draggedGroupFields.length===o.length&&this.draggedGroupFields.every(e=>o.includes(e)))return;const t=i.getBoundingClientRect(),r=t.left+t.width/2,n=e.clientX<r;this.clearDragClasses(),i.classList.add("drop-target"),i.classList.toggle("drop-before",n),i.classList.toggle("drop-after",!n)}),i.addEventListener("dragleave",()=>{i.classList.remove("drop-target","drop-before","drop-after")}),i.addEventListener("drop",e=>{if(e.preventDefault(),!this.isDragging)return;const t=i.getBoundingClientRect(),r=e.clientX<t.left+t.width/2;if(this.draggedGroupFields.length>0){if(this.draggedGroupFields.length===o.length&&this.draggedGroupFields.every(e=>o.includes(e)))return;this.executeGroupBlockMove(this.draggedGroupFields,o,r)}else if(this.draggedField){const e=this.getColumnOrder(),t=r?o[0]:o[o.length-1],i=e.indexOf(this.draggedField),n=r?e.indexOf(t):e.indexOf(t)+1;if(-1===i||-1===n)return;const s=n>i?n-1:n,a=h(e,i,s);this.emitCancelable("column-move",{field:this.draggedField,fromIndex:i,toIndex:s,columnOrder:a})||this.updateColumnOrder(a)}}))})}getGroupFragmentFields(e,t){const r=e.style.gridColumn,i=/(\d+)\s*\/\s*span\s+(\d+)/.exec(r);if(!i)return[];const n=parseInt(i[1],10),o=parseInt(i[2],10),s=this.visibleColumns,a=[];for(let l=n-1;l<n-1+o&&l<s.length;l++){const e=s[l];e&&a.push(e.field)}return a}executeGroupBlockMove(e,t,r){const i=this.getColumnOrder(),n=i.filter(t=>!e.includes(t)),o=r?t[0]:t[t.length-1],s=n.indexOf(o);if(-1===s)return;const a=r?s:s+1,l=i.filter(t=>e.includes(t));n.splice(a,0,...l);this.emitCancelable("column-move",{field:e[0],fromIndex:i.indexOf(e[0]),toIndex:a,columnOrder:n})||this.updateColumnOrder(n)}onKeyDown(t){if(!t.altKey||"ArrowLeft"!==t.key&&"ArrowRight"!==t.key)return;const r=this.#r,i=r._focusCol,n=r._visibleColumns;if(i<0||i>=n.length)return;const o=n[i];if(!this.canMoveColumnWithPlugins(o))return;const s=this.getColumnOrder(),a=s.indexOf(o.field);if(-1===a)return;const l="ArrowLeft"===t.key?a-1:a+1;if(l<0||l>=s.length)return;const d=n.find(e=>e.field===s[l]);return this.canMoveColumnWithPlugins(d)?(this.moveColumn(o.field,l),r._focusCol=l,function(t,r){if(t._virtualization?.enabled){const{rowHeight:e,container:r,viewportEl:i,scrollMapping:n}=t._virtualization,o=r,s=i?.clientHeight??o?.clientHeight??0;if(o&&s>0){const r=t._focusRow*e,i=n?function(e,t){if(!t.capped)return e;const r=t.spacerHeight-t.viewportHeight,i=t.rawContentHeight-t.viewportHeight;if(r<=0||i<=0)return e;const n=e*i/r;return n<0?0:n>i?i:n}(o.scrollTop,n):o.scrollTop;if(r<i)o.scrollTop=n?c(r,n):r;else if(r+e>i+s){const t=r-s+e;o.scrollTop=n?c(t,n):t}}}const i=void 0!==t._activeEditRows&&-1!==t._activeEditRows||!!t._isGridEditMode;var n;i||t.refreshVirtualWindow(!1),(n=t._bodyEl)&&n.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 o=t._focusRow,s=t._virtualization.start??0,a=t._virtualization.end??t._rows.length;if(o>=s&&o<a){const n=t._bodyEl.querySelectorAll(".data-grid-row")[o-s];let a=n?.children[t._focusCol];if(a&&a.classList?.contains("cell")||(a=n?.querySelector(`.cell[data-col="${t._focusCol}"]`)??n?.querySelector(".cell[data-col]")),a){a.classList.add("cell-focus"),a.setAttribute("aria-selected","true");const o=t.querySelector(".tbw-scroll-area");if(o&&a&&(!i||r?.forceHorizontalScroll)){const e=t._getHorizontalScrollOffsets?.(n??void 0,a)??{left:0,right:0};if(!e.skipScroll){const t=a.getBoundingClientRect(),r=o.getBoundingClientRect(),i=t.left-r.left+o.scrollLeft,n=i+t.width,s=o.scrollLeft+e.left,l=o.scrollLeft+o.clientWidth-e.right;i<s?o.scrollLeft=i-e.left:n>l&&(o.scrollLeft=n-o.clientWidth+e.right)}}if(i&&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(i&&!a.contains(document.activeElement)){a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1");try{a.focus({preventScroll:!0})}catch{}}else if(!i){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})}}}}(this.#r),t.preventDefault(),t.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const r=this.getColumnOrder(),i=r.indexOf(e);if(-1===i)return;const n=h(r,i,t);this.emitCancelable("column-move",{field:e,fromIndex:i,toIndex:t,columnOrder:n})||this.updateColumnOrder(n)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.originalColumnOrder??this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=/* @__PURE__ */new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");r&&e.set(r,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const r=/* @__PURE__ */new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");if(!i)return;const n=e.get(i);if(void 0===n)return;const o=n-t.getBoundingClientRect().left;Math.abs(o)>1&&r.set(i,o)}),0===r.size)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=r.get(e.getAttribute("data-field")??"");if(void 0!==t){const r=e;r.style.transform=`translateX(${t}px)`,i.push(r)}}),0===i.length)return;t.offsetHeight;const n=this.animationDuration;requestAnimationFrame(()=>{i.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{i.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},n+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const r=this.captureHeaderPositions();e();const i=/* @__PURE__ */new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const n=r.get(t);if(void 0===n)return;const o=e.getBoundingClientRect().left;Math.abs(n-o)>1&&i.add(t)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&i.has(t)){const t=e;t.classList.add("fade-animating"),n.push(t)}}),0===n.length)return;const o=this.animationDuration;setTimeout(()=>{n.forEach(e=>e.classList.remove("fade-animating"))},o+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),"function"==typeof this.grid.forceLayout?this.grid.forceLayout().then(()=>{this.animateFLIP(t)}):requestAnimationFrame(()=>{this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}}export{p as ReorderPlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- function e(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function t(t,i,r,n){return`${e(r,n)} ${t}: ${i}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(t)}`}const i="editing",r=/{{\s*([^}]+)\s*}}/g,n="__DG_EMPTY__",o=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,s="__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("")),a=new RegExp(`__(proto|defineGetter|defineSetter)|${s.slice(3).join("|")}|this\\b`),d=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("|")),l=/^on\w+$/i,c=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),u=/^\s*(javascript|vbscript|data|blob):/i;function h(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=[],i=e.querySelectorAll("*");for(const r of i){const e=r.tagName.toLowerCase();if(d.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>l.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const i=[];for(const t of r.attributes){const e=t.name.toLowerCase();l.test(e)?i.push(t.name):(c.has(e)&&u.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&i.push(t.name)}i.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}function p(e,t){const i=function(e){const t=[];let i=0;for(;i<e.length;){const r=e[i];if(" "!==r){if(r>="0"&&r<="9"||"."===r&&i+1<e.length&&e[i+1]>="0"&&e[i+1]<="9"){const r=i;for(;i<e.length&&(e[i]>="0"&&e[i]<="9"||"."===e[i]);)i++;t.push({type:"num",v:Number(e.slice(r,i))});continue}if("'"===r){let r="";for(i++;i<e.length&&"'"!==e[i];)r+=e[i++];if(i>=e.length)return null;i++,t.push({type:"str",v:r});continue}if(r>="a"&&r<="z"||r>="A"&&r<="Z"||"_"===r||"$"===r){const r=i;for(;i<e.length&&/[\w$.]/.test(e[i]);)i++;t.push({type:"id",v:e.slice(r,i)});continue}if(i+2<e.length){const r=e.slice(i,i+3);if("==="===r||"!=="===r){t.push({type:"op",v:r}),i+=3;continue}}if(i+1<e.length){const r=e.slice(i,i+2);if("=="===r||"!="===r||"<="===r||">="===r||"&&"===r||"||"===r){t.push({type:"op",v:r}),i+=2;continue}}if(!"+-*/%<>!?:(),".includes(r))return null;t.push({type:"op",v:r}),i++}else i++}return t}(e);if(!i)return;const r=i;let n=0;function o(){return r[n]}function s(){return r[n++]}function a(e,t){const i=o();return!!i&&(i.type===e&&(void 0===t||i.v===t))}function d(){const e=function(){let e=l();for(;a("op","||");)s(),e=e||l();return e}();if(a("op","?")){s();const t=d();if(!a("op",":"))return;s();const i=d();return e?t:i}return e}function l(){let e=c();for(;a("op","&&");)s(),e=e&&c();return e}function c(){let e=u();for(;;){const t=o();if(!t||"op"!==t.type)break;if("==="===t.v)s(),e=e===u();else if("!=="===t.v)s(),e=e!==u();else if("=="===t.v)s(),e=e==u();else{if("!="!==t.v)break;s(),e=e!=u()}}return e}function u(){let e=h();for(;;){const t=o();if(!t||"op"!==t.type)break;if("<"===t.v)s(),e=e<h();else if(">"===t.v)s(),e=e>h();else if("<="===t.v)s(),e=e<=h();else{if(">="!==t.v)break;s(),e=e>=h()}}return e}function h(){let e=p();for(;;){const t=o();if(!t||"op"!==t.type)break;if("+"===t.v)s(),e+=p();else{if("-"!==t.v)break;s(),e-=p()}}return e}function p(){let e=g();for(;;){const t=o();if(!t||"op"!==t.type)break;if("*"===t.v)s(),e*=g();else if("/"===t.v)s(),e/=g();else{if("%"!==t.v)break;s(),e%=g()}}return e}function g(){return a("op","!")?(s(),!g()):f()}function f(){const e=o();if(e){if("num"===e.type)return s(),e.v;if("str"===e.type)return s(),e.v;if("id"===e.type)return s(),function(e){if("value"===e)return t.value;if(e.startsWith("row.")){const i=e.slice(4);return t.row?t.row[i]:void 0}if(e.startsWith("typeDefault.")){const i=e.slice(12);return t.typeDefault?t.typeDefault[i]:void 0}return"row"===e?t.row:"typeDefault"===e?t.typeDefault:void 0}(e.v);if("op"===e.type&&"("===e.v){s();const e=d();return a("op",")")&&s(),e}return"op"===e.type&&"-"===e.v?(s(),-f()):void 0}}const v=d();return n<r.length?void 0:v}function g(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],s=e.replace(r,(e,r)=>{const s=function(e,t){if(e=(e||"").trim(),!e)return n;if(f.test(e))return n;if("value"===e)return null==t.value?n:String(t.value);if(e.startsWith("row.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(4),r=t.row?t.row[i]:void 0;return null==r?n:String(r)}if(e.startsWith("typeDefault.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(12),r=t.typeDefault?t.typeDefault[i]:void 0;return null==r?n:String(r)}if(e.length>80)return n;if(!o.test(e)||a.test(e))return n;const i=e.match(/\./g);if(i&&i.length>1)return n;try{const i=p(e,t),r=null==i?"":String(i);return f.test(r)?n:r||n}catch{return n}}(r,t);return i.push({expr:r.trim(),result:s}),s}),d=(l=s)?l.replace(new RegExp(n,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):l;var l;const c=i.length&&i.every(e=>""===e.result||e.result===n);return f.test(e)||c?"":d}const f=/Reflect|Proxy|ownKeys/;document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function v(e,t){if(!t.capped)return e;const i=t.spacerHeight-t.viewportHeight,r=t.rawContentHeight-t.viewportHeight;return i<=0||r<=0?e:e*i/r}function m(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:i,viewportEl:r,scrollMapping:n}=e._virtualization,o=i,s=r?.clientHeight??o?.clientHeight??0;if(o&&s>0){const i=e._focusRow*t,r=n?function(e,t){if(!t.capped)return e;const i=t.spacerHeight-t.viewportHeight,r=t.rawContentHeight-t.viewportHeight;if(i<=0||r<=0)return e;const n=e*r/i;return n<0?0:n>r?r:n}(o.scrollTop,n):o.scrollTop;if(i<r)o.scrollTop=n?v(i,n):i;else if(i+t>r+s){const e=i-s+t;o.scrollTop=n?v(e,n):e}}}const r=void 0!==e._activeEditRows&&-1!==e._activeEditRows||!!e._isGridEditMode;var n;r||e.refreshVirtualWindow(!1),(n=e._bodyEl)&&n.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus")),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const o=e._focusRow,s=e._virtualization.start??0,a=e._virtualization.end??e._rows.length;if(o>=s&&o<a){const n=e._bodyEl.querySelectorAll(".data-grid-row")[o-s];let a=n?.children[e._focusCol];if(a&&a.classList?.contains("cell")||(a=n?.querySelector(`.cell[data-col="${e._focusCol}"]`)??n?.querySelector(".cell[data-col]")),a){a.classList.add("cell-focus"),a.setAttribute("aria-selected","true");const o=e.querySelector(".tbw-scroll-area");if(o&&a&&(!r||t?.forceHorizontalScroll)){const t=e._getHorizontalScrollOffsets?.(n??void 0,a)??{left:0,right:0};if(!t.skipScroll){const e=a.getBoundingClientRect(),i=o.getBoundingClientRect(),r=e.left-i.left+o.scrollLeft,n=r+e.width,s=o.scrollLeft+t.left,d=o.scrollLeft+o.clientWidth-t.right;r<s?o.scrollLeft=r-t.left:n>d&&(o.scrollLeft=n-o.clientWidth+t.right)}}if(r&&a.classList.contains(i)){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(r&&!a.contains(document.activeElement)){a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1");try{a.focus({preventScroll:!0})}catch{}}else if(!r){const t=document.activeElement;t instanceof HTMLElement&&t!==e&&"function"==typeof e.contains&&e.contains(t)&&!t.classList.contains("cell")&&!t.closest(".cell")||t===e||e.focus({preventScroll:!0})}}}}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const w={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class b{static dependencies;static manifest;aliases;version="3.0.0-beta.2";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 i={...this.userConfig},r={};for(const t of Object.keys(i))r[t]=this;for(const n of e){const e=n.userConfig;for(const[o,s]of Object.entries(e)){if(void 0===s)continue;if(!(o in i)){i[o]=s,r[o]=n;continue}if(i[o]===s)continue;const e=r[o]?.constructor.name??this.constructor.name,a=n.constructor.name,d=t("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${o}" supplied by both ${e} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(d)}}Object.assign(this.userConfig,i)}refreshUserConfigFrom(e){const t=this.userConfig,i={...e.userConfig};for(const r of Object.keys(t))delete t[r];Object.assign(t,i)}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 i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.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{...w,...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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}setIcon(e,t,i){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,i);void 0!==r?"string"==typeof r?e.innerHTML=h(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.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 i=document.createElement("span");i.setAttribute("part","sort-indicator"),i.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(i,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(i,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(i,r):e.appendChild(i),i}warn(i,r){void 0!==r?console.warn(t(i,r,this.gridElement.id,this.name)):console.warn(`${e(this.gridElement.id,this.name)} ${i}`)}throwDiagnostic(e,i){throw new Error(t(e,i,this.gridElement.id,this.name))}}class R extends b{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]:before{display:none!important}tbw-grid[data-responsive][data-responsive-hide-header] .data-grid-row:not(.group-row)>.cell:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-header-pinned,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#i;#r=!1;#n;#o=!1;#s=0;#a=/* @__PURE__ */new Set;#d=/* @__PURE__ */new Set;#l=null;#c=[];get#u(){return this.grid}isResponsive(){return this.#r}setResponsive(e){e!==this.#r&&(this.#r=e,this.#h(),this.emit("responsive-change",{isResponsive:e,width:this.#s,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#p(this.#s)}setCardRenderer(e){this.config.cardRenderer=e,this.#r&&this.requestRender()}getWidth(){return this.#s}getActiveBreakpoint(){return this.#l}attach(e){super.attach(e),this.#g(),this.#f(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#c=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#i=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#s=t,clearTimeout(this.#n),this.#n=setTimeout(()=>{this.#p(t)},this.config.debounceMs??100)}),this.#i.observe(this.gridElement)}#g(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#u.__frameworkAdapter;if(i?.parseResponsiveCardElement){const e=i.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const r=t.getAttribute("breakpoint"),n=t.getAttribute("card-row-height"),o=t.getAttribute("hidden-columns"),s=t.getAttribute("hide-header"),a=t.getAttribute("debounce-ms"),d={};if(null!==r){const e=parseInt(r,10);isNaN(e)||(d.breakpoint=e)}if(null!==n&&(d.cardRowHeight="auto"===n?"auto":parseInt(n,10)),null!==o&&(d.hiddenColumns=o.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==s&&(d.hideHeader="false"!==s),null!==a){const e=parseInt(a,10);isNaN(e)||(d.debounceMs=e)}const l=t.innerHTML.trim();!l||this.config.cardRenderer||i?.parseResponsiveCardElement||(d.cardRenderer=e=>{const t=h(g(l,{value:e,row:e})),i=document.createElement("div");return i.className="tbw-responsive-card-content",i.innerHTML=t,i}),Object.keys(d).length>0&&(this.config={...this.config,...d})}#f(e){if(this.#a.clear(),this.#d.clear(),e)for(const t of e)"string"==typeof t?this.#a.add(t):t.showValue?this.#d.add(t.field):this.#a.add(t.field)}detach(){this.#i?.disconnect(),this.#i=void 0,clearTimeout(this.#n),this.#n=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#r}afterRender(){this.#v();if(!(this.#c.length>0?null!==this.#l:this.#r))return;const e=this.#a.size>0,t=this.#d.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#a.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#d.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#p(e){if(this.#c.length>0)return void this.#m(e);const t=this.config.breakpoint??0;0!==t||this.#o||(this.#o=!0,this.warn("TBW110","No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#r&&(this.#r=i,this.#h(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#m(e){let t=null;for(const i of this.#c)e<=i.maxWidth&&(t=i);if(t!==this.#l){this.#l=t,t?.hiddenColumns?this.#f(t.hiddenColumns):this.#f(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#r&&(this.#r=i,this.#h()),this.emit("responsive-change",{isResponsive:this.#r,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#w;#h(){this.gridElement.toggleAttribute("data-responsive",this.#r);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.gridElement.toggleAttribute("data-responsive-hide-header",this.#r&&!0===this.config.hideHeader),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.#u;if(this.#r){t._virtualization&&(this.#w=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#w&&this.#w>0&&t._virtualization&&(t._virtualization.rowHeight=this.#w,this.#w=void 0),this.#b=void 0,this.#R=void 0,this.#y=void 0}}renderRow(e,t,i){if(!this.#r||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const n=this.config.cardRowHeight;return t.style.height="auto"===n||void 0===n?"auto":`${this.#C()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#r)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,i=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,e.preventDefault(),m(this.#u),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),m(this.#u),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),m(this.#u),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),m(this.#u),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),m(this.#u),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),m(this.#u),!0}return!1}#b;#R;#y;#C(){if(this.#b&&this.#b>0)return this.#b;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#k(){return this.#R&&this.#R>0?this.#R:this.#w??28}#_(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}getRowHeight(e,t){if(this.#r&&this.config.cardRenderer)return e.__isGroupRow?this.#k():this.#C()}#H(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#S=!1;#v(){if(!this.#r)return;let e=!1;const t=this.#u,i=this.#_(),r=this.#H();if(r!==this.#y&&(this.#y=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#R&&(this.#R=i,e=!0)}}const n=this.config.cardRenderer?".data-grid-row.responsive-card":".data-grid-row:not(.group-row)",o=this.gridElement.querySelector(n);if(o){const r=o.getBoundingClientRect().height;r>0&&r!==this.#b&&(this.#b=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#S&&(this.#S=!0,queueMicrotask(()=>{this.#S=!1,this.grid&&this.#r&&this.#u.refreshVirtualWindow?.(!0,!0)}))}}export{R as ResponsivePlugin};
1
+ function e(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function t(t,i,r,n){return`${e(r,n)} ${t}: ${i}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(t)}`}const i="editing",r=/{{\s*([^}]+)\s*}}/g,n="__DG_EMPTY__",o=/^[\w$. '?+\-*/%:()!<>=,&|]+$/,s="__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("")),a=new RegExp(`__(proto|defineGetter|defineSetter)|${s.slice(3).join("|")}|this\\b`),d=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("|")),l=/^on\w+$/i,c=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),u=/^\s*(javascript|vbscript|data|blob):/i;function h(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=[],i=e.querySelectorAll("*");for(const r of i){const e=r.tagName.toLowerCase();if(d.has(e)){t.push(r);continue}if("svg"===e||"http://www.w3.org/2000/svg"===r.namespaceURI){if(Array.from(r.attributes).some(e=>l.test(e.name)||"href"===e.name||"xlink:href"===e.name)){t.push(r);continue}}const i=[];for(const t of r.attributes){const e=t.name.toLowerCase();l.test(e)?i.push(t.name):(c.has(e)&&u.test(t.value)||"style"===e&&/expression\s*\(|javascript:|behavior\s*:/i.test(t.value))&&i.push(t.name)}i.forEach(e=>r.removeAttribute(e))}t.forEach(e=>e.remove())}(t.content),t.innerHTML}function p(e,t){const i=function(e){const t=[];let i=0;for(;i<e.length;){const r=e[i];if(" "!==r){if(r>="0"&&r<="9"||"."===r&&i+1<e.length&&e[i+1]>="0"&&e[i+1]<="9"){const r=i;for(;i<e.length&&(e[i]>="0"&&e[i]<="9"||"."===e[i]);)i++;t.push({type:"num",v:Number(e.slice(r,i))});continue}if("'"===r){let r="";for(i++;i<e.length&&"'"!==e[i];)r+=e[i++];if(i>=e.length)return null;i++,t.push({type:"str",v:r});continue}if(r>="a"&&r<="z"||r>="A"&&r<="Z"||"_"===r||"$"===r){const r=i;for(;i<e.length&&/[\w$.]/.test(e[i]);)i++;t.push({type:"id",v:e.slice(r,i)});continue}if(i+2<e.length){const r=e.slice(i,i+3);if("==="===r||"!=="===r){t.push({type:"op",v:r}),i+=3;continue}}if(i+1<e.length){const r=e.slice(i,i+2);if("=="===r||"!="===r||"<="===r||">="===r||"&&"===r||"||"===r){t.push({type:"op",v:r}),i+=2;continue}}if(!"+-*/%<>!?:(),".includes(r))return null;t.push({type:"op",v:r}),i++}else i++}return t}(e);if(!i)return;const r=i;let n=0;function o(){return r[n]}function s(){return r[n++]}function a(e,t){const i=o();return!!i&&(i.type===e&&(void 0===t||i.v===t))}function d(){const e=function(){let e=l();for(;a("op","||");)s(),e=e||l();return e}();if(a("op","?")){s();const t=d();if(!a("op",":"))return;s();const i=d();return e?t:i}return e}function l(){let e=c();for(;a("op","&&");)s(),e=e&&c();return e}function c(){let e=u();for(;;){const t=o();if(!t||"op"!==t.type)break;if("==="===t.v)s(),e=e===u();else if("!=="===t.v)s(),e=e!==u();else if("=="===t.v)s(),e=e==u();else{if("!="!==t.v)break;s(),e=e!=u()}}return e}function u(){let e=h();for(;;){const t=o();if(!t||"op"!==t.type)break;if("<"===t.v)s(),e=e<h();else if(">"===t.v)s(),e=e>h();else if("<="===t.v)s(),e=e<=h();else{if(">="!==t.v)break;s(),e=e>=h()}}return e}function h(){let e=p();for(;;){const t=o();if(!t||"op"!==t.type)break;if("+"===t.v)s(),e+=p();else{if("-"!==t.v)break;s(),e-=p()}}return e}function p(){let e=g();for(;;){const t=o();if(!t||"op"!==t.type)break;if("*"===t.v)s(),e*=g();else if("/"===t.v)s(),e/=g();else{if("%"!==t.v)break;s(),e%=g()}}return e}function g(){return a("op","!")?(s(),!g()):f()}function f(){const e=o();if(e){if("num"===e.type)return s(),e.v;if("str"===e.type)return s(),e.v;if("id"===e.type)return s(),function(e){if("value"===e)return t.value;if(e.startsWith("row.")){const i=e.slice(4);return t.row?t.row[i]:void 0}if(e.startsWith("typeDefault.")){const i=e.slice(12);return t.typeDefault?t.typeDefault[i]:void 0}return"row"===e?t.row:"typeDefault"===e?t.typeDefault:void 0}(e.v);if("op"===e.type&&"("===e.v){s();const e=d();return a("op",")")&&s(),e}return"op"===e.type&&"-"===e.v?(s(),-f()):void 0}}const v=d();return n<r.length?void 0:v}function g(e,t){if(!e||-1===e.indexOf("{{"))return e;const i=[],s=e.replace(r,(e,r)=>{const s=function(e,t){if(e=(e||"").trim(),!e)return n;if(f.test(e))return n;if("value"===e)return null==t.value?n:String(t.value);if(e.startsWith("row.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(4),r=t.row?t.row[i]:void 0;return null==r?n:String(r)}if(e.startsWith("typeDefault.")&&!/[()?]/.test(e)&&!e.includes(":")){const i=e.slice(12),r=t.typeDefault?t.typeDefault[i]:void 0;return null==r?n:String(r)}if(e.length>80)return n;if(!o.test(e)||a.test(e))return n;const i=e.match(/\./g);if(i&&i.length>1)return n;try{const i=p(e,t),r=null==i?"":String(i);return f.test(r)?n:r||n}catch{return n}}(r,t);return i.push({expr:r.trim(),result:s}),s}),d=(l=s)?l.replace(new RegExp(n,"g"),"").replace(/Reflect\.[^<>{}\s]+|\bProxy\b|ownKeys\([^)]*\)/g,""):l;var l;const c=i.length&&i.every(e=>""===e.result||e.result===n);return f.test(e)||c?"":d}const f=/Reflect|Proxy|ownKeys/;document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function v(e,t){if(!t.capped)return e;const i=t.spacerHeight-t.viewportHeight,r=t.rawContentHeight-t.viewportHeight;return i<=0||r<=0?e:e*i/r}function m(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:i,viewportEl:r,scrollMapping:n}=e._virtualization,o=i,s=r?.clientHeight??o?.clientHeight??0;if(o&&s>0){const i=e._focusRow*t,r=n?function(e,t){if(!t.capped)return e;const i=t.spacerHeight-t.viewportHeight,r=t.rawContentHeight-t.viewportHeight;if(i<=0||r<=0)return e;const n=e*r/i;return n<0?0:n>r?r:n}(o.scrollTop,n):o.scrollTop;if(i<r)o.scrollTop=n?v(i,n):i;else if(i+t>r+s){const e=i-s+t;o.scrollTop=n?v(e,n):e}}}const r=void 0!==e._activeEditRows&&-1!==e._activeEditRows||!!e._isGridEditMode;var n;r||e.refreshVirtualWindow(!1),(n=e._bodyEl)&&n.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus")),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const o=e._focusRow,s=e._virtualization.start??0,a=e._virtualization.end??e._rows.length;if(o>=s&&o<a){const n=e._bodyEl.querySelectorAll(".data-grid-row")[o-s];let a=n?.children[e._focusCol];if(a&&a.classList?.contains("cell")||(a=n?.querySelector(`.cell[data-col="${e._focusCol}"]`)??n?.querySelector(".cell[data-col]")),a){a.classList.add("cell-focus"),a.setAttribute("aria-selected","true");const o=e.querySelector(".tbw-scroll-area");if(o&&a&&(!r||t?.forceHorizontalScroll)){const t=e._getHorizontalScrollOffsets?.(n??void 0,a)??{left:0,right:0};if(!t.skipScroll){const e=a.getBoundingClientRect(),i=o.getBoundingClientRect(),r=e.left-i.left+o.scrollLeft,n=r+e.width,s=o.scrollLeft+t.left,d=o.scrollLeft+o.clientWidth-t.right;r<s?o.scrollLeft=r-t.left:n>d&&(o.scrollLeft=n-o.clientWidth+t.right)}}if(r&&a.classList.contains(i)){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(r&&!a.contains(document.activeElement)){a.hasAttribute("tabindex")||a.setAttribute("tabindex","-1");try{a.focus({preventScroll:!0})}catch{}}else if(!r){const t=document.activeElement;t instanceof HTMLElement&&t!==e&&"function"==typeof e.contains&&e.contains(t)&&!t.classList.contains("cell")&&!t.closest(".cell")||t===e||e.focus({preventScroll:!0})}}}}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const w={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class b{static dependencies;static manifest;aliases;version="3.0.0-beta.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const i={...this.userConfig},r={};for(const t of Object.keys(i))r[t]=this;for(const n of e){const e=n.userConfig;for(const[o,s]of Object.entries(e)){if(void 0===s)continue;if(!(o in i)){i[o]=s,r[o]=n;continue}if(i[o]===s)continue;const e=r[o]?.constructor.name??this.constructor.name,a=n.constructor.name,d=t("TBW025",`Cannot merge plugin configs for "${this.name}": conflicting value for "${o}" supplied by both ${e} and ${a}. Pass the option on a single instance, or remove the duplicate.`,void 0,this.name);throw new Error(d)}}Object.assign(this.userConfig,i)}refreshUserConfigFrom(e){const t=this.userConfig,i={...e.userConfig};for(const r of Object.keys(t))delete t[r];Object.assign(t,i)}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 i=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(i),i.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{...w,...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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),i=parseInt(t,10);if(!isNaN(i))return i}return 200}setIcon(e,t,i){e.dataset.icon=t.replace(/([A-Z])/g,"-$1").toLowerCase(),"collapse"===t?e.dataset.expanded="":"expand"===t&&delete e.dataset.expanded;const r=this.#t(t,i);void 0!==r?"string"==typeof r?e.innerHTML=h(r):r instanceof HTMLElement&&(e.innerHTML="",e.appendChild(r.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 i=document.createElement("span");i.setAttribute("part","sort-indicator"),i.className="sort-indicator",t?(e.setAttribute("aria-sort","asc"===t?"ascending":"descending"),e.setAttribute("data-sort",t),this.setIcon(i,"asc"===t?"sortAsc":"sortDesc")):(e.setAttribute("aria-sort","none"),e.removeAttribute("data-sort"),this.setIcon(i,"sortNone"));const r=e.querySelector(".tbw-filter-btn")??e.querySelector(".resize-handle");return r?e.insertBefore(i,r):e.appendChild(i),i}warn(i,r){void 0!==r?console.warn(t(i,r,this.gridElement.id,this.name)):console.warn(`${e(this.gridElement.id,this.name)} ${i}`)}throwDiagnostic(e,i){throw new Error(t(e,i,this.gridElement.id,this.name))}}class R extends b{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]:before{display:none!important}tbw-grid[data-responsive][data-responsive-hide-header] .data-grid-row:not(.group-row)>.cell:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-header-pinned,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#i;#r=!1;#n;#o=!1;#s=0;#a=/* @__PURE__ */new Set;#d=/* @__PURE__ */new Set;#l=null;#c=[];get#u(){return this.grid}isResponsive(){return this.#r}setResponsive(e){e!==this.#r&&(this.#r=e,this.#h(),this.emit("responsive-change",{isResponsive:e,width:this.#s,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#p(this.#s)}setCardRenderer(e){this.config.cardRenderer=e,this.#r&&this.requestRender()}getWidth(){return this.#s}getActiveBreakpoint(){return this.#l}attach(e){super.attach(e),this.#g(),this.#f(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#c=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#i=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#s=t,clearTimeout(this.#n),this.#n=setTimeout(()=>{this.#p(t)},this.config.debounceMs??100)}),this.#i.observe(this.gridElement)}#g(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#u.__frameworkAdapter;if(i?.parseResponsiveCardElement){const e=i.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const r=t.getAttribute("breakpoint"),n=t.getAttribute("card-row-height"),o=t.getAttribute("hidden-columns"),s=t.getAttribute("hide-header"),a=t.getAttribute("debounce-ms"),d={};if(null!==r){const e=parseInt(r,10);isNaN(e)||(d.breakpoint=e)}if(null!==n&&(d.cardRowHeight="auto"===n?"auto":parseInt(n,10)),null!==o&&(d.hiddenColumns=o.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==s&&(d.hideHeader="false"!==s),null!==a){const e=parseInt(a,10);isNaN(e)||(d.debounceMs=e)}const l=t.innerHTML.trim();!l||this.config.cardRenderer||i?.parseResponsiveCardElement||(d.cardRenderer=e=>{const t=h(g(l,{value:e,row:e})),i=document.createElement("div");return i.className="tbw-responsive-card-content",i.innerHTML=t,i}),Object.keys(d).length>0&&(this.config={...this.config,...d})}#f(e){if(this.#a.clear(),this.#d.clear(),e)for(const t of e)"string"==typeof t?this.#a.add(t):t.showValue?this.#d.add(t.field):this.#a.add(t.field)}detach(){this.#i?.disconnect(),this.#i=void 0,clearTimeout(this.#n),this.#n=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#r}afterRender(){this.#v();if(!(this.#c.length>0?null!==this.#l:this.#r))return;const e=this.#a.size>0,t=this.#d.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#a.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#d.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#p(e){if(this.#c.length>0)return void this.#m(e);const t=this.config.breakpoint??0;0!==t||this.#o||(this.#o=!0,this.warn("TBW110","No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#r&&(this.#r=i,this.#h(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#m(e){let t=null;for(const i of this.#c)e<=i.maxWidth&&(t=i);if(t!==this.#l){this.#l=t,t?.hiddenColumns?this.#f(t.hiddenColumns):this.#f(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#r&&(this.#r=i,this.#h()),this.emit("responsive-change",{isResponsive:this.#r,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#w;#h(){this.gridElement.toggleAttribute("data-responsive",this.#r);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.gridElement.toggleAttribute("data-responsive-hide-header",this.#r&&!0===this.config.hideHeader),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.#u;if(this.#r){t._virtualization&&(this.#w=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#w&&this.#w>0&&t._virtualization&&(t._virtualization.rowHeight=this.#w,this.#w=void 0),this.#b=void 0,this.#R=void 0,this.#y=void 0}}renderRow(e,t,i){if(!this.#r||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const n=this.config.cardRowHeight;return t.style.height="auto"===n||void 0===n?"auto":`${this.#C()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#r)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,i=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,e.preventDefault(),m(this.#u),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),m(this.#u),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),m(this.#u),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,e.preventDefault(),m(this.#u),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),m(this.#u),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),m(this.#u),!0}return!1}#b;#R;#y;#C(){if(this.#b&&this.#b>0)return this.#b;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#k(){return this.#R&&this.#R>0?this.#R:this.#w??28}#_(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}getRowHeight(e,t){if(this.#r&&this.config.cardRenderer)return e.__isGroupRow?this.#k():this.#C()}#H(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#S=!1;#v(){if(!this.#r)return;let e=!1;const t=this.#u,i=this.#_(),r=this.#H();if(r!==this.#y&&(this.#y=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#R&&(this.#R=i,e=!0)}}const n=this.config.cardRenderer?".data-grid-row.responsive-card":".data-grid-row:not(.group-row)",o=this.gridElement.querySelector(n);if(o){const r=o.getBoundingClientRect().height;r>0&&r!==this.#b&&(this.#b=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#S&&(this.#S=!0,queueMicrotask(()=>{this.#S=!1,this.grid&&this.#r&&this.#u.refreshVirtualWindow?.(!0,!0)}))}}export{R as ResponsivePlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- const 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=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)}`}let s=0;function a(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function d(e,t,r,o){return`${a(r,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const c="__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(""));new RegExp(`__(proto|defineGetter|defineSetter)|${c.slice(3).join("|")}|this\\b`);const l=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("|")),g=/^on\w+$/i,u=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),f=/^\s*(javascript|vbscript|data|blob):/i;function h(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(l.has(e)){t.push(o);continue}if("svg"===e||"http://www.w3.org/2000/svg"===o.namespaceURI){if(Array.from(o.attributes).some(e=>g.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();g.test(e)?r.push(t.name):(u.has(e)&&f.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}document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function p(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 w(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?p(r,i):r;else if(r+e>o+s){const t=r-s+e;n.scrollTop=i?p(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,a=t._virtualization.end??t._rows.length;if(n>=s&&n<a){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)){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})}}}}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const m={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class b{static dependencies;static manifest;aliases;version="3.0.0-beta.2";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=d("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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}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=h(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(d(e,t,this.gridElement.id,this.name)):console.warn(`${a(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(d(e,t,this.gridElement.id,this.name))}}let v=null;function I(){return v}function y(){v=null}const 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}}const E="__tbw_row_drag";let S=null;const A=/* @__PURE__ */new Set;function T(){if("undefined"==typeof BroadcastChannel)return null;if(S)return S;try{S=new BroadcastChannel("tbw-row-drag-drop"),S.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}class _ extends b{name="rowDragDrop";aliases=["reorderRows","rowReorder"];styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;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}.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{position:fixed;top:-10000px;left:-10000px;pointer-events:none}.tbw-row-drag-count{position:fixed;top:-1000px;left:-1000px;pointer-events:none;background:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));color:var(--tbw-color-accent-fg);font:600 12px/1.4 system-ui,sans-serif;border-radius:999px;padding:2px 8px;box-shadow:0 2px 6px var(--tbw-color-shadow);z-index:9999}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before,.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;left:0;right:0;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}.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),T())}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(e){return null!==e.closest(_.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(t===x||t.startsWith(`${x};`))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;const e=function(e,t){for(const r of e)if(R(r)===t)return r;return null}(r,o);if(!(e||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;const r=I();let i=r?.payload??null,n=null;if(i){const e=o(i.sessionId);e&&(n=e)}else{if(i=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)),i){const e=o(i.sessionId);e&&(n=e)}}if(!i)return;const s=e.target.closest(".data-grid-row"),a=this.internalGrid._rows??[],d=D(s,e.clientY,e=>this.getRowIndex(e),a.length);let c=this.dropRowIndex??d.insertIndex;const l=i.sourceGridId===this.gridId,g=this.config.dropZone??"";if(l){const e=i.rowIndices[0];if(1===i.rowIndices.length&&c>e&&c--,e===c)return;const t=(n??i.rows)[0];if(!this.canMoveRow(e,c))return;return void this.executeIntraGridMove(t,e,c,"drag")}if(!g||g!==i.dropZone)return;if(this.config.canDrop&&!this.config.canDrop(i,c))return this.gridElement.classList.add("tbw-grid--drop-target-rejected"),void setTimeout(()=>this.gridElement.classList.remove("tbw-grid--drop-target-rejected"),200);const u=this.config.deserializeRow??(e=>e),f=n??i.rows.map(e=>u(e)),h={payload:i,sourceGridId:i.sourceGridId,targetIndex:c,operation:i.operation};if(this.emitCancelable("row-drop",h))return;const p=[...a];p.splice(c,0,...f),this.grid.rows=p;const w=this.findPeerOnGrid(i.sourceGridId);if("move"===i.operation&&w){const e=document.getElementById(i.sourceGridId);if(e){const t=(e._rows??e.rows??[]).slice(),r=[...i.rowIndices].sort((e,t)=>t-e);for(const e of r)e>=0&&e<t.length&&t.splice(e,1);e.rows=t}}w&&(w.dragAccepted=!0);const m={rows:f,fromGridId:i.sourceGridId,toGridId:this.gridId,fromIndices:i.rowIndices,toIndex:c,operation:i.operation};this.emit("row-transfer",m),w?w.emitTransfer(m):function(e){const t=T();if(t)try{t.postMessage(e)}catch{}}({type:"tbw-row-drag-drop:transfer",sessionId:i.sessionId,sourceGridId:i.sourceGridId,toGridId:this.gridId,dropZone:g,rowIndices:i.rowIndices,toIndex:c,operation:i.operation,serializedRows:i.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),w(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),w(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,_ as RowDragDropPlugin};
1
+ const 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=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)}`}let s=0;function a(e,t){return`[tbw-grid${e?`#${e}`:""}${t?`:${t}`:""}]`}function d(e,t,r,o){return`${a(r,o)} ${e}: ${t}\n\n → More info: ${function(e){return`https://toolboxjs.com/grid/errors#${e.toLowerCase()}`}(e)}`}const c="__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(""));new RegExp(`__(proto|defineGetter|defineSetter)|${c.slice(3).join("|")}|this\\b`);const l=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("|")),g=/^on\w+$/i,u=new Set("href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset".split("|")),f=/^\s*(javascript|vbscript|data|blob):/i;function h(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(l.has(e)){t.push(o);continue}if("svg"===e||"http://www.w3.org/2000/svg"===o.namespaceURI){if(Array.from(o.attributes).some(e=>g.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();g.test(e)?r.push(t.name):(u.has(e)&&f.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}document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';function p(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 w(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?p(r,i):r;else if(r+e>o+s){const t=r-s+e;n.scrollTop=i?p(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,a=t._virtualization.end??t._rows.length;if(n>=s&&n<a){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)){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})}}}}document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const m={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:"",filterActive:"",print:"🖨️"};class b{static dependencies;static manifest;aliases;version="3.0.0-beta.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},r={};for(const o of Object.keys(t))r[o]=this;for(const o of e){const e=o.userConfig;for(const[i,n]of Object.entries(e)){if(void 0===n)continue;if(!(i in t)){t[i]=n,r[i]=o;continue}if(t[i]===n)continue;const e=r[i]?.constructor.name??this.constructor.name,s=o.constructor.name,a=d("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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}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=h(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(d(e,t,this.gridElement.id,this.name)):console.warn(`${a(this.gridElement.id,this.name)} ${e}`)}throwDiagnostic(e,t){throw new Error(d(e,t,this.gridElement.id,this.name))}}let v=null;function I(){return v}function y(){v=null}const 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}}const E="__tbw_row_drag";let S=null;const A=/* @__PURE__ */new Set;function T(){if("undefined"==typeof BroadcastChannel)return null;if(S)return S;try{S=new BroadcastChannel("tbw-row-drag-drop"),S.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}class _ extends b{name="rowDragDrop";aliases=["reorderRows","rowReorder"];styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;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}.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{position:fixed;top:-10000px;left:-10000px;pointer-events:none}.tbw-row-drag-count{position:fixed;top:-1000px;left:-1000px;pointer-events:none;background:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));color:var(--tbw-color-accent-fg);font:600 12px/1.4 system-ui,sans-serif;border-radius:999px;padding:2px 8px;box-shadow:0 2px 6px var(--tbw-color-shadow);z-index:9999}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before,.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;left:0;right:0;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}.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),T())}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(e){return null!==e.closest(_.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(t===x||t.startsWith(`${x};`))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;const e=function(e,t){for(const r of e)if(R(r)===t)return r;return null}(r,o);if(!(e||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;const r=I();let i=r?.payload??null,n=null;if(i){const e=o(i.sessionId);e&&(n=e)}else{if(i=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)),i){const e=o(i.sessionId);e&&(n=e)}}if(!i)return;const s=e.target.closest(".data-grid-row"),a=this.internalGrid._rows??[],d=D(s,e.clientY,e=>this.getRowIndex(e),a.length);let c=this.dropRowIndex??d.insertIndex;const l=i.sourceGridId===this.gridId,g=this.config.dropZone??"";if(l){const e=i.rowIndices[0];if(1===i.rowIndices.length&&c>e&&c--,e===c)return;const t=(n??i.rows)[0];if(!this.canMoveRow(e,c))return;return void this.executeIntraGridMove(t,e,c,"drag")}if(!g||g!==i.dropZone)return;if(this.config.canDrop&&!this.config.canDrop(i,c))return this.gridElement.classList.add("tbw-grid--drop-target-rejected"),void setTimeout(()=>this.gridElement.classList.remove("tbw-grid--drop-target-rejected"),200);const u=this.config.deserializeRow??(e=>e),f=n??i.rows.map(e=>u(e)),h={payload:i,sourceGridId:i.sourceGridId,targetIndex:c,operation:i.operation};if(this.emitCancelable("row-drop",h))return;const p=[...a];p.splice(c,0,...f),this.grid.rows=p;const w=this.findPeerOnGrid(i.sourceGridId);if("move"===i.operation&&w){const e=document.getElementById(i.sourceGridId);if(e){const t=(e._rows??e.rows??[]).slice(),r=[...i.rowIndices].sort((e,t)=>t-e);for(const e of r)e>=0&&e<t.length&&t.splice(e,1);e.rows=t}}w&&(w.dragAccepted=!0);const m={rows:f,fromGridId:i.sourceGridId,toGridId:this.gridId,fromIndices:i.rowIndices,toIndex:c,operation:i.operation};this.emit("row-transfer",m),w?w.emitTransfer(m):function(e){const t=T();if(t)try{t.postMessage(e)}catch{}}({type:"tbw-row-drag-drop:transfer",sessionId:i.sessionId,sourceGridId:i.sourceGridId,toGridId:this.gridId,dropZone:g,rowIndices:i.rowIndices,toIndex:c,operation:i.operation,serializedRows:i.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),w(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),w(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,_ as RowDragDropPlugin};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- const 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;const s="effectiveConfig"in e?e.effectiveConfig:void 0;if(!1===s?.a11y?.announcements)return;const i=e.querySelector?.(".tbw-sr-only");i&&(i.textContent="",requestAnimationFrame(()=>{i.textContent=t}))}function n(e,s,...i){const n=e&&"effectiveConfig"in e?e.effectiveConfig:void 0,o=n?.a11y?.messages?.[s];return o?o(...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)}`}const 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(""));new RegExp(`__(proto|defineGetter|defineSetter)|${a.slice(3).join("|")}|this\\b`);const d=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 f(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){if(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}class m{static dependencies;static manifest;aliases;version="3.0.0-beta.2";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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}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=f(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 E(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function x(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"}const q="__tbw_checkbox";class I extends m{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:"";position:absolute;inset:0;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}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:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}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;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}tbw-grid .header-row>.cell.column-selected,tbw-grid .data-grid-row>.cell.column-selected{background:linear-gradient(var(--tbw-column-selection-bg, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),var(--tbw-color-panel-bg)}tbw-grid .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];if(!i)return!1;return 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(){const e=this.gridElement?.querySelector(".rows-body");e?.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}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=E(this.cellAnchor,{row:t,col:s}),i=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(i&&x(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&&x(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}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}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(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&&x(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=E(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&x(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")})}if("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"))})}if("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=E(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))return;this.#d("column");if(!1!==this.config.multiSelect)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);else 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(){if(0===this.selectedColumns.size)return[];return 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
+ const 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;const s="effectiveConfig"in e?e.effectiveConfig:void 0;if(!1===s?.a11y?.announcements)return;const i=e.querySelector?.(".tbw-sr-only");i&&(i.textContent="",requestAnimationFrame(()=>{i.textContent=t}))}function n(e,s,...i){const n=e&&"effectiveConfig"in e?e.effectiveConfig:void 0,o=n?.a11y?.messages?.[s];return o?o(...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)}`}const 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(""));new RegExp(`__(proto|defineGetter|defineSetter)|${a.slice(3).join("|")}|this\\b`);const d=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 f(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){if(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}class m{static dependencies;static manifest;aliases;version="3.0.0-beta.3";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}get resolvedConfig(){return this.#e?this.config:{...this.defaultConfig,...this.userConfig}}mergeConfigsFrom(e){if(0===e.length)return;const t={...this.userConfig},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;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}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=f(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 E(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function x(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"}const q="__tbw_checkbox";class I extends m{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:"";position:absolute;inset:0;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}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:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}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;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}tbw-grid .header-row>.cell.column-selected,tbw-grid .data-grid-row>.cell.column-selected{background:linear-gradient(var(--tbw-column-selection-bg, rgba(from var(--tbw-color-accent) r g b / 12%)) 0 0),var(--tbw-color-panel-bg)}tbw-grid .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];if(!i)return!1;return 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(){const e=this.gridElement?.querySelector(".rows-body");e?.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}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=E(this.cellAnchor,{row:t,col:s}),i=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(i&&x(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&&x(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}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}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(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&&x(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=E(this.cellAnchor,{row:e.rowIndex,col:t}),n=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return n&&x(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")})}if("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"))})}if("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=E(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))return;this.#d("column");if(!1!==this.config.multiSelect)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);else 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(){if(0===this.selectedColumns.size)return[];return 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