@toolbox-web/grid 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -3
- package/all.d.ts +1 -0
- package/all.js +2 -2
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/internal/aria.d.ts +4 -0
- package/lib/core/types.d.ts +90 -31
- package/lib/features/sticky-rows.d.ts +9 -0
- package/lib/features/sticky-rows.js +2 -0
- package/lib/features/sticky-rows.js.map +1 -0
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/index.js +1 -1
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/GroupingRowsPlugin.d.ts +15 -0
- package/lib/plugins/grouping-rows/index.js +2 -2
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-rows/PinnedRowsPlugin.d.ts +28 -4
- package/lib/plugins/pinned-rows/index.d.ts +3 -2
- package/lib/plugins/pinned-rows/index.js +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/pinned-rows.d.ts +29 -1
- package/lib/plugins/pinned-rows/types.d.ts +96 -9
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/reorder-columns/index.js.map +1 -1
- package/lib/plugins/reorder-rows/index.js.map +1 -1
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/row-drag-drop/index.js.map +1 -1
- package/lib/plugins/row-drag-drop/types.d.ts +7 -0
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/sticky-rows/StickyRowsPlugin.d.ts +114 -0
- package/lib/plugins/sticky-rows/index.d.ts +7 -0
- package/lib/plugins/sticky-rows/index.js +2 -0
- package/lib/plugins/sticky-rows/index.js.map +1 -0
- package/lib/plugins/sticky-rows/types.d.ts +67 -0
- package/lib/plugins/tooltip/index.js.map +1 -1
- package/lib/plugins/tree/index.js +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/types.d.ts +4 -0
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/visibility/VisibilityPlugin.d.ts +0 -11
- package/lib/plugins/visibility/index.d.ts +1 -2
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +32 -0
- package/package.json +1 -1
- package/public.d.ts +28 -67
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js +1 -1
- package/umd/plugins/context-menu.umd.js.map +1 -1
- package/umd/plugins/grouping-rows.umd.js +1 -1
- package/umd/plugins/grouping-rows.umd.js.map +1 -1
- package/umd/plugins/pinned-rows.umd.js +1 -1
- package/umd/plugins/pinned-rows.umd.js.map +1 -1
- package/umd/plugins/responsive.umd.js +1 -1
- package/umd/plugins/responsive.umd.js.map +1 -1
- package/umd/plugins/sticky-rows.umd.js +2 -0
- package/umd/plugins/sticky-rows.umd.js.map +1 -0
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
- package/umd/plugins/visibility.umd.js.map +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/plugin/base-plugin"),require("../../core/internal/sanitize")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/internal/sanitize"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_contextMenu={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,n){"use strict";const o="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function r(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function i(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function s(e,o,l,c){const a=document.createElement("div");a.className="tbw-context-menu",a.setAttribute("role","menu");const u=e.some(e=>!e.separator&&e.icon);for(const d of e){if(d.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),a.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",d.cssClass&&e.classList.add(d.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",d.id),e.setAttribute("tabindex","-1");const m=i(d,o);if(m&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),d.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=n.sanitizeHTML(d.icon),e.appendChild(t)}else if(u){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=" ",e.appendChild(t)}const b=document.createElement("span");if(b.className="tbw-context-menu-label",b.textContent=d.name,e.appendChild(b),d.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(d.shortcut))d.shortcut.forEach((e,n)=>{n>0&&t.appendChild(document.createTextNode("+"));const o=document.createElement("kbd");o.textContent=e,t.appendChild(o)});else{const e=document.createElement("kbd");e.textContent=d.shortcut,t.appendChild(e)}e.appendChild(t)}if(d.subMenu?.length){const i=document.createElement("span");i.className="tbw-context-menu-arrow",i.dataset.icon=t.toIconAttr("submenuArrow"),void 0!==c&&("string"==typeof c?i.innerHTML=n.sanitizeHTML(c):c instanceof HTMLElement&&i.appendChild(c.cloneNode(!0))),e.appendChild(i),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!d.subMenu)return;const t=s(r(d.subMenu,o),o,l,c);t.classList.add("tbw-context-submenu"),t.style.position="absolute",t.style.left="100%",t.style.top="0",e.style.position="relative",e.appendChild(t)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}m||!d.action||d.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),l(d)}),a.appendChild(e)}return a}const l="getContextMenuItems";let c=null,a=null,u=0;const d=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.query?.("clipboard:copy")}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.query?.("export:csv")}}];class m extends t.BaseGridPlugin{static manifest={queries:[{type:l,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:d}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),u++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),n=t?.[0];return n?n.includes(e)?n:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size","--tbw-icon-submenu-arrow"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const n=getComputedStyle(t),o=[],r=n.getPropertyValue("color-scheme").trim();r&&o.push(`color-scheme: ${r}`);for(const i of m.CSS_VARS_TO_COPY){const e=n.getPropertyValue(i).trim();e&&o.push(`${i}: ${e}`)}if(o.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+o.join("; ")+";")}}installGlobalHandlers(){if(!a&&"undefined"!=typeof document&&o&&(a=document.createElement("style"),a.id="tbw-context-menu-styles",a.textContent=o,document.head.appendChild(a)),!c){c=new AbortController;const e=c.signal,t=()=>{document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())};document.addEventListener("click",t,{signal:e}),document.addEventListener("keydown",e=>{"Escape"===e.key&&t()},{signal:e}),document.addEventListener("scroll",t,{capture:!0,signal:e})}}uninstallGlobalHandlers(){u--,u>0||(c&&(c.abort(),c=null),a&&(a.remove(),a=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(l,e),n=[];for(const o of t)Array.isArray(o)&&n.push(...o);return n.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(n)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let n=-1;for(const o of e){if(o.separator){t.push(o);continue}const e=Math.floor((o.order??100)/10);n>=0&&e!==n&&t.push({id:`__sep-${n}-${e}`,label:"",separator:!0,action:()=>{}}),n=e,t.push(o)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}openMenuAt(e,t,n,o=!1){this.params=e,this.position={x:t,y:n};const i=this.collectPluginItems(e);let l=r(this.config.items??d,e);if(i.length>0){const e=this.convertPluginItems(i);l=l.length>0&&e.length>0?[...l,{id:"__plugin-sep",name:"",separator:!0},...e]:[...l,...e]}var c,a;(l=function(e){const t=[];for(const n of e)n.separator&&(0===t.length||t[t.length-1].separator)||t.push(n);return t.length>0&&t[t.length-1].separator&&t.pop(),t}(l),l.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=s(l,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.grid?.gridConfig?.icons?.submenuArrow),c=this.menuElement,a=()=>this.hideMenu(),c.addEventListener("keydown",e=>{const t=Array.from(c.querySelectorAll('[role="menuitem"]:not(.disabled)'));if(!t.length)return;const n=document.activeElement,o=t.indexOf(n);switch(e.key){case"ArrowDown":e.preventDefault(),t[o<t.length-1?o+1:0].focus();break;case"ArrowUp":e.preventDefault(),t[o>0?o-1:t.length-1].focus();break;case"Enter":case" ":e.preventDefault(),n&&t.includes(n)&&n.click();break;case"Escape":e.preventDefault(),a()}}),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),function(e,t,n){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.visibility="hidden",e.style.zIndex="10000";const o=e.getBoundingClientRect(),r=window.innerWidth,i=window.innerHeight;let s=t,l=n;t+o.width>r&&(s=t-o.width),n+o.height>i&&(l=n-o.height),s=Math.max(0,s),l=Math.max(0,l),e.style.left=`${s}px`,e.style.top=`${l}px`,e.style.visibility="visible"}(this.menuElement,t,n),this.isOpen=!0,o&&function(e){const t=e.querySelector('[role="menuitem"]:not(.disabled)');t?.focus()}(this.menuElement),this.emit("context-menu-open",{params:e,items:l}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const n=t.target,o=n.closest("[data-row][data-col]"),r=n.closest('[part~="header-cell"]');let i;if(o){const e=parseInt(o.getAttribute("data-row")??"-1",10),n=parseInt(o.getAttribute("data-col")??"-1",10),r=this.visibleColumns[n],s=this.rows[e],l=this.syncSelectionOnContextMenu(e);i={row:s,rowIndex:e,column:r,columnIndex:n,field:r?.field??"",value:s?.[r?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!r)return;{const e=parseInt(r.getAttribute("data-col")??"-1",10),n=this.visibleColumns[e];i={row:null,rowIndex:-1,column:n,columnIndex:e,field:n?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.openMenuAt(i,t.clientX,t.clientY)}))}onKeyDown(e){const t="F10"===e.key&&e.shiftKey,n="ContextMenu"===e.key;if(!t&&!n)return;e.preventDefault();const o=this.grid;if(!o)return;const r=o._focusRow,i=o._focusCol,s=this.visibleColumns[i],l=this.rows[r],c=this.gridElement,a=c?.querySelector(`[data-row="${r}"][data-col="${i}"]`);let u=0,d=0;if(a){const e=a.getBoundingClientRect();u=e.left+e.width/2,d=e.bottom}const m=this.syncSelectionOnContextMenu(r),b={row:l,rowIndex:r,column:s,columnIndex:i,field:s?.field??"",value:l?.[s?.field]??null,isHeader:!1,event:e,selectedRows:m};return this.openMenuAt(b,u,d,!0),!0}showMenu(e,t,n){const o={row:n.row??null,rowIndex:n.rowIndex??-1,column:n.column??null,columnIndex:n.columnIndex??-1,field:n.field??"",value:n.value??null,isHeader:n.isHeader??!1,event:n.event??new MouseEvent("contextmenu"),selectedRows:n.selectedRows??[]};this.openMenuAt(o,e,t)}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}e.ContextMenuPlugin=m,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/plugin/base-plugin"),require("../../core/internal/sanitize")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/internal/sanitize"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_contextMenu={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,n){"use strict";const o="@layer tbw-plugins{.tbw-context-menu{position:fixed;background:var(--tbw-context-menu-bg, var(--tbw-color-panel-bg));color:var(--tbw-context-menu-fg, var(--tbw-color-fg));border:1px solid var(--tbw-context-menu-border, var(--tbw-color-border));border-radius:var(--tbw-context-menu-radius, var(--tbw-border-radius));box-shadow:var(--tbw-context-menu-shadow, 0 2px 10px var(--tbw-color-shadow));min-width:var(--tbw-context-menu-min-width, var(--tbw-menu-min-width));padding:var(--tbw-spacing-xs) 0;z-index:10000;font-size:var(--tbw-context-menu-font-size, var(--tbw-font-size-sm));font-family:var(--tbw-context-menu-font-family, var(--tbw-font-family))}.tbw-context-menu-item{display:flex;align-items:center;padding:var(--tbw-context-menu-item-padding, var(--tbw-menu-item-padding));cursor:pointer;gap:var(--tbw-context-menu-item-gap, var(--tbw-menu-item-gap))}.tbw-context-menu-item:hover:not(.disabled){background:var(--tbw-context-menu-hover, var(--tbw-color-row-hover))}.tbw-context-menu-item.disabled{opacity:.5;cursor:default}.tbw-context-menu-item.danger{color:var(--tbw-context-menu-danger, var(--tbw-color-danger))}.tbw-context-menu-icon{width:var(--tbw-context-menu-icon-size, var(--tbw-icon-size));text-align:center}.tbw-context-menu-label{flex:1}.tbw-context-menu-shortcut kbd{color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted));font-size:var(--tbw-context-menu-shortcut-size, var(--tbw-font-size-xs))}.tbw-context-menu-arrow{font-size:var(--tbw-context-menu-arrow-size, var(--tbw-font-size-2xs));color:var(--tbw-context-menu-muted, var(--tbw-color-fg-muted))}.tbw-context-menu-separator{height:1px;background:var(--tbw-context-menu-border, var(--tbw-color-border));margin:var(--tbw-spacing-xs) 0}}";function i(e,t){return("function"==typeof e?e(t):e).filter(e=>!0!==e.hidden&&("function"!=typeof e.hidden||!e.hidden(t)))}function r(e,t){return!0===e.disabled||"function"==typeof e.disabled&&e.disabled(t)}function s(e,o,l,c){const a=document.createElement("div");a.className="tbw-context-menu",a.setAttribute("role","menu");const u=e.some(e=>!e.separator&&e.icon);for(const d of e){if(d.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),a.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",d.cssClass&&e.classList.add(d.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",d.id),e.setAttribute("tabindex","-1");const m=r(d,o);if(m&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),d.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=n.sanitizeHTML(d.icon),e.appendChild(t)}else if(u){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=" ",e.appendChild(t)}const b=document.createElement("span");if(b.className="tbw-context-menu-label",b.textContent=d.name,e.appendChild(b),d.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(d.shortcut))d.shortcut.forEach((e,n)=>{n>0&&t.appendChild(document.createTextNode("+"));const o=document.createElement("kbd");o.textContent=e,t.appendChild(o)});else{const e=document.createElement("kbd");e.textContent=d.shortcut,t.appendChild(e)}e.appendChild(t)}if(d.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",r.dataset.icon=t.toIconAttr("submenuArrow"),void 0!==c&&("string"==typeof c?r.innerHTML=n.sanitizeHTML(c):c instanceof HTMLElement&&r.appendChild(c.cloneNode(!0))),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!d.subMenu)return;const t=s(i(d.subMenu,o),o,l,c);t.classList.add("tbw-context-submenu"),t.style.position="absolute",t.style.left="100%",t.style.top="0",e.style.position="relative",e.appendChild(t)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}m||!d.action||d.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),l(d)}),a.appendChild(e)}return a}const l="getContextMenuItems";let c=null,a=null,u=0;const d=new Set,m=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.query?.("clipboard:copy")}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.query?.("export:csv")}}];class b extends t.BaseGridPlugin{static manifest={queries:[{type:l,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:m}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),u++,d.add(this)}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,d.delete(this),this.uninstallGlobalHandlers()}syncSelectionOnContextMenu(e){if(e<0)return[];const t=this.grid?.query("getSelectedRowIndices"),n=t?.[0];return n?n.includes(e)?n:(this.grid?.query("selectRows",[e]),[e]):[e]}static CSS_VARS_TO_COPY=["--tbw-color-panel-bg","--tbw-color-fg","--tbw-color-fg-muted","--tbw-color-border","--tbw-color-row-hover","--tbw-color-shadow","--tbw-color-danger","--tbw-border-radius","--tbw-font-family","--tbw-font-size-sm","--tbw-font-size-xs","--tbw-font-size-2xs","--tbw-spacing-xs","--tbw-icon-size","--tbw-menu-min-width","--tbw-menu-item-padding","--tbw-menu-item-gap","--tbw-context-menu-bg","--tbw-context-menu-fg","--tbw-context-menu-border","--tbw-context-menu-radius","--tbw-context-menu-shadow","--tbw-context-menu-hover","--tbw-context-menu-danger","--tbw-context-menu-muted","--tbw-context-menu-min-width","--tbw-context-menu-font-size","--tbw-context-menu-font-family","--tbw-context-menu-item-padding","--tbw-context-menu-item-gap","--tbw-context-menu-icon-size","--tbw-context-menu-shortcut-size","--tbw-context-menu-arrow-size","--tbw-icon-submenu-arrow"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const n=getComputedStyle(t),o=[],i=n.getPropertyValue("color-scheme").trim();i&&o.push(`color-scheme: ${i}`);for(const r of b.CSS_VARS_TO_COPY){const e=n.getPropertyValue(r).trim();e&&o.push(`${r}: ${e}`)}if(o.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+o.join("; ")+";")}}installGlobalHandlers(){if(!a&&"undefined"!=typeof document&&o&&(a=document.createElement("style"),a.id="tbw-context-menu-styles",a.textContent=o,document.head.appendChild(a)),!c){c=new AbortController;const e=c.signal,t=()=>{for(const e of d)e.isMenuOpen()&&e.hideMenu();document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove())};document.addEventListener("click",t,{signal:e}),document.addEventListener("keydown",e=>{"Escape"===e.key&&t()},{signal:e}),document.addEventListener("scroll",t,{capture:!0,signal:e})}}uninstallGlobalHandlers(){u--,u>0||(c&&(c.abort(),c=null),a&&(a.remove(),a=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(l,e),n=[];for(const o of t)Array.isArray(o)&&n.push(...o);return n.sort((e,t)=>(e.order??100)-(t.order??100)),this.insertGroupSeparators(n)}insertGroupSeparators(e){if(e.length<=1)return e;const t=[];let n=-1;for(const o of e){if(o.separator){t.push(o);continue}const e=Math.floor((o.order??100)/10);n>=0&&e!==n&&t.push({id:`__sep-${n}-${e}`,label:"",separator:!0,action:()=>{}}),n=e,t.push(o)}return t}convertPluginItems(e){return e.map(e=>({id:e.id,name:e.label,icon:e.icon,shortcut:e.shortcut,disabled:e.disabled??!1,action:()=>e.action(),separator:e.separator,cssClass:e.cssClass}))}openMenuAt(e,t,n,o=!1){this.params=e,this.position={x:t,y:n};const r=this.collectPluginItems(e);let l=i(this.config.items??m,e);if(r.length>0){const e=this.convertPluginItems(r);l=l.length>0&&e.length>0?[...l,{id:"__plugin-sep",name:"",separator:!0},...e]:[...l,...e]}var c,a;(l=function(e){const t=[];for(const n of e)n.separator&&(0===t.length||t[t.length-1].separator)||t.push(n);return t.length>0&&t[t.length-1].separator&&t.pop(),t}(l),l.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=s(l,e,t=>{t.action&&t.action(e),this.hideMenu()},this.grid?.gridConfig?.icons?.submenuArrow),c=this.menuElement,a=()=>this.hideMenu(),c.addEventListener("keydown",e=>{const t=Array.from(c.querySelectorAll('[role="menuitem"]:not(.disabled)'));if(!t.length)return;const n=document.activeElement,o=t.indexOf(n);switch(e.key){case"ArrowDown":e.preventDefault(),t[o<t.length-1?o+1:0].focus();break;case"ArrowUp":e.preventDefault(),t[o>0?o-1:t.length-1].focus();break;case"Enter":case" ":e.preventDefault(),n&&t.includes(n)&&n.click();break;case"Escape":e.preventDefault(),a()}}),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),function(e,t,n){e.style.position="fixed",e.style.left=`${t}px`,e.style.top=`${n}px`,e.style.visibility="hidden",e.style.zIndex="10000";const o=e.getBoundingClientRect(),i=window.innerWidth,r=window.innerHeight;let s=t,l=n;t+o.width>i&&(s=t-o.width),n+o.height>r&&(l=n-o.height),s=Math.max(0,s),l=Math.max(0,l),e.style.left=`${s}px`,e.style.top=`${l}px`,e.style.visibility="visible"}(this.menuElement,t,n),this.isOpen=!0,o&&function(e){const t=e.querySelector('[role="menuitem"]:not(.disabled)');t?.focus()}(this.menuElement),this.emit("context-menu-open",{params:e,items:l}))}afterRender(){const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root");t&&"true"!==t.getAttribute("data-context-menu-bound")&&(t.setAttribute("data-context-menu-bound","true"),t.addEventListener("contextmenu",e=>{const t=e;t.preventDefault();const n=t.target,o=n.closest("[data-row][data-col]"),i=n.closest('[part~="header-cell"]');let r;if(o){const e=parseInt(o.getAttribute("data-row")??"-1",10),n=parseInt(o.getAttribute("data-col")??"-1",10),i=this.visibleColumns[n],s=this.rows[e],l=this.syncSelectionOnContextMenu(e);r={row:s,rowIndex:e,column:i,columnIndex:n,field:i?.field??"",value:s?.[i?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!i)return;{const e=parseInt(i.getAttribute("data-col")??"-1",10),n=this.visibleColumns[e];r={row:null,rowIndex:-1,column:n,columnIndex:e,field:n?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.openMenuAt(r,t.clientX,t.clientY)}))}onKeyDown(e){const t="F10"===e.key&&e.shiftKey,n="ContextMenu"===e.key;if(!t&&!n)return;e.preventDefault();const o=this.grid;if(!o)return;const i=o._focusRow,r=o._focusCol,s=this.visibleColumns[r],l=this.rows[i],c=this.gridElement,a=c?.querySelector(`[data-row="${i}"][data-col="${r}"]`);let u=0,d=0;if(a){const e=a.getBoundingClientRect();u=e.left+e.width/2,d=e.bottom}const m=this.syncSelectionOnContextMenu(i),b={row:l,rowIndex:i,column:s,columnIndex:r,field:s?.field??"",value:l?.[s?.field]??null,isHeader:!1,event:e,selectedRows:m};return this.openMenuAt(b,u,d,!0),!0}showMenu(e,t,n){const o={row:n.row??null,rowIndex:n.rowIndex??-1,column:n.column??null,columnIndex:n.columnIndex??-1,field:n.field??"",value:n.value??null,isHeader:n.isHeader??!1,event:n.event??new MouseEvent("contextmenu"),selectedRows:n.selectedRows??[]};this.openMenuAt(o,e,t)}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen&&(this.isOpen=!1)}isMenuOpen(){return this.isOpen}}e.ContextMenuPlugin=b,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=context-menu.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-menu.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/context-menu/menu.ts","../../../../../libs/grid/src/lib/plugins/context-menu/ContextMenuPlugin.ts"],"sourcesContent":["/**\n * Context Menu Rendering Logic\n *\n * Pure functions for building and positioning context menus.\n */\n\nimport { sanitizeHTML } from '../../core/internal/sanitize';\nimport { toIconAttr } from '../../core/plugin/base-plugin';\nimport type { IconValue } from '../../core/types';\nimport type { ContextMenuItem, ContextMenuParams } from './types';\n\n/**\n * Build the visible menu items by resolving dynamic items and filtering hidden ones.\n *\n * @param items - Menu items configuration (array or factory function)\n * @param params - Context menu parameters for evaluating dynamic properties\n * @returns Filtered array of visible menu items\n */\nexport function buildMenuItems(\n items: ContextMenuItem[] | ((params: ContextMenuParams) => ContextMenuItem[]),\n params: ContextMenuParams,\n): ContextMenuItem[] {\n const menuItems = typeof items === 'function' ? items(params) : items;\n\n return menuItems.filter((item) => {\n if (item.hidden === true) return false;\n if (typeof item.hidden === 'function' && item.hidden(params)) return false;\n return true;\n });\n}\n\n/**\n * Remove consecutive, leading, and trailing separators from a menu item list.\n *\n * @param items - Array of menu items\n * @returns Cleaned array with no redundant separators\n */\nexport function collapseSeparators(items: ContextMenuItem[]): ContextMenuItem[] {\n const result: ContextMenuItem[] = [];\n for (const item of items) {\n if (item.separator) {\n // Skip if the last item is already a separator (consecutive) or list is empty (leading)\n if (result.length === 0 || result[result.length - 1].separator) continue;\n }\n result.push(item);\n }\n // Remove trailing separator\n if (result.length > 0 && result[result.length - 1].separator) {\n result.pop();\n }\n return result;\n}\n\n/**\n * Check if a menu item is disabled.\n *\n * @param item - The menu item to check\n * @param params - Context menu parameters for evaluating dynamic disabled state\n * @returns True if the item is disabled\n */\nexport function isItemDisabled(item: ContextMenuItem, params: ContextMenuParams): boolean {\n if (item.disabled === true) return true;\n if (typeof item.disabled === 'function') return item.disabled(params);\n return false;\n}\n\n/**\n * Create the menu DOM element from a list of menu items.\n *\n * @param items - Array of menu items to render\n * @param params - Context menu parameters for evaluating dynamic properties\n * @param onAction - Callback when a menu item action is triggered\n * @param submenuArrow - Optional custom submenu arrow icon\n * @returns The created menu element\n */\nexport function createMenuElement(\n items: ContextMenuItem[],\n params: ContextMenuParams,\n onAction: (item: ContextMenuItem) => void,\n submenuArrow?: IconValue,\n): HTMLElement {\n const menu = document.createElement('div');\n menu.className = 'tbw-context-menu';\n menu.setAttribute('role', 'menu');\n\n // Check if any non-separator item has an icon\n const hasAnyIcon = items.some((item) => !item.separator && item.icon);\n\n for (const item of items) {\n if (item.separator) {\n const separator = document.createElement('div');\n separator.className = 'tbw-context-menu-separator';\n separator.setAttribute('role', 'separator');\n menu.appendChild(separator);\n continue;\n }\n\n const menuItem = document.createElement('div');\n menuItem.className = 'tbw-context-menu-item';\n if (item.cssClass) menuItem.classList.add(item.cssClass);\n menuItem.setAttribute('role', 'menuitem');\n menuItem.setAttribute('data-id', item.id);\n menuItem.setAttribute('tabindex', '-1');\n\n const disabled = isItemDisabled(item, params);\n if (disabled) {\n menuItem.classList.add('disabled');\n menuItem.setAttribute('aria-disabled', 'true');\n }\n\n if (item.icon) {\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = sanitizeHTML(item.icon);\n menuItem.appendChild(icon);\n } else if (hasAnyIcon) {\n // Add empty placeholder to align labels when other items have icons\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = ' ';\n menuItem.appendChild(icon);\n }\n\n const label = document.createElement('span');\n label.className = 'tbw-context-menu-label';\n label.textContent = item.name;\n menuItem.appendChild(label);\n\n if (item.shortcut) {\n const shortcut = document.createElement('span');\n shortcut.className = 'tbw-context-menu-shortcut';\n if (Array.isArray(item.shortcut)) {\n item.shortcut.forEach((key, i) => {\n if (i > 0) shortcut.appendChild(document.createTextNode('+'));\n const kbd = document.createElement('kbd');\n kbd.textContent = key;\n shortcut.appendChild(kbd);\n });\n } else {\n const kbd = document.createElement('kbd');\n kbd.textContent = item.shortcut;\n shortcut.appendChild(kbd);\n }\n menuItem.appendChild(shortcut);\n }\n\n if (item.subMenu?.length) {\n const arrow = document.createElement('span');\n arrow.className = 'tbw-context-menu-arrow';\n arrow.dataset.icon = toIconAttr('submenuArrow');\n // Only inject content if a JS icon override was provided\n if (submenuArrow !== undefined) {\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = sanitizeHTML(submenuArrow);\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\n }\n }\n menuItem.appendChild(arrow);\n\n // Add submenu on hover\n menuItem.addEventListener('mouseenter', () => {\n const existingSubMenu = menuItem.querySelector('.tbw-context-menu');\n if (existingSubMenu) return;\n if (!item.subMenu) return;\n\n const subMenuItems = buildMenuItems(item.subMenu, params);\n const subMenu = createMenuElement(subMenuItems, params, onAction, submenuArrow);\n subMenu.classList.add('tbw-context-submenu');\n subMenu.style.position = 'absolute';\n subMenu.style.left = '100%';\n subMenu.style.top = '0';\n menuItem.style.position = 'relative';\n menuItem.appendChild(subMenu);\n });\n\n menuItem.addEventListener('mouseleave', () => {\n const subMenu = menuItem.querySelector('.tbw-context-menu');\n if (subMenu) subMenu.remove();\n });\n }\n\n if (!disabled && item.action && !item.subMenu) {\n menuItem.addEventListener('click', (e) => {\n e.stopPropagation();\n onAction(item);\n });\n }\n\n menu.appendChild(menuItem);\n }\n\n return menu;\n}\n\n/**\n * Position the menu at the given viewport coordinates.\n * Menu is rendered in document.body with fixed positioning for top-layer behavior.\n *\n * @param menu - The menu element to position\n * @param x - Desired X coordinate (viewport)\n * @param y - Desired Y coordinate (viewport)\n */\nexport function positionMenu(menu: HTMLElement, x: number, y: number): void {\n // Use fixed positioning for top-layer behavior\n menu.style.position = 'fixed';\n menu.style.left = `${x}px`;\n menu.style.top = `${y}px`;\n menu.style.visibility = 'hidden';\n menu.style.zIndex = '10000';\n\n // Force layout to get dimensions\n const menuRect = menu.getBoundingClientRect();\n\n // Calculate visible area within viewport\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let left = x;\n let top = y;\n\n // Check if menu overflows right edge of viewport\n if (x + menuRect.width > viewportWidth) {\n left = x - menuRect.width;\n }\n // Check if menu overflows bottom edge of viewport\n if (y + menuRect.height > viewportHeight) {\n top = y - menuRect.height;\n }\n\n // Ensure we don't go negative\n left = Math.max(0, left);\n top = Math.max(0, top);\n\n menu.style.left = `${left}px`;\n menu.style.top = `${top}px`;\n menu.style.visibility = 'visible';\n}\n\n/**\n * Attach keyboard navigation to a context menu element.\n * Handles ArrowUp/Down to move between items, Enter to activate, Escape to close.\n *\n * @param menu - The menu element (must have role=\"menu\" children with role=\"menuitem\")\n * @param onClose - Callback to run when the menu is closed via keyboard\n */\nexport function setupMenuKeyboard(menu: HTMLElement, onClose: () => void): void {\n menu.addEventListener('keydown', (e: KeyboardEvent) => {\n const items = Array.from(menu.querySelectorAll<HTMLElement>('[role=\"menuitem\"]:not(.disabled)'));\n if (!items.length) return;\n\n const current = document.activeElement as HTMLElement;\n const idx = items.indexOf(current);\n\n switch (e.key) {\n case 'ArrowDown': {\n e.preventDefault();\n const next = idx < items.length - 1 ? idx + 1 : 0;\n items[next].focus();\n break;\n }\n case 'ArrowUp': {\n e.preventDefault();\n const prev = idx > 0 ? idx - 1 : items.length - 1;\n items[prev].focus();\n break;\n }\n case 'Enter':\n case ' ': {\n e.preventDefault();\n if (current && items.includes(current)) {\n current.click();\n }\n break;\n }\n case 'Escape': {\n e.preventDefault();\n onClose();\n break;\n }\n }\n });\n}\n\n/**\n * Focus the first non-disabled menu item.\n *\n * @param menu - The menu element\n */\nexport function focusFirstMenuItem(menu: HTMLElement): void {\n const first = menu.querySelector<HTMLElement>('[role=\"menuitem\"]:not(.disabled)');\n first?.focus();\n}\n","/**\n * Context Menu Plugin (Class-based)\n *\n * Provides right-click context menu functionality for tbw-grid.\n * Supports custom menu items, submenus, icons, shortcuts, and dynamic item generation.\n */\n\nimport type { PluginManifest } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport {\n buildMenuItems,\n collapseSeparators,\n createMenuElement,\n focusFirstMenuItem,\n positionMenu,\n setupMenuKeyboard,\n} from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams, HeaderContextMenuItem } from './types';\n\n/** Query type for collecting context menu items from plugins */\nconst QUERY_GET_CONTEXT_MENU_ITEMS = 'getContextMenuItems';\n\n/** Shared AbortController for global document listeners (all instances share one) */\nlet globalAbortController: AbortController | null = null;\n/** Global stylesheet for context menu (injected once) */\nlet globalStyleSheet: HTMLStyleElement | null = null;\n/** Reference count for instances using global handlers */\nlet globalHandlerRefCount = 0;\n\n/** Default menu items when none are configured */\nconst defaultItems: ContextMenuItem[] = [\n {\n id: 'copy',\n name: 'Copy',\n shortcut: 'Ctrl+C',\n action: (params) => {\n // Use the query system instead of direct plugin access for proper decoupling\n const grid = (params as ContextMenuParams & { grid?: { query?: (type: string) => unknown[] } }).grid;\n grid?.query?.('clipboard:copy');\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n // Use the query system instead of direct plugin access for proper decoupling\n const grid = (params as ContextMenuParams & { grid?: { query?: (type: string) => unknown[] } }).grid;\n grid?.query?.('export:csv');\n },\n },\n];\n\n/**\n * Context Menu Plugin for tbw-grid\n *\n * Adds a customizable right-click menu to grid cells. Build anything from simple\n * copy/paste actions to complex nested menus with conditional visibility, icons,\n * and keyboard shortcuts.\n *\n * ## Installation\n *\n * ```ts\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n * ```\n *\n * ## Menu Item Structure\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique item identifier |\n * | `name` | `string` | Display label |\n * | `icon` | `string` | Icon class or HTML |\n * | `shortcut` | `string` | Keyboard shortcut hint |\n * | `action` | `(params) => void` | Click handler |\n * | `disabled` | `boolean \\| (params) => boolean` | Disable condition |\n * | `visible` | `boolean \\| (params) => boolean` | Visibility condition |\n * | `items` | `MenuItem[]` | Submenu items |\n * | `separator` | `boolean` | Create a divider line |\n *\n * ## Menu Context (params)\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `rowIndex` | `number` | Clicked row index |\n * | `colIndex` | `number` | Clicked column index |\n * | `field` | `string` | Column field name |\n * | `value` | `any` | Cell value |\n * | `row` | `any` | Full row data |\n * | `column` | `ColumnConfig` | Column configuration |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-context-menu-bg` | `var(--tbw-color-panel-bg)` | Menu background |\n * | `--tbw-context-menu-fg` | `var(--tbw-color-fg)` | Menu text color |\n * | `--tbw-context-menu-hover` | `var(--tbw-color-row-hover)` | Item hover background |\n *\n * @example Basic Context Menu\n * ```ts\n * import '@toolbox-web/grid';\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ContextMenuPlugin({\n * items: [\n * { id: 'copy', name: 'Copy', shortcut: 'Ctrl+C', action: (ctx) => navigator.clipboard.writeText(ctx.value) },\n * { separator: true, id: 'sep1', name: '' },\n * { id: 'delete', name: 'Delete', action: (ctx) => removeRow(ctx.rowIndex) },\n * ],\n * }),\n * ],\n * };\n * ```\n *\n * @example Conditional Menu Items\n * ```ts\n * new ContextMenuPlugin({\n * items: [\n * { id: 'edit', name: 'Edit', visible: (ctx) => ctx.column.editable === true },\n * { id: 'delete', name: 'Delete', disabled: (ctx) => ctx.row.locked === true },\n * ],\n * })\n * ```\n *\n * @see {@link ContextMenuConfig} for configuration options\n * @see {@link ContextMenuItem} for menu item structure\n * @see {@link ContextMenuParams} for action callback parameters\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ContextMenuPlugin extends BaseGridPlugin<ContextMenuConfig> {\n /**\n * Plugin manifest - declares queries used by this plugin.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: QUERY_GET_CONTEXT_MENU_ITEMS,\n description: 'Collects context menu items from other plugins for header right-click menus',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'contextMenu';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ContextMenuConfig> {\n return {\n items: defaultItems,\n };\n }\n\n // #region Internal State\n private isOpen = false;\n private position = { x: 0, y: 0 };\n private params: ContextMenuParams | null = null;\n private menuElement: HTMLElement | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n this.installGlobalHandlers();\n globalHandlerRefCount++;\n }\n\n /** @internal */\n override detach(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n this.isOpen = false;\n this.params = null;\n this.uninstallGlobalHandlers();\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Sync selection with the right-clicked row.\n * If the right-clicked row is already selected, keeps the multi-selection.\n * If not, selects only the right-clicked row (standard behavior in file managers / spreadsheets).\n *\n * @returns Sorted array of selected row indices after sync\n */\n private syncSelectionOnContextMenu(rowIndex: number): number[] {\n if (rowIndex < 0) return [];\n\n // Use the query system for loose coupling — no import of SelectionPlugin needed\n const selectionResult = this.grid?.query<number[]>('getSelectedRowIndices');\n const currentSelection = selectionResult?.[0];\n\n // No selection plugin loaded\n if (!currentSelection) return [rowIndex];\n\n if (currentSelection.includes(rowIndex)) {\n // Right-clicked row is already selected — preserve multi-selection\n return currentSelection;\n }\n\n // Right-clicked row is NOT selected — select only this row\n this.grid?.query('selectRows', [rowIndex]);\n return [rowIndex];\n }\n\n /**\n * CSS variables to copy from the grid element to the context menu.\n * Includes both base variables and context-menu specific overrides.\n */\n private static readonly CSS_VARS_TO_COPY = [\n // Base palette (for themes that only set base vars)\n '--tbw-color-panel-bg',\n '--tbw-color-fg',\n '--tbw-color-fg-muted',\n '--tbw-color-border',\n '--tbw-color-row-hover',\n '--tbw-color-shadow',\n '--tbw-color-danger',\n '--tbw-border-radius',\n '--tbw-font-family',\n '--tbw-font-size-sm',\n '--tbw-font-size-xs',\n '--tbw-font-size-2xs',\n '--tbw-spacing-xs',\n '--tbw-icon-size',\n '--tbw-menu-min-width',\n '--tbw-menu-item-padding',\n '--tbw-menu-item-gap',\n // Context menu specific overrides\n '--tbw-context-menu-bg',\n '--tbw-context-menu-fg',\n '--tbw-context-menu-border',\n '--tbw-context-menu-radius',\n '--tbw-context-menu-shadow',\n '--tbw-context-menu-hover',\n '--tbw-context-menu-danger',\n '--tbw-context-menu-muted',\n '--tbw-context-menu-min-width',\n '--tbw-context-menu-font-size',\n '--tbw-context-menu-font-family',\n '--tbw-context-menu-item-padding',\n '--tbw-context-menu-item-gap',\n '--tbw-context-menu-icon-size',\n '--tbw-context-menu-shortcut-size',\n '--tbw-context-menu-arrow-size',\n // Icon variables for context menu icons rendered outside tbw-grid\n '--tbw-icon-submenu-arrow',\n ];\n\n /**\n * Copy CSS custom properties from the grid element to the menu element.\n * This allows the context menu (appended to document.body) to inherit\n * theme variables set on tbw-grid.\n */\n private copyGridStyles(menuElement: HTMLElement): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const computed = getComputedStyle(gridEl);\n const styles: string[] = [];\n\n // Copy color-scheme so light-dark() can resolve in the context menu\n const colorScheme = computed.getPropertyValue('color-scheme').trim();\n if (colorScheme) {\n styles.push(`color-scheme: ${colorScheme}`);\n }\n\n for (const varName of ContextMenuPlugin.CSS_VARS_TO_COPY) {\n const value = computed.getPropertyValue(varName).trim();\n if (value) {\n styles.push(`${varName}: ${value}`);\n }\n }\n\n if (styles.length > 0) {\n // Append to existing inline styles (don't overwrite)\n const existing = menuElement.getAttribute('style') || '';\n menuElement.setAttribute('style', existing + styles.join('; ') + ';');\n }\n }\n\n private installGlobalHandlers(): void {\n // Inject global stylesheet for context menu (once)\n // Only inject if we have valid CSS text (Vite's ?inline import)\n // When importing from source without Vite, the import is a module object, not a string\n if (\n !globalStyleSheet &&\n typeof document !== 'undefined' &&\n typeof contextMenuStyles === 'string' &&\n contextMenuStyles\n ) {\n globalStyleSheet = document.createElement('style');\n globalStyleSheet.id = 'tbw-context-menu-styles';\n globalStyleSheet.textContent = contextMenuStyles;\n document.head.appendChild(globalStyleSheet);\n }\n\n if (!globalAbortController) {\n globalAbortController = new AbortController();\n const signal = globalAbortController.signal;\n\n const closeAllMenus = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n\n // Close menu on click outside\n document.addEventListener('click', closeAllMenus, { signal });\n\n // Close on escape\n document.addEventListener(\n 'keydown',\n (e: KeyboardEvent) => {\n if (e.key === 'Escape') closeAllMenus();\n },\n { signal },\n );\n\n // Close on scroll (any scrollable ancestor)\n document.addEventListener('scroll', closeAllMenus, { capture: true, signal });\n }\n }\n\n /**\n * Clean up global handlers when the last instance detaches.\n * Uses reference counting to ensure handlers persist while any grid uses the plugin.\n */\n private uninstallGlobalHandlers(): void {\n globalHandlerRefCount--;\n if (globalHandlerRefCount > 0) return;\n\n // Last instance - abort all global listeners at once\n if (globalAbortController) {\n globalAbortController.abort();\n globalAbortController = null;\n }\n if (globalStyleSheet) {\n globalStyleSheet.remove();\n globalStyleSheet = null;\n }\n }\n\n /**\n * Query all plugins for context menu items via the query system.\n * Each plugin that handles `getContextMenuItems` can return an array of HeaderContextMenuItem.\n */\n private collectPluginItems(params: ContextMenuParams): HeaderContextMenuItem[] {\n if (!this.grid) return [];\n\n const responses = this.grid.query<HeaderContextMenuItem[]>(QUERY_GET_CONTEXT_MENU_ITEMS, params);\n const items: HeaderContextMenuItem[] = [];\n\n for (const response of responses) {\n if (Array.isArray(response)) {\n items.push(...response);\n }\n }\n\n // Sort by order (default 100), then stable by insertion order\n items.sort((a, b) => (a.order ?? 100) - (b.order ?? 100));\n\n // Insert separators between different order groups\n return this.insertGroupSeparators(items);\n }\n\n /**\n * Insert separators between groups of items with different order ranges.\n * Groups are defined by the tens digit (10-19, 20-29, etc.).\n */\n private insertGroupSeparators(items: HeaderContextMenuItem[]): HeaderContextMenuItem[] {\n if (items.length <= 1) return items;\n\n const result: HeaderContextMenuItem[] = [];\n let lastGroup = -1;\n\n for (const item of items) {\n if (item.separator) {\n result.push(item);\n continue;\n }\n const group = Math.floor((item.order ?? 100) / 10);\n if (lastGroup >= 0 && group !== lastGroup) {\n result.push({\n id: `__sep-${lastGroup}-${group}`,\n label: '',\n separator: true,\n action: () => {\n /* noop */\n },\n });\n }\n lastGroup = group;\n result.push(item);\n }\n\n return result;\n }\n\n /**\n * Convert plugin-contributed HeaderContextMenuItems to the internal ContextMenuItem format.\n */\n private convertPluginItems(items: HeaderContextMenuItem[]): ContextMenuItem[] {\n return items.map((item) => ({\n id: item.id,\n name: item.label,\n icon: item.icon,\n shortcut: item.shortcut,\n disabled: item.disabled ?? false,\n action: () => item.action(),\n separator: item.separator,\n cssClass: item.cssClass,\n }));\n }\n // #endregion\n\n // #region Hooks\n\n /**\n * Shared logic to build menu items, create the menu element, and show it.\n * Used by both the contextmenu mouse handler and keyboard triggers.\n *\n * @param params - Context menu parameters\n * @param x - Viewport X coordinate\n * @param y - Viewport Y coordinate\n * @param focusFirst - Whether to focus the first menu item (keyboard-triggered)\n */\n private openMenuAt(params: ContextMenuParams, x: number, y: number, focusFirst = false): void {\n this.params = params;\n this.position = { x, y };\n\n // Collect plugin-contributed items via the query system\n const pluginItems = this.collectPluginItems(params);\n\n // Build configured items\n let items = buildMenuItems(this.config.items ?? defaultItems, params);\n\n // Merge plugin items with configured items\n if (pluginItems.length > 0) {\n const converted = this.convertPluginItems(pluginItems);\n if (items.length > 0 && converted.length > 0) {\n items = [...items, { id: '__plugin-sep', name: '', separator: true }, ...converted];\n } else {\n items = [...items, ...converted];\n }\n }\n\n // Collapse consecutive/leading/trailing separators\n items = collapseSeparators(items);\n\n if (!items.length) return;\n\n // Close any open context menu (including from other grids)\n document.querySelectorAll('.tbw-context-menu').forEach((m) => m.remove());\n this.menuElement = null;\n\n this.menuElement = createMenuElement(\n items,\n params,\n (item) => {\n if (item.action) {\n item.action(params);\n }\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.grid?.gridConfig?.icons?.submenuArrow,\n );\n\n // Attach keyboard navigation (arrow keys, Enter, Escape)\n setupMenuKeyboard(this.menuElement, () => this.hideMenu());\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n\n if (focusFirst) {\n focusFirstMenuItem(this.menuElement);\n }\n\n this.emit('context-menu-open', { params, items });\n }\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Use querySelector instead of children[0] because light DOM children\n // (e.g. <tbw-grid-column>) are re-appended before .tbw-grid-root, making\n // children[0] point to a declarative element instead of the data container.\n const container = gridEl.querySelector('.tbw-grid-root');\n if (!container) return;\n\n // Check if handler already attached\n if (container.getAttribute('data-context-menu-bound') === 'true') return;\n container.setAttribute('data-context-menu-bound', 'true');\n\n container.addEventListener('contextmenu', (e: Event) => {\n const event = e as MouseEvent;\n event.preventDefault();\n\n const target = event.target as HTMLElement;\n const cell = target.closest('[data-row][data-col]');\n const header = target.closest('[part~=\"header-cell\"]');\n\n let params: ContextMenuParams;\n\n if (cell) {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const column = this.visibleColumns[colIndex];\n const row = this.rows[rowIndex];\n\n // Sync selection: if the right-clicked row is not already selected,\n // select it (clearing multi-selection). If it IS selected, keep all.\n const selectedRows = this.syncSelectionOnContextMenu(rowIndex);\n\n params = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event,\n selectedRows,\n };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.visibleColumns[colIndex];\n\n params = {\n row: null,\n rowIndex: -1,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: null,\n isHeader: true,\n event,\n selectedRows: [],\n };\n } else {\n return;\n }\n\n this.openMenuAt(params, event.clientX, event.clientY);\n });\n }\n\n /**\n * Handle keyboard shortcuts to open the context menu.\n * Shift+F10 and the dedicated ContextMenu key open the menu at the focused cell.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // Shift+F10 or the dedicated ContextMenu/Application key\n const isShiftF10 = event.key === 'F10' && event.shiftKey;\n const isContextMenuKey = event.key === 'ContextMenu';\n\n if (!isShiftF10 && !isContextMenuKey) return;\n\n // Prevent the browser's native context menu from appearing\n event.preventDefault();\n\n const grid = this.grid;\n if (!grid) return;\n\n const rowIndex = grid._focusRow;\n const colIndex = grid._focusCol;\n const column = this.visibleColumns[colIndex];\n const row = this.rows[rowIndex];\n\n // Find the focused cell element to position the menu near it\n const gridEl = this.gridElement;\n const cellEl = gridEl?.querySelector<HTMLElement>(`[data-row=\"${rowIndex}\"][data-col=\"${colIndex}\"]`);\n let x = 0;\n let y = 0;\n if (cellEl) {\n const rect = cellEl.getBoundingClientRect();\n x = rect.left + rect.width / 2;\n y = rect.bottom;\n }\n\n const selectedRows = this.syncSelectionOnContextMenu(rowIndex);\n\n const params: ContextMenuParams = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event: event,\n selectedRows,\n };\n\n this.openMenuAt(params, x, y, true);\n return true;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n *\n * Use this to open the menu from custom UI elements or keyboard shortcuts\n * without requiring a native `contextmenu` event.\n *\n * @param x - Viewport X coordinate (pixels)\n * @param y - Viewport Y coordinate (pixels)\n * @param params - Partial context menu parameters — unspecified fields receive sensible defaults\n *\n * @example\n * ```ts\n * const menu = grid.getPluginByName('context-menu');\n * // Open menu at a button's position with row context\n * const rect = button.getBoundingClientRect();\n * menu.showMenu(rect.left, rect.bottom, {\n * row: selectedRow,\n * rowIndex: 3,\n * column: columns[0],\n * });\n * ```\n */\n showMenu(x: number, y: number, params: Partial<ContextMenuParams>): void {\n const fullParams: ContextMenuParams = {\n row: params.row ?? null,\n rowIndex: params.rowIndex ?? -1,\n column: params.column ?? null,\n columnIndex: params.columnIndex ?? -1,\n field: params.field ?? '',\n value: params.value ?? null,\n isHeader: params.isHeader ?? false,\n event: params.event ?? new MouseEvent('contextmenu'),\n selectedRows: params.selectedRows ?? [],\n };\n\n this.openMenuAt(fullParams, x, y);\n }\n\n /**\n * Hide the context menu if it is currently open.\n *\n * Safe to call even when the menu is already closed.\n */\n hideMenu(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n this.isOpen = false;\n }\n }\n\n /**\n * Check if the context menu is currently open.\n *\n * @returns `true` when the menu is visible\n */\n isMenuOpen(): boolean {\n return this.isOpen;\n }\n // #endregion\n\n // Styles are injected globally via installGlobalHandlers() since menu renders in document.body\n}\n"],"names":["buildMenuItems","items","params","filter","item","hidden","isItemDisabled","disabled","createMenuElement","onAction","submenuArrow","menu","document","createElement","className","setAttribute","hasAnyIcon","some","separator","icon","appendChild","menuItem","cssClass","classList","add","id","innerHTML","sanitizeHTML","label","textContent","name","shortcut","Array","isArray","forEach","key","i","createTextNode","kbd","subMenu","length","arrow","dataset","toIconAttr","HTMLElement","cloneNode","addEventListener","querySelector","style","position","left","top","remove","action","e","stopPropagation","QUERY_GET_CONTEXT_MENU_ITEMS","globalAbortController","globalStyleSheet","globalHandlerRefCount","defaultItems","grid","query","ContextMenuPlugin","BaseGridPlugin","static","queries","type","description","defaultConfig","isOpen","x","y","menuElement","attach","super","this","installGlobalHandlers","detach","uninstallGlobalHandlers","syncSelectionOnContextMenu","rowIndex","selectionResult","currentSelection","includes","copyGridStyles","gridEl","gridElement","computed","getComputedStyle","styles","colorScheme","getPropertyValue","trim","push","varName","CSS_VARS_TO_COPY","value","existing","getAttribute","join","contextMenuStyles","head","AbortController","signal","closeAllMenus","querySelectorAll","capture","abort","collectPluginItems","responses","response","sort","a","b","order","insertGroupSeparators","result","lastGroup","group","Math","floor","convertPluginItems","map","openMenuAt","focusFirst","pluginItems","config","converted","onClose","pop","collapseSeparators","m","gridConfig","icons","hideMenu","from","current","activeElement","idx","indexOf","preventDefault","focus","click","body","visibility","zIndex","menuRect","getBoundingClientRect","viewportWidth","window","innerWidth","viewportHeight","innerHeight","width","height","max","positionMenu","first","focusFirstMenuItem","emit","afterRender","container","event","target","cell","closest","header","parseInt","colIndex","column","visibleColumns","row","rows","selectedRows","columnIndex","field","isHeader","clientX","clientY","onKeyDown","isShiftF10","shiftKey","isContextMenuKey","_focusRow","_focusCol","cellEl","rect","bottom","showMenu","fullParams","MouseEvent","isMenuOpen"],"mappings":"0mEAkBO,SAASA,EACdC,EACAC,GAIA,OAFmC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AAK4H,UAChBf,EAAS9F,KAAK+F,eAAeF,GAC7BG,EAAMhG,KAAKiG,KAAK5F,GAGhBK,EAASV,KAAKW,YACdmG,EAASpG,GAAQvC,cAA2B,cAAckC,iBAAwBwF,OACxF,IAAIlG,EAAI,EACJC,EAAI,EACR,GAAIkH,EAAQ,CACV,MAAMC,EAAOD,EAAOtC,wBACpB7E,EAAIoH,EAAKzI,KAAOyI,EAAKjC,MAAQ,EAC7BlF,EAAImH,EAAKC,MACX,CAEA,MAAMd,EAAelG,KAAKI,2BAA2BC,GAE/C/E,EAA4B,CAChC0K,MACA3F,WACAyF,SACAK,YAAaN,EACbO,MAAON,GAAQM,OAAS,GACxB/E,MAAO2E,IAAMF,GAAQM,QAA8B,KACnDC,UAAU,EACVd,QACAW,gBAIF,OADAlG,KAAKgD,WAAW1H,EAAQqE,EAAGC,GAAG,IACvB,CACT,CA2BA,QAAAqH,CAAStH,EAAWC,EAAWtE,GAC7B,MAAM4L,EAAgC,CACpClB,IAAK1K,EAAO0K,KAAO,KACnB3F,SAAU/E,EAAO+E,WAAY,EAC7ByF,OAAQxK,EAAOwK,QAAU,KACzBK,YAAa7K,EAAO6K,cAAe,EACnCC,MAAO9K,EAAO8K,OAAS,GACvB/E,MAAO/F,EAAO+F,OAAS,KACvBgF,SAAU/K,EAAO+K,WAAY,EAC7Bd,MAAOjK,EAAOiK,OAAS,IAAI4B,WAAW,eACtCjB,aAAc5K,EAAO4K,cAAgB,IAGvClG,KAAKgD,WAAWkE,EAAYvH,EAAGC,EACjC,CAOA,QAAA+D,GACM3D,KAAKH,cACPG,KAAKH,YAAYrB,SACjBwB,KAAKH,YAAc,KACnBG,KAAKN,QAAS,EAElB,CAOA,UAAA0H,GACE,OAAOpH,KAAKN,MACd"}
|
|
1
|
+
{"version":3,"file":"context-menu.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/context-menu/menu.ts","../../../../../libs/grid/src/lib/plugins/context-menu/ContextMenuPlugin.ts"],"sourcesContent":["/**\n * Context Menu Rendering Logic\n *\n * Pure functions for building and positioning context menus.\n */\n\nimport { sanitizeHTML } from '../../core/internal/sanitize';\nimport { toIconAttr } from '../../core/plugin/base-plugin';\nimport type { IconValue } from '../../core/types';\nimport type { ContextMenuItem, ContextMenuParams } from './types';\n\n/**\n * Build the visible menu items by resolving dynamic items and filtering hidden ones.\n *\n * @param items - Menu items configuration (array or factory function)\n * @param params - Context menu parameters for evaluating dynamic properties\n * @returns Filtered array of visible menu items\n */\nexport function buildMenuItems(\n items: ContextMenuItem[] | ((params: ContextMenuParams) => ContextMenuItem[]),\n params: ContextMenuParams,\n): ContextMenuItem[] {\n const menuItems = typeof items === 'function' ? items(params) : items;\n\n return menuItems.filter((item) => {\n if (item.hidden === true) return false;\n if (typeof item.hidden === 'function' && item.hidden(params)) return false;\n return true;\n });\n}\n\n/**\n * Remove consecutive, leading, and trailing separators from a menu item list.\n *\n * @param items - Array of menu items\n * @returns Cleaned array with no redundant separators\n */\nexport function collapseSeparators(items: ContextMenuItem[]): ContextMenuItem[] {\n const result: ContextMenuItem[] = [];\n for (const item of items) {\n if (item.separator) {\n // Skip if the last item is already a separator (consecutive) or list is empty (leading)\n if (result.length === 0 || result[result.length - 1].separator) continue;\n }\n result.push(item);\n }\n // Remove trailing separator\n if (result.length > 0 && result[result.length - 1].separator) {\n result.pop();\n }\n return result;\n}\n\n/**\n * Check if a menu item is disabled.\n *\n * @param item - The menu item to check\n * @param params - Context menu parameters for evaluating dynamic disabled state\n * @returns True if the item is disabled\n */\nexport function isItemDisabled(item: ContextMenuItem, params: ContextMenuParams): boolean {\n if (item.disabled === true) return true;\n if (typeof item.disabled === 'function') return item.disabled(params);\n return false;\n}\n\n/**\n * Create the menu DOM element from a list of menu items.\n *\n * @param items - Array of menu items to render\n * @param params - Context menu parameters for evaluating dynamic properties\n * @param onAction - Callback when a menu item action is triggered\n * @param submenuArrow - Optional custom submenu arrow icon\n * @returns The created menu element\n */\nexport function createMenuElement(\n items: ContextMenuItem[],\n params: ContextMenuParams,\n onAction: (item: ContextMenuItem) => void,\n submenuArrow?: IconValue,\n): HTMLElement {\n const menu = document.createElement('div');\n menu.className = 'tbw-context-menu';\n menu.setAttribute('role', 'menu');\n\n // Check if any non-separator item has an icon\n const hasAnyIcon = items.some((item) => !item.separator && item.icon);\n\n for (const item of items) {\n if (item.separator) {\n const separator = document.createElement('div');\n separator.className = 'tbw-context-menu-separator';\n separator.setAttribute('role', 'separator');\n menu.appendChild(separator);\n continue;\n }\n\n const menuItem = document.createElement('div');\n menuItem.className = 'tbw-context-menu-item';\n if (item.cssClass) menuItem.classList.add(item.cssClass);\n menuItem.setAttribute('role', 'menuitem');\n menuItem.setAttribute('data-id', item.id);\n menuItem.setAttribute('tabindex', '-1');\n\n const disabled = isItemDisabled(item, params);\n if (disabled) {\n menuItem.classList.add('disabled');\n menuItem.setAttribute('aria-disabled', 'true');\n }\n\n if (item.icon) {\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = sanitizeHTML(item.icon);\n menuItem.appendChild(icon);\n } else if (hasAnyIcon) {\n // Add empty placeholder to align labels when other items have icons\n const icon = document.createElement('span');\n icon.className = 'tbw-context-menu-icon';\n icon.innerHTML = ' ';\n menuItem.appendChild(icon);\n }\n\n const label = document.createElement('span');\n label.className = 'tbw-context-menu-label';\n label.textContent = item.name;\n menuItem.appendChild(label);\n\n if (item.shortcut) {\n const shortcut = document.createElement('span');\n shortcut.className = 'tbw-context-menu-shortcut';\n if (Array.isArray(item.shortcut)) {\n item.shortcut.forEach((key, i) => {\n if (i > 0) shortcut.appendChild(document.createTextNode('+'));\n const kbd = document.createElement('kbd');\n kbd.textContent = key;\n shortcut.appendChild(kbd);\n });\n } else {\n const kbd = document.createElement('kbd');\n kbd.textContent = item.shortcut;\n shortcut.appendChild(kbd);\n }\n menuItem.appendChild(shortcut);\n }\n\n if (item.subMenu?.length) {\n const arrow = document.createElement('span');\n arrow.className = 'tbw-context-menu-arrow';\n arrow.dataset.icon = toIconAttr('submenuArrow');\n // Only inject content if a JS icon override was provided\n if (submenuArrow !== undefined) {\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = sanitizeHTML(submenuArrow);\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\n }\n }\n menuItem.appendChild(arrow);\n\n // Add submenu on hover\n menuItem.addEventListener('mouseenter', () => {\n const existingSubMenu = menuItem.querySelector('.tbw-context-menu');\n if (existingSubMenu) return;\n if (!item.subMenu) return;\n\n const subMenuItems = buildMenuItems(item.subMenu, params);\n const subMenu = createMenuElement(subMenuItems, params, onAction, submenuArrow);\n subMenu.classList.add('tbw-context-submenu');\n subMenu.style.position = 'absolute';\n subMenu.style.left = '100%';\n subMenu.style.top = '0';\n menuItem.style.position = 'relative';\n menuItem.appendChild(subMenu);\n });\n\n menuItem.addEventListener('mouseleave', () => {\n const subMenu = menuItem.querySelector('.tbw-context-menu');\n if (subMenu) subMenu.remove();\n });\n }\n\n if (!disabled && item.action && !item.subMenu) {\n menuItem.addEventListener('click', (e) => {\n e.stopPropagation();\n onAction(item);\n });\n }\n\n menu.appendChild(menuItem);\n }\n\n return menu;\n}\n\n/**\n * Position the menu at the given viewport coordinates.\n * Menu is rendered in document.body with fixed positioning for top-layer behavior.\n *\n * @param menu - The menu element to position\n * @param x - Desired X coordinate (viewport)\n * @param y - Desired Y coordinate (viewport)\n */\nexport function positionMenu(menu: HTMLElement, x: number, y: number): void {\n // Use fixed positioning for top-layer behavior\n menu.style.position = 'fixed';\n menu.style.left = `${x}px`;\n menu.style.top = `${y}px`;\n menu.style.visibility = 'hidden';\n menu.style.zIndex = '10000';\n\n // Force layout to get dimensions\n const menuRect = menu.getBoundingClientRect();\n\n // Calculate visible area within viewport\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let left = x;\n let top = y;\n\n // Check if menu overflows right edge of viewport\n if (x + menuRect.width > viewportWidth) {\n left = x - menuRect.width;\n }\n // Check if menu overflows bottom edge of viewport\n if (y + menuRect.height > viewportHeight) {\n top = y - menuRect.height;\n }\n\n // Ensure we don't go negative\n left = Math.max(0, left);\n top = Math.max(0, top);\n\n menu.style.left = `${left}px`;\n menu.style.top = `${top}px`;\n menu.style.visibility = 'visible';\n}\n\n/**\n * Attach keyboard navigation to a context menu element.\n * Handles ArrowUp/Down to move between items, Enter to activate, Escape to close.\n *\n * @param menu - The menu element (must have role=\"menu\" children with role=\"menuitem\")\n * @param onClose - Callback to run when the menu is closed via keyboard\n */\nexport function setupMenuKeyboard(menu: HTMLElement, onClose: () => void): void {\n menu.addEventListener('keydown', (e: KeyboardEvent) => {\n const items = Array.from(menu.querySelectorAll<HTMLElement>('[role=\"menuitem\"]:not(.disabled)'));\n if (!items.length) return;\n\n const current = document.activeElement as HTMLElement;\n const idx = items.indexOf(current);\n\n switch (e.key) {\n case 'ArrowDown': {\n e.preventDefault();\n const next = idx < items.length - 1 ? idx + 1 : 0;\n items[next].focus();\n break;\n }\n case 'ArrowUp': {\n e.preventDefault();\n const prev = idx > 0 ? idx - 1 : items.length - 1;\n items[prev].focus();\n break;\n }\n case 'Enter':\n case ' ': {\n e.preventDefault();\n if (current && items.includes(current)) {\n current.click();\n }\n break;\n }\n case 'Escape': {\n e.preventDefault();\n onClose();\n break;\n }\n }\n });\n}\n\n/**\n * Focus the first non-disabled menu item.\n *\n * @param menu - The menu element\n */\nexport function focusFirstMenuItem(menu: HTMLElement): void {\n const first = menu.querySelector<HTMLElement>('[role=\"menuitem\"]:not(.disabled)');\n first?.focus();\n}\n","/**\n * Context Menu Plugin (Class-based)\n *\n * Provides right-click context menu functionality for tbw-grid.\n * Supports custom menu items, submenus, icons, shortcuts, and dynamic item generation.\n */\n\nimport type { PluginManifest } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport {\n buildMenuItems,\n collapseSeparators,\n createMenuElement,\n focusFirstMenuItem,\n positionMenu,\n setupMenuKeyboard,\n} from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams, HeaderContextMenuItem } from './types';\n\n/** Query type for collecting context menu items from plugins */\nconst QUERY_GET_CONTEXT_MENU_ITEMS = 'getContextMenuItems';\n\n/** Shared AbortController for global document listeners (all instances share one) */\nlet globalAbortController: AbortController | null = null;\n/** Global stylesheet for context menu (injected once) */\nlet globalStyleSheet: HTMLStyleElement | null = null;\n/** Reference count for instances using global handlers */\nlet globalHandlerRefCount = 0;\n/**\n * Active plugin instances. The shared global close handlers (Escape / scroll /\n * click outside) iterate this set and call `hideMenu()` on each instance so\n * per-instance state (`isOpen`) stays in sync when a\n * menu is closed without going through the owning plugin's API.\n */\nconst activeInstances = new Set<ContextMenuPlugin>();\n\n/** Default menu items when none are configured */\nconst defaultItems: ContextMenuItem[] = [\n {\n id: 'copy',\n name: 'Copy',\n shortcut: 'Ctrl+C',\n action: (params) => {\n // Use the query system instead of direct plugin access for proper decoupling\n const grid = (params as ContextMenuParams & { grid?: { query?: (type: string) => unknown[] } }).grid;\n grid?.query?.('clipboard:copy');\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n // Use the query system instead of direct plugin access for proper decoupling\n const grid = (params as ContextMenuParams & { grid?: { query?: (type: string) => unknown[] } }).grid;\n grid?.query?.('export:csv');\n },\n },\n];\n\n/**\n * Context Menu Plugin for tbw-grid\n *\n * Adds a customizable right-click menu to grid cells. Build anything from simple\n * copy/paste actions to complex nested menus with conditional visibility, icons,\n * and keyboard shortcuts.\n *\n * ## Installation\n *\n * ```ts\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n * ```\n *\n * ## Menu Item Structure\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `id` | `string` | Unique item identifier |\n * | `name` | `string` | Display label |\n * | `icon` | `string` | Icon class or HTML |\n * | `shortcut` | `string` | Keyboard shortcut hint |\n * | `action` | `(params) => void` | Click handler |\n * | `disabled` | `boolean \\| (params) => boolean` | Disable condition |\n * | `visible` | `boolean \\| (params) => boolean` | Visibility condition |\n * | `items` | `MenuItem[]` | Submenu items |\n * | `separator` | `boolean` | Create a divider line |\n *\n * ## Menu Context (params)\n *\n * | Property | Type | Description |\n * |----------|------|-------------|\n * | `rowIndex` | `number` | Clicked row index |\n * | `colIndex` | `number` | Clicked column index |\n * | `field` | `string` | Column field name |\n * | `value` | `any` | Cell value |\n * | `row` | `any` | Full row data |\n * | `column` | `ColumnConfig` | Column configuration |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-context-menu-bg` | `var(--tbw-color-panel-bg)` | Menu background |\n * | `--tbw-context-menu-fg` | `var(--tbw-color-fg)` | Menu text color |\n * | `--tbw-context-menu-hover` | `var(--tbw-color-row-hover)` | Item hover background |\n *\n * @example Basic Context Menu\n * ```ts\n * import '@toolbox-web/grid';\n * import { ContextMenuPlugin } from '@toolbox-web/grid/plugins/context-menu';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ContextMenuPlugin({\n * items: [\n * { id: 'copy', name: 'Copy', shortcut: 'Ctrl+C', action: (ctx) => navigator.clipboard.writeText(ctx.value) },\n * { separator: true, id: 'sep1', name: '' },\n * { id: 'delete', name: 'Delete', action: (ctx) => removeRow(ctx.rowIndex) },\n * ],\n * }),\n * ],\n * };\n * ```\n *\n * @example Conditional Menu Items\n * ```ts\n * new ContextMenuPlugin({\n * items: [\n * { id: 'edit', name: 'Edit', visible: (ctx) => ctx.column.editable === true },\n * { id: 'delete', name: 'Delete', disabled: (ctx) => ctx.row.locked === true },\n * ],\n * })\n * ```\n *\n * @see {@link ContextMenuConfig} for configuration options\n * @see {@link ContextMenuItem} for menu item structure\n * @see {@link ContextMenuParams} for action callback parameters\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ContextMenuPlugin extends BaseGridPlugin<ContextMenuConfig> {\n /**\n * Plugin manifest - declares queries used by this plugin.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: QUERY_GET_CONTEXT_MENU_ITEMS,\n description: 'Collects context menu items from other plugins for header right-click menus',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'contextMenu';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ContextMenuConfig> {\n return {\n items: defaultItems,\n };\n }\n\n // #region Internal State\n private isOpen = false;\n private position = { x: 0, y: 0 };\n private params: ContextMenuParams | null = null;\n private menuElement: HTMLElement | null = null;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n this.installGlobalHandlers();\n globalHandlerRefCount++;\n activeInstances.add(this);\n }\n\n /** @internal */\n override detach(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n this.isOpen = false;\n this.params = null;\n activeInstances.delete(this);\n this.uninstallGlobalHandlers();\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Sync selection with the right-clicked row.\n * If the right-clicked row is already selected, keeps the multi-selection.\n * If not, selects only the right-clicked row (standard behavior in file managers / spreadsheets).\n *\n * @returns Sorted array of selected row indices after sync\n */\n private syncSelectionOnContextMenu(rowIndex: number): number[] {\n if (rowIndex < 0) return [];\n\n // Use the query system for loose coupling — no import of SelectionPlugin needed\n const selectionResult = this.grid?.query<number[]>('getSelectedRowIndices');\n const currentSelection = selectionResult?.[0];\n\n // No selection plugin loaded\n if (!currentSelection) return [rowIndex];\n\n if (currentSelection.includes(rowIndex)) {\n // Right-clicked row is already selected — preserve multi-selection\n return currentSelection;\n }\n\n // Right-clicked row is NOT selected — select only this row\n this.grid?.query('selectRows', [rowIndex]);\n return [rowIndex];\n }\n\n /**\n * CSS variables to copy from the grid element to the context menu.\n * Includes both base variables and context-menu specific overrides.\n */\n private static readonly CSS_VARS_TO_COPY = [\n // Base palette (for themes that only set base vars)\n '--tbw-color-panel-bg',\n '--tbw-color-fg',\n '--tbw-color-fg-muted',\n '--tbw-color-border',\n '--tbw-color-row-hover',\n '--tbw-color-shadow',\n '--tbw-color-danger',\n '--tbw-border-radius',\n '--tbw-font-family',\n '--tbw-font-size-sm',\n '--tbw-font-size-xs',\n '--tbw-font-size-2xs',\n '--tbw-spacing-xs',\n '--tbw-icon-size',\n '--tbw-menu-min-width',\n '--tbw-menu-item-padding',\n '--tbw-menu-item-gap',\n // Context menu specific overrides\n '--tbw-context-menu-bg',\n '--tbw-context-menu-fg',\n '--tbw-context-menu-border',\n '--tbw-context-menu-radius',\n '--tbw-context-menu-shadow',\n '--tbw-context-menu-hover',\n '--tbw-context-menu-danger',\n '--tbw-context-menu-muted',\n '--tbw-context-menu-min-width',\n '--tbw-context-menu-font-size',\n '--tbw-context-menu-font-family',\n '--tbw-context-menu-item-padding',\n '--tbw-context-menu-item-gap',\n '--tbw-context-menu-icon-size',\n '--tbw-context-menu-shortcut-size',\n '--tbw-context-menu-arrow-size',\n // Icon variables for context menu icons rendered outside tbw-grid\n '--tbw-icon-submenu-arrow',\n ];\n\n /**\n * Copy CSS custom properties from the grid element to the menu element.\n * This allows the context menu (appended to document.body) to inherit\n * theme variables set on tbw-grid.\n */\n private copyGridStyles(menuElement: HTMLElement): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const computed = getComputedStyle(gridEl);\n const styles: string[] = [];\n\n // Copy color-scheme so light-dark() can resolve in the context menu\n const colorScheme = computed.getPropertyValue('color-scheme').trim();\n if (colorScheme) {\n styles.push(`color-scheme: ${colorScheme}`);\n }\n\n for (const varName of ContextMenuPlugin.CSS_VARS_TO_COPY) {\n const value = computed.getPropertyValue(varName).trim();\n if (value) {\n styles.push(`${varName}: ${value}`);\n }\n }\n\n if (styles.length > 0) {\n // Append to existing inline styles (don't overwrite)\n const existing = menuElement.getAttribute('style') || '';\n menuElement.setAttribute('style', existing + styles.join('; ') + ';');\n }\n }\n\n private installGlobalHandlers(): void {\n // Inject global stylesheet for context menu (once)\n // Only inject if we have valid CSS text (Vite's ?inline import)\n // When importing from source without Vite, the import is a module object, not a string\n if (\n !globalStyleSheet &&\n typeof document !== 'undefined' &&\n typeof contextMenuStyles === 'string' &&\n contextMenuStyles\n ) {\n globalStyleSheet = document.createElement('style');\n globalStyleSheet.id = 'tbw-context-menu-styles';\n globalStyleSheet.textContent = contextMenuStyles;\n document.head.appendChild(globalStyleSheet);\n }\n\n if (!globalAbortController) {\n globalAbortController = new AbortController();\n const signal = globalAbortController.signal;\n\n const closeAllMenus = () => {\n // Route through each plugin instance so per-instance state\n // (`isOpen`) stays consistent. Falls back to\n // a DOM sweep for any orphaned menus (e.g. plugin already detached).\n for (const instance of activeInstances) {\n if (instance.isMenuOpen()) instance.hideMenu();\n }\n document.querySelectorAll('.tbw-context-menu').forEach((menu) => menu.remove());\n };\n\n // Close menu on click outside\n document.addEventListener('click', closeAllMenus, { signal });\n\n // Close on escape\n document.addEventListener(\n 'keydown',\n (e: KeyboardEvent) => {\n if (e.key === 'Escape') closeAllMenus();\n },\n { signal },\n );\n\n // Close on scroll (any scrollable ancestor)\n document.addEventListener('scroll', closeAllMenus, { capture: true, signal });\n }\n }\n\n /**\n * Clean up global handlers when the last instance detaches.\n * Uses reference counting to ensure handlers persist while any grid uses the plugin.\n */\n private uninstallGlobalHandlers(): void {\n globalHandlerRefCount--;\n if (globalHandlerRefCount > 0) return;\n\n // Last instance - abort all global listeners at once\n if (globalAbortController) {\n globalAbortController.abort();\n globalAbortController = null;\n }\n if (globalStyleSheet) {\n globalStyleSheet.remove();\n globalStyleSheet = null;\n }\n }\n\n /**\n * Query all plugins for context menu items via the query system.\n * Each plugin that handles `getContextMenuItems` can return an array of HeaderContextMenuItem.\n */\n private collectPluginItems(params: ContextMenuParams): HeaderContextMenuItem[] {\n if (!this.grid) return [];\n\n const responses = this.grid.query<HeaderContextMenuItem[]>(QUERY_GET_CONTEXT_MENU_ITEMS, params);\n const items: HeaderContextMenuItem[] = [];\n\n for (const response of responses) {\n if (Array.isArray(response)) {\n items.push(...response);\n }\n }\n\n // Sort by order (default 100), then stable by insertion order\n items.sort((a, b) => (a.order ?? 100) - (b.order ?? 100));\n\n // Insert separators between different order groups\n return this.insertGroupSeparators(items);\n }\n\n /**\n * Insert separators between groups of items with different order ranges.\n * Groups are defined by the tens digit (10-19, 20-29, etc.).\n */\n private insertGroupSeparators(items: HeaderContextMenuItem[]): HeaderContextMenuItem[] {\n if (items.length <= 1) return items;\n\n const result: HeaderContextMenuItem[] = [];\n let lastGroup = -1;\n\n for (const item of items) {\n if (item.separator) {\n result.push(item);\n continue;\n }\n const group = Math.floor((item.order ?? 100) / 10);\n if (lastGroup >= 0 && group !== lastGroup) {\n result.push({\n id: `__sep-${lastGroup}-${group}`,\n label: '',\n separator: true,\n action: () => {\n /* noop */\n },\n });\n }\n lastGroup = group;\n result.push(item);\n }\n\n return result;\n }\n\n /**\n * Convert plugin-contributed HeaderContextMenuItems to the internal ContextMenuItem format.\n */\n private convertPluginItems(items: HeaderContextMenuItem[]): ContextMenuItem[] {\n return items.map((item) => ({\n id: item.id,\n name: item.label,\n icon: item.icon,\n shortcut: item.shortcut,\n disabled: item.disabled ?? false,\n action: () => item.action(),\n separator: item.separator,\n cssClass: item.cssClass,\n }));\n }\n // #endregion\n\n // #region Hooks\n\n /**\n * Shared logic to build menu items, create the menu element, and show it.\n * Used by both the contextmenu mouse handler and keyboard triggers.\n *\n * @param params - Context menu parameters\n * @param x - Viewport X coordinate\n * @param y - Viewport Y coordinate\n * @param focusFirst - Whether to focus the first menu item (keyboard-triggered)\n */\n private openMenuAt(params: ContextMenuParams, x: number, y: number, focusFirst = false): void {\n this.params = params;\n this.position = { x, y };\n\n // Collect plugin-contributed items via the query system\n const pluginItems = this.collectPluginItems(params);\n\n // Build configured items\n let items = buildMenuItems(this.config.items ?? defaultItems, params);\n\n // Merge plugin items with configured items\n if (pluginItems.length > 0) {\n const converted = this.convertPluginItems(pluginItems);\n if (items.length > 0 && converted.length > 0) {\n items = [...items, { id: '__plugin-sep', name: '', separator: true }, ...converted];\n } else {\n items = [...items, ...converted];\n }\n }\n\n // Collapse consecutive/leading/trailing separators\n items = collapseSeparators(items);\n\n if (!items.length) return;\n\n // Close any open context menu (including from other grids)\n document.querySelectorAll('.tbw-context-menu').forEach((m) => m.remove());\n this.menuElement = null;\n\n this.menuElement = createMenuElement(\n items,\n params,\n (item) => {\n if (item.action) {\n item.action(params);\n }\n this.hideMenu();\n },\n this.grid?.gridConfig?.icons?.submenuArrow,\n );\n\n // Attach keyboard navigation (arrow keys, Enter, Escape)\n setupMenuKeyboard(this.menuElement, () => this.hideMenu());\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n\n if (focusFirst) {\n focusFirstMenuItem(this.menuElement);\n }\n\n this.emit('context-menu-open', { params, items });\n }\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Use querySelector instead of children[0] because light DOM children\n // (e.g. <tbw-grid-column>) are re-appended before .tbw-grid-root, making\n // children[0] point to a declarative element instead of the data container.\n const container = gridEl.querySelector('.tbw-grid-root');\n if (!container) return;\n\n // Check if handler already attached\n if (container.getAttribute('data-context-menu-bound') === 'true') return;\n container.setAttribute('data-context-menu-bound', 'true');\n\n container.addEventListener('contextmenu', (e: Event) => {\n const event = e as MouseEvent;\n event.preventDefault();\n\n const target = event.target as HTMLElement;\n const cell = target.closest('[data-row][data-col]');\n const header = target.closest('[part~=\"header-cell\"]');\n\n let params: ContextMenuParams;\n\n if (cell) {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n const column = this.visibleColumns[colIndex];\n const row = this.rows[rowIndex];\n\n // Sync selection: if the right-clicked row is not already selected,\n // select it (clearing multi-selection). If it IS selected, keep all.\n const selectedRows = this.syncSelectionOnContextMenu(rowIndex);\n\n params = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event,\n selectedRows,\n };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.visibleColumns[colIndex];\n\n params = {\n row: null,\n rowIndex: -1,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: null,\n isHeader: true,\n event,\n selectedRows: [],\n };\n } else {\n return;\n }\n\n this.openMenuAt(params, event.clientX, event.clientY);\n });\n }\n\n /**\n * Handle keyboard shortcuts to open the context menu.\n * Shift+F10 and the dedicated ContextMenu key open the menu at the focused cell.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // Shift+F10 or the dedicated ContextMenu/Application key\n const isShiftF10 = event.key === 'F10' && event.shiftKey;\n const isContextMenuKey = event.key === 'ContextMenu';\n\n if (!isShiftF10 && !isContextMenuKey) return;\n\n // Prevent the browser's native context menu from appearing\n event.preventDefault();\n\n const grid = this.grid;\n if (!grid) return;\n\n const rowIndex = grid._focusRow;\n const colIndex = grid._focusCol;\n const column = this.visibleColumns[colIndex];\n const row = this.rows[rowIndex];\n\n // Find the focused cell element to position the menu near it\n const gridEl = this.gridElement;\n const cellEl = gridEl?.querySelector<HTMLElement>(`[data-row=\"${rowIndex}\"][data-col=\"${colIndex}\"]`);\n let x = 0;\n let y = 0;\n if (cellEl) {\n const rect = cellEl.getBoundingClientRect();\n x = rect.left + rect.width / 2;\n y = rect.bottom;\n }\n\n const selectedRows = this.syncSelectionOnContextMenu(rowIndex);\n\n const params: ContextMenuParams = {\n row,\n rowIndex,\n column,\n columnIndex: colIndex,\n field: column?.field ?? '',\n value: row?.[column?.field as keyof typeof row] ?? null,\n isHeader: false,\n event: event,\n selectedRows,\n };\n\n this.openMenuAt(params, x, y, true);\n return true;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n *\n * Use this to open the menu from custom UI elements or keyboard shortcuts\n * without requiring a native `contextmenu` event.\n *\n * @param x - Viewport X coordinate (pixels)\n * @param y - Viewport Y coordinate (pixels)\n * @param params - Partial context menu parameters — unspecified fields receive sensible defaults\n *\n * @example\n * ```ts\n * const menu = grid.getPluginByName('context-menu');\n * // Open menu at a button's position with row context\n * const rect = button.getBoundingClientRect();\n * menu.showMenu(rect.left, rect.bottom, {\n * row: selectedRow,\n * rowIndex: 3,\n * column: columns[0],\n * });\n * ```\n */\n showMenu(x: number, y: number, params: Partial<ContextMenuParams>): void {\n const fullParams: ContextMenuParams = {\n row: params.row ?? null,\n rowIndex: params.rowIndex ?? -1,\n column: params.column ?? null,\n columnIndex: params.columnIndex ?? -1,\n field: params.field ?? '',\n value: params.value ?? null,\n isHeader: params.isHeader ?? false,\n event: params.event ?? new MouseEvent('contextmenu'),\n selectedRows: params.selectedRows ?? [],\n };\n\n this.openMenuAt(fullParams, x, y);\n }\n\n /**\n * Hide the context menu if it is currently open.\n *\n * Safe to call even when the menu is already closed.\n */\n hideMenu(): void {\n if (this.menuElement) {\n this.menuElement.remove();\n this.menuElement = null;\n }\n if (this.isOpen) {\n this.isOpen = false;\n }\n }\n\n /**\n * Check if the context menu is currently open.\n *\n * @returns `true` when the menu is visible\n */\n isMenuOpen(): boolean {\n return this.isOpen;\n }\n // #endregion\n\n // Styles are injected globally via installGlobalHandlers() since menu renders in document.body\n}\n"],"names":["buildMenuItems","items","params","filter","item","hidden","isItemDisabled","disabled","createMenuElement","onAction","submenuArrow","menu","document","createElement","className","setAttribute","hasAnyIcon","some","separator","icon","appendChild","menuItem","cssClass","classList","add","id","innerHTML","sanitizeHTML","label","textContent","name","shortcut","Array","isArray","forEach","key","i","createTextNode","kbd","subMenu","length","arrow","dataset","toIconAttr","HTMLElement","cloneNode","addEventListener","querySelector","style","position","left","top","remove","action","e","stopPropagation","QUERY_GET_CONTEXT_MENU_ITEMS","globalAbortController","globalStyleSheet","globalHandlerRefCount","activeInstances","Set","defaultItems","grid","query","ContextMenuPlugin","BaseGridPlugin","static","queries","type","description","defaultConfig","isOpen","x","y","menuElement","attach","super","this","installGlobalHandlers","detach","delete","uninstallGlobalHandlers","syncSelectionOnContextMenu","rowIndex","selectionResult","currentSelection","includes","copyGridStyles","gridEl","gridElement","computed","getComputedStyle","styles","colorScheme","getPropertyValue","trim","push","varName","CSS_VARS_TO_COPY","value","existing","getAttribute","join","contextMenuStyles","head","AbortController","signal","closeAllMenus","instance","isMenuOpen","hideMenu","querySelectorAll","capture","abort","collectPluginItems","responses","response","sort","a","b","order","insertGroupSeparators","result","lastGroup","group","Math","floor","convertPluginItems","map","openMenuAt","focusFirst","pluginItems","config","converted","onClose","pop","collapseSeparators","m","gridConfig","icons","from","current","activeElement","idx","indexOf","preventDefault","focus","click","body","visibility","zIndex","menuRect","getBoundingClientRect","viewportWidth","window","innerWidth","viewportHeight","innerHeight","width","height","max","positionMenu","first","focusFirstMenuItem","emit","afterRender","container","event","target","cell","closest","header","parseInt","colIndex","column","visibleColumns","row","rows","selectedRows","columnIndex","field","isHeader","clientX","clientY","onKeyDown","isShiftF10","shiftKey","isContextMenuKey","_focusRow","_focusCol","cellEl","rect","bottom","showMenu","fullParams","MouseEvent"],"mappings":"0mEAkBO,SAASA,EACdC,EACAC,GAIA,OAFmC,mBAAVD,EAAuBA,EAAMC,GAAUD,GAE/CE,OAAQC,IACH,IAAhBA,EAAKC,SACkB,mBAAhBD,EAAKC,SAAyBD,EAAKC,OAAOH,IAGzD,CA+BO,SAASI,EAAeF,EAAuBF,GACpD,OAAsB,IAAlBE,EAAKG,UACoB,mBAAlBH,EAAKG,UAAgCH,EAAKG,SAASL,EAEhE,CAWO,SAASM,EACdP,EACAC,EACAO,EACAC,GAEA,MAAMC,EAAOC,SAASC,cAAc,OACpCF,EAAKG,UAAY,mBACjBH,EAAKI,aAAa,OAAQ,QAG1B,MAAMC,EAAaf,EAAMgB,KAAMb,IAAUA,EAAKc,WAAad,EAAKe,MAEhE,IAAA,MAAWf,KAAQH,EAAO,CACxB,GA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MAAON,GAAQM,OAAS,GACxBjF,MAAO6E,IAAMF,GAAQM,QAA8B,KACnDC,UAAU,EACVd,QACAW,gBAIF,OADArG,KAAKoD,WAAWhI,EAAQuE,EAAGC,GAAG,IACvB,CACT,CA2BA,QAAAwH,CAASzH,EAAWC,EAAWxE,GAC7B,MAAMiM,EAAgC,CACpClB,IAAK/K,EAAO+K,KAAO,KACnB7F,SAAUlF,EAAOkF,WAAY,EAC7B2F,OAAQ7K,EAAO6K,QAAU,KACzBK,YAAalL,EAAOkL,cAAe,EACnCC,MAAOnL,EAAOmL,OAAS,GACvBjF,MAAOlG,EAAOkG,OAAS,KACvBkF,SAAUpL,EAAOoL,WAAY,EAC7Bd,MAAOtK,EAAOsK,OAAS,IAAI4B,WAAW,eACtCjB,aAAcjL,EAAOiL,cAAgB,IAGvCrG,KAAKoD,WAAWiE,EAAY1H,EAAGC,EACjC,CAOA,QAAAqC,GACMjC,KAAKH,cACPG,KAAKH,YAAYvB,SACjB0B,KAAKH,YAAc,MAEjBG,KAAKN,SACPM,KAAKN,QAAS,EAElB,CAOA,UAAAsC,GACE,OAAOhC,KAAKN,MACd"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/internal/aggregators"),require("../../core/internal/aria"),require("../../core/internal/loading"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/aggregators","../../core/internal/aria","../../core/internal/loading","../../core/plugin/base-plugin","../../core/plugin/expander-column"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_groupingRows={},e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,r,o,n,i,s){"use strict";function a({rows:e,config:t,expanded:r,initialExpanded:o,groupSortDirections:n}){const i=t.groupOn;if("function"!=typeof i)return[];const s={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=i(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let r=s;t.forEach((t,o)=>{const n=null==t?"∅":String(t),i="__root__"===r.key?n:r.key+"||"+n;let s=r.children.get(n);s||(s={key:i,value:t,depth:o,rows:[],children:new Map,parent:r},r.children.set(n,s)),s.rows.push(e),r=s})}),1===s.children.size&&s.children.has("__ungrouped__")){if(s.children.get("__ungrouped__").rows.length===e.length)return[]}const a=new Map;for(let g=0;g<e.length;g++)a.set(e[g],g);const d=new Set([...r,...o??[]]),p=e=>{const t=[...e.children.values()],r=e===s?0:e.depth+1,o=n?.get(r)??1;return t.sort((e,t)=>{const r=e.value,n=t.value;return null==r&&null==n?0:null==r?o:null==n?-o:r>n?o:r<n?-o:0}),t},u=[],l=e=>{if(e===s){for(const t of p(e))l(t);return}const t=d.has(e.key);if(u.push({kind:"group",key:e.key,value:e.value,depth:e.depth,rows:e.rows,expanded:t}),t)if(e.children.size)for(const r of p(e))l(r);else e.rows.forEach(e=>u.push({kind:"data",row:e,rowIndex:a.get(e)??-1}))};return l(s),u}function d(e,t){if(!0===e)return new Set(t);if(!1===e||null==e)return new Set;if("number"==typeof e){const r=t[e];return r?new Set([r]):new Set}return"string"==typeof e?new Set([e]):Array.isArray(e)?new Set(e):new Set}function p({groups:e,expanded:t,groupRows:r,loadingGroups:o,parentPath:n=[]}){const i=[],s=n.length;for(const a of e){const e=[...n,a.key],d=t.has(a.key),u=r.get(a.key)??[],l=o.has(a.key);if(i.push({kind:"group",key:a.key,value:a.value,depth:s,rows:u,expanded:d}),d)if(a.children?.length){const n=p({groups:a.children,expanded:t,groupRows:r,loadingGroups:o,parentPath:e});i.push(...n)}else l?i.push({kind:"data",row:{__loading:!0,__groupKey:a.key},rowIndex:-1}):u.forEach((e,t)=>{i.push({kind:"data",row:e,rowIndex:t})})}return i}function u(e,t,r=[]){for(const o of e){const e=[...r,o.key];if(o.key===t)return e;if(o.children?.length){const r=u(o.children,t,e);if(r.length>0)return r}}return[]}class l extends i.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10,onHeaderClick:-1},incompatibleWith:[{name:"tree",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin creates its own aggregated row and column structure. Row grouping cannot be applied on top of pivot-generated rows."}],events:[{type:"group-toggle",description:"Emitted when groups are expanded/collapsed. Broadcast to both DOM consumers and plugin bus."},{type:"group-expand",description:"Emitted when a pre-defined group is expanded."},{type:"group-collapse",description:"Emitted when a pre-defined group is collapsed."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"},{type:"grouping:get-grouped-fields",description:"Returns the column field names that match group depth levels (string[])"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level group indices for ServerSide pagination."}],configRules:[{id:"groupingRows/accordion-defaultExpanded",severity:"warn",message:'"accordion: true" and "defaultExpanded" (non-false) are used together.\n → In accordion mode, only one group can be open at a time.\n → Using defaultExpanded with multiple groups will collapse to one on first toggle.\n → Consider using "defaultExpanded: false" or a single group key/index with accordion mode.',check:e=>!0===e.accordion&&!1!==e.defaultExpanded&&void 0!==e.defaultExpanded&&!("number"==typeof e.defaultExpanded)&&!("string"==typeof e.defaultExpanded)&&(!0===e.defaultExpanded||Array.isArray(e.defaultExpanded)&&e.defaultExpanded.length>1)}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated group sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded grouped data"}];name="groupingRows";styles="@layer tbw-plugins{.group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}.group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem)}@media(hover:hover){.group-row:hover{background:var(--tbw-grouping-rows-bg-hover, var(--tbw-color-row-hover))}}.group-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toggle-size, 1.25rem);height:var(--tbw-toggle-size, 1.25rem);margin-right:.25rem;background:none;border:0;font:inherit}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:var(--tbw-border-radius, .125rem)}.group-label{display:inline-flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:var(--tbw-font-size-xs, .85em);font-weight:400}.group-aggregates{display:inline-flex;align-items:center;gap:var(--tbw-spacing-lg, 1rem);margin-left:var(--tbw-spacing-lg, 1rem);font-weight:400;font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-grouping-rows-aggregate-color, var(--tbw-color-fg-muted))}.group-aggregate{white-space:nowrap}.group-row{padding-left:calc(var(--tbw-group-depth, 0) * var(--tbw-group-indent-width, 1.25em))}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide",accordion:!1}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;hasAppliedDefaultExpanded=!1;preDefinedGroups=[];groupRowsMap=new Map;loadingGroups=new Set;groupedFields=[];userGroupSortDirections=new Map;get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){this.expandedKeys.clear(),this.flattenedRows=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.hasAppliedDefaultExpanded=!1,this.preDefinedGroups=[],this.groupRowsMap.clear(),this.loadingGroups.clear(),this.groupedFields=[],this.userGroupSortDirections.clear()}getRowHeight(e,t){if(null!=this.config.groupRowHeight)return!0===e.__isGroupRow?this.config.groupRowHeight:void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context;if(!0===t?.__isGroupRow)return!1}if("grouping:get-grouped-fields"===e.type)return[...this.groupedFields];if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:r}=e.context;if(0===this.flattenedRows.length)return;if(0===this.preDefinedGroups.length&&!Array.isArray(this.config.groups))return;const o=this.getActiveGroups();return{startNode:this.getTopLevelGroupIndex(t),endNode:this.getTopLevelGroupIndex(r)+1,totalLoadedNodes:o.length}}}getTopLevelGroupIndex(e){let t=-1;const r=Math.min(e,this.flattenedRows.length-1);for(let o=0;o<=r;o++){const e=this.flattenedRows[o];"group"===e.kind&&0===e.depth&&t++}return Math.max(0,t)}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0,this.preDefinedGroups=t.rows,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender())}),this.on("datasource:children",e=>{const t=e;if("grouping-rows"!==t.context?.source)return;t.claimed=!0;const r=t.context.groupKey;r&&(this.groupRowsMap.set(r,t.rows),this.loadingGroups.delete(r),this.requestRender())})}onHeaderClick(e){const t=this.groupedFields.indexOf(e.field);if(-1===t)return;if(!e.column.sortable)return;const r=t,o=this.userGroupSortDirections.get(r)??1;return this.userGroupSortDirections.set(r,1===o?-1:1),this.requestRender(),!0}resolveGroupSortDirections(e){const t=this.config;if("function"!=typeof t.groupOn||0===e.length)return void(this.groupedFields=[]);const r=this.columns.map(e=>e.field),o=function(e,t,r){const o=new Map;if(0===e.length)return o;const n=e[0];let i=t(n);if(null==i||!1===i)return o;Array.isArray(i)||(i=[i]);for(let s=0;s<i.length;s++){const e=i[s];for(const t of r)if(n[t]===e){o.set(s,t);break}}return o}([...e],t.groupOn,r);if(this.groupedFields=[...o.values()],0===o.size)return;const n=new Map(this.userGroupSortDirections);if(n.size<o.size){const e=new Map,t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0){const r=t[0];if(Array.isArray(r))for(const t of r)e.set(t.field,"desc"===t.direction?-1:1)}if(0===e.size){const t=this.grid;t._sortState&&e.set(t._sortState.field,t._sortState.direction)}for(const[r,i]of o)if(!n.has(r)){const t=e.get(i);void 0!==t&&n.set(r,t)}}return n.size>0?n:void 0}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping||Array.isArray(t?.groups)}processRows(e){if(this.preDefinedGroups.length>0||Array.isArray(this.config.groups))return this.preDefinedGroups.length>0||Array.isArray(this.config.groups)&&this.config.groups.length>0?this.processPreDefinedGroups():(this.isActive=!1,this.flattenedRows=[],[]);const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const r=this.resolveGroupSortDirections(e),o=a({rows:[...e],config:t,expanded:new Set,groupSortDirections:r});if(0===o.length)return this.isActive=!1,this.flattenedRows=[],[...e];let n;if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==t.defaultExpanded){const e=function(e){return e.filter(e=>"group"===e.kind).map(e=>e.key)}(o);n=d(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const i=a({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n,groupSortDirections:r});this.isActive=!0,this.flattenedRows=i,this.keysToAnimate.clear();const s=new Set;return i.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;s.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=s,i.map(e=>{return"group"===e.kind?{__isGroupRow:!0,__groupKey:e.key,__groupValue:e.value,__groupDepth:e.depth,__groupRows:e.rows,__groupExpanded:e.expanded,__groupRowCount:(t=e,"group"!==t.kind?0:t.rows.length),__rowCacheKey:`group:${e.key}`}:e.row;var t})}onCellClick(e){const r=e.row;if(r?.__isGroupRow){const o=e.originalEvent.target;if(o?.closest(`.${t.GridClasses.GROUP_TOGGLE}`))return this.toggle(r.__groupKey),!0}}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,r=this.rows[t];return r?.__isGroupRow?(e.preventDefault(),this.toggle(r.__groupKey),this.requestRenderWithFocus(),!0):void 0}renderRow(e,t,r){if(!0===e?.__loading&&e?.__groupKey){t.className="data-grid-row",t.__isCustomRow=!0,t.innerHTML="";const e=document.createElement("div");return e.className="cell",e.style.gridColumn="1 / -1",e.setAttribute("role","gridcell"),e.textContent=" ",t.appendChild(e),n.setRowLoadingState(t,!0),!0}if(!e?.__isGroupRow)return!1;const o=this.config;if(o.groupRowRenderer){const r=()=>{this.toggle(e.__groupKey)},n=o.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:r});if(n)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),"string"==typeof n?t.innerHTML=n:(t.innerHTML="",t.appendChild(n)),!0}const i=()=>{this.toggle(e.__groupKey)};t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),t.setAttribute("role","row"),t.setAttribute("aria-expanded",String(e.__groupExpanded)),t.style.setProperty("--tbw-group-depth",String(e.__groupDepth||0)),void 0!==o.indentWidth&&t.style.setProperty("--tbw-group-indent-width",`${o.indentWidth}px`),t.style.height="",t.innerHTML="";return!1!==o.fullWidth?this.renderFullWidthGroupRow(e,t,i):this.renderPerColumnGroupRow(e,t,i),!0}afterRender(){const e=this.animationStyle;if(!1===e||0===this.keysToAnimate.size)return;const t=this.gridElement?.querySelector(".rows");if(!t)return;const r="fade"===e?"tbw-group-fade-in":"tbw-group-slide-in";for(const o of t.querySelectorAll(".data-grid-row:not(.group-row)")){const e=o.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,n=this.flattenedRows[t],i="data"===n?.kind?`data-${t}`:void 0;i&&this.keysToAnimate.has(i)&&(o.classList.add(r),o.addEventListener("animationend",()=>o.classList.remove(r),{once:!0}))}this.keysToAnimate.clear()}processPreDefinedGroups(){const e=this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[];if(0===e.length)return this.isActive=!1,this.flattenedRows=[],[];if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==this.config.defaultExpanded){const t=this.collectGroupKeys(e),r=d(this.config.defaultExpanded??!1,t);r.size>0&&(this.expandedKeys=new Set(r),this.hasAppliedDefaultExpanded=!0)}const t=p({groups:e,expanded:this.expandedKeys,groupRows:this.groupRowsMap,loadingGroups:this.loadingGroups});this.isActive=!0,this.flattenedRows=t,this.keysToAnimate.clear();const r=new Set;return t.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;r.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=r,t.map(t=>{if("group"===t.kind){const r=this.findGroupDefinition(e,t.key),o=r?.rowCount??t.rows.length;return{__isGroupRow:!0,__groupKey:t.key,__groupValue:t.value,__groupDepth:t.depth,__groupRows:t.rows,__groupExpanded:t.expanded,__groupRowCount:o,__rowCacheKey:`group:${t.key}`}}return t.row})}collectGroupKeys(e){const t=[];for(const r of e)t.push(r.key),r.children?.length&&t.push(...this.collectGroupKeys(r.children));return t}getActiveGroups(){return this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[]}findGroupDefinition(e,t){for(const r of e){if(r.key===t)return r;if(r.children?.length){const e=this.findGroupDefinition(r.children,t);if(e)return e}}}createToggleButton(e,r){const o=document.createElement("button");return o.type="button",o.className=`${t.GridClasses.GROUP_TOGGLE}${e?` ${t.GridClasses.EXPANDED}`:""}`,o.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(o,e?"collapse":"expand"),o.addEventListener("click",e=>{e.stopPropagation(),r()}),o}getGroupLabelText(e,t,r){const o=this.config;return o.formatLabel?o.formatLabel(e,t,r):String(e)}renderFullWidthGroupRow(e,o,n){const i=this.config,s=i.aggregators??{},a=e.__groupRows??[],d=document.createElement("div");d.className="cell group-full",d.style.gridColumn="1 / -1",d.setAttribute("role","gridcell"),d.setAttribute("data-col","0"),d.appendChild(this.createToggleButton(e.__groupExpanded,n));const p=document.createElement("span");if(p.className=t.GridClasses.GROUP_LABEL,p.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey),d.appendChild(p),!1!==i.showRowCount){const r=document.createElement("span");r.className=t.GridClasses.GROUP_COUNT,r.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,d.appendChild(r)}const u=Object.entries(s);if(u.length>0){const e=document.createElement("span");e.className="group-aggregates";for(const[t,o]of u){const n=this.columns.find(e=>e.field===t),i=r.aggregatorRegistry.run(o,a,t,n);if(null!=i){const r=document.createElement("span");r.className="group-aggregate",r.setAttribute("data-field",t);const o=n?.header??t;r.textContent=`${o}: ${i}`,e.appendChild(r)}}e.children.length>0&&d.appendChild(e)}o.appendChild(d)}renderPerColumnGroupRow(e,o,n){const i=this.config,a=i.aggregators??{},d=this.columns,p=e.__groupRows??[],u=this.gridElement?.querySelector(".body"),l=u?.style.gridTemplateColumns||"";l&&(o.style.display="grid",o.style.gridTemplateColumns=l);let g=!1;d.forEach((d,u)=>{const l=document.createElement("div");if(l.className="cell group-cell",l.setAttribute("data-col",String(u)),l.setAttribute("role","gridcell"),s.isExpanderColumn(d))return l.setAttribute("data-field",d.field),void o.appendChild(l);if(g){const e=a[d.field];if(e){const t=r.aggregatorRegistry.run(e,p,d.field,d);l.textContent=null!=t?String(t):""}else l.textContent=""}else{g=!0,l.appendChild(this.createToggleButton(e.__groupExpanded,n));const o=document.createElement("span"),s=a[d.field];if(s){const t=r.aggregatorRegistry.run(s,p,d.field,d);o.textContent=String(null!=t?t:e.__groupValue)}else o.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey);if(l.appendChild(o),!1!==i.showRowCount){const e=document.createElement("span");e.className=t.GridClasses.GROUP_COUNT,e.textContent=` (${p.length})`,l.appendChild(e)}}o.appendChild(l)})}expandAll(){this.expandedKeys=function(e){const t=new Set;for(const r of e)"group"===r.kind&&t.add(r.key);return t}(this.flattenedRows),this.emitPluginEvent("group-toggle",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("group-toggle",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}toggle(e){const t=!this.expandedKeys.has(e),r=this.config,n=this.flattenedRows.find(t=>"group"===t.kind&&t.key===e);if(r.accordion&&t&&n){const t=new Set;for(const r of this.expandedKeys)if(e.startsWith(r+"||")||r.startsWith(e+"||"))e.startsWith(r+"||")&&t.add(r);else{const e=this.flattenedRows.find(e=>"group"===e.kind&&e.key===r);e&&e.depth!==n.depth&&t.add(r)}t.add(e),this.expandedKeys=t}else this.expandedKeys=function(e,t){const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}(this.expandedKeys,e);this.broadcast("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:n?.value,depth:n?.depth??0,expandedKeys:[...this.expandedKeys]});const i=this.getActiveGroups();if(i.length>0){const r=u(i,e);if(t){if(this.emit("group-expand",{groupKey:e,groupPath:r}),!this.groupRowsMap.has(e)){const t=this.findGroupDefinition(i,e);t&&(this.loadingGroups.add(e),this.grid?.query?.("datasource:fetch-children",{context:{source:"grouping-rows",groupKey:e,group:t,groupPath:r}}))}}else this.emit("group-collapse",{groupKey:e,groupPath:r})}const s=this.expandedKeys.has(e),a=null!=n?.value?String(n.value):e;if(s){const e=n?.rows?.length??0;o.announce(this.gridElement,o.getA11yMessage(this.gridElement,"groupExpanded",a,e))}else o.announce(this.gridElement,o.getA11yMessage(this.gridElement,"groupCollapsed",a));this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(e=>"group"===e.kind);return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}setGroups(e){this.preDefinedGroups=e,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.expandedKeys.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender()}getGroups(){return this.preDefinedGroups.length>0?[...this.preDefinedGroups]:Array.isArray(this.config.groups)?[...this.config.groups]:[]}setGroupRows(e,t){this.groupRowsMap.set(e,t),this.loadingGroups.delete(e),this.requestRender()}setGroupLoading(e,t){t?this.loadingGroups.add(e):this.loadingGroups.delete(e),this.requestRender()}clearGroupRows(e){null!=e?this.groupRowsMap.delete(e):this.groupRowsMap.clear(),this.requestRender()}}e.GroupingRowsPlugin=l,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/internal/aggregators"),require("../../core/internal/aria"),require("../../core/internal/loading"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/aggregators","../../core/internal/aria","../../core/internal/loading","../../core/plugin/base-plugin","../../core/plugin/expander-column"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_groupingRows={},e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,r,o,n,s,i){"use strict";function a({rows:e,config:t,expanded:r,initialExpanded:o,groupSortDirections:n}){const s=t.groupOn;if("function"!=typeof s)return[];const i={key:"__root__",value:null,depth:-1,rows:[],children:new Map};if(e.forEach(e=>{let t=s(e);null==t||!1===t?t=["__ungrouped__"]:Array.isArray(t)||(t=[t]);let r=i;t.forEach((t,o)=>{const n=null==t?"∅":String(t),s="__root__"===r.key?n:r.key+"||"+n;let i=r.children.get(n);i||(i={key:s,value:t,depth:o,rows:[],children:new Map,parent:r},r.children.set(n,i)),i.rows.push(e),r=i})}),1===i.children.size&&i.children.has("__ungrouped__")){if(i.children.get("__ungrouped__").rows.length===e.length)return[]}const a=new Map;for(let g=0;g<e.length;g++)a.set(e[g],g);const d=new Set([...r,...o??[]]),p=e=>{const t=[...e.children.values()],r=e===i?0:e.depth+1,o=n?.get(r)??1;return t.sort((e,t)=>{const r=e.value,n=t.value;return null==r&&null==n?0:null==r?o:null==n?-o:r>n?o:r<n?-o:0}),t},u=[],l=e=>{if(e===i){for(const t of p(e))l(t);return}const t=d.has(e.key);if(u.push({kind:"group",key:e.key,value:e.value,depth:e.depth,rows:e.rows,expanded:t}),t)if(e.children.size)for(const r of p(e))l(r);else e.rows.forEach(e=>u.push({kind:"data",row:e,rowIndex:a.get(e)??-1}))};return l(i),u}function d(e,t){if(!0===e)return new Set(t);if(!1===e||null==e)return new Set;if("number"==typeof e){const r=t[e];return r?new Set([r]):new Set}return"string"==typeof e?new Set([e]):Array.isArray(e)?new Set(e):new Set}function p({groups:e,expanded:t,groupRows:r,loadingGroups:o,parentPath:n=[]}){const s=[],i=n.length;for(const a of e){const e=[...n,a.key],d=t.has(a.key),u=r.get(a.key)??[],l=o.has(a.key);if(s.push({kind:"group",key:a.key,value:a.value,depth:i,rows:u,expanded:d}),d)if(a.children?.length){const n=p({groups:a.children,expanded:t,groupRows:r,loadingGroups:o,parentPath:e});s.push(...n)}else l?s.push({kind:"data",row:{__loading:!0,__groupKey:a.key},rowIndex:-1}):u.forEach((e,t)=>{s.push({kind:"data",row:e,rowIndex:t})})}return s}function u(e,t,r=[]){for(const o of e){const e=[...r,o.key];if(o.key===t)return e;if(o.children?.length){const r=u(o.children,t,e);if(r.length>0)return r}}return[]}class l extends s.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10,onHeaderClick:-1},incompatibleWith:[{name:"tree",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin creates its own aggregated row and column structure. Row grouping cannot be applied on top of pivot-generated rows."}],events:[{type:"group-toggle",description:"Emitted when groups are expanded/collapsed. Broadcast to both DOM consumers and plugin bus."},{type:"group-expand",description:"Emitted when a pre-defined group is expanded."},{type:"group-collapse",description:"Emitted when a pre-defined group is collapsed."}],queries:[{type:"canMoveRow",description:"Returns false for group header rows (cannot be reordered)"},{type:"grouping:get-grouped-fields",description:"Returns the column field names that match group depth levels (string[])"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level group indices for ServerSide pagination."}],configRules:[{id:"groupingRows/accordion-defaultExpanded",severity:"warn",message:'"accordion: true" and "defaultExpanded" (non-false) are used together.\n → In accordion mode, only one group can be open at a time.\n → Using defaultExpanded with multiple groups will collapse to one on first toggle.\n → Consider using "defaultExpanded: false" or a single group key/index with accordion mode.',check:e=>!0===e.accordion&&!1!==e.defaultExpanded&&void 0!==e.defaultExpanded&&!("number"==typeof e.defaultExpanded)&&!("string"==typeof e.defaultExpanded)&&(!0===e.defaultExpanded||Array.isArray(e.defaultExpanded)&&e.defaultExpanded.length>1)}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated group sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded grouped data"}];name="groupingRows";styles="@layer tbw-plugins{.group-row{display:grid;grid-template-columns:var(--tbw-column-template);background:var(--tbw-grouping-rows-bg, var(--tbw-color-panel-bg));font-weight:500;border-bottom:var(--tbw-row-divider);min-height:var(--tbw-row-height)}.group-row .cell{display:flex;align-items:center;padding:var(--tbw-cell-padding, .125rem .5rem)}@media(hover:hover){.group-row:hover{background:var(--tbw-grouping-rows-bg-hover, var(--tbw-color-row-hover))}}.group-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-toggle-size, 1.25rem);height:var(--tbw-toggle-size, 1.25rem);margin-right:.25rem;background:none;border:0;font:inherit}.group-toggle:hover{background:var(--tbw-grouping-rows-toggle-hover, var(--tbw-color-row-hover));border-radius:var(--tbw-border-radius, .125rem)}.group-label{display:inline-flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.group-count{color:var(--tbw-grouping-rows-count-color, var(--tbw-color-fg-muted));font-size:var(--tbw-font-size-xs, .85em);font-weight:400}.group-aggregates{display:inline-flex;align-items:center;gap:var(--tbw-spacing-lg, 1rem);margin-left:var(--tbw-spacing-lg, 1rem);font-weight:400;font-size:var(--tbw-font-size-sm, .875em);color:var(--tbw-grouping-rows-aggregate-color, var(--tbw-color-fg-muted))}.group-aggregate{white-space:nowrap}.group-row{padding-left:calc(var(--tbw-group-depth, 0) * var(--tbw-group-indent-width, 1.25em))}.data-grid-row.tbw-group-slide-in{animation:tbw-group-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}.data-grid-row.tbw-group-fade-in{animation:tbw-group-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-group-fade-in{0%{opacity:0}to{opacity:1}}}";get defaultConfig(){return{defaultExpanded:!1,showRowCount:!0,indentWidth:20,aggregators:{},animation:"slide",accordion:!1}}expandedKeys=new Set;flattenedRows=[];isActive=!1;previousVisibleKeys=new Set;keysToAnimate=new Set;hasAppliedDefaultExpanded=!1;preDefinedGroups=[];groupRowsMap=new Map;loadingGroups=new Set;groupedFields=[];userGroupSortDirections=new Map;flatMeta=[];get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detach(){const e=this.gridElement?.querySelector(".rows-body");e?.setAttribute("role","grid"),this.expandedKeys.clear(),this.flattenedRows=[],this.flatMeta=[],this.isActive=!1,this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.hasAppliedDefaultExpanded=!1,this.preDefinedGroups=[],this.groupRowsMap.clear(),this.loadingGroups.clear(),this.groupedFields=[],this.userGroupSortDirections.clear()}getRowHeight(e,t){if(null!=this.config.groupRowHeight)return!0===e.__isGroupRow?this.config.groupRowHeight:void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context;if(!0===t?.__isGroupRow)return!1}if("grouping:get-grouped-fields"===e.type)return[...this.groupedFields];if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:r}=e.context;if(0===this.flattenedRows.length)return;if(0===this.preDefinedGroups.length&&!Array.isArray(this.config.groups))return;const o=this.getActiveGroups();return{startNode:this.getTopLevelGroupIndex(t),endNode:this.getTopLevelGroupIndex(r)+1,totalLoadedNodes:o.length}}}getTopLevelGroupIndex(e){let t=-1;const r=Math.min(e,this.flattenedRows.length-1);for(let o=0;o<=r;o++){const e=this.flattenedRows[o];"group"===e.kind&&0===e.depth&&t++}return Math.max(0,t)}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0,this.preDefinedGroups=t.rows,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender())}),this.on("datasource:children",e=>{const t=e;if("grouping-rows"!==t.context?.source)return;t.claimed=!0;const r=t.context.groupKey;r&&(this.groupRowsMap.set(r,t.rows),this.loadingGroups.delete(r),this.requestRender())})}onHeaderClick(e){const t=this.groupedFields.indexOf(e.field);if(-1===t)return;if(!e.column.sortable)return;const r=t,o=this.userGroupSortDirections.get(r)??1;return this.userGroupSortDirections.set(r,1===o?-1:1),this.requestRender(),!0}resolveGroupSortDirections(e){const t=this.config;if("function"!=typeof t.groupOn||0===e.length)return void(this.groupedFields=[]);const r=this.columns.map(e=>e.field),o=function(e,t,r){const o=new Map;if(0===e.length)return o;const n=e[0];let s=t(n);if(null==s||!1===s)return o;Array.isArray(s)||(s=[s]);for(let i=0;i<s.length;i++){const e=s[i];for(const t of r)if(n[t]===e){o.set(i,t);break}}return o}([...e],t.groupOn,r);if(this.groupedFields=[...o.values()],0===o.size)return;const n=new Map(this.userGroupSortDirections);if(n.size<o.size){const e=new Map,t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0){const r=t[0];if(Array.isArray(r))for(const t of r)e.set(t.field,"desc"===t.direction?-1:1)}if(0===e.size){const t=this.grid;t._sortState&&e.set(t._sortState.field,t._sortState.direction)}for(const[r,s]of o)if(!n.has(r)){const t=e.get(s);void 0!==t&&n.set(r,t)}}return n.size>0?n:void 0}static detect(e,t){return"function"==typeof t?.groupOn||"boolean"==typeof t?.enableRowGrouping||Array.isArray(t?.groups)}processRows(e){if(this.preDefinedGroups.length>0||Array.isArray(this.config.groups))return this.preDefinedGroups.length>0||Array.isArray(this.config.groups)&&this.config.groups.length>0?this.processPreDefinedGroups():(this.isActive=!1,this.flattenedRows=[],[]);const t=this.config;if("function"!=typeof t.groupOn)return this.isActive=!1,this.flattenedRows=[],[...e];const r=this.resolveGroupSortDirections(e),o=a({rows:[...e],config:t,expanded:new Set,groupSortDirections:r});if(0===o.length)return this.isActive=!1,this.flattenedRows=[],[...e];let n;if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==t.defaultExpanded){const e=function(e){return e.filter(e=>"group"===e.kind).map(e=>e.key)}(o);n=d(t.defaultExpanded??!1,e),n.size>0&&(this.expandedKeys=new Set(n),this.hasAppliedDefaultExpanded=!0)}const s=a({rows:[...e],config:t,expanded:this.expandedKeys,initialExpanded:n,groupSortDirections:r});this.isActive=!0,this.flattenedRows=s,this.computeFlatMeta(),this.keysToAnimate.clear();const i=new Set;return s.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;i.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=i,s.map(e=>{return"group"===e.kind?{__isGroupRow:!0,__groupKey:e.key,__groupValue:e.value,__groupDepth:e.depth,__groupRows:e.rows,__groupExpanded:e.expanded,__groupRowCount:(t=e,"group"!==t.kind?0:t.rows.length),__rowCacheKey:`group:${e.key}`}:e.row;var t})}onCellClick(e){const r=e.row;if(r?.__isGroupRow){const o=e.originalEvent.target;if(o?.closest(`.${t.GridClasses.GROUP_TOGGLE}`))return this.toggle(r.__groupKey),!0}}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,r=this.rows[t];return r?.__isGroupRow?(e.preventDefault(),this.toggle(r.__groupKey),this.requestRenderWithFocus(),!0):void 0}renderRow(e,t,r){if(!0===e?.__loading&&e?.__groupKey){t.className="data-grid-row",t.__isCustomRow=!0,t.innerHTML="";const e=document.createElement("div");return e.className="cell",e.style.gridColumn="1 / -1",e.setAttribute("role","gridcell"),e.textContent=" ",t.appendChild(e),n.setRowLoadingState(t,!0),!0}if(!e?.__isGroupRow)return!1;const o=this.config;if(o.groupRowRenderer){const r=()=>{this.toggle(e.__groupKey)},n=o.groupRowRenderer({key:e.__groupKey,value:e.__groupValue,depth:e.__groupDepth,rows:e.__groupRows,expanded:e.__groupExpanded,toggleExpand:r});if(n)return t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),"string"==typeof n?t.innerHTML=n:(t.innerHTML="",t.appendChild(n)),!0}const s=()=>{this.toggle(e.__groupKey)};t.className="data-grid-row group-row",t.__isCustomRow=!0,t.setAttribute("data-group-depth",String(e.__groupDepth)),t.setAttribute("role","row"),t.setAttribute("aria-expanded",String(e.__groupExpanded));const i=this.flatMeta[r];i&&(t.setAttribute("aria-level",String(i.level)),t.setAttribute("aria-setsize",String(i.setSize)),t.setAttribute("aria-posinset",String(i.posInSet))),t.style.setProperty("--tbw-group-depth",String(e.__groupDepth||0)),void 0!==o.indentWidth&&t.style.setProperty("--tbw-group-indent-width",`${o.indentWidth}px`),t.style.height="",t.innerHTML="";return!1!==o.fullWidth?this.renderFullWidthGroupRow(e,t,s):this.renderPerColumnGroupRow(e,t,s),!0}afterRender(){const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.gridElement?.querySelector(".rows-body");t&&"treegrid"!==t.getAttribute("role")&&t.setAttribute("role","treegrid");for(const n of e.querySelectorAll(".data-grid-row:not(.group-row)")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flatMeta[t];r&&(n.setAttribute("aria-level",String(r.level)),n.setAttribute("aria-setsize",String(r.setSize)),n.setAttribute("aria-posinset",String(r.posInSet)))}const r=this.animationStyle;if(!1===r||0===this.keysToAnimate.size)return;const o="fade"===r?"tbw-group-fade-in":"tbw-group-slide-in";for(const n of e.querySelectorAll(".data-grid-row:not(.group-row)")){const e=n.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t],s="data"===r?.kind?`data-${t}`:void 0;s&&this.keysToAnimate.has(s)&&(n.classList.add(o),n.addEventListener("animationend",()=>n.classList.remove(o),{once:!0}))}this.keysToAnimate.clear()}computeFlatMeta(){const e=this.flattenedRows,t=new Array(e.length),r=new Map,o=new Map;let n=null,s=0;for(const p of e)if("group"===p.kind){n&&o.set(n.key,s),n=p,s=0;const e=`${p.key.split("||").slice(0,-1).join("||")}@${p.depth}`;r.set(e,(r.get(e)??0)+1)}else s++;n&&o.set(n.key,s);const i=new Map;let a=null,d=0;for(let p=0;p<e.length;p++){const n=e[p];if("group"===n.kind){const e=`${n.key.split("||").slice(0,-1).join("||")}@${n.depth}`,o=(i.get(e)??0)+1;i.set(e,o),t[p]={level:n.depth+1,setSize:r.get(e)??1,posInSet:o},a=n,d=0}else{d++;const r=a?.depth??-1,n=a?o.get(a.key)??1:e.length;t[p]={level:r+2,setSize:n,posInSet:d}}}this.flatMeta=t}processPreDefinedGroups(){const e=this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[];if(0===e.length)return this.isActive=!1,this.flattenedRows=[],[];if(!this.hasAppliedDefaultExpanded&&0===this.expandedKeys.size&&!1!==this.config.defaultExpanded){const t=this.collectGroupKeys(e),r=d(this.config.defaultExpanded??!1,t);r.size>0&&(this.expandedKeys=new Set(r),this.hasAppliedDefaultExpanded=!0)}const t=p({groups:e,expanded:this.expandedKeys,groupRows:this.groupRowsMap,loadingGroups:this.loadingGroups});this.isActive=!0,this.flattenedRows=t,this.computeFlatMeta(),this.keysToAnimate.clear();const r=new Set;return t.forEach((e,t)=>{if("data"===e.kind){const e=`data-${t}`;r.add(e),this.previousVisibleKeys.has(e)||this.keysToAnimate.add(e)}}),this.previousVisibleKeys=r,t.map(t=>{if("group"===t.kind){const r=this.findGroupDefinition(e,t.key),o=r?.rowCount??t.rows.length;return{__isGroupRow:!0,__groupKey:t.key,__groupValue:t.value,__groupDepth:t.depth,__groupRows:t.rows,__groupExpanded:t.expanded,__groupRowCount:o,__rowCacheKey:`group:${t.key}`}}return t.row})}collectGroupKeys(e){const t=[];for(const r of e)t.push(r.key),r.children?.length&&t.push(...this.collectGroupKeys(r.children));return t}getActiveGroups(){return this.preDefinedGroups.length>0?this.preDefinedGroups:Array.isArray(this.config.groups)?this.config.groups:[]}findGroupDefinition(e,t){for(const r of e){if(r.key===t)return r;if(r.children?.length){const e=this.findGroupDefinition(r.children,t);if(e)return e}}}createToggleButton(e,r){const o=document.createElement("button");return o.type="button",o.className=`${t.GridClasses.GROUP_TOGGLE}${e?` ${t.GridClasses.EXPANDED}`:""}`,o.setAttribute("aria-label",e?"Collapse group":"Expand group"),this.setIcon(o,e?"collapse":"expand"),o.addEventListener("click",e=>{e.stopPropagation(),r()}),o}getGroupLabelText(e,t,r){const o=this.config;return o.formatLabel?o.formatLabel(e,t,r):String(e)}renderFullWidthGroupRow(e,o,n){const s=this.config,i=s.aggregators??{},a=e.__groupRows??[],d=document.createElement("div");d.className="cell group-full",d.style.gridColumn="1 / -1",d.setAttribute("role","gridcell"),d.setAttribute("data-col","0"),d.appendChild(this.createToggleButton(e.__groupExpanded,n));const p=document.createElement("span");if(p.className=t.GridClasses.GROUP_LABEL,p.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey),d.appendChild(p),!1!==s.showRowCount){const r=document.createElement("span");r.className=t.GridClasses.GROUP_COUNT,r.textContent=`(${e.__groupRowCount??e.__groupRows?.length??0})`,d.appendChild(r)}const u=Object.entries(i);if(u.length>0){const e=document.createElement("span");e.className="group-aggregates";for(const[t,o]of u){const n=this.columns.find(e=>e.field===t),s=r.aggregatorRegistry.run(o,a,t,n);if(null!=s){const r=document.createElement("span");r.className="group-aggregate",r.setAttribute("data-field",t);const o=n?.header??t;r.textContent=`${o}: ${s}`,e.appendChild(r)}}e.children.length>0&&d.appendChild(e)}o.appendChild(d)}renderPerColumnGroupRow(e,o,n){const s=this.config,a=s.aggregators??{},d=this.columns,p=e.__groupRows??[],u=this.gridElement?.querySelector(".body"),l=u?.style.gridTemplateColumns||"";l&&(o.style.display="grid",o.style.gridTemplateColumns=l);let g=!1;d.forEach((d,u)=>{const l=document.createElement("div");if(l.className="cell group-cell",l.setAttribute("data-col",String(u)),l.setAttribute("role","gridcell"),i.isExpanderColumn(d))return l.setAttribute("data-field",d.field),void o.appendChild(l);if(g){const e=a[d.field];if(e){const t=r.aggregatorRegistry.run(e,p,d.field,d);l.textContent=null!=t?String(t):""}else l.textContent=""}else{g=!0,l.appendChild(this.createToggleButton(e.__groupExpanded,n));const o=document.createElement("span"),i=a[d.field];if(i){const t=r.aggregatorRegistry.run(i,p,d.field,d);o.textContent=String(null!=t?t:e.__groupValue)}else o.textContent=this.getGroupLabelText(e.__groupValue,e.__groupDepth||0,e.__groupKey);if(l.appendChild(o),!1!==s.showRowCount){const e=document.createElement("span");e.className=t.GridClasses.GROUP_COUNT,e.textContent=` (${p.length})`,l.appendChild(e)}}o.appendChild(l)})}expandAll(){this.expandedKeys=function(e){const t=new Set;for(const r of e)"group"===r.kind&&t.add(r.key);return t}(this.flattenedRows),this.emitPluginEvent("group-toggle",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("group-toggle",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}toggle(e){const t=!this.expandedKeys.has(e),r=this.config,n=this.flattenedRows.find(t=>"group"===t.kind&&t.key===e);if(r.accordion&&t&&n){const t=new Set;for(const r of this.expandedKeys)if(e.startsWith(r+"||")||r.startsWith(e+"||"))e.startsWith(r+"||")&&t.add(r);else{const e=this.flattenedRows.find(e=>"group"===e.kind&&e.key===r);e&&e.depth!==n.depth&&t.add(r)}t.add(e),this.expandedKeys=t}else this.expandedKeys=function(e,t){const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}(this.expandedKeys,e);this.broadcast("group-toggle",{key:e,expanded:this.expandedKeys.has(e),value:n?.value,depth:n?.depth??0,expandedKeys:[...this.expandedKeys]});const s=this.getActiveGroups();if(s.length>0){const r=u(s,e);if(t){if(this.emit("group-expand",{groupKey:e,groupPath:r}),!this.groupRowsMap.has(e)){const t=this.findGroupDefinition(s,e);t&&(this.loadingGroups.add(e),this.grid?.query?.("datasource:fetch-children",{context:{source:"grouping-rows",groupKey:e,group:t,groupPath:r}}))}}else this.emit("group-collapse",{groupKey:e,groupPath:r})}const i=this.expandedKeys.has(e),a=null!=n?.value?String(n.value):e;if(i){const e=n?.rows?.length??0;o.announce(this.gridElement,o.getA11yMessage(this.gridElement,"groupExpanded",a,e))}else o.announce(this.gridElement,o.getA11yMessage(this.gridElement,"groupCollapsed",a));this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}expand(e){this.expandedKeys.has(e)||(this.expandedKeys=new Set([...this.expandedKeys,e]),this.requestRender())}collapse(e){if(this.expandedKeys.has(e)){const t=new Set(this.expandedKeys);t.delete(e),this.expandedKeys=t,this.requestRender()}}getGroupState(){const e=this.flattenedRows.filter(e=>"group"===e.kind);return{isActive:this.isActive,expandedCount:this.expandedKeys.size,totalGroups:e.length,expandedKeys:[...this.expandedKeys]}}getRowCount(){return this.flattenedRows.length}refreshGroups(){this.requestRender()}getExpandedGroups(){return[...this.expandedKeys]}getFlattenedRows(){return this.flattenedRows}isGroupingActive(){return this.isActive}setGroupOn(e){this.config.groupOn=e,this.requestRender()}setGroups(e){this.preDefinedGroups=e,this.groupRowsMap.clear(),this.loadingGroups.clear(),this.expandedKeys.clear(),this.hasAppliedDefaultExpanded=!1,this.requestRender()}getGroups(){return this.preDefinedGroups.length>0?[...this.preDefinedGroups]:Array.isArray(this.config.groups)?[...this.config.groups]:[]}setGroupRows(e,t){this.groupRowsMap.set(e,t),this.loadingGroups.delete(e),this.requestRender()}setGroupLoading(e,t){t?this.loadingGroups.add(e):this.loadingGroups.delete(e),this.requestRender()}clearGroupRows(e){null!=e?this.groupRowsMap.delete(e):this.groupRowsMap.clear(),this.requestRender()}}e.GroupingRowsPlugin=l,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=grouping-rows.umd.js.map
|