@toolbox-web/grid 1.23.3 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +35 -6
  2. package/all.d.ts +2 -2
  3. package/all.d.ts.map +1 -1
  4. package/all.js +2 -2
  5. package/all.js.map +1 -1
  6. package/index.js +1 -1
  7. package/index.js.map +1 -1
  8. package/lib/core/grid.d.ts +28 -0
  9. package/lib/core/grid.d.ts.map +1 -1
  10. package/lib/core/internal/feature-hook.d.ts +8 -0
  11. package/lib/core/internal/feature-hook.d.ts.map +1 -0
  12. package/lib/core/plugin/base-plugin.d.ts +14 -2
  13. package/lib/core/plugin/base-plugin.d.ts.map +1 -1
  14. package/lib/core/plugin/types.d.ts +2 -1
  15. package/lib/core/plugin/types.d.ts.map +1 -1
  16. package/lib/core/types.d.ts +68 -2
  17. package/lib/core/types.d.ts.map +1 -1
  18. package/lib/features/clipboard.d.ts +8 -0
  19. package/lib/features/clipboard.d.ts.map +1 -0
  20. package/lib/features/clipboard.js +2 -0
  21. package/lib/features/clipboard.js.map +1 -0
  22. package/lib/features/column-virtualization.d.ts +8 -0
  23. package/lib/features/column-virtualization.d.ts.map +1 -0
  24. package/lib/features/column-virtualization.js +2 -0
  25. package/lib/features/column-virtualization.js.map +1 -0
  26. package/lib/features/context-menu.d.ts +8 -0
  27. package/lib/features/context-menu.d.ts.map +1 -0
  28. package/lib/features/context-menu.js +2 -0
  29. package/lib/features/context-menu.js.map +1 -0
  30. package/lib/features/editing.d.ts +8 -0
  31. package/lib/features/editing.d.ts.map +1 -0
  32. package/lib/features/editing.js +2 -0
  33. package/lib/features/editing.js.map +1 -0
  34. package/lib/features/export.d.ts +8 -0
  35. package/lib/features/export.d.ts.map +1 -0
  36. package/lib/features/export.js +2 -0
  37. package/lib/features/export.js.map +1 -0
  38. package/lib/features/filtering.d.ts +8 -0
  39. package/lib/features/filtering.d.ts.map +1 -0
  40. package/lib/features/filtering.js +2 -0
  41. package/lib/features/filtering.js.map +1 -0
  42. package/lib/features/grouping-columns.d.ts +8 -0
  43. package/lib/features/grouping-columns.d.ts.map +1 -0
  44. package/lib/features/grouping-columns.js +2 -0
  45. package/lib/features/grouping-columns.js.map +1 -0
  46. package/lib/features/grouping-rows.d.ts +8 -0
  47. package/lib/features/grouping-rows.d.ts.map +1 -0
  48. package/lib/features/grouping-rows.js +2 -0
  49. package/lib/features/grouping-rows.js.map +1 -0
  50. package/lib/features/magic-string.es-CkyDP9Ir.mjs.map +1 -0
  51. package/lib/features/master-detail.d.ts +8 -0
  52. package/lib/features/master-detail.d.ts.map +1 -0
  53. package/lib/features/master-detail.js +2 -0
  54. package/lib/features/master-detail.js.map +1 -0
  55. package/lib/features/multi-sort.d.ts +10 -0
  56. package/lib/features/multi-sort.d.ts.map +1 -0
  57. package/lib/features/multi-sort.js +2 -0
  58. package/lib/features/multi-sort.js.map +1 -0
  59. package/lib/features/pinned-columns.d.ts +18 -0
  60. package/lib/features/pinned-columns.d.ts.map +1 -0
  61. package/lib/features/pinned-columns.js +2 -0
  62. package/lib/features/pinned-columns.js.map +1 -0
  63. package/lib/features/pinned-rows.d.ts +8 -0
  64. package/lib/features/pinned-rows.d.ts.map +1 -0
  65. package/lib/features/pinned-rows.js +2 -0
  66. package/lib/features/pinned-rows.js.map +1 -0
  67. package/lib/features/pivot.d.ts +8 -0
  68. package/lib/features/pivot.d.ts.map +1 -0
  69. package/lib/features/pivot.js +2 -0
  70. package/lib/features/pivot.js.map +1 -0
  71. package/lib/features/print.d.ts +8 -0
  72. package/lib/features/print.d.ts.map +1 -0
  73. package/lib/features/print.js +2 -0
  74. package/lib/features/print.js.map +1 -0
  75. package/lib/features/registry.d.ts +50 -0
  76. package/lib/features/registry.d.ts.map +1 -0
  77. package/lib/features/registry.js +2 -0
  78. package/lib/features/registry.js.map +1 -0
  79. package/lib/features/registry.spec.js +5 -0
  80. package/lib/features/registry.spec.js.map +1 -0
  81. package/lib/features/reorder-columns.d.ts +10 -0
  82. package/lib/features/reorder-columns.d.ts.map +1 -0
  83. package/lib/features/reorder-columns.js +2 -0
  84. package/lib/features/reorder-columns.js.map +1 -0
  85. package/lib/features/reorder-rows.d.ts +10 -0
  86. package/lib/features/reorder-rows.d.ts.map +1 -0
  87. package/lib/features/reorder-rows.js +2 -0
  88. package/lib/features/reorder-rows.js.map +1 -0
  89. package/lib/features/responsive.d.ts +8 -0
  90. package/lib/features/responsive.d.ts.map +1 -0
  91. package/lib/features/responsive.js +2 -0
  92. package/lib/features/responsive.js.map +1 -0
  93. package/lib/features/selection.d.ts +8 -0
  94. package/lib/features/selection.d.ts.map +1 -0
  95. package/lib/features/selection.js +2 -0
  96. package/lib/features/selection.js.map +1 -0
  97. package/lib/features/server-side.d.ts +8 -0
  98. package/lib/features/server-side.d.ts.map +1 -0
  99. package/lib/features/server-side.js +2 -0
  100. package/lib/features/server-side.js.map +1 -0
  101. package/lib/features/tree.d.ts +8 -0
  102. package/lib/features/tree.d.ts.map +1 -0
  103. package/lib/features/tree.js +2 -0
  104. package/lib/features/tree.js.map +1 -0
  105. package/lib/features/undo-redo.d.ts +8 -0
  106. package/lib/features/undo-redo.d.ts.map +1 -0
  107. package/lib/features/undo-redo.js +2 -0
  108. package/lib/features/undo-redo.js.map +1 -0
  109. package/lib/features/visibility.d.ts +8 -0
  110. package/lib/features/visibility.d.ts.map +1 -0
  111. package/lib/features/visibility.js +2 -0
  112. package/lib/features/visibility.js.map +1 -0
  113. package/lib/plugins/clipboard/ClipboardPlugin.d.ts +3 -3
  114. package/lib/plugins/clipboard/index.js +1 -1
  115. package/lib/plugins/clipboard/index.js.map +1 -1
  116. package/lib/plugins/clipboard/types.d.ts +1 -1
  117. package/lib/plugins/column-virtualization/index.js +1 -1
  118. package/lib/plugins/column-virtualization/index.js.map +1 -1
  119. package/lib/plugins/column-virtualization/types.d.ts +24 -2
  120. package/lib/plugins/column-virtualization/types.d.ts.map +1 -1
  121. package/lib/plugins/context-menu/index.js +1 -1
  122. package/lib/plugins/context-menu/index.js.map +1 -1
  123. package/lib/plugins/editing/index.js +1 -1
  124. package/lib/plugins/editing/index.js.map +1 -1
  125. package/lib/plugins/editing/types.d.ts +1 -1
  126. package/lib/plugins/export/ExportPlugin.d.ts +1 -1
  127. package/lib/plugins/export/index.js +1 -1
  128. package/lib/plugins/export/index.js.map +1 -1
  129. package/lib/plugins/export/types.d.ts +9 -1
  130. package/lib/plugins/export/types.d.ts.map +1 -1
  131. package/lib/plugins/filtering/index.js +1 -1
  132. package/lib/plugins/filtering/index.js.map +1 -1
  133. package/lib/plugins/filtering/types.d.ts +586 -29
  134. package/lib/plugins/filtering/types.d.ts.map +1 -1
  135. package/lib/plugins/grouping-columns/index.d.ts +1 -1
  136. package/lib/plugins/grouping-columns/index.js +1 -1
  137. package/lib/plugins/grouping-columns/index.js.map +1 -1
  138. package/lib/plugins/grouping-rows/index.d.ts +2 -2
  139. package/lib/plugins/grouping-rows/index.d.ts.map +1 -1
  140. package/lib/plugins/grouping-rows/index.js +1 -1
  141. package/lib/plugins/grouping-rows/index.js.map +1 -1
  142. package/lib/plugins/grouping-rows/types.d.ts +48 -3
  143. package/lib/plugins/grouping-rows/types.d.ts.map +1 -1
  144. package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +2 -2
  145. package/lib/plugins/master-detail/index.js +1 -1
  146. package/lib/plugins/master-detail/index.js.map +1 -1
  147. package/lib/plugins/multi-sort/index.js +1 -1
  148. package/lib/plugins/multi-sort/index.js.map +1 -1
  149. package/lib/plugins/multi-sort/types.d.ts +40 -6
  150. package/lib/plugins/multi-sort/types.d.ts.map +1 -1
  151. package/lib/plugins/pinned-columns/index.js +1 -1
  152. package/lib/plugins/pinned-columns/index.js.map +1 -1
  153. package/lib/plugins/pinned-columns/types.d.ts +3 -3
  154. package/lib/plugins/pinned-rows/index.js +1 -1
  155. package/lib/plugins/pinned-rows/index.js.map +1 -1
  156. package/lib/plugins/pinned-rows/types.d.ts +42 -4
  157. package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
  158. package/lib/plugins/pivot/index.js +1 -1
  159. package/lib/plugins/pivot/index.js.map +1 -1
  160. package/lib/plugins/pivot/types.d.ts +66 -1
  161. package/lib/plugins/pivot/types.d.ts.map +1 -1
  162. package/lib/plugins/print/PrintPlugin.d.ts +1 -1
  163. package/lib/plugins/print/index.js +1 -1
  164. package/lib/plugins/print/index.js.map +1 -1
  165. package/lib/plugins/print/types.d.ts +9 -1
  166. package/lib/plugins/print/types.d.ts.map +1 -1
  167. package/lib/plugins/{reorder → reorder-columns}/ReorderPlugin.d.ts +5 -3
  168. package/lib/plugins/reorder-columns/ReorderPlugin.d.ts.map +1 -0
  169. package/lib/plugins/reorder-columns/column-drag.d.ts.map +1 -0
  170. package/lib/plugins/{reorder → reorder-columns}/index.d.ts +2 -2
  171. package/lib/plugins/reorder-columns/index.d.ts.map +1 -0
  172. package/lib/plugins/reorder-columns/index.js +2 -0
  173. package/lib/plugins/reorder-columns/index.js.map +1 -0
  174. package/lib/plugins/{reorder → reorder-columns}/types.d.ts +17 -1
  175. package/lib/plugins/reorder-columns/types.d.ts.map +1 -0
  176. package/lib/plugins/{row-reorder → reorder-rows}/RowReorderPlugin.d.ts +5 -3
  177. package/lib/plugins/reorder-rows/RowReorderPlugin.d.ts.map +1 -0
  178. package/lib/plugins/{row-reorder → reorder-rows}/index.d.ts +2 -2
  179. package/lib/plugins/reorder-rows/index.d.ts.map +1 -0
  180. package/lib/plugins/reorder-rows/index.js +2 -0
  181. package/lib/plugins/reorder-rows/index.js.map +1 -0
  182. package/lib/plugins/{row-reorder → reorder-rows}/types.d.ts +5 -0
  183. package/lib/plugins/reorder-rows/types.d.ts.map +1 -0
  184. package/lib/plugins/responsive/ResponsivePlugin.d.ts +2 -2
  185. package/lib/plugins/responsive/index.js +1 -1
  186. package/lib/plugins/responsive/index.js.map +1 -1
  187. package/lib/plugins/selection/SelectionPlugin.d.ts +5 -5
  188. package/lib/plugins/selection/index.js +1 -1
  189. package/lib/plugins/selection/index.js.map +1 -1
  190. package/lib/plugins/server-side/index.js +1 -1
  191. package/lib/plugins/server-side/index.js.map +1 -1
  192. package/lib/plugins/server-side/types.d.ts +82 -0
  193. package/lib/plugins/server-side/types.d.ts.map +1 -1
  194. package/lib/plugins/tree/index.js +1 -1
  195. package/lib/plugins/tree/index.js.map +1 -1
  196. package/lib/plugins/undo-redo/index.js +1 -1
  197. package/lib/plugins/undo-redo/index.js.map +1 -1
  198. package/lib/plugins/visibility/VisibilityPlugin.d.ts +2 -2
  199. package/lib/plugins/visibility/index.js +1 -1
  200. package/lib/plugins/visibility/index.js.map +1 -1
  201. package/lib/plugins/visibility/types.d.ts +16 -2
  202. package/lib/plugins/visibility/types.d.ts.map +1 -1
  203. package/package.json +17 -2
  204. package/public.d.ts +9 -2
  205. package/public.d.ts.map +1 -1
  206. package/umd/grid.all.umd.js +1 -1
  207. package/umd/grid.all.umd.js.map +1 -1
  208. package/umd/grid.umd.js +1 -1
  209. package/umd/grid.umd.js.map +1 -1
  210. package/umd/plugins/clipboard.umd.js.map +1 -1
  211. package/umd/plugins/export.umd.js.map +1 -1
  212. package/umd/plugins/master-detail.umd.js.map +1 -1
  213. package/umd/plugins/print.umd.js.map +1 -1
  214. package/umd/plugins/reorder-columns.umd.js +2 -0
  215. package/umd/plugins/reorder-columns.umd.js.map +1 -0
  216. package/umd/plugins/reorder-rows.umd.js +2 -0
  217. package/umd/plugins/reorder-rows.umd.js.map +1 -0
  218. package/umd/plugins/responsive.umd.js.map +1 -1
  219. package/umd/plugins/selection.umd.js.map +1 -1
  220. package/umd/plugins/visibility.umd.js.map +1 -1
  221. package/lib/plugins/reorder/ReorderPlugin.d.ts.map +0 -1
  222. package/lib/plugins/reorder/column-drag.d.ts.map +0 -1
  223. package/lib/plugins/reorder/index.d.ts.map +0 -1
  224. package/lib/plugins/reorder/index.js +0 -2
  225. package/lib/plugins/reorder/index.js.map +0 -1
  226. package/lib/plugins/reorder/types.d.ts.map +0 -1
  227. package/lib/plugins/row-reorder/RowReorderPlugin.d.ts.map +0 -1
  228. package/lib/plugins/row-reorder/index.d.ts.map +0 -1
  229. package/lib/plugins/row-reorder/index.js +0 -2
  230. package/lib/plugins/row-reorder/index.js.map +0 -1
  231. package/lib/plugins/row-reorder/types.d.ts.map +0 -1
  232. package/umd/plugins/reorder.umd.js +0 -2
  233. package/umd/plugins/reorder.umd.js.map +0 -1
  234. package/umd/plugins/row-reorder.umd.js +0 -2
  235. package/umd/plugins/row-reorder.umd.js.map +0 -1
  236. /package/lib/plugins/{reorder → reorder-columns}/column-drag.d.ts +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Returns a new Set with the updated state.\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n if (newExpanded.has(row)) {\n newExpanded.delete(row);\n } else {\n newExpanded.add(row);\n }\n return newExpanded;\n}\n\n/**\n * Expand a detail row.\n * Returns a new Set with the row added.\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.add(row);\n return newExpanded;\n}\n\n/**\n * Collapse a detail row.\n * Returns a new Set with the row removed.\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.delete(row);\n return newExpanded;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `detailRenderer` | `(row) => HTMLElement \\| string` | required | Render function for detail content |\n * | `expandOnRowClick` | `boolean` | `false` | Expand when clicking the row |\n * | `detailHeight` | `number \\| 'auto'` | `'auto'` | Fixed height or auto-size |\n * | `collapseOnClickOutside` | `boolean` | `false` | Collapse when clicking outside |\n * | `showExpandColumn` | `boolean` | `true` | Show expand/collapse column |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expandRow` | `(rowIndex) => void` | Expand a specific row |\n * | `collapseRow` | `(rowIndex) => void` | Collapse a specific row |\n * | `toggleRow` | `(rowIndex) => void` | Toggle row expansion |\n * | `expandAll` | `() => void` | Expand all rows |\n * | `collapseAll` | `() => void` | Collapse all rows |\n * | `isRowExpanded` | `(rowIndex) => boolean` | Check if row is expanded |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseDetailElement?: (el: Element) => ((row: any, rowIndex: number) => HTMLElement | string) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseDetailElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, this.resolveIcon(isExpanded ? 'collapse' : 'expand'));\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n // _focusCol is a visible-column index (set from data-col), so use visibleColumns\n const column = this.visibleColumns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#syncDetailRows();\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = (this.grid as unknown as { __frameworkAdapter?: { unmount?(c: HTMLElement): void } })\n .__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Return total extra height from all expanded detail rows.\n * Used by grid virtualization to adjust scrollbar height.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeight(): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n totalHeight += this.getDetailHeight(row);\n }\n return totalHeight;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * This is the sum of heights of all expanded details whose parent row is before the given index.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v3.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n // Include detail if it's for a row before the given index\n if (rowIndex >= 0 && rowIndex < beforeRowIndex) {\n totalHeight += this.getDetailHeight(row);\n }\n }\n return totalHeight;\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n */\n expandAll(): void {\n for (const row of this.rows) {\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.grid as unknown as { refreshColumns?: () => void };\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","newExpanded","Set","has","delete","add","createDetailElement","rowIndex","renderer","columnCount","detailRow","document","createElement","className","setAttribute","String","detailCell","style","gridColumn","content","innerHTML","HTMLElement","appendChild","MasterDetailPlugin","BaseGridPlugin","name","styles","defaultConfig","detailHeight","expandOnRowClick","collapseOnClickOutside","animation","attach","grid","super","this","parseLightDomDetail","gridEl","querySelector","detailEl","gridWithAdapter","__frameworkAdapter","parseDetailElement","adapterRenderer","config","detailRenderer","getAttribute","showExpandColumn","heightAttr","configUpdates","parseInt","templateHTML","trim","_rowIndex","evaluated","evalTemplateString","value","sanitizeHTML","Object","keys","length","animationStyle","isAnimationEnabled","animateExpand","classList","measured","measureOnce","remove","measureAndCacheDetailHeight","addEventListener","once","setTimeout","animationDuration","animateCollapse","onComplete","cleanup","isConnected","height","offsetHeight","previousHeight","measuredDetailHeights","get","set","invalidateRowHeight","detailElements","Map","rowsToAnimate","static","getDetailHeight","contains","cachedHeight","DEFAULT_DETAIL_HEIGHT","toggleAndEmit","expanded","emit","requestRender","detach","clear","processColumns","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","viewRenderer","renderCtx","isExpanded","container","toggle","setIcon","resolveIcon","onRowClick","event","onCellClick","target","originalEvent","size","queueMicrotask","syncDetailRows","onKeyDown","key","focusCol","_focusCol","focusRow","_focusRow","column","visibleColumns","isExpanderColumn","rows","preventDefault","requestRenderWithFocus","afterRender","onScrollRender","body","gridElement","gridInternal","rowPool","_rowPool","vStart","_virtualization","start","vEnd","end","visibleStart","visibleEnd","visibleRowMap","poolLen","Math","min","i","rowEl","parentNode","dataRows","querySelectorAll","firstCell","indexOf","isStillExpanded","isRowVisible","adapter","unmount","firstElementChild","existingDetail","previousElementSibling","after","shouldAnimate","requestAnimationFrame","getExtraHeight","totalHeight","getExtraHeightBefore","beforeRowIndex","getRowHeight","_index","defaultRowHeight","adjustVirtualStart","scrollTop","rowHeight","positionCache","minStart","offset","expandedIndices","index","push","sort","a","b","cumulativeExtraHeight","actualRowTop","expand","expandDetailRow","collapse","collapseDetailRow","isDetailExpanded","expandAll","collapseAll","getExpandedRows","indices","idx","getDetailElement","refreshDetailRenderer","currentRenderer","refreshColumns"],"mappings":"sgBAaO,SAASA,EAAgBC,EAA2BC,GACzD,MAAMC,EAAc,IAAIC,IAAIH,GAM5B,OALIE,EAAYE,IAAIH,GAClBC,EAAYG,OAAOJ,GAEnBC,EAAYI,IAAIL,GAEXC,CACT,CAiCO,SAASK,EACdN,EACAO,EACAC,EACAC,GAEA,MAAMC,E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,CACA,OAAOD,CACT,CAOA,gBAAAE,CAAiB9L,GACf,MAAMP,EAAMmC,KAAK6F,KAAKzH,GACtB,OAAOP,EAAMmC,KAAKiD,eAAeH,IAAIjF,QAAO,CAC9C,CASA,qBAAAsM,GAEE,MAAMC,EAAkBpK,KAAKS,OAAOC,eAapC,GAZAV,KAAKS,OAAS,IAAKT,KAAKS,OAAQC,oBAAgB,GAChDV,KAAKC,uBAGAD,KAAKS,OAAOC,gBAAkB0J,IACjCpK,KAAKS,OAAS,IAAKT,KAAKS,OAAQC,eAAgB0J,IAO9CpK,KAAKS,OAAOC,eAAgB,CAC9B,MAAMZ,EAAOE,KAAKF,KACiB,mBAAxBA,EAAKuK,eACdvK,EAAKuK,iBAGLrK,KAAK4D,eAET,CACF"}
1
+ {"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Returns a new Set with the updated state.\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n if (newExpanded.has(row)) {\n newExpanded.delete(row);\n } else {\n newExpanded.add(row);\n }\n return newExpanded;\n}\n\n/**\n * Expand a detail row.\n * Returns a new Set with the row added.\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.add(row);\n return newExpanded;\n}\n\n/**\n * Collapse a detail row.\n * Returns a new Set with the row removed.\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n const newExpanded = new Set(expandedRows);\n newExpanded.delete(row);\n return newExpanded;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig } from '../../core/types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `detailRenderer` | `(row) => HTMLElement \\| string` | required | Render function for detail content |\n * | `expandOnRowClick` | `boolean` | `false` | Expand when clicking the row |\n * | `detailHeight` | `number \\| 'auto'` | `'auto'` | Fixed height or auto-size |\n * | `collapseOnClickOutside` | `boolean` | `false` | Collapse when clicking outside |\n * | `showExpandColumn` | `boolean` | `true` | Show expand/collapse column |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expandRow` | `(rowIndex) => void` | Expand a specific row |\n * | `collapseRow` | `(rowIndex) => void` | Collapse a specific row |\n * | `toggleRow` | `(rowIndex) => void` | Toggle row expansion |\n * | `expandAll` | `() => void` | Expand all rows |\n * | `collapseAll` | `() => void` | Collapse all rows |\n * | `isRowExpanded` | `(rowIndex) => boolean` | Check if row is expanded |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseDetailElement?: (el: Element) => ((row: any, rowIndex: number) => HTMLElement | string) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseDetailElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, this.resolveIcon(isExpanded ? 'collapse' : 'expand'));\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n // _focusCol is a visible-column index (set from data-col), so use visibleColumns\n const column = this.visibleColumns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#syncDetailRows();\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = (this.grid as unknown as { __frameworkAdapter?: { unmount?(c: HTMLElement): void } })\n .__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Return total extra height from all expanded detail rows.\n * Used by grid virtualization to adjust scrollbar height.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeight(): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n totalHeight += this.getDetailHeight(row);\n }\n return totalHeight;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * This is the sum of heights of all expanded details whose parent row is before the given index.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n let totalHeight = 0;\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n // Include detail if it's for a row before the given index\n if (rowIndex >= 0 && rowIndex < beforeRowIndex) {\n totalHeight += this.getDetailHeight(row);\n }\n }\n return totalHeight;\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n */\n expandAll(): void {\n for (const row of this.rows) {\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.grid as unknown as { refreshColumns?: () => void };\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","newExpanded","Set","has","delete","add","createDetailElement","rowIndex","renderer","columnCount","detailRow","document","createElement","className","setAttribute","String","detailCell","style","gridColumn","content","innerHTML","HTMLElement","appendChild","MasterDetailPlugin","BaseGridPlugin","name","styles","defaultConfig","detailHeight","expandOnRowClick","collapseOnClickOutside","animation","attach","grid","super","this","parseLightDomDetail","gridEl","querySelector","detailEl","gridWithAdapter","__frameworkAdapter","parseDetailElement","adapterRenderer","config","detailRenderer","getAttribute","showExpandColumn","heightAttr","configUpdates","parseInt","templateHTML","trim","_rowIndex","evaluated","evalTemplateString","value","sanitizeHTML","Object","keys","length","animationStyle","isAnimationEnabled","animateExpand","classList","measured","measureOnce","remove","measureAndCacheDetailHeight","addEventListener","once","setTimeout","animationDuration","animateCollapse","onComplete","cleanup","isConnected","height","offsetHeight","previousHeight","measuredDetailHeights","get","set","invalidateRowHeight","detailElements","Map","rowsToAnimate","static","getDetailHeight","contains","cachedHeight","DEFAULT_DETAIL_HEIGHT","toggleAndEmit","expanded","emit","requestRender","detach","clear","processColumns","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","viewRenderer","renderCtx","isExpanded","container","toggle","setIcon","resolveIcon","onRowClick","event","onCellClick","target","originalEvent","size","queueMicrotask","syncDetailRows","onKeyDown","key","focusCol","_focusCol","focusRow","_focusRow","column","visibleColumns","isExpanderColumn","rows","preventDefault","requestRenderWithFocus","afterRender","onScrollRender","body","gridElement","gridInternal","rowPool","_rowPool","vStart","_virtualization","start","vEnd","end","visibleStart","visibleEnd","visibleRowMap","poolLen","Math","min","i","rowEl","parentNode","dataRows","querySelectorAll","firstCell","indexOf","isStillExpanded","isRowVisible","adapter","unmount","firstElementChild","existingDetail","previousElementSibling","after","shouldAnimate","requestAnimationFrame","getExtraHeight","totalHeight","getExtraHeightBefore","beforeRowIndex","getRowHeight","_index","defaultRowHeight","adjustVirtualStart","scrollTop","rowHeight","positionCache","minStart","offset","expandedIndices","index","push","sort","a","b","cumulativeExtraHeight","actualRowTop","expand","expandDetailRow","collapse","collapseDetailRow","isDetailExpanded","expandAll","collapseAll","getExpandedRows","indices","idx","getDetailElement","refreshDetailRenderer","currentRenderer","refreshColumns"],"mappings":"sgBAaO,SAASA,EAAgBC,EAA2BC,GACzD,MAAMC,EAAc,IAAIC,IAAIH,GAM5B,OALIE,EAAYE,IAAIH,GAClBC,EAAYG,OAAOJ,GAE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MqM,EAAMjK,KAAK6F,KAAK2B,QAAQ3J,GAC1BoM,GAAO,GAAGD,EAAQd,KAAKe,EAC7B,CACA,OAAOD,CACT,CAOA,gBAAAE,CAAiB9L,GACf,MAAMP,EAAMmC,KAAK6F,KAAKzH,GACtB,OAAOP,EAAMmC,KAAKiD,eAAeH,IAAIjF,QAAO,CAC9C,CASA,qBAAAsM,GAEE,MAAMC,EAAkBpK,KAAKS,OAAOC,eAapC,GAZAV,KAAKS,OAAS,IAAKT,KAAKS,OAAQC,oBAAgB,GAChDV,KAAKC,uBAGAD,KAAKS,OAAOC,gBAAkB0J,IACjCpK,KAAKS,OAAS,IAAKT,KAAKS,OAAQC,eAAgB0J,IAO9CpK,KAAKS,OAAOC,eAAgB,CAC9B,MAAMZ,EAAOE,KAAKF,KACiB,mBAAxBA,EAAKuK,eACdvK,EAAKuK,iBAGLrK,KAAK4D,eAET,CACF"}
@@ -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 // 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","async","printGridIsolated","gridElement","options","orientation","gridId","id","document","querySelectorAll","CSS","escape","length","console","warn","getElementById","remove","isolationStyle","style","createElement","textContent","createIsolationStylesheet","head","appendChild","Promise","resolve","onAfterPrint","window","removeEventListener","addEventListener","print","setTimeout","DEFAULT_CONFIG","button","warnThreshold","maxRows","includeTitle","includeTimestamp","title","isolate","PrintPlugin","BaseGridPlugin","name","version","styles","printing","savedHiddenColumns","savedVirtualization","savedRows","printHeader","printFooter","appliedScale","internalGrid","this","grid","isPrinting","params","config","originalRowCount","rows","rowCount","limitApplied","limitInfo","toLocaleString","confirm","startTime","performance","now","emit","bypassThreshold","_virtualization","hidePrintColumns","sourceRows","slice","addPrintHeader","disableVirtualization","requestAnimationFrame","classList","add","printInIsolatedWindow","triggerPrint","success","duration","Math","round","error","cleanup","className","effectiveConfig","shell","header","titleEl","timestampEl","Date","insertBefore","firstChild","location","hostname","totalRows","refreshVirtualWindow","columns","Map","col","printHidden","field","set","hidden","setColumnVisible","restorePrintColumns","wasVisible","transform","transformOrigin","width","afterRender","toolbarRegistered","registerToolbarButton","registerToolbarContent","order","render","container","type","icon","resolveIcon","setIcon","signal","disconnectSignal"],"mappings":"+UAeA,MAAMA,EAAqB,4BAsG3BC,eAAsBC,EAAkBC,EAA0BC,EAAgC,IAChG,MAAMC,YAAEA,EAAc,aAAgBD,EAEhCE,EAASH,EAAYI,GAGJC,SAASC,iBAAiB,IAAIC,IAAIC,OAAOL,MAC7CM,OAAS,GAC1BC,QAAQC,KACN,qDAAqDR,iFAMzDE,SAASO,eAAef,IAAqBgB,SAG7C,MAAMC,EAlHR,SAAmCX,EAAgBD,GACjD,MAAMa,EAAQV,SAASW,cAAc,SAyErC,OAxEAD,EAAMX,GAAKP,EACXkB,EAAME,YAAc,+JAIAd,0IAKbA,meAeAA,cACAA,kJAKaA,0BACFA,6gBAeAA,oBAAyBA,YAAiBA,+GAM9CD,yeAmBPa,CACT,CAuCyBG,CAA0Bf,EAAQD,GAGzD,OAFAG,SAASc,KAAKC,YAAYN,GAEnB,IAAIO,QAASC,IAElB,MAAMC,EAAe,KACnBC,OAAOC,oBAAoB,aAAcF,GAEzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KAEFE,OAAOE,iBAAiB,aAAcH,GAGtCC,OAAOG,QAGPC,WAAW,KACTJ,OAAOC,oBAAoB,aAAcF,GACzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KACC,MAEP,OCrIMO,EAAwC,CAC5CC,QAAQ,EACR5B,YAAa,YACb6B,cAAe,IACfC,QAAS,EACTC,cAAc,EACdC,kBAAkB,EAClBC,MAAO,GACPC,SAAS,GAiEJ,MAAMC,UAAoBC,EAAAA,eAEtBC,KAAO,QAGEC,QAAU,QAGVC,kwEAGlBC,IAAY,EAGZC,GAAmD,KAGnDC,GAA2D,KAG3DC,GAA+B,KAG/BC,GAAmC,KAGnCC,GAAmC,KAGnCC,GAA+B,KAK/B,KAAIC,GACF,OAAOC,KAAKC,IACd,CAKA,UAAAC,GACE,OAAOF,MAAKR,CAC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AItB,MAAME,EAAeC,MAAKD,EACtBC,MAAKN,GAAwBK,EAAakB,kBAC5ClB,EAAakB,gBAAgBD,gBAAkBhB,MAAKN,EAAqBsB,gBACzEjB,EAAa+C,sBAAqB,GAClC9C,MAAKN,EAAuB,MAIN,OAApBM,MAAKL,IACNK,KAAKC,KAAwCK,KAAON,MAAKL,EAC1DK,MAAKL,EAAa,KAEtB,CAMS,WAAAiE,GAEH5D,KAAKI,QAAQxB,SAAWoB,MAAK6D,IAC/B7D,MAAK8D,IACL9D,MAAK6D,GAAqB,EAE9B,CAGAA,IAAqB,EAKrB,EAAAC,GACE,MAAM7D,EAAOD,MAAKD,EAGlBE,EAAK8D,yBAAyB,CAC5B7G,GAAI,eACJ8G,MAAO,IACPC,OAASC,IACP,MAAMtF,EAASzB,SAASW,cAAc,UACtCc,EAAOsD,UAAY,gCACnBtD,EAAOK,MAAQ,aACfL,EAAOuF,KAAO,SAGd,MAAMC,EAAOpE,KAAKqE,YAAY,UAAY,MAC1CrE,KAAKsE,QAAQ1F,EAAQwF,GAErBxF,EAAOJ,iBACL,QACA,KACEwB,KAAKvB,SAEP,CAAE8F,OAAQvE,KAAKwE,mBAGjBN,EAAUhG,YAAYU,KAG5B"}
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.getPluginByName('print');\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","async","printGridIsolated","gridElement","options","orientation","gridId","id","document","querySelectorAll","CSS","escape","length","console","warn","getElementById","remove","isolationStyle","style","createElement","textContent","createIsolationStylesheet","head","appendChild","Promise","resolve","onAfterPrint","window","removeEventListener","addEventListener","print","setTimeout","DEFAULT_CONFIG","button","warnThreshold","maxRows","includeTitle","includeTimestamp","title","isolate","PrintPlugin","BaseGridPlugin","name","version","styles","printing","savedHiddenColumns","savedVirtualization","savedRows","printHeader","printFooter","appliedScale","internalGrid","this","grid","isPrinting","params","config","originalRowCount","rows","rowCount","limitApplied","limitInfo","toLocaleString","confirm","startTime","performance","now","emit","bypassThreshold","_virtualization","hidePrintColumns","sourceRows","slice","addPrintHeader","disableVirtualization","requestAnimationFrame","classList","add","printInIsolatedWindow","triggerPrint","success","duration","Math","round","error","cleanup","className","effectiveConfig","shell","header","titleEl","timestampEl","Date","insertBefore","firstChild","location","hostname","totalRows","refreshVirtualWindow","columns","Map","col","printHidden","field","set","hidden","setColumnVisible","restorePrintColumns","wasVisible","transform","transformOrigin","width","afterRender","toolbarRegistered","registerToolbarButton","registerToolbarContent","order","render","container","type","icon","resolveIcon","setIcon","signal","disconnectSignal"],"mappings":"+UAeA,MAAMA,EAAqB,4BAsG3BC,eAAsBC,EAAkBC,EAA0BC,EAAgC,IAChG,MAAMC,YAAEA,EAAc,aAAgBD,EAEhCE,EAASH,EAAYI,GAGJC,SAASC,iBAAiB,IAAIC,IAAIC,OAAOL,MAC7CM,OAAS,GAC1BC,QAAQC,KACN,qDAAqDR,iFAMzDE,SAASO,eAAef,IAAqBgB,SAG7C,MAAMC,EAlHR,SAAmCX,EAAgBD,GACjD,MAAMa,EAAQV,SAASW,cAAc,SAyErC,OAxEAD,EAAMX,GAAKP,EACXkB,EAAME,YAAc,+JAIAd,0IAKbA,meAeAA,cACAA,kJAKaA,0BACFA,6gBAeAA,oBAAyBA,YAAiBA,+GAM9CD,yeAmBPa,CACT,CAuCyBG,CAA0Bf,EAAQD,GAGzD,OAFAG,SAASc,KAAKC,YAAYN,GAEnB,IAAIO,QAASC,IAElB,MAAMC,EAAe,KACnBC,OAAOC,oBAAoB,aAAcF,GAEzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KAEFE,OAAOE,iBAAiB,aAAcH,GAGtCC,OAAOG,QAGPC,WAAW,KACTJ,OAAOC,oBAAoB,aAAcF,GACzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KACC,MAEP,OCrIMO,EAAwC,CAC5CC,QAAQ,EACR5B,YAAa,YACb6B,cAAe,IACfC,QAAS,EACTC,cAAc,EACdC,kBAAkB,EAClBC,MAAO,GACPC,SAAS,GAiEJ,MAAMC,UAAoBC,EAAAA,eAEtBC,KAAO,QAGEC,QAAU,QAGVC,kwEAG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B,GAC7BzD,EAAKpC,MAAM8F,MAAQ,GACnB3D,MAAKF,EAAgB,MAInBE,MAAKJ,IACPI,MAAKJ,EAAajC,SAClBqC,MAAKJ,EAAe,MAElBI,MAAKH,IACPG,MAAKH,EAAalC,SAClBqC,MAAKH,EAAe,MAItB,MAAME,EAAeC,MAAKD,EACtBC,MAAKN,GAAwBK,EAAakB,kBAC5ClB,EAAakB,gBAAgBD,gBAAkBhB,MAAKN,EAAqBsB,gBACzEjB,EAAa+C,sBAAqB,GAClC9C,MAAKN,EAAuB,MAIN,OAApBM,MAAKL,IACNK,KAAKC,KAAwCK,KAAON,MAAKL,EAC1DK,MAAKL,EAAa,KAEtB,CAMS,WAAAiE,GAEH5D,KAAKI,QAAQxB,SAAWoB,MAAK6D,IAC/B7D,MAAK8D,IACL9D,MAAK6D,GAAqB,EAE9B,CAGAA,IAAqB,EAKrB,EAAAC,GACE,MAAM7D,EAAOD,MAAKD,EAGlBE,EAAK8D,yBAAyB,CAC5B7G,GAAI,eACJ8G,MAAO,IACPC,OAASC,IACP,MAAMtF,EAASzB,SAASW,cAAc,UACtCc,EAAOsD,UAAY,gCACnBtD,EAAOK,MAAQ,aACfL,EAAOuF,KAAO,SAGd,MAAMC,EAAOpE,KAAKqE,YAAY,UAAY,MAC1CrE,KAAKsE,QAAQ1F,EAAQwF,GAErBxF,EAAOJ,iBACL,QACA,KACEwB,KAAKvB,SAEP,CAAE8F,OAAQvE,KAAKwE,mBAGjBN,EAAUhG,YAAYU,KAG5B"}
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_reorderColumns={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,r){"use strict";function i(e,t,r){if(t===r)return e;if(t<0||t>=e.length)return e;if(r<0||r>e.length)return e;const i=[...e],[n]=i.splice(t,1);return i.splice(r,0,n),i}class n extends r.BaseGridPlugin{name="reorderColumns";aliases=["reorder"];styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){if(!e||!function(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}(e))return!1;return!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(e=>{const t=e,r=t.getAttribute("data-field");if(!r)return;const n=this.columns.find(e=>e.field===r);this.canMoveColumnWithPlugins(n)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const i=this.getColumnOrder().indexOf(r);this.isDragging=!0,this.draggedField=r,this.draggedIndex=i,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",r)),t.classList.add("dragging")}),t.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging||this.draggedField===r)return;const i=t.getBoundingClientRect(),n=i.left+i.width/2,a=this.getColumnOrder().indexOf(r);this.dropIndex=e.clientX<n?a:a+1,t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<n),t.classList.toggle("drop-after",e.clientX>=n)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedField,r=this.draggedIndex,n=this.dropIndex;if(!this.isDragging||null===t||null===r||null===n)return;const a=n>r?n-1:n,o=i(this.getColumnOrder(),r,a),s={field:t,fromIndex:r,toIndex:a,columnOrder:o};this.emitCancelable("column-move",s)||this.updateColumnOrder(o)}))):t.draggable=!1})}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const r=this.grid,i=r._focusCol,n=r._visibleColumns;if(i<0||i>=n.length)return;const a=n[i];if(!this.canMoveColumnWithPlugins(a))return;const o=this.getColumnOrder(),s=o.indexOf(a.field);if(-1===s)return;const d="ArrowLeft"===e.key?s-1:s+1;if(d<0||d>=o.length)return;const l=n.find(e=>e.field===o[d]);return this.canMoveColumnWithPlugins(l)?(this.moveColumn(a.field,d),r._focusCol=d,t.ensureCellVisible(this.grid),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const r=this.getColumnOrder(),n=r.indexOf(e);if(-1===n)return;const a=i(r,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:a})||this.updateColumnOrder(a)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");r&&e.set(r,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const r=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");if(!i)return;const n=e.get(i);if(void 0===n)return;const a=n-t.getBoundingClientRect().left;Math.abs(a)>1&&r.set(i,a)}),0===r.size)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=r.get(e.getAttribute("data-field")??"");if(void 0!==t){const r=e;r.style.transform=`translateX(${t}px)`,i.push(r)}}),0===i.length)return;this.gridElement.offsetHeight;const n=this.animationDuration;requestAnimationFrame(()=>{i.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{i.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},n+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const r=this.captureHeaderPositions();e();const i=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const n=r.get(t);if(void 0===n)return;const a=e.getBoundingClientRect().left;Math.abs(n-a)>1&&i.add(t)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&i.has(t)){const t=e;t.classList.add("fade-animating"),n.push(t)}}),0===n.length)return;const a=this.animationDuration;setTimeout(()=>{n.forEach(e=>e.classList.remove("fade-animating"))},a+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}}e.ReorderPlugin=n,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
+ //# sourceMappingURL=reorder-columns.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reorder-columns.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/reorder-columns/column-drag.ts","../../../../../libs/grid/src/lib/plugins/reorder-columns/ReorderPlugin.ts"],"sourcesContent":["/**\n * Column Reordering Core Logic\n *\n * Pure functions for column drag and reordering operations.\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Check if a column can be moved based on its own metadata.\n * This checks column-level properties like lockPosition and suppressMovable.\n *\n * Note: For full movability checks including plugin constraints (e.g., pinned columns),\n * use `grid.query<boolean>('canMoveColumn', column)` which queries all plugins that\n * declare the 'canMoveColumn' query in their manifest.\n *\n * @param column - The column configuration to check\n * @returns True if the column can be moved based on its metadata\n */\nexport function canMoveColumn<TRow = unknown>(column: ColumnConfig<TRow>): boolean {\n // Check for lockPosition or suppressMovable properties in the column config\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Move a column from one position to another in the order array.\n *\n * @param columns - Array of field names in current order\n * @param fromIndex - The current index of the column to move\n * @param toIndex - The target index to move the column to\n * @returns New array with updated order\n */\nexport function moveColumn(columns: string[], fromIndex: number, toIndex: number): string[] {\n if (fromIndex === toIndex) return columns;\n if (fromIndex < 0 || fromIndex >= columns.length) return columns;\n if (toIndex < 0 || toIndex > columns.length) return columns;\n\n const result = [...columns];\n const [removed] = result.splice(fromIndex, 1);\n result.splice(toIndex, 0, removed);\n return result;\n}\n\n/**\n * Calculate the drop index based on the current drag position.\n *\n * @param dragX - The current X position of the drag\n * @param headerRect - The bounding rect of the header container\n * @param columnWidths - Array of column widths in order\n * @returns The index where the column should be dropped\n */\nexport function getDropIndex(dragX: number, headerRect: DOMRect, columnWidths: number[]): number {\n let x = headerRect.left;\n\n for (let i = 0; i < columnWidths.length; i++) {\n const mid = x + columnWidths[i] / 2;\n if (dragX < mid) return i;\n x += columnWidths[i];\n }\n\n return columnWidths.length;\n}\n\n/**\n * Reorder columns according to a specified order.\n * Columns not in the order array are appended at the end.\n *\n * @param columns - Array of column configurations\n * @param order - Array of field names specifying the desired order\n * @returns New array of columns in the specified order\n */\nexport function reorderColumns<TRow = unknown>(columns: ColumnConfig<TRow>[], order: string[]): ColumnConfig<TRow>[] {\n const columnMap = new Map<string, ColumnConfig<TRow>>(columns.map((c) => [c.field as string, c]));\n const reordered: ColumnConfig<TRow>[] = [];\n\n // Add columns in specified order\n for (const field of order) {\n const col = columnMap.get(field);\n if (col) {\n reordered.push(col);\n columnMap.delete(field);\n }\n }\n\n // Add any remaining columns not in order\n for (const col of columnMap.values()) {\n reordered.push(col);\n }\n\n return reordered;\n}\n","/**\n * Column Reordering Plugin (Class-based)\n *\n * Provides drag-and-drop column reordering functionality for tbw-grid.\n * Supports keyboard and mouse interactions with visual feedback.\n * Uses FLIP animation technique for smooth column transitions.\n *\n * Animation respects grid-level animation.mode setting but style is plugin-configured.\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, InternalGrid } from '../../core/types';\nimport { canMoveColumn, moveColumn } from './column-drag';\nimport styles from './reorder.css?inline';\nimport type { ColumnMoveDetail, ReorderConfig } from './types';\n\n/**\n * Column Reorder Plugin for tbw-grid\n *\n * Lets users rearrange columns by dragging and dropping column headers. Supports smooth\n * FLIP animations, fade transitions, or instant reordering. Animation respects the\n * grid-level `animation.mode` setting.\n *\n * ## Installation\n *\n * ```ts\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `animation` | `false \\| 'flip' \\| 'fade'` | `'flip'` | Animation type for column moves |\n * | `animationDuration` | `number` | `200` | Animation duration in ms |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Alt + ←` | Move focused column left |\n * | `Alt + →` | Move focused column right |\n *\n * ## Events\n *\n * | Event | Detail | Cancelable | Description |\n * |-------|--------|------------|-------------|\n * | `column-move` | `{ field, fromIndex, toIndex, columnOrder }` | Yes | Fired when a column move is attempted |\n *\n * @example Basic Drag-and-Drop Reordering\n * ```ts\n * import '@toolbox-web/grid';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ReorderPlugin({ animation: 'flip', animationDuration: 200 })],\n * };\n *\n * // Persist column order\n * grid.addEventListener('column-move', (e) => {\n * localStorage.setItem('columnOrder', JSON.stringify(e.detail.columnOrder));\n * });\n * ```\n *\n * @example Prevent Moves That Break Group Boundaries\n * ```ts\n * grid.addEventListener('column-move', (e) => {\n * if (!isValidMoveWithinGroup(e.detail.field, e.detail.fromIndex, e.detail.toIndex)) {\n * e.preventDefault(); // Column snaps back to original position\n * }\n * });\n * ```\n *\n * @see {@link ReorderConfig} for all configuration options\n * @see {@link ColumnMoveDetail} for the event detail structure\n * @see {@link GroupingColumnsPlugin} for column group integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ReorderPlugin extends BaseGridPlugin<ReorderConfig> {\n /** @internal */\n readonly name = 'reorderColumns';\n /** @internal */\n override readonly aliases = ['reorder'] as const;\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<ReorderConfig> {\n return {\n animation: 'flip', // Plugin's own default\n };\n }\n\n /**\n * Resolve animation type from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationType(): false | 'flip' | 'fade' {\n // Check if animations are globally disabled\n if (!this.isAnimationEnabled) return false;\n\n // Plugin config (with default from defaultConfig)\n if (this.config.animation !== undefined) return this.config.animation;\n\n return 'flip'; // Plugin default\n }\n\n /**\n * Get animation duration, allowing plugin config override.\n * Uses base class animationDuration for default.\n */\n protected override get animationDuration(): number {\n // Plugin config override\n if (this.config.animationDuration !== undefined) {\n return this.config.animationDuration;\n }\n return super.animationDuration;\n }\n\n // #region Internal State\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n\n /**\n * Check if a column can be moved, considering both column config and plugin queries.\n */\n private canMoveColumnWithPlugins(column: ColumnConfig | undefined): boolean {\n if (!column || !canMoveColumn(column)) return false;\n // Query plugins that respond to 'canMoveColumn' (e.g., PinnedColumnsPlugin)\n const responses = this.grid.query<boolean>('canMoveColumn', column);\n return !responses.includes(false);\n }\n\n /**\n * Clear all drag-related classes from header cells.\n */\n private clearDragClasses(): void {\n this.gridElement?.querySelectorAll('.header-row > .cell').forEach((h) => {\n h.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\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\n // Listen for reorder requests from other plugins (e.g., VisibilityPlugin)\n // Uses disconnectSignal for automatic cleanup - no need for manual removeEventListener\n (grid as unknown as HTMLElement).addEventListener(\n 'column-reorder-request',\n (e: Event) => {\n const detail = (e as CustomEvent).detail;\n if (detail?.field && typeof detail.toIndex === 'number') {\n this.moveColumn(detail.field, detail.toIndex);\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\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 headers = gridEl.querySelectorAll('.header-row > .cell');\n\n headers.forEach((header) => {\n const headerEl = header as HTMLElement;\n const field = headerEl.getAttribute('data-field');\n if (!field) return;\n\n const column = this.columns.find((c) => c.field === field);\n if (!this.canMoveColumnWithPlugins(column)) {\n headerEl.draggable = false;\n return;\n }\n\n headerEl.draggable = true;\n\n // Remove existing listeners to prevent duplicates\n if (headerEl.getAttribute('data-dragstart-bound')) return;\n headerEl.setAttribute('data-dragstart-bound', 'true');\n\n headerEl.addEventListener('dragstart', (e: DragEvent) => {\n const currentOrder = this.getColumnOrder();\n const orderIndex = currentOrder.indexOf(field);\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = orderIndex;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n headerEl.classList.add('dragging');\n });\n\n headerEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses();\n });\n\n headerEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || this.draggedField === field) return;\n\n const rect = headerEl.getBoundingClientRect();\n const midX = rect.left + rect.width / 2;\n\n const currentOrder = this.getColumnOrder();\n const orderIndex = currentOrder.indexOf(field);\n this.dropIndex = e.clientX < midX ? orderIndex : orderIndex + 1;\n\n headerEl.classList.add('drop-target');\n headerEl.classList.toggle('drop-before', e.clientX < midX);\n headerEl.classList.toggle('drop-after', e.clientX >= midX);\n });\n\n headerEl.addEventListener('dragleave', () => {\n headerEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n headerEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (!this.isDragging || draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n const currentOrder = this.getColumnOrder();\n const newOrder = moveColumn(currentOrder, draggedIndex, effectiveToIndex);\n\n const detail: ColumnMoveDetail = {\n field: draggedField,\n fromIndex: draggedIndex,\n toIndex: effectiveToIndex,\n columnOrder: newOrder,\n };\n\n // Emit cancelable event first - only update if not cancelled\n const cancelled = this.emitCancelable('column-move', detail);\n if (!cancelled) {\n // Update the grid's column order (with optional view transition)\n this.updateColumnOrder(newOrder);\n }\n });\n });\n }\n\n /**\n * Handle Alt+Arrow keyboard shortcuts for column reordering.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n if (!event.altKey || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) {\n return;\n }\n\n const grid = this.grid as unknown as { _focusCol: number; _visibleColumns: ColumnConfig[] };\n const focusCol = grid._focusCol;\n const columns = grid._visibleColumns;\n\n if (focusCol < 0 || focusCol >= columns.length) return;\n\n const column = columns[focusCol];\n if (!this.canMoveColumnWithPlugins(column)) return;\n\n const currentOrder = this.getColumnOrder();\n const fromIndex = currentOrder.indexOf(column.field);\n if (fromIndex === -1) return;\n\n const toIndex = event.key === 'ArrowLeft' ? fromIndex - 1 : fromIndex + 1;\n\n // Check bounds\n if (toIndex < 0 || toIndex >= currentOrder.length) return;\n\n // Check if target position is allowed (e.g., not into pinned area)\n const targetColumn = columns.find((c) => c.field === currentOrder[toIndex]);\n if (!this.canMoveColumnWithPlugins(targetColumn)) return;\n\n this.moveColumn(column.field, toIndex);\n\n // Update focus to follow the moved column and refresh visual focus state\n grid._focusCol = toIndex;\n ensureCellVisible(this.grid as unknown as InternalGrid);\n\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current column order from the grid.\n * @returns Array of field names in display order\n */\n getColumnOrder(): string[] {\n return this.grid.getColumnOrder();\n }\n\n /**\n * Move a column to a new position.\n * @param field - The field name of the column to move\n * @param toIndex - The target index\n */\n moveColumn(field: string, toIndex: number): void {\n const currentOrder = this.getColumnOrder();\n const fromIndex = currentOrder.indexOf(field);\n if (fromIndex === -1) return;\n\n const newOrder = moveColumn(currentOrder, fromIndex, toIndex);\n\n // Emit cancelable event first - only update if not cancelled\n const cancelled = this.emitCancelable<ColumnMoveDetail>('column-move', {\n field,\n fromIndex,\n toIndex,\n columnOrder: newOrder,\n });\n if (!cancelled) {\n // Update with view transition\n this.updateColumnOrder(newOrder);\n }\n }\n\n /**\n * Set a specific column order.\n * @param order - Array of field names in desired order\n */\n setColumnOrder(order: string[]): void {\n this.updateColumnOrder(order);\n }\n\n /**\n * Reset column order to the original configuration order.\n */\n resetColumnOrder(): void {\n const originalOrder = this.columns.map((c) => c.field);\n this.updateColumnOrder(originalOrder);\n }\n // #endregion\n\n // #region View Transition\n\n /**\n * Capture header cell positions before reorder.\n */\n private captureHeaderPositions(): Map<string, number> {\n const positions = new Map<string, number>();\n this.gridElement?.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (field) positions.set(field, cell.getBoundingClientRect().left);\n });\n return positions;\n }\n\n /**\n * Apply FLIP animation for column reorder.\n * Uses CSS transitions - JS sets initial transform and toggles class.\n * @param oldPositions - Header positions captured before DOM change\n */\n private animateFLIP(oldPositions: Map<string, number>): void {\n const gridEl = this.gridElement;\n if (!gridEl || oldPositions.size === 0) return;\n\n // Compute deltas from header cells (stable reference points)\n const deltas = new Map<string, number>();\n gridEl.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n const oldLeft = oldPositions.get(field);\n if (oldLeft === undefined) return;\n const deltaX = oldLeft - cell.getBoundingClientRect().left;\n if (Math.abs(deltaX) > 1) deltas.set(field, deltaX);\n });\n\n if (deltas.size === 0) return;\n\n // Set initial transform (First → Last position offset)\n const cells: HTMLElement[] = [];\n gridEl.querySelectorAll('.cell[data-field]').forEach((cell) => {\n const deltaX = deltas.get(cell.getAttribute('data-field') ?? '');\n if (deltaX !== undefined) {\n const el = cell as HTMLElement;\n el.style.transform = `translateX(${deltaX}px)`;\n cells.push(el);\n }\n });\n\n if (cells.length === 0) return;\n\n // Force reflow then animate to final position via CSS transition\n void this.gridElement.offsetHeight;\n\n const duration = this.animationDuration;\n\n requestAnimationFrame(() => {\n cells.forEach((el) => {\n el.classList.add('flip-animating');\n el.style.transform = '';\n });\n\n // Cleanup after animation\n setTimeout(() => {\n cells.forEach((el) => {\n el.style.transform = '';\n el.classList.remove('flip-animating');\n });\n }, duration + 50);\n });\n }\n\n /**\n * Apply crossfade animation for moved columns.\n * Uses CSS keyframes - JS just toggles classes.\n */\n private animateFade(applyChange: () => void): void {\n const gridEl = this.gridElement;\n if (!gridEl) {\n applyChange();\n return;\n }\n\n // Capture old positions to detect which columns moved\n const oldPositions = this.captureHeaderPositions();\n\n // Apply the change first\n applyChange();\n\n // Find which columns changed position\n const movedFields = new Set<string>();\n gridEl.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n const oldLeft = oldPositions.get(field);\n if (oldLeft === undefined) return;\n const newLeft = cell.getBoundingClientRect().left;\n if (Math.abs(oldLeft - newLeft) > 1) {\n movedFields.add(field);\n }\n });\n\n if (movedFields.size === 0) return;\n\n // Add animation class to moved columns (headers + body cells)\n const cells: HTMLElement[] = [];\n gridEl.querySelectorAll('.cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (field && movedFields.has(field)) {\n const el = cell as HTMLElement;\n el.classList.add('fade-animating');\n cells.push(el);\n }\n });\n\n if (cells.length === 0) return;\n\n // Remove class after animation completes\n const duration = this.animationDuration;\n setTimeout(() => {\n cells.forEach((el) => el.classList.remove('fade-animating'));\n }, duration + 50);\n }\n\n /**\n * Update column order with configured animation.\n */\n private updateColumnOrder(newOrder: string[]): void {\n const animation = this.animationType;\n\n if (animation === 'flip' && this.gridElement) {\n const oldPositions = this.captureHeaderPositions();\n this.grid.setColumnOrder(newOrder);\n // Wait for the scheduler to process the virtual window update (RAF)\n // before running FLIP animation on the new cells\n requestAnimationFrame(() => {\n void this.gridElement.offsetHeight;\n this.animateFLIP(oldPositions);\n });\n } else if (animation === 'fade') {\n this.animateFade(() => this.grid.setColumnOrder(newOrder));\n } else {\n this.grid.setColumnOrder(newOrder);\n }\n\n this.grid.requestStateChange?.();\n }\n // #endregion\n}\n"],"names":["moveColumn","columns","fromIndex","toIndex","length","result","removed","splice","ReorderPlugin","BaseGridPlugin","name","aliases","styles","defaultConfig","animation","animationType","this","isAnimationEnabled","config","animationDuration","super","isDragging","draggedField","draggedIndex","dropIndex","canMoveColumnWithPlugins","column","meta","lockPosition","suppressMovable","canMoveColumn","grid","query","includes","clearDragClasses","gridElement","querySelectorAll","forEach","h","classList","remove","attach","addEventListener","e","detail","field","signal","disconnectSignal","detach","afterRender","gridEl","header","headerEl","getAttribute","find","c","draggable","setAttribute","orderIndex","getColumnOrder","indexOf","dataTransfer","effectAllowed","setData","add","preventDefault","rect","getBoundingClientRect","midX","left","width","clientX","toggle","effectiveToIndex","newOrder","columnOrder","emitCancelable","updateColumnOrder","onKeyDown","event","altKey","key","focusCol","_focusCol","_visibleColumns","currentOrder","targetColumn","ensureCellVisible","stopPropagation","setColumnOrder","order","resetColumnOrder","originalOrder","map","captureHeaderPositions","positions","Map","cell","set","animateFLIP","oldPositions","size","deltas","oldLeft","get","deltaX","Math","abs","cells","el","style","transform","push","offsetHeight","duration","requestAnimationFrame","setTimeout","animateFade","applyChange","movedFields","Set","newLeft","has","requestStateChange"],"mappings":"2aAiCO,SAASA,EAAWC,EAAmBC,EAAmBC,GAC/D,GAAID,IAAcC,EAAS,OAAOF,EAClC,GAAIC,EAAY,GAAKA,GAAaD,EAAQG,OAAQ,OAAOH,EACzD,GAAIE,EAAU,GAAKA,EAAUF,EAAQG,OAAQ,OAAOH,EAEpD,MAAMI,EAAS,IAAIJ,IACZK,GAAWD,EAAOE,OAAOL,EAAW,GAE3C,OADAG,EAAOE,OAAOJ,EAAS,EAAGG,GACnBD,CACT,CC4CO,MAAMG,UAAsBC,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IAErB,KAAyB,SAAdtF,EACTE,KAAKqG,YAAY,IAAMrG,KAAKe,KAAK0D,eAAef,IAEhD1D,KAAKe,KAAK0D,eAAef,GAG3B1D,KAAKe,KAAK4F,sBACZ"}
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_reorderRows={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,r){"use strict";const o="__tbw_row_drag";class n extends r.BaseGridPlugin{name="reorderRows";aliases=["rowReorder"];styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const t={field:o,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,this.resolveIcon("dragHandle")),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(e=>{const t=e;if(t.getAttribute("data-drag-bound"))return;t.setAttribute("data-drag-bound","true");const r=t.closest(".data-grid-row");r&&this.setupHandleDragListeners(t,r)});e.querySelectorAll(".data-grid-row").forEach(e=>{const t=e;t.getAttribute("data-drop-bound")||(t.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(t))})}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.grid,r=t._focusRow,o=t._rows??this.sourceRows;if(r<0||r>=o.length)return;const n="ArrowUp"===e.key?"up":"down",i="up"===n?r-1:r+1;if(i<0||i>=o.length)return;const s=o[r];return!this.config.canMove||this.config.canMove(s,r,i,n)?(this.handleKeyboardMove(s,r,i,n,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const r=[...this.sourceRows];if(e<0||e>=r.length)return;if(t<0||t>=r.length)return;if(e===t)return;const o=t<e?"up":"down",n=r[e];this.config.canMove&&!this.config.canMove(n,e,t,o)||this.executeMove(n,e,t,"keyboard")}canMoveRow(e,t){const r=this.sourceRows;if(e<0||e>=r.length)return!1;if(t<0||t>=r.length)return!1;if(e===t)return!1;if(!this.config.canMove)return!0;const o=t<e?"up":"down";return this.config.canMove(r[e],e,t,o)}setupHandleDragListeners(e,t){e.addEventListener("dragstart",e=>{const r=this.getRowIndex(t);r<0||(this.isDragging=!0,this.draggedRowIndex=r,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",String(r))),t.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging||null===this.draggedRowIndex)return;const r=this.getRowIndex(e);if(r<0||r===this.draggedRowIndex)return;const o=e.getBoundingClientRect(),n=o.top+o.height/2,i=t.clientY<n;this.dropRowIndex=i?r:r+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",i),e.classList.toggle("drop-after",!i)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedRowIndex;let r=this.dropRowIndex;if(this.isDragging&&null!==t&&null!==r&&(r>t&&r--,t!==r)){const e=this.sourceRows[t],o=r<t?"up":"down";this.config.canMove&&!this.config.canMove(e,t,r,o)||this.executeMove(e,t,r,"drag")}})}handleKeyboardMove(e,r,o,n,i){this.pendingMove?this.pendingMove.currentIndex=o:this.pendingMove={originalIndex:r,currentIndex:o,row:e},this.lastFocusCol=i;const s=this.grid,a=[...s._rows??this.sourceRows],[d]=a.splice(r,1);a.splice(o,0,d),s._rows=a,s._focusRow=o,s._focusCol=i,s.refreshVirtualWindow(!0),t.ensureCellVisible(s),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:r,row:o}=this.pendingMove;if(this.pendingMove=null,e===r)return;const n={row:o,fromIndex:e,toIndex:r,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",n)){const o=[...this.sourceRows],[n]=o.splice(r,1);o.splice(e,0,n);const i=this.grid;i._rows=o,i._focusRow=e,i._focusCol=this.lastFocusCol,i.refreshVirtualWindow(!0),t.ensureCellVisible(i)}}executeMove(e,t,r,o){const n=[...this.sourceRows],[i]=n.splice(t,1);n.splice(r,0,i);const s={row:e,fromIndex:t,toIndex:r,rows:n,source:o};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=n,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,r)})}else this.grid.rows=n}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const r=this.getRowIndex(t);r>=0&&e.set(r,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,r){const o=this.gridElement;if(!o||0===e.size)return;const n=Math.min(t,r),i=Math.max(t,r),s=[];if(o.querySelectorAll(".data-grid-row").forEach(o=>{const a=o,d=this.getRowIndex(a);if(d<0||d<n||d>i)return;let l;l=d===r?t:t<r?d+1:d-1;const c=e.get(l);if(void 0===c)return;const g=c-a.getBoundingClientRect().top;Math.abs(g)>1&&s.push({el:a,deltaY:g})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),o.offsetHeight;const a=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},a+50)})}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}e.ROW_DRAG_HANDLE_FIELD=o,e.RowReorderPlugin=n,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
+ //# sourceMappingURL=reorder-rows.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reorder-rows.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/reorder-rows/RowReorderPlugin.ts"],"sourcesContent":["/**\n * Row Reordering Plugin\n *\n * Provides keyboard and drag-drop row reordering functionality for tbw-grid.\n * Supports Ctrl+Up/Down keyboard shortcuts and optional drag handle column.\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, InternalGrid } from '../../core/types';\nimport styles from './row-reorder.css?inline';\nimport type { PendingMove, RowMoveDetail, RowReorderConfig } from './types';\n\n/** Field name for the drag handle column */\nexport const ROW_DRAG_HANDLE_FIELD = '__tbw_row_drag';\n\n/**\n * Row Reorder Plugin for tbw-grid\n *\n * Enables row reordering via keyboard shortcuts (Ctrl+Up/Down) and drag-drop.\n * Supports validation callbacks and debounced keyboard moves.\n *\n * ## Installation\n *\n * ```ts\n * import { RowReorderPlugin } from '@toolbox-web/grid/plugins/reorder-rows';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `enableKeyboard` | `boolean` | `true` | Enable Ctrl+Up/Down shortcuts |\n * | `showDragHandle` | `boolean` | `true` | Show drag handle column |\n * | `dragHandlePosition` | `'left' \\| 'right'` | `'left'` | Drag handle column position |\n * | `dragHandleWidth` | `number` | `40` | Drag handle column width |\n * | `canMove` | `function` | - | Validation callback |\n * | `debounceMs` | `number` | `300` | Debounce time for keyboard moves |\n * | `animation` | `false \\| 'flip'` | `'flip'` | Animation for row moves |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Ctrl + ↑` | Move focused row up |\n * | `Ctrl + ↓` | Move focused row down |\n *\n * ## Events\n *\n * | Event | Detail | Cancelable | Description |\n * |-------|--------|------------|-------------|\n * | `row-move` | `RowMoveDetail` | Yes | Fired when a row move is attempted |\n *\n * @example Basic Row Reordering\n * ```ts\n * import '@toolbox-web/grid';\n * import { RowReorderPlugin } from '@toolbox-web/grid/plugins/reorder-rows';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * ],\n * plugins: [new RowReorderPlugin()],\n * };\n *\n * grid.addEventListener('row-move', (e) => {\n * console.log('Row moved from', e.detail.fromIndex, 'to', e.detail.toIndex);\n * });\n * ```\n *\n * @example With Validation\n * ```ts\n * new RowReorderPlugin({\n * canMove: (row, fromIndex, toIndex, direction) => {\n * // Prevent moving locked rows\n * return !row.locked;\n * },\n * })\n * ```\n *\n * @see {@link RowReorderConfig} for all configuration options\n * @see {@link RowMoveDetail} for the event detail structure\n */\nexport class RowReorderPlugin extends BaseGridPlugin<RowReorderConfig> {\n /** @internal */\n readonly name = 'reorderRows';\n /** @internal */\n override readonly aliases = ['rowReorder'] as const;\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<RowReorderConfig> {\n return {\n enableKeyboard: true,\n showDragHandle: true,\n dragHandlePosition: 'left',\n dragHandleWidth: 40,\n debounceMs: 150,\n animation: 'flip',\n };\n }\n\n /**\n * Resolve animation type from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationType(): false | 'flip' {\n // Check if animations are globally disabled\n if (!this.isAnimationEnabled) return false;\n\n // Plugin config (with default from defaultConfig)\n if (this.config.animation !== undefined) return this.config.animation;\n\n return 'flip'; // Plugin default\n }\n\n // #region Internal State\n private isDragging = false;\n private draggedRowIndex: number | null = null;\n private dropRowIndex: number | null = null;\n private pendingMove: PendingMove | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Column index to use when flushing pending move */\n private lastFocusCol = 0;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.clearDebounceTimer();\n this.isDragging = false;\n this.draggedRowIndex = null;\n this.dropRowIndex = null;\n this.pendingMove = null;\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (!this.config.showDragHandle) {\n return [...columns];\n }\n\n const dragHandleColumn: ColumnConfig = {\n field: ROW_DRAG_HANDLE_FIELD,\n header: '',\n width: this.config.dragHandleWidth ?? 40,\n resizable: false,\n sortable: false,\n filterable: false,\n meta: {\n lockPosition: true,\n suppressMovable: true,\n utility: true,\n },\n viewRenderer: () => {\n const container = document.createElement('div');\n container.className = 'dg-row-drag-handle';\n container.setAttribute('aria-label', 'Drag to reorder');\n container.setAttribute('role', 'button');\n container.setAttribute('tabindex', '-1');\n // Set draggable as property (not just attribute) for proper HTML5 drag-drop\n container.draggable = true;\n\n // Use the grid's configured dragHandle icon\n this.setIcon(container, this.resolveIcon('dragHandle'));\n\n return container;\n },\n };\n\n // Position the drag handle column\n if (this.config.dragHandlePosition === 'right') {\n return [...columns, dragHandleColumn];\n }\n return [dragHandleColumn, ...columns];\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.config.showDragHandle) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Set up drag start/end listeners on drag handles\n const handles = gridEl.querySelectorAll('.dg-row-drag-handle');\n handles.forEach((handle) => {\n const handleEl = handle as HTMLElement;\n if (handleEl.getAttribute('data-drag-bound')) return;\n handleEl.setAttribute('data-drag-bound', 'true');\n\n const rowEl = handleEl.closest('.data-grid-row') as HTMLElement;\n if (!rowEl) return;\n\n // Set up dragstart/dragend on the handle\n this.setupHandleDragListeners(handleEl, rowEl);\n });\n\n // Set up drop target listeners on ALL rows (not just the handle's row)\n const rows = gridEl.querySelectorAll('.data-grid-row');\n rows.forEach((row) => {\n const rowEl = row as HTMLElement;\n if (rowEl.getAttribute('data-drop-bound')) return;\n rowEl.setAttribute('data-drop-bound', 'true');\n\n this.setupRowDropListeners(rowEl);\n });\n }\n\n /**\n * Handle Ctrl+Arrow keyboard shortcuts for row reordering.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n if (!this.config.enableKeyboard) return;\n if (!event.ctrlKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) {\n return;\n }\n\n const grid = this.grid as unknown as InternalGrid;\n const focusRow = grid._focusRow;\n // Use _rows (current visual state) for keyboard moves, not sourceRows\n // This ensures rapid moves work correctly since we update _rows directly\n // Fallback to sourceRows for compatibility with tests\n const rows = grid._rows ?? this.sourceRows;\n\n if (focusRow < 0 || focusRow >= rows.length) return;\n\n const direction = event.key === 'ArrowUp' ? 'up' : 'down';\n const toIndex = direction === 'up' ? focusRow - 1 : focusRow + 1;\n\n // Check bounds\n if (toIndex < 0 || toIndex >= rows.length) return;\n\n const row = rows[focusRow];\n\n // Validate move\n if (this.config.canMove && !this.config.canMove(row, focusRow, toIndex, direction)) {\n return;\n }\n\n // Debounce keyboard moves\n this.handleKeyboardMove(row, focusRow, toIndex, direction, grid._focusCol);\n\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n\n /**\n * Flush pending keyboard moves when user clicks a cell.\n * This commits the move immediately so focus works correctly.\n * @internal\n */\n override onCellClick(): void {\n // If there's a pending keyboard move, flush it immediately\n // so the user's click focus isn't overridden\n this.flushPendingMove();\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Move a row to a new position programmatically.\n * @param fromIndex - Current index of the row\n * @param toIndex - Target index\n */\n moveRow(fromIndex: number, toIndex: number): void {\n const rows = [...this.sourceRows];\n if (fromIndex < 0 || fromIndex >= rows.length) return;\n if (toIndex < 0 || toIndex >= rows.length) return;\n if (fromIndex === toIndex) return;\n\n const direction = toIndex < fromIndex ? 'up' : 'down';\n const row = rows[fromIndex];\n\n // Validate move\n if (this.config.canMove && !this.config.canMove(row, fromIndex, toIndex, direction)) {\n return;\n }\n\n this.executeMove(row, fromIndex, toIndex, 'keyboard');\n }\n\n /**\n * Check if a row can be moved to a position.\n * @param fromIndex - Current index of the row\n * @param toIndex - Target index\n */\n canMoveRow(fromIndex: number, toIndex: number): boolean {\n const rows = this.sourceRows;\n if (fromIndex < 0 || fromIndex >= rows.length) return false;\n if (toIndex < 0 || toIndex >= rows.length) return false;\n if (fromIndex === toIndex) return false;\n\n if (!this.config.canMove) return true;\n\n const direction = toIndex < fromIndex ? 'up' : 'down';\n return this.config.canMove(rows[fromIndex], fromIndex, toIndex, direction);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Set up drag start/end listeners on the drag handle element.\n */\n private setupHandleDragListeners(handleEl: HTMLElement, rowEl: HTMLElement): void {\n handleEl.addEventListener('dragstart', (e: DragEvent) => {\n const rowIndex = this.getRowIndex(rowEl);\n if (rowIndex < 0) return;\n\n this.isDragging = true;\n this.draggedRowIndex = rowIndex;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', String(rowIndex));\n }\n\n rowEl.classList.add('dragging');\n });\n\n handleEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedRowIndex = null;\n this.dropRowIndex = null;\n this.clearDragClasses();\n });\n }\n\n /**\n * Set up drop target listeners on a row element.\n * All rows are valid drop targets during drag operations.\n */\n private setupRowDropListeners(rowEl: HTMLElement): void {\n rowEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || this.draggedRowIndex === null) return;\n\n const targetIndex = this.getRowIndex(rowEl);\n if (targetIndex < 0 || targetIndex === this.draggedRowIndex) return;\n\n const rect = rowEl.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const isBefore = e.clientY < midY;\n\n this.dropRowIndex = isBefore ? targetIndex : targetIndex + 1;\n\n rowEl.classList.add('drop-target');\n rowEl.classList.toggle('drop-before', isBefore);\n rowEl.classList.toggle('drop-after', !isBefore);\n });\n\n rowEl.addEventListener('dragleave', () => {\n rowEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n rowEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n const fromIndex = this.draggedRowIndex;\n let toIndex = this.dropRowIndex;\n\n if (!this.isDragging || fromIndex === null || toIndex === null) {\n return;\n }\n\n // Adjust toIndex if dropping after the dragged row\n if (toIndex > fromIndex) {\n toIndex--;\n }\n\n if (fromIndex !== toIndex) {\n const rows = this.sourceRows;\n const row = rows[fromIndex];\n const direction = toIndex < fromIndex ? 'up' : 'down';\n\n // Validate move\n if (!this.config.canMove || this.config.canMove(row, fromIndex, toIndex, direction)) {\n this.executeMove(row, fromIndex, toIndex, 'drag');\n }\n }\n });\n }\n\n /**\n * Handle debounced keyboard moves.\n * Rows move immediately for visual feedback, but the event emission is debounced.\n */\n private handleKeyboardMove(\n row: unknown,\n fromIndex: number,\n toIndex: number,\n direction: 'up' | 'down',\n focusCol: number,\n ): void {\n // Track move for debounced event emission\n if (!this.pendingMove) {\n this.pendingMove = {\n originalIndex: fromIndex,\n currentIndex: toIndex,\n row,\n };\n } else {\n // Update the current index for rapid moves\n this.pendingMove.currentIndex = toIndex;\n }\n\n // Store focus column for flush\n this.lastFocusCol = focusCol;\n\n // Move rows immediately for visual feedback\n // Use _rows (current visual state) for rapid moves, not sourceRows\n // Fallback to sourceRows for compatibility with tests\n const grid = this.grid as unknown as InternalGrid;\n const rows = [...(grid._rows ?? this.sourceRows)];\n const [movedRow] = rows.splice(fromIndex, 1);\n rows.splice(toIndex, 0, movedRow);\n\n // Update grid rows immediately (without triggering change events)\n grid._rows = rows;\n\n // Update focus to follow the row\n grid._focusRow = toIndex;\n grid._focusCol = focusCol;\n\n // Refresh virtual window directly - this re-renders from _rows\n // without overwriting _rows from #rows (which requestRender does)\n grid.refreshVirtualWindow(true);\n\n // Ensure focus styling is applied after the row rebuild\n ensureCellVisible(grid);\n\n // Debounce the event emission only\n this.clearDebounceTimer();\n this.debounceTimer = setTimeout(() => {\n this.flushPendingMove();\n }, this.config.debounceMs ?? 300);\n }\n\n /**\n * Flush the pending move by emitting the event.\n * Called when debounce timer fires or user clicks elsewhere.\n */\n private flushPendingMove(): void {\n this.clearDebounceTimer();\n\n if (!this.pendingMove) return;\n\n const { originalIndex, currentIndex, row: movedRow } = this.pendingMove;\n this.pendingMove = null;\n\n if (originalIndex === currentIndex) return;\n\n // Emit cancelable event\n const detail: RowMoveDetail = {\n row: movedRow,\n fromIndex: originalIndex,\n toIndex: currentIndex,\n rows: [...this.sourceRows],\n source: 'keyboard',\n };\n\n const cancelled = this.emitCancelable('row-move', detail);\n if (cancelled) {\n // Revert to original position\n const rows = [...this.sourceRows];\n const [row] = rows.splice(currentIndex, 1);\n rows.splice(originalIndex, 0, row);\n\n const grid = this.grid as unknown as InternalGrid;\n grid._rows = rows;\n grid._focusRow = originalIndex;\n grid._focusCol = this.lastFocusCol;\n grid.refreshVirtualWindow(true);\n ensureCellVisible(grid);\n }\n }\n\n /**\n * Execute a row move and emit the event.\n */\n private executeMove(row: unknown, fromIndex: number, toIndex: number, source: 'keyboard' | 'drag'): void {\n const rows = [...this.sourceRows];\n const [movedRow] = rows.splice(fromIndex, 1);\n rows.splice(toIndex, 0, movedRow);\n\n const detail: RowMoveDetail = {\n row,\n fromIndex,\n toIndex,\n rows,\n source,\n };\n\n // Emit cancelable event\n const cancelled = this.emitCancelable('row-move', detail);\n if (!cancelled) {\n // Apply with animation if enabled\n if (this.animationType === 'flip' && this.gridElement) {\n const oldPositions = this.captureRowPositions();\n this.grid.rows = rows;\n // Wait for the scheduler to process the virtual window update (RAF)\n // before running FLIP animation on the new rows\n requestAnimationFrame(() => {\n void this.gridElement.offsetHeight;\n this.animateFLIP(oldPositions, fromIndex, toIndex);\n });\n } else {\n // No animation, just update rows\n this.grid.rows = rows;\n }\n }\n }\n\n /**\n * Capture row positions before reorder.\n * Maps visual row index to its top position.\n */\n private captureRowPositions(): Map<number, number> {\n const positions = new Map<number, number>();\n this.gridElement?.querySelectorAll('.data-grid-row').forEach((row) => {\n const rowIndex = this.getRowIndex(row as HTMLElement);\n if (rowIndex >= 0) {\n positions.set(rowIndex, row.getBoundingClientRect().top);\n }\n });\n return positions;\n }\n\n /**\n * Apply FLIP animation for row reorder.\n * Uses CSS transitions - JS sets initial transform and toggles class.\n * @param oldPositions - Row positions captured before DOM change\n * @param fromIndex - Original index of moved row\n * @param toIndex - New index of moved row\n */\n private animateFLIP(oldPositions: Map<number, number>, fromIndex: number, toIndex: number): void {\n const gridEl = this.gridElement;\n if (!gridEl || oldPositions.size === 0) return;\n\n // Calculate which row indices were affected and their new positions\n const minIndex = Math.min(fromIndex, toIndex);\n const maxIndex = Math.max(fromIndex, toIndex);\n\n // Build a map of new row index -> delta Y\n const rowsToAnimate: { el: HTMLElement; deltaY: number }[] = [];\n\n gridEl.querySelectorAll('.data-grid-row').forEach((row) => {\n const rowEl = row as HTMLElement;\n const newRowIndex = this.getRowIndex(rowEl);\n if (newRowIndex < 0 || newRowIndex < minIndex || newRowIndex > maxIndex) return;\n\n // Figure out what this row's old index was\n let oldIndex: number;\n if (newRowIndex === toIndex) {\n // This is the moved row\n oldIndex = fromIndex;\n } else if (fromIndex < toIndex) {\n // Row moved down: rows in between shifted up by 1\n oldIndex = newRowIndex + 1;\n } else {\n // Row moved up: rows in between shifted down by 1\n oldIndex = newRowIndex - 1;\n }\n\n const oldTop = oldPositions.get(oldIndex);\n if (oldTop === undefined) return;\n\n const newTop = rowEl.getBoundingClientRect().top;\n const deltaY = oldTop - newTop;\n\n if (Math.abs(deltaY) > 1) {\n rowsToAnimate.push({ el: rowEl, deltaY });\n }\n });\n\n if (rowsToAnimate.length === 0) return;\n\n // Set initial transform (First → Last position offset)\n rowsToAnimate.forEach(({ el, deltaY }) => {\n el.style.transform = `translateY(${deltaY}px)`;\n });\n\n // Force reflow then animate to final position via CSS transition\n void gridEl.offsetHeight;\n\n const duration = this.animationDuration;\n\n requestAnimationFrame(() => {\n rowsToAnimate.forEach(({ el }) => {\n el.classList.add('flip-animating');\n el.style.transform = '';\n });\n\n // Cleanup after animation\n setTimeout(() => {\n rowsToAnimate.forEach(({ el }) => {\n el.style.transform = '';\n el.classList.remove('flip-animating');\n });\n }, duration + 50);\n });\n }\n\n /**\n * Get the row index from a row element by checking data-row attribute on cells.\n * This is consistent with how other plugins retrieve row indices.\n */\n private getRowIndex(rowEl: HTMLElement): number {\n const cell = rowEl.querySelector('.cell[data-row]');\n return cell ? parseInt(cell.getAttribute('data-row') ?? '-1', 10) : -1;\n }\n\n /**\n * Clear all drag-related classes from rows.\n */\n private clearDragClasses(): void {\n this.gridElement?.querySelectorAll('.data-grid-row').forEach((row) => {\n row.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n\n /**\n * Clear the debounce timer.\n */\n private clearDebounceTimer(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n // #endregion\n}\n"],"names":["ROW_DRAG_HANDLE_FIELD","RowReorderPlugin","BaseGridPlugin","name","aliases","styles","defaultConfig","enableKeyboard","showDragHandle","dragHandlePosition","dragHandleWidth","debounceMs","animation","animationType","this","isAnimationEnabled","config","isDragging","draggedRowIndex","dropRowIndex","pendingMove","debounceTimer","lastFocusCol","detach","clearDebounceTimer","processColumns","columns","dragHandleColumn","field","header","width","resizable","sortable","filterable","meta","lockPosition","suppressMovable","utility","viewRenderer","container","document","createElement","className","setAttribute","draggable","setIcon","resolveIcon","afterRender","gridEl","gridElement","querySelectorAll","forEach","handle","handleEl","getAttribute","rowEl","closest","setupHandleDragListeners","row","setupRowDropListeners","onKeyDown","event","ctrlKey","key","grid","focusRow","_focusRow","rows","_rows","sourceRows","length","direction","toIndex","canMove","handleKeyboardMove","_focusCol","preventDefault","stopPropagation","onCellClick","flushPendingMove","moveRow","fromIndex","executeMove","canMoveRow","addEventListener","e","rowIndex","getRowIndex","dataTransfer","effectAllowed","setData","String","classList","add","clearDragClasses","targetIndex","rect","getBoundingClientRect","midY","top","height","isBefore","clientY","toggle","remove","focusCol","currentIndex","originalIndex","movedRow","splice","refreshVirtualWindow","ensureCellVisible","setTimeout","detail","source","emitCancelable","oldPositions","captureRowPositions","requestAnimationFrame","offsetHeight","animateFLIP","positions","Map","set","size","minIndex","Math","min","maxIndex","max","rowsToAnimate","newRowIndex","oldIndex","oldTop","get","deltaY","abs","push","el","style","transform","duration","animationDuration","cell","querySelector","parseInt","clearTimeout"],"mappings":"8aAcaA,EAAwB,iBAuE9B,MAAMC,UAAyBC,EAAAA,eAE3BC,KAAO,cAEEC,QAAU,CAAC,cAEXC,g4CAGlB,iBAAuBC,GACrB,MAAO,CACLC,gBAAgB,EAChBC,gBAAgB,EAChBC,mBAAoB,OACpBC,gBAAiB,GACjBC,WAAY,IACZC,UAAW,OAEf,CAMA,iBAAYC,GAEV,QAAKC,KAAKC,0BAGoB,IAA1BD,KAAKE,OAAOJ,UAAgCE,KAAKE,OAAOJ,UAErD,OACT,CAGQK,YAAa,EACbC,gBAAiC,KACjCC,aAA8B,KAC9BC,YAAkC,KAClCC,cAAsD,KAEtDC,aAAe,EAMd,MAAAC,GACPT,KAAKU,qBACLV,KAAKG,YAAa,EAClBH,KAAKI,gBAAkB,KACvBJ,KAAKK,aAAe,KACpBL,KAAKM,YAAc,IACrB,CAMS,cAAAK,CAAeC,GACtB,IAAKZ,KAAKE,OAAOR,eACf,MAAO,IAAIkB,GAGb,MAAMC,EAAiC,CACrCC,MAAO5B,EACP6B,OAAQ,GACRC,MAAOhB,KAAKE,OAAON,iBAAmB,GACtCqB,WAAW,EACXC,UAAU,EACVC,YAAY,EACZC,KAAM,CACJC,cAAc,EACdC,iBAAiB,EACjBC,SAAS,GAEXC,aAAc,KACZ,MAAMC,E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