@toolbox-web/grid 1.15.0 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +33 -11
- package/all.js.map +1 -1
- package/index.js +877 -865
- package/index.js.map +1 -1
- package/lib/core/internal/columns.d.ts +0 -5
- package/lib/core/internal/columns.d.ts.map +1 -1
- package/lib/core/internal/rows.d.ts.map +1 -1
- package/lib/core/types.d.ts +12 -0
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/index.js +59 -49
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/context-menu/menu.d.ts.map +1 -1
- package/lib/plugins/context-menu/types.d.ts +4 -4
- package/lib/plugins/context-menu/types.d.ts.map +1 -1
- package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
- package/lib/plugins/editing/index.js +228 -216
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/filter-model.d.ts.map +1 -1
- package/lib/plugins/filtering/index.js +4 -5
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/row-reorder/index.js.map +1 -1
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +26 -26
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +21 -21
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js +1 -1
- package/umd/plugins/context-menu.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/filtering.umd.js +1 -1
- package/umd/plugins/filtering.umd.js.map +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(m,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],g):(m=typeof globalThis<"u"?globalThis:m||self,g(m.TbwGridPlugin_contextMenu={},m.TbwGrid,m.TbwGrid))})(this,(function(m,g,O){"use strict";const x="@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{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 v(l,e){return(typeof l=="function"?l(e):l).filter(t=>!(t.hidden===!0||typeof t.hidden=="function"&&t.hidden(e)))}function M(l){const e=[];for(const o of l)o.separator&&(e.length===0||e[e.length-1].separator)||e.push(o);return e.length>0&&e[e.length-1].separator&&e.pop(),e}function _(l,e){return l.disabled===!0?!0:typeof l.disabled=="function"?l.disabled(e):!1}function y(l,e,o,t=O.DEFAULT_GRID_ICONS.submenuArrow){const s=document.createElement("div");s.className="tbw-context-menu",s.setAttribute("role","menu");const c=l.some(n=>!n.separator&&n.icon);for(const n of l){if(n.separator){const r=document.createElement("div");r.className="tbw-context-menu-separator",r.setAttribute("role","separator"),s.appendChild(r);continue}const i=document.createElement("div");i.className="tbw-context-menu-item",n.cssClass&&i.classList.add(n.cssClass),i.setAttribute("role","menuitem"),i.setAttribute("data-id",n.id);const a=_(n,e);if(a&&(i.classList.add("disabled"),i.setAttribute("aria-disabled","true")),n.icon){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=n.icon,i.appendChild(r)}else if(c){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=" ",i.appendChild(r)}const w=document.createElement("span");if(w.className="tbw-context-menu-label",w.textContent=n.name,i.appendChild(w),n.shortcut){const r=document.createElement("span");r.className="tbw-context-menu-shortcut",r.textContent=n.shortcut,i.appendChild(r)}if(n.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",typeof t=="string"?r.innerHTML=t:t instanceof HTMLElement&&r.appendChild(t.cloneNode(!0)),i.appendChild(r),i.addEventListener("mouseenter",()=>{if(i.querySelector(".tbw-context-menu")||!n.subMenu)return;const f=v(n.subMenu,e),d=y(f,e,o,t);d.classList.add("tbw-context-submenu"),d.style.position="absolute",d.style.left="100%",d.style.top="0",i.style.position="relative",i.appendChild(d)}),i.addEventListener("mouseleave",()=>{const u=i.querySelector(".tbw-context-menu");u&&u.remove()})}!a&&n.action&&!n.subMenu&&i.addEventListener("click",r=>{r.stopPropagation(),o(n)}),s.appendChild(i)}return s}function S(l,e,o){l.style.position="fixed",l.style.left=`${e}px`,l.style.top=`${o}px`,l.style.visibility="hidden",l.style.zIndex="10000";const t=l.getBoundingClientRect(),s=window.innerWidth,c=window.innerHeight;let n=e,i=o;e+t.width>s&&(n=e-t.width),o+t.height>c&&(i=o-t.height),n=Math.max(0,n),i=Math.max(0,i),l.style.left=`${n}px`,l.style.top=`${i}px`,l.style.visibility="visible"}const z="getContextMenuItems";let p=null,h=null,b=null,E=0;const C=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:l=>{l.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:l=>{l.grid?.plugins?.export?.exportCsv?.()}}];class I extends g.BaseGridPlugin{static manifest={queries:[{type:z,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:C}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),E++}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")?.[0];return t?t.includes(e)?t:(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 o=this.gridElement;if(!o)return;const t=getComputedStyle(o),s=[],c=t.getPropertyValue("color-scheme").trim();c&&s.push(`color-scheme: ${c}`);for(const n of I.CSS_VARS_TO_COPY){const i=t.getPropertyValue(n).trim();i&&s.push(`${n}: ${i}`)}if(s.length>0){const n=e.getAttribute("style")||"";e.setAttribute("style",n+s.join("; ")+";")}}installGlobalHandlers(){!b&&typeof document<"u"&&typeof x=="string"&&x&&(b=document.createElement("style"),b.id="tbw-context-menu-styles",b.textContent=x,document.head.appendChild(b)),p||(p=()=>{document.querySelectorAll(".tbw-context-menu").forEach(o=>o.remove())},document.addEventListener("click",p)),h||(h=e=>{e.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("keydown",h))}uninstallGlobalHandlers(){E--,!(E>0)&&(p&&(document.removeEventListener("click",p),p=null),h&&(document.removeEventListener("keydown",h),h=null),b&&(b.remove(),b=null))}collectPluginItems(e){if(!this.grid)return[];const o=this.grid.query(z,e),t=[];for(const s of o)Array.isArray(s)&&t.push(...s);return t.sort((s,c)=>(s.order??100)-(c.order??100)),this.insertGroupSeparators(t)}insertGroupSeparators(e){if(e.length<=1)return e;const o=[];let t=-1;for(const s of e){if(s.separator){o.push(s);continue}const c=Math.floor((s.order??100)/10);t>=0&&c!==t&&o.push({id:`__sep-${t}-${c}`,label:"",separator:!0,action:()=>{}}),t=c,o.push(s)}return o}convertPluginItems(e){return e.map(o=>({id:o.id,name:o.label,icon:o.icon,shortcut:o.shortcut,disabled:o.disabled??!1,action:()=>o.action(),separator:o.separator,cssClass:o.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const o=e.querySelector(".tbw-grid-root");o&&o.getAttribute("data-context-menu-bound")!=="true"&&(o.setAttribute("data-context-menu-bound","true"),o.addEventListener("contextmenu",t=>{const s=t;s.preventDefault();const c=s.target,n=c.closest("[data-row][data-col]"),i=c.closest('[part~="header-cell"]');let a;if(n){const u=parseInt(n.getAttribute("data-row")??"-1",10),f=parseInt(n.getAttribute("data-col")??"-1",10),d=this.visibleColumns[f],A=this.rows[u],H=this.syncSelectionOnContextMenu(u);a={row:A,rowIndex:u,column:d,columnIndex:f,field:d?.field??"",value:A?.[d?.field]??null,isHeader:!1,event:s,selectedRows:H}}else if(i){const u=parseInt(i.getAttribute("data-col")??"-1",10),f=this.visibleColumns[u];a={row:null,rowIndex:-1,column:f,columnIndex:u,field:f?.field??"",value:null,isHeader:!0,event:s,selectedRows:[]}}else return;this.params=a,this.position={x:s.clientX,y:s.clientY};const w=this.collectPluginItems(a);let r=v(this.config.items??C,a);if(w.length>0){const u=this.convertPluginItems(w);r.length>0&&u.length>0?r=[...r,{id:"__plugin-sep",name:"",separator:!0},...u]:r=[...r,...u]}r=M(r),r.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=y(r,a,u=>{u.action&&u.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,s.clientX,s.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:r}))}))}showMenu(e,o,t){const s={row:t.row??null,rowIndex:t.rowIndex??-1,column:t.column??null,columnIndex:t.columnIndex??-1,field:t.field??"",value:t.value??null,isHeader:t.isHeader??!1,event:t.event??new MouseEvent("contextmenu"),selectedRows:t.selectedRows??[]},c=this.collectPluginItems(s);let n=v(this.config.items??C,s);if(c.length>0){const i=this.convertPluginItems(c);n.length>0&&i.length>0?n=[...n,{id:"__plugin-sep",name:"",separator:!0},...i]:n=[...n,...i]}n=M(n),this.menuElement&&this.menuElement.remove(),this.menuElement=y(n,s,i=>{i.action&&i.action(s),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,e,o),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}m.ContextMenuPlugin=I,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(b,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],g):(b=typeof globalThis<"u"?globalThis:b||self,g(b.TbwGridPlugin_contextMenu={},b.TbwGrid,b.TbwGrid))})(this,(function(b,g,O){"use strict";const x="@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 v(l,e){return(typeof l=="function"?l(e):l).filter(t=>!(t.hidden===!0||typeof t.hidden=="function"&&t.hidden(e)))}function M(l){const e=[];for(const o of l)o.separator&&(e.length===0||e[e.length-1].separator)||e.push(o);return e.length>0&&e[e.length-1].separator&&e.pop(),e}function T(l,e){return l.disabled===!0?!0:typeof l.disabled=="function"?l.disabled(e):!1}function y(l,e,o,t=O.DEFAULT_GRID_ICONS.submenuArrow){const s=document.createElement("div");s.className="tbw-context-menu",s.setAttribute("role","menu");const u=l.some(n=>!n.separator&&n.icon);for(const n of l){if(n.separator){const r=document.createElement("div");r.className="tbw-context-menu-separator",r.setAttribute("role","separator"),s.appendChild(r);continue}const i=document.createElement("div");i.className="tbw-context-menu-item",n.cssClass&&i.classList.add(n.cssClass),i.setAttribute("role","menuitem"),i.setAttribute("data-id",n.id);const d=T(n,e);if(d&&(i.classList.add("disabled"),i.setAttribute("aria-disabled","true")),n.icon){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=n.icon,i.appendChild(r)}else if(u){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=" ",i.appendChild(r)}const w=document.createElement("span");if(w.className="tbw-context-menu-label",w.textContent=n.name,i.appendChild(w),n.shortcut){const r=document.createElement("span");if(r.className="tbw-context-menu-shortcut",Array.isArray(n.shortcut))n.shortcut.forEach((c,m)=>{m>0&&r.appendChild(document.createTextNode("+"));const a=document.createElement("kbd");a.textContent=c,r.appendChild(a)});else{const c=document.createElement("kbd");c.textContent=n.shortcut,r.appendChild(c)}i.appendChild(r)}if(n.subMenu?.length){const r=document.createElement("span");r.className="tbw-context-menu-arrow",typeof t=="string"?r.innerHTML=t:t instanceof HTMLElement&&r.appendChild(t.cloneNode(!0)),i.appendChild(r),i.addEventListener("mouseenter",()=>{if(i.querySelector(".tbw-context-menu")||!n.subMenu)return;const m=v(n.subMenu,e),a=y(m,e,o,t);a.classList.add("tbw-context-submenu"),a.style.position="absolute",a.style.left="100%",a.style.top="0",i.style.position="relative",i.appendChild(a)}),i.addEventListener("mouseleave",()=>{const c=i.querySelector(".tbw-context-menu");c&&c.remove()})}!d&&n.action&&!n.subMenu&&i.addEventListener("click",r=>{r.stopPropagation(),o(n)}),s.appendChild(i)}return s}function S(l,e,o){l.style.position="fixed",l.style.left=`${e}px`,l.style.top=`${o}px`,l.style.visibility="hidden",l.style.zIndex="10000";const t=l.getBoundingClientRect(),s=window.innerWidth,u=window.innerHeight;let n=e,i=o;e+t.width>s&&(n=e-t.width),o+t.height>u&&(i=o-t.height),n=Math.max(0,n),i=Math.max(0,i),l.style.left=`${n}px`,l.style.top=`${i}px`,l.style.visibility="visible"}const z="getContextMenuItems";let f=null,h=null,p=null,E=0;const C=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:l=>{l.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:l=>{l.grid?.plugins?.export?.exportCsv?.()}}];class I extends g.BaseGridPlugin{static manifest={queries:[{type:z,description:"Collects context menu items from other plugins for header right-click menus"}]};name="contextMenu";get defaultConfig(){return{items:C}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(e){super.attach(e),this.installGlobalHandlers(),E++}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")?.[0];return t?t.includes(e)?t:(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 o=this.gridElement;if(!o)return;const t=getComputedStyle(o),s=[],u=t.getPropertyValue("color-scheme").trim();u&&s.push(`color-scheme: ${u}`);for(const n of I.CSS_VARS_TO_COPY){const i=t.getPropertyValue(n).trim();i&&s.push(`${n}: ${i}`)}if(s.length>0){const n=e.getAttribute("style")||"";e.setAttribute("style",n+s.join("; ")+";")}}installGlobalHandlers(){!p&&typeof document<"u"&&typeof x=="string"&&x&&(p=document.createElement("style"),p.id="tbw-context-menu-styles",p.textContent=x,document.head.appendChild(p)),f||(f=()=>{document.querySelectorAll(".tbw-context-menu").forEach(o=>o.remove())},document.addEventListener("click",f)),h||(h=e=>{e.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("keydown",h))}uninstallGlobalHandlers(){E--,!(E>0)&&(f&&(document.removeEventListener("click",f),f=null),h&&(document.removeEventListener("keydown",h),h=null),p&&(p.remove(),p=null))}collectPluginItems(e){if(!this.grid)return[];const o=this.grid.query(z,e),t=[];for(const s of o)Array.isArray(s)&&t.push(...s);return t.sort((s,u)=>(s.order??100)-(u.order??100)),this.insertGroupSeparators(t)}insertGroupSeparators(e){if(e.length<=1)return e;const o=[];let t=-1;for(const s of e){if(s.separator){o.push(s);continue}const u=Math.floor((s.order??100)/10);t>=0&&u!==t&&o.push({id:`__sep-${t}-${u}`,label:"",separator:!0,action:()=>{}}),t=u,o.push(s)}return o}convertPluginItems(e){return e.map(o=>({id:o.id,name:o.label,icon:o.icon,shortcut:o.shortcut,disabled:o.disabled??!1,action:()=>o.action(),separator:o.separator,cssClass:o.cssClass}))}afterRender(){const e=this.gridElement;if(!e)return;const o=e.querySelector(".tbw-grid-root");o&&o.getAttribute("data-context-menu-bound")!=="true"&&(o.setAttribute("data-context-menu-bound","true"),o.addEventListener("contextmenu",t=>{const s=t;s.preventDefault();const u=s.target,n=u.closest("[data-row][data-col]"),i=u.closest('[part~="header-cell"]');let d;if(n){const c=parseInt(n.getAttribute("data-row")??"-1",10),m=parseInt(n.getAttribute("data-col")??"-1",10),a=this.visibleColumns[m],A=this.rows[c],_=this.syncSelectionOnContextMenu(c);d={row:A,rowIndex:c,column:a,columnIndex:m,field:a?.field??"",value:A?.[a?.field]??null,isHeader:!1,event:s,selectedRows:_}}else if(i){const c=parseInt(i.getAttribute("data-col")??"-1",10),m=this.visibleColumns[c];d={row:null,rowIndex:-1,column:m,columnIndex:c,field:m?.field??"",value:null,isHeader:!0,event:s,selectedRows:[]}}else return;this.params=d,this.position={x:s.clientX,y:s.clientY};const w=this.collectPluginItems(d);let r=v(this.config.items??C,d);if(w.length>0){const c=this.convertPluginItems(w);r.length>0&&c.length>0?r=[...r,{id:"__plugin-sep",name:"",separator:!0},...c]:r=[...r,...c]}r=M(r),r.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=y(r,d,c=>{c.action&&c.action(d),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,s.clientX,s.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:d,items:r}))}))}showMenu(e,o,t){const s={row:t.row??null,rowIndex:t.rowIndex??-1,column:t.column??null,columnIndex:t.columnIndex??-1,field:t.field??"",value:t.value??null,isHeader:t.isHeader??!1,event:t.event??new MouseEvent("contextmenu"),selectedRows:t.selectedRows??[]},u=this.collectPluginItems(s);let n=v(this.config.items??C,s);if(u.length>0){const i=this.convertPluginItems(u);n.length>0&&i.length>0?n=[...n,{id:"__plugin-sep",name:"",separator:!0},...i]:n=[...n,...i]}n=M(n),this.menuElement&&this.menuElement.remove(),this.menuElement=y(n,s,i=>{i.action&&i.action(s),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),S(this.menuElement,e,o),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}b.ContextMenuPlugin=I,Object.defineProperty(b,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\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 = ' ';\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 shortcut.textContent = item.shortcut;\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 * 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 { buildMenuItems, collapseSeparators, createMenuElement, positionMenu } 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/** Global click handler reference for cleanup */\nlet globalClickHandler: ((e: Event) => void) | null = null;\n/** Global keydown handler reference for cleanup */\nlet globalKeydownHandler: ((e: KeyboardEvent) => void) | 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 // Close menu on click outside\n if (!globalClickHandler) {\n globalClickHandler = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n document.addEventListener('click', globalClickHandler);\n }\n\n // Close on escape\n if (!globalKeydownHandler) {\n globalKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n }\n };\n document.addEventListener('keydown', globalKeydownHandler);\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 - clean up all global resources\n if (globalClickHandler) {\n document.removeEventListener('click', globalClickHandler);\n globalClickHandler = null;\n }\n if (globalKeydownHandler) {\n document.removeEventListener('keydown', globalKeydownHandler);\n globalKeydownHandler = 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 /** @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.params = params;\n this.position = { x: event.clientX, y: event.clientY };\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 // Add separator between configured and plugin items\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 if (this.menuElement) {\n this.menuElement.remove();\n }\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 document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, event.clientX, event.clientY);\n this.isOpen = true;\n\n this.emit('context-menu-open', { params, items });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param params - Partial context menu parameters\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 const pluginItems = this.collectPluginItems(fullParams);\n let items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\n\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 (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n fullParams,\n (item) => {\n if (item.action) item.action(fullParams);\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n }\n\n /**\n * Hide the context menu.\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 * @returns Whether the menu is open\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","item","collapseSeparators","result","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","hasAnyIcon","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","QUERY_GET_CONTEXT_MENU_ITEMS","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","rowIndex","currentSelection","menuElement","gridEl","computed","styles","colorScheme","varName","value","existing","contextMenuStyles","responses","response","a","b","lastGroup","group","container","event","target","cell","header","colIndex","column","row","selectedRows","pluginItems","converted","fullParams"],"mappings":"gkE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OAAS,EAChB,EACA,KAAK,UAAU,YAAA,EAGjB,SAAS,KAAK,YAAY,KAAK,WAAW,EAC1C,KAAK,eAAe,KAAK,WAAW,EACpC7C,EAAa,KAAK,YAAaC,EAAGC,CAAC,EACnC,KAAK,OAAS,EAChB,CAKA,UAAiB,CACX,KAAK,cACP,KAAK,YAAY,OAAA,EACjB,KAAK,YAAc,KACnB,KAAK,OAAS,GAElB,CAMA,YAAsB,CACpB,OAAO,KAAK,MACd,CAIF"}
|
|
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\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 = ' ';\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 * 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 { buildMenuItems, collapseSeparators, createMenuElement, positionMenu } 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/** Global click handler reference for cleanup */\nlet globalClickHandler: ((e: Event) => void) | null = null;\n/** Global keydown handler reference for cleanup */\nlet globalKeydownHandler: ((e: KeyboardEvent) => void) | 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 // Close menu on click outside\n if (!globalClickHandler) {\n globalClickHandler = () => {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n };\n document.addEventListener('click', globalClickHandler);\n }\n\n // Close on escape\n if (!globalKeydownHandler) {\n globalKeydownHandler = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n const menus = document.querySelectorAll('.tbw-context-menu');\n menus.forEach((menu) => menu.remove());\n }\n };\n document.addEventListener('keydown', globalKeydownHandler);\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 - clean up all global resources\n if (globalClickHandler) {\n document.removeEventListener('click', globalClickHandler);\n globalClickHandler = null;\n }\n if (globalKeydownHandler) {\n document.removeEventListener('keydown', globalKeydownHandler);\n globalKeydownHandler = 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 /** @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.params = params;\n this.position = { x: event.clientX, y: event.clientY };\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 // Add separator between configured and plugin items\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 if (this.menuElement) {\n this.menuElement.remove();\n }\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 document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, event.clientX, event.clientY);\n this.isOpen = true;\n\n this.emit('context-menu-open', { params, items });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Programmatically show the context menu at the specified position.\n * @param x - X coordinate\n * @param y - Y coordinate\n * @param params - Partial context menu parameters\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 const pluginItems = this.collectPluginItems(fullParams);\n let items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\n\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 (this.menuElement) {\n this.menuElement.remove();\n }\n\n this.menuElement = createMenuElement(\n items,\n fullParams,\n (item) => {\n if (item.action) item.action(fullParams);\n this.menuElement?.remove();\n this.menuElement = null;\n this.isOpen = false;\n },\n this.gridIcons.submenuArrow,\n );\n\n document.body.appendChild(this.menuElement);\n this.copyGridStyles(this.menuElement);\n positionMenu(this.menuElement, x, y);\n this.isOpen = true;\n }\n\n /**\n * Hide the context menu.\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 * @returns Whether the menu is open\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","item","collapseSeparators","result","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","hasAnyIcon","separator","menuItem","disabled","icon","label","shortcut","key","i","kbd","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","QUERY_GET_CONTEXT_MENU_ITEMS","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","rowIndex","currentSelection","menuElement","gridEl","computed","styles","colorScheme","varName","value","existing","contextMenuStyles","responses","response","a","b","lastGroup","group","container","event","target","cell","header","colIndex","column","row","selectedRows","pluginItems","converted","fullParams"],"mappings":"okEAiBO,SAASA,EACdC,EACAC,EACmB,CAGnB,OAFkB,OAAOD,GAAU,WAAaA,EAAMC,CAAM,EAAID,GAE/C,OAAQE,GACnB,EAAAA,EAAK,SAAW,IAChB,OAAOA,EAAK,QAAW,YAAcA,EAAK,OAAOD,CAAM,EAE5D,CACH,CAQO,SAASE,EAAmBH,EAA6C,CAC9E,MAAMI,EAA4B,CAAA,EAClC,UAAWF,KAAQF,EACbE,EAAK,YAEHE,EAAO,SAAW,GAAKA,EAAOA,EAAO,OAAS,CAAC,EAAE,YAEvDA,EAAO,KAAKF,CAAI,EAGlB,OAAIE,EAAO,OAAS,GAAKA,EAAOA,EAAO,OAAS,CAAC,EAAE,WACjDA,EAAO,IAAA,EAEFA,CACT,CASO,SAASC,EAAeH,E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ACnC,KAAK,OAAS,EAChB,CAKA,UAAiB,CACX,KAAK,cACP,KAAK,YAAY,OAAA,EACjB,KAAK,YAAc,KACnB,KAAK,OAAS,GAElB,CAMA,YAAsB,CACpB,OAAO,KAAK,MACd,CAIF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(v,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("../../core/internal/keyboard"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/rows","../../core/plugin/base-plugin"],y):(v=typeof globalThis<"u"?globalThis:v||self,y(v.TbwGridPlugin_editing={},v.TbwGrid,v.TbwGrid,v.TbwGrid))})(this,(function(v,y,b,q){"use strict";const P="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";function B(l){const e=l.options;return e?typeof e=="function"?e():e:[]}function D(l){return e=>{const t=l.editorParams,i=document.createElement("input");i.type="number",i.value=e.value!=null?String(e.value):"",t?.min!==void 0&&(i.min=String(t.min)),t?.max!==void 0&&(i.max=String(t.max)),t?.step!==void 0&&(i.step=String(t.step)),t?.placeholder&&(i.placeholder=t.placeholder);const s=()=>e.commit(i.value===""?null:Number(i.value));return i.addEventListener("blur",s),i.addEventListener("keydown",n=>{n.key==="Enter"&&s(),n.key==="Escape"&&e.cancel()}),i}}function M(){return l=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!l.value,e.addEventListener("change",()=>l.commit(e.checked)),e}}function H(l){return e=>{const t=l.editorParams,i=document.createElement("input");i.type="date",e.value instanceof Date?i.valueAsDate=e.value:typeof e.value=="string"&&e.value&&(i.value=e.value.split("T")[0]),t?.min&&(i.min=t.min),t?.max&&(i.max=t.max),t?.placeholder&&(i.placeholder=t.placeholder);const s=()=>{typeof e.value=="string"?e.commit(i.value):e.commit(i.valueAsDate)};return i.addEventListener("change",s),i.addEventListener("keydown",n=>{n.key==="Escape"&&e.cancel()}),i}}function $(l){return e=>{const t=l.editorParams,i=document.createElement("select");if(l.multi&&(i.multiple=!0),t?.includeEmpty){const r=document.createElement("option");r.value="",r.textContent=t.emptyLabel??"",i.appendChild(r)}B(l).forEach(r=>{const o=document.createElement("option");o.value=String(r.value),o.textContent=r.label,(l.multi&&Array.isArray(e.value)&&e.value.includes(r.value)||!l.multi&&e.value===r.value)&&(o.selected=!0),i.appendChild(o)});const n=()=>{if(l.multi){const r=Array.from(i.selectedOptions).map(o=>o.value);e.commit(r)}else e.commit(i.value)};return i.addEventListener("change",n),i.addEventListener("blur",n),i.addEventListener("keydown",r=>{r.key==="Escape"&&e.cancel()}),i}}function x(l){return e=>{const t=l.editorParams,i=document.createElement("input");i.type="text",i.value=e.value!=null?String(e.value):"",t?.maxLength!==void 0&&(i.maxLength=t.maxLength),t?.pattern&&(i.pattern=t.pattern),t?.placeholder&&(i.placeholder=t.placeholder);const s=()=>{const n=i.value;(e.value===null||e.value===void 0)&&n===""||typeof e.value=="string"&&n===e.value.replace(/[\n\r]/g,"")||(typeof e.value=="number"&&n!==""?e.commit(Number(n)):e.commit(n))};return i.addEventListener("blur",s),i.addEventListener("keydown",n=>{n.key==="Enter"&&s(),n.key==="Escape"&&e.cancel()}),i}}function A(l){switch(l.type){case"number":return D(l);case"boolean":return M();case"date":return H(l);case"select":return $(l);default:return x(l)}}function G(l,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const i=l.effectiveConfig?.typeDefaults;if(i?.[e.type]?.editor)return i[e.type].editor;const s=l.__frameworkAdapter;if(s?.getTypeDefault){const n=s.getTypeDefault(e.type);if(n?.editor)return n.editor}}function k(l){return!(typeof l!="string"||l==="__proto__"||l==="constructor"||l==="prototype")}function F(l){const e=(l.__editingCellCount??0)+1;l.__editingCellCount=e,l.setAttribute("data-has-editing","")}function N(l){l.__editingCellCount=0,l.removeAttribute("data-has-editing")}function R(l,e,t){return l instanceof HTMLInputElement?l.type==="checkbox"?l.checked:l.type==="number"?l.value===""?null:Number(l.value):l.type==="date"?typeof t=="string"?l.value:l.valueAsDate:typeof t=="number"?l.value===""?null:Number(l.value):t==null&&l.value===""||typeof t=="string"&&l.value===t.replace(/[\n\r]/g,"")?t:l.value:e?.type==="number"&&l.value!==""||typeof t=="number"&&l.value!==""?Number(l.value):t==null&&l.value===""?t:l.value}function O(l){}function j(l,e,t,i){const s=l.querySelector("input,textarea,select");s&&(s.addEventListener("blur",()=>{t(R(s,e,i))}),s instanceof HTMLInputElement&&s.type==="checkbox"?s.addEventListener("change",()=>t(s.checked)):s instanceof HTMLSelectElement&&s.addEventListener("change",()=>t(R(s,e,i))))}class U extends q.BaseGridPlugin{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>e===!0},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles=P;get defaultConfig(){return{mode:"row",editOn:"click"}}get#t(){return this.config.mode==="grid"}#e=-1;#u=-1;#l=new Map;#s=new Set;#o=new Set;#a=new Map;#f=!1;#h=-1;#i=new Map;#r=!1;#c=!1;#d=!1;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=s=>this.resetChangedRows(s),e.beginBulkEdit=(s,n)=>{n&&this.beginCellEdit(s,n)},document.addEventListener("keydown",s=>{if(!this.#t&&s.key==="Escape"&&this.#e!==-1){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(s)===!1)return;this.#n(this.#e,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",s=>{if(this.#t||this.#e===-1)return;const n=i.findRenderedRowElement?.(this.#e);!n||(s.composedPath&&s.composedPath()||[]).includes(n)||this.config.onBeforeEditClose&&this.config.onBeforeEditClose(s)===!1||queueMicrotask(()=>{this.#e!==-1&&this.#n(this.#e,!1)})},{signal:t}),this.gridElement.addEventListener("cell-change",s=>{const n=s.detail;if(n.source==="user")return;const r=`${n.rowIndex}:${n.field}`,o=this.#a.get(r);o&&o(n.newValue)},{signal:t}),this.#t&&(this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",s=>{const n=s.target;if(n.matches(b.FOCUSABLE_EDITOR_SELECTOR)){if(this.#c){n.blur(),this.gridElement.focus();return}this.#r=!0}},{signal:t}),this.gridElement.addEventListener("focusout",s=>{const n=s.relatedTarget;(!n||!this.gridElement.contains(n)||!n.matches(b.FOCUSABLE_EDITOR_SELECTOR))&&(this.#r=!1)},{signal:t}),this.gridElement.addEventListener("keydown",s=>{if(s.key==="Escape"&&this.#r){const n=document.activeElement;n&&this.gridElement.contains(n)&&(n.blur(),this.gridElement.focus()),this.#r=!1,this.#c=!0,s.preventDefault(),s.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",s=>{s.target.matches(b.FOCUSABLE_EDITOR_SELECTOR)&&(this.#c=!1)},{signal:t}))}detach(){this.gridElement.classList.remove("tbw-grid-mode"),this.#e=-1,this.#u=-1,this.#l.clear(),this.#s.clear(),this.#o.clear(),this.#a.clear(),this.#r=!1,this.#c=!1,this.#d=!1,super.detach()}handleQuery(e){if(e.type==="isEditing")return this.#t||this.#e!==-1}onCellClick(e){if(this.#t)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual"||i!=="click"&&i!=="dblclick")return!1;const s=e.originalEvent.type==="dblclick";if(i==="click"&&s||i==="dblclick"&&!s)return!1;const{rowIndex:n}=e;return t._columns?.some(o=>o.editable)?(e.originalEvent.stopPropagation(),this.beginBulkEdit(n),!0):!1}onKeyDown(e){const t=this.grid;if(e.key==="Escape"){if(this.#t&&this.#r){const i=document.activeElement;return i&&this.gridElement.contains(i)&&i.blur(),this.#r=!1,this.requestAfterRender(),!0}if(this.#e!==-1&&!this.#t)return this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1||this.#n(this.#e,!0),!0}if(this.#t&&!this.#r&&(e.key==="ArrowUp"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return!1;if((e.key==="ArrowUp"||e.key==="ArrowDown")&&this.#e!==-1&&!this.#t){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=t._rows.length-1,s=this.#e;return this.#n(s,!1),e.key==="ArrowDown"?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),y.ensureCellVisible(t),this.requestAfterRender(),!0}if(e.key==="Tab"&&(this.#e!==-1||this.#t)){if(e.preventDefault(),this.#d)return this.#n(this.#e,!1),!0;const i=!e.shiftKey;return this.#C(i),!0}if(e.key===" "||e.key==="Spacebar"){if(this.#e!==-1)return!1;const i=t._focusRow,s=t._focusCol;if(i>=0&&s>=0){const n=t._visibleColumns[s],r=t._rows[i];if(n?.editable&&n.type==="boolean"&&r){const o=n.field;if(k(o)){const c=!r[o];return this.#m(i,n,c,r),e.preventDefault(),this.requestRender(),!0}}}return!1}if(e.key==="Enter"&&!e.shiftKey){if(this.#t&&!this.#r)return this.#y(),!0;if(this.#e!==-1)return!!(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1);const i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual")return!1;const s=t._focusRow,n=t._focusCol;if(s>=0&&t._columns?.some(o=>o.editable)){const o=t._visibleColumns[n],a=t._rows[s],c=o?.field??"",d=c&&a?a[c]:void 0,E=this.gridElement.querySelector(`[data-row="${s}"][data-col="${n}"]`),h=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:s,colIndex:n,field:c,value:d,row:a,cellEl:E,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(h);const m=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:s,col:n}});return this.gridElement.dispatchEvent(m),h.defaultPrevented||m.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(s),!0)}return!1}if(e.key==="F2"){if(this.#e!==-1||this.#t||(this.config.editOn??t.effectiveConfig?.editOn)===!1)return!1;const s=t._focusRow,n=t._focusCol;if(s>=0&&n>=0){const r=t._visibleColumns[n];if(r?.editable&&r.field)return e.preventDefault(),this.beginCellEdit(s,r.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,s=t.__frameworkAdapter;return!i&&!s?.getTypeDefault?e:e.map(n=>{if(!n.type)return n;let r;if(i?.[n.type]?.editorParams&&(r=i[n.type].editorParams),!r&&s?.getTypeDefault){const o=s.getTypeDefault(n.type);o?.editorParams&&(r=o.editorParams)}return r?{...n,editorParams:{...r,...n.editorParams}}:n})}afterRender(){const e=this.grid;if(this.#f&&(this.#f=!1,this.#v(e)),this.#h!==-1){const t=this.#h;this.#h=-1,e.animateRow?.(t,"change")}if(!this.#t&&this.#o.size!==0)for(const t of this.#o){const[i,s]=t.split(":"),n=parseInt(i,10),r=parseInt(s,10),o=e.findRenderedRowElement?.(n);if(!o)continue;const a=o.querySelector(`.cell[data-col="${r}"]`);if(!a||a.classList.contains("editing"))continue;const c=e._rows[n],d=e._visibleColumns[r];c&&d&&this.#E(c,n,d,r,a,!0)}}afterCellRender(e){if(!this.#t)return;const{row:t,rowIndex:i,column:s,colIndex:n,cellElement:r}=e;s.editable&&(r.classList.contains("editing")||this.#E(t,i,s,n,r,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#s){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#s)}get activeEditRow(){return this.#e}get activeEditCol(){return this.#u}isRowEditing(e){return this.#e===e}isCellEditing(e,t){return this.#o.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const s=t.getRowId?.(i);return s?this.#s.has(s):!1}catch{return!1}}isRowChangedById(e){return this.#s.has(e)}setInvalid(e,t,i=""){let s=this.#i.get(e);s||(s=new Map,this.#i.set(e,s)),s.set(t,i),this.#g(e,t,!0)}clearInvalid(e,t){const i=this.#i.get(e);i&&(i.delete(t),i.size===0&&this.#i.delete(e)),this.#g(e,t,!1)}clearRowInvalid(e){const t=this.#i.get(e);if(t){const i=Array.from(t.keys());this.#i.delete(e),i.forEach(s=>this.#g(e,s,!1))}}clearAllInvalid(){const e=Array.from(this.#i.entries());this.#i.clear(),e.forEach(([t,i])=>{i.forEach((s,n)=>this.#g(t,n,!1))})}isCellInvalid(e,t){return this.#i.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#i.get(e)?.get(t)}hasInvalidCells(e){const t=this.#i.get(e);return t?t.size>0:!1}getInvalidFields(e){return new Map(this.#i.get(e)??[])}#g(e,t,i){const s=this.grid,n=s._visibleColumns?.findIndex(d=>d.field===t);if(n===-1||n===void 0)return;const o=s._rows?.findIndex(d=>{try{return s.getRowId?.(d)===e}catch{return!1}});if(o===-1||o===void 0)return;const c=s.findRenderedRowElement?.(o)?.querySelector(`.cell[data-col="${n}"]`);if(c)if(i){c.setAttribute("data-invalid","true");const d=this.#i.get(e)?.get(t);d&&c.setAttribute("title",d)}else c.removeAttribute("data-invalid"),c.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#s.clear(),this.#p(),e||this.emit("changed-rows-reset",{rows:t,ids:i}),this.grid._rowPool?.forEach(n=>n.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,s=i._visibleColumns.findIndex(a=>a.field===t);if(s===-1||!i._visibleColumns[s]?.editable)return;const o=i.findRenderedRowElement?.(e)?.querySelector(`.cell[data-col="${s}"]`);o&&(this.#d=!0,this.#b(e,s,o))}beginBulkEdit(e){const t=this.grid;if((this.config.editOn??t.effectiveConfig?.editOn)===!1||!t._columns?.some(o=>o.editable))return;const n=t.findRenderedRowElement?.(e);if(!n)return;this.#d=!1;const r=t._rows[e];this.#w(e,r),Array.from(n.children).forEach((o,a)=>{const c=t._visibleColumns[a];if(c?.editable){const d=o;d.classList.contains("editing")||this.#E(r,e,c,a,d,!0)}}),setTimeout(()=>{let o=n.querySelector(`.cell[data-col="${t._focusCol}"]`);if(o?.classList.contains("editing")||(o=n.querySelector(".cell.editing")),o?.classList.contains("editing")){const a=o.querySelector(b.FOCUSABLE_EDITOR_SELECTOR);try{a?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){this.#e!==-1&&this.#n(this.#e,!1)}cancelActiveRowEdit(){this.#e!==-1&&this.#n(this.#e,!0)}#b(e,t,i){const s=this.grid,n=s._rows[e],r=s._visibleColumns[t];!n||!r?.editable||i.classList.contains("editing")||(this.#e!==e&&this.#w(e,n),this.#u=t,this.#E(n,e,r,t,i,!1))}#y(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const n=e.findRenderedRowElement?.(t)?.querySelector(`.cell[data-col="${i}"]`);if(n?.classList.contains("editing")){const r=n.querySelector(b.FOCUSABLE_EDITOR_SELECTOR);r&&(this.#c=!1,r.focus(),this.#r=!0,r instanceof HTMLInputElement&&(r.type==="text"||r.type==="number")&&r.select())}}#C(e){const t=this.grid,i=t._rows,s=this.#t?t._focusRow:this.#e,n=t._visibleColumns.map((c,d)=>c.editable?d:-1).filter(c=>c>=0);if(n.length===0)return;const o=n.indexOf(t._focusCol)+(e?1:-1);if(o>=0&&o<n.length){t._focusCol=n[o];const d=t.findRenderedRowElement?.(s)?.querySelector(`.cell[data-col="${n[o]}"]`);d?.classList.contains("editing")&&d.querySelector(b.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0}),y.ensureCellVisible(t,{forceHorizontalScroll:!0});return}const a=s+(e?1:-1);a>=0&&a<i.length&&(this.#t?(t._focusRow=a,t._focusCol=e?n[0]:n[n.length-1],y.ensureCellVisible(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const d=t.findRenderedRowElement?.(a)?.querySelector(`.cell[data-col="${t._focusCol}"]`);d?.classList.contains("editing")&&d.querySelector(b.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0})},0)):(this.#n(s,!1),t._focusRow=a,t._focusCol=e?n[0]:n[n.length-1],this.beginBulkEdit(a),y.ensureCellVisible(t,{forceHorizontalScroll:!0})))}#p(){const e=this.grid;e._activeEditRows=this.#e,e._rowEditSnapshots=this.#l}#w(e,t){if(this.#e!==e&&(this.#l.set(e,{...t}),this.#e=e,this.#p(),!this.#t)){const i=this.grid;let s="";try{s=i.getRowId?.(t)??""}catch{}this.emit("edit-open",{rowIndex:e,rowId:s,row:t})}}#n(e,t){if(this.#e!==e)return;const i=this.grid,s=this.#l.get(e),n=i._rows[e],r=i.findRenderedRowElement?.(e);let o;if(n)try{o=i.getRowId?.(n)}catch{}if(!t&&r&&n&&r.querySelectorAll(".cell.editing").forEach(c=>{const d=Number(c.getAttribute("data-col"));if(isNaN(d))return;const E=i._visibleColumns[d];if(!E||c.hasAttribute("data-editor-managed"))return;const h=c.querySelector("input,textarea,select");if(h){const m=E.field,g=n[m],p=R(h,E,g);g!==p&&this.#m(e,E,p,n)}}),t&&s&&n)Object.keys(s).forEach(a=>{n[a]=s[a]}),o&&(this.#s.delete(o),this.clearRowInvalid(o));else if(!t&&n){const a=this.#_(s,n),c=o?this.#s.has(o):a,d=this.emitCancelable("row-commit",{rowIndex:e,rowId:o??"",row:n,oldValue:s,newValue:n,changed:c,changedRows:this.changedRows,changedRowIds:this.changedRowIds});d&&s?(Object.keys(s).forEach(E=>{n[E]=s[E]}),o&&(this.#s.delete(o),this.clearRowInvalid(o))):!d&&a&&this.isAnimationEnabled&&(this.#h=e)}this.#l.delete(e),this.#e=-1,this.#u=-1,this.#d=!1,this.#p();for(const a of this.#o)a.startsWith(`${e}:`)&&this.#o.delete(a);for(const a of this.#a.keys())a.startsWith(`${e}:`)&&this.#a.delete(a);r&&(r.querySelectorAll(".cell.editing").forEach(a=>{a.classList.remove("editing"),N(a.parentElement)}),this.requestRender()),this.#f=!0,r||(this.#v(i),this.#f=!1),!this.#t&&n&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:n,reverted:t})}#m(e,t,i,s){const n=t.field;if(!k(n))return;const r=s[n];if(r===i)return;const o=this.grid;let a;try{a=this.grid.getRowId(s)}catch{}const c=a?!this.#s.has(a):!0,d=a?p=>this.grid.updateRow(a,p,"cascade"):O;let E=!1;const h=a?p=>{E=!0,this.setInvalid(a,n,p??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:s,rowId:a??"",field:n,oldValue:r,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:c,updateRow:d,setInvalid:h}))return;a&&!E&&this.isCellInvalid(a,n)&&this.clearInvalid(a,n),s[n]=i,a&&this.#s.add(a),this.#p(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:n,oldValue:r,newValue:i});const g=o.findRenderedRowElement?.(e);g&&g.classList.add("changed")}#E(e,t,i,s,n,r){if(!i.editable||n.classList.contains("editing"))return;let o;try{o=this.grid.getRowId(e)}catch{}const a=o?u=>this.grid.updateRow(o,u,"cascade"):O,c=k(i.field)?e[i.field]:void 0;n.classList.add("editing"),this.#o.add(`${t}:${s}`);const d=n.parentElement;d&&F(d);let E=!1;const h=u=>{E||!this.#t&&this.#e===-1||this.#m(t,i,u,e)},m=()=>{E=!0,k(i.field)&&(e[i.field]=c)},g=document.createElement("div");g.className="tbw-editor-host",n.innerHTML="",n.appendChild(g),g.addEventListener("keydown",u=>{if(u.key==="Enter"){if(this.#t){u.stopPropagation(),u.preventDefault();const f=g.querySelector("input,textarea,select");f&&h(R(f,i,c));return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(u)===!1)return;u.stopPropagation(),u.preventDefault(),E=!0,this.#n(t,!1)}if(u.key==="Escape"){if(this.#t){u.stopPropagation(),u.preventDefault();return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(u)===!1)return;u.stopPropagation(),u.preventDefault(),m(),this.#n(t,!0)}});const p=i,_=p.__editorTemplate,w=G(this.grid,p)??A(i),T=c,z=`${t}:${i.field}`,I=[];this.#a.set(z,u=>{for(const f of I)f(u)});const S=u=>{I.push(u)};if(w==="template"&&_)this.#R(g,p,e,c,h,m,r,t),S(u=>{const f=g.querySelector("input,textarea,select");f&&(f instanceof HTMLInputElement&&f.type==="checkbox"?f.checked=!!u:f.value=String(u??""))});else if(typeof w=="string"){const u=document.createElement(w);u.value=T,u.addEventListener("change",()=>h(u.value)),S(f=>{u.value=f}),g.appendChild(u),r||queueMicrotask(()=>{g.querySelector(b.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0})})}else if(typeof w=="function"){const u={row:e,rowId:o??"",value:T,field:i.field,column:i,commit:h,cancel:m,updateRow:a,onValueChange:S},f=w(u);typeof f=="string"?(g.innerHTML=f,j(g,i,h,c),S(L=>{const C=g.querySelector("input,textarea,select");C&&(C instanceof HTMLInputElement&&C.type==="checkbox"?C.checked=!!L:C.value=String(L??""))})):f instanceof Node&&(g.appendChild(f),f instanceof HTMLInputElement||f instanceof HTMLSelectElement||f instanceof HTMLTextAreaElement?S(C=>{f instanceof HTMLInputElement&&f.type==="checkbox"?f.checked=!!C:f.value=String(C??"")}):n.setAttribute("data-editor-managed","")),r||queueMicrotask(()=>{g.querySelector(b.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0})})}else if(w&&typeof w=="object"){const u=document.createElement("div");u.setAttribute("data-external-editor",""),u.setAttribute("data-field",i.field),g.appendChild(u),n.setAttribute("data-editor-managed","");const f={row:e,rowId:o??"",value:T,field:i.field,column:i,commit:h,cancel:m,updateRow:a,onValueChange:S};if(w.mount)try{w.mount({placeholder:u,context:f,spec:w})}catch(L){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,L)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:u,spec:w,context:f}}))}}#R(e,t,i,s,n,r,o,a){const c=t.__editorTemplate;if(!c)return;const d=c.cloneNode(!0),E=t.__compiledEditor;E?d.innerHTML=E({row:i,value:s,field:t.field,column:t,commit:n,cancel:r}):d.querySelectorAll("*").forEach(m=>{m.childNodes.length===1&&m.firstChild?.nodeType===Node.TEXT_NODE&&(m.textContent=m.textContent?.replace(/{{\s*value\s*}}/g,s==null?"":String(s)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(g,p)=>{if(!k(p))return"";const _=i[p];return _==null?"":String(_)})||"")});const h=d.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&h.type==="checkbox"?h.checked=!!s:h.value=String(s??"");let m=!1;h.addEventListener("blur",()=>{m||n(R(h,t,s))}),h.addEventListener("keydown",g=>{const p=g;if(p.key==="Enter"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(p)===!1)return;p.stopPropagation(),p.preventDefault(),m=!0,n(R(h,t,s)),this.#n(a,!1)}if(p.key==="Escape"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(p)===!1)return;p.stopPropagation(),p.preventDefault(),r(),this.#n(a,!0)}}),h instanceof HTMLInputElement&&h.type==="checkbox"&&h.addEventListener("change",()=>n(h.checked)),o||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(d)}#_(e,t){if(!e)return!1;const i=e,s=t,n=new Set([...Object.keys(i),...Object.keys(s)]);for(const r of n)if(i[r]!==s[r])return!0;return!1}#v(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,s=e.findRenderedRowElement?.(t);if(s){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(r=>r.classList.remove("cell-focus"));const n=s.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);n&&(n.classList.add("cell-focus"),n.setAttribute("aria-selected","true"),n.hasAttribute("tabindex")||n.setAttribute("tabindex","-1"),n.focus({preventScroll:!0}))}}catch{}})}}v.EditingPlugin=U,v.defaultEditorFor=A,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(b,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("../../core/internal/keyboard"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/rows","../../core/plugin/base-plugin"],y):(b=typeof globalThis<"u"?globalThis:b||self,y(b.TbwGridPlugin_editing={},b.TbwGrid,b.TbwGrid,b.TbwGrid))})(this,(function(b,y,v,q){"use strict";const B="@layer tbw-plugins{tbw-grid{--tbw-editing-bg: var(--tbw-color-selection);--tbw-editing-row-bg: var(--tbw-editing-bg);--tbw-editing-border: var(--tbw-border-input, 1px solid var(--tbw-color-border-strong));--tbw-padding-editing-input: var(--tbw-cell-padding-input, 2px 6px);--tbw-font-size-editor: inherit;--tbw-editing-row-outline-color: var(--tbw-color-accent);--tbw-editing-row-outline-width: 1px;--tbw-invalid-bg: light-dark(#fef2f2, #450a0a);--tbw-invalid-border-color: light-dark(#ef4444, #f87171)}tbw-grid:not(.tbw-grid-mode) .data-grid-row:has(.editing){background:var(--tbw-editing-row-bg);outline:var(--tbw-editing-row-outline-width) solid var(--tbw-editing-row-outline-color);outline-offset:calc(-1 * var(--tbw-editing-row-outline-width))}tbw-grid .data-grid-row>.cell.editing{overflow:hidden;padding:0;display:flex;min-height:calc(var(--tbw-row-height) + 2px);align-items:center;justify-content:center}tbw-grid .data-grid-row>.cell.editing input:not([type=checkbox]),tbw-grid .data-grid-row>.cell.editing select,tbw-grid .data-grid-row>.cell.editing textarea{width:100%;height:100%;flex:1 1 auto;min-width:0;border:var(--tbw-editing-border);padding:var(--tbw-padding-editing-input);font-size:var(--tbw-font-size-editor)}tbw-grid .tbw-editor-host{display:contents}tbw-grid .data-grid-row>.cell[data-invalid=true]{background:var(--tbw-invalid-bg);outline:1px solid var(--tbw-invalid-border-color);outline-offset:-1px}}";function D(l){const e=l.options;return e?typeof e=="function"?e():e:[]}function P(l){return e=>{const t=l.editorParams,i=document.createElement("input");i.type="number",i.value=e.value!=null?String(e.value):"",t?.min!==void 0&&(i.min=String(t.min)),t?.max!==void 0&&(i.max=String(t.max)),t?.step!==void 0&&(i.step=String(t.step)),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>e.commit(i.value===""?null:Number(i.value));return i.addEventListener("blur",n),i.addEventListener("keydown",s=>{s.key==="Enter"&&n(),s.key==="Escape"&&e.cancel()}),i}}function M(){return l=>{const e=document.createElement("input");return e.type="checkbox",e.checked=!!l.value,e.addEventListener("change",()=>l.commit(e.checked)),e}}function G(l){return e=>{const t=l.editorParams,i=document.createElement("input");i.type="date",e.value instanceof Date?i.valueAsDate=e.value:typeof e.value=="string"&&e.value&&(i.value=e.value.split("T")[0]),t?.min&&(i.min=t.min),t?.max&&(i.max=t.max),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>{typeof e.value=="string"?e.commit(i.value):e.commit(i.valueAsDate)};return i.addEventListener("change",n),i.addEventListener("keydown",s=>{s.key==="Escape"&&e.cancel()}),i}}function H(l){return e=>{const t=l.editorParams,i=document.createElement("select");if(l.multi&&(i.multiple=!0),t?.includeEmpty){const r=document.createElement("option");r.value="",r.textContent=t.emptyLabel??"",i.appendChild(r)}D(l).forEach(r=>{const o=document.createElement("option");o.value=String(r.value),o.textContent=r.label,(l.multi&&Array.isArray(e.value)&&e.value.includes(r.value)||!l.multi&&e.value===r.value)&&(o.selected=!0),i.appendChild(o)});const s=()=>{if(l.multi){const r=Array.from(i.selectedOptions).map(o=>o.value);e.commit(r)}else e.commit(i.value)};return i.addEventListener("change",s),i.addEventListener("blur",s),i.addEventListener("keydown",r=>{r.key==="Escape"&&e.cancel()}),i}}function $(l){return e=>{const t=l.editorParams,i=document.createElement("input");i.type="text",i.value=e.value!=null?String(e.value):"",t?.maxLength!==void 0&&(i.maxLength=t.maxLength),t?.pattern&&(i.pattern=t.pattern),t?.placeholder&&(i.placeholder=t.placeholder);const n=()=>{const s=i.value;(e.value===null||e.value===void 0)&&s===""||typeof e.value=="string"&&s===e.value.replace(/[\n\r]/g,"")||(typeof e.value=="number"&&s!==""?e.commit(Number(s)):e.commit(s))};return i.addEventListener("blur",n),i.addEventListener("keydown",s=>{s.key==="Enter"&&n(),s.key==="Escape"&&e.cancel()}),i}}function A(l){switch(l.type){case"number":return P(l);case"boolean":return M();case"date":return G(l);case"select":return H(l);default:return $(l)}}function x(l,e){if(e.editor)return e.editor;if(e.__editorTemplate)return"template";if(!e.type)return;const i=l.effectiveConfig?.typeDefaults;if(i?.[e.type]?.editor)return i[e.type].editor;const n=l.__frameworkAdapter;if(n?.getTypeDefault){const s=n.getTypeDefault(e.type);if(s?.editor)return s.editor}}function L(l){return!(typeof l!="string"||l==="__proto__"||l==="constructor"||l==="prototype")}function F(l){const e=(l.__editingCellCount??0)+1;l.__editingCellCount=e,l.setAttribute("data-has-editing","")}function N(l){l.__editingCellCount=0,l.removeAttribute("data-has-editing")}function R(l,e,t){return l instanceof HTMLInputElement?l.type==="checkbox"?l.checked:l.type==="number"?l.value===""?null:Number(l.value):l.type==="date"?typeof t=="string"?l.value:l.valueAsDate:typeof t=="number"?l.value===""?null:Number(l.value):t==null&&l.value===""||typeof t=="string"&&l.value===t.replace(/[\n\r]/g,"")?t:l.value:e?.type==="number"&&l.value!==""||typeof t=="number"&&l.value!==""?Number(l.value):t==null&&l.value===""?t:l.value}function O(l){}function U(l,e,t,i){const n=l.querySelector("input,textarea,select");n&&(n.addEventListener("blur",()=>{t(R(n,e,i))}),n instanceof HTMLInputElement&&n.type==="checkbox"?n.addEventListener("change",()=>t(n.checked)):n instanceof HTMLSelectElement&&n.addEventListener("change",()=>t(R(n,e,i))))}class j extends q.BaseGridPlugin{static manifest={ownedProperties:[{property:"editable",level:"column",description:'the "editable" column property',isUsed:e=>e===!0},{property:"editor",level:"column",description:'the "editor" column property'},{property:"editorParams",level:"column",description:'the "editorParams" column property'}],events:[{type:"cell-edit-committed",description:"Emitted when a cell edit is committed (for plugin-to-plugin coordination)"}],queries:[{type:"isEditing",description:"Returns whether any cell is currently being edited"}]};name="editing";styles=B;get defaultConfig(){return{mode:"row",editOn:"click"}}get#t(){return this.config.mode==="grid"}#e=-1;#f=-1;#l=new Map;#n=new Set;#o=new Set;#a=new Map;#u=!1;#h=-1;#i=new Map;#r=!1;#c=!1;#d=!1;attach(e){super.attach(e);const t=this.disconnectSignal,i=e;i._activeEditRows=-1,i._rowEditSnapshots=new Map,Object.defineProperty(e,"changedRows",{get:()=>this.changedRows,configurable:!0}),Object.defineProperty(e,"changedRowIds",{get:()=>this.changedRowIds,configurable:!0}),e.resetChangedRows=n=>this.resetChangedRows(n),e.beginBulkEdit=(n,s)=>{s&&this.beginCellEdit(n,s)},document.addEventListener("keydown",n=>{if(!this.#t&&n.key==="Escape"&&this.#e!==-1){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1)return;this.#s(this.#e,!0)}},{capture:!0,signal:t}),document.addEventListener("mousedown",n=>{if(this.#t||this.#e===-1)return;const s=i.findRenderedRowElement?.(this.#e);!s||(n.composedPath&&n.composedPath()||[]).includes(s)||this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1||queueMicrotask(()=>{this.#e!==-1&&this.#s(this.#e,!1)})},{signal:t}),this.gridElement.addEventListener("cell-change",n=>{const s=n.detail;if(s.source==="user")return;const r=`${s.rowIndex}:${s.field}`,o=this.#a.get(r);o&&o(s.newValue)},{signal:t}),this.#t&&(i._isGridEditMode=!0,this.gridElement.classList.add("tbw-grid-mode"),this.requestRender(),this.gridElement.addEventListener("focusin",n=>{const s=n.target;if(s.matches(v.FOCUSABLE_EDITOR_SELECTOR)){if(this.#c){s.blur(),this.gridElement.focus();return}this.#r=!0}},{signal:t}),this.gridElement.addEventListener("focusout",n=>{const s=n.relatedTarget;(!s||!this.gridElement.contains(s)||!s.matches(v.FOCUSABLE_EDITOR_SELECTOR))&&(this.#r=!1)},{signal:t}),this.gridElement.addEventListener("keydown",n=>{if(n.key==="Escape"&&this.#r){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(n)===!1)return;const s=document.activeElement;s&&this.gridElement.contains(s)&&(s.blur(),this.gridElement.focus()),this.#r=!1,this.#c=!0,n.preventDefault(),n.stopPropagation()}},{capture:!0,signal:t}),this.gridElement.addEventListener("mousedown",n=>{n.target.matches(v.FOCUSABLE_EDITOR_SELECTOR)&&(this.#c=!1)},{signal:t}))}detach(){const e=this.gridElement;e._isGridEditMode=!1,this.gridElement.classList.remove("tbw-grid-mode"),this.#e=-1,this.#f=-1,this.#l.clear(),this.#n.clear(),this.#o.clear(),this.#a.clear(),this.#r=!1,this.#c=!1,this.#d=!1,super.detach()}handleQuery(e){if(e.type==="isEditing")return this.#t||this.#e!==-1}onCellClick(e){if(this.#t)return!1;const t=this.grid,i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual"||i!=="click"&&i!=="dblclick")return!1;const n=e.originalEvent.type==="dblclick";if(i==="click"&&n||i==="dblclick"&&!n)return!1;const{rowIndex:s}=e;return t._columns?.some(o=>o.editable)?(e.originalEvent.stopPropagation(),this.beginBulkEdit(s),!0):!1}onKeyDown(e){const t=this.grid;if(e.key==="Escape"){if(this.#t&&this.#r){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=document.activeElement;return i&&this.gridElement.contains(i)&&i.blur(),this.#r=!1,this.requestAfterRender(),!0}if(this.#e!==-1&&!this.#t)return this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1||this.#s(this.#e,!0),!0}if(this.#t&&!this.#r&&(e.key==="ArrowUp"||e.key==="ArrowDown"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return!1;if(this.#t&&this.#r&&(e.key==="ArrowUp"||e.key==="ArrowDown"))return!0;if((e.key==="ArrowUp"||e.key==="ArrowDown")&&this.#e!==-1&&!this.#t){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1)return!0;const i=t._rows.length-1,n=this.#e;return this.#s(n,!1),e.key==="ArrowDown"?t._focusRow=Math.min(i,t._focusRow+1):t._focusRow=Math.max(0,t._focusRow-1),e.preventDefault(),y.ensureCellVisible(t),this.requestAfterRender(),!0}if(e.key==="Tab"&&(this.#e!==-1||this.#t)){if(e.preventDefault(),this.#d)return this.#s(this.#e,!1),!0;const i=!e.shiftKey;return this.#C(i),!0}if(e.key===" "||e.key==="Spacebar"){if(this.#e!==-1)return!1;const i=t._focusRow,n=t._focusCol;if(i>=0&&n>=0){const s=t._visibleColumns[n],r=t._rows[i];if(s?.editable&&s.type==="boolean"&&r){const o=s.field;if(L(o)){const c=!r[o];return this.#m(i,s,c,r),e.preventDefault(),this.requestRender(),!0}}}return!1}if(e.key==="Enter"&&!e.shiftKey&&!e.ctrlKey&&!e.altKey&&!e.metaKey){if(this.#t&&!this.#r)return this.#y(),!0;if(this.#e!==-1)return!!(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(e)===!1);const i=this.config.editOn??t.effectiveConfig?.editOn;if(i===!1||i==="manual")return!1;const n=t._focusRow,s=t._focusCol;if(n>=0&&t._columns?.some(o=>o.editable)){const o=t._visibleColumns[s],a=t._rows[n],c=o?.field??"",f=c&&a?a[c]:void 0,E=this.gridElement.querySelector(`[data-row="${n}"][data-col="${s}"]`),h=new CustomEvent("cell-activate",{cancelable:!0,bubbles:!0,detail:{rowIndex:n,colIndex:s,field:c,value:f,row:a,cellEl:E,trigger:"keyboard",originalEvent:e}});this.gridElement.dispatchEvent(h);const m=new CustomEvent("activate-cell",{cancelable:!0,bubbles:!0,detail:{row:n,col:s}});return this.gridElement.dispatchEvent(m),h.defaultPrevented||m.defaultPrevented?(e.preventDefault(),!0):(this.beginBulkEdit(n),!0)}return!1}if(e.key==="F2"){if(this.#e!==-1||this.#t||(this.config.editOn??t.effectiveConfig?.editOn)===!1)return!1;const n=t._focusRow,s=t._focusCol;if(n>=0&&s>=0){const r=t._visibleColumns[s];if(r?.editable&&r.field)return e.preventDefault(),this.beginCellEdit(n,r.field),!0}return!1}return!1}processColumns(e){const t=this.grid,i=t.effectiveConfig?.typeDefaults,n=t.__frameworkAdapter;return!i&&!n?.getTypeDefault?e:e.map(s=>{if(!s.type)return s;let r;if(i?.[s.type]?.editorParams&&(r=i[s.type].editorParams),!r&&n?.getTypeDefault){const o=n.getTypeDefault(s.type);o?.editorParams&&(r=o.editorParams)}return r?{...s,editorParams:{...r,...s.editorParams}}:s})}afterRender(){const e=this.grid;if(this.#u&&(this.#u=!1,this.#b(e)),this.#h!==-1){const t=this.#h;this.#h=-1,e.animateRow?.(t,"change")}if(!this.#t&&this.#o.size!==0)for(const t of this.#o){const[i,n]=t.split(":"),s=parseInt(i,10),r=parseInt(n,10),o=e.findRenderedRowElement?.(s);if(!o)continue;const a=o.querySelector(`.cell[data-col="${r}"]`);if(!a||a.classList.contains("editing"))continue;const c=e._rows[s],f=e._visibleColumns[r];c&&f&&this.#E(c,s,f,r,a,!0)}}afterCellRender(e){if(!this.#t)return;const{row:t,rowIndex:i,column:n,colIndex:s,cellElement:r}=e;n.editable&&(r.classList.contains("editing")||this.#E(t,i,n,s,r,!0))}onScrollRender(){this.afterRender()}get changedRows(){const e=[];for(const t of this.#n){const i=this.grid.getRow(t);i&&e.push(i)}return e}get changedRowIds(){return Array.from(this.#n)}get activeEditRow(){return this.#e}get activeEditCol(){return this.#f}isRowEditing(e){return this.#e===e}isCellEditing(e,t){return this.#o.has(`${e}:${t}`)}isRowChanged(e){const t=this.grid,i=t._rows[e];if(!i)return!1;try{const n=t.getRowId?.(i);return n?this.#n.has(n):!1}catch{return!1}}isRowChangedById(e){return this.#n.has(e)}setInvalid(e,t,i=""){let n=this.#i.get(e);n||(n=new Map,this.#i.set(e,n)),n.set(t,i),this.#g(e,t,!0)}clearInvalid(e,t){const i=this.#i.get(e);i&&(i.delete(t),i.size===0&&this.#i.delete(e)),this.#g(e,t,!1)}clearRowInvalid(e){const t=this.#i.get(e);if(t){const i=Array.from(t.keys());this.#i.delete(e),i.forEach(n=>this.#g(e,n,!1))}}clearAllInvalid(){const e=Array.from(this.#i.entries());this.#i.clear(),e.forEach(([t,i])=>{i.forEach((n,s)=>this.#g(t,s,!1))})}isCellInvalid(e,t){return this.#i.get(e)?.has(t)??!1}getInvalidMessage(e,t){return this.#i.get(e)?.get(t)}hasInvalidCells(e){const t=this.#i.get(e);return t?t.size>0:!1}getInvalidFields(e){return new Map(this.#i.get(e)??[])}#g(e,t,i){const n=this.grid,s=n._visibleColumns?.findIndex(f=>f.field===t);if(s===-1||s===void 0)return;const o=n._rows?.findIndex(f=>{try{return n.getRowId?.(f)===e}catch{return!1}});if(o===-1||o===void 0)return;const c=n.findRenderedRowElement?.(o)?.querySelector(`.cell[data-col="${s}"]`);if(c)if(i){c.setAttribute("data-invalid","true");const f=this.#i.get(e)?.get(t);f&&c.setAttribute("title",f)}else c.removeAttribute("data-invalid"),c.removeAttribute("title")}resetChangedRows(e){const t=this.changedRows,i=this.changedRowIds;this.#n.clear(),this.#p(),e||this.emit("changed-rows-reset",{rows:t,ids:i}),this.grid._rowPool?.forEach(s=>s.classList.remove("changed"))}beginCellEdit(e,t){const i=this.grid,n=i._visibleColumns.findIndex(a=>a.field===t);if(n===-1||!i._visibleColumns[n]?.editable)return;const o=i.findRenderedRowElement?.(e)?.querySelector(`.cell[data-col="${n}"]`);o&&(this.#d=!0,this.#v(e,n,o))}beginBulkEdit(e){const t=this.grid;if((this.config.editOn??t.effectiveConfig?.editOn)===!1||!t._columns?.some(o=>o.editable))return;const s=t.findRenderedRowElement?.(e);if(!s)return;this.#d=!1;const r=t._rows[e];this.#w(e,r),Array.from(s.children).forEach((o,a)=>{const c=t._visibleColumns[a];if(c?.editable){const f=o;f.classList.contains("editing")||this.#E(r,e,c,a,f,!0)}}),setTimeout(()=>{let o=s.querySelector(`.cell[data-col="${t._focusCol}"]`);if(o?.classList.contains("editing")||(o=s.querySelector(".cell.editing")),o?.classList.contains("editing")){const a=o.querySelector(v.FOCUSABLE_EDITOR_SELECTOR);try{a?.focus({preventScroll:!0})}catch{}}},0)}commitActiveRowEdit(){this.#e!==-1&&this.#s(this.#e,!1)}cancelActiveRowEdit(){this.#e!==-1&&this.#s(this.#e,!0)}#v(e,t,i){const n=this.grid,s=n._rows[e],r=n._visibleColumns[t];!s||!r?.editable||i.classList.contains("editing")||(this.#e!==e&&this.#w(e,s),this.#f=t,this.#E(s,e,r,t,i,!1))}#y(){const e=this.grid,t=e._focusRow,i=e._focusCol;if(t<0||i<0)return;const s=e.findRenderedRowElement?.(t)?.querySelector(`.cell[data-col="${i}"]`);if(s?.classList.contains("editing")){const r=s.querySelector(v.FOCUSABLE_EDITOR_SELECTOR);r&&(this.#c=!1,r.focus(),this.#r=!0,r instanceof HTMLInputElement&&(r.type==="text"||r.type==="number")&&r.select())}}#C(e){const t=this.grid,i=t._rows,n=this.#t?t._focusRow:this.#e,s=t._visibleColumns.map((c,f)=>c.editable?f:-1).filter(c=>c>=0);if(s.length===0)return;const o=s.indexOf(t._focusCol)+(e?1:-1);if(o>=0&&o<s.length){t._focusCol=s[o];const f=t.findRenderedRowElement?.(n)?.querySelector(`.cell[data-col="${s[o]}"]`);f?.classList.contains("editing")&&f.querySelector(v.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0}),y.ensureCellVisible(t,{forceHorizontalScroll:!0});return}const a=n+(e?1:-1);a>=0&&a<i.length&&(this.#t?(t._focusRow=a,t._focusCol=e?s[0]:s[s.length-1],y.ensureCellVisible(t,{forceHorizontalScroll:!0}),this.requestAfterRender(),setTimeout(()=>{const f=t.findRenderedRowElement?.(a)?.querySelector(`.cell[data-col="${t._focusCol}"]`);f?.classList.contains("editing")&&f.querySelector(v.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0})},0)):(this.#s(n,!1),t._focusRow=a,t._focusCol=e?s[0]:s[s.length-1],this.beginBulkEdit(a),y.ensureCellVisible(t,{forceHorizontalScroll:!0})))}#p(){const e=this.grid;e._activeEditRows=this.#e,e._rowEditSnapshots=this.#l}#w(e,t){if(this.#e!==e&&(this.#l.set(e,{...t}),this.#e=e,this.#p(),!this.#t)){const i=this.grid;let n="";try{n=i.getRowId?.(t)??""}catch{}this.emit("edit-open",{rowIndex:e,rowId:n,row:t})}}#s(e,t){if(this.#e!==e)return;const i=this.grid,n=this.#l.get(e),s=i._rows[e],r=i.findRenderedRowElement?.(e);let o;if(s)try{o=i.getRowId?.(s)}catch{}if(!t&&r&&s&&r.querySelectorAll(".cell.editing").forEach(c=>{const f=Number(c.getAttribute("data-col"));if(isNaN(f))return;const E=i._visibleColumns[f];if(!E||c.hasAttribute("data-editor-managed"))return;const h=c.querySelector("input,textarea,select");if(h){const m=E.field,g=s[m],p=R(h,E,g);g!==p&&this.#m(e,E,p,s)}}),t&&n&&s)Object.keys(n).forEach(a=>{s[a]=n[a]}),o&&(this.#n.delete(o),this.clearRowInvalid(o));else if(!t&&s){const a=this.#_(n,s),c=o?this.#n.has(o):a,f=this.emitCancelable("row-commit",{rowIndex:e,rowId:o??"",row:s,oldValue:n,newValue:s,changed:c,changedRows:this.changedRows,changedRowIds:this.changedRowIds});f&&n?(Object.keys(n).forEach(E=>{s[E]=n[E]}),o&&(this.#n.delete(o),this.clearRowInvalid(o))):!f&&a&&this.isAnimationEnabled&&(this.#h=e)}this.#l.delete(e),this.#e=-1,this.#f=-1,this.#d=!1,this.#p();for(const a of this.#o)a.startsWith(`${e}:`)&&this.#o.delete(a);for(const a of this.#a.keys())a.startsWith(`${e}:`)&&this.#a.delete(a);r&&(r.querySelectorAll(".cell.editing").forEach(a=>{a.classList.remove("editing"),N(a.parentElement)}),this.requestRender()),this.#u=!0,r||(this.#b(i),this.#u=!1),!this.#t&&s&&this.emit("edit-close",{rowIndex:e,rowId:o??"",row:s,reverted:t})}#m(e,t,i,n){const s=t.field;if(!L(s))return;const r=n[s];if(r===i)return;const o=this.grid;let a;try{a=this.grid.getRowId(n)}catch{}const c=a?!this.#n.has(a):!0,f=a?p=>this.grid.updateRow(a,p,"cascade"):O;let E=!1;const h=a?p=>{E=!0,this.setInvalid(a,s,p??"")}:()=>{};if(this.emitCancelable("cell-commit",{row:n,rowId:a??"",field:s,oldValue:r,value:i,rowIndex:e,changedRows:this.changedRows,changedRowIds:this.changedRowIds,firstTimeForRow:c,updateRow:f,setInvalid:h}))return;a&&!E&&this.isCellInvalid(a,s)&&this.clearInvalid(a,s),n[s]=i,a&&this.#n.add(a),this.#p(),this.emitPluginEvent("cell-edit-committed",{rowIndex:e,field:s,oldValue:r,newValue:i});const g=o.findRenderedRowElement?.(e);g&&g.classList.add("changed")}#E(e,t,i,n,s,r){if(!i.editable||s.classList.contains("editing"))return;let o;try{o=this.grid.getRowId(e)}catch{}const a=o?d=>this.grid.updateRow(o,d,"cascade"):O,c=L(i.field)?e[i.field]:void 0;s.classList.add("editing"),this.#o.add(`${t}:${n}`);const f=s.parentElement;f&&F(f);let E=!1;const h=d=>{if(E||!this.#t&&this.#e===-1)return;const u=this.grid._rows[t]??e;this.#m(t,i,d,u)},m=()=>{if(E=!0,L(i.field)){const d=this.grid._rows[t]??e;d[i.field]=c}},g=document.createElement("div");g.className="tbw-editor-host",s.innerHTML="",s.appendChild(g),g.addEventListener("keydown",d=>{if(d.key==="Enter"){if(this.#t){d.stopPropagation(),d.preventDefault();const u=g.querySelector("input,textarea,select");u&&h(R(u,i,c));return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(d)===!1)return;d.stopPropagation(),d.preventDefault(),E=!0,this.#s(t,!1)}if(d.key==="Escape"){if(this.#t){d.stopPropagation(),d.preventDefault();return}if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(d)===!1)return;d.stopPropagation(),d.preventDefault(),m(),this.#s(t,!0)}});const p=i,_=p.__editorTemplate,w=x(this.grid,p)??A(i),T=c,z=`${t}:${i.field}`,I=[];this.#a.set(z,d=>{for(const u of I)u(d)});const S=d=>{I.push(d)};if(w==="template"&&_)this.#R(g,p,e,c,h,m,r,t),S(d=>{const u=g.querySelector("input,textarea,select");u&&(u instanceof HTMLInputElement&&u.type==="checkbox"?u.checked=!!d:u.value=String(d??""))});else if(typeof w=="string"){const d=document.createElement(w);d.value=T,d.addEventListener("change",()=>h(d.value)),S(u=>{d.value=u}),g.appendChild(d),r||queueMicrotask(()=>{g.querySelector(v.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0})})}else if(typeof w=="function"){const d={row:e,rowId:o??"",value:T,field:i.field,column:i,commit:h,cancel:m,updateRow:a,onValueChange:S},u=w(d);typeof u=="string"?(g.innerHTML=u,U(g,i,h,c),S(k=>{const C=g.querySelector("input,textarea,select");C&&(C instanceof HTMLInputElement&&C.type==="checkbox"?C.checked=!!k:C.value=String(k??""))})):u instanceof Node&&(g.appendChild(u),u instanceof HTMLInputElement||u instanceof HTMLSelectElement||u instanceof HTMLTextAreaElement?S(C=>{u instanceof HTMLInputElement&&u.type==="checkbox"?u.checked=!!C:u.value=String(C??"")}):s.setAttribute("data-editor-managed","")),r||queueMicrotask(()=>{g.querySelector(v.FOCUSABLE_EDITOR_SELECTOR)?.focus({preventScroll:!0})})}else if(w&&typeof w=="object"){const d=document.createElement("div");d.setAttribute("data-external-editor",""),d.setAttribute("data-field",i.field),g.appendChild(d),s.setAttribute("data-editor-managed","");const u={row:e,rowId:o??"",value:T,field:i.field,column:i,commit:h,cancel:m,updateRow:a,onValueChange:S};if(w.mount)try{w.mount({placeholder:d,context:u,spec:w})}catch(k){console.warn(`[tbw-grid] External editor mount error for column '${i.field}':`,k)}else this.grid.dispatchEvent(new CustomEvent("mount-external-editor",{detail:{placeholder:d,spec:w,context:u}}))}}#R(e,t,i,n,s,r,o,a){const c=t.__editorTemplate;if(!c)return;const f=c.cloneNode(!0),E=t.__compiledEditor;E?f.innerHTML=E({row:i,value:n,field:t.field,column:t,commit:s,cancel:r}):f.querySelectorAll("*").forEach(m=>{m.childNodes.length===1&&m.firstChild?.nodeType===Node.TEXT_NODE&&(m.textContent=m.textContent?.replace(/{{\s*value\s*}}/g,n==null?"":String(n)).replace(/{{\s*row\.([a-zA-Z0-9_]+)\s*}}/g,(g,p)=>{if(!L(p))return"";const _=i[p];return _==null?"":String(_)})||"")});const h=f.querySelector("input,textarea,select");if(h){h instanceof HTMLInputElement&&h.type==="checkbox"?h.checked=!!n:h.value=String(n??"");let m=!1;h.addEventListener("blur",()=>{m||s(R(h,t,n))}),h.addEventListener("keydown",g=>{const p=g;if(p.key==="Enter"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(p)===!1)return;p.stopPropagation(),p.preventDefault(),m=!0,s(R(h,t,n)),this.#s(a,!1)}if(p.key==="Escape"){if(this.config.onBeforeEditClose&&this.config.onBeforeEditClose(p)===!1)return;p.stopPropagation(),p.preventDefault(),r(),this.#s(a,!0)}}),h instanceof HTMLInputElement&&h.type==="checkbox"&&h.addEventListener("change",()=>s(h.checked)),o||setTimeout(()=>h.focus({preventScroll:!0}),0)}e.appendChild(f)}#_(e,t){if(!e)return!1;const i=e,n=t,s=new Set([...Object.keys(i),...Object.keys(n)]);for(const r of s)if(i[r]!==n[r])return!0;return!1}#b(e){queueMicrotask(()=>{try{const t=e._focusRow,i=e._focusCol,n=e.findRenderedRowElement?.(t);if(n){Array.from(e._bodyEl.querySelectorAll(".cell-focus")).forEach(r=>r.classList.remove("cell-focus"));const s=n.querySelector(`.cell[data-row="${t}"][data-col="${i}"]`);s&&(s.classList.add("cell-focus"),s.setAttribute("aria-selected","true"),s.hasAttribute("tabindex")||s.setAttribute("tabindex","-1"),s.focus({preventScroll:!0}))}}catch{}})}}b.EditingPlugin=j,b.defaultEditorFor=A,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=editing.umd.js.map
|