@toolbox-web/grid 1.27.2 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/all.d.ts +1 -0
  2. package/all.js +2 -2
  3. package/all.js.map +1 -1
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/core/types.d.ts +0 -2
  7. package/lib/features/tooltip.d.ts +7 -0
  8. package/lib/features/tooltip.js +2 -0
  9. package/lib/features/tooltip.js.map +1 -0
  10. package/lib/plugins/clipboard/index.js +1 -1
  11. package/lib/plugins/clipboard/index.js.map +1 -1
  12. package/lib/plugins/column-virtualization/index.js +1 -1
  13. package/lib/plugins/column-virtualization/index.js.map +1 -1
  14. package/lib/plugins/context-menu/index.js +1 -1
  15. package/lib/plugins/context-menu/index.js.map +1 -1
  16. package/lib/plugins/editing/index.js +1 -1
  17. package/lib/plugins/editing/index.js.map +1 -1
  18. package/lib/plugins/editing/types.d.ts +2 -0
  19. package/lib/plugins/export/index.js +1 -1
  20. package/lib/plugins/export/index.js.map +1 -1
  21. package/lib/plugins/filtering/index.js +1 -1
  22. package/lib/plugins/filtering/index.js.map +1 -1
  23. package/lib/plugins/grouping-columns/index.js +1 -1
  24. package/lib/plugins/grouping-columns/index.js.map +1 -1
  25. package/lib/plugins/grouping-rows/index.js +2 -2
  26. package/lib/plugins/grouping-rows/index.js.map +1 -1
  27. package/lib/plugins/master-detail/index.js +1 -1
  28. package/lib/plugins/master-detail/index.js.map +1 -1
  29. package/lib/plugins/multi-sort/index.js +1 -1
  30. package/lib/plugins/multi-sort/index.js.map +1 -1
  31. package/lib/plugins/pinned-columns/index.js +1 -1
  32. package/lib/plugins/pinned-columns/index.js.map +1 -1
  33. package/lib/plugins/pinned-rows/index.js +1 -1
  34. package/lib/plugins/pinned-rows/index.js.map +1 -1
  35. package/lib/plugins/pivot/index.js +1 -1
  36. package/lib/plugins/pivot/index.js.map +1 -1
  37. package/lib/plugins/print/index.js +1 -1
  38. package/lib/plugins/print/index.js.map +1 -1
  39. package/lib/plugins/reorder-columns/index.js +1 -1
  40. package/lib/plugins/reorder-columns/index.js.map +1 -1
  41. package/lib/plugins/reorder-rows/index.js +1 -1
  42. package/lib/plugins/reorder-rows/index.js.map +1 -1
  43. package/lib/plugins/responsive/index.js +1 -1
  44. package/lib/plugins/responsive/index.js.map +1 -1
  45. package/lib/plugins/selection/index.js +1 -1
  46. package/lib/plugins/selection/index.js.map +1 -1
  47. package/lib/plugins/server-side/index.js +1 -1
  48. package/lib/plugins/server-side/index.js.map +1 -1
  49. package/lib/plugins/tooltip/TooltipPlugin.d.ts +52 -0
  50. package/lib/plugins/tooltip/index.d.ts +8 -0
  51. package/lib/plugins/tooltip/index.js +2 -0
  52. package/lib/plugins/tooltip/index.js.map +1 -0
  53. package/lib/plugins/tooltip/types.d.ts +78 -0
  54. package/lib/plugins/tree/index.js +1 -1
  55. package/lib/plugins/tree/index.js.map +1 -1
  56. package/lib/plugins/undo-redo/index.js +1 -1
  57. package/lib/plugins/undo-redo/index.js.map +1 -1
  58. package/lib/plugins/visibility/index.js +1 -1
  59. package/lib/plugins/visibility/index.js.map +1 -1
  60. package/package.json +1 -1
  61. package/umd/grid.all.umd.js +1 -1
  62. package/umd/grid.all.umd.js.map +1 -1
  63. package/umd/grid.umd.js +1 -1
  64. package/umd/grid.umd.js.map +1 -1
  65. package/umd/plugins/context-menu.umd.js +1 -1
  66. package/umd/plugins/context-menu.umd.js.map +1 -1
  67. package/umd/plugins/tooltip.umd.js +2 -0
  68. package/umd/plugins/tooltip.umd.js.map +1 -0
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],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 s(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 i(e,t,o,l=n.DEFAULT_GRID_ICONS.submenuArrow){const c=document.createElement("div");c.className="tbw-context-menu",c.setAttribute("role","menu");const a=e.some(e=>!e.separator&&e.icon);for(const n of e){if(n.separator){const e=document.createElement("div");e.className="tbw-context-menu-separator",e.setAttribute("role","separator"),c.appendChild(e);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",n.cssClass&&e.classList.add(n.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",n.id),e.setAttribute("tabindex","-1");const u=r(n,t);if(u&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),n.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=n.icon,e.appendChild(t)}else if(a){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const d=document.createElement("span");if(d.className="tbw-context-menu-label",d.textContent=n.name,e.appendChild(d),n.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(n.shortcut))n.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=n.shortcut,t.appendChild(e)}e.appendChild(t)}if(n.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow","string"==typeof l?r.innerHTML=l:l instanceof HTMLElement&&r.appendChild(l.cloneNode(!0)),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu"))return;if(!n.subMenu)return;const r=i(s(n.subMenu,t),t,o,l);r.classList.add("tbw-context-submenu"),r.style.position="absolute",r.style.left="100%",r.style.top="0",e.style.position="relative",e.appendChild(r)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}u||!n.action||n.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),o(n)}),c.appendChild(e)}return c}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?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.plugins?.export?.exportCsv?.()}}];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"];copyGridStyles(e){const t=this.gridElement;if(!t)return;const n=getComputedStyle(t),o=[],s=n.getPropertyValue("color-scheme").trim();s&&o.push(`color-scheme: ${s}`);for(const r of m.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=()=>{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=s(this.config.items??d,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=i(l,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.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(),s=window.innerWidth,r=window.innerHeight;let i=t,l=n;t+o.width>s&&(i=t-o.width),n+o.height>r&&(l=n-o.height),i=Math.max(0,i),l=Math.max(0,l),e.style.left=`${i}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]"),s=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),s=this.visibleColumns[n],i=this.rows[e],l=this.syncSelectionOnContextMenu(e);r={row:i,rowIndex:e,column:s,columnIndex:n,field:s?.field??"",value:i?.[s?.field]??null,isHeader:!1,event:t,selectedRows:l}}else{if(!s)return;{const e=parseInt(s.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 s=o._focusRow,r=o._focusCol,i=this.visibleColumns[r],l=this.rows[s],c=this.gridElement,a=c?.querySelector(`[data-row="${s}"][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(s),b={row:l,rowIndex:s,column:i,columnIndex:r,field:i?.field??"",value:l?.[i?.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"),require("../../core/types")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/internal/sanitize","../../core/types"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_contextMenu={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,n,o){"use strict";const r="@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 s(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 l(e,t,r,c=o.DEFAULT_GRID_ICONS.submenuArrow){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 o of e){if(o.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",o.cssClass&&e.classList.add(o.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",o.id),e.setAttribute("tabindex","-1");const d=i(o,t);if(d&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),o.icon){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML=n.sanitizeHTML(o.icon),e.appendChild(t)}else if(u){const t=document.createElement("span");t.className="tbw-context-menu-icon",t.innerHTML="&nbsp;",e.appendChild(t)}const m=document.createElement("span");if(m.className="tbw-context-menu-label",m.textContent=o.name,e.appendChild(m),o.shortcut){const t=document.createElement("span");if(t.className="tbw-context-menu-shortcut",Array.isArray(o.shortcut))o.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=o.shortcut,t.appendChild(e)}e.appendChild(t)}if(o.subMenu?.length){const i=document.createElement("span");i.className="tbw-context-menu-arrow","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(!o.subMenu)return;const n=l(s(o.subMenu,t),t,r,c);n.classList.add("tbw-context-submenu"),n.style.position="absolute",n.style.left="100%",n.style.top="0",e.style.position="relative",e.appendChild(n)}),e.addEventListener("mouseleave",()=>{const t=e.querySelector(".tbw-context-menu");t&&t.remove()})}d||!o.action||o.subMenu||e.addEventListener("click",e=>{e.stopPropagation(),r(o)}),a.appendChild(e)}return a}const c="getContextMenuItems";let a=null,u=null,d=0;const m=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:e=>{const t=e.grid;t?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:e=>{const t=e.grid;t?.plugins?.export?.exportCsv?.()}}];class b extends t.BaseGridPlugin{static manifest={queries:[{type:c,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(),d++}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"];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 s of b.CSS_VARS_TO_COPY){const e=n.getPropertyValue(s).trim();e&&o.push(`${s}: ${e}`)}if(o.length>0){const t=e.getAttribute("style")||"";e.setAttribute("style",t+o.join("; ")+";")}}installGlobalHandlers(){if(!u&&"undefined"!=typeof document&&r&&(u=document.createElement("style"),u.id="tbw-context-menu-styles",u.textContent=r,document.head.appendChild(u)),!a){a=new AbortController;const e=a.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(){d--,d>0||(a&&(a.abort(),a=null),u&&(u.remove(),u=null))}collectPluginItems(e){if(!this.grid)return[];const t=this.grid.query(c,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 i=s(this.config.items??m,e);if(r.length>0){const e=this.convertPluginItems(r);i=i.length>0&&e.length>0?[...i,{id:"__plugin-sep",name:"",separator:!0},...e]:[...i,...e]}var c,a;(i=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}(i),i.length)&&(document.querySelectorAll(".tbw-context-menu").forEach(e=>e.remove()),this.menuElement=null,this.menuElement=l(i,e,t=>{t.action&&t.action(e),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.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,s=window.innerHeight;let i=t,l=n;t+o.width>r&&(i=t-o.width),n+o.height>s&&(l=n-o.height),i=Math.max(0,i),l=Math.max(0,l),e.style.left=`${i}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:i}))}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 s;if(o){const e=parseInt(o.getAttribute("data-row")??"-1",10),n=parseInt(o.getAttribute("data-col")??"-1",10),r=this.visibleColumns[n],i=this.rows[e],l=this.syncSelectionOnContextMenu(e);s={row:i,rowIndex:e,column:r,columnIndex:n,field:r?.field??"",value:i?.[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];s={row:null,rowIndex:-1,column:n,columnIndex:e,field:n?.field??"",value:null,isHeader:!0,event:t,selectedRows:[]}}}this.openMenuAt(s,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,s=o._focusCol,i=this.visibleColumns[s],l=this.rows[r],c=this.gridElement,a=c?.querySelector(`[data-row="${r}"][data-col="${s}"]`);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:i,columnIndex:s,field:i?.field??"",value:l?.[i?.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=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 type { IconValue } from '../../core/types';\nimport { DEFAULT_GRID_ICONS } 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 = DEFAULT_GRID_ICONS.submenuArrow,\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 = 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 = '&nbsp;';\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 // Use provided submenu arrow icon (string or HTMLElement)\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = submenuArrow;\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\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 const grid = (params as ContextMenuParams & { grid?: { plugins?: { clipboard?: { copy?: () => void } } } }).grid;\n grid?.plugins?.clipboard?.copy?.();\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { export?: { exportCsv?: () => void } } } })\n .grid;\n grid?.plugins?.export?.exportCsv?.();\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 ];\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.gridIcons.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","DEFAULT_GRID_ICONS","menu","document","createElement","className","setAttribute","hasAnyIcon","some","separator","icon","appendChild","menuItem","cssClass","classList","add","id","innerHTML","label","textContent","name","shortcut","Array","isArray","forEach","key","i","createTextNode","kbd","subMenu","length","arrow","HTMLElement","cloneNode","addEventListener","querySelector","style","position","left","top","remove","action","e","stopPropagation","QUERY_GET_CONTEXT_MENU_ITEMS","globalAbortController","globalStyleSheet","globalHandlerRefCount","defaultItems","grid","plugins","clipboard","copy","export","exportCsv","ContextMenuPlugin","BaseGridPlugin","static","queries","type","description","defaultConfig","isOpen","x","y","menuElement","attach","super","this","installGlobalHandlers","detach","uninstallGlobalHandlers","syncSelectionOnContextMenu","rowIndex","selectionResult","query","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","gridIcons","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":"klEAiBO,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,EAA0BC,EAAAA,mBAAmBD,cAE7C,MAAME,EAAOC,SAASC,cAAc,OACpCF,EAAKG,UAAY,mBACjBH,EAAKI,aAAa,OAAQ,QAG1B,MAAMC,EAAahB,EAAM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,UAAU,EACVd,QACAW,gBAIF,OADAlG,KAAKiD,WAAW7H,EAAQuE,EAAGC,GAAG,IACvB,CACT,CA2BA,QAAAqH,CAAStH,EAAWC,EAAWxE,GAC7B,MAAM8L,EAAgC,CACpClB,IAAK5K,EAAO4K,KAAO,KACnB3F,SAAUjF,EAAOiF,WAAY,EAC7ByF,OAAQ1K,EAAO0K,QAAU,KACzBK,YAAa/K,EAAO+K,cAAe,EACnCC,MAAOhL,EAAOgL,OAAS,GACvB9E,MAAOlG,EAAOkG,OAAS,KACvB+E,SAAUjL,EAAOiL,WAAY,EAC7Bd,MAAOnK,EAAOmK,OAAS,IAAI4B,WAAW,eACtCjB,aAAc9K,EAAO8K,cAAgB,IAGvClG,KAAKiD,WAAWiE,EAAYvH,EAAGC,EACjC,CAOA,QAAA+D,GACM3D,KAAKH,cACPG,KAAKH,YAAYzB,SACjB4B,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 type { IconValue } from '../../core/types';\nimport { DEFAULT_GRID_ICONS } 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 = DEFAULT_GRID_ICONS.submenuArrow,\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 = '&nbsp;';\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 // Use provided submenu arrow icon (string or HTMLElement)\n if (typeof submenuArrow === 'string') {\n arrow.innerHTML = sanitizeHTML(submenuArrow);\n } else if (submenuArrow instanceof HTMLElement) {\n arrow.appendChild(submenuArrow.cloneNode(true));\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 const grid = (params as ContextMenuParams & { grid?: { plugins?: { clipboard?: { copy?: () => void } } } }).grid;\n grid?.plugins?.clipboard?.copy?.();\n },\n },\n { separator: true, id: 'sep1', name: '' },\n {\n id: 'export-csv',\n name: 'Export CSV',\n action: (params) => {\n const grid = (params as ContextMenuParams & { grid?: { plugins?: { export?: { exportCsv?: () => void } } } })\n .grid;\n grid?.plugins?.export?.exportCsv?.();\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 ];\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.gridIcons.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","DEFAULT_GRID_ICONS","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","HTMLElement","cloneNode","addEventListener","querySelector","style","position","left","top","remove","action","e","stopPropagation","QUERY_GET_CONTEXT_MENU_ITEMS","globalAbortController","globalStyleSheet","globalHandlerRefCount","defaultItems","grid","plugins","clipboard","copy","export","exportCsv","ContextMenuPlugin","BaseGridPlugin","static","queries","type","description","defaultConfig","isOpen","x","y","menuElement","attach","super","this","installGlobalHandlers","detach","uninstallGlobalHandlers","syncSelectionOnContextMenu","rowIndex","selectionResult","query","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","gridIcons","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":"qqEAkBO,SAASA,EACdC,EACAC,GAIA,OAFmC,mBAAVD,EAAuBA,EAAMC,GAAUD,GAE/CE,OAAQC,IACH,IAAhBA,EAAKC,SACkB,mBAAhBD,EA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C,iBAAwBwF,OACxF,IAAIlG,EAAI,EACJC,EAAI,EACR,GAAIkH,EAAQ,CACV,MAAMC,EAAOD,EAAOtC,wBACpB7E,EAAIoH,EAAK7I,KAAO6I,EAAKjC,MAAQ,EAC7BlF,EAAImH,EAAKC,MACX,CAEA,MAAMd,EAAelG,KAAKI,2BAA2BC,GAE/ClF,EAA4B,CAChC6K,MACA3F,WACAyF,SACAK,YAAaN,EACbO,MAAON,GAAQM,OAAS,GACxB9E,MAAO0E,IAAMF,GAAQM,QAA8B,KACnDC,UAAU,EACVd,QACAW,gBAIF,OADAlG,KAAKiD,WAAW9H,EAAQwE,EAAGC,GAAG,IACvB,CACT,CA2BA,QAAAqH,CAAStH,EAAWC,EAAWzE,GAC7B,MAAM+L,EAAgC,CACpClB,IAAK7K,EAAO6K,KAAO,KACnB3F,SAAUlF,EAAOkF,WAAY,EAC7ByF,OAAQ3K,EAAO2K,QAAU,KACzBK,YAAahL,EAAOgL,cAAe,EACnCC,MAAOjL,EAAOiL,OAAS,GACvB9E,MAAOnG,EAAOmG,OAAS,KACvB+E,SAAUlL,EAAOkL,WAAY,EAC7Bd,MAAOpK,EAAOoK,OAAS,IAAI4B,WAAW,eACtCjB,aAAc/K,EAAO+K,cAAgB,IAGvClG,KAAKiD,WAAWiE,EAAYvH,EAAGC,EACjC,CAOA,QAAA+D,GACM3D,KAAKH,cACPG,KAAKH,YAAYzB,SACjB4B,KAAKH,YAAc,KACnBG,KAAKN,QAAS,EAElB,CAOA,UAAA0H,GACE,OAAOpH,KAAKN,MACd"}
@@ -0,0 +1,2 @@
1
+ !function(t,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],o):o((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_tooltip={},t.TbwGrid)}(this,function(t,o){"use strict";function e(t){return t.scrollWidth>t.clientWidth}function r(){return"function"==typeof HTMLElement.prototype?.showPopover}class i extends o.BaseGridPlugin{name="tooltip";styles='@layer tbw-plugins{.tbw-tooltip-popover{margin:0;padding:var(--tbw-tooltip-padding, var(--tbw-spacing-sm, .375rem) var(--tbw-spacing-md, .5rem));background:var(--tbw-tooltip-bg, light-dark(#333338, #484850));color:var(--tbw-tooltip-fg, light-dark(#f5f5f5, #f0f0f0));border:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-radius:var(--tbw-tooltip-radius, var(--tbw-border-radius, .25rem));box-shadow:none;filter:var(--tbw-tooltip-shadow, drop-shadow(0 4px 4px rgba(0, 0, 0, .45)));font-family:var(--tbw-font-family, system-ui, sans-serif);font-size:var(--tbw-tooltip-font-size, var(--tbw-font-size-sm, .9285em));max-width:var(--tbw-tooltip-max-width, 300px);white-space:pre-line;word-wrap:break-word;overflow-wrap:break-word;pointer-events:none;z-index:10001}.tbw-tooltip-popover:after{content:"";position:absolute;width:var(--tbw-tooltip-arrow-size, 14px);height:var(--tbw-tooltip-arrow-size, 14px);left:var(--tbw-tooltip-arrow-offset, 16px);background:inherit;pointer-events:none}.tbw-tooltip-popover:not(.tbw-tooltip-above):after{top:calc(var(--tbw-tooltip-arrow-size, 14px) / -2);transform:rotate(45deg);border-top:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-left:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72))}.tbw-tooltip-popover.tbw-tooltip-above:after{bottom:calc(var(--tbw-tooltip-arrow-size, 14px) / -2);transform:rotate(45deg);border-bottom:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72));border-right:1px solid var(--tbw-tooltip-border, light-dark(#222226, #6a6a72))}@supports (anchor-name: --test){.tbw-tooltip-popover{position-anchor:--tbw-tooltip-anchor;top:calc(anchor(bottom) + 11px);left:anchor(left);position-try-fallbacks:--tbw-tooltip-flip-above}@position-try --tbw-tooltip-flip-above{top:auto;bottom:calc(anchor(top) + 11px)}}}';static manifest={ownedProperties:[{property:"cellTooltip",level:"column",description:'the "cellTooltip" column property'},{property:"headerTooltip",level:"column",description:'the "headerTooltip" column property'}],configRules:[]};#t=null;#o=null;#e=!1;get#r(){return!1!==this.config.header}get#i(){return!1!==this.config.cell}attach(t){super.attach(t)}detach(){this.#l(),this.#t?.remove(),this.#t=null,this.#e=!1,super.detach()}afterRender(){this.#n(),this.#s()}#n(){if(this.#t)return;const t=document.createElement("div");t.className="tbw-tooltip-popover",t.setAttribute("popover","hint"),t.style.overflow="visible",t.style.margin="0",document.body.appendChild(t),this.#t=t}#p(t,o){if(this.#t){if(this.#a(),t.style.setProperty("anchor-name","--tbw-tooltip-anchor"),this.#o=t,this.#t.textContent=o,r())try{this.#t.showPopover()}catch{}"undefined"!=typeof CSS&&!0===CSS.supports?.("anchor-name","--test")?requestAnimationFrame(()=>this.#d(t)):this.#c(t)}}#l(){if(this.#t){if(r())try{this.#t.hidePopover()}catch{}this.#t.classList.remove("tbw-tooltip-above")}this.#a()}#a(){this.#o&&(this.#o.style.removeProperty("anchor-name"),this.#o=null)}#c(t){if(!this.#t)return;const o=t.getBoundingClientRect();this.#t.style.position="fixed",this.#t.style.left=`${o.left}px`;window.innerHeight-o.bottom<80?(this.#t.style.top="",this.#t.style.bottom=window.innerHeight-o.top+11+"px",this.#t.classList.add("tbw-tooltip-above")):(this.#t.style.top=`${o.bottom+11}px`,this.#t.style.bottom="",this.#t.classList.remove("tbw-tooltip-above"))}#d(t){if(!this.#t)return;const o=t.getBoundingClientRect(),e=this.#t.getBoundingClientRect();this.#t.classList.toggle("tbw-tooltip-above",e.bottom<=o.top)}#s(){if(this.#e)return;const t=this.gridElement?.querySelector(".tbw-grid-root");t&&(this.#e=!0,t.addEventListener("mouseover",t=>this.#h(t),{signal:this.disconnectSignal}),t.addEventListener("mouseout",t=>this.#u(t),{signal:this.disconnectSignal}))}#h(t){const o=t.target;if(!o?.closest)return;const e=o.closest('[part~="header-cell"]');if(e&&this.#r)return void this.#b(e);const r=o.closest("[data-row][data-col]");r&&this.#i&&this.#f(r)}#u(t){const o=t.target;if(!o?.closest)return;const e=o.closest('[part~="header-cell"], [data-row][data-col]');if(!e)return;const r=t.relatedTarget;r&&e.contains(r)||this.#l()}#b(t){const o=parseInt(t.getAttribute("data-col")??"-1",10);if(o<0)return;const r=this.visibleColumns[o];if(!r)return;const i=function(t,o){const r=t.headerTooltip;if(!1===r)return null;if("string"==typeof r)return r;if("function"==typeof r)return r({column:t,value:t.header??t.field});const i=o.querySelector("span:first-child")??o;return e(i)&&i.textContent?.trim()||null}(r,t);i&&this.#p(t,i)}#f(t){const o=parseInt(t.getAttribute("data-row")??"-1",10),r=parseInt(t.getAttribute("data-col")??"-1",10);if(o<0||r<0)return;const i=this.visibleColumns[r];if(!i)return;const l=this.rows[o],n=l?.[i.field],s=function(t,o,r,i){const l=t.cellTooltip;if(!1===l)return null;if("string"==typeof l)return l;if("function"==typeof l)return l({value:i,row:r,column:t,field:t.field});return e(o)&&o.textContent?.trim()||null}(i,t,l,n);s&&this.#p(t,s)}}t.TooltipPlugin=i,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
+ //# sourceMappingURL=tooltip.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tooltip.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/tooltip/TooltipPlugin.ts"],"sourcesContent":["/**\n * Tooltip Plugin\n *\n * Shows styled popover tooltips on header and data cells when text\n * overflows (ellipsis). Uses the Popover API (`popover=\"hint\"`) with\n * CSS anchor positioning for consistent, themed placement.\n *\n * Supports per-column overrides via `cellTooltip` and `headerTooltip`\n * on column config.\n */\n\nimport type { GridElement, PluginManifest } from '../../core/plugin/base-plugin';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { CellRenderContext, ColumnConfig, HeaderLabelContext } from '../../core/types';\nimport tooltipStyles from './tooltip.css?inline';\nimport type { TooltipConfig } from './types';\n\n// #region Helpers\n\n/** Check if an element's text content overflows its visible width. */\nfunction isOverflowing(el: HTMLElement): boolean {\n return el.scrollWidth > el.clientWidth;\n}\n\n/**\n * Resolve the tooltip text for a cell.\n * Returns the text to show, or `null` to suppress.\n */\nfunction resolveCellTooltip(column: ColumnConfig, cell: HTMLElement, row: unknown, value: unknown): string | null {\n const spec = column.cellTooltip;\n\n if (spec === false) return null;\n if (typeof spec === 'string') return spec;\n if (typeof spec === 'function') {\n const ctx: CellRenderContext = { value, row, column, field: column.field };\n return spec(ctx);\n }\n\n // Default: show textContent only when overflowing\n if (isOverflowing(cell)) {\n return cell.textContent?.trim() || null;\n }\n\n return null;\n}\n\n/**\n * Resolve the tooltip text for a header cell.\n * Returns the text to show, or `null` to suppress.\n */\nfunction resolveHeaderTooltip(column: ColumnConfig, headerCell: HTMLElement): string | null {\n const spec = column.headerTooltip;\n\n if (spec === false) return null;\n if (typeof spec === 'string') return spec;\n if (typeof spec === 'function') {\n const ctx: HeaderLabelContext = {\n column,\n value: column.header ?? column.field,\n };\n return spec(ctx);\n }\n\n // Default: show header text only when overflowing\n const labelSpan = headerCell.querySelector('span:first-child') as HTMLElement | null;\n const target = labelSpan ?? headerCell;\n\n if (isOverflowing(target)) {\n return target.textContent?.trim() || null;\n }\n\n return null;\n}\n\n/** Runtime check — happy-dom and older browsers may lack Popover API. */\nfunction supportsPopover(): boolean {\n return typeof HTMLElement.prototype?.showPopover === 'function';\n}\n\n/** Runtime check for CSS anchor positioning. */\nfunction supportsAnchor(): boolean {\n return typeof CSS !== 'undefined' && CSS.supports?.('anchor-name', '--test') === true;\n}\n// #endregion\n\n// #region TooltipPlugin\n/**\n * Tooltip Plugin for tbw-grid\n *\n * Shows styled popover tooltips when header or cell text overflows its\n * container. Uses the Popover API with CSS anchor positioning for\n * consistent themed appearance across light and dark modes.\n *\n * ## Installation\n *\n * ```ts\n * import { TooltipPlugin } from '@toolbox-web/grid/plugins/tooltip';\n * ```\n *\n * @example Default — auto-tooltip on overflow\n * ```ts\n * grid.gridConfig = {\n * plugins: [new TooltipPlugin()],\n * };\n * ```\n *\n * @example Header-only tooltips\n * ```ts\n * grid.gridConfig = {\n * plugins: [new TooltipPlugin({ cell: false })],\n * };\n * ```\n *\n * @example Per-column overrides\n * ```ts\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', cellTooltip: (ctx) => `${ctx.row.first} ${ctx.row.last}` },\n * { field: 'actions', cellTooltip: false },\n * { field: 'revenue', headerTooltip: 'Total revenue in USD (before tax)' },\n * ],\n * plugins: [new TooltipPlugin()],\n * };\n * ```\n *\n * @category Plugins\n */\nexport class TooltipPlugin extends BaseGridPlugin<TooltipConfig> {\n readonly name = 'tooltip';\n override readonly styles = tooltipStyles;\n\n static override readonly manifest: PluginManifest<TooltipConfig> = {\n ownedProperties: [\n { property: 'cellTooltip', level: 'column', description: 'the \"cellTooltip\" column property' },\n { property: 'headerTooltip', level: 'column', description: 'the \"headerTooltip\" column property' },\n ],\n configRules: [],\n };\n\n /** The shared popover element for all tooltips. */\n #popoverEl: HTMLElement | null = null;\n\n /** The cell currently acting as CSS anchor. */\n #anchorCell: HTMLElement | null = null;\n\n /** Whether delegated listeners are bound. */\n #bound = false;\n\n /** Whether header tooltips are enabled globally. */\n get #headerEnabled(): boolean {\n return this.config.header !== false;\n }\n\n /** Whether cell tooltips are enabled globally. */\n get #cellEnabled(): boolean {\n return this.config.cell !== false;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n }\n\n override detach(): void {\n this.#hideTooltip();\n this.#popoverEl?.remove();\n this.#popoverEl = null;\n this.#bound = false;\n super.detach();\n }\n\n override afterRender(): void {\n this.#ensurePopover();\n this.#bindEvents();\n }\n\n // #region Popover Lifecycle\n\n /** Create the shared popover element (once). */\n #ensurePopover(): void {\n if (this.#popoverEl) return;\n const el = document.createElement('div');\n el.className = 'tbw-tooltip-popover';\n el.setAttribute('popover', 'hint');\n // Override UA popover defaults that @layer CSS cannot beat\n el.style.overflow = 'visible';\n el.style.margin = '0';\n document.body.appendChild(el);\n this.#popoverEl = el;\n }\n\n /** Show the popover anchored to `cell` with the given `text`. */\n #showTooltip(cell: HTMLElement, text: string): void {\n if (!this.#popoverEl) return;\n\n // Move the CSS anchor to the hovered cell\n this.#clearAnchor();\n cell.style.setProperty('anchor-name', '--tbw-tooltip-anchor');\n this.#anchorCell = cell;\n\n // Set content (always textContent — safe, no XSS)\n this.#popoverEl.textContent = text;\n\n // Show via Popover API\n if (supportsPopover()) {\n try {\n this.#popoverEl.showPopover();\n } catch {\n /* already shown */\n }\n }\n\n if (supportsAnchor()) {\n // Detect flip after the browser resolves position-try-fallbacks\n requestAnimationFrame(() => this.#detectFlip(cell));\n } else {\n this.#positionFallback(cell);\n }\n }\n\n /** Hide the popover and clear the anchor reference. */\n #hideTooltip(): void {\n if (this.#popoverEl) {\n if (supportsPopover()) {\n try {\n this.#popoverEl.hidePopover();\n } catch {\n /* already hidden */\n }\n }\n this.#popoverEl.classList.remove('tbw-tooltip-above');\n }\n this.#clearAnchor();\n }\n\n /** Remove the CSS anchor-name from the previous cell. */\n #clearAnchor(): void {\n if (this.#anchorCell) {\n this.#anchorCell.style.removeProperty('anchor-name');\n this.#anchorCell = null;\n }\n }\n\n /**\n * Fallback positioning for browsers without CSS anchor support.\n * Places the popover below or above the cell using fixed coordinates.\n */\n #positionFallback(cell: HTMLElement): void {\n if (!this.#popoverEl) return;\n const cellRect = cell.getBoundingClientRect();\n const arrowGap = 11;\n\n this.#popoverEl.style.position = 'fixed';\n this.#popoverEl.style.left = `${cellRect.left}px`;\n\n // Check if there's space below\n const spaceBelow = window.innerHeight - cellRect.bottom;\n if (spaceBelow < 80) {\n // Place above the cell\n this.#popoverEl.style.top = '';\n this.#popoverEl.style.bottom = `${window.innerHeight - cellRect.top + arrowGap}px`;\n this.#popoverEl.classList.add('tbw-tooltip-above');\n } else {\n this.#popoverEl.style.top = `${cellRect.bottom + arrowGap}px`;\n this.#popoverEl.style.bottom = '';\n this.#popoverEl.classList.remove('tbw-tooltip-above');\n }\n }\n\n /** Toggle the arrow direction class after CSS anchor positioning resolves. */\n #detectFlip(cell: HTMLElement): void {\n if (!this.#popoverEl) return;\n const cellRect = cell.getBoundingClientRect();\n const popoverRect = this.#popoverEl.getBoundingClientRect();\n // If the popover's bottom edge is above the cell's top, it flipped\n this.#popoverEl.classList.toggle('tbw-tooltip-above', popoverRect.bottom <= cellRect.top);\n }\n // #endregion\n\n // #region Event Delegation\n\n /** Bind delegated mouseover/mouseout once. */\n #bindEvents(): void {\n if (this.#bound) return;\n const container = this.gridElement?.querySelector('.tbw-grid-root');\n if (!container) return;\n\n this.#bound = true;\n\n container.addEventListener('mouseover', (e: Event) => this.#onMouseOver(e as MouseEvent), {\n signal: this.disconnectSignal,\n });\n\n container.addEventListener('mouseout', (e: Event) => this.#onMouseOut(e as MouseEvent), {\n signal: this.disconnectSignal,\n });\n }\n\n #onMouseOver(e: MouseEvent): void {\n const target = e.target as HTMLElement;\n if (!target?.closest) return;\n\n // Check for header cell\n const headerCell = target.closest('[part~=\"header-cell\"]') as HTMLElement | null;\n if (headerCell && this.#headerEnabled) {\n this.#showHeaderTooltip(headerCell);\n return;\n }\n\n // Check for data cell\n const dataCell = target.closest('[data-row][data-col]') as HTMLElement | null;\n if (dataCell && this.#cellEnabled) {\n this.#showCellTooltip(dataCell);\n }\n }\n\n #onMouseOut(e: MouseEvent): void {\n const target = e.target as HTMLElement;\n if (!target?.closest) return;\n\n const cell = target.closest('[part~=\"header-cell\"], [data-row][data-col]') as HTMLElement | null;\n if (!cell) return;\n\n // Keep tooltip if pointer moved to a child still inside the same cell\n const related = e.relatedTarget as HTMLElement | null;\n if (related && cell.contains(related)) return;\n\n this.#hideTooltip();\n }\n // #endregion\n\n // #region Tooltip Resolution\n\n #showHeaderTooltip(headerCell: HTMLElement): void {\n const colIndex = parseInt(headerCell.getAttribute('data-col') ?? '-1', 10);\n if (colIndex < 0) return;\n\n const column = this.visibleColumns[colIndex];\n if (!column) return;\n\n const text = resolveHeaderTooltip(column, headerCell);\n if (text) {\n this.#showTooltip(headerCell, text);\n }\n }\n\n #showCellTooltip(cell: HTMLElement): void {\n const rowIndex = parseInt(cell.getAttribute('data-row') ?? '-1', 10);\n const colIndex = parseInt(cell.getAttribute('data-col') ?? '-1', 10);\n if (rowIndex < 0 || colIndex < 0) return;\n\n const column = this.visibleColumns[colIndex];\n if (!column) return;\n\n const row = this.rows[rowIndex];\n const value = row?.[column.field as keyof typeof row];\n\n const text = resolveCellTooltip(column, cell, row, value);\n if (text) {\n this.#showTooltip(cell, text);\n }\n }\n // #endregion\n}\n// #endregion\n"],"names":["isOverflowing","el","scrollWidth","clientWidth","supportsPopover","HTMLElement","prototype","showPopover","TooltipPlugin","BaseGridPlugin","name","styles","static","ownedProperties","property","level","description","configRules","popoverEl","anchorCell","bound","headerEnabled","this","config","header","cellEnabled","cell","attach","grid","super","detach","hideTooltip","remove","afterRender","ensurePopover","bindEvents","document","createElement","className","setAttribute","style","overflow","margin","body","appendChild","showTooltip","text","clearAnchor","setProperty","textContent","CSS","supports","requestAnimationFrame","detectFlip","positionFallback","hidePopover","classList","removeProperty","cellRect","getBoundingClientRect","position","left","window","innerHeight","bottom","top","add","popoverRect","toggle","container","gridElement","querySelector","addEventListener","e","onMouseOver","signal","disconnectSignal","onMouseOut","target","closest","headerCell","showHeaderTooltip","dataCell","showCellTooltip","related","relatedTarget","contains","colIndex","parseInt","getAttribute","column","visibleColumns","spec","headerTooltip","value","field","trim","resolveHeaderTooltip","rowIndex","row","rows","cellTooltip","resolveCellTooltip"],"mappings":"iVAoBA,SAASA,EAAcC,GACrB,OAAOA,EAAGC,YAAcD,EAAGE,WAC7B,CAqDA,SAASC,IACP,MAAqD,mBAAvCC,YAAYC,WAAWC,WACvC,CAkDO,MAAMC,UAAsBC,EAAAA,eACxBC,KAAO,UACEC,yzDAElBC,gBAAmE,CACjEC,gBAAiB,CACf,CAAEC,SAAU,cAAeC,MAAO,SAAUC,YAAa,qCACzD,CAAEF,SAAU,gBAAiBC,MAAO,SAAUC,YAAa,wCAE7DC,YAAa,IAIfC,G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