@toolbox-web/grid 1.26.1 → 1.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/all.js +2 -2
  2. package/all.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/lib/core/grid.d.ts +64 -1
  6. package/lib/core/internal/diagnostics.d.ts +4 -3
  7. package/lib/core/internal/row-manager.d.ts +3 -1
  8. package/lib/core/plugin/base-plugin.d.ts +2 -2
  9. package/lib/core/types.d.ts +59 -3
  10. package/lib/features/registry.js.map +1 -1
  11. package/lib/plugins/clipboard/ClipboardPlugin.d.ts +1 -1
  12. package/lib/plugins/clipboard/index.js.map +1 -1
  13. package/lib/plugins/column-virtualization/index.js.map +1 -1
  14. package/lib/plugins/context-menu/ContextMenuPlugin.d.ts +24 -5
  15. package/lib/plugins/context-menu/index.js.map +1 -1
  16. package/lib/plugins/editing/EditingPlugin.d.ts +1 -1
  17. package/lib/plugins/editing/index.js.map +1 -1
  18. package/lib/plugins/export/ExportPlugin.d.ts +1 -1
  19. package/lib/plugins/export/index.js.map +1 -1
  20. package/lib/plugins/filtering/index.d.ts +2 -2
  21. package/lib/plugins/filtering/index.js +1 -1
  22. package/lib/plugins/filtering/index.js.map +1 -1
  23. package/lib/plugins/grouping-columns/GroupingColumnsPlugin.d.ts +2 -2
  24. package/lib/plugins/grouping-columns/grouping-columns.d.ts +18 -3
  25. package/lib/plugins/grouping-columns/index.d.ts +0 -1
  26. package/lib/plugins/grouping-columns/index.js +1 -1
  27. package/lib/plugins/grouping-columns/index.js.map +1 -1
  28. package/lib/plugins/grouping-columns/types.d.ts +1 -7
  29. package/lib/plugins/grouping-rows/index.d.ts +2 -1
  30. package/lib/plugins/grouping-rows/index.js +1 -1
  31. package/lib/plugins/grouping-rows/index.js.map +1 -1
  32. package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +2 -0
  33. package/lib/plugins/master-detail/index.js +1 -1
  34. package/lib/plugins/master-detail/index.js.map +1 -1
  35. package/lib/plugins/master-detail/types.d.ts +20 -1
  36. package/lib/plugins/multi-sort/index.js.map +1 -1
  37. package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts +8 -1
  38. package/lib/plugins/pinned-columns/index.js +1 -1
  39. package/lib/plugins/pinned-columns/index.js.map +1 -1
  40. package/lib/plugins/pinned-columns/pinned-columns.d.ts +11 -1
  41. package/lib/plugins/pinned-rows/index.d.ts +1 -1
  42. package/lib/plugins/pinned-rows/index.js +1 -1
  43. package/lib/plugins/pinned-rows/index.js.map +1 -1
  44. package/lib/plugins/pinned-rows/types.d.ts +10 -3
  45. package/lib/plugins/pivot/PivotPlugin.d.ts +107 -1
  46. package/lib/plugins/pivot/index.d.ts +2 -1
  47. package/lib/plugins/pivot/index.js +1 -1
  48. package/lib/plugins/pivot/index.js.map +1 -1
  49. package/lib/plugins/print/index.js.map +1 -1
  50. package/lib/plugins/print/types.d.ts +0 -3
  51. package/lib/plugins/reorder-columns/ReorderPlugin.d.ts +19 -2
  52. package/lib/plugins/reorder-columns/index.js +1 -1
  53. package/lib/plugins/reorder-columns/index.js.map +1 -1
  54. package/lib/plugins/reorder-rows/index.d.ts +1 -1
  55. package/lib/plugins/reorder-rows/index.js.map +1 -1
  56. package/lib/plugins/responsive/ResponsivePlugin.d.ts +1 -1
  57. package/lib/plugins/responsive/index.js +1 -1
  58. package/lib/plugins/responsive/index.js.map +1 -1
  59. package/lib/plugins/selection/SelectionPlugin.d.ts +1 -1
  60. package/lib/plugins/selection/index.js +1 -1
  61. package/lib/plugins/selection/index.js.map +1 -1
  62. package/lib/plugins/selection/types.d.ts +3 -3
  63. package/lib/plugins/server-side/ServerSidePlugin.d.ts +6 -1
  64. package/lib/plugins/server-side/index.js +1 -1
  65. package/lib/plugins/server-side/index.js.map +1 -1
  66. package/lib/plugins/tree/TreePlugin.d.ts +116 -0
  67. package/lib/plugins/tree/index.d.ts +1 -1
  68. package/lib/plugins/tree/index.js +1 -1
  69. package/lib/plugins/tree/index.js.map +1 -1
  70. package/lib/plugins/tree/types.d.ts +16 -1
  71. package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts +1 -1
  72. package/lib/plugins/undo-redo/index.js.map +1 -1
  73. package/lib/plugins/undo-redo/types.d.ts +15 -3
  74. package/lib/plugins/visibility/VisibilityPlugin.d.ts +18 -5
  75. package/lib/plugins/visibility/index.js +1 -1
  76. package/lib/plugins/visibility/index.js.map +1 -1
  77. package/package.json +1 -1
  78. package/public.d.ts +2 -4
  79. package/themes/dg-theme-material.css +16 -4
  80. package/umd/grid.all.umd.js +1 -1
  81. package/umd/grid.all.umd.js.map +1 -1
  82. package/umd/grid.umd.js +1 -1
  83. package/umd/grid.umd.js.map +1 -1
  84. package/umd/plugins/clipboard.umd.js.map +1 -1
  85. package/umd/plugins/context-menu.umd.js.map +1 -1
  86. package/umd/plugins/editing.umd.js.map +1 -1
  87. package/umd/plugins/export.umd.js.map +1 -1
  88. package/umd/plugins/filtering.umd.js +1 -1
  89. package/umd/plugins/filtering.umd.js.map +1 -1
  90. package/umd/plugins/grouping-columns.umd.js +1 -1
  91. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  92. package/umd/plugins/grouping-rows.umd.js +1 -1
  93. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  94. package/umd/plugins/master-detail.umd.js +1 -1
  95. package/umd/plugins/master-detail.umd.js.map +1 -1
  96. package/umd/plugins/pinned-columns.umd.js +1 -1
  97. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  98. package/umd/plugins/pinned-rows.umd.js +1 -1
  99. package/umd/plugins/pinned-rows.umd.js.map +1 -1
  100. package/umd/plugins/pivot.umd.js +1 -1
  101. package/umd/plugins/pivot.umd.js.map +1 -1
  102. package/umd/plugins/reorder-columns.umd.js +1 -1
  103. package/umd/plugins/reorder-columns.umd.js.map +1 -1
  104. package/umd/plugins/responsive.umd.js +1 -1
  105. package/umd/plugins/responsive.umd.js.map +1 -1
  106. package/umd/plugins/selection.umd.js +1 -1
  107. package/umd/plugins/selection.umd.js.map +1 -1
  108. package/umd/plugins/server-side.umd.js +1 -1
  109. package/umd/plugins/server-side.umd.js.map +1 -1
  110. package/umd/plugins/tree.umd.js +1 -1
  111. package/umd/plugins/tree.umd.js.map +1 -1
  112. package/umd/plugins/undo-redo.umd.js.map +1 -1
  113. package/umd/plugins/visibility.umd.js +1 -1
  114. 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, GridHost } 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\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 { queryGrid } from '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = queryGrid('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 GridHost;\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 body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n const style = this.animationStyle;\n const shouldAnimate = style !== false && this.keysToAnimate.size > 0;\n const animClass = style === 'fade' ? 'tbw-tree-fade-in' : 'tbw-tree-slide-in';\n\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 treeRow = this.flattenedRows[idx];\n\n // Set aria-expanded on parent rows for screen readers\n if (treeRow?.hasChildren) {\n rowEl.setAttribute('aria-expanded', String(treeRow.isExpanded));\n }\n\n if (shouldAnimate && treeRow?.key && this.keysToAnimate.has(treeRow.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","body","gridElement","querySelector","shouldAnimate","size","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,EACA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9J,aAAc,IAAIkD,KAAKlD,gBACnEkD,KAAK8E,eACP,CAEA,WAAA+B,GACE7G,KAAKlD,iBFpZIG,IEqZT+C,KAAK4G,gBAAgB,oBAAqB,CAAE9J,aAAc,IAAIkD,KAAKlD,gBACnEkD,KAAK8E,eACP,CAEA,UAAAlD,CAAW7E,GACT,OAAOiD,KAAKlD,aAAaI,IAAIH,EAC/B,CAEA,eAAA+J,GACE,MAAO,IAAI9G,KAAKlD,aAClB,CAEA,gBAAAiK,GACE,MAAO,IAAI/G,KAAKP,cAClB,CAEA,WAAAuH,CAAYjK,GACV,OAAOiD,KAAKN,UAAUkF,IAAI7H,IAAM+D,IAClC,CAEA,WAAAzC,CAAYtB,GACViD,KAAKlD,aAAeuB,EAAY2B,KAAK1C,KAAmBP,EAAKiD,KAAKzC,OAAQyC,KAAKlD,cAC/EkD,KAAK8E,eACP"}
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, GridHost } 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\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 { queryGrid } from '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = queryGrid('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 incompatibleWith: [\n {\n name: 'groupingRows',\n reason:\n 'Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while ' +\n 'GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid.',\n },\n {\n name: 'pivot',\n reason:\n 'PivotPlugin replaces the entire row and column structure with aggregated pivot data. ' +\n 'Tree hierarchy cannot coexist with pivot aggregation.',\n },\n {\n name: 'serverSide',\n reason:\n 'TreePlugin requires the full hierarchy to flatten and manage expansion state. ' +\n 'ServerSidePlugin lazy-loads rows in blocks and cannot provide nested children on demand.',\n },\n ],\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 GridHost;\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 body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n const style = this.animationStyle;\n const shouldAnimate = style !== false && this.keysToAnimate.size > 0;\n const animClass = style === 'fade' ? 'tbw-tree-fade-in' : 'tbw-tree-slide-in';\n\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 treeRow = this.flattenedRows[idx];\n\n // Set aria-expanded on parent rows for screen readers\n if (treeRow?.hasChildren) {\n rowEl.setAttribute('aria-expanded', String(treeRow.isExpanded));\n }\n\n if (shouldAnimate && treeRow?.key && this.keysToAnimate.has(treeRow.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 /**\n * Expand a specific tree node, revealing its children.\n *\n * If the node is already expanded, this is a no-op.\n * Does **not** emit a `tree-expand` event (use {@link toggle} for event emission).\n *\n * @param key - The unique key of the node to expand (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.expand('documents'); // Expand a root node\n * tree.expand('documents||reports'); // Expand a nested node\n * ```\n */\n expand(key: string): void {\n this.expandedKeys.add(key);\n this.requestRender();\n }\n\n /**\n * Collapse a specific tree node, hiding its children.\n *\n * If the node is already collapsed, this is a no-op.\n * Does **not** emit a `tree-expand` event (use {@link toggle} for event emission).\n *\n * @param key - The unique key of the node to collapse (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.collapse('documents');\n * ```\n */\n collapse(key: string): void {\n this.expandedKeys.delete(key);\n this.requestRender();\n }\n\n /**\n * Toggle the expanded state of a tree node.\n *\n * If the node is expanded it will be collapsed, and vice versa.\n * Emits a `tree-state-change` plugin event with the updated expanded keys.\n *\n * @param key - The unique key of the node to toggle (from {@link FlattenedTreeRow.key})\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.toggle('documents'); // Expand if collapsed, collapse if expanded\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 /**\n * Expand all tree nodes recursively.\n *\n * Every node with children will be expanded, revealing the full tree hierarchy.\n * Emits a `tree-state-change` plugin event.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.expandAll();\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 /**\n * Collapse all tree nodes.\n *\n * Every node will be collapsed, showing only root-level rows.\n * Emits a `tree-state-change` plugin event.\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * tree.collapseAll();\n * ```\n */\n collapseAll(): void {\n this.expandedKeys = collapseAll();\n this.emitPluginEvent('tree-state-change', { expandedKeys: [...this.expandedKeys] });\n this.requestRender();\n }\n\n /**\n * Check whether a specific tree node is currently expanded.\n *\n * @param key - The unique key of the node to check\n * @returns `true` if the node is expanded, `false` otherwise\n */\n isExpanded(key: string): boolean {\n return this.expandedKeys.has(key);\n }\n\n /**\n * Get the keys of all currently expanded nodes.\n *\n * Returns a snapshot copy — mutating the returned array does not affect the tree state.\n *\n * @returns Array of expanded node keys\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * const keys = tree.getExpandedKeys();\n * localStorage.setItem('treeState', JSON.stringify(keys));\n * ```\n */\n getExpandedKeys(): string[] {\n return [...this.expandedKeys];\n }\n\n /**\n * Get the flattened row model used for rendering.\n *\n * Returns a snapshot copy of the internal flattened tree rows, including\n * hierarchy metadata (depth, hasChildren, isExpanded, parentKey).\n *\n * @returns Array of {@link FlattenedTreeRow} objects\n */\n getFlattenedRows(): FlattenedTreeRow[] {\n return [...this.flattenedRows];\n }\n\n /**\n * Look up an original row data object by its tree key.\n *\n * @param key - The unique key of the node\n * @returns The original row data, or `undefined` if not found\n */\n getRowByKey(key: string): TreeRow | undefined {\n return this.rowKeyMap.get(key)?.data;\n }\n\n /**\n * Expand all ancestor nodes of the target key, revealing it in the tree.\n *\n * Useful for \"scroll to node\" or search-and-reveal scenarios where a deeply\n * nested node needs to be made visible.\n *\n * @param key - The unique key of the node to reveal\n *\n * @example\n * ```ts\n * const tree = grid.getPluginByName('tree');\n * // Reveal a deeply nested node by expanding all its parents\n * tree.expandToKey('root||child||grandchild');\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","incompatibleWith","name","reason","events","type","description","queries","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","body","gridElement","querySelector","shouldAnimate","size","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,EA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B,GACE7G,KAAKpD,iBF3eIG,IE4eTiD,KAAK4G,gBAAgB,oBAAqB,CAAEhK,aAAc,IAAIoD,KAAKpD,gBACnEoD,KAAK8E,eACP,CAQA,UAAAlD,CAAW/E,GACT,OAAOmD,KAAKpD,aAAaI,IAAIH,EAC/B,CAgBA,eAAAiK,GACE,MAAO,IAAI9G,KAAKpD,aAClB,CAUA,gBAAAmK,GACE,MAAO,IAAI/G,KAAKP,cAClB,CAQA,WAAAuH,CAAYnK,GACV,OAAOmD,KAAKN,UAAUkF,IAAI/H,IAAMiE,IAClC,CAiBA,WAAA3C,CAAYtB,GACVmD,KAAKpD,aAAeuB,EAAY6B,KAAK5C,KAAmBP,EAAKmD,KAAK3C,OAAQ2C,KAAKpD,cAC/EoD,KAAK8E,eACP"}
@@ -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 { CompoundEditAction, EditAction, UndoRedoAction, 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: UndoRedoAction, 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: UndoRedoAction | 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: UndoRedoAction | 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/**\n * Create a compound action grouping multiple edits into a single undo/redo unit.\n *\n * @param actions - The individual edit actions to group (in chronological order)\n * @returns A CompoundEditAction wrapping all provided edits\n */\nexport function createCompoundAction(actions: EditAction[]): CompoundEditAction {\n return {\n type: 'compound',\n actions,\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 { NO_TRANSACTION, TRANSACTION_IN_PROGRESS, throwDiagnostic } from '../../core/internal/diagnostics';\nimport { FOCUSABLE_EDITOR_SELECTOR } from '../../core/internal/rows';\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport {\n canRedo,\n canUndo,\n clearHistory,\n createCompoundAction,\n createEditAction,\n pushAction,\n redo,\n undo,\n} from './history';\nimport type { EditAction, UndoRedoAction, 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` | `() => UndoRedoAction \\| null` | Undo the last edit (or compound) |\n * | `redo` | `() => UndoRedoAction \\| null` | Redo the last undone edit (or compound) |\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 * | `recordEdit` | `(rowIndex, field, old, new) => void` | Manually record a cell edit |\n * | `beginTransaction` | `() => void` | Start grouping edits into a compound |\n * | `endTransaction` | `() => void` | Finalize and push the compound action |\n *\n * @example Basic Usage with EditingPlugin\n * ```ts\n * import { queryGrid } from '@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 = queryGrid('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: UndoRedoAction[] = [];\n private redoStack: UndoRedoAction[] = [];\n\n /** Suppresses recording during undo/redo to prevent feedback loops. */\n #suppressRecording = false;\n\n /** Accumulates edits during a transaction; `null` when no transaction is active. */\n #transactionBuffer: EditAction[] | null = null;\n\n /**\n * Apply a value to a row cell, using `updateRow()` when possible so that\n * active editors (during row-edit mode) are notified via the `cell-change`\n * → `onValueChange` pipeline. Falls back to direct mutation when the row\n * has no ID.\n */\n #applyValue(action: EditAction, value: unknown): void {\n const rows = this.rows as Record<string, unknown>[];\n const row = rows[action.rowIndex];\n if (!row) return;\n\n // Prefer updateRow() — it emits `cell-change` events which notify active\n // editors via their `onValueChange` callbacks. Without this, undo/redo\n // during row-edit mode is invisible because the render pipeline skips\n // cells that have active editors.\n try {\n const rowId = this.grid.getRowId(row);\n if (rowId) {\n this.grid.updateRow(rowId, { [action.field]: value });\n return;\n }\n } catch {\n // No row ID configured — fall back to direct mutation\n }\n\n // Fallback: direct mutation (editors won't see the change during editing)\n row[action.field] = value;\n }\n\n /**\n * Move keyboard focus to the cell targeted by an undo/redo action.\n * If the grid is in row-edit mode and the cell has an active editor,\n * the editor input is focused so the user can continue editing.\n */\n #focusActionCell(action: EditAction): void {\n const internalGrid: GridHost = this.grid as unknown as GridHost;\n\n // Map field name → visible column index\n const colIdx = internalGrid._visibleColumns?.findIndex((c) => c.field === action.field) ?? -1;\n if (colIdx < 0) return;\n\n internalGrid._focusRow = action.rowIndex;\n internalGrid._focusCol = colIdx;\n\n // If we're in row-edit mode, focus the editor input in the target cell\n const rowEl = internalGrid.findRenderedRowElement?.(action.rowIndex);\n if (!rowEl) return;\n\n const cellEl = rowEl.querySelector(`.cell[data-col=\"${colIdx}\"]`) as HTMLElement | null;\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n editor?.focus({ preventScroll: true });\n }\n }\n\n /**\n * Apply value changes for a single or compound action.\n * Wraps `#applyValue` calls with `#suppressRecording` to prevent feedback loops.\n */\n #applyUndoRedoAction(action: UndoRedoAction, direction: 'undo' | 'redo'): void {\n this.#suppressRecording = true;\n if (action.type === 'compound') {\n const subActions = direction === 'undo' ? [...action.actions].reverse() : action.actions;\n for (const sub of subActions) {\n this.#applyValue(sub, direction === 'undo' ? sub.oldValue : sub.newValue);\n }\n } else {\n this.#applyValue(action, direction === 'undo' ? action.oldValue : action.newValue);\n }\n this.#suppressRecording = false;\n }\n\n /**\n * Focus the cell associated with an undo/redo action.\n * For compound actions, focuses the **last** action's cell. When consumers\n * use `beginTransaction()` + `recordEdit()` (cascaded fields) followed by\n * `queueMicrotask(() => endTransaction())`, the grid's auto-recorded\n * primary field edit is appended last. Focusing it ensures the cursor\n * lands on the field the user originally edited, not on a cascaded field\n * whose column may not even be visible.\n */\n #focusUndoRedoAction(action: UndoRedoAction): void {\n const target = action.type === 'compound' ? action.actions[action.actions.length - 1] : action;\n if (target) this.#focusActionCell(target);\n }\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 // Skip recording during undo/redo operations. When undo/redo applies a\n // value via updateRow, two things can cause re-entry:\n // 1. updateRow → cell-change → onValueChange → editor triggers commit\n // 2. Browser native undo (if not fully suppressed) fires input event → commit\n // The suppress flag prevents these from corrupting the history stacks.\n if (this.#suppressRecording) return;\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 this.#transactionBuffer = null;\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 // Prevent browser native undo on text inputs — it would conflict\n // with the grid's undo by mutating the input text independently,\n // triggering re-commits that cancel the grid undo.\n event.preventDefault();\n\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'undo');\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.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\n }\n return true;\n }\n\n if (isRedo) {\n // Prevent browser native redo — same reason as undo above\n event.preventDefault();\n\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'redo');\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.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\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\n // Buffer during transactions instead of pushing to undo stack\n if (this.#transactionBuffer) {\n this.#transactionBuffer.push(action);\n return;\n }\n\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 * Begin grouping subsequent edits into a single compound action.\n *\n * While a transaction is active, all `recordEdit()` calls (both manual\n * and auto-recorded from `cell-edit-committed`) are buffered instead of\n * pushed to the undo stack. Call `endTransaction()` to finalize the group.\n *\n * **Typical usage** — group a user edit with its cascaded side-effects:\n *\n * ```ts\n * grid.on('cell-commit', () => {\n * const undoRedo = grid.getPluginByName('undoRedo');\n * undoRedo.beginTransaction();\n *\n * // Record cascaded updates (these won't auto-record)\n * const oldB = row.fieldB;\n * undoRedo.recordEdit(rowIndex, 'fieldB', oldB, computedB);\n * grid.updateRow(rowId, { fieldB: computedB });\n *\n * // End after the auto-recorded original edit is captured\n * queueMicrotask(() => undoRedo.endTransaction());\n * });\n * ```\n *\n * @throws Error if a transaction is already in progress\n */\n beginTransaction(): void {\n if (this.#transactionBuffer) {\n throwDiagnostic(TRANSACTION_IN_PROGRESS, 'Transaction already in progress. Call endTransaction() first.');\n }\n this.#transactionBuffer = [];\n }\n\n /**\n * Finalize the current transaction, wrapping all buffered edits into a\n * single compound action on the undo stack.\n *\n * - If the buffer contains multiple edits, they are wrapped in a `CompoundEditAction`.\n * - If the buffer contains a single edit, it is pushed as a regular `EditAction`.\n * - If the buffer is empty, this is a no-op.\n *\n * Undoing a compound action reverts all edits in reverse order; redoing\n * replays them in forward order.\n *\n * @throws Error if no transaction is in progress\n */\n endTransaction(): void {\n const buffer = this.#transactionBuffer;\n if (!buffer) {\n throwDiagnostic(NO_TRANSACTION, 'No transaction in progress. Call beginTransaction() first.');\n }\n this.#transactionBuffer = null;\n\n if (buffer.length === 0) return;\n\n const action: UndoRedoAction = buffer.length === 1 ? buffer[0] : createCompoundAction(buffer);\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(): UndoRedoAction | null {\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'undo');\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\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(): UndoRedoAction | null {\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'redo');\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\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 this.#transactionBuffer = null;\n }\n\n /**\n * Get a copy of the current undo stack.\n */\n getUndoStack(): UndoRedoAction[] {\n return [...this.undoStack];\n }\n\n /**\n * Get a copy of the current redo stack.\n */\n getRedoStack(): UndoRedoAction[] {\n return [...this.redoStack];\n }\n // #endregion\n}\n"],"names":["pushAction","state","action","maxSize","undoStack","length","shift","redoStack","undo","newState","pop","redo","UndoRedoPlugin","BaseGridPlugin","static","name","required","reason","defaultConfig","maxHistorySize","suppressRecording","transactionBuffer","applyValue","value","row","this","rows","rowIndex","rowId","grid","getRowId","updateRow","field","focusActionCell","internalGrid","colIdx","_visibleColumns","findIndex","c","_focusRow","_focusCol","rowEl","findRenderedRowElement","cellEl","querySelector","classList","contains","editor","FOCUSABLE_EDITOR_SELECTOR","focus","preventScroll","applyUndoRedoAction","direction","type","subActions","actions","reverse","sub","oldValue","newValue","focusUndoRedoAction","target","attach","super","on","detail","recordEdit","detach","onKeyDown","event","isUndo","ctrlKey","metaKey","key","shiftKey","isRedo","preventDefault","result","emit","requestRenderWithFocus","timestamp","Date","now","createEditAction","push","config","beginTransaction","throwDiagnostic","TRANSACTION_IN_PROGRESS","endTransaction","buffer","NO_TRANSACTION","canUndo","canRedo","clearHistory","getUndoStack","getRedoStack"],"mappings":"sfAkBO,SAASA,EAAWC,EAAsBC,EAAwBC,GACvE,MAAMC,EAAY,IAAIH,EAAMG,UAAWF,GAGvC,KAAOE,EAAUC,OAASF,GACxBC,EAAUE,QAGZ,MAAO,CACLF,YACAG,UAAW,GAEf,CASO,SAASC,EAAKP,GAInB,GAA+B,IAA3BA,EAAMG,UAAUC,OAClB,MAAO,CAAEI,SAAUR,EAAOC,OAAQ,MAGpC,MAAME,EAAY,IAAIH,EAAMG,WACtBF,EAASE,EAAUM,MAIzB,OAAKR,EAIE,CACLO,SAAU,CACRL,YACAG,UAAW,IAAIN,EAAMM,UAAWL,IAElCA,UARO,CAAEO,SAAUR,EAAOC,OAAQ,KAUtC,CASO,SAASS,EAAKV,GAInB,GAA+B,IAA3BA,EAAMM,UAAUF,OAClB,MAAO,CAAEI,SAAUR,EAAOC,OAAQ,MAGpC,MAAMK,EAAY,IAAIN,EAAMM,WACtBL,EAASK,EAAUG,MAIzB,OAAKR,EAIE,CACLO,SAAU,CACRL,UAAW,IAAIH,EAAMG,UAAWF,GAChCK,aAEFL,UARO,CAAEO,SAAUR,EAAOC,OAAQ,KAUtC,CCNO,MAAMU,UAAuBC,EAAAA,eAOlCC,oBAA4D,CAC1D,CAAEC,KAAM,UAAWC,UAAU,EAAMC,OAAQ,4CAIpCF,KAAO,WAGhB,iBAAuBG,GACrB,MAAO,CACLC,eAAgB,IAEpB,CAGQf,UAA8B,GAC9BG,UAA8B,GAGtCa,IAAqB,EAGrBC,GAA0C,KAQ1C,EAAAC,CAAYpB,EAAoBqB,GAC9B,MACMC,EADOC,KAAKC,KACDxB,EAAOyB,UACxB,GAAKH,EAAL,CAMA,IACE,MAAMI,EAAQH,KA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EAAO3E,QACjCuB,KAAKsD,0BAEAF,EAAO3E,MAChB,CAOA,IAAAS,GACE,MAAMkE,EAASlE,EAAK,CAAEP,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,YAQjE,OAPIsE,EAAO3E,SACTuB,MAAK0B,EAAqB0B,EAAO3E,OAAQ,QACzCuB,KAAKrB,UAAYyE,EAAOpE,SAASL,UACjCqB,KAAKlB,UAAYsE,EAAOpE,SAASF,UACjCkB,MAAKmC,EAAqBiB,EAAO3E,QACjCuB,KAAKsD,0BAEAF,EAAO3E,MAChB,CAKA,OAAA0F,GACE,MAAe,CAAExF,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,WDtUjDH,UAAUC,OAAS,CCuUhC,CAKA,OAAAwF,GACE,MAAe,CAAEzF,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,WDnUjDA,UAAUF,OAAS,CCoUhC,CAKA,YAAAyF,GACE,MAAMrF,EDjUD,CAAEL,UAAW,GAAIG,UAAW,ICkUjCkB,KAAKrB,UAAYK,EAASL,UAC1BqB,KAAKlB,UAAYE,EAASF,UAC1BkB,MAAKJ,EAAqB,IAC5B,CAKA,YAAA0E,GACE,MAAO,IAAItE,KAAKrB,UAClB,CAKA,YAAA4F,GACE,MAAO,IAAIvE,KAAKlB,UAClB"}
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 { CompoundEditAction, EditAction, UndoRedoAction, 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: UndoRedoAction, 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: UndoRedoAction | 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: UndoRedoAction | 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/**\n * Create a compound action grouping multiple edits into a single undo/redo unit.\n *\n * @param actions - The individual edit actions to group (in chronological order)\n * @returns A CompoundEditAction wrapping all provided edits\n */\nexport function createCompoundAction(actions: EditAction[]): CompoundEditAction {\n return {\n type: 'compound',\n actions,\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 { NO_TRANSACTION, TRANSACTION_IN_PROGRESS, throwDiagnostic } from '../../core/internal/diagnostics';\nimport { FOCUSABLE_EDITOR_SELECTOR } from '../../core/internal/rows';\nimport { BaseGridPlugin, type GridElement, type PluginDependency } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport {\n canRedo,\n canUndo,\n clearHistory,\n createCompoundAction,\n createEditAction,\n pushAction,\n redo,\n undo,\n} from './history';\nimport type { EditAction, UndoRedoAction, 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` | `() => UndoRedoAction \\| null` | Undo the last edit (or compound) |\n * | `redo` | `() => UndoRedoAction \\| null` | Redo the last undone edit (or compound) |\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 * | `recordEdit` | `(rowIndex, field, old, new) => void` | Manually record a cell edit |\n * | `beginTransaction` | `() => void` | Start grouping edits into a compound |\n * | `endTransaction` | `() => void` | Finalize and push the compound action |\n *\n * @example Basic Usage with EditingPlugin\n * ```ts\n * import { queryGrid } from '@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 = queryGrid('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 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: UndoRedoAction[] = [];\n private redoStack: UndoRedoAction[] = [];\n\n /** Suppresses recording during undo/redo to prevent feedback loops. */\n #suppressRecording = false;\n\n /** Accumulates edits during a transaction; `null` when no transaction is active. */\n #transactionBuffer: EditAction[] | null = null;\n\n /**\n * Apply a value to a row cell, using `updateRow()` when possible so that\n * active editors (during row-edit mode) are notified via the `cell-change`\n * → `onValueChange` pipeline. Falls back to direct mutation when the row\n * has no ID.\n */\n #applyValue(action: EditAction, value: unknown): void {\n const rows = this.rows as Record<string, unknown>[];\n const row = rows[action.rowIndex];\n if (!row) return;\n\n // Prefer updateRow() — it emits `cell-change` events which notify active\n // editors via their `onValueChange` callbacks. Without this, undo/redo\n // during row-edit mode is invisible because the render pipeline skips\n // cells that have active editors.\n try {\n const rowId = this.grid.getRowId(row);\n if (rowId) {\n this.grid.updateRow(rowId, { [action.field]: value });\n return;\n }\n } catch {\n // No row ID configured — fall back to direct mutation\n }\n\n // Fallback: direct mutation (editors won't see the change during editing)\n row[action.field] = value;\n }\n\n /**\n * Move keyboard focus to the cell targeted by an undo/redo action.\n * If the grid is in row-edit mode and the cell has an active editor,\n * the editor input is focused so the user can continue editing.\n */\n #focusActionCell(action: EditAction): void {\n const internalGrid: GridHost = this.grid as unknown as GridHost;\n\n // Map field name → visible column index\n const colIdx = internalGrid._visibleColumns?.findIndex((c) => c.field === action.field) ?? -1;\n if (colIdx < 0) return;\n\n internalGrid._focusRow = action.rowIndex;\n internalGrid._focusCol = colIdx;\n\n // If we're in row-edit mode, focus the editor input in the target cell\n const rowEl = internalGrid.findRenderedRowElement?.(action.rowIndex);\n if (!rowEl) return;\n\n const cellEl = rowEl.querySelector(`.cell[data-col=\"${colIdx}\"]`) as HTMLElement | null;\n if (cellEl?.classList.contains('editing')) {\n const editor = cellEl.querySelector(FOCUSABLE_EDITOR_SELECTOR) as HTMLElement | null;\n editor?.focus({ preventScroll: true });\n }\n }\n\n /**\n * Apply value changes for a single or compound action.\n * Wraps `#applyValue` calls with `#suppressRecording` to prevent feedback loops.\n */\n #applyUndoRedoAction(action: UndoRedoAction, direction: 'undo' | 'redo'): void {\n this.#suppressRecording = true;\n if (action.type === 'compound') {\n const subActions = direction === 'undo' ? [...action.actions].reverse() : action.actions;\n for (const sub of subActions) {\n this.#applyValue(sub, direction === 'undo' ? sub.oldValue : sub.newValue);\n }\n } else {\n this.#applyValue(action, direction === 'undo' ? action.oldValue : action.newValue);\n }\n this.#suppressRecording = false;\n }\n\n /**\n * Focus the cell associated with an undo/redo action.\n * For compound actions, focuses the **last** action's cell. When consumers\n * use `beginTransaction()` + `recordEdit()` (cascaded fields) followed by\n * `queueMicrotask(() => endTransaction())`, the grid's auto-recorded\n * primary field edit is appended last. Focusing it ensures the cursor\n * lands on the field the user originally edited, not on a cascaded field\n * whose column may not even be visible.\n */\n #focusUndoRedoAction(action: UndoRedoAction): void {\n const target = action.type === 'compound' ? action.actions[action.actions.length - 1] : action;\n if (target) this.#focusActionCell(target);\n }\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 // Skip recording during undo/redo operations. When undo/redo applies a\n // value via updateRow, two things can cause re-entry:\n // 1. updateRow → cell-change → onValueChange → editor triggers commit\n // 2. Browser native undo (if not fully suppressed) fires input event → commit\n // The suppress flag prevents these from corrupting the history stacks.\n if (this.#suppressRecording) return;\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 this.#transactionBuffer = null;\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 // Prevent browser native undo on text inputs — it would conflict\n // with the grid's undo by mutating the input text independently,\n // triggering re-commits that cancel the grid undo.\n event.preventDefault();\n\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'undo');\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.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\n }\n return true;\n }\n\n if (isRedo) {\n // Prevent browser native redo — same reason as undo above\n event.preventDefault();\n\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'redo');\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.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\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\n // Buffer during transactions instead of pushing to undo stack\n if (this.#transactionBuffer) {\n this.#transactionBuffer.push(action);\n return;\n }\n\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 * Begin grouping subsequent edits into a single compound action.\n *\n * While a transaction is active, all `recordEdit()` calls (both manual\n * and auto-recorded from `cell-edit-committed`) are buffered instead of\n * pushed to the undo stack. Call `endTransaction()` to finalize the group.\n *\n * **Typical usage** — group a user edit with its cascaded side-effects:\n *\n * ```ts\n * grid.on('cell-commit', () => {\n * const undoRedo = grid.getPluginByName('undoRedo');\n * undoRedo.beginTransaction();\n *\n * // Record cascaded updates (these won't auto-record)\n * const oldB = row.fieldB;\n * undoRedo.recordEdit(rowIndex, 'fieldB', oldB, computedB);\n * grid.updateRow(rowId, { fieldB: computedB });\n *\n * // End after the auto-recorded original edit is captured\n * queueMicrotask(() => undoRedo.endTransaction());\n * });\n * ```\n *\n * @throws Error if a transaction is already in progress\n */\n beginTransaction(): void {\n if (this.#transactionBuffer) {\n throwDiagnostic(TRANSACTION_IN_PROGRESS, 'Transaction already in progress. Call endTransaction() first.');\n }\n this.#transactionBuffer = [];\n }\n\n /**\n * Finalize the current transaction, wrapping all buffered edits into a\n * single compound action on the undo stack.\n *\n * - If the buffer contains multiple edits, they are wrapped in a `CompoundEditAction`.\n * - If the buffer contains a single edit, it is pushed as a regular `EditAction`.\n * - If the buffer is empty, this is a no-op.\n *\n * Undoing a compound action reverts all edits in reverse order; redoing\n * replays them in forward order.\n *\n * @throws Error if no transaction is in progress\n */\n endTransaction(): void {\n const buffer = this.#transactionBuffer;\n if (!buffer) {\n throwDiagnostic(NO_TRANSACTION, 'No transaction in progress. Call beginTransaction() first.');\n }\n this.#transactionBuffer = null;\n\n if (buffer.length === 0) return;\n\n const action: UndoRedoAction = buffer.length === 1 ? buffer[0] : createCompoundAction(buffer);\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(): UndoRedoAction | null {\n const result = undo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'undo');\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\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(): UndoRedoAction | null {\n const result = redo({ undoStack: this.undoStack, redoStack: this.redoStack });\n if (result.action) {\n this.#applyUndoRedoAction(result.action, 'redo');\n this.undoStack = result.newState.undoStack;\n this.redoStack = result.newState.redoStack;\n this.#focusUndoRedoAction(result.action);\n this.requestRenderWithFocus();\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 this.#transactionBuffer = null;\n }\n\n /**\n * Get a copy of the current undo stack.\n */\n getUndoStack(): UndoRedoAction[] {\n return [...this.undoStack];\n }\n\n /**\n * Get a copy of the current redo stack.\n */\n getRedoStack(): UndoRedoAction[] {\n return [...this.redoStack];\n }\n // #endregion\n}\n"],"names":["pushAction","state","action","maxSize","undoStack","length","shift","redoStack","undo","newState","pop","redo","UndoRedoPlugin","BaseGridPlugin","static","name","required","reason","defaultConfig","maxHistorySize","suppressRecording","transactionBuffer","applyValue","value","row","this","rows","rowIndex","rowId","grid","getRowId","updateRow","field","focusActionCell","internalGrid","colIdx","_visibleColumns","findIndex","c","_focusRow","_focusCol","rowEl","findRenderedRowElement","cellEl","querySelector","classList","contains","editor","FOCUSABLE_EDITOR_SELECTOR","focus","preventScroll","applyUndoRedoAction","direction","type","subActions","actions","reverse","sub","oldValue","newValue","focusUndoRedoAction","target","attach","super","on","detail","recordEdit","detach","onKeyDown","event","isUndo","ctrlKey","metaKey","key","shiftKey","isRedo","preventDefault","result","emit","requestRenderWithFocus","timestamp","Date","now","createEditAction","push","config","beginTransaction","throwDiagnostic","TRANSACTION_IN_PROGRESS","endTransaction","buffer","NO_TRANSACTION","canUndo","canRedo","clearHistory","getUndoStack","getRedoStack"],"mappings":"sfAkBO,SAASA,EAAWC,EAAsBC,EAAwBC,GACvE,MAAMC,EAAY,IAAIH,EAAMG,UAAWF,GAGvC,KAAOE,EAAUC,OAASF,GACxBC,EAAUE,QAGZ,MAAO,CACLF,YACAG,UAAW,GAEf,CASO,SAASC,EAAKP,GAInB,GAA+B,IAA3BA,EAAMG,UAAUC,OAClB,MAAO,CAAEI,SAAUR,EAAOC,OAAQ,MAGpC,MAAME,EAAY,IAAIH,EAAMG,WACtBF,EAASE,EAAUM,MAIzB,OAAKR,EAIE,CACLO,SAAU,CACRL,YACAG,UAAW,IAAIN,EAAMM,UAAWL,IAElCA,UARO,CAAEO,SAAUR,EAAOC,OAAQ,KAUtC,CASO,SAASS,EAAKV,GAInB,GAA+B,IAA3BA,EAAMM,UAAUF,OAClB,MAAO,CAAEI,SAAUR,EAAOC,OAAQ,MAGpC,MAAMK,EAAY,IAAIN,EAAMM,WACtBL,EAASK,EAAUG,MAIzB,OAAKR,EAIE,CACLO,SAAU,CACRL,UAAW,IAAIH,EAAMG,UAAWF,GAChCK,aAEFL,UARO,CAAEO,SAAUR,EAAOC,OAAQ,KAUtC,CCNO,MAAMU,UAAuBC,EAAAA,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B,UAAYK,EAASL,UAC1BqB,KAAKlB,UAAYE,EAASF,SAC5B,CAOA,IAAAC,GACE,MAAMqE,EAASrE,EAAK,CAAEJ,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,YAQjE,OAPIsE,EAAO3E,SACTuB,MAAK0B,EAAqB0B,EAAO3E,OAAQ,QACzCuB,KAAKrB,UAAYyE,EAAOpE,SAASL,UACjCqB,KAAKlB,UAAYsE,EAAOpE,SAASF,UACjCkB,MAAKmC,EAAqBiB,EAAO3E,QACjCuB,KAAKsD,0BAEAF,EAAO3E,MAChB,CAOA,IAAAS,GACE,MAAMkE,EAASlE,EAAK,CAAEP,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,YAQjE,OAPIsE,EAAO3E,SACTuB,MAAK0B,EAAqB0B,EAAO3E,OAAQ,QACzCuB,KAAKrB,UAAYyE,EAAOpE,SAASL,UACjCqB,KAAKlB,UAAYsE,EAAOpE,SAASF,UACjCkB,MAAKmC,EAAqBiB,EAAO3E,QACjCuB,KAAKsD,0BAEAF,EAAO3E,MAChB,CAKA,OAAA0F,GACE,MAAe,CAAExF,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,WDtUjDH,UAAUC,OAAS,CCuUhC,CAKA,OAAAwF,GACE,MAAe,CAAEzF,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,WDnUjDA,UAAUF,OAAS,CCoUhC,CAKA,YAAAyF,GACE,MAAMrF,EDjUD,CAAEL,UAAW,GAAIG,UAAW,ICkUjCkB,KAAKrB,UAAYK,EAASL,UAC1BqB,KAAKlB,UAAYE,EAASF,UAC1BkB,MAAKJ,EAAqB,IAC5B,CAKA,YAAA0E,GACE,MAAO,IAAItE,KAAKrB,UAClB,CAKA,YAAA4F,GACE,MAAO,IAAIvE,KAAKlB,UAClB"}
@@ -1,2 +1,2 @@
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),this.gridElement.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"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_visibility={},e.TbwGrid)}(this,function(e,t){"use strict";function i(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}class r extends t.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),this.gridElement.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 t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.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,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(r.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const r=document.createElement("button");return r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(r),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=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(i,t,e);const s=new Map;for(const o of l)for(const e of o.fields)s.set(e,o);const n=this.computeFragments(i,s);for(const o of n)if(o.group)this.renderGroupSection(o.group,o.columns,t,e);else{const r=i.indexOf(o.columns[0]);e.appendChild(this.createColumnRow(o.columns[0],r,t,e))}}computeFragments(e,t){const i=[];let r=null,l=[];for(const s of e){const e=t.get(s.field)??null;e&&r&&e.id===r.id?l.push(s):(l.length>0&&i.push({group:r,columns:l}),r=e,l=[s])}return l.length>0&&i.push({group:r,columns:l}),i}renderGroupSection(e,t,i,r){const l=t.map(e=>e.field),s=document.createElement("div");s.className="tbw-visibility-group-header",s.setAttribute("data-group-id",e.id),i&&(s.draggable=!0,s.classList.add("reorderable"),this.setupGroupDragListeners(s,e,l,r));const n=document.createElement("label");n.className="tbw-visibility-label";const o=document.createElement("input");o.type="checkbox";const d=t.filter(e=>e.visible).length,a=t.every(e=>e.lockVisible);d===t.length?(o.checked=!0,o.indeterminate=!1):0===d?(o.checked=!1,o.indeterminate=!1):(o.checked=!1,o.indeterminate=!0),o.disabled=a,o.addEventListener("change",()=>{const e=o.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(r),0)});const g=document.createElement("span");if(g.textContent=e.label,n.appendChild(o),n.appendChild(g),s.appendChild(n),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,this.resolveIcon("dragHandle")),e.title="Drag to reorder group",s.insertBefore(e,n)}r.appendChild(s);const c=this.grid.getAllColumns().filter(e=>!e.utility);for(const u of t){const e=c.findIndex(e=>e.field===u.field),t=this.createColumnRow(u,e,i,r);t.classList.add("tbw-visibility-row--grouped"),r.appendChild(t)}}renderFlatColumnList(e,t,i){const r=this.grid.getAllColumns().filter(e=>!e.utility);for(const l of e){const e=r.findIndex(e=>e.field===l.field);i.appendChild(this.createColumnRow(l,e,t,i))}}createColumnRow(e,t,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(t)),r&&i(e)&&(n.draggable=!0,n.classList.add("reorderable"),this.setupDragListeners(n,e.field,t,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&&i(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,t,i,r){e.addEventListener("dragstart",l=>{this.isDragging=!0,this.draggedGroupId=t.id,this.draggedGroupFields=[...i],this.draggedField=null,this.draggedIndex=null,l.dataTransfer&&(l.dataTransfer.effectAllowed="move",l.dataTransfer.setData("text/plain",`group:${t.id}`)),e.classList.add("dragging"),r.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&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(r)}),e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length===i.length&&this.draggedGroupFields.every(e=>i.includes(e)))return;if(!this.draggedGroupId)return;const l=e.getBoundingClientRect(),s=l.top+l.height/2,n=t.clientY<s;this.clearDragClasses(r),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",t=>{if(t.preventDefault(),!this.isDragging||!this.draggedGroupId)return;if(this.draggedGroupFields.length===i.length&&this.draggedGroupFields.every(e=>i.includes(e)))return;const r=e.getBoundingClientRect(),l=t.clientY<r.top+r.height/2;this.executeGroupDrop(this.draggedGroupFields,i,l)})}executeGroupDrop(e,t,i){const r=this.grid.getAllColumns().map(e=>e.field),l=r.filter(t=>!e.includes(t)),s=i?t[0]:t[t.length-1],n=l.indexOf(s);if(-1===n)return;const o=i?n:n+1,d=r.filter(t=>e.includes(t));l.splice(o,0,...d);const a=this.grid.getPluginByName?.("reorder");a?.setColumnOrder&&a.gridElement?a.setColumnOrder(l):this.grid.setColumnOrder(l),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,t,i,r){e.addEventListener("dragstart",r=>{this.isDragging=!0,this.draggedField=t,this.draggedIndex=i,this.draggedGroupId=null,this.draggedGroupFields=[],r.dataTransfer&&(r.dataTransfer.effectAllowed="move",r.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(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===t)return;const s=e.getBoundingClientRect(),n=s.top+s.height/2;this.dropIndex=l.clientY<n?i:i+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 t=e.getAttribute("data-field");t&&this.draggedGroupFields.includes(t)&&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",i=>{if(i.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const r=e.getBoundingClientRect(),l=i.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[t],l)}const r=this.draggedField,l=this.draggedIndex,s=this.dropIndex;if(null===r||null===l||null===s)return;const n=s>l?s-1:s;if(n!==l){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[n]?.field,s={field:r,fromIndex:l,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",s)}})}}e.VisibilityPlugin=r,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=visibility.umd.js.map