@toolbox-web/grid 1.21.0 → 1.21.2

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 (109) hide show
  1. package/all.js +2 -6850
  2. package/all.js.map +1 -1
  3. package/index.js +1 -4352
  4. package/index.js.map +1 -1
  5. package/lib/core/grid.d.ts +22 -6
  6. package/lib/core/grid.d.ts.map +1 -1
  7. package/lib/core/styles/index.d.ts.map +1 -1
  8. package/lib/plugins/clipboard/index.js +1 -733
  9. package/lib/plugins/clipboard/index.js.map +1 -1
  10. package/lib/plugins/column-virtualization/index.js +1 -560
  11. package/lib/plugins/column-virtualization/index.js.map +1 -1
  12. package/lib/plugins/context-menu/index.js +1 -754
  13. package/lib/plugins/context-menu/index.js.map +1 -1
  14. package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
  15. package/lib/plugins/editing/index.d.ts +1 -1
  16. package/lib/plugins/editing/index.d.ts.map +1 -1
  17. package/lib/plugins/editing/index.js +1 -1539
  18. package/lib/plugins/editing/index.js.map +1 -1
  19. package/lib/plugins/editing/types.d.ts +23 -0
  20. package/lib/plugins/editing/types.d.ts.map +1 -1
  21. package/lib/plugins/export/index.js +1 -589
  22. package/lib/plugins/export/index.js.map +1 -1
  23. package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
  24. package/lib/plugins/filtering/filter-model.d.ts.map +1 -1
  25. package/lib/plugins/filtering/index.js +1 -1283
  26. package/lib/plugins/filtering/index.js.map +1 -1
  27. package/lib/plugins/filtering/types.d.ts +4 -2
  28. package/lib/plugins/filtering/types.d.ts.map +1 -1
  29. package/lib/plugins/grouping-columns/index.js +1 -726
  30. package/lib/plugins/grouping-columns/index.js.map +1 -1
  31. package/lib/plugins/grouping-rows/index.js +2 -905
  32. package/lib/plugins/grouping-rows/index.js.map +1 -1
  33. package/lib/plugins/master-detail/index.js +1 -950
  34. package/lib/plugins/master-detail/index.js.map +1 -1
  35. package/lib/plugins/multi-sort/index.js +1 -553
  36. package/lib/plugins/multi-sort/index.js.map +1 -1
  37. package/lib/plugins/pinned-columns/index.js +1 -688
  38. package/lib/plugins/pinned-columns/index.js.map +1 -1
  39. package/lib/plugins/pinned-rows/index.js +1 -704
  40. package/lib/plugins/pinned-rows/index.js.map +1 -1
  41. package/lib/plugins/pivot/index.js +1 -1191
  42. package/lib/plugins/pivot/index.js.map +1 -1
  43. package/lib/plugins/print/index.js +1 -691
  44. package/lib/plugins/print/index.js.map +1 -1
  45. package/lib/plugins/reorder/index.js +1 -703
  46. package/lib/plugins/reorder/index.js.map +1 -1
  47. package/lib/plugins/responsive/index.js +1 -971
  48. package/lib/plugins/responsive/index.js.map +1 -1
  49. package/lib/plugins/row-reorder/index.js +1 -728
  50. package/lib/plugins/row-reorder/index.js.map +1 -1
  51. package/lib/plugins/selection/index.js +1 -1071
  52. package/lib/plugins/selection/index.js.map +1 -1
  53. package/lib/plugins/server-side/index.js +1 -521
  54. package/lib/plugins/server-side/index.js.map +1 -1
  55. package/lib/plugins/tree/index.js +1 -686
  56. package/lib/plugins/tree/index.js.map +1 -1
  57. package/lib/plugins/undo-redo/index.js +1 -584
  58. package/lib/plugins/undo-redo/index.js.map +1 -1
  59. package/lib/plugins/visibility/index.js +1 -792
  60. package/lib/plugins/visibility/index.js.map +1 -1
  61. package/package.json +4 -5
  62. package/umd/grid.all.umd.js +1 -186
  63. package/umd/grid.all.umd.js.map +1 -1
  64. package/umd/grid.umd.js +1 -90
  65. package/umd/grid.umd.js.map +1 -1
  66. package/umd/plugins/clipboard.umd.js +1 -6
  67. package/umd/plugins/clipboard.umd.js.map +1 -1
  68. package/umd/plugins/column-virtualization.umd.js +1 -1
  69. package/umd/plugins/column-virtualization.umd.js.map +1 -1
  70. package/umd/plugins/context-menu.umd.js +1 -1
  71. package/umd/plugins/context-menu.umd.js.map +1 -1
  72. package/umd/plugins/editing.umd.js +1 -1
  73. package/umd/plugins/editing.umd.js.map +1 -1
  74. package/umd/plugins/export.umd.js +1 -13
  75. package/umd/plugins/export.umd.js.map +1 -1
  76. package/umd/plugins/filtering.umd.js +1 -1
  77. package/umd/plugins/filtering.umd.js.map +1 -1
  78. package/umd/plugins/grouping-columns.umd.js +1 -1
  79. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  80. package/umd/plugins/grouping-rows.umd.js +1 -4
  81. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  82. package/umd/plugins/master-detail.umd.js +1 -1
  83. package/umd/plugins/master-detail.umd.js.map +1 -1
  84. package/umd/plugins/multi-sort.umd.js +1 -1
  85. package/umd/plugins/multi-sort.umd.js.map +1 -1
  86. package/umd/plugins/pinned-columns.umd.js +1 -1
  87. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  88. package/umd/plugins/pinned-rows.umd.js +1 -1
  89. package/umd/plugins/pinned-rows.umd.js.map +1 -1
  90. package/umd/plugins/pivot.umd.js +1 -1
  91. package/umd/plugins/pivot.umd.js.map +1 -1
  92. package/umd/plugins/print.umd.js +1 -75
  93. package/umd/plugins/print.umd.js.map +1 -1
  94. package/umd/plugins/reorder.umd.js +1 -1
  95. package/umd/plugins/reorder.umd.js.map +1 -1
  96. package/umd/plugins/responsive.umd.js +1 -1
  97. package/umd/plugins/responsive.umd.js.map +1 -1
  98. package/umd/plugins/row-reorder.umd.js +1 -1
  99. package/umd/plugins/row-reorder.umd.js.map +1 -1
  100. package/umd/plugins/selection.umd.js +1 -3
  101. package/umd/plugins/selection.umd.js.map +1 -1
  102. package/umd/plugins/server-side.umd.js +1 -1
  103. package/umd/plugins/server-side.umd.js.map +1 -1
  104. package/umd/plugins/tree.umd.js +1 -1
  105. package/umd/plugins/tree.umd.js.map +1 -1
  106. package/umd/plugins/undo-redo.umd.js +1 -1
  107. package/umd/plugins/undo-redo.umd.js.map +1 -1
  108. package/umd/plugins/visibility.umd.js +1 -1
  109. package/umd/plugins/visibility.umd.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tree.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/tree/tree-data.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-detect.ts","../../../../../libs/grid/src/lib/plugins/tree/TreePlugin.ts"],"sourcesContent":["/**\n * Core Tree Data Logic\n *\n * Pure functions for tree flattening, expansion, and traversal.\n */\n\nimport type { FlattenedTreeRow, TreeConfig, TreeRow } from './types';\n\n/**\n * Generates a unique key for a row.\n * Uses row.id if available, otherwise generates from path.\n */\nexport function generateRowKey(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) return String(row.id);\n return parentKey ? `${parentKey}-${index}` : String(index);\n}\n\n/**\n * Flattens a hierarchical tree into a flat array of rows with metadata.\n * Only includes children of expanded nodes.\n */\nexport function flattenTree(\n rows: readonly TreeRow[],\n config: TreeConfig,\n expandedKeys: Set<string>,\n parentKey: string | null = null,\n depth = 0,\n): FlattenedTreeRow[] {\n const childrenField = config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expandedKeys.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n });\n\n // Recursively add children if expanded\n if (hasChildren && isExpanded) {\n const childRows = flattenTree(children as TreeRow[], config, expandedKeys, key, depth + 1);\n result.push(...childRows);\n }\n }\n\n return result;\n}\n\n/**\n * Toggles the expansion state of a row.\n * Returns a new Set with the toggled state.\n */\nexport function toggleExpand(expandedKeys: Set<string>, key: string): Set<string> {\n const newExpanded = new Set(expandedKeys);\n if (newExpanded.has(key)) {\n newExpanded.delete(key);\n } else {\n newExpanded.add(key);\n }\n return newExpanded;\n}\n\n/**\n * Expands all nodes in the tree.\n * Returns a Set of all parent row keys.\n */\nexport function expandAll(\n rows: readonly TreeRow[],\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): Set<string> {\n const childrenField = config.childrenField ?? 'children';\n const keys = new Set<string>();\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n\n if (Array.isArray(children) && children.length > 0) {\n keys.add(key);\n const childKeys = expandAll(children as TreeRow[], config, key, depth + 1);\n for (const k of childKeys) keys.add(k);\n }\n }\n\n return keys;\n}\n\n/**\n * Collapses all nodes.\n * Returns an empty Set.\n */\nexport function collapseAll(): Set<string> {\n return new Set();\n}\n\n/**\n * Gets all descendants of a node from the flattened row list.\n * Useful for operations that need to affect an entire subtree.\n */\nexport function getDescendants(flattenedRows: FlattenedTreeRow[], parentKey: string): FlattenedTreeRow[] {\n const descendants: FlattenedTreeRow[] = [];\n let collecting = false;\n let parentDepth = -1;\n\n for (const row of flattenedRows) {\n if (row.key === parentKey) {\n collecting = true;\n parentDepth = row.depth;\n continue;\n }\n\n if (collecting) {\n if (row.depth > parentDepth) {\n descendants.push(row);\n } else {\n break; // No longer a descendant\n }\n }\n }\n\n return descendants;\n}\n\n/**\n * Finds the path from root to a specific row key.\n * Returns an array of keys from root to the target (inclusive).\n */\nexport function getPathToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): string[] | null {\n const childrenField = config.childrenField ?? 'children';\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n\n if (key === targetKey) {\n return [key];\n }\n\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childPath = getPathToKey(children as TreeRow[], targetKey, config, key, depth + 1);\n if (childPath) {\n return [key, ...childPath];\n }\n }\n }\n\n return null;\n}\n\n/**\n * Expands all ancestors of a specific row to make it visible.\n * Returns a new Set with the required keys added.\n */\nexport function expandToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n existingExpanded: Set<string>,\n): Set<string> {\n const path = getPathToKey(rows, targetKey, config);\n if (!path) return existingExpanded;\n\n const newExpanded = new Set(existingExpanded);\n // Add all keys except the last one (the target itself)\n for (let i = 0; i < path.length - 1; i++) {\n newExpanded.add(path[i]);\n }\n return newExpanded;\n}\n","/**\n * Tree Structure Auto-Detection\n *\n * Utilities for detecting hierarchical tree data structures.\n */\n\nimport type { TreeRow } from './types';\n\n/**\n * Detects if the data has a tree structure by checking for children arrays.\n */\nexport function detectTreeStructure(rows: readonly TreeRow[], childrenField = 'children'): boolean {\n if (!Array.isArray(rows) || rows.length === 0) return false;\n\n // Check if any row has a non-empty children array\n for (const row of rows) {\n if (!row) continue;\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Attempts to infer the children field name from common patterns.\n * Returns the first field that contains an array with items.\n */\nexport function inferChildrenField(rows: readonly TreeRow[]): string | null {\n if (!Array.isArray(rows) || rows.length === 0) return null;\n\n const commonArrayFields = ['children', 'items', 'nodes', 'subRows', 'nested'];\n\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue;\n\n for (const field of commonArrayFields) {\n const value = row[field];\n if (Array.isArray(value) && value.length > 0) {\n return field;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Calculates the maximum depth of the tree.\n * Useful for layout calculations and virtualization.\n */\nexport function getMaxDepth(rows: readonly TreeRow[], childrenField = 'children', currentDepth = 0): number {\n if (!Array.isArray(rows) || rows.length === 0) return currentDepth;\n\n let maxDepth = currentDepth;\n\n for (const row of rows) {\n if (!row) continue;\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childDepth = getMaxDepth(children as TreeRow[], childrenField, currentDepth + 1);\n if (childDepth > maxDepth) {\n maxDepth = childDepth;\n }\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Counts total nodes in the tree (including all descendants).\n */\nexport function countNodes(rows: readonly TreeRow[], childrenField = 'children'): number {\n if (!Array.isArray(rows)) return 0;\n\n let count = 0;\n for (const row of rows) {\n if (!row) continue;\n count++;\n const children = row[childrenField];\n if (Array.isArray(children)) {\n count += countNodes(children as TreeRow[], childrenField);\n }\n }\n\n return count;\n}\n","/**\n * Tree Data Plugin\n *\n * Enables hierarchical tree data with expand/collapse, sorting, and auto-detection.\n */\n\nimport {\n BaseGridPlugin,\n CellClickEvent,\n HeaderClickEvent,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ColumnViewRenderer } from '../../core/types';\nimport { collapseAll, expandAll, expandToKey, toggleExpand } from './tree-data';\nimport { detectTreeStructure, inferChildrenField } from './tree-detect';\nimport styles from './tree.css?inline';\nimport type { ExpandCollapseAnimation, FlattenedTreeRow, TreeConfig, TreeExpandDetail, TreeRow } from './types';\n\ninterface GridWithSortState {\n _sortState?: { field: string; direction: 1 | -1 } | null;\n}\n\n/**\n * Tree Data Plugin for tbw-grid\n *\n * Transforms your flat grid into a hierarchical tree view with expandable parent-child\n * relationships. Ideal for file explorers, organizational charts, nested categories,\n * or any data with a natural hierarchy.\n *\n * ## Installation\n *\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `childrenField` | `string` | `'children'` | Field containing child array |\n * | `autoDetect` | `boolean` | `true` | Auto-detect tree structure from data |\n * | `defaultExpanded` | `boolean` | `false` | Expand all nodes initially |\n * | `indentWidth` | `number` | `20` | Indentation per level (pixels) |\n * | `showExpandIcons` | `boolean` | `true` | Show expand/collapse toggle icons |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style for expand/collapse |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expand` | `(nodeId) => void` | Expand a specific node |\n * | `collapse` | `(nodeId) => void` | Collapse a specific node |\n * | `toggle` | `(nodeId) => void` | Toggle a node's expanded state |\n * | `expandAll` | `() => void` | Expand all nodes |\n * | `collapseAll` | `() => void` | Collapse all nodes |\n * | `getExpandedNodes` | `() => Set<string>` | Get currently expanded node keys |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-tree-toggle-size` | `1.25em` | Toggle icon width |\n * | `--tbw-tree-indent-width` | `var(--tbw-tree-toggle-size)` | Indentation per level |\n * | `--tbw-tree-accent` | `var(--tbw-color-accent)` | Toggle icon hover color |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation duration |\n * | `--tbw-animation-easing` | `ease-out` | Animation curve |\n *\n * @example Basic Tree with Nested Children\n * ```ts\n * import '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'type', header: 'Type' },\n * { field: 'size', header: 'Size' },\n * ],\n * plugins: [new TreePlugin({ childrenField: 'children', indentWidth: 24 })],\n * };\n * grid.rows = [\n * {\n * id: 1,\n * name: 'Documents',\n * type: 'folder',\n * children: [\n * { id: 2, name: 'Report.docx', type: 'file', size: '24 KB' },\n * ],\n * },\n * ];\n * ```\n *\n * @example Expanded by Default with Custom Animation\n * ```ts\n * new TreePlugin({\n * defaultExpanded: true,\n * animation: 'fade', // 'slide' | 'fade' | false\n * indentWidth: 32,\n * })\n * ```\n *\n * @see {@link TreeConfig} for all configuration options\n * @see {@link FlattenedTreeRow} for the flattened row structure\n *\n * @internal Extends BaseGridPlugin\n */\nexport class TreePlugin extends BaseGridPlugin<TreeConfig> {\n static override readonly manifest: PluginManifest = {\n events: [\n {\n type: 'tree-state-change',\n description: 'Emitted when tree expansion state changes (toggle, expand all, collapse all)',\n },\n ],\n queries: [\n {\n type: 'canMoveRow',\n description: 'Returns false for rows with children (parent nodes cannot be reordered)',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'tree';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<TreeConfig> {\n return {\n childrenField: 'children',\n autoDetect: true,\n defaultExpanded: false,\n indentWidth: 20,\n showExpandIcons: true,\n animation: 'slide',\n };\n }\n\n // #region State\n\n private expandedKeys = new Set<string>();\n private initialExpansionDone = false;\n private flattenedRows: FlattenedTreeRow[] = [];\n private rowKeyMap = new Map<string, FlattenedTreeRow>();\n private previousVisibleKeys = new Set<string>();\n private keysToAnimate = new Set<string>();\n private sortState: { field: string; direction: 1 | -1 } | null = null;\n\n /** @internal */\n override detach(): void {\n this.expandedKeys.clear();\n this.initialExpansionDone = false;\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.keysToAnimate.clear();\n this.sortState = null;\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'canMoveRow') {\n // Tree rows with children cannot be reordered\n const row = query.context as { [key: string]: unknown } | null | undefined;\n const childrenField = this.config.childrenField ?? 'children';\n const children = row?.[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return false;\n }\n }\n return undefined;\n }\n\n // #endregion\n\n // #region Animation\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 // #endregion\n\n // #region Auto-Detection\n\n detect(rows: readonly unknown[]): boolean {\n if (!this.config.autoDetect) return false;\n const treeRows = rows as readonly TreeRow[];\n const field = this.config.childrenField ?? inferChildrenField(treeRows) ?? 'children';\n return detectTreeStructure(treeRows, field);\n }\n\n // #endregion\n\n // #region Data Processing\n\n /** @internal */\n override processRows(rows: readonly unknown[]): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const treeRows = rows as readonly TreeRow[];\n\n if (!detectTreeStructure(treeRows, childrenField)) {\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n return [...rows] as TreeRow[];\n }\n\n // Assign stable keys, then optionally sort\n let data = this.withStableKeys(treeRows);\n if (this.sortState) {\n data = this.sortTree(data, this.sortState.field, this.sortState.direction);\n }\n\n // Initialize expansion if needed\n if (this.config.defaultExpanded && !this.initialExpansionDone) {\n this.expandedKeys = expandAll(data, this.config);\n this.initialExpansionDone = true;\n }\n\n // Flatten and track animations\n this.flattenedRows = this.flattenTree(data, this.expandedKeys);\n this.rowKeyMap.clear();\n this.keysToAnimate.clear();\n const currentKeys = new Set<string>();\n\n for (const row of this.flattenedRows) {\n this.rowKeyMap.set(row.key, row);\n currentKeys.add(row.key);\n if (!this.previousVisibleKeys.has(row.key) && row.depth > 0) {\n this.keysToAnimate.add(row.key);\n }\n }\n this.previousVisibleKeys = currentKeys;\n\n return this.flattenedRows.map((r) => ({\n ...r.data,\n __treeKey: r.key,\n __treeDepth: r.depth,\n __treeHasChildren: r.hasChildren,\n __treeExpanded: r.isExpanded,\n }));\n }\n\n /** Assign stable keys to rows (preserves key across sort operations) */\n private withStableKeys(rows: readonly TreeRow[], parentKey: string | null = null): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n return rows.map((row, i) => {\n const stableKey = row.__stableKey as string | undefined;\n const key = row.id !== undefined ? String(row.id) : (stableKey ?? (parentKey ? `${parentKey}-${i}` : String(i)));\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n return {\n ...row,\n __stableKey: key,\n ...(hasChildren ? { [childrenField]: this.withStableKeys(children as TreeRow[], key) } : {}),\n };\n });\n }\n\n /** Flatten tree using stable keys */\n private flattenTree(rows: readonly TreeRow[], expanded: Set<string>, depth = 0): FlattenedTreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n\n for (const row of rows) {\n const stableKey = row.__stableKey as string | undefined;\n const key = stableKey ?? String(row.id ?? '?');\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expanded.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey: depth > 0 ? key.substring(0, key.lastIndexOf('-')) || null : null,\n });\n\n if (hasChildren && isExpanded) {\n result.push(...this.flattenTree(children as TreeRow[], expanded, depth + 1));\n }\n }\n return result;\n }\n\n /** Sort tree recursively, keeping children with parents */\n private sortTree(rows: readonly TreeRow[], field: string, dir: 1 | -1): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const sorted = [...rows].sort((a, b) => {\n const aVal = a[field],\n bVal = b[field];\n if (aVal == null && bVal == null) return 0;\n if (aVal == null) return -1;\n if (bVal == null) return 1;\n return aVal > bVal ? dir : aVal < bVal ? -dir : 0;\n });\n return sorted.map((row) => {\n const children = row[childrenField];\n return Array.isArray(children) && children.length > 0\n ? { ...row, [childrenField]: this.sortTree(children as TreeRow[], field, dir) }\n : row;\n });\n }\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (this.flattenedRows.length === 0) return [...columns];\n\n const cols = [...columns] as ColumnConfig[];\n if (cols.length === 0) return cols;\n\n // Wrap the first column's renderer to add tree indentation and expand icons\n // This is the correct approach for trees because:\n // 1. Indentation can grow naturally with depth\n // 2. Expand icons appear inline with content\n // 3. Works with column reordering (icons stay with first visible column)\n const firstCol = cols[0];\n const originalRenderer = firstCol.viewRenderer;\n const getConfig = () => this.config;\n const setIcon = this.setIcon.bind(this);\n const resolveIcon = this.resolveIcon.bind(this);\n\n const wrappedRenderer: ColumnViewRenderer = (ctx) => {\n const { row, value } = ctx;\n const { showExpandIcons = true, indentWidth } = getConfig();\n const treeRow = row as TreeRow;\n const depth = treeRow.__treeDepth ?? 0;\n\n const container = document.createElement('span');\n container.className = 'tree-cell-wrapper';\n container.style.setProperty('--tbw-tree-depth', String(depth));\n // Allow config-based indentWidth to override CSS default\n if (indentWidth !== undefined) {\n container.style.setProperty('--tbw-tree-indent-width', `${indentWidth}px`);\n }\n\n // Add expand/collapse icon or spacer\n if (showExpandIcons) {\n if (treeRow.__treeHasChildren) {\n const icon = document.createElement('span');\n icon.className = `tree-toggle${treeRow.__treeExpanded ? ' expanded' : ''}`;\n setIcon(icon, resolveIcon(treeRow.__treeExpanded ? 'collapse' : 'expand'));\n icon.setAttribute('data-tree-key', String(treeRow.__treeKey ?? ''));\n container.appendChild(icon);\n } else {\n const spacer = document.createElement('span');\n spacer.className = 'tree-spacer';\n container.appendChild(spacer);\n }\n }\n\n // Add the original content\n const content = document.createElement('span');\n content.className = 'tree-content';\n if (originalRenderer) {\n const result = originalRenderer(ctx);\n if (result instanceof Node) {\n content.appendChild(result);\n } else if (typeof result === 'string') {\n content.innerHTML = result;\n }\n } else {\n content.textContent = value != null ? String(value) : '';\n }\n container.appendChild(content);\n\n return container;\n };\n\n cols[0] = { ...firstCol, viewRenderer: wrappedRenderer };\n return cols;\n }\n\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n const target = event.originalEvent?.target as HTMLElement;\n if (!target?.classList.contains('tree-toggle')) return false;\n\n const key = target.getAttribute('data-tree-key');\n if (!key) return false;\n\n const flatRow = this.rowKeyMap.get(key);\n if (!flatRow) return false;\n\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n this.emit<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when on a row with children\n if (event.key !== ' ') return;\n\n const focusRow = this.grid._focusRow;\n const flatRow = this.flattenedRows[focusRow];\n if (!flatRow?.hasChildren) return;\n\n event.preventDefault();\n this.expandedKeys = toggleExpand(this.expandedKeys, flatRow.key);\n this.emit<TreeExpandDetail>('tree-expand', {\n key: flatRow.key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(flatRow.key),\n depth: flatRow.depth,\n });\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n if (this.flattenedRows.length === 0 || !event.column.sortable) return false;\n\n const { field } = event.column;\n if (!this.sortState || this.sortState.field !== field) {\n this.sortState = { field, direction: 1 };\n } else if (this.sortState.direction === 1) {\n this.sortState = { field, direction: -1 };\n } else {\n this.sortState = null;\n }\n\n // Sync grid sort indicator\n const gridEl = this.grid as unknown as GridWithSortState;\n if (gridEl._sortState !== undefined) {\n gridEl._sortState = this.sortState ? { ...this.sortState } : null;\n }\n\n this.emit('sort-change', { field, direction: this.sortState?.direction ?? 0 });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n const style = this.animationStyle;\n if (style === false || this.keysToAnimate.size === 0) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n const animClass = style === 'fade' ? 'tbw-tree-fade-in' : 'tbw-tree-slide-in';\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n const cell = rowEl.querySelector('.cell[data-row]');\n const idx = cell ? parseInt(cell.getAttribute('data-row') ?? '-1', 10) : -1;\n const key = this.flattenedRows[idx]?.key;\n\n if (key && this.keysToAnimate.has(key)) {\n rowEl.classList.add(animClass);\n rowEl.addEventListener('animationend', () => rowEl.classList.remove(animClass), { once: true });\n }\n }\n this.keysToAnimate.clear();\n }\n\n // #endregion\n\n // #region Public API\n\n expand(key: string): void {\n this.expandedKeys.add(key);\n this.requestRender();\n }\n\n collapse(key: string): void {\n this.expandedKeys.delete(key);\n this.requestRender();\n }\n\n toggle(key: string): void {\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n expandAll(): void {\n this.expandedKeys = expandAll(this.rows as TreeRow[], this.config);\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n collapseAll(): void {\n this.expandedKeys = collapseAll();\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n isExpanded(key: string): boolean {\n return this.expandedKeys.has(key);\n }\n\n getExpandedKeys(): string[] {\n return [...this.expandedKeys];\n }\n\n getFlattenedRows(): FlattenedTreeRow[] {\n return [...this.flattenedRows];\n }\n\n getRowByKey(key: string): TreeRow | undefined {\n return this.rowKeyMap.get(key)?.data;\n }\n\n expandToKey(key: string): void {\n this.expandedKeys = expandToKey(this.rows as TreeRow[], key, this.config, this.expandedKeys);\n this.requestRender();\n }\n\n // #endregion\n}\n"],"names":["generateRowKey","row","index","parentKey","toggleExpand","expandedKeys","key","newExpanded","expandAll","rows","config","depth","childrenField","keys","children","childKeys","k","collapseAll","getPathToKey","targetKey","childPath","expandToKey","existingExpanded","path","detectTreeStructure","inferChildrenField","commonArrayFields","field","value","TreePlugin","BaseGridPlugin","styles","query","treeRows","data","currentKeys","r","i","stableKey","hasChildren","expanded","result","isExpanded","dir","a","b","aVal","bVal","columns","cols","firstCol","originalRenderer","getConfig","setIcon","resolveIcon","wrappedRenderer","ctx","showExpandIcons","indentWidth","treeRow","container","icon","spacer","content","event","target","flatRow","focusRow","gridEl","style","body","animClass","rowEl","cell","idx"],"mappings":"gUAYO,SAASA,EAAeC,EAAcC,EAAeC,EAAkC,CAC5F,OAAIF,EAAI,KAAO,OAAkB,OAAOA,EAAI,EAAE,EACvCE,EAAY,GAAGA,CAAS,IAAID,CAAK,GAAK,OAAOA,CAAK,CAC3D,CA8CO,SAASE,EAAaC,EAA2BC,EAA0B,CAChF,MAAMC,EAAc,IAAI,IAAIF,CAAY,EACxC,OAAIE,EAAY,IAAID,CAAG,EACrBC,EAAY,OAAOD,CAAG,EAEtBC,EAAY,IAAID,CAAG,EAEdC,CACT,CAMO,SAASC,EACdC,EACAC,EACAP,EAA2B,KAC3BQ,EAAQ,EACK,CACb,MAAMC,EAAgBF,EAAO,eAAiB,WACxCG,MAAW,IAEjB,QAAS,EAAI,EAAG,EAAIJ,EAAK,OAAQ,IAAK,CACpC,MAAMR,EAAMQ,EAA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Q,KAAK,YAAY,EAC3F,KAAK,cAAA,CACP,CAGF"}
1
+ {"version":3,"file":"tree.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/tree/tree-data.ts","../../../../../libs/grid/src/lib/plugins/tree/tree-detect.ts","../../../../../libs/grid/src/lib/plugins/tree/TreePlugin.ts"],"sourcesContent":["/**\n * Core Tree Data Logic\n *\n * Pure functions for tree flattening, expansion, and traversal.\n */\n\nimport type { FlattenedTreeRow, TreeConfig, TreeRow } from './types';\n\n/**\n * Generates a unique key for a row.\n * Uses row.id if available, otherwise generates from path.\n */\nexport function generateRowKey(row: TreeRow, index: number, parentKey: string | null): string {\n if (row.id !== undefined) return String(row.id);\n return parentKey ? `${parentKey}-${index}` : String(index);\n}\n\n/**\n * Flattens a hierarchical tree into a flat array of rows with metadata.\n * Only includes children of expanded nodes.\n */\nexport function flattenTree(\n rows: readonly TreeRow[],\n config: TreeConfig,\n expandedKeys: Set<string>,\n parentKey: string | null = null,\n depth = 0,\n): FlattenedTreeRow[] {\n const childrenField = config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expandedKeys.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey,\n });\n\n // Recursively add children if expanded\n if (hasChildren && isExpanded) {\n const childRows = flattenTree(children as TreeRow[], config, expandedKeys, key, depth + 1);\n result.push(...childRows);\n }\n }\n\n return result;\n}\n\n/**\n * Toggles the expansion state of a row.\n * Returns a new Set with the toggled state.\n */\nexport function toggleExpand(expandedKeys: Set<string>, key: string): Set<string> {\n const newExpanded = new Set(expandedKeys);\n if (newExpanded.has(key)) {\n newExpanded.delete(key);\n } else {\n newExpanded.add(key);\n }\n return newExpanded;\n}\n\n/**\n * Expands all nodes in the tree.\n * Returns a Set of all parent row keys.\n */\nexport function expandAll(\n rows: readonly TreeRow[],\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): Set<string> {\n const childrenField = config.childrenField ?? 'children';\n const keys = new Set<string>();\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n const children = row[childrenField];\n\n if (Array.isArray(children) && children.length > 0) {\n keys.add(key);\n const childKeys = expandAll(children as TreeRow[], config, key, depth + 1);\n for (const k of childKeys) keys.add(k);\n }\n }\n\n return keys;\n}\n\n/**\n * Collapses all nodes.\n * Returns an empty Set.\n */\nexport function collapseAll(): Set<string> {\n return new Set();\n}\n\n/**\n * Gets all descendants of a node from the flattened row list.\n * Useful for operations that need to affect an entire subtree.\n */\nexport function getDescendants(flattenedRows: FlattenedTreeRow[], parentKey: string): FlattenedTreeRow[] {\n const descendants: FlattenedTreeRow[] = [];\n let collecting = false;\n let parentDepth = -1;\n\n for (const row of flattenedRows) {\n if (row.key === parentKey) {\n collecting = true;\n parentDepth = row.depth;\n continue;\n }\n\n if (collecting) {\n if (row.depth > parentDepth) {\n descendants.push(row);\n } else {\n break; // No longer a descendant\n }\n }\n }\n\n return descendants;\n}\n\n/**\n * Finds the path from root to a specific row key.\n * Returns an array of keys from root to the target (inclusive).\n */\nexport function getPathToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n parentKey: string | null = null,\n depth = 0,\n): string[] | null {\n const childrenField = config.childrenField ?? 'children';\n\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n const key = generateRowKey(row, i, parentKey);\n\n if (key === targetKey) {\n return [key];\n }\n\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childPath = getPathToKey(children as TreeRow[], targetKey, config, key, depth + 1);\n if (childPath) {\n return [key, ...childPath];\n }\n }\n }\n\n return null;\n}\n\n/**\n * Expands all ancestors of a specific row to make it visible.\n * Returns a new Set with the required keys added.\n */\nexport function expandToKey(\n rows: readonly TreeRow[],\n targetKey: string,\n config: TreeConfig,\n existingExpanded: Set<string>,\n): Set<string> {\n const path = getPathToKey(rows, targetKey, config);\n if (!path) return existingExpanded;\n\n const newExpanded = new Set(existingExpanded);\n // Add all keys except the last one (the target itself)\n for (let i = 0; i < path.length - 1; i++) {\n newExpanded.add(path[i]);\n }\n return newExpanded;\n}\n","/**\n * Tree Structure Auto-Detection\n *\n * Utilities for detecting hierarchical tree data structures.\n */\n\nimport type { TreeRow } from './types';\n\n/**\n * Detects if the data has a tree structure by checking for children arrays.\n */\nexport function detectTreeStructure(rows: readonly TreeRow[], childrenField = 'children'): boolean {\n if (!Array.isArray(rows) || rows.length === 0) return false;\n\n // Check if any row has a non-empty children array\n for (const row of rows) {\n if (!row) continue;\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Attempts to infer the children field name from common patterns.\n * Returns the first field that contains an array with items.\n */\nexport function inferChildrenField(rows: readonly TreeRow[]): string | null {\n if (!Array.isArray(rows) || rows.length === 0) return null;\n\n const commonArrayFields = ['children', 'items', 'nodes', 'subRows', 'nested'];\n\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue;\n\n for (const field of commonArrayFields) {\n const value = row[field];\n if (Array.isArray(value) && value.length > 0) {\n return field;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Calculates the maximum depth of the tree.\n * Useful for layout calculations and virtualization.\n */\nexport function getMaxDepth(rows: readonly TreeRow[], childrenField = 'children', currentDepth = 0): number {\n if (!Array.isArray(rows) || rows.length === 0) return currentDepth;\n\n let maxDepth = currentDepth;\n\n for (const row of rows) {\n if (!row) continue;\n const children = row[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n const childDepth = getMaxDepth(children as TreeRow[], childrenField, currentDepth + 1);\n if (childDepth > maxDepth) {\n maxDepth = childDepth;\n }\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Counts total nodes in the tree (including all descendants).\n */\nexport function countNodes(rows: readonly TreeRow[], childrenField = 'children'): number {\n if (!Array.isArray(rows)) return 0;\n\n let count = 0;\n for (const row of rows) {\n if (!row) continue;\n count++;\n const children = row[childrenField];\n if (Array.isArray(children)) {\n count += countNodes(children as TreeRow[], childrenField);\n }\n }\n\n return count;\n}\n","/**\n * Tree Data Plugin\n *\n * Enables hierarchical tree data with expand/collapse, sorting, and auto-detection.\n */\n\nimport {\n BaseGridPlugin,\n CellClickEvent,\n HeaderClickEvent,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ColumnViewRenderer } from '../../core/types';\nimport { collapseAll, expandAll, expandToKey, toggleExpand } from './tree-data';\nimport { detectTreeStructure, inferChildrenField } from './tree-detect';\nimport styles from './tree.css?inline';\nimport type { ExpandCollapseAnimation, FlattenedTreeRow, TreeConfig, TreeExpandDetail, TreeRow } from './types';\n\ninterface GridWithSortState {\n _sortState?: { field: string; direction: 1 | -1 } | null;\n}\n\n/**\n * Tree Data Plugin for tbw-grid\n *\n * Transforms your flat grid into a hierarchical tree view with expandable parent-child\n * relationships. Ideal for file explorers, organizational charts, nested categories,\n * or any data with a natural hierarchy.\n *\n * ## Installation\n *\n * ```ts\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `childrenField` | `string` | `'children'` | Field containing child array |\n * | `autoDetect` | `boolean` | `true` | Auto-detect tree structure from data |\n * | `defaultExpanded` | `boolean` | `false` | Expand all nodes initially |\n * | `indentWidth` | `number` | `20` | Indentation per level (pixels) |\n * | `showExpandIcons` | `boolean` | `true` | Show expand/collapse toggle icons |\n * | `animation` | `false \\| 'slide' \\| 'fade'` | `'slide'` | Animation style for expand/collapse |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `expand` | `(nodeId) => void` | Expand a specific node |\n * | `collapse` | `(nodeId) => void` | Collapse a specific node |\n * | `toggle` | `(nodeId) => void` | Toggle a node's expanded state |\n * | `expandAll` | `() => void` | Expand all nodes |\n * | `collapseAll` | `() => void` | Collapse all nodes |\n * | `getExpandedNodes` | `() => Set<string>` | Get currently expanded node keys |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-tree-toggle-size` | `1.25em` | Toggle icon width |\n * | `--tbw-tree-indent-width` | `var(--tbw-tree-toggle-size)` | Indentation per level |\n * | `--tbw-tree-accent` | `var(--tbw-color-accent)` | Toggle icon hover color |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation duration |\n * | `--tbw-animation-easing` | `ease-out` | Animation curve |\n *\n * @example Basic Tree with Nested Children\n * ```ts\n * import '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'type', header: 'Type' },\n * { field: 'size', header: 'Size' },\n * ],\n * plugins: [new TreePlugin({ childrenField: 'children', indentWidth: 24 })],\n * };\n * grid.rows = [\n * {\n * id: 1,\n * name: 'Documents',\n * type: 'folder',\n * children: [\n * { id: 2, name: 'Report.docx', type: 'file', size: '24 KB' },\n * ],\n * },\n * ];\n * ```\n *\n * @example Expanded by Default with Custom Animation\n * ```ts\n * new TreePlugin({\n * defaultExpanded: true,\n * animation: 'fade', // 'slide' | 'fade' | false\n * indentWidth: 32,\n * })\n * ```\n *\n * @see {@link TreeConfig} for all configuration options\n * @see {@link FlattenedTreeRow} for the flattened row structure\n *\n * @internal Extends BaseGridPlugin\n */\nexport class TreePlugin extends BaseGridPlugin<TreeConfig> {\n static override readonly manifest: PluginManifest = {\n events: [\n {\n type: 'tree-state-change',\n description: 'Emitted when tree expansion state changes (toggle, expand all, collapse all)',\n },\n ],\n queries: [\n {\n type: 'canMoveRow',\n description: 'Returns false for rows with children (parent nodes cannot be reordered)',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'tree';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<TreeConfig> {\n return {\n childrenField: 'children',\n autoDetect: true,\n defaultExpanded: false,\n indentWidth: 20,\n showExpandIcons: true,\n animation: 'slide',\n };\n }\n\n // #region State\n\n private expandedKeys = new Set<string>();\n private initialExpansionDone = false;\n private flattenedRows: FlattenedTreeRow[] = [];\n private rowKeyMap = new Map<string, FlattenedTreeRow>();\n private previousVisibleKeys = new Set<string>();\n private keysToAnimate = new Set<string>();\n private sortState: { field: string; direction: 1 | -1 } | null = null;\n\n /** @internal */\n override detach(): void {\n this.expandedKeys.clear();\n this.initialExpansionDone = false;\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.keysToAnimate.clear();\n this.sortState = null;\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'canMoveRow') {\n // Tree rows with children cannot be reordered\n const row = query.context as { [key: string]: unknown } | null | undefined;\n const childrenField = this.config.childrenField ?? 'children';\n const children = row?.[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return false;\n }\n }\n return undefined;\n }\n\n // #endregion\n\n // #region Animation\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 // #endregion\n\n // #region Auto-Detection\n\n detect(rows: readonly unknown[]): boolean {\n if (!this.config.autoDetect) return false;\n const treeRows = rows as readonly TreeRow[];\n const field = this.config.childrenField ?? inferChildrenField(treeRows) ?? 'children';\n return detectTreeStructure(treeRows, field);\n }\n\n // #endregion\n\n // #region Data Processing\n\n /** @internal */\n override processRows(rows: readonly unknown[]): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const treeRows = rows as readonly TreeRow[];\n\n if (!detectTreeStructure(treeRows, childrenField)) {\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n return [...rows] as TreeRow[];\n }\n\n // Assign stable keys, then optionally sort\n let data = this.withStableKeys(treeRows);\n if (this.sortState) {\n data = this.sortTree(data, this.sortState.field, this.sortState.direction);\n }\n\n // Initialize expansion if needed\n if (this.config.defaultExpanded && !this.initialExpansionDone) {\n this.expandedKeys = expandAll(data, this.config);\n this.initialExpansionDone = true;\n }\n\n // Flatten and track animations\n this.flattenedRows = this.flattenTree(data, this.expandedKeys);\n this.rowKeyMap.clear();\n this.keysToAnimate.clear();\n const currentKeys = new Set<string>();\n\n for (const row of this.flattenedRows) {\n this.rowKeyMap.set(row.key, row);\n currentKeys.add(row.key);\n if (!this.previousVisibleKeys.has(row.key) && row.depth > 0) {\n this.keysToAnimate.add(row.key);\n }\n }\n this.previousVisibleKeys = currentKeys;\n\n return this.flattenedRows.map((r) => ({\n ...r.data,\n __treeKey: r.key,\n __treeDepth: r.depth,\n __treeHasChildren: r.hasChildren,\n __treeExpanded: r.isExpanded,\n }));\n }\n\n /** Assign stable keys to rows (preserves key across sort operations) */\n private withStableKeys(rows: readonly TreeRow[], parentKey: string | null = null): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n return rows.map((row, i) => {\n const stableKey = row.__stableKey as string | undefined;\n const key = row.id !== undefined ? String(row.id) : (stableKey ?? (parentKey ? `${parentKey}-${i}` : String(i)));\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n return {\n ...row,\n __stableKey: key,\n ...(hasChildren ? { [childrenField]: this.withStableKeys(children as TreeRow[], key) } : {}),\n };\n });\n }\n\n /** Flatten tree using stable keys */\n private flattenTree(rows: readonly TreeRow[], expanded: Set<string>, depth = 0): FlattenedTreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n\n for (const row of rows) {\n const stableKey = row.__stableKey as string | undefined;\n const key = stableKey ?? String(row.id ?? '?');\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expanded.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey: depth > 0 ? key.substring(0, key.lastIndexOf('-')) || null : null,\n });\n\n if (hasChildren && isExpanded) {\n result.push(...this.flattenTree(children as TreeRow[], expanded, depth + 1));\n }\n }\n return result;\n }\n\n /** Sort tree recursively, keeping children with parents */\n private sortTree(rows: readonly TreeRow[], field: string, dir: 1 | -1): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const sorted = [...rows].sort((a, b) => {\n const aVal = a[field],\n bVal = b[field];\n if (aVal == null && bVal == null) return 0;\n if (aVal == null) return -1;\n if (bVal == null) return 1;\n return aVal > bVal ? dir : aVal < bVal ? -dir : 0;\n });\n return sorted.map((row) => {\n const children = row[childrenField];\n return Array.isArray(children) && children.length > 0\n ? { ...row, [childrenField]: this.sortTree(children as TreeRow[], field, dir) }\n : row;\n });\n }\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (this.flattenedRows.length === 0) return [...columns];\n\n const cols = [...columns] as ColumnConfig[];\n if (cols.length === 0) return cols;\n\n // Wrap the first column's renderer to add tree indentation and expand icons\n // This is the correct approach for trees because:\n // 1. Indentation can grow naturally with depth\n // 2. Expand icons appear inline with content\n // 3. Works with column reordering (icons stay with first visible column)\n const firstCol = cols[0];\n const originalRenderer = firstCol.viewRenderer;\n const getConfig = () => this.config;\n const setIcon = this.setIcon.bind(this);\n const resolveIcon = this.resolveIcon.bind(this);\n\n const wrappedRenderer: ColumnViewRenderer = (ctx) => {\n const { row, value } = ctx;\n const { showExpandIcons = true, indentWidth } = getConfig();\n const treeRow = row as TreeRow;\n const depth = treeRow.__treeDepth ?? 0;\n\n const container = document.createElement('span');\n container.className = 'tree-cell-wrapper';\n container.style.setProperty('--tbw-tree-depth', String(depth));\n // Allow config-based indentWidth to override CSS default\n if (indentWidth !== undefined) {\n container.style.setProperty('--tbw-tree-indent-width', `${indentWidth}px`);\n }\n\n // Add expand/collapse icon or spacer\n if (showExpandIcons) {\n if (treeRow.__treeHasChildren) {\n const icon = document.createElement('span');\n icon.className = `tree-toggle${treeRow.__treeExpanded ? ' expanded' : ''}`;\n setIcon(icon, resolveIcon(treeRow.__treeExpanded ? 'collapse' : 'expand'));\n icon.setAttribute('data-tree-key', String(treeRow.__treeKey ?? ''));\n container.appendChild(icon);\n } else {\n const spacer = document.createElement('span');\n spacer.className = 'tree-spacer';\n container.appendChild(spacer);\n }\n }\n\n // Add the original content\n const content = document.createElement('span');\n content.className = 'tree-content';\n if (originalRenderer) {\n const result = originalRenderer(ctx);\n if (result instanceof Node) {\n content.appendChild(result);\n } else if (typeof result === 'string') {\n content.innerHTML = result;\n }\n } else {\n content.textContent = value != null ? String(value) : '';\n }\n container.appendChild(content);\n\n return container;\n };\n\n cols[0] = { ...firstCol, viewRenderer: wrappedRenderer };\n return cols;\n }\n\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n const target = event.originalEvent?.target as HTMLElement;\n if (!target?.classList.contains('tree-toggle')) return false;\n\n const key = target.getAttribute('data-tree-key');\n if (!key) return false;\n\n const flatRow = this.rowKeyMap.get(key);\n if (!flatRow) return false;\n\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n this.emit<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when on a row with children\n if (event.key !== ' ') return;\n\n const focusRow = this.grid._focusRow;\n const flatRow = this.flattenedRows[focusRow];\n if (!flatRow?.hasChildren) return;\n\n event.preventDefault();\n this.expandedKeys = toggleExpand(this.expandedKeys, flatRow.key);\n this.emit<TreeExpandDetail>('tree-expand', {\n key: flatRow.key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(flatRow.key),\n depth: flatRow.depth,\n });\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n if (this.flattenedRows.length === 0 || !event.column.sortable) return false;\n\n const { field } = event.column;\n if (!this.sortState || this.sortState.field !== field) {\n this.sortState = { field, direction: 1 };\n } else if (this.sortState.direction === 1) {\n this.sortState = { field, direction: -1 };\n } else {\n this.sortState = null;\n }\n\n // Sync grid sort indicator\n const gridEl = this.grid as unknown as GridWithSortState;\n if (gridEl._sortState !== undefined) {\n gridEl._sortState = this.sortState ? { ...this.sortState } : null;\n }\n\n this.emit('sort-change', { field, direction: this.sortState?.direction ?? 0 });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n const style = this.animationStyle;\n if (style === false || this.keysToAnimate.size === 0) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n const animClass = style === 'fade' ? 'tbw-tree-fade-in' : 'tbw-tree-slide-in';\n for (const rowEl of body.querySelectorAll('.data-grid-row')) {\n const cell = rowEl.querySelector('.cell[data-row]');\n const idx = cell ? parseInt(cell.getAttribute('data-row') ?? '-1', 10) : -1;\n const key = this.flattenedRows[idx]?.key;\n\n if (key && this.keysToAnimate.has(key)) {\n rowEl.classList.add(animClass);\n rowEl.addEventListener('animationend', () => rowEl.classList.remove(animClass), { once: true });\n }\n }\n this.keysToAnimate.clear();\n }\n\n // #endregion\n\n // #region Public API\n\n expand(key: string): void {\n this.expandedKeys.add(key);\n this.requestRender();\n }\n\n collapse(key: string): void {\n this.expandedKeys.delete(key);\n this.requestRender();\n }\n\n toggle(key: string): void {\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n expandAll(): void {\n this.expandedKeys = expandAll(this.rows as TreeRow[], this.config);\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n collapseAll(): void {\n this.expandedKeys = collapseAll();\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n isExpanded(key: string): boolean {\n return this.expandedKeys.has(key);\n }\n\n getExpandedKeys(): string[] {\n return [...this.expandedKeys];\n }\n\n getFlattenedRows(): FlattenedTreeRow[] {\n return [...this.flattenedRows];\n }\n\n getRowByKey(key: string): TreeRow | undefined {\n return this.rowKeyMap.get(key)?.data;\n }\n\n expandToKey(key: string): void {\n this.expandedKeys = expandToKey(this.rows as TreeRow[], key, this.config, this.expandedKeys);\n this.requestRender();\n }\n\n // #endregion\n}\n"],"names":["generateRowKey","row","index","parentKey","id","String","toggleExpand","expandedKeys","key","newExpanded","Set","has","delete","add","expandAll","rows","config","depth","childrenField","keys","i","length","children","Array","isArray","childKeys","k","getPathToKey","targetKey","childPath","expandToKey","existingExpanded","path","detectTreeStructure","TreePlugin","BaseGridPlugin","static","events","type","description","queries","name","styles","defaultConfig","autoDetect","defaultExpanded","indentWidth","showExpandIcons","animation","initialExpansionDone","flattenedRows","rowKeyMap","Map","previousVisibleKeys","keysToAnimate","sortState","detach","this","clear","handleQuery","query","context","animationStyle","isAnimationEnabled","detect","treeRows","field","commonArrayFields","value","inferChildrenField","processRows","data","withStableKeys","sortTree","direction","flattenTree","currentKeys","set","map","r","__treeKey","__treeDepth","__treeHasChildren","hasChildren","__treeExpanded","isExpanded","stableKey","__stableKey","expanded","result","push","substring","lastIndexOf","dir","sort","a","b","aVal","bVal","processColumns","columns","cols","firstCol","originalRenderer","viewRenderer","getConfig","setIcon","bind","resolveIcon","ctx","treeRow","container","document","createElement","className","style","setProperty","icon","setAttribute","appendChild","spacer","content","Node","innerHTML","textContent","onCellClick","event","target","originalEvent","classList","contains","getAttribute","flatRow","get","emit","requestRender","onKeyDown","focusRow","grid","_focusRow","preventDefault","requestRenderWithFocus","onHeaderClick","column","sortable","gridEl","_sortState","afterRender","size","body","gridElement","querySelector","animClass","rowEl","querySelectorAll","cell","idx","parseInt","addEventListener","remove","once","expand","collapse","toggle","emitPluginEvent","collapseAll","getExpandedKeys","getFlattenedRows","getRowByKey"],"mappings":"8UAYO,SAASA,EAAeC,EAAcC,EAAeC,GAC1D,YAAe,IAAXF,EAAIG,GAAyBC,OAAOJ,EAAIG,IACrCD,EAAY,GAAGA,KAAaD,IAAUG,OAAOH,EACtD,CA8CO,SAASI,EAAaC,EAA2BC,GACtD,MAAMC,EAAc,IAAIC,IAAIH,GAM5B,OALIE,EAAYE,IAAIH,GAClBC,EAAYG,OAAOJ,GAEnBC,EAAYI,IAAIL,GAEXC,CACT,CAMO,SAASK,EACdC,EACAC,EACAb,EAA2B,KAC3Bc,EAAQ,GAER,MAAMC,EAAgBF,EAAOE,eAAiB,WACxCC,MAAWT,IAEjB,IAAA,IAASU,EAAI,EAAGA,EAAIL,EAAKM,OAAQD,IAAK,CACpC,MAAMnB,EAAMc,EAAKK,GACXZ,EAAMR,EAAeC,EAAKmB,EAAGjB,GAC7BmB,EAAWrB,EAAIiB,GAErB,GAAIK,MAAMC,QAAQF,IAAaA,EAASD,OAAS,EAAG,CAClDF,EAAKN,IAAIL,GACT,MAAMiB,EAAYX,EAAUQ,EAAuBN,EAAQR,EAAKS,EAAQ,GACxE,IAAA,MAAWS,KAAKD,EAAWN,EAAKN,IAAIa,EACtC,CACF,CAEA,OAAOP,CACT,CA0CO,SAASQ,EACdZ,EACAa,EACAZ,EACAb,EAA2B,KAC3Bc,EAAQ,GAER,MAAMC,EAAgBF,EAAOE,eAAiB,WAE9C,IAAA,IAASE,EAAI,EAAGA,EAAIL,EAAKM,OAAQD,IAAK,CACpC,MAAMnB,EAAMc,EAAKK,GACXZ,EAAMR,EAAeC,EAAKmB,EAAGjB,GAEnC,GAAIK,IAAQoB,EACV,MAAO,CAACpB,GAGV,MAAMc,EAAWrB,EAAIiB,GACrB,GAAIK,MAAMC,QAAQF,IAAaA,EAASD,OAAS,EAAG,CAClD,MAAMQ,EAAYF,EAAa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AEA,WAAAzC,CAAYtB,GACViD,KAAKlD,aAAeuB,EAAY2B,KAAK1C,KAAmBP,EAAKiD,KAAKzC,OAAQyC,KAAKlD,cAC/EkD,KAAK8E,eACP"}
@@ -1,2 +1,2 @@
1
- (function(i,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin"],d):(i=typeof globalThis<"u"?globalThis:i||self,d(i.TbwGridPlugin_undoRedo={},i.TbwGrid))})(this,(function(i,d){"use strict";function S(n,t,e){const c=[...n.undoStack,t];for(;c.length>e;)c.shift();return{undoStack:c,redoStack:[]}}function r(n){if(n.undoStack.length===0)return{newState:n,action:null};const t=[...n.undoStack],e=t.pop();return e?{newState:{undoStack:t,redoStack:[...n.redoStack,e]},action:e}:{newState:n,action:null}}function u(n){if(n.redoStack.length===0)return{newState:n,action:null};const t=[...n.redoStack],e=t.pop();return e?{newState:{undoStack:[...n.undoStack,e],redoStack:t},action:e}:{newState:n,action:null}}function k(n){return n.undoStack.length>0}function h(n){return n.redoStack.length>0}function l(){return{undoStack:[],redoStack:[]}}function f(n,t,e,c){return{type:"cell-edit",rowIndex:n,field:t,oldValue:e,newValue:c,timestamp:Date.now()}}class w extends d.BaseGridPlugin{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];attach(t){super.attach(t),this.on("cell-edit-committed",e=>{this.recordEdit(e.rowIndex,e.field,e.oldValue,e.newValue)})}detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(t){const e=(t.ctrlKey||t.metaKey)&&t.key==="z"&&!t.shiftKey,c=(t.ctrlKey||t.metaKey)&&(t.key==="y"||t.key==="z"&&t.shiftKey);if(e){const o=r({undoStack:this.undoStack,redoStack:this.redoStack});if(o.action){const a=this.rows;a[o.action.rowIndex]&&(a[o.action.rowIndex][o.action.field]=o.action.oldValue),this.undoStack=o.newState.undoStack,this.redoStack=o.newState.redoStack,this.emit("undo",{action:o.action,type:"undo"}),this.requestRender()}return!0}if(c){const o=u({undoStack:this.undoStack,redoStack:this.redoStack});if(o.action){const a=this.rows;a[o.action.rowIndex]&&(a[o.action.rowIndex][o.action.field]=o.action.newValue),this.undoStack=o.newState.undoStack,this.redoStack=o.newState.redoStack,this.emit("redo",{action:o.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(t,e,c,o){const a=f(t,e,c,o),s=S({undoStack:this.undoStack,redoStack:this.redoStack},a,this.config.maxHistorySize??100);this.undoStack=s.undoStack,this.redoStack=s.redoStack}undo(){const t=r({undoStack:this.undoStack,redoStack:this.redoStack});if(t.action){const e=this.rows;e[t.action.rowIndex]&&(e[t.action.rowIndex][t.action.field]=t.action.oldValue),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.requestRender()}return t.action}redo(){const t=u({undoStack:this.undoStack,redoStack:this.redoStack});if(t.action){const e=this.rows;e[t.action.rowIndex]&&(e[t.action.rowIndex][t.action.field]=t.action.newValue),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.requestRender()}return t.action}canUndo(){return k({undoStack:this.undoStack,redoStack:this.redoStack})}canRedo(){return h({undoStack:this.undoStack,redoStack:this.redoStack})}clearHistory(){const t=l();this.undoStack=t.undoStack,this.redoStack=t.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}i.UndoRedoPlugin=w,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_undoRedo={},t.TbwGrid)}(this,function(t,e){"use strict";function o(t){if(0===t.undoStack.length)return{newState:t,action:null};const e=[...t.undoStack],o=e.pop();return o?{newState:{undoStack:e,redoStack:[...t.redoStack,o]},action:o}:{newState:t,action:null}}function n(t){if(0===t.redoStack.length)return{newState:t,action:null};const e=[...t.redoStack],o=e.pop();return o?{newState:{undoStack:[...t.undoStack,o],redoStack:e},action:o}:{newState:t,action:null}}class a extends e.BaseGridPlugin{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];attach(t){super.attach(t),this.on("cell-edit-committed",t=>{this.recordEdit(t.rowIndex,t.field,t.oldValue,t.newValue)})}detach(){this.undoStack=[],this.redoStack=[]}onKeyDown(t){const e=(t.ctrlKey||t.metaKey)&&"z"===t.key&&!t.shiftKey,a=(t.ctrlKey||t.metaKey)&&("y"===t.key||"z"===t.key&&t.shiftKey);if(e){const t=o({undoStack:this.undoStack,redoStack:this.redoStack});if(t.action){const e=this.rows;e[t.action.rowIndex]&&(e[t.action.rowIndex][t.action.field]=t.action.oldValue),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("undo",{action:t.action,type:"undo"}),this.requestRender()}return!0}if(a){const t=n({undoStack:this.undoStack,redoStack:this.redoStack});if(t.action){const e=this.rows;e[t.action.rowIndex]&&(e[t.action.rowIndex][t.action.field]=t.action.newValue),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.emit("redo",{action:t.action,type:"redo"}),this.requestRender()}return!0}return!1}recordEdit(t,e,o,n){const a=function(t,e,o,n){return{type:"cell-edit",rowIndex:t,field:e,oldValue:o,newValue:n,timestamp:Date.now()}}(t,e,o,n),c=function(t,e,o){const n=[...t.undoStack,e];for(;n.length>o;)n.shift();return{undoStack:n,redoStack:[]}}({undoStack:this.undoStack,redoStack:this.redoStack},a,this.config.maxHistorySize??100);this.undoStack=c.undoStack,this.redoStack=c.redoStack}undo(){const t=o({undoStack:this.undoStack,redoStack:this.redoStack});if(t.action){const e=this.rows;e[t.action.rowIndex]&&(e[t.action.rowIndex][t.action.field]=t.action.oldValue),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.requestRender()}return t.action}redo(){const t=n({undoStack:this.undoStack,redoStack:this.redoStack});if(t.action){const e=this.rows;e[t.action.rowIndex]&&(e[t.action.rowIndex][t.action.field]=t.action.newValue),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.requestRender()}return t.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const t={undoStack:[],redoStack:[]};this.undoStack=t.undoStack,this.redoStack=t.redoStack}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}t.UndoRedoPlugin=a,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=undo-redo.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"undo-redo.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/undo-redo/history.ts","../../../../../libs/grid/src/lib/plugins/undo-redo/UndoRedoPlugin.ts"],"sourcesContent":["/**\n * Undo/Redo History Management\n *\n * Pure functions for managing the undo/redo stacks.\n * These functions are stateless and return new state objects.\n */\n\nimport type { EditAction, UndoRedoState } from './types';\n\n/**\n * Push a new action onto the undo stack.\n * Clears the redo stack since new actions invalidate redo history.\n *\n * @param state - Current undo/redo state\n * @param action - The action to add\n * @param maxSize - Maximum history size\n * @returns New state with the action added\n */\nexport function pushAction(state: UndoRedoState, action: EditAction, maxSize: number): UndoRedoState {\n const undoStack = [...state.undoStack, action];\n\n // Trim oldest actions if over max size\n while (undoStack.length > maxSize) {\n undoStack.shift();\n }\n\n return {\n undoStack,\n redoStack: [], // Clear redo on new action\n };\n}\n\n/**\n * Undo the most recent action.\n * Moves the action from undo stack to redo stack.\n *\n * @param state - Current undo/redo state\n * @returns New state and the action that was undone (or null if nothing to undo)\n */\nexport function undo(state: UndoRedoState): {\n newState: UndoRedoState;\n action: EditAction | null;\n} {\n if (state.undoStack.length === 0) {\n return { newState: state, action: null };\n }\n\n const undoStack = [...state.undoStack];\n const action = undoStack.pop();\n\n // This should never happen due to the length check above,\n // but TypeScript needs the explicit check\n if (!action) {\n return { newState: state, action: null };\n }\n\n return {\n newState: {\n undoStack,\n redoStack: [...state.redoStack, action],\n },\n action,\n };\n}\n\n/**\n * Redo the most recently undone action.\n * Moves the action from redo stack back to undo stack.\n *\n * @param state - Current undo/redo state\n * @returns New state and the action that was redone (or null if nothing to redo)\n */\nexport function redo(state: UndoRedoState): {\n newState: UndoRedoState;\n action: EditAction | null;\n} {\n if (state.redoStack.length === 0) {\n return { newState: state, action: null };\n }\n\n const redoStack = [...state.redoStack];\n const action = redoStack.pop();\n\n // This should never happen due to the length check above,\n // but TypeScript needs the explicit check\n if (!action) {\n return { newState: state, action: null };\n }\n\n return {\n newState: {\n undoStack: [...state.undoStack, action],\n redoStack,\n },\n action,\n };\n}\n\n/**\n * Check if there are any actions that can be undone.\n *\n * @param state - Current undo/redo state\n * @returns True if undo is available\n */\nexport function canUndo(state: UndoRedoState): boolean {\n return state.undoStack.length > 0;\n}\n\n/**\n * Check if there are any actions that can be redone.\n *\n * @param state - Current undo/redo state\n * @returns True if redo is available\n */\nexport function canRedo(state: UndoRedoState): boolean {\n return state.redoStack.length > 0;\n}\n\n/**\n * Clear all history, returning an empty state.\n *\n * @returns Fresh empty state\n */\nexport function clearHistory(): UndoRedoState {\n return { undoStack: [], redoStack: [] };\n}\n\n/**\n * Create a new edit action with the current timestamp.\n *\n * @param rowIndex - The row index where the edit occurred\n * @param field - The field (column key) that was edited\n * @param oldValue - The value before the edit\n * @param newValue - The value after the edit\n * @returns A new EditAction object\n */\nexport function createEditAction(rowIndex: number, field: string, oldValue: unknown, newValue: unknown): EditAction {\n return {\n type: 'cell-edit',\n rowIndex,\n field,\n oldValue,\n newValue,\n timestamp: Date.now(),\n };\n}\n","/**\n * Undo/Redo Plugin (Class-based)\n *\n * Provides undo/redo functionality for cell edits in tbw-grid.\n * Supports Ctrl+Z/Cmd+Z for undo and Ctrl+Y/Cmd+Y (or Ctrl+Shift+Z) for redo.\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport { canRedo, canUndo, clearHistory, createEditAction, pushAction, redo, undo } from './history';\nimport type { EditAction, UndoRedoConfig, UndoRedoDetail } from './types';\n\n/**\n * Undo/Redo Plugin for tbw-grid\n *\n * Tracks all cell edits and lets users revert or replay changes with familiar keyboard\n * shortcuts (Ctrl+Z / Ctrl+Y). Maintains an in-memory history stack with configurable\n * depth—perfect for data entry workflows where mistakes happen.\n *\n * > **Required Dependency:** This plugin requires EditingPlugin to be loaded first.\n * > UndoRedo tracks the edit history that EditingPlugin creates.\n *\n * ## Installation\n *\n * ```ts\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * import { UndoRedoPlugin } from '@toolbox-web/grid/plugins/undo-redo';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `maxHistorySize` | `number` | `100` | Maximum actions in history stack |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+Z` / `Cmd+Z` | Undo last edit |\n * | `Ctrl+Y` / `Cmd+Shift+Z` | Redo last undone edit |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `undo` | `() => void` | Undo the last edit |\n * | `redo` | `() => void` | Redo the last undone edit |\n * | `canUndo` | `() => boolean` | Check if undo is available |\n * | `canRedo` | `() => boolean` | Check if redo is available |\n * | `clearHistory` | `() => void` | Clear the entire history stack |\n *\n * @example Basic Usage with EditingPlugin\n * ```ts\n * import '@toolbox-web/grid';\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * import { UndoRedoPlugin } from '@toolbox-web/grid/plugins/undo-redo';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name', editable: true },\n * { field: 'price', header: 'Price', type: 'number', editable: true },\n * ],\n * plugins: [\n * new EditingPlugin({ editOn: 'dblclick' }), // Required - must be first\n * new UndoRedoPlugin({ maxHistorySize: 50 }),\n * ],\n * };\n * ```\n *\n * @see {@link UndoRedoConfig} for configuration options\n * @see {@link EditingPlugin} for the required dependency\n *\n * @internal Extends BaseGridPlugin\n */\nexport class UndoRedoPlugin extends BaseGridPlugin<UndoRedoConfig> {\n /**\n * Plugin dependencies - UndoRedoPlugin requires EditingPlugin to track edits.\n *\n * The EditingPlugin must be loaded BEFORE this plugin in the plugins array.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'editing', required: true, reason: 'UndoRedoPlugin tracks cell edit history' },\n ];\n\n /** @internal */\n readonly name = 'undoRedo';\n\n /** @internal */\n protected override get defaultConfig(): Partial<UndoRedoConfig> {\n return {\n maxHistorySize: 100,\n };\n }\n\n // State as class properties\n private undoStack: EditAction[] = [];\n private redoStack: EditAction[] = [];\n\n /**\n * Subscribe to cell-edit-committed events from EditingPlugin.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n // Auto-record edits via Event Bus\n this.on(\n 'cell-edit-committed',\n (detail: { rowIndex: number; field: string; oldValue: unknown; newValue: unknown }) => {\n this.recordEdit(detail.rowIndex, detail.field, detail.oldValue, detail.newValue);\n },\n );\n }\n\n /**\n * Clean up state when plugin is detached.\n * @internal\n */\n override detach(): void {\n this.undoStack = [];\n this.redoStack = [];\n }\n\n /**\n * Handle keyboard shortcuts for undo/redo.\n * - Ctrl+Z / Cmd+Z: Undo\n * - Ctrl+Y / Cmd+Y / Ctrl+Shift+Z / Cmd+Shift+Z: Redo\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isUndo = (event.ctrlKey || event.metaKey) && event.key === 'z' && !event.shiftKey;\n const isRedo = (event.ctrlKey || event.metaKey) && (event.key === 'y' || (event.key === 'z' && event.shiftKey));\n\n if (isUndo) {\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n // Apply undo - restore old value\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.oldValue;\n }\n\n // Update state from result\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n\n this.emit<UndoRedoDetail>('undo', {\n action: result.action,\n type: 'undo',\n });\n\n this.requestRender();\n }\n return true;\n }\n\n if (isRedo) {\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n // Apply redo - restore new value\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.newValue;\n }\n\n // Update state from result\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n\n this.emit<UndoRedoDetail>('redo', {\n action: result.action,\n type: 'redo',\n });\n\n this.requestRender();\n }\n return true;\n }\n\n return false;\n }\n\n // #region Public API Methods\n\n /**\n * Record a cell edit for undo/redo tracking.\n * Call this when a cell value changes.\n *\n * @param rowIndex - The row index where the edit occurred\n * @param field - The field (column key) that was edited\n * @param oldValue - The value before the edit\n * @param newValue - The value after the edit\n */\n recordEdit(rowIndex: number, field: string, oldValue: unknown, newValue: unknown): void {\n const action = createEditAction(rowIndex, field, oldValue, newValue);\n const newState = pushAction(\n { undoStack: this.undoStack, redoStack: this.redoStack },\n action,\n this.config.maxHistorySize ?? 100,\n );\n this.undoStack = newState.undoStack;\n this.redoStack = newState.redoStack;\n }\n\n /**\n * Programmatically undo the last action.\n *\n * @returns The undone action, or null if nothing to undo\n */\n undo(): EditAction | null {\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.oldValue;\n }\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.requestRender();\n }\n return result.action;\n }\n\n /**\n * Programmatically redo the last undone action.\n *\n * @returns The redone action, or null if nothing to redo\n */\n redo(): EditAction | null {\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.newValue;\n }\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.requestRender();\n }\n return result.action;\n }\n\n /**\n * Check if there are any actions that can be undone.\n */\n canUndo(): boolean {\n return canUndo({ undoStack: this.undoStack, redoStack: this.redoStack });\n }\n\n /**\n * Check if there are any actions that can be redone.\n */\n canRedo(): boolean {\n return canRedo({ undoStack: this.undoStack, redoStack: this.redoStack });\n }\n\n /**\n * Clear all undo/redo history.\n */\n clearHistory(): void {\n const newState = clearHistory();\n this.undoStack = newState.undoStack;\n this.redoStack = newState.redoStack;\n }\n\n /**\n * Get a copy of the current undo stack.\n */\n getUndoStack(): EditAction[] {\n return [...this.undoStack];\n }\n\n /**\n * Get a copy of the current redo stack.\n */\n getRedoStack(): EditAction[] {\n return [...this.redoStack];\n }\n // #endregion\n}\n"],"names":["pushAction","state","action","maxSize","undoStack","undo","redo","redoStack","canUndo","canRedo","clearHistory","createEditAction","rowIndex","field","oldValue","newValue","UndoRedoPlugin","BaseGridPlugin","grid","detail","event","isUndo","isRedo","result","rows","newState"],"mappings":"oUAkBO,SAASA,EAAWC,EAAsBC,EAAoBC,EAAgC,CACnG,MAAMC,EAAY,CAAC,GAAGH,EAAM,UAAWC,CAAM,EAG7C,KAAOE,EAAU,OAASD,GACxBC,EAAU,MAAA,EAGZ,MAAO,CACL,UAAAA,EACA,UAAW,CAAA,CAAC,CAEhB,CASO,SAASC,EAAKJ,EAGnB,CACA,GAAIA,EAAM,UAAU,SAAW,EAC7B,MAAO,CAAE,SAAUA,EAAO,OAAQ,IAAA,EAGpC,MAAMG,EAAY,CAAC,GAAGH,EAA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AS,CAC3B,CAKA,cAA6B,CAC3B,MAAO,CAAC,GAAG,KAAK,SAAS,CAC3B,CAEF"}
1
+ {"version":3,"file":"undo-redo.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/undo-redo/history.ts","../../../../../libs/grid/src/lib/plugins/undo-redo/UndoRedoPlugin.ts"],"sourcesContent":["/**\n * Undo/Redo History Management\n *\n * Pure functions for managing the undo/redo stacks.\n * These functions are stateless and return new state objects.\n */\n\nimport type { EditAction, UndoRedoState } from './types';\n\n/**\n * Push a new action onto the undo stack.\n * Clears the redo stack since new actions invalidate redo history.\n *\n * @param state - Current undo/redo state\n * @param action - The action to add\n * @param maxSize - Maximum history size\n * @returns New state with the action added\n */\nexport function pushAction(state: UndoRedoState, action: EditAction, maxSize: number): UndoRedoState {\n const undoStack = [...state.undoStack, action];\n\n // Trim oldest actions if over max size\n while (undoStack.length > maxSize) {\n undoStack.shift();\n }\n\n return {\n undoStack,\n redoStack: [], // Clear redo on new action\n };\n}\n\n/**\n * Undo the most recent action.\n * Moves the action from undo stack to redo stack.\n *\n * @param state - Current undo/redo state\n * @returns New state and the action that was undone (or null if nothing to undo)\n */\nexport function undo(state: UndoRedoState): {\n newState: UndoRedoState;\n action: EditAction | null;\n} {\n if (state.undoStack.length === 0) {\n return { newState: state, action: null };\n }\n\n const undoStack = [...state.undoStack];\n const action = undoStack.pop();\n\n // This should never happen due to the length check above,\n // but TypeScript needs the explicit check\n if (!action) {\n return { newState: state, action: null };\n }\n\n return {\n newState: {\n undoStack,\n redoStack: [...state.redoStack, action],\n },\n action,\n };\n}\n\n/**\n * Redo the most recently undone action.\n * Moves the action from redo stack back to undo stack.\n *\n * @param state - Current undo/redo state\n * @returns New state and the action that was redone (or null if nothing to redo)\n */\nexport function redo(state: UndoRedoState): {\n newState: UndoRedoState;\n action: EditAction | null;\n} {\n if (state.redoStack.length === 0) {\n return { newState: state, action: null };\n }\n\n const redoStack = [...state.redoStack];\n const action = redoStack.pop();\n\n // This should never happen due to the length check above,\n // but TypeScript needs the explicit check\n if (!action) {\n return { newState: state, action: null };\n }\n\n return {\n newState: {\n undoStack: [...state.undoStack, action],\n redoStack,\n },\n action,\n };\n}\n\n/**\n * Check if there are any actions that can be undone.\n *\n * @param state - Current undo/redo state\n * @returns True if undo is available\n */\nexport function canUndo(state: UndoRedoState): boolean {\n return state.undoStack.length > 0;\n}\n\n/**\n * Check if there are any actions that can be redone.\n *\n * @param state - Current undo/redo state\n * @returns True if redo is available\n */\nexport function canRedo(state: UndoRedoState): boolean {\n return state.redoStack.length > 0;\n}\n\n/**\n * Clear all history, returning an empty state.\n *\n * @returns Fresh empty state\n */\nexport function clearHistory(): UndoRedoState {\n return { undoStack: [], redoStack: [] };\n}\n\n/**\n * Create a new edit action with the current timestamp.\n *\n * @param rowIndex - The row index where the edit occurred\n * @param field - The field (column key) that was edited\n * @param oldValue - The value before the edit\n * @param newValue - The value after the edit\n * @returns A new EditAction object\n */\nexport function createEditAction(rowIndex: number, field: string, oldValue: unknown, newValue: unknown): EditAction {\n return {\n type: 'cell-edit',\n rowIndex,\n field,\n oldValue,\n newValue,\n timestamp: Date.now(),\n };\n}\n","/**\n * Undo/Redo Plugin (Class-based)\n *\n * Provides undo/redo functionality for cell edits in tbw-grid.\n * Supports Ctrl+Z/Cmd+Z for undo and Ctrl+Y/Cmd+Y (or Ctrl+Shift+Z) for redo.\n */\n\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport { canRedo, canUndo, clearHistory, createEditAction, pushAction, redo, undo } from './history';\nimport type { EditAction, UndoRedoConfig, UndoRedoDetail } from './types';\n\n/**\n * Undo/Redo Plugin for tbw-grid\n *\n * Tracks all cell edits and lets users revert or replay changes with familiar keyboard\n * shortcuts (Ctrl+Z / Ctrl+Y). Maintains an in-memory history stack with configurable\n * depth—perfect for data entry workflows where mistakes happen.\n *\n * > **Required Dependency:** This plugin requires EditingPlugin to be loaded first.\n * > UndoRedo tracks the edit history that EditingPlugin creates.\n *\n * ## Installation\n *\n * ```ts\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * import { UndoRedoPlugin } from '@toolbox-web/grid/plugins/undo-redo';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `maxHistorySize` | `number` | `100` | Maximum actions in history stack |\n *\n * ## Keyboard Shortcuts\n *\n * | Shortcut | Action |\n * |----------|--------|\n * | `Ctrl+Z` / `Cmd+Z` | Undo last edit |\n * | `Ctrl+Y` / `Cmd+Shift+Z` | Redo last undone edit |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `undo` | `() => void` | Undo the last edit |\n * | `redo` | `() => void` | Redo the last undone edit |\n * | `canUndo` | `() => boolean` | Check if undo is available |\n * | `canRedo` | `() => boolean` | Check if redo is available |\n * | `clearHistory` | `() => void` | Clear the entire history stack |\n *\n * @example Basic Usage with EditingPlugin\n * ```ts\n * import '@toolbox-web/grid';\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * import { UndoRedoPlugin } from '@toolbox-web/grid/plugins/undo-redo';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name', editable: true },\n * { field: 'price', header: 'Price', type: 'number', editable: true },\n * ],\n * plugins: [\n * new EditingPlugin({ editOn: 'dblclick' }), // Required - must be first\n * new UndoRedoPlugin({ maxHistorySize: 50 }),\n * ],\n * };\n * ```\n *\n * @see {@link UndoRedoConfig} for configuration options\n * @see {@link EditingPlugin} for the required dependency\n *\n * @internal Extends BaseGridPlugin\n */\nexport class UndoRedoPlugin extends BaseGridPlugin<UndoRedoConfig> {\n /**\n * Plugin dependencies - UndoRedoPlugin requires EditingPlugin to track edits.\n *\n * The EditingPlugin must be loaded BEFORE this plugin in the plugins array.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'editing', required: true, reason: 'UndoRedoPlugin tracks cell edit history' },\n ];\n\n /** @internal */\n readonly name = 'undoRedo';\n\n /** @internal */\n protected override get defaultConfig(): Partial<UndoRedoConfig> {\n return {\n maxHistorySize: 100,\n };\n }\n\n // State as class properties\n private undoStack: EditAction[] = [];\n private redoStack: EditAction[] = [];\n\n /**\n * Subscribe to cell-edit-committed events from EditingPlugin.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n // Auto-record edits via Event Bus\n this.on(\n 'cell-edit-committed',\n (detail: { rowIndex: number; field: string; oldValue: unknown; newValue: unknown }) => {\n this.recordEdit(detail.rowIndex, detail.field, detail.oldValue, detail.newValue);\n },\n );\n }\n\n /**\n * Clean up state when plugin is detached.\n * @internal\n */\n override detach(): void {\n this.undoStack = [];\n this.redoStack = [];\n }\n\n /**\n * Handle keyboard shortcuts for undo/redo.\n * - Ctrl+Z / Cmd+Z: Undo\n * - Ctrl+Y / Cmd+Y / Ctrl+Shift+Z / Cmd+Shift+Z: Redo\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean {\n const isUndo = (event.ctrlKey || event.metaKey) && event.key === 'z' && !event.shiftKey;\n const isRedo = (event.ctrlKey || event.metaKey) && (event.key === 'y' || (event.key === 'z' && event.shiftKey));\n\n if (isUndo) {\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n // Apply undo - restore old value\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.oldValue;\n }\n\n // Update state from result\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n\n this.emit<UndoRedoDetail>('undo', {\n action: result.action,\n type: 'undo',\n });\n\n this.requestRender();\n }\n return true;\n }\n\n if (isRedo) {\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n // Apply redo - restore new value\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.newValue;\n }\n\n // Update state from result\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n\n this.emit<UndoRedoDetail>('redo', {\n action: result.action,\n type: 'redo',\n });\n\n this.requestRender();\n }\n return true;\n }\n\n return false;\n }\n\n // #region Public API Methods\n\n /**\n * Record a cell edit for undo/redo tracking.\n * Call this when a cell value changes.\n *\n * @param rowIndex - The row index where the edit occurred\n * @param field - The field (column key) that was edited\n * @param oldValue - The value before the edit\n * @param newValue - The value after the edit\n */\n recordEdit(rowIndex: number, field: string, oldValue: unknown, newValue: unknown): void {\n const action = createEditAction(rowIndex, field, oldValue, newValue);\n const newState = pushAction(\n { undoStack: this.undoStack, redoStack: this.redoStack },\n action,\n this.config.maxHistorySize ?? 100,\n );\n this.undoStack = newState.undoStack;\n this.redoStack = newState.redoStack;\n }\n\n /**\n * Programmatically undo the last action.\n *\n * @returns The undone action, or null if nothing to undo\n */\n undo(): EditAction | null {\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.oldValue;\n }\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.requestRender();\n }\n return result.action;\n }\n\n /**\n * Programmatically redo the last undone action.\n *\n * @returns The redone action, or null if nothing to redo\n */\n redo(): EditAction | null {\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n const rows = this.rows as Record<string, unknown>[];\n if (rows[result.action.rowIndex]) {\n rows[result.action.rowIndex][result.action.field] = result.action.newValue;\n }\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.requestRender();\n }\n return result.action;\n }\n\n /**\n * Check if there are any actions that can be undone.\n */\n canUndo(): boolean {\n return canUndo({ undoStack: this.undoStack, redoStack: this.redoStack });\n }\n\n /**\n * Check if there are any actions that can be redone.\n */\n canRedo(): boolean {\n return canRedo({ undoStack: this.undoStack, redoStack: this.redoStack });\n }\n\n /**\n * Clear all undo/redo history.\n */\n clearHistory(): void {\n const newState = clearHistory();\n this.undoStack = newState.undoStack;\n this.redoStack = newState.redoStack;\n }\n\n /**\n * Get a copy of the current undo stack.\n */\n getUndoStack(): EditAction[] {\n return [...this.undoStack];\n }\n\n /**\n * Get a copy of the current redo stack.\n */\n getRedoStack(): EditAction[] {\n return [...this.redoStack];\n }\n // #endregion\n}\n"],"names":["undo","state","undoStack","length","newState","action","pop","redoStack","redo","UndoRedoPlugin","BaseGridPlugin","static","name","required","reason","defaultConfig","maxHistorySize","attach","grid","super","this","on","detail","recordEdit","rowIndex","field","oldValue","newValue","detach","onKeyDown","event","isUndo","ctrlKey","metaKey","key","shiftKey","isRedo","result","rows","emit","type","requestRender","timestamp","Date","now","createEditAction","maxSize","shift","pushAction","config","canUndo","canRedo","clearHistory","getUndoStack","getRedoStack"],"mappings":"kVAuCO,SAASA,EAAKC,GAInB,GAA+B,IAA3BA,EAAMC,UAAUC,OAClB,MAAO,CAAEC,SAAUH,EAAOI,OAAQ,MAGpC,MAAMH,EAAY,IAAID,EAAMC,WACtBG,EAASH,EAAUI,MAIzB,OAAKD,EAIE,CACLD,SAAU,CACRF,YACAK,UAAW,IAAIN,EAAMM,UAAWF,IAElCA,UARO,CAAED,SAAUH,EAAOI,OAAQ,KAUtC,CASO,SAASG,EAAKP,GAInB,GAA+B,IAA3BA,EAAMM,UAAUJ,OAClB,MAAO,CAAEC,SAAUH,EAAOI,OAAQ,MAGpC,MAAME,EAAY,IAAIN,EAAMM,WACtBF,EAASE,EAAUD,MAIzB,OAAKD,EAIE,CACLD,SAAU,CACRF,UAAW,IAAID,EAAMC,UAAWG,GAChCE,aAEFF,UARO,CAAED,SAAUH,EAAOI,OAAQ,KAUtC,CCrBO,MAAMI,UAAuBC,EAAAA,eAOlCC,oBAA4D,CAC1D,CAAEC,KAAM,UAAWC,UAAU,EAAMC,OAAQ,4CAIpCF,KAAO,WAGhB,iBAAuBG,GAC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ACdA,EAAKD,EAAOhC,OAAOmB,YACrBc,EAAKD,EAAOhC,OAAOmB,UAAUa,EAAOhC,OAAOoB,OAASY,EAAOhC,OAAOsB,UAEpEP,KAAKlB,UAAYmC,EAAOjC,SAASF,UACjCkB,KAAKb,UAAY8B,EAAOjC,SAASG,UACjCa,KAAKqB,eACP,CACA,OAAOJ,EAAOhC,MAChB,CAKA,OAAA6C,GACE,MAAe,CAAEhD,UAAWkB,KAAKlB,UAAWK,UAAWa,KAAKb,WD9IjDL,UAAUC,OAAS,CC+IhC,CAKA,OAAAgD,GACE,MAAe,CAAEjD,UAAWkB,KAAKlB,UAAWK,UAAWa,KAAKb,WD3IjDA,UAAUJ,OAAS,CC4IhC,CAKA,YAAAiD,GACE,MAAMhD,EDzID,CAAEF,UAAW,GAAIK,UAAW,IC0IjCa,KAAKlB,UAAYE,EAASF,UAC1BkB,KAAKb,UAAYH,EAASG,SAC5B,CAKA,YAAA8C,GACE,MAAO,IAAIjC,KAAKlB,UAClB,CAKA,YAAAoD,GACE,MAAO,IAAIlC,KAAKb,UAClB"}
@@ -1,2 +1,2 @@
1
- (function(u,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/plugin/base-plugin"],h):(u=typeof globalThis<"u"?globalThis:u||self,h(u.TbwGridPlugin_visibility={},u.TbwGrid))})(this,(function(u,h){"use strict";const w='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';function v(y){const e=y.meta??{};return e.lockPosition!==!0&&e.suppressMovable!==!0}class b extends h.BaseGridPlugin{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles=w;get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(t=>{t.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if(e.type==="getContextMenuItems"){const t=e.context;if(!t.isHeader)return;const l=t.column;return!l?.field||l.meta?.lockVisibility?void 0:[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(l.field)}]}}getToolPanel(){return{id:b.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(b.PANEL_ID)||this.grid.toggleToolPanelSection(b.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(b.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(b.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const l=document.createElement("div");l.className="tbw-visibility-list",t.appendChild(l);const n=document.createElement("button");return n.className="tbw-visibility-show-all",n.textContent="Show All",n.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(l)}),t.appendChild(n),this.columnListElement=l,this.rebuildToggles(l),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!!(e&&typeof e.moveColumn=="function")}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const l=this.grid.getAllColumns().filter(o=>!o.utility),i=this.grid.query("getColumnGrouping")?.flat().filter(o=>o&&o.fields.length>0)??[];if(i.length===0){this.renderFlatColumnList(l,t,e);return}const s=new Map;for(const o of i)for(const a of o.fields)s.set(a,o);const r=new Set;for(const o of l){const a=s.get(o.field);if(a){if(!r.has(a.id)){r.add(a.id);const g=new Set(a.fields),c=l.filter(d=>g.has(d.field));c.length>0&&this.renderGroupSection(a,c,t,e)}}else{const g=l.indexOf(o);e.appendChild(this.createColumnRow(o,g,t,e))}}}renderGroupSection(e,t,l,n){const i=document.createElement("div");i.className="tbw-visibility-group-header",i.setAttribute("data-group-id",e.id),l&&(i.draggable=!0,i.classList.add("reorderable"),this.setupGroupDragListeners(i,e,n));const s=document.createElement("label");s.className="tbw-visibility-label";const r=document.createElement("input");r.type="checkbox";const o=t.filter(d=>d.visible).length,a=t.every(d=>d.lockVisible);o===t.length?(r.checked=!0,r.indeterminate=!1):o===0?(r.checked=!1,r.indeterminate=!1):(r.checked=!1,r.indeterminate=!0),r.disabled=a,r.addEventListener("change",()=>{const d=r.checked;for(const p of t)p.lockVisible||this.grid.setColumnVisible(p.field,d);setTimeout(()=>this.rebuildToggles(n),0)});const g=document.createElement("span");if(g.textContent=e.label,s.appendChild(r),s.appendChild(g),i.appendChild(s),l){const d=document.createElement("span");d.className="tbw-visibility-handle",this.setIcon(d,this.resolveIcon("dragHandle")),d.title="Drag to reorder group",i.insertBefore(d,s)}n.appendChild(i);const c=this.grid.getAllColumns().filter(d=>!d.utility);for(const d of t){const p=c.findIndex(f=>f.field===d.field),m=this.createColumnRow(d,p,l,n);m.classList.add("tbw-visibility-row--grouped"),n.appendChild(m)}}renderFlatColumnList(e,t,l){const n=this.grid.getAllColumns().filter(i=>!i.utility);for(const i of e){const s=n.findIndex(r=>r.field===i.field);l.appendChild(this.createColumnRow(i,s,t,l))}}createColumnRow(e,t,l,n){const i=e.header||e.field,s=document.createElement("div");s.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",s.setAttribute("data-field",e.field),s.setAttribute("data-index",String(t)),l&&v(e)&&(s.draggable=!0,s.classList.add("reorderable"),this.setupDragListeners(s,e.field,t,n));const r=document.createElement("label");r.className="tbw-visibility-label";const o=document.createElement("input");o.type="checkbox",o.checked=e.visible,o.disabled=e.lockVisible??!1,o.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(n),0)});const a=document.createElement("span");if(a.textContent=i,r.appendChild(o),r.appendChild(a),l&&v(e)){const g=document.createElement("span");g.className="tbw-visibility-handle",this.setIcon(g,this.resolveIcon("dragHandle")),g.title="Drag to reorder",s.appendChild(g)}return s.appendChild(r),s}setupGroupDragListeners(e,t,l){e.addEventListener("dragstart",n=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...t.fields],this.draggedField=null,this.draggedIndex=null,n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),l.querySelectorAll(".tbw-visibility-row--grouped").forEach(i=>{const s=i.getAttribute("data-field");s&&this.draggedGroupFields.includes(s)&&i.classList.add("dragging")})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(l)}),e.addEventListener("dragover",n=>{if(n.preventDefault(),!this.isDragging||this.draggedGroupId===t.id||!this.draggedGroupId)return;const i=e.getBoundingClientRect(),s=i.top+i.height/2,r=n.clientY<s;this.clearDragClasses(l),e.classList.add("drop-target"),e.classList.toggle("drop-before",r),e.classList.toggle("drop-after",!r)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",n=>{if(n.preventDefault(),!this.isDragging||!this.draggedGroupId||this.draggedGroupId===t.id)return;const i=e.getBoundingClientRect(),s=n.clientY<i.top+i.height/2;this.executeGroupDrop(this.draggedGroupFields,t.fields,s,l)})}executeGroupDrop(e,t,l,n){const s=this.grid.getAllColumns().map(d=>d.field),r=s.filter(d=>!e.includes(d)),o=l?t[0]:t[t.length-1],a=r.indexOf(o);if(a===-1)return;const g=l?a:a+1,c=s.filter(d=>e.includes(d));r.splice(g,0,...c),this.grid.setColumnOrder(r),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,l,n){e.addEventListener("dragstart",i=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=l,this.draggedGroupId=null,this.draggedGroupFields=[],i.dataTransfer&&(i.dataTransfer.effectAllowed="move",i.dataTransfer.setData("text/plain",t)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(n)}),e.addEventListener("dragover",i=>{if(i.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===t)return;const s=e.getBoundingClientRect(),r=s.top+s.height/2;this.dropIndex=i.clientY<r?l:l+1,this.clearDragClasses(n),this.draggedGroupId?(n.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),n.querySelectorAll(".tbw-visibility-row--grouped").forEach(o=>{const a=o.getAttribute("data-field");a&&this.draggedGroupFields.includes(a)&&o.classList.add("dragging")})):this.draggedField&&n.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",i.clientY<r),e.classList.toggle("drop-after",i.clientY>=r)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",i=>{if(i.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const g=e.getBoundingClientRect(),c=i.clientY<g.top+g.height/2;this.executeGroupDrop(this.draggedGroupFields,[t],c,n);return}const s=this.draggedField,r=this.draggedIndex,o=this.dropIndex;if(s===null||r===null||o===null)return;const a=o>r?o-1:o;if(a!==r){const g=this.grid.getAllColumns(),d=g.filter(f=>!f.utility)[a]?.field,p=d?g.findIndex(f=>f.field===d):g.length,m={field:s,fromIndex:r,toIndex:p};this.emit("column-reorder-request",m)}})}}u.VisibilityPlugin=b,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],i):i((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_visibility={},e.TbwGrid)}(this,function(e,i){"use strict";function t(e){const i=e.meta??{};return!0!==i.lockPosition&&!0!==i.suppressMovable}class r extends i.BaseGridPlugin{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if("getContextMenuItems"===e.type){const i=e.context;if(!i.isHeader)return;const t=i.column;if(!t?.field)return;if(t.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(t.field)}]}}getToolPanel(){return{id:r.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(),this.grid.expandedToolPanelSections.includes(r.PANEL_ID)||this.grid.toggleToolPanelSection(r.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(r.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,i){this.grid.setColumnVisible(e,i)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(r.PANEL_ID)}renderPanelContent(e){const i=document.createElement("div");i.className="tbw-visibility-content";const t=document.createElement("div");t.className="tbw-visibility-list",i.appendChild(t);const r=document.createElement("button");return r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(t)}),i.appendChild(r),this.columnListElement=t,this.rebuildToggles(t),e.appendChild(i),()=>{this.columnListElement=null,i.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}rebuildToggles(e){const i=this.hasReorderPlugin();e.innerHTML="";const t=this.grid.getAllColumns().filter(e=>!e.utility),r=this.grid.query("getColumnGrouping"),l=r?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===l.length)return void this.renderFlatColumnList(t,i,e);const s=new Map;for(const o of l)for(const e of o.fields)s.set(e,o);const n=new Set;for(const o of t){const r=s.get(o.field);if(r){if(!n.has(r.id)){n.add(r.id);const l=new Set(r.fields),s=t.filter(e=>l.has(e.field));s.length>0&&this.renderGroupSection(r,s,i,e)}}else{const r=t.indexOf(o);e.appendChild(this.createColumnRow(o,r,i,e))}}}renderGroupSection(e,i,t,r){const l=document.createElement("div");l.className="tbw-visibility-group-header",l.setAttribute("data-group-id",e.id),t&&(l.draggable=!0,l.classList.add("reorderable"),this.setupGroupDragListeners(l,e,r));const s=document.createElement("label");s.className="tbw-visibility-label";const n=document.createElement("input");n.type="checkbox";const o=i.filter(e=>e.visible).length,d=i.every(e=>e.lockVisible);o===i.length?(n.checked=!0,n.indeterminate=!1):0===o?(n.checked=!1,n.indeterminate=!1):(n.checked=!1,n.indeterminate=!0),n.disabled=d,n.addEventListener("change",()=>{const e=n.checked;for(const t of i)t.lockVisible||this.grid.setColumnVisible(t.field,e);setTimeout(()=>this.rebuildToggles(r),0)});const a=document.createElement("span");if(a.textContent=e.label,s.appendChild(n),s.appendChild(a),l.appendChild(s),t){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder group",l.insertBefore(e,s)}r.appendChild(l);const g=this.grid.getAllColumns().filter(e=>!e.utility);for(const c of i){const e=g.findIndex(e=>e.field===c.field),i=this.createColumnRow(c,e,t,r);i.classList.add("tbw-visibility-row--grouped"),r.appendChild(i)}}renderFlatColumnList(e,i,t){const r=this.grid.getAllColumns().filter(e=>!e.utility);for(const l of e){const e=r.findIndex(e=>e.field===l.field);t.appendChild(this.createColumnRow(l,e,i,t))}}createColumnRow(e,i,r,l){const s=e.header||e.field,n=document.createElement("div");n.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",n.setAttribute("data-field",e.field),n.setAttribute("data-index",String(i)),r&&t(e)&&(n.draggable=!0,n.classList.add("reorderable"),this.setupDragListeners(n,e.field,i,l));const o=document.createElement("label");o.className="tbw-visibility-label";const d=document.createElement("input");d.type="checkbox",d.checked=e.visible,d.disabled=e.lockVisible??!1,d.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(l),0)});const a=document.createElement("span");if(a.textContent=s,o.appendChild(d),o.appendChild(a),r&&t(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder",n.appendChild(e)}return n.appendChild(o),n}setupGroupDragListeners(e,i,t){e.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedGroupId=i.id,this.draggedGroupFields=[...i.fields],this.draggedField=null,this.draggedIndex=null,r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",`group:${i.id}`)),e.classList.add("dragging"),t.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const i=e.getAttribute("data-field");i&&this.draggedGroupFields.includes(i)&&e.classList.add("dragging")})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(t)}),e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging)return;if(this.draggedGroupId===i.id)return;if(!this.draggedGroupId)return;const l=e.getBoundingClientRect(),s=l.top+l.height/2,n=r.clientY<s;this.clearDragClasses(t),e.classList.add("drop-target"),e.classList.toggle("drop-before",n),e.classList.toggle("drop-after",!n)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",r=>{if(r.preventDefault(),!this.isDragging||!this.draggedGroupId||this.draggedGroupId===i.id)return;const l=e.getBoundingClientRect(),s=r.clientY<l.top+l.height/2;this.executeGroupDrop(this.draggedGroupFields,i.fields,s,t)})}executeGroupDrop(e,i,t,r){const l=this.grid.getAllColumns().map(e=>e.field),s=l.filter(i=>!e.includes(i)),n=t?i[0]:i[i.length-1],o=s.indexOf(n);if(-1===o)return;const d=t?o:o+1,a=l.filter(i=>e.includes(i));s.splice(d,0,...a),this.grid.setColumnOrder(s),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,i,t,r){e.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=i,this.draggedIndex=t,this.draggedGroupId=null,this.draggedGroupFields=[],r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",i)),e.classList.add("dragging")}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(r)}),e.addEventListener("dragover",l=>{if(l.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===i)return;const s=e.getBoundingClientRect(),n=s.top+s.height/2;this.dropIndex=l.clientY<n?t:t+1,this.clearDragClasses(r),this.draggedGroupId?(r.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add("dragging"),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const i=e.getAttribute("data-field");i&&this.draggedGroupFields.includes(i)&&e.classList.add("dragging")})):this.draggedField&&r.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add("dragging"),e.classList.add("drop-target"),e.classList.toggle("drop-before",l.clientY<n),e.classList.toggle("drop-after",l.clientY>=n)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const l=e.getBoundingClientRect(),s=t.clientY<l.top+l.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[i],s,r)}const l=this.draggedField,s=this.draggedIndex,n=this.dropIndex;if(null===l||null===s||null===n)return;const o=n>s?n-1:n;if(o!==s){const e=this.grid.getAllColumns(),i=e.filter(e=>!e.utility),t=i[o]?.field,r={field:l,fromIndex:s,toIndex:t?e.findIndex(e=>e.field===t):e.length};this.emit("column-reorder-request",r)}})}}e.VisibilityPlugin=r,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=visibility.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"visibility.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/visibility/VisibilityPlugin.ts"],"sourcesContent":["/**\n * Column Visibility Plugin (Class-based)\n *\n * Provides a UI for column visibility control via the shell's tool panel system.\n * Column visibility is a core grid feature - this plugin provides:\n * - A tool panel for column visibility management (registered with the shell)\n * - Backward-compatible API methods that delegate to grid.setColumnVisible(), etc.\n *\n * The grid emits 'column-visibility' events when columns are shown/hidden,\n * allowing consumers to save user preferences.\n *\n * When a reorder plugin is present, column rows become draggable for reordering.\n * Drag-drop emits 'column-reorder-request' events that the ReorderPlugin can listen for.\n */\n\nimport {\n BaseGridPlugin,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ToolPanelDefinition } from '../../core/types';\nimport type { ContextMenuParams, HeaderContextMenuItem } from '../context-menu/types';\nimport type { ColumnGroupInfo, VisibilityConfig } from './types';\nimport styles from './visibility.css?inline';\n\n/**\n * Detail for column-reorder-request events emitted when users drag-drop in the visibility panel.\n */\nexport interface ColumnReorderRequestDetail {\n /** The field name of the column to move */\n field: string;\n /** The source index (before move) */\n fromIndex: number;\n /** The target index (after move) */\n toIndex: number;\n}\n\n/**\n * Check if a column can be moved (respects lockPosition/suppressMovable).\n * Inlined to avoid importing from reorder plugin.\n */\nfunction canMoveColumn(column: ColumnConfig): boolean {\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Column Visibility Plugin for tbw-grid\n *\n * Gives users control over which columns are displayed. Hide less important columns\n * by default, let users toggle them via a column chooser UI, or programmatically\n * show/hide columns based on user preferences or screen size.\n *\n * > **Optional Enhancement:** When ReorderPlugin is also loaded, columns in the\n * > visibility panel become draggable for reordering.\n *\n * ## Installation\n *\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `allowHideAll` | `boolean` | `false` | Allow hiding all columns (no minimum) |\n *\n * ## Column Configuration\n *\n * | Property | Type | Default | Description |\n * |----------|------|---------|-------------|\n * | `visible` | `boolean` | `true` | Initial visibility state |\n * | `meta.lockVisibility` | `boolean` | `false` | Prevent user from toggling |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `hideColumn` | `(field: string) => void` | Hide a column |\n * | `showColumn` | `(field: string) => void` | Show a column |\n * | `toggleColumn` | `(field: string) => void` | Toggle visibility |\n * | `showAllColumns` | `() => void` | Show all columns |\n * | `getHiddenColumns` | `() => string[]` | Get list of hidden column fields |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-visibility-hover` | `var(--tbw-color-row-hover)` | Row hover background |\n * | `--tbw-panel-padding` | `0.75em` | Panel content padding |\n * | `--tbw-panel-gap` | `0.5em` | Gap between items |\n *\n * @example Columns Hidden by Default\n * ```ts\n * import '@toolbox-web/grid';\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\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: 'phone', header: 'Phone', visible: false }, // Hidden by default\n * { field: 'address', header: 'Address', visible: false },\n * ],\n * plugins: [new VisibilityPlugin()],\n * };\n *\n * // Toggle programmatically\n * const plugin = grid.getPlugin(VisibilityPlugin);\n * plugin.showColumn('phone');\n * ```\n *\n * @example With Drag-to-Reorder\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ReorderPlugin(), // Enables drag-drop in visibility panel\n * new VisibilityPlugin(),\n * ],\n * };\n * ```\n *\n * @see {@link VisibilityConfig} for configuration options\n * @see {@link ReorderPlugin} for drag-to-reorder integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class VisibilityPlugin extends BaseGridPlugin<VisibilityConfig> {\n /**\n * Plugin dependencies - VisibilityPlugin optionally uses ReorderPlugin for drag-drop reordering.\n *\n * When ReorderPlugin is present, columns in the visibility panel become draggable.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'reorder', required: false, reason: 'Enables drag-to-reorder columns in visibility panel' },\n ];\n\n /**\n * Plugin manifest - declares handled queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'getContextMenuItems',\n description: 'Contributes \"Hide column\" item to the header context menu',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'visibility';\n\n /** Tool panel ID for shell integration */\n static readonly PANEL_ID = 'columns';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<VisibilityConfig> {\n return {\n allowHideAll: false,\n };\n }\n\n // #region Internal State\n private columnListElement: HTMLElement | null = null;\n\n // Drag state for reorder integration\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n /** When dragging a group, holds the group ID; null for individual column drags. */\n private draggedGroupId: string | null = null;\n /** Fields belonging to the group currently being dragged. */\n private draggedGroupFields: string[] = [];\n\n /** Clear drag-related classes from all rows and group headers in a list. */\n private clearDragClasses(container: HTMLElement): void {\n container.querySelectorAll('.tbw-visibility-row, .tbw-visibility-group-header').forEach((r) => {\n r.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 column-move events (emitted by ReorderPlugin after any reorder,\n // including header drag-drop and visibility panel drag-drop) to keep the\n // panel list in sync with the grid's column order.\n (grid as unknown as HTMLElement).addEventListener(\n 'column-move',\n () => {\n if (this.columnListElement) {\n // column-move fires BEFORE setColumnOrder runs. Defer the rebuild\n // to allow the full reorder cycle (setColumnOrder + renderHeader +\n // refreshVirtualWindow) to complete before reading the new order.\n // Use RAF to run after the current synchronous work and any\n // animation frames queued by the animation system.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.columnListElement = null;\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n }\n // #endregion\n\n // #region Query Handlers\n\n /**\n * Handle inter-plugin queries.\n * Contributes a \"Hide column\" item to the header context menu.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getContextMenuItems') {\n const params = query.context as ContextMenuParams;\n if (!params.isHeader) return undefined;\n\n const column = params.column as ColumnConfig;\n if (!column?.field) return undefined;\n\n // Don't offer \"Hide\" for locked-visibility columns\n if (column.meta?.lockVisibility) return undefined;\n\n const items: HeaderContextMenuItem[] = [\n {\n id: 'visibility/hide-column',\n label: 'Hide Column',\n icon: '👁',\n order: 30,\n action: () => this.hideColumn(column.field),\n },\n ];\n\n return items;\n }\n return undefined;\n }\n // #endregion\n\n // #region Shell Integration\n\n /**\n * Register the column visibility tool panel with the shell.\n * @internal\n */\n override getToolPanel(): ToolPanelDefinition | undefined {\n return {\n id: VisibilityPlugin.PANEL_ID,\n title: 'Columns',\n icon: '☰',\n tooltip: 'Column visibility',\n order: 100, // High order so it appears last\n render: (container) => this.renderPanelContent(container),\n };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Show the visibility sidebar panel.\n * Opens the tool panel and ensures this section is expanded.\n */\n show(): void {\n this.grid.openToolPanel();\n // Ensure our section is expanded\n if (!this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID)) {\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n }\n\n /**\n * Hide the visibility sidebar panel.\n */\n hide(): void {\n this.grid.closeToolPanel();\n }\n\n /**\n * Toggle the visibility sidebar panel section.\n */\n toggle(): void {\n // If tool panel is closed, open it first\n if (!this.grid.isToolPanelOpen) {\n this.grid.openToolPanel();\n }\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n\n /**\n * Check if a specific column is visible.\n * Delegates to grid.isColumnVisible().\n * @param field - The field name to check\n * @returns True if the column is visible\n */\n isColumnVisible(field: string): boolean {\n return this.grid.isColumnVisible(field);\n }\n\n /**\n * Set visibility for a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column\n * @param visible - Whether the column should be visible\n */\n setColumnVisible(field: string, visible: boolean): void {\n this.grid.setColumnVisible(field, visible);\n }\n\n /**\n * Get list of all visible column fields.\n * @returns Array of visible field names\n */\n getVisibleColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Get list of all hidden column fields.\n * @returns Array of hidden field names\n */\n getHiddenColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => !c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Show all columns.\n * Delegates to grid.showAllColumns().\n */\n showAll(): void {\n this.grid.showAllColumns();\n }\n\n /**\n * Toggle visibility for a specific column.\n * Delegates to grid.toggleColumnVisibility().\n * @param field - The field name of the column\n */\n toggleColumn(field: string): void {\n this.grid.toggleColumnVisibility(field);\n }\n\n /**\n * Show a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to show\n */\n showColumn(field: string): void {\n this.setColumnVisible(field, true);\n }\n\n /**\n * Hide a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to hide\n */\n hideColumn(field: string): void {\n this.setColumnVisible(field, false);\n }\n\n /**\n * Get all columns with their visibility status.\n * Useful for building visibility UI.\n * @returns Array of column info with visibility status\n */\n getAllColumns(): Array<{\n field: string;\n header: string;\n visible: boolean;\n lockVisible?: boolean;\n utility?: boolean;\n }> {\n return this.grid.getAllColumns();\n }\n\n /**\n * Check if the sidebar panel is currently open.\n * @returns True if the panel section is expanded\n */\n isPanelVisible(): boolean {\n return this.grid.isToolPanelOpen && this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Render the panel content into the shell's tool panel container.\n * Returns a cleanup function.\n */\n private renderPanelContent(container: HTMLElement): (() => void) | void {\n // Create content wrapper\n const wrapper = document.createElement('div');\n wrapper.className = 'tbw-visibility-content';\n\n // Column list container\n const columnList = document.createElement('div');\n columnList.className = 'tbw-visibility-list';\n wrapper.appendChild(columnList);\n\n // Show all button\n const showAllBtn = document.createElement('button');\n showAllBtn.className = 'tbw-visibility-show-all';\n showAllBtn.textContent = 'Show All';\n showAllBtn.addEventListener('click', () => {\n this.grid.showAllColumns();\n this.rebuildToggles(columnList);\n });\n wrapper.appendChild(showAllBtn);\n\n // Store reference\n this.columnListElement = columnList;\n\n // Build initial toggles\n this.rebuildToggles(columnList);\n\n // Append to container\n container.appendChild(wrapper);\n\n // Return cleanup function\n return () => {\n this.columnListElement = null;\n wrapper.remove();\n };\n }\n\n /**\n * Check if a reorder plugin is present (by name to avoid static import).\n */\n private hasReorderPlugin(): boolean {\n const plugin = this.grid?.getPluginByName?.('reorder');\n // Duck-type check - just verify the plugin exists and has a moveColumn method\n return !!(plugin && typeof (plugin as { moveColumn?: unknown }).moveColumn === 'function');\n }\n\n /**\n * Build the column toggle checkboxes.\n * When GroupingColumnsPlugin is present, renders columns under collapsible group headers.\n * When a reorder plugin is present, adds drag handles for reordering.\n */\n private rebuildToggles(columnList: HTMLElement): void {\n const reorderEnabled = this.hasReorderPlugin();\n\n columnList.innerHTML = '';\n\n // getAllColumns() returns columns in their effective display order\n // Filter out utility columns (e.g., expander column) as they're internal\n const allColumns = this.grid.getAllColumns().filter((c) => !c.utility);\n\n // Query for column grouping info from GroupingColumnsPlugin (or any responder)\n const groupResults = this.grid.query<ColumnGroupInfo[]>('getColumnGrouping');\n const groups: ColumnGroupInfo[] = groupResults?.flat().filter((g) => g && g.fields.length > 0) ?? [];\n\n if (groups.length === 0) {\n // No grouping — render flat list (original behavior)\n this.renderFlatColumnList(allColumns, reorderEnabled, columnList);\n return;\n }\n\n // Build field → group lookup\n const fieldToGroup = new Map<string, ColumnGroupInfo>();\n for (const group of groups) {\n for (const field of group.fields) fieldToGroup.set(field, group);\n }\n\n // Walk columns in display order, interleaving groups and ungrouped columns.\n // When we encounter the first column of a group, render the entire group section.\n const renderedGroups = new Set<string>();\n\n for (const col of allColumns) {\n const group = fieldToGroup.get(col.field);\n\n if (group) {\n // Column belongs to a group — render entire group section at first encounter\n if (!renderedGroups.has(group.id)) {\n renderedGroups.add(group.id);\n // Filter allColumns (which is in display order) to group members.\n // This preserves the current column order after reordering,\n // rather than using group.fields which may be in static/original order.\n const groupFieldSet = new Set(group.fields);\n const groupCols = allColumns.filter((c) => groupFieldSet.has(c.field));\n if (groupCols.length > 0) {\n this.renderGroupSection(group, groupCols, reorderEnabled, columnList);\n }\n }\n // Subsequent columns of the same group are already rendered — skip\n } else {\n // Ungrouped column — render as individual row at its natural position\n const fullIndex = allColumns.indexOf(col);\n columnList.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, columnList));\n }\n }\n }\n\n /**\n * Render a group section with header checkbox and indented column rows.\n */\n private renderGroupSection(\n group: ColumnGroupInfo,\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n // Group header row\n const header = document.createElement('div');\n header.className = 'tbw-visibility-group-header';\n header.setAttribute('data-group-id', group.id);\n\n // Make group header draggable when reorder is enabled\n if (reorderEnabled) {\n header.draggable = true;\n header.classList.add('reorderable');\n this.setupGroupDragListeners(header, group, container);\n }\n\n const headerLabel = document.createElement('label');\n headerLabel.className = 'tbw-visibility-label';\n\n const groupCheckbox = document.createElement('input');\n groupCheckbox.type = 'checkbox';\n\n // Calculate tri-state: all visible, all hidden, or mixed\n const visibleCount = columns.filter((c) => c.visible).length;\n const allLocked = columns.every((c) => c.lockVisible);\n if (visibleCount === columns.length) {\n groupCheckbox.checked = true;\n groupCheckbox.indeterminate = false;\n } else if (visibleCount === 0) {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = false;\n } else {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = true;\n }\n groupCheckbox.disabled = allLocked;\n\n // Toggle all columns in group\n groupCheckbox.addEventListener('change', () => {\n const newVisible = groupCheckbox.checked;\n for (const col of columns) {\n if (col.lockVisible) continue;\n this.grid.setColumnVisible(col.field, newVisible);\n }\n setTimeout(() => this.rebuildToggles(container), 0);\n });\n\n const headerText = document.createElement('span');\n headerText.textContent = group.label;\n\n headerLabel.appendChild(groupCheckbox);\n headerLabel.appendChild(headerText);\n header.appendChild(headerLabel);\n\n // Add drag handle icon for group if reorderable\n if (reorderEnabled) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder group';\n // Insert handle before the label\n header.insertBefore(handle, headerLabel);\n }\n\n container.appendChild(header);\n\n // Render indented column rows\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n const row = this.createColumnRow(col, fullIndex, reorderEnabled, container);\n row.classList.add('tbw-visibility-row--grouped');\n container.appendChild(row);\n }\n }\n\n /**\n * Render a flat (ungrouped) list of column rows.\n */\n private renderFlatColumnList(\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n container.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, container));\n }\n }\n\n /**\n * Create a single column visibility row element.\n */\n private createColumnRow(\n col: ReturnType<typeof this.grid.getAllColumns>[number],\n index: number,\n reorderEnabled: boolean,\n columnList: HTMLElement,\n ): HTMLElement {\n const label = col.header || col.field;\n\n const row = document.createElement('div');\n row.className = col.lockVisible ? 'tbw-visibility-row locked' : 'tbw-visibility-row';\n row.setAttribute('data-field', col.field);\n row.setAttribute('data-index', String(index));\n\n // Add drag handle if reorder is enabled\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n row.draggable = true;\n row.classList.add('reorderable');\n this.setupDragListeners(row, col.field, index, columnList);\n }\n\n const labelWrapper = document.createElement('label');\n labelWrapper.className = 'tbw-visibility-label';\n\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.checked = col.visible;\n checkbox.disabled = col.lockVisible ?? false;\n checkbox.addEventListener('change', () => {\n this.grid.toggleColumnVisibility(col.field);\n // Refresh after toggle (grid may re-render)\n setTimeout(() => this.rebuildToggles(columnList), 0);\n });\n\n const text = document.createElement('span');\n text.textContent = label;\n\n labelWrapper.appendChild(checkbox);\n labelWrapper.appendChild(text);\n\n // Add drag handle icon if reorderable\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder';\n row.appendChild(handle);\n }\n\n row.appendChild(labelWrapper);\n return row;\n }\n\n /**\n * Set up drag-and-drop listeners for a group header row.\n * Dragging a group moves all its member columns as a block.\n */\n private setupGroupDragListeners(header: HTMLElement, group: ColumnGroupInfo, columnList: HTMLElement): void {\n header.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedGroupId = group.id;\n this.draggedGroupFields = [...group.fields];\n // Use first field as representative for dataTransfer\n this.draggedField = null;\n this.draggedIndex = null;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `group:${group.id}`);\n }\n\n // Mark entire group (header + children) as dragging\n header.classList.add('dragging');\n columnList.querySelectorAll(`.tbw-visibility-row--grouped`).forEach((row) => {\n const field = row.getAttribute('data-field');\n if (field && this.draggedGroupFields.includes(field)) {\n row.classList.add('dragging');\n }\n });\n });\n\n header.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n // Group headers are also drop targets for other groups\n header.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n // Can't drop onto self\n if (this.draggedGroupId === group.id) return;\n // Can't drop individual columns onto group headers\n if (!this.draggedGroupId) return;\n\n const rect = header.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const before = e.clientY < midY;\n\n this.clearDragClasses(columnList);\n header.classList.add('drop-target');\n header.classList.toggle('drop-before', before);\n header.classList.toggle('drop-after', !before);\n });\n\n header.addEventListener('dragleave', () => {\n header.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n header.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || !this.draggedGroupId || this.draggedGroupId === group.id) return;\n\n const rect = header.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n\n this.executeGroupDrop(this.draggedGroupFields, group.fields, before, columnList);\n });\n }\n\n /**\n * Execute a group drop — move the dragged group's fields as a block\n * to the position relative to the target group or column.\n */\n private executeGroupDrop(\n draggedFields: string[],\n targetFields: string[],\n before: boolean,\n columnList: HTMLElement,\n ): void {\n const allColumns = this.grid.getAllColumns();\n const currentOrder = allColumns.map((c) => c.field);\n\n // Remove dragged fields from current order\n const remaining = currentOrder.filter((f) => !draggedFields.includes(f));\n\n // Find insertion point relative to target\n // Use the first field of target group if inserting before, last if after\n const anchorField = before ? targetFields[0] : targetFields[targetFields.length - 1];\n const insertAt = remaining.indexOf(anchorField);\n if (insertAt === -1) return;\n\n // Insert the dragged group block at the correct position\n const insertIndex = before ? insertAt : insertAt + 1;\n\n // Preserve the dragged fields' original relative order\n const draggedInOrder = currentOrder.filter((f) => draggedFields.includes(f));\n remaining.splice(insertIndex, 0, ...draggedInOrder);\n\n this.grid.setColumnOrder(remaining);\n // Panel rebuild handled by column-move listener — but since we're calling\n // setColumnOrder directly (not through ReorderPlugin.moveColumn), we need\n // to manually trigger a rebuild.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n\n /**\n * Set up drag-and-drop event listeners for a row.\n * On drop, emits a 'column-reorder-request' event for other plugins to handle.\n */\n private setupDragListeners(row: HTMLElement, field: string, index: number, columnList: HTMLElement): void {\n row.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = index;\n // Clear any stale group drag state\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n row.classList.add('dragging');\n });\n\n row.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n row.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n\n // If dragging a group, only allow drop on ungrouped rows\n if (this.draggedGroupId) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n } else if (this.draggedField === field) {\n return;\n }\n\n const rect = row.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n\n this.dropIndex = e.clientY < midY ? index : index + 1;\n\n // Clear other highlights\n this.clearDragClasses(columnList);\n // Re-mark dragged elements\n if (this.draggedGroupId) {\n columnList\n .querySelector(`.tbw-visibility-group-header[data-group-id=\"${this.draggedGroupId}\"]`)\n ?.classList.add('dragging');\n columnList.querySelectorAll('.tbw-visibility-row--grouped').forEach((r) => {\n const f = r.getAttribute('data-field');\n if (f && this.draggedGroupFields.includes(f)) r.classList.add('dragging');\n });\n } else if (this.draggedField) {\n columnList.querySelector(`.tbw-visibility-row[data-field=\"${this.draggedField}\"]`)?.classList.add('dragging');\n }\n\n row.classList.add('drop-target');\n row.classList.toggle('drop-before', e.clientY < midY);\n row.classList.toggle('drop-after', e.clientY >= midY);\n });\n\n row.addEventListener('dragleave', () => {\n row.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n row.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n\n if (!this.isDragging) return;\n\n // Group drop onto an ungrouped row\n if (this.draggedGroupId && this.draggedGroupFields.length > 0) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n const rect = row.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n this.executeGroupDrop(this.draggedGroupFields, [field], before, columnList);\n return;\n }\n\n // Individual column drop\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n // Calculate the effective target index (in the filtered non-utility list)\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n\n if (effectiveToIndex !== draggedIndex) {\n // Convert from non-utility index to full column order index\n // by counting how many utility columns come before the target position\n const allColumns = this.grid.getAllColumns();\n const nonUtilityColumns = allColumns.filter((c) => !c.utility);\n\n // Find the target field at effectiveToIndex in non-utility list\n const targetField = nonUtilityColumns[effectiveToIndex]?.field;\n // Find its actual index in the full column order\n const fullOrderToIndex = targetField ? allColumns.findIndex((c) => c.field === targetField) : allColumns.length;\n\n // Emit a request event - other plugins (like ReorderPlugin) can listen and handle\n const detail: ColumnReorderRequestDetail = {\n field: draggedField,\n fromIndex: draggedIndex, // Not used by ReorderPlugin, just for info\n toIndex: fullOrderToIndex,\n };\n this.emit<ColumnReorderRequestDetail>('column-reorder-request', detail);\n // Panel rebuild is handled by the column-move listener in attach()\n }\n });\n }\n // #endregion\n}\n"],"names":["canMoveColumn","column","meta","VisibilityPlugin","BaseGridPlugin","styles","container","r","grid","query","params","field","visible","c","wrapper","columnList","showAllBtn","plugin","reorderEnabled","allColumns","groups","g","fieldToGroup","group","renderedGroups","col","groupFieldSet","groupCols","fullIndex","columns","header","headerLabel","groupCheckbox","visibleCount","allLocked","newVisible","headerText","handle","allColumnsFullList","row","index","label","labelWrapper","checkbox","text","e","rect","midY","before","draggedFields","targetFields","currentOrder","remaining","f","anchorField","insertAt","insertIndex","draggedInOrder","draggedField","draggedIndex","dropIndex","effectiveToIndex","targetField","fullOrderToIndex","detail"],"mappings":"ouHA0CA,SAASA,EAAcC,EAA+B,CACpD,MAAMC,EAAOD,EAAO,MAAQ,CAAA,EAC5B,OAAOC,EAAK,eAAiB,IAAQA,EAAK,kBAAoB,EAChE,CAwFO,MAAMC,UAAyBC,EAAAA,cAAiC,CAOrE,OAAyB,aAAmC,CAC1D,CAAE,KAAM,UAAW,SAAU,GAAO,OAAQ,qDAAA,CAAsD,EAOpG,OAAyB,SAA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":3,"file":"visibility.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/visibility/VisibilityPlugin.ts"],"sourcesContent":["/**\n * Column Visibility Plugin (Class-based)\n *\n * Provides a UI for column visibility control via the shell's tool panel system.\n * Column visibility is a core grid feature - this plugin provides:\n * - A tool panel for column visibility management (registered with the shell)\n * - Backward-compatible API methods that delegate to grid.setColumnVisible(), etc.\n *\n * The grid emits 'column-visibility' events when columns are shown/hidden,\n * allowing consumers to save user preferences.\n *\n * When a reorder plugin is present, column rows become draggable for reordering.\n * Drag-drop emits 'column-reorder-request' events that the ReorderPlugin can listen for.\n */\n\nimport {\n BaseGridPlugin,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ToolPanelDefinition } from '../../core/types';\nimport type { ContextMenuParams, HeaderContextMenuItem } from '../context-menu/types';\nimport type { ColumnGroupInfo, VisibilityConfig } from './types';\nimport styles from './visibility.css?inline';\n\n/**\n * Detail for column-reorder-request events emitted when users drag-drop in the visibility panel.\n */\nexport interface ColumnReorderRequestDetail {\n /** The field name of the column to move */\n field: string;\n /** The source index (before move) */\n fromIndex: number;\n /** The target index (after move) */\n toIndex: number;\n}\n\n/**\n * Check if a column can be moved (respects lockPosition/suppressMovable).\n * Inlined to avoid importing from reorder plugin.\n */\nfunction canMoveColumn(column: ColumnConfig): boolean {\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Column Visibility Plugin for tbw-grid\n *\n * Gives users control over which columns are displayed. Hide less important columns\n * by default, let users toggle them via a column chooser UI, or programmatically\n * show/hide columns based on user preferences or screen size.\n *\n * > **Optional Enhancement:** When ReorderPlugin is also loaded, columns in the\n * > visibility panel become draggable for reordering.\n *\n * ## Installation\n *\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `allowHideAll` | `boolean` | `false` | Allow hiding all columns (no minimum) |\n *\n * ## Column Configuration\n *\n * | Property | Type | Default | Description |\n * |----------|------|---------|-------------|\n * | `visible` | `boolean` | `true` | Initial visibility state |\n * | `meta.lockVisibility` | `boolean` | `false` | Prevent user from toggling |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `hideColumn` | `(field: string) => void` | Hide a column |\n * | `showColumn` | `(field: string) => void` | Show a column |\n * | `toggleColumn` | `(field: string) => void` | Toggle visibility |\n * | `showAllColumns` | `() => void` | Show all columns |\n * | `getHiddenColumns` | `() => string[]` | Get list of hidden column fields |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-visibility-hover` | `var(--tbw-color-row-hover)` | Row hover background |\n * | `--tbw-panel-padding` | `0.75em` | Panel content padding |\n * | `--tbw-panel-gap` | `0.5em` | Gap between items |\n *\n * @example Columns Hidden by Default\n * ```ts\n * import '@toolbox-web/grid';\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\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: 'phone', header: 'Phone', visible: false }, // Hidden by default\n * { field: 'address', header: 'Address', visible: false },\n * ],\n * plugins: [new VisibilityPlugin()],\n * };\n *\n * // Toggle programmatically\n * const plugin = grid.getPlugin(VisibilityPlugin);\n * plugin.showColumn('phone');\n * ```\n *\n * @example With Drag-to-Reorder\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ReorderPlugin(), // Enables drag-drop in visibility panel\n * new VisibilityPlugin(),\n * ],\n * };\n * ```\n *\n * @see {@link VisibilityConfig} for configuration options\n * @see {@link ReorderPlugin} for drag-to-reorder integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class VisibilityPlugin extends BaseGridPlugin<VisibilityConfig> {\n /**\n * Plugin dependencies - VisibilityPlugin optionally uses ReorderPlugin for drag-drop reordering.\n *\n * When ReorderPlugin is present, columns in the visibility panel become draggable.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'reorder', required: false, reason: 'Enables drag-to-reorder columns in visibility panel' },\n ];\n\n /**\n * Plugin manifest - declares handled queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'getContextMenuItems',\n description: 'Contributes \"Hide column\" item to the header context menu',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'visibility';\n\n /** Tool panel ID for shell integration */\n static readonly PANEL_ID = 'columns';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<VisibilityConfig> {\n return {\n allowHideAll: false,\n };\n }\n\n // #region Internal State\n private columnListElement: HTMLElement | null = null;\n\n // Drag state for reorder integration\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n /** When dragging a group, holds the group ID; null for individual column drags. */\n private draggedGroupId: string | null = null;\n /** Fields belonging to the group currently being dragged. */\n private draggedGroupFields: string[] = [];\n\n /** Clear drag-related classes from all rows and group headers in a list. */\n private clearDragClasses(container: HTMLElement): void {\n container.querySelectorAll('.tbw-visibility-row, .tbw-visibility-group-header').forEach((r) => {\n r.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 column-move events (emitted by ReorderPlugin after any reorder,\n // including header drag-drop and visibility panel drag-drop) to keep the\n // panel list in sync with the grid's column order.\n (grid as unknown as HTMLElement).addEventListener(\n 'column-move',\n () => {\n if (this.columnListElement) {\n // column-move fires BEFORE setColumnOrder runs. Defer the rebuild\n // to allow the full reorder cycle (setColumnOrder + renderHeader +\n // refreshVirtualWindow) to complete before reading the new order.\n // Use RAF to run after the current synchronous work and any\n // animation frames queued by the animation system.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.columnListElement = null;\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n }\n // #endregion\n\n // #region Query Handlers\n\n /**\n * Handle inter-plugin queries.\n * Contributes a \"Hide column\" item to the header context menu.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getContextMenuItems') {\n const params = query.context as ContextMenuParams;\n if (!params.isHeader) return undefined;\n\n const column = params.column as ColumnConfig;\n if (!column?.field) return undefined;\n\n // Don't offer \"Hide\" for locked-visibility columns\n if (column.meta?.lockVisibility) return undefined;\n\n const items: HeaderContextMenuItem[] = [\n {\n id: 'visibility/hide-column',\n label: 'Hide Column',\n icon: '👁',\n order: 30,\n action: () => this.hideColumn(column.field),\n },\n ];\n\n return items;\n }\n return undefined;\n }\n // #endregion\n\n // #region Shell Integration\n\n /**\n * Register the column visibility tool panel with the shell.\n * @internal\n */\n override getToolPanel(): ToolPanelDefinition | undefined {\n return {\n id: VisibilityPlugin.PANEL_ID,\n title: 'Columns',\n icon: '☰',\n tooltip: 'Column visibility',\n order: 100, // High order so it appears last\n render: (container) => this.renderPanelContent(container),\n };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Show the visibility sidebar panel.\n * Opens the tool panel and ensures this section is expanded.\n */\n show(): void {\n this.grid.openToolPanel();\n // Ensure our section is expanded\n if (!this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID)) {\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n }\n\n /**\n * Hide the visibility sidebar panel.\n */\n hide(): void {\n this.grid.closeToolPanel();\n }\n\n /**\n * Toggle the visibility sidebar panel section.\n */\n toggle(): void {\n // If tool panel is closed, open it first\n if (!this.grid.isToolPanelOpen) {\n this.grid.openToolPanel();\n }\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n\n /**\n * Check if a specific column is visible.\n * Delegates to grid.isColumnVisible().\n * @param field - The field name to check\n * @returns True if the column is visible\n */\n isColumnVisible(field: string): boolean {\n return this.grid.isColumnVisible(field);\n }\n\n /**\n * Set visibility for a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column\n * @param visible - Whether the column should be visible\n */\n setColumnVisible(field: string, visible: boolean): void {\n this.grid.setColumnVisible(field, visible);\n }\n\n /**\n * Get list of all visible column fields.\n * @returns Array of visible field names\n */\n getVisibleColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Get list of all hidden column fields.\n * @returns Array of hidden field names\n */\n getHiddenColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => !c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Show all columns.\n * Delegates to grid.showAllColumns().\n */\n showAll(): void {\n this.grid.showAllColumns();\n }\n\n /**\n * Toggle visibility for a specific column.\n * Delegates to grid.toggleColumnVisibility().\n * @param field - The field name of the column\n */\n toggleColumn(field: string): void {\n this.grid.toggleColumnVisibility(field);\n }\n\n /**\n * Show a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to show\n */\n showColumn(field: string): void {\n this.setColumnVisible(field, true);\n }\n\n /**\n * Hide a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to hide\n */\n hideColumn(field: string): void {\n this.setColumnVisible(field, false);\n }\n\n /**\n * Get all columns with their visibility status.\n * Useful for building visibility UI.\n * @returns Array of column info with visibility status\n */\n getAllColumns(): Array<{\n field: string;\n header: string;\n visible: boolean;\n lockVisible?: boolean;\n utility?: boolean;\n }> {\n return this.grid.getAllColumns();\n }\n\n /**\n * Check if the sidebar panel is currently open.\n * @returns True if the panel section is expanded\n */\n isPanelVisible(): boolean {\n return this.grid.isToolPanelOpen && this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Render the panel content into the shell's tool panel container.\n * Returns a cleanup function.\n */\n private renderPanelContent(container: HTMLElement): (() => void) | void {\n // Create content wrapper\n const wrapper = document.createElement('div');\n wrapper.className = 'tbw-visibility-content';\n\n // Column list container\n const columnList = document.createElement('div');\n columnList.className = 'tbw-visibility-list';\n wrapper.appendChild(columnList);\n\n // Show all button\n const showAllBtn = document.createElement('button');\n showAllBtn.className = 'tbw-visibility-show-all';\n showAllBtn.textContent = 'Show All';\n showAllBtn.addEventListener('click', () => {\n this.grid.showAllColumns();\n this.rebuildToggles(columnList);\n });\n wrapper.appendChild(showAllBtn);\n\n // Store reference\n this.columnListElement = columnList;\n\n // Build initial toggles\n this.rebuildToggles(columnList);\n\n // Append to container\n container.appendChild(wrapper);\n\n // Return cleanup function\n return () => {\n this.columnListElement = null;\n wrapper.remove();\n };\n }\n\n /**\n * Check if a reorder plugin is present (by name to avoid static import).\n */\n private hasReorderPlugin(): boolean {\n const plugin = this.grid?.getPluginByName?.('reorder');\n // Duck-type check - just verify the plugin exists and has a moveColumn method\n return !!(plugin && typeof (plugin as { moveColumn?: unknown }).moveColumn === 'function');\n }\n\n /**\n * Build the column toggle checkboxes.\n * When GroupingColumnsPlugin is present, renders columns under collapsible group headers.\n * When a reorder plugin is present, adds drag handles for reordering.\n */\n private rebuildToggles(columnList: HTMLElement): void {\n const reorderEnabled = this.hasReorderPlugin();\n\n columnList.innerHTML = '';\n\n // getAllColumns() returns columns in their effective display order\n // Filter out utility columns (e.g., expander column) as they're internal\n const allColumns = this.grid.getAllColumns().filter((c) => !c.utility);\n\n // Query for column grouping info from GroupingColumnsPlugin (or any responder)\n const groupResults = this.grid.query<ColumnGroupInfo[]>('getColumnGrouping');\n const groups: ColumnGroupInfo[] = groupResults?.flat().filter((g) => g && g.fields.length > 0) ?? [];\n\n if (groups.length === 0) {\n // No grouping — render flat list (original behavior)\n this.renderFlatColumnList(allColumns, reorderEnabled, columnList);\n return;\n }\n\n // Build field → group lookup\n const fieldToGroup = new Map<string, ColumnGroupInfo>();\n for (const group of groups) {\n for (const field of group.fields) fieldToGroup.set(field, group);\n }\n\n // Walk columns in display order, interleaving groups and ungrouped columns.\n // When we encounter the first column of a group, render the entire group section.\n const renderedGroups = new Set<string>();\n\n for (const col of allColumns) {\n const group = fieldToGroup.get(col.field);\n\n if (group) {\n // Column belongs to a group — render entire group section at first encounter\n if (!renderedGroups.has(group.id)) {\n renderedGroups.add(group.id);\n // Filter allColumns (which is in display order) to group members.\n // This preserves the current column order after reordering,\n // rather than using group.fields which may be in static/original order.\n const groupFieldSet = new Set(group.fields);\n const groupCols = allColumns.filter((c) => groupFieldSet.has(c.field));\n if (groupCols.length > 0) {\n this.renderGroupSection(group, groupCols, reorderEnabled, columnList);\n }\n }\n // Subsequent columns of the same group are already rendered — skip\n } else {\n // Ungrouped column — render as individual row at its natural position\n const fullIndex = allColumns.indexOf(col);\n columnList.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, columnList));\n }\n }\n }\n\n /**\n * Render a group section with header checkbox and indented column rows.\n */\n private renderGroupSection(\n group: ColumnGroupInfo,\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n // Group header row\n const header = document.createElement('div');\n header.className = 'tbw-visibility-group-header';\n header.setAttribute('data-group-id', group.id);\n\n // Make group header draggable when reorder is enabled\n if (reorderEnabled) {\n header.draggable = true;\n header.classList.add('reorderable');\n this.setupGroupDragListeners(header, group, container);\n }\n\n const headerLabel = document.createElement('label');\n headerLabel.className = 'tbw-visibility-label';\n\n const groupCheckbox = document.createElement('input');\n groupCheckbox.type = 'checkbox';\n\n // Calculate tri-state: all visible, all hidden, or mixed\n const visibleCount = columns.filter((c) => c.visible).length;\n const allLocked = columns.every((c) => c.lockVisible);\n if (visibleCount === columns.length) {\n groupCheckbox.checked = true;\n groupCheckbox.indeterminate = false;\n } else if (visibleCount === 0) {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = false;\n } else {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = true;\n }\n groupCheckbox.disabled = allLocked;\n\n // Toggle all columns in group\n groupCheckbox.addEventListener('change', () => {\n const newVisible = groupCheckbox.checked;\n for (const col of columns) {\n if (col.lockVisible) continue;\n this.grid.setColumnVisible(col.field, newVisible);\n }\n setTimeout(() => this.rebuildToggles(container), 0);\n });\n\n const headerText = document.createElement('span');\n headerText.textContent = group.label;\n\n headerLabel.appendChild(groupCheckbox);\n headerLabel.appendChild(headerText);\n header.appendChild(headerLabel);\n\n // Add drag handle icon for group if reorderable\n if (reorderEnabled) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder group';\n // Insert handle before the label\n header.insertBefore(handle, headerLabel);\n }\n\n container.appendChild(header);\n\n // Render indented column rows\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n const row = this.createColumnRow(col, fullIndex, reorderEnabled, container);\n row.classList.add('tbw-visibility-row--grouped');\n container.appendChild(row);\n }\n }\n\n /**\n * Render a flat (ungrouped) list of column rows.\n */\n private renderFlatColumnList(\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n container.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, container));\n }\n }\n\n /**\n * Create a single column visibility row element.\n */\n private createColumnRow(\n col: ReturnType<typeof this.grid.getAllColumns>[number],\n index: number,\n reorderEnabled: boolean,\n columnList: HTMLElement,\n ): HTMLElement {\n const label = col.header || col.field;\n\n const row = document.createElement('div');\n row.className = col.lockVisible ? 'tbw-visibility-row locked' : 'tbw-visibility-row';\n row.setAttribute('data-field', col.field);\n row.setAttribute('data-index', String(index));\n\n // Add drag handle if reorder is enabled\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n row.draggable = true;\n row.classList.add('reorderable');\n this.setupDragListeners(row, col.field, index, columnList);\n }\n\n const labelWrapper = document.createElement('label');\n labelWrapper.className = 'tbw-visibility-label';\n\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.checked = col.visible;\n checkbox.disabled = col.lockVisible ?? false;\n checkbox.addEventListener('change', () => {\n this.grid.toggleColumnVisibility(col.field);\n // Refresh after toggle (grid may re-render)\n setTimeout(() => this.rebuildToggles(columnList), 0);\n });\n\n const text = document.createElement('span');\n text.textContent = label;\n\n labelWrapper.appendChild(checkbox);\n labelWrapper.appendChild(text);\n\n // Add drag handle icon if reorderable\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder';\n row.appendChild(handle);\n }\n\n row.appendChild(labelWrapper);\n return row;\n }\n\n /**\n * Set up drag-and-drop listeners for a group header row.\n * Dragging a group moves all its member columns as a block.\n */\n private setupGroupDragListeners(header: HTMLElement, group: ColumnGroupInfo, columnList: HTMLElement): void {\n header.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedGroupId = group.id;\n this.draggedGroupFields = [...group.fields];\n // Use first field as representative for dataTransfer\n this.draggedField = null;\n this.draggedIndex = null;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `group:${group.id}`);\n }\n\n // Mark entire group (header + children) as dragging\n header.classList.add('dragging');\n columnList.querySelectorAll(`.tbw-visibility-row--grouped`).forEach((row) => {\n const field = row.getAttribute('data-field');\n if (field && this.draggedGroupFields.includes(field)) {\n row.classList.add('dragging');\n }\n });\n });\n\n header.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n // Group headers are also drop targets for other groups\n header.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n // Can't drop onto self\n if (this.draggedGroupId === group.id) return;\n // Can't drop individual columns onto group headers\n if (!this.draggedGroupId) return;\n\n const rect = header.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const before = e.clientY < midY;\n\n this.clearDragClasses(columnList);\n header.classList.add('drop-target');\n header.classList.toggle('drop-before', before);\n header.classList.toggle('drop-after', !before);\n });\n\n header.addEventListener('dragleave', () => {\n header.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n header.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || !this.draggedGroupId || this.draggedGroupId === group.id) return;\n\n const rect = header.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n\n this.executeGroupDrop(this.draggedGroupFields, group.fields, before, columnList);\n });\n }\n\n /**\n * Execute a group drop — move the dragged group's fields as a block\n * to the position relative to the target group or column.\n */\n private executeGroupDrop(\n draggedFields: string[],\n targetFields: string[],\n before: boolean,\n columnList: HTMLElement,\n ): void {\n const allColumns = this.grid.getAllColumns();\n const currentOrder = allColumns.map((c) => c.field);\n\n // Remove dragged fields from current order\n const remaining = currentOrder.filter((f) => !draggedFields.includes(f));\n\n // Find insertion point relative to target\n // Use the first field of target group if inserting before, last if after\n const anchorField = before ? targetFields[0] : targetFields[targetFields.length - 1];\n const insertAt = remaining.indexOf(anchorField);\n if (insertAt === -1) return;\n\n // Insert the dragged group block at the correct position\n const insertIndex = before ? insertAt : insertAt + 1;\n\n // Preserve the dragged fields' original relative order\n const draggedInOrder = currentOrder.filter((f) => draggedFields.includes(f));\n remaining.splice(insertIndex, 0, ...draggedInOrder);\n\n this.grid.setColumnOrder(remaining);\n // Panel rebuild handled by column-move listener — but since we're calling\n // setColumnOrder directly (not through ReorderPlugin.moveColumn), we need\n // to manually trigger a rebuild.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n\n /**\n * Set up drag-and-drop event listeners for a row.\n * On drop, emits a 'column-reorder-request' event for other plugins to handle.\n */\n private setupDragListeners(row: HTMLElement, field: string, index: number, columnList: HTMLElement): void {\n row.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = index;\n // Clear any stale group drag state\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n row.classList.add('dragging');\n });\n\n row.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n row.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n\n // If dragging a group, only allow drop on ungrouped rows\n if (this.draggedGroupId) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n } else if (this.draggedField === field) {\n return;\n }\n\n const rect = row.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n\n this.dropIndex = e.clientY < midY ? index : index + 1;\n\n // Clear other highlights\n this.clearDragClasses(columnList);\n // Re-mark dragged elements\n if (this.draggedGroupId) {\n columnList\n .querySelector(`.tbw-visibility-group-header[data-group-id=\"${this.draggedGroupId}\"]`)\n ?.classList.add('dragging');\n columnList.querySelectorAll('.tbw-visibility-row--grouped').forEach((r) => {\n const f = r.getAttribute('data-field');\n if (f && this.draggedGroupFields.includes(f)) r.classList.add('dragging');\n });\n } else if (this.draggedField) {\n columnList.querySelector(`.tbw-visibility-row[data-field=\"${this.draggedField}\"]`)?.classList.add('dragging');\n }\n\n row.classList.add('drop-target');\n row.classList.toggle('drop-before', e.clientY < midY);\n row.classList.toggle('drop-after', e.clientY >= midY);\n });\n\n row.addEventListener('dragleave', () => {\n row.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n row.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n\n if (!this.isDragging) return;\n\n // Group drop onto an ungrouped row\n if (this.draggedGroupId && this.draggedGroupFields.length > 0) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n const rect = row.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n this.executeGroupDrop(this.draggedGroupFields, [field], before, columnList);\n return;\n }\n\n // Individual column drop\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n // Calculate the effective target index (in the filtered non-utility list)\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n\n if (effectiveToIndex !== draggedIndex) {\n // Convert from non-utility index to full column order index\n // by counting how many utility columns come before the target position\n const allColumns = this.grid.getAllColumns();\n const nonUtilityColumns = allColumns.filter((c) => !c.utility);\n\n // Find the target field at effectiveToIndex in non-utility list\n const targetField = nonUtilityColumns[effectiveToIndex]?.field;\n // Find its actual index in the full column order\n const fullOrderToIndex = targetField ? allColumns.findIndex((c) => c.field === targetField) : allColumns.length;\n\n // Emit a request event - other plugins (like ReorderPlugin) can listen and handle\n const detail: ColumnReorderRequestDetail = {\n field: draggedField,\n fromIndex: draggedIndex, // Not used by ReorderPlugin, just for info\n toIndex: fullOrderToIndex,\n };\n this.emit<ColumnReorderRequestDetail>('column-reorder-request', detail);\n // Panel rebuild is handled by the column-move listener in attach()\n }\n });\n }\n // #endregion\n}\n"],"names":["canMoveColumn","column","meta","lockPosition","suppressMovable","VisibilityPlugin","BaseGridPlugin","static","name","required","reason","queries","type","description","styles","defaultConfig","allowHideAll","columnListElement","isDragging","draggedField","draggedIndex","dropIndex","draggedGroupId","draggedGroupFields","clearDragClasses","container","querySelectorAll","forEach","r","classList","remove","attach","grid","super","addEventListener","this","requestAnimationFrame","rebuildToggles","signal","disconnectSignal","detach","handleQuery","query","params","context","isHeader","field","lockVisibility","id","label","icon","order","action","hideColumn","getToolPanel","PANEL_ID","title","tooltip","render","renderPanelContent","show","openToolPanel","expandedToolPanelSections","includes","toggleToolPanelSection","hide","closeToolPanel","toggle","isToolPanelOpen","isColumnVisible","setColumnVisible","visible","getVisibleColumns","getAllColumns","filter","c","map","getHiddenColumns","showAll","showAllColumns","toggleColumn","toggleColumnVisibility","showColumn","isPanelVisible","wrapper","document","createElement","className","columnList","appendChild","showAllBtn","textContent","hasReorderPlugin","plugin","getPluginByName","moveColumn","reorderEnabled","innerHTML","allColumns","utility","groupResults","groups","flat","g","fields","length","renderFlatColumnList","fieldToGroup","Map","group","set","renderedGroups","Set","col","get","has","add","groupFieldSet","groupCols","renderGroupSection","fullIndex","indexOf","createColumnRow","columns","header","setAttribute","draggable","setupGroupDragListeners","headerLabel","groupCheckbox","visibleCount","allLocked","every","lockVisible","checked","indeterminate","disabled","newVisible","setTimeout","headerText","handle","setIcon","resolveIcon","insertBefore","allColumnsFullList","findIndex","row","index","String","setupDragListeners","labelWrapper","checkbox","text","e","dataTransfer","effectAllowed","setData","getAttribute","preventDefault","rect","getBoundingClientRect","midY","top","height","before","clientY","executeGroupDrop","draggedFields","targetFields","currentOrder","remaining","f","anchorField","insertAt","insertIndex","draggedInOrder","splice","setColumnOrder","contains","querySelector","effectiveToIndex","nonUtilityColumns","targetField","detail","fromIndex","toIndex","emit"],"mappings":"oVA0CA,SAASA,EAAcC,GACrB,MAAMC,EAAOD,EAAOC,MAAQ,CAAA,EAC5B,OAA6B,IAAtBA,EAAKC,eAAkD,IAAzBD,EAAKE,eAC5C,CAwFO,MAAMC,UAAyBC,EAAAA,eAOpCC,oBAA4D,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