@toolbox-web/grid 1.6.2 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +9 -8
- package/all.js.map +1 -1
- package/index.js +668 -583
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +46 -0
- package/lib/core/grid.d.ts.map +1 -1
- package/lib/core/types.d.ts +114 -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/ContextMenuPlugin.d.ts.map +1 -1
- package/lib/plugins/context-menu/index.js +72 -71
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-rows/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/PrintPlugin.d.ts.map +1 -1
- package/lib/plugins/print/index.js +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/public.d.ts +1 -1
- package/public.d.ts.map +1 -1
- package/umd/grid.all.umd.js +13 -13
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +11 -11
- 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/print.umd.js +1 -1
- package/umd/plugins/print.umd.js.map +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(m,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],h):(m=typeof globalThis<"u"?globalThis:m||self,h(m.TbwGridPlugin_contextMenu={},m.TbwGrid,m.TbwGrid))})(this,(function(m,h,S){"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:
|
|
1
|
+
(function(m,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("../../core/plugin/base-plugin"),require("../../core/types")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin","../../core/types"],h):(m=typeof globalThis<"u"?globalThis:m||self,h(m.TbwGridPlugin_contextMenu={},m.TbwGrid,m.TbwGrid))})(this,(function(m,h,S){"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 g(s,n){return(typeof s=="function"?s(n):s).filter(t=>!(t.hidden===!0||typeof t.hidden=="function"&&t.hidden(n)))}function z(s,n){return s.disabled===!0?!0:typeof s.disabled=="function"?s.disabled(n):!1}function v(s,n,l,t=S.DEFAULT_GRID_ICONS.submenuArrow){const i=document.createElement("div");i.className="tbw-context-menu",i.setAttribute("role","menu");for(const o of s){if(o.separator){const r=document.createElement("div");r.className="tbw-context-menu-separator",r.setAttribute("role","separator"),i.appendChild(r);continue}const e=document.createElement("div");e.className="tbw-context-menu-item",o.cssClass&&e.classList.add(o.cssClass),e.setAttribute("role","menuitem"),e.setAttribute("data-id",o.id);const u=z(o,n);if(u&&(e.classList.add("disabled"),e.setAttribute("aria-disabled","true")),o.icon){const r=document.createElement("span");r.className="tbw-context-menu-icon",r.innerHTML=o.icon,e.appendChild(r)}const a=document.createElement("span");if(a.className="tbw-context-menu-label",a.textContent=o.name,e.appendChild(a),o.shortcut){const r=document.createElement("span");r.className="tbw-context-menu-shortcut",r.textContent=o.shortcut,e.appendChild(r)}if(o.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)),e.appendChild(r),e.addEventListener("mouseenter",()=>{if(e.querySelector(".tbw-context-menu")||!o.subMenu)return;const f=g(o.subMenu,n),d=v(f,n,l,t);d.classList.add("tbw-context-submenu"),d.style.position="absolute",d.style.left="100%",d.style.top="0",e.style.position="relative",e.appendChild(d)}),e.addEventListener("mouseleave",()=>{const c=e.querySelector(".tbw-context-menu");c&&c.remove()})}!u&&o.action&&!o.subMenu&&e.addEventListener("click",r=>{r.stopPropagation(),l(o)}),i.appendChild(e)}return i}function M(s,n,l){s.style.position="fixed",s.style.left=`${n}px`,s.style.top=`${l}px`,s.style.visibility="hidden",s.style.zIndex="10000";const t=s.getBoundingClientRect(),i=window.innerWidth,o=window.innerHeight;let e=n,u=l;n+t.width>i&&(e=n-t.width),l+t.height>o&&(u=l-t.height),e=Math.max(0,e),u=Math.max(0,u),s.style.left=`${e}px`,s.style.top=`${u}px`,s.style.visibility="visible"}let w=null,p=null,b=null,y=0;const E=[{id:"copy",name:"Copy",shortcut:"Ctrl+C",action:s=>{s.grid?.plugins?.clipboard?.copy?.()}},{separator:!0,id:"sep1",name:""},{id:"export-csv",name:"Export CSV",action:s=>{s.grid?.plugins?.export?.exportCsv?.()}}];class C extends h.BaseGridPlugin{name="contextMenu";get defaultConfig(){return{items:E}}isOpen=!1;position={x:0,y:0};params=null;menuElement=null;attach(n){super.attach(n),this.installGlobalHandlers(),y++}detach(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null),this.isOpen=!1,this.params=null,this.uninstallGlobalHandlers()}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(n){const l=this.gridElement;if(!l)return;const t=getComputedStyle(l),i=[],o=t.getPropertyValue("color-scheme").trim();o&&i.push(`color-scheme: ${o}`);for(const e of C.CSS_VARS_TO_COPY){const u=t.getPropertyValue(e).trim();u&&i.push(`${e}: ${u}`)}if(i.length>0){const e=n.getAttribute("style")||"";n.setAttribute("style",e+i.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)),w||(w=()=>{document.querySelectorAll(".tbw-context-menu").forEach(l=>l.remove())},document.addEventListener("click",w)),p||(p=n=>{n.key==="Escape"&&document.querySelectorAll(".tbw-context-menu").forEach(t=>t.remove())},document.addEventListener("keydown",p))}uninstallGlobalHandlers(){y--,!(y>0)&&(w&&(document.removeEventListener("click",w),w=null),p&&(document.removeEventListener("keydown",p),p=null),b&&(b.remove(),b=null))}afterRender(){const n=this.gridElement;if(!n)return;const l=n.children[0];l&&l.getAttribute("data-context-menu-bound")!=="true"&&(l.setAttribute("data-context-menu-bound","true"),l.addEventListener("contextmenu",t=>{const i=t;i.preventDefault();const o=i.target,e=o.closest("[data-row][data-col]"),u=o.closest(".header-cell");let a;if(e){const c=parseInt(e.getAttribute("data-row")??"-1",10),f=parseInt(e.getAttribute("data-col")??"-1",10),d=this.columns[f],I=this.rows[c];a={row:I,rowIndex:c,column:d,columnIndex:f,field:d?.field??"",value:I?.[d?.field]??null,isHeader:!1,event:i}}else if(u){const c=parseInt(u.getAttribute("data-col")??"-1",10),f=this.columns[c];a={row:null,rowIndex:-1,column:f,columnIndex:c,field:f?.field??"",value:null,isHeader:!0,event:i}}else return;this.params=a,this.position={x:i.clientX,y:i.clientY};const r=g(this.config.items??E,a);r.length&&(this.menuElement&&this.menuElement.remove(),this.menuElement=v(r,a,c=>{c.action&&c.action(a),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),M(this.menuElement,i.clientX,i.clientY),this.isOpen=!0,this.emit("context-menu-open",{params:a,items:r}))}))}showMenu(n,l,t){const i={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")},o=g(this.config.items??E,i);this.menuElement&&this.menuElement.remove(),this.menuElement=v(o,i,e=>{e.action&&e.action(i),this.menuElement?.remove(),this.menuElement=null,this.isOpen=!1},this.gridIcons.submenuArrow),document.body.appendChild(this.menuElement),this.copyGridStyles(this.menuElement),M(this.menuElement,n,l),this.isOpen=!0}hideMenu(){this.menuElement&&(this.menuElement.remove(),this.menuElement=null,this.isOpen=!1)}isMenuOpen(){return this.isOpen}}m.ContextMenuPlugin=C,Object.defineProperty(m,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 * 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 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 }\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 { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport { buildMenuItems, createMenuElement, positionMenu } from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams } from './types';\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 /** @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 * 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 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 // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const container = gridEl.children[0];\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('.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.columns[colIndex];\n const row = this.rows[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 };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[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 };\n } else {\n return;\n }\n\n this.params = params;\n this.position = { x: event.clientX, y: event.clientY };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, params);\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 };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\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","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","menuElement","gridEl","computed","styles","varName","value","existing","contextMenuStyles","container","event","target","cell","header","rowIndex","colIndex","column","row","fullParams"],"mappings":"gkEAiBO,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,CASO,SAASE,EAAeD,EAAuBD,EAAoC,CACxF,OAAIC,EAAK,WAAa,GAAa,GAC/B,OAAOA,EAAK,UAAa,WAAmBA,EAAK,SAASD,CAAM,EAC7D,EACT,CAWO,SAASG,EACdJ,EACAC,EACAI,EACAC,EAA0BC,EAAAA,mBAAmB,aAChC,CACb,MAAMC,EAAO,SAAS,cAAc,KAAK,EACzCA,EAAK,UAAY,mBACjBA,EAAK,aAAa,OAAQ,MAAM,EAEhC,UAAWN,KAAQF,EAAO,CACxB,GAAIE,EAAK,UAAW,CAClB,MAAMO,EAAY,SAAS,cAAc,KAAK,EAC9CA,EAAU,UAAY,6BACtBA,EAAU,aAAa,OAAQ,WAAW,EAC1CD,EAAK,YAAYC,CAAS,EAC1B,QACF,CAEA,MAAMC,EAAW,SAAS,cAAc,KAAK,EAC7CA,EAAS,UAAY,wBACjBR,EAAK,UAAUQ,EAAS,UAAU,IAAIR,EAAK,QAAQ,EACvDQ,EAAS,aAAa,OAAQ,UA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AAK,QAAQA,EAAK,OAAOkD,CAAU,EACvC,KAAK,aAAa,OAAA,EAClB,KAAK,YAAc,KACnB,KAAK,OAAS,EAChB,EACA,KAAK,UAAU,YAAA,EAGjB,SAAS,KAAK,YAAY,KAAK,WAAW,EAC1C,KAAK,eAAe,KAAK,WAAW,EACpCjC,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 * 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 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 }\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 { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport contextMenuStyles from './context-menu.css?inline';\nimport { buildMenuItems, createMenuElement, positionMenu } from './menu';\nimport type { ContextMenuConfig, ContextMenuItem, ContextMenuParams } from './types';\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 /** @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 * 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 // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const container = gridEl.children[0];\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('.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.columns[colIndex];\n const row = this.rows[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 };\n } else if (header) {\n const colIndex = parseInt(header.getAttribute('data-col') ?? '-1', 10);\n const column = this.columns[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 };\n } else {\n return;\n }\n\n this.params = params;\n this.position = { x: event.clientX, y: event.clientY };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, params);\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 };\n\n const items = buildMenuItems(this.config.items ?? defaultItems, fullParams);\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","isItemDisabled","createMenuElement","onAction","submenuArrow","DEFAULT_GRID_ICONS","menu","separator","menuItem","disabled","icon","label","shortcut","arrow","subMenuItems","subMenu","e","positionMenu","x","y","menuRect","viewportWidth","viewportHeight","left","top","globalClickHandler","globalKeydownHandler","globalStyleSheet","globalHandlerRefCount","defaultItems","ContextMenuPlugin","BaseGridPlugin","grid","menuElement","gridEl","computed","styles","colorScheme","varName","value","existing","contextMenuStyles","container","event","target","cell","header","rowIndex","colIndex","column","row","fullParams"],"mappings":"gkEAiBO,SAASA,EACdC,EACAC,EACmB,CAGnB,OAFkB,OAAOD,GA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CAIF"}
|
package/umd/plugins/print.umd.js
CHANGED
|
@@ -72,5 +72,5 @@
|
|
|
72
72
|
|
|
73
73
|
Note: Output will be limited to ${i.maxRows.toLocaleString()} rows.`:"";if(!confirm(`This grid has ${a.toLocaleString()} rows. Printing large datasets may cause performance issues or browser slowdowns.${m}
|
|
74
74
|
|
|
75
|
-
Click OK to continue, or Cancel to abort.`))return}i.maxRows>0&&a>i.maxRows&&(l=i.maxRows,d=!0),this.#n=!0;const w=performance.now();this.emit("print-start",{rowCount:l,limitApplied:d,originalRowCount:a});try{const m=this.#s;this.#r={bypassThreshold:m._virtualization?.bypassThreshold??24},this.#c(),d&&(this.#o=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,l),await new Promise(r=>setTimeout(r,50))),(i.includeTitle||i.includeTimestamp)&&this.#d(i),await this.#p(),await new Promise(r=>requestAnimationFrame(r)),await new Promise(r=>requestAnimationFrame(r)),t.classList.add(`print-${i.orientation}`),await new Promise(r=>requestAnimationFrame(r)),await new Promise(r=>requestAnimationFrame(r)),i.isolate?await this.#h(i):await this.#m(),this.emit("print-complete",{success:!0,rowCount:l,duration:Math.round(performance.now()-w)})}catch(m){console.error("[PrintPlugin] Print failed:",m),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-w)})}finally{this.#u(),this.#n=!1}}#d(e){const t=this.gridElement;if(t){if(this.#t=document.createElement("div"),this.#t.className="tbw-print-header",e.includeTitle){const i=e.title||this.grid.effectiveConfig?.shell?.header?.title||"Grid Data",s=document.createElement("div");s.className="tbw-print-header-title",s.textContent=i,this.#t.appendChild(s)}if(e.includeTimestamp){const i=document.createElement("div");i.className="tbw-print-header-timestamp",i.textContent=`Printed: ${new Date().toLocaleString()}`,this.#t.appendChild(i)}t.insertBefore(this.#t,t.firstChild),this.#i=document.createElement("div"),this.#i.className="tbw-print-footer",this.#i.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#i)}}async#p(){const e=this.#s;if(!e._virtualization)return;const t=this.rows.length;e._virtualization.bypassThreshold=t+100,e.refreshVirtualWindow(!0),await new Promise(i=>setTimeout(i,100))}async#m(){return new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{window.removeEventListener("afterprint",t),e()},1e3)})}async#h(e){const t=this.gridElement;t&&await c(t,{orientation:e.orientation})}#c(){const e=this.columns;if(e){this.#e=new Map;for(const t of e)t.printHidden&&t.field&&(this.#e.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#w(){if(this.#e){for(const[e,t]of this.#e)this.grid.setColumnVisible(e,t);this.#e=null}}#u(){const e=this.gridElement;if(!e)return;this.#w(),e.classList.remove("print-portrait","print-landscape"),this.#a!==null&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#a=null),this.#t&&(this.#t.remove(),this.#t=null),this.#i&&(this.#i.remove(),this.#i=null);const t=this.#s;this.#r&&t._virtualization&&(t._virtualization.bypassThreshold=this.#r.bypassThreshold,t.refreshVirtualWindow(!0),this.#r=null),this.#o!==null&&(this.grid.rows=this.#o,this.#o=null)}afterRender(){this.config?.button&&!this.#l&&(this.#g(),this.#l=!0)}#l=!1;#g(){this.#s.registerToolbarContent?.({id:"print-button",order:900,render:t=>{const i=document.createElement("button");i.className="tbw-toolbar-btn tbw-print-btn",i.title="Print grid",i.type="button";const s=this.resolveIcon("print")||"🖨️";this.setIcon(i,s),i.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),t.appendChild(i)}})}}o.PrintPlugin=f,o.printGridIsolated=c,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
|
|
75
|
+
Click OK to continue, or Cancel to abort.`))return}i.maxRows>0&&a>i.maxRows&&(l=i.maxRows,d=!0),this.#n=!0;const w=performance.now();this.emit("print-start",{rowCount:l,limitApplied:d,originalRowCount:a});try{const m=this.#s;this.#r={bypassThreshold:m._virtualization?.bypassThreshold??24},this.#c(),d&&(this.#o=this.sourceRows,this.grid.rows=this.sourceRows.slice(0,l),await new Promise(r=>setTimeout(r,50))),(i.includeTitle||i.includeTimestamp)&&this.#d(i),await this.#p(),await new Promise(r=>requestAnimationFrame(r)),await new Promise(r=>requestAnimationFrame(r)),t.classList.add(`print-${i.orientation}`),await new Promise(r=>requestAnimationFrame(r)),await new Promise(r=>requestAnimationFrame(r)),i.isolate?await this.#h(i):await this.#m(),this.emit("print-complete",{success:!0,rowCount:l,duration:Math.round(performance.now()-w)})}catch(m){console.error("[PrintPlugin] Print failed:",m),this.emit("print-complete",{success:!1,rowCount:0,duration:Math.round(performance.now()-w)})}finally{this.#u(),this.#n=!1}}#d(e){const t=this.gridElement;if(t){if(this.#t=document.createElement("div"),this.#t.className="tbw-print-header",e.includeTitle){const i=e.title||this.grid.effectiveConfig?.shell?.header?.title||"Grid Data",s=document.createElement("div");s.className="tbw-print-header-title",s.textContent=i,this.#t.appendChild(s)}if(e.includeTimestamp){const i=document.createElement("div");i.className="tbw-print-header-timestamp",i.textContent=`Printed: ${new Date().toLocaleString()}`,this.#t.appendChild(i)}t.insertBefore(this.#t,t.firstChild),this.#i=document.createElement("div"),this.#i.className="tbw-print-footer",this.#i.textContent=`Page generated from ${window.location.hostname}`,t.appendChild(this.#i)}}async#p(){const e=this.#s;if(!e._virtualization)return;const t=this.rows.length;e._virtualization.bypassThreshold=t+100,e.refreshVirtualWindow(!0),await new Promise(i=>setTimeout(i,100))}async#m(){return new Promise(e=>{const t=()=>{window.removeEventListener("afterprint",t),e()};window.addEventListener("afterprint",t),window.print(),setTimeout(()=>{typeof window<"u"&&window.removeEventListener("afterprint",t),e()},1e3)})}async#h(e){const t=this.gridElement;t&&await c(t,{orientation:e.orientation})}#c(){const e=this.columns;if(e){this.#e=new Map;for(const t of e)t.printHidden&&t.field&&(this.#e.set(t.field,!t.hidden),this.grid.setColumnVisible(t.field,!1))}}#w(){if(this.#e){for(const[e,t]of this.#e)this.grid.setColumnVisible(e,t);this.#e=null}}#u(){const e=this.gridElement;if(!e)return;this.#w(),e.classList.remove("print-portrait","print-landscape"),this.#a!==null&&(e.style.transform="",e.style.transformOrigin="",e.style.width="",this.#a=null),this.#t&&(this.#t.remove(),this.#t=null),this.#i&&(this.#i.remove(),this.#i=null);const t=this.#s;this.#r&&t._virtualization&&(t._virtualization.bypassThreshold=this.#r.bypassThreshold,t.refreshVirtualWindow(!0),this.#r=null),this.#o!==null&&(this.grid.rows=this.#o,this.#o=null)}afterRender(){this.config?.button&&!this.#l&&(this.#g(),this.#l=!0)}#l=!1;#g(){this.#s.registerToolbarContent?.({id:"print-button",order:900,render:t=>{const i=document.createElement("button");i.className="tbw-toolbar-btn tbw-print-btn",i.title="Print grid",i.type="button";const s=this.resolveIcon("print")||"🖨️";this.setIcon(i,s),i.addEventListener("click",()=>{this.print()},{signal:this.disconnectSignal}),t.appendChild(i)}})}}o.PrintPlugin=f,o.printGridIsolated=c,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
|
|
76
76
|
//# sourceMappingURL=print.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"print.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/print/print-isolated.ts","../../../../../libs/grid/src/lib/plugins/print/PrintPlugin.ts"],"sourcesContent":["/**\n * Utility for printing a grid in isolation by hiding all other page content.\n *\n * This approach keeps the grid in place (with virtualization disabled by PrintPlugin)\n * and uses CSS to hide everything else on the page during printing.\n */\n\nimport type { PrintOrientation } from './types';\n\nexport interface PrintIsolatedOptions {\n /** Page orientation hint */\n orientation?: PrintOrientation;\n}\n\n/** ID for the isolation stylesheet */\nconst ISOLATION_STYLE_ID = 'tbw-print-isolation-style';\n\n/**\n * Create a stylesheet that hides everything except the target grid.\n * Uses the grid's ID to target it specifically.\n */\nfunction createIsolationStylesheet(gridId: string, orientation: PrintOrientation): HTMLStyleElement {\n const style = document.createElement('style');\n style.id = ISOLATION_STYLE_ID;\n style.textContent = `\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${gridId}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${gridId} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${gridId},\n #${gridId} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${gridId}),\n body *:has(#${gridId}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${gridId}) > *:not(:has(#${gridId})):not(#${gridId}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${orientation};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `;\n return style;\n}\n\n/**\n * Print a grid in isolation by hiding all other page content.\n *\n * This function adds a temporary stylesheet that uses CSS to hide everything\n * on the page except the target grid during printing. The grid stays in place\n * with all its data (virtualization should be disabled separately).\n *\n * @param gridElement - The tbw-grid element to print (must have an ID)\n * @param options - Optional configuration\n * @returns Promise that resolves when the print dialog closes\n *\n * @example\n * ```typescript\n * import { printGridIsolated } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * await printGridIsolated(grid, { orientation: 'landscape' });\n * ```\n */\nexport async function printGridIsolated(gridElement: HTMLElement, options: PrintIsolatedOptions = {}): Promise<void> {\n const { orientation = 'landscape' } = options;\n\n const gridId = gridElement.id;\n\n // Warn if multiple elements share this ID (user-set IDs could collide)\n const elementsWithId = document.querySelectorAll(`#${CSS.escape(gridId)}`);\n if (elementsWithId.length > 1) {\n console.warn(\n `[tbw-grid:print] Multiple elements found with id=\"${gridId}\". ` +\n `Print isolation may not work correctly. Ensure each grid has a unique ID.`,\n );\n }\n\n // Remove any existing isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n\n // Add the isolation stylesheet\n const isolationStyle = createIsolationStylesheet(gridId, orientation);\n document.head.appendChild(isolationStyle);\n\n return new Promise((resolve) => {\n // Listen for afterprint event to cleanup\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n // Remove isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n }, 5000);\n });\n}\n","/**\n * Print Plugin (Class-based)\n *\n * Provides print layout functionality for tbw-grid.\n * Temporarily disables virtualization to render all rows and uses\n * @media print CSS for print-optimized styling.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { InternalGrid, ToolbarContentDefinition } from '../../core/types';\nimport { printGridIsolated } from './print-isolated';\nimport styles from './print.css?inline';\nimport type { PrintCompleteDetail, PrintConfig, PrintParams, PrintStartDetail } from './types';\n\n/**\n * Extended grid interface for PrintPlugin internal access.\n * Includes registerToolbarContent which is available on the grid class\n * but not exposed in the standard plugin API.\n */\ninterface PrintGridRef extends InternalGrid {\n registerToolbarContent?(content: ToolbarContentDefinition): void;\n unregisterToolbarContent?(contentId: string): void;\n}\n\n/** Default configuration */\nconst DEFAULT_CONFIG: Required<PrintConfig> = {\n button: false,\n orientation: 'landscape',\n warnThreshold: 500,\n maxRows: 0,\n includeTitle: true,\n includeTimestamp: true,\n title: '',\n isolate: false,\n};\n\n/**\n * Print Plugin for tbw-grid\n *\n * Enables printing the full grid content by temporarily disabling virtualization\n * and applying print-optimized styles. Handles large datasets gracefully with\n * configurable row limits.\n *\n * ## Installation\n *\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `button` | `boolean` | `false` | Show print button in toolbar |\n * | `orientation` | `'portrait' \\| 'landscape'` | `'landscape'` | Page orientation |\n * | `warnThreshold` | `number` | `500` | Show confirmation dialog when rows exceed this (0 = no warning) |\n * | `maxRows` | `number` | `0` | Hard limit on printed rows (0 = unlimited) |\n * | `includeTitle` | `boolean` | `true` | Include grid title in print |\n * | `includeTimestamp` | `boolean` | `true` | Include timestamp in footer |\n * | `title` | `string` | `''` | Custom print title |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `print` | `(params?) => Promise<void>` | Trigger print dialog |\n * | `isPrinting` | `() => boolean` | Check if print is in progress |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `print-start` | `PrintStartDetail` | Fired when print begins |\n * | `print-complete` | `PrintCompleteDetail` | Fired when print completes |\n *\n * @example Basic Print\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * plugins: [new PrintPlugin()],\n * };\n *\n * // Trigger print\n * const printPlugin = grid.getPlugin(PrintPlugin);\n * await printPlugin.print();\n * ```\n *\n * @example With Toolbar Button\n * ```ts\n * grid.gridConfig = {\n * plugins: [new PrintPlugin({ button: true, orientation: 'landscape' })],\n * };\n * ```\n *\n * @see {@link PrintConfig} for all configuration options\n */\nexport class PrintPlugin extends BaseGridPlugin<PrintConfig> {\n /** @internal */\n readonly name = 'print';\n\n /** @internal */\n override readonly version = '1.0.0';\n\n /** CSS styles for print mode */\n override readonly styles = styles;\n\n /** Current print state */\n #printing = false;\n\n /** Saved column visibility state */\n #savedHiddenColumns: Map<string, boolean> | null = null;\n\n /** Saved virtualization state */\n #savedVirtualization: { bypassThreshold: number } | null = null;\n\n /** Saved rows when maxRows limit is applied */\n #savedRows: unknown[] | null = null;\n\n /** Print header element */\n #printHeader: HTMLElement | null = null;\n\n /** Print footer element */\n #printFooter: HTMLElement | null = null;\n\n /** Applied scale factor (legacy, used for cleanup) */\n #appliedScale: number | null = null;\n\n /**\n * Get the grid typed as PrintGridRef for internal access.\n */\n get #internalGrid(): PrintGridRef {\n return this.grid as unknown as PrintGridRef;\n }\n\n /**\n * Check if print is currently in progress\n */\n isPrinting(): boolean {\n return this.#printing;\n }\n\n /**\n * Trigger the browser print dialog\n *\n * This method:\n * 1. Validates row count against maxRows limit\n * 2. Disables virtualization to render all rows\n * 3. Applies print-specific CSS classes\n * 4. Opens the browser print dialog (or isolated window if `isolate: true`)\n * 5. Restores normal state after printing\n *\n * @param params - Optional parameters to override config for this print\n * @param params.isolate - If true, prints in an isolated window containing only the grid\n * @returns Promise that resolves when print dialog closes\n */\n async print(params?: PrintParams): Promise<void> {\n if (this.#printing) {\n console.warn('[PrintPlugin] Print already in progress');\n return;\n }\n\n const grid = this.gridElement;\n if (!grid) {\n console.warn('[PrintPlugin] Grid not available');\n return;\n }\n\n const config = { ...DEFAULT_CONFIG, ...this.config, ...params };\n const rows = this.rows;\n const originalRowCount = rows.length;\n let rowCount = originalRowCount;\n let limitApplied = false;\n\n // Check if we should warn about large datasets\n if (config.warnThreshold > 0 && originalRowCount > config.warnThreshold) {\n const limitInfo =\n config.maxRows > 0 ? `\\n\\nNote: Output will be limited to ${config.maxRows.toLocaleString()} rows.` : '';\n const proceed = confirm(\n `This grid has ${originalRowCount.toLocaleString()} rows. ` +\n `Printing large datasets may cause performance issues or browser slowdowns.${limitInfo}\\n\\n` +\n `Click OK to continue, or Cancel to abort.`,\n );\n if (!proceed) {\n return;\n }\n }\n\n // Apply hard row limit if configured\n if (config.maxRows > 0 && originalRowCount > config.maxRows) {\n rowCount = config.maxRows;\n limitApplied = true;\n }\n\n this.#printing = true;\n\n // Track timing for duration reporting\n const startTime = performance.now();\n\n // Emit print-start event\n this.emit<PrintStartDetail>('print-start', {\n rowCount,\n limitApplied,\n originalRowCount,\n });\n\n try {\n // Save current virtualization state\n const internalGrid = this.#internalGrid;\n this.#savedVirtualization = {\n bypassThreshold: internalGrid._virtualization?.bypassThreshold ?? 24,\n };\n\n // Hide columns marked with printHidden\n this.#hidePrintColumns();\n\n // Apply row limit if configured\n if (limitApplied) {\n this.#savedRows = this.sourceRows;\n // Set limited rows on the grid\n (this.grid as unknown as { rows: unknown[] }).rows = this.sourceRows.slice(0, rowCount);\n // Wait for grid to process new rows\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Add print header if configured\n if (config.includeTitle || config.includeTimestamp) {\n this.#addPrintHeader(config);\n }\n\n // Disable virtualization to render all rows\n // This forces the grid to render all rows in the DOM\n await this.#disableVirtualization();\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Add orientation class for @page rules\n grid.classList.add(`print-${config.orientation}`);\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Trigger browser print dialog (isolated or inline)\n if (config.isolate) {\n await this.#printInIsolatedWindow(config);\n } else {\n await this.#triggerPrint();\n }\n\n // Emit print-complete event\n this.emit<PrintCompleteDetail>('print-complete', {\n success: true,\n rowCount,\n duration: Math.round(performance.now() - startTime),\n });\n } catch (error) {\n console.error('[PrintPlugin] Print failed:', error);\n this.emit<PrintCompleteDetail>('print-complete', {\n success: false,\n rowCount: 0,\n duration: Math.round(performance.now() - startTime),\n });\n } finally {\n // Restore normal state\n this.#cleanup();\n this.#printing = false;\n }\n }\n\n /**\n * Add print header with title and timestamp\n */\n #addPrintHeader(config: Required<PrintConfig>): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Create print header\n this.#printHeader = document.createElement('div');\n this.#printHeader.className = 'tbw-print-header';\n\n // Title\n if (config.includeTitle) {\n const title = config.title || this.grid.effectiveConfig?.shell?.header?.title || 'Grid Data';\n const titleEl = document.createElement('div');\n titleEl.className = 'tbw-print-header-title';\n titleEl.textContent = title;\n this.#printHeader.appendChild(titleEl);\n }\n\n // Timestamp\n if (config.includeTimestamp) {\n const timestampEl = document.createElement('div');\n timestampEl.className = 'tbw-print-header-timestamp';\n timestampEl.textContent = `Printed: ${new Date().toLocaleString()}`;\n this.#printHeader.appendChild(timestampEl);\n }\n\n // Insert at the beginning of the grid\n grid.insertBefore(this.#printHeader, grid.firstChild);\n\n // Create print footer\n this.#printFooter = document.createElement('div');\n this.#printFooter.className = 'tbw-print-footer';\n this.#printFooter.textContent = `Page generated from ${window.location.hostname}`;\n grid.appendChild(this.#printFooter);\n }\n\n /**\n * Disable virtualization to render all rows\n */\n async #disableVirtualization(): Promise<void> {\n const internalGrid = this.#internalGrid;\n if (!internalGrid._virtualization) return;\n\n // Set bypass threshold higher than total row count to disable virtualization\n // This makes the grid render all rows (up to maxRows) instead of just visible ones\n const totalRows = this.rows.length;\n internalGrid._virtualization.bypassThreshold = totalRows + 100;\n\n // Force a full refresh to re-render with virtualization disabled\n internalGrid.refreshVirtualWindow(true);\n\n // Wait for render to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Trigger the browser print dialog\n */\n async #triggerPrint(): Promise<void> {\n return new Promise((resolve) => {\n // Listen for afterprint event\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n }, 1000);\n });\n }\n\n /**\n * Print in isolation by hiding all other page content.\n * This excludes navigation, sidebars, etc. while keeping the grid in place.\n */\n async #printInIsolatedWindow(config: Required<PrintConfig>): Promise<void> {\n const grid = this.gridElement;\n if (!grid) return;\n\n await printGridIsolated(grid, {\n orientation: config.orientation,\n });\n }\n\n /**\n * Hide columns marked with printHidden: true\n */\n #hidePrintColumns(): void {\n const columns = this.columns;\n if (!columns) return;\n\n // Save current hidden state and hide print columns\n this.#savedHiddenColumns = new Map();\n\n for (const col of columns) {\n if (col.printHidden && col.field) {\n // Save current visibility state (true = visible, false = hidden)\n this.#savedHiddenColumns.set(col.field, !col.hidden);\n // Hide the column for printing\n this.grid.setColumnVisible(col.field, false);\n }\n }\n }\n\n /**\n * Restore columns that were hidden for printing\n */\n #restorePrintColumns(): void {\n if (!this.#savedHiddenColumns) return;\n\n for (const [field, wasVisible] of this.#savedHiddenColumns) {\n // Restore original visibility\n this.grid.setColumnVisible(field, wasVisible);\n }\n\n this.#savedHiddenColumns = null;\n }\n\n /**\n * Cleanup after printing\n */\n #cleanup(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Restore columns that were hidden for printing\n this.#restorePrintColumns();\n\n // Remove orientation classes (both original and possibly switched)\n grid.classList.remove('print-portrait', 'print-landscape');\n\n // Remove scaling transform if applied (legacy)\n if (this.#appliedScale !== null) {\n grid.style.transform = '';\n grid.style.transformOrigin = '';\n grid.style.width = '';\n this.#appliedScale = null;\n }\n\n // Remove print header/footer\n if (this.#printHeader) {\n this.#printHeader.remove();\n this.#printHeader = null;\n }\n if (this.#printFooter) {\n this.#printFooter.remove();\n this.#printFooter = null;\n }\n\n // Restore virtualization\n const internalGrid = this.#internalGrid;\n if (this.#savedVirtualization && internalGrid._virtualization) {\n internalGrid._virtualization.bypassThreshold = this.#savedVirtualization.bypassThreshold;\n internalGrid.refreshVirtualWindow(true);\n this.#savedVirtualization = null;\n }\n\n // Restore original rows if they were limited\n if (this.#savedRows !== null) {\n (this.grid as unknown as { rows: unknown[] }).rows = this.#savedRows;\n this.#savedRows = null;\n }\n }\n\n /**\n * Register toolbar button if configured\n * @internal\n */\n override afterRender(): void {\n // Register toolbar on first render when button is enabled\n if (this.config?.button && !this.#toolbarRegistered) {\n this.#registerToolbarButton();\n this.#toolbarRegistered = true;\n }\n }\n\n /** Track if toolbar button is registered */\n #toolbarRegistered = false;\n\n /**\n * Register print button in toolbar\n */\n #registerToolbarButton(): void {\n const grid = this.#internalGrid;\n\n // Register toolbar content\n grid.registerToolbarContent?.({\n id: 'print-button',\n order: 900, // High order to appear at the end\n render: (container: HTMLElement) => {\n const button = document.createElement('button');\n button.className = 'tbw-toolbar-btn tbw-print-btn';\n button.title = 'Print grid';\n button.type = 'button';\n\n // Use print icon\n const icon = this.resolveIcon('print') || '🖨️';\n this.setIcon(button, icon);\n\n button.addEventListener(\n 'click',\n () => {\n this.print();\n },\n { signal: this.disconnectSignal },\n );\n\n container.appendChild(button);\n },\n });\n }\n}\n"],"names":["ISOLATION_STYLE_ID","createIsolationStylesheet","gridId","orientation","style","printGridIsolated","gridElement","options","isolationStyle","resolve","onAfterPrint","DEFAULT_CONFIG","PrintPlugin","BaseGridPlugin","styles","#printing","#savedHiddenColumns","#savedVirtualization","#savedRows","#printHeader","#printFooter","#appliedScale","#internalGrid","params","grid","config","originalRowCount","rowCount","limitApplied","limitInfo","startTime","internalGrid","#hidePrintColumns","#addPrintHeader","#disableVirtualization","#printInIsolatedWindow","#triggerPrint","error","#cleanup","title","titleEl","timestampEl","totalRows","columns","col","#restorePrintColumns","field","wasVisible","#toolbarRegistered","#registerToolbarButton","container","button","icon"],"mappings":"iUAeA,MAAMA,EAAqB,4BAM3B,SAASC,EAA0BC,EAAgBC,EAAiD,CAClG,MAAMC,EAAQ,SAAS,cAAc,OAAO,EAC5C,OAAAA,EAAM,GAAKJ,EACXI,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA,sBAIAF,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,SAKnBA,CA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P,EACA,CAAE,OAAQ,KAAK,gBAAA,CAAiB,EAGlCD,EAAU,YAAYC,CAAM,CAC9B,CAAA,CACD,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"print.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/print/print-isolated.ts","../../../../../libs/grid/src/lib/plugins/print/PrintPlugin.ts"],"sourcesContent":["/**\n * Utility for printing a grid in isolation by hiding all other page content.\n *\n * This approach keeps the grid in place (with virtualization disabled by PrintPlugin)\n * and uses CSS to hide everything else on the page during printing.\n */\n\nimport type { PrintOrientation } from './types';\n\nexport interface PrintIsolatedOptions {\n /** Page orientation hint */\n orientation?: PrintOrientation;\n}\n\n/** ID for the isolation stylesheet */\nconst ISOLATION_STYLE_ID = 'tbw-print-isolation-style';\n\n/**\n * Create a stylesheet that hides everything except the target grid.\n * Uses the grid's ID to target it specifically.\n */\nfunction createIsolationStylesheet(gridId: string, orientation: PrintOrientation): HTMLStyleElement {\n const style = document.createElement('style');\n style.id = ISOLATION_STYLE_ID;\n style.textContent = `\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${gridId}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${gridId} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${gridId},\n #${gridId} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${gridId}),\n body *:has(#${gridId}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${gridId}) > *:not(:has(#${gridId})):not(#${gridId}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${orientation};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `;\n return style;\n}\n\n/**\n * Print a grid in isolation by hiding all other page content.\n *\n * This function adds a temporary stylesheet that uses CSS to hide everything\n * on the page except the target grid during printing. The grid stays in place\n * with all its data (virtualization should be disabled separately).\n *\n * @param gridElement - The tbw-grid element to print (must have an ID)\n * @param options - Optional configuration\n * @returns Promise that resolves when the print dialog closes\n *\n * @example\n * ```typescript\n * import { printGridIsolated } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * await printGridIsolated(grid, { orientation: 'landscape' });\n * ```\n */\nexport async function printGridIsolated(gridElement: HTMLElement, options: PrintIsolatedOptions = {}): Promise<void> {\n const { orientation = 'landscape' } = options;\n\n const gridId = gridElement.id;\n\n // Warn if multiple elements share this ID (user-set IDs could collide)\n const elementsWithId = document.querySelectorAll(`#${CSS.escape(gridId)}`);\n if (elementsWithId.length > 1) {\n console.warn(\n `[tbw-grid:print] Multiple elements found with id=\"${gridId}\". ` +\n `Print isolation may not work correctly. Ensure each grid has a unique ID.`,\n );\n }\n\n // Remove any existing isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n\n // Add the isolation stylesheet\n const isolationStyle = createIsolationStylesheet(gridId, orientation);\n document.head.appendChild(isolationStyle);\n\n return new Promise((resolve) => {\n // Listen for afterprint event to cleanup\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n // Remove isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n }, 5000);\n });\n}\n","/**\n * Print Plugin (Class-based)\n *\n * Provides print layout functionality for tbw-grid.\n * Temporarily disables virtualization to render all rows and uses\n * @media print CSS for print-optimized styling.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { InternalGrid, ToolbarContentDefinition } from '../../core/types';\nimport { printGridIsolated } from './print-isolated';\nimport styles from './print.css?inline';\nimport type { PrintCompleteDetail, PrintConfig, PrintParams, PrintStartDetail } from './types';\n\n/**\n * Extended grid interface for PrintPlugin internal access.\n * Includes registerToolbarContent which is available on the grid class\n * but not exposed in the standard plugin API.\n */\ninterface PrintGridRef extends InternalGrid {\n registerToolbarContent?(content: ToolbarContentDefinition): void;\n unregisterToolbarContent?(contentId: string): void;\n}\n\n/** Default configuration */\nconst DEFAULT_CONFIG: Required<PrintConfig> = {\n button: false,\n orientation: 'landscape',\n warnThreshold: 500,\n maxRows: 0,\n includeTitle: true,\n includeTimestamp: true,\n title: '',\n isolate: false,\n};\n\n/**\n * Print Plugin for tbw-grid\n *\n * Enables printing the full grid content by temporarily disabling virtualization\n * and applying print-optimized styles. Handles large datasets gracefully with\n * configurable row limits.\n *\n * ## Installation\n *\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `button` | `boolean` | `false` | Show print button in toolbar |\n * | `orientation` | `'portrait' \\| 'landscape'` | `'landscape'` | Page orientation |\n * | `warnThreshold` | `number` | `500` | Show confirmation dialog when rows exceed this (0 = no warning) |\n * | `maxRows` | `number` | `0` | Hard limit on printed rows (0 = unlimited) |\n * | `includeTitle` | `boolean` | `true` | Include grid title in print |\n * | `includeTimestamp` | `boolean` | `true` | Include timestamp in footer |\n * | `title` | `string` | `''` | Custom print title |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `print` | `(params?) => Promise<void>` | Trigger print dialog |\n * | `isPrinting` | `() => boolean` | Check if print is in progress |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `print-start` | `PrintStartDetail` | Fired when print begins |\n * | `print-complete` | `PrintCompleteDetail` | Fired when print completes |\n *\n * @example Basic Print\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * plugins: [new PrintPlugin()],\n * };\n *\n * // Trigger print\n * const printPlugin = grid.getPlugin(PrintPlugin);\n * await printPlugin.print();\n * ```\n *\n * @example With Toolbar Button\n * ```ts\n * grid.gridConfig = {\n * plugins: [new PrintPlugin({ button: true, orientation: 'landscape' })],\n * };\n * ```\n *\n * @see {@link PrintConfig} for all configuration options\n */\nexport class PrintPlugin extends BaseGridPlugin<PrintConfig> {\n /** @internal */\n readonly name = 'print';\n\n /** @internal */\n override readonly version = '1.0.0';\n\n /** CSS styles for print mode */\n override readonly styles = styles;\n\n /** Current print state */\n #printing = false;\n\n /** Saved column visibility state */\n #savedHiddenColumns: Map<string, boolean> | null = null;\n\n /** Saved virtualization state */\n #savedVirtualization: { bypassThreshold: number } | null = null;\n\n /** Saved rows when maxRows limit is applied */\n #savedRows: unknown[] | null = null;\n\n /** Print header element */\n #printHeader: HTMLElement | null = null;\n\n /** Print footer element */\n #printFooter: HTMLElement | null = null;\n\n /** Applied scale factor (legacy, used for cleanup) */\n #appliedScale: number | null = null;\n\n /**\n * Get the grid typed as PrintGridRef for internal access.\n */\n get #internalGrid(): PrintGridRef {\n return this.grid as unknown as PrintGridRef;\n }\n\n /**\n * Check if print is currently in progress\n */\n isPrinting(): boolean {\n return this.#printing;\n }\n\n /**\n * Trigger the browser print dialog\n *\n * This method:\n * 1. Validates row count against maxRows limit\n * 2. Disables virtualization to render all rows\n * 3. Applies print-specific CSS classes\n * 4. Opens the browser print dialog (or isolated window if `isolate: true`)\n * 5. Restores normal state after printing\n *\n * @param params - Optional parameters to override config for this print\n * @param params.isolate - If true, prints in an isolated window containing only the grid\n * @returns Promise that resolves when print dialog closes\n */\n async print(params?: PrintParams): Promise<void> {\n if (this.#printing) {\n console.warn('[PrintPlugin] Print already in progress');\n return;\n }\n\n const grid = this.gridElement;\n if (!grid) {\n console.warn('[PrintPlugin] Grid not available');\n return;\n }\n\n const config = { ...DEFAULT_CONFIG, ...this.config, ...params };\n const rows = this.rows;\n const originalRowCount = rows.length;\n let rowCount = originalRowCount;\n let limitApplied = false;\n\n // Check if we should warn about large datasets\n if (config.warnThreshold > 0 && originalRowCount > config.warnThreshold) {\n const limitInfo =\n config.maxRows > 0 ? `\\n\\nNote: Output will be limited to ${config.maxRows.toLocaleString()} rows.` : '';\n const proceed = confirm(\n `This grid has ${originalRowCount.toLocaleString()} rows. ` +\n `Printing large datasets may cause performance issues or browser slowdowns.${limitInfo}\\n\\n` +\n `Click OK to continue, or Cancel to abort.`,\n );\n if (!proceed) {\n return;\n }\n }\n\n // Apply hard row limit if configured\n if (config.maxRows > 0 && originalRowCount > config.maxRows) {\n rowCount = config.maxRows;\n limitApplied = true;\n }\n\n this.#printing = true;\n\n // Track timing for duration reporting\n const startTime = performance.now();\n\n // Emit print-start event\n this.emit<PrintStartDetail>('print-start', {\n rowCount,\n limitApplied,\n originalRowCount,\n });\n\n try {\n // Save current virtualization state\n const internalGrid = this.#internalGrid;\n this.#savedVirtualization = {\n bypassThreshold: internalGrid._virtualization?.bypassThreshold ?? 24,\n };\n\n // Hide columns marked with printHidden\n this.#hidePrintColumns();\n\n // Apply row limit if configured\n if (limitApplied) {\n this.#savedRows = this.sourceRows;\n // Set limited rows on the grid\n (this.grid as unknown as { rows: unknown[] }).rows = this.sourceRows.slice(0, rowCount);\n // Wait for grid to process new rows\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Add print header if configured\n if (config.includeTitle || config.includeTimestamp) {\n this.#addPrintHeader(config);\n }\n\n // Disable virtualization to render all rows\n // This forces the grid to render all rows in the DOM\n await this.#disableVirtualization();\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Add orientation class for @page rules\n grid.classList.add(`print-${config.orientation}`);\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Trigger browser print dialog (isolated or inline)\n if (config.isolate) {\n await this.#printInIsolatedWindow(config);\n } else {\n await this.#triggerPrint();\n }\n\n // Emit print-complete event\n this.emit<PrintCompleteDetail>('print-complete', {\n success: true,\n rowCount,\n duration: Math.round(performance.now() - startTime),\n });\n } catch (error) {\n console.error('[PrintPlugin] Print failed:', error);\n this.emit<PrintCompleteDetail>('print-complete', {\n success: false,\n rowCount: 0,\n duration: Math.round(performance.now() - startTime),\n });\n } finally {\n // Restore normal state\n this.#cleanup();\n this.#printing = false;\n }\n }\n\n /**\n * Add print header with title and timestamp\n */\n #addPrintHeader(config: Required<PrintConfig>): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Create print header\n this.#printHeader = document.createElement('div');\n this.#printHeader.className = 'tbw-print-header';\n\n // Title\n if (config.includeTitle) {\n const title = config.title || this.grid.effectiveConfig?.shell?.header?.title || 'Grid Data';\n const titleEl = document.createElement('div');\n titleEl.className = 'tbw-print-header-title';\n titleEl.textContent = title;\n this.#printHeader.appendChild(titleEl);\n }\n\n // Timestamp\n if (config.includeTimestamp) {\n const timestampEl = document.createElement('div');\n timestampEl.className = 'tbw-print-header-timestamp';\n timestampEl.textContent = `Printed: ${new Date().toLocaleString()}`;\n this.#printHeader.appendChild(timestampEl);\n }\n\n // Insert at the beginning of the grid\n grid.insertBefore(this.#printHeader, grid.firstChild);\n\n // Create print footer\n this.#printFooter = document.createElement('div');\n this.#printFooter.className = 'tbw-print-footer';\n this.#printFooter.textContent = `Page generated from ${window.location.hostname}`;\n grid.appendChild(this.#printFooter);\n }\n\n /**\n * Disable virtualization to render all rows\n */\n async #disableVirtualization(): Promise<void> {\n const internalGrid = this.#internalGrid;\n if (!internalGrid._virtualization) return;\n\n // Set bypass threshold higher than total row count to disable virtualization\n // This makes the grid render all rows (up to maxRows) instead of just visible ones\n const totalRows = this.rows.length;\n internalGrid._virtualization.bypassThreshold = totalRows + 100;\n\n // Force a full refresh to re-render with virtualization disabled\n internalGrid.refreshVirtualWindow(true);\n\n // Wait for render to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Trigger the browser print dialog\n */\n async #triggerPrint(): Promise<void> {\n return new Promise((resolve) => {\n // Listen for afterprint event\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n // Guard against test environment teardown where window may be undefined\n if (typeof window !== 'undefined') {\n window.removeEventListener('afterprint', onAfterPrint);\n }\n resolve();\n }, 1000);\n });\n }\n\n /**\n * Print in isolation by hiding all other page content.\n * This excludes navigation, sidebars, etc. while keeping the grid in place.\n */\n async #printInIsolatedWindow(config: Required<PrintConfig>): Promise<void> {\n const grid = this.gridElement;\n if (!grid) return;\n\n await printGridIsolated(grid, {\n orientation: config.orientation,\n });\n }\n\n /**\n * Hide columns marked with printHidden: true\n */\n #hidePrintColumns(): void {\n const columns = this.columns;\n if (!columns) return;\n\n // Save current hidden state and hide print columns\n this.#savedHiddenColumns = new Map();\n\n for (const col of columns) {\n if (col.printHidden && col.field) {\n // Save current visibility state (true = visible, false = hidden)\n this.#savedHiddenColumns.set(col.field, !col.hidden);\n // Hide the column for printing\n this.grid.setColumnVisible(col.field, false);\n }\n }\n }\n\n /**\n * Restore columns that were hidden for printing\n */\n #restorePrintColumns(): void {\n if (!this.#savedHiddenColumns) return;\n\n for (const [field, wasVisible] of this.#savedHiddenColumns) {\n // Restore original visibility\n this.grid.setColumnVisible(field, wasVisible);\n }\n\n this.#savedHiddenColumns = null;\n }\n\n /**\n * Cleanup after printing\n */\n #cleanup(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Restore columns that were hidden for printing\n this.#restorePrintColumns();\n\n // Remove orientation classes (both original and possibly switched)\n grid.classList.remove('print-portrait', 'print-landscape');\n\n // Remove scaling transform if applied (legacy)\n if (this.#appliedScale !== null) {\n grid.style.transform = '';\n grid.style.transformOrigin = '';\n grid.style.width = '';\n this.#appliedScale = null;\n }\n\n // Remove print header/footer\n if (this.#printHeader) {\n this.#printHeader.remove();\n this.#printHeader = null;\n }\n if (this.#printFooter) {\n this.#printFooter.remove();\n this.#printFooter = null;\n }\n\n // Restore virtualization\n const internalGrid = this.#internalGrid;\n if (this.#savedVirtualization && internalGrid._virtualization) {\n internalGrid._virtualization.bypassThreshold = this.#savedVirtualization.bypassThreshold;\n internalGrid.refreshVirtualWindow(true);\n this.#savedVirtualization = null;\n }\n\n // Restore original rows if they were limited\n if (this.#savedRows !== null) {\n (this.grid as unknown as { rows: unknown[] }).rows = this.#savedRows;\n this.#savedRows = null;\n }\n }\n\n /**\n * Register toolbar button if configured\n * @internal\n */\n override afterRender(): void {\n // Register toolbar on first render when button is enabled\n if (this.config?.button && !this.#toolbarRegistered) {\n this.#registerToolbarButton();\n this.#toolbarRegistered = true;\n }\n }\n\n /** Track if toolbar button is registered */\n #toolbarRegistered = false;\n\n /**\n * Register print button in toolbar\n */\n #registerToolbarButton(): void {\n const grid = this.#internalGrid;\n\n // Register toolbar content\n grid.registerToolbarContent?.({\n id: 'print-button',\n order: 900, // High order to appear at the end\n render: (container: HTMLElement) => {\n const button = document.createElement('button');\n button.className = 'tbw-toolbar-btn tbw-print-btn';\n button.title = 'Print grid';\n button.type = 'button';\n\n // Use print icon\n const icon = this.resolveIcon('print') || '🖨️';\n this.setIcon(button, icon);\n\n button.addEventListener(\n 'click',\n () => {\n this.print();\n },\n { signal: this.disconnectSignal },\n );\n\n container.appendChild(button);\n },\n });\n }\n}\n"],"names":["ISOLATION_STYLE_ID","createIsolationStylesheet","gridId","orientation","style","printGridIsolated","gridElement","options","isolationStyle","resolve","onAfterPrint","DEFAULT_CONFIG","PrintPlugin","BaseGridPlugin","styles","#printing","#savedHiddenColumns","#savedVirtualization","#savedRows","#printHeader","#printFooter","#appliedScale","#internalGrid","params","grid","config","originalRowCount","rowCount","limitApplied","limitInfo","startTime","internalGrid","#hidePrintColumns","#addPrintHeader","#disableVirtualization","#printInIsolatedWindow","#triggerPrint","error","#cleanup","title","titleEl","timestampEl","totalRows","columns","col","#restorePrintColumns","field","wasVisible","#toolbarRegistered","#registerToolbarButton","container","button","icon"],"mappings":"iUAeA,MAAMA,EAAqB,4BAM3B,SAASC,EAA0BC,EAAgBC,EAAiD,CAClG,MAAMC,EAAQ,SAAS,cAAc,OAAO,EAC5C,OAAAA,EAAM,GAAKJ,EACXI,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA,sBAIAF,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,SAKnBA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAeNA,CAAM;AAAA,SACNA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,sBAKOA,CAAM;AAAA,oBACRA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAeNA,CAAM,mBAAmBA,CAAM,WAAWA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAMpDC,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAmBlBC,CACT,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