@toolbox-web/grid 1.25.0 → 1.25.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) 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 +18 -2
  6. package/lib/core/internal/diagnostics.d.ts +164 -0
  7. package/lib/core/internal/sorting.d.ts +53 -4
  8. package/lib/core/internal/utils.d.ts +0 -8
  9. package/lib/core/plugin/base-plugin.d.ts +18 -2
  10. package/lib/core/plugin/plugin-manager.d.ts +6 -4
  11. package/lib/core/types.d.ts +3 -2
  12. package/lib/features/registry.js +1 -1
  13. package/lib/features/registry.js.map +1 -1
  14. package/lib/plugins/clipboard/index.js +1 -1
  15. package/lib/plugins/clipboard/index.js.map +1 -1
  16. package/lib/plugins/column-virtualization/index.js +1 -1
  17. package/lib/plugins/column-virtualization/index.js.map +1 -1
  18. package/lib/plugins/context-menu/index.js +1 -1
  19. package/lib/plugins/context-menu/index.js.map +1 -1
  20. package/lib/plugins/editing/index.js +1 -1
  21. package/lib/plugins/editing/index.js.map +1 -1
  22. package/lib/plugins/editing/types.d.ts +3 -1
  23. package/lib/plugins/export/ExportPlugin.d.ts +2 -2
  24. package/lib/plugins/export/index.js +1 -1
  25. package/lib/plugins/export/index.js.map +1 -1
  26. package/lib/plugins/filtering/FilteringPlugin.d.ts +2 -2
  27. package/lib/plugins/filtering/index.js +1 -1
  28. package/lib/plugins/filtering/index.js.map +1 -1
  29. package/lib/plugins/grouping-columns/grouping-columns.d.ts +15 -1
  30. package/lib/plugins/grouping-columns/index.d.ts +1 -0
  31. package/lib/plugins/grouping-columns/index.js +1 -1
  32. package/lib/plugins/grouping-columns/index.js.map +1 -1
  33. package/lib/plugins/grouping-columns/types.d.ts +98 -8
  34. package/lib/plugins/grouping-rows/GroupingRowsPlugin.d.ts +2 -2
  35. package/lib/plugins/grouping-rows/index.js +2 -2
  36. package/lib/plugins/grouping-rows/index.js.map +1 -1
  37. package/lib/plugins/master-detail/index.js +1 -1
  38. package/lib/plugins/master-detail/index.js.map +1 -1
  39. package/lib/plugins/multi-sort/MultiSortPlugin.d.ts +2 -2
  40. package/lib/plugins/multi-sort/index.js +1 -1
  41. package/lib/plugins/multi-sort/index.js.map +1 -1
  42. package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts +2 -2
  43. package/lib/plugins/pinned-columns/index.js +1 -1
  44. package/lib/plugins/pinned-columns/index.js.map +1 -1
  45. package/lib/plugins/pinned-rows/index.js +1 -1
  46. package/lib/plugins/pinned-rows/index.js.map +1 -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/PrintPlugin.d.ts +2 -1
  50. package/lib/plugins/print/index.js +1 -1
  51. package/lib/plugins/print/index.js.map +1 -1
  52. package/lib/plugins/print/print-isolated.d.ts +2 -1
  53. package/lib/plugins/reorder-columns/ReorderPlugin.d.ts +2 -2
  54. package/lib/plugins/reorder-columns/index.js +1 -1
  55. package/lib/plugins/reorder-columns/index.js.map +1 -1
  56. package/lib/plugins/reorder-rows/RowReorderPlugin.d.ts +2 -2
  57. package/lib/plugins/reorder-rows/index.js +1 -1
  58. package/lib/plugins/reorder-rows/index.js.map +1 -1
  59. package/lib/plugins/responsive/index.js +1 -1
  60. package/lib/plugins/responsive/index.js.map +1 -1
  61. package/lib/plugins/selection/index.js +1 -1
  62. package/lib/plugins/selection/index.js.map +1 -1
  63. package/lib/plugins/server-side/index.js +1 -1
  64. package/lib/plugins/server-side/index.js.map +1 -1
  65. package/lib/plugins/tree/TreePlugin.d.ts +2 -2
  66. package/lib/plugins/tree/index.js +1 -1
  67. package/lib/plugins/tree/index.js.map +1 -1
  68. package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts +2 -2
  69. package/lib/plugins/undo-redo/index.js +1 -1
  70. package/lib/plugins/undo-redo/index.js.map +1 -1
  71. package/lib/plugins/visibility/VisibilityPlugin.d.ts +2 -2
  72. package/lib/plugins/visibility/index.js +1 -1
  73. package/lib/plugins/visibility/index.js.map +1 -1
  74. package/package.json +1 -1
  75. package/umd/grid.all.umd.js +1 -1
  76. package/umd/grid.all.umd.js.map +1 -1
  77. package/umd/grid.umd.js +1 -1
  78. package/umd/grid.umd.js.map +1 -1
  79. package/umd/plugins/clipboard.umd.js +1 -1
  80. package/umd/plugins/clipboard.umd.js.map +1 -1
  81. package/umd/plugins/context-menu.umd.js +1 -1
  82. package/umd/plugins/context-menu.umd.js.map +1 -1
  83. package/umd/plugins/editing.umd.js +1 -1
  84. package/umd/plugins/editing.umd.js.map +1 -1
  85. package/umd/plugins/export.umd.js.map +1 -1
  86. package/umd/plugins/filtering.umd.js.map +1 -1
  87. package/umd/plugins/grouping-columns.umd.js +1 -1
  88. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  89. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  90. package/umd/plugins/multi-sort.umd.js.map +1 -1
  91. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  92. package/umd/plugins/print.umd.js +1 -1
  93. package/umd/plugins/print.umd.js.map +1 -1
  94. package/umd/plugins/reorder-columns.umd.js.map +1 -1
  95. package/umd/plugins/reorder-rows.umd.js.map +1 -1
  96. package/umd/plugins/responsive.umd.js +1 -1
  97. package/umd/plugins/responsive.umd.js.map +1 -1
  98. package/umd/plugins/tree.umd.js.map +1 -1
  99. package/umd/plugins/undo-redo.umd.js +1 -1
  100. package/umd/plugins/undo-redo.umd.js.map +1 -1
  101. package/umd/plugins/visibility.umd.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"responsive.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/responsive/ResponsivePlugin.ts"],"sourcesContent":["/**\n * Responsive Plugin\n *\n * Transforms the grid from tabular layout to a card/list layout when the grid\n * width falls below a configurable breakpoint. This enables grids to work in\n * narrow containers (split-pane UIs, mobile viewports, dashboard widgets).\n *\n * ## Installation\n *\n * ```ts\n * import { ResponsivePlugin } from '@toolbox-web/grid/plugins/responsive';\n *\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * ## How It Works\n *\n * 1. ResizeObserver monitors the grid element's width\n * 2. When `width < breakpoint`, adds `data-responsive` attribute to grid\n * 3. CSS transforms cells from horizontal to vertical layout\n * 4. Each cell displays \"Header: Value\" using CSS `::before` pseudo-element\n *\n * @see [Responsive Demo](?path=/story/grid-plugins-responsive--default)\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, type GridElement, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport styles from './responsive.css?inline';\nimport type { BreakpointConfig, HiddenColumnConfig, ResponsiveChangeDetail, ResponsivePluginConfig } from './types';\n\n/**\n * Responsive Plugin for tbw-grid\n *\n * Adds automatic card layout mode when the grid width falls below a configurable\n * breakpoint. Perfect for responsive designs, split-pane UIs, and mobile viewports.\n *\n * @template T The row data type\n *\n * @example\n * ```ts\n * // Basic usage - switch to card layout below 500px\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Hide less important columns in card mode\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 600,\n * hiddenColumns: ['createdAt', 'updatedAt'],\n * }),\n * ],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Custom card renderer for advanced layouts\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 400,\n * cardRenderer: (row) => {\n * const card = document.createElement('div');\n * card.className = 'custom-card';\n * card.innerHTML = `<strong>${row.name}</strong><br>${row.email}`;\n * return card;\n * },\n * }),\n * ],\n * };\n * ```\n */\nexport class ResponsivePlugin<T = unknown> extends BaseGridPlugin<ResponsivePluginConfig<T>> {\n readonly name = 'responsive';\n override readonly version = '1.0.0';\n override readonly styles = styles;\n\n /**\n * Plugin manifest declaring incompatibilities with other plugins.\n */\n static override readonly manifest: PluginManifest = {\n incompatibleWith: [\n {\n name: 'groupingRows',\n reason:\n 'Responsive card layout does not yet support row grouping. ' +\n 'The variable row heights (cards vs group headers) cause scroll calculation issues.',\n },\n ],\n queries: [\n {\n type: 'isCardMode',\n description: 'Returns whether the grid is currently in responsive card mode',\n },\n ],\n };\n\n #resizeObserver?: ResizeObserver;\n #isResponsive = false;\n #debounceTimer?: ReturnType<typeof setTimeout>;\n #warnedAboutMissingBreakpoint = false;\n #currentWidth = 0;\n /** Set of column fields to completely hide */\n #hiddenColumnSet: Set<string> = new Set();\n /** Set of column fields to show value only (no header label) */\n #valueOnlyColumnSet: Set<string> = new Set();\n /** Currently active breakpoint, or null if none */\n #activeBreakpoint: BreakpointConfig | null = null;\n /** Sorted breakpoints from largest to smallest */\n #sortedBreakpoints: BreakpointConfig[] = [];\n\n /** Typed internal grid accessor — centralizes the single required cast. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if currently in responsive mode.\n * @returns `true` if the grid is in card layout mode\n */\n isResponsive(): boolean {\n return this.#isResponsive;\n }\n\n /**\n * Force responsive mode regardless of width.\n * Useful for testing or manual control.\n * @param enabled - Whether to enable responsive mode\n */\n setResponsive(enabled: boolean): void {\n if (enabled !== this.#isResponsive) {\n this.#isResponsive = enabled;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: enabled,\n width: this.#currentWidth,\n breakpoint: this.config.breakpoint ?? 0,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Update breakpoint dynamically.\n * @param width - New breakpoint width in pixels\n */\n setBreakpoint(width: number): void {\n this.config.breakpoint = width;\n this.#checkBreakpoint(this.#currentWidth);\n }\n\n /**\n * Set a custom card renderer.\n * This allows framework adapters to provide template-based renderers at runtime.\n * @param renderer - The card renderer function, or undefined to use default\n */\n setCardRenderer(renderer: ResponsivePluginConfig<T>['cardRenderer']): void {\n this.config.cardRenderer = renderer;\n // If already in responsive mode, trigger a re-render to apply the new renderer\n if (this.#isResponsive) {\n this.requestRender();\n }\n }\n\n /**\n * Get current grid width.\n * @returns Width of the grid element in pixels\n */\n getWidth(): number {\n return this.#currentWidth;\n }\n\n /**\n * Get the currently active breakpoint config (multi-breakpoint mode only).\n * @returns The active BreakpointConfig, or null if no breakpoint is active\n */\n getActiveBreakpoint(): BreakpointConfig | null {\n return this.#activeBreakpoint;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Parse light DOM configuration first (may update this.config)\n this.#parseLightDomCard();\n\n // Build hidden column sets from config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n\n // Sort breakpoints from largest to smallest for evaluation\n if (this.config.breakpoints?.length) {\n this.#sortedBreakpoints = [...this.config.breakpoints].sort((a, b) => b.maxWidth - a.maxWidth);\n }\n\n // Observe the grid element itself (not internal viewport)\n // This captures the container width including when shell panels open/close\n this.#resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width ?? 0;\n this.#currentWidth = width;\n\n // Debounce to avoid thrashing during resize drag\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = setTimeout(() => {\n this.#checkBreakpoint(width);\n }, this.config.debounceMs ?? 100);\n });\n\n this.#resizeObserver.observe(this.gridElement);\n }\n\n // #region Light DOM Parsing\n\n /**\n * Parse `<tbw-grid-responsive-card>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-responsive-card breakpoint=\"500\" card-row-height=\"80\">\n * <div class=\"custom-card\">\n * <strong>{{ row.name }}</strong>\n * <span>{{ row.email }}</span>\n * </div>\n * </tbw-grid-responsive-card>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `breakpoint`: number - Width threshold for responsive mode\n * - `card-row-height`: number | 'auto' - Card height (default: 'auto')\n * - `hidden-columns`: string - Comma-separated fields to hide\n * - `hide-header`: 'true' | 'false' - Hide header row (default: 'true')\n * - `debounce-ms`: number - Resize debounce delay (default: 100)\n */\n #parseLightDomCard(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const cardEl = gridEl.querySelector('tbw-grid-responsive-card');\n if (!cardEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., React adapter intercepts for JSX rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseResponsiveCardElement) {\n const adapterRenderer = adapter.parseResponsiveCardElement(cardEl);\n if (adapterRenderer) {\n this.config = { ...this.config, cardRenderer: adapterRenderer };\n // Continue to parse attributes even if adapter provides renderer\n }\n }\n\n // Parse attributes for configuration\n const breakpointAttr = cardEl.getAttribute('breakpoint');\n const cardRowHeightAttr = cardEl.getAttribute('card-row-height');\n const hiddenColumnsAttr = cardEl.getAttribute('hidden-columns');\n const hideHeaderAttr = cardEl.getAttribute('hide-header');\n const debounceMsAttr = cardEl.getAttribute('debounce-ms');\n\n const configUpdates: Partial<ResponsivePluginConfig<T>> = {};\n\n if (breakpointAttr !== null) {\n const breakpoint = parseInt(breakpointAttr, 10);\n if (!isNaN(breakpoint)) {\n configUpdates.breakpoint = breakpoint;\n }\n }\n\n if (cardRowHeightAttr !== null) {\n configUpdates.cardRowHeight = cardRowHeightAttr === 'auto' ? 'auto' : parseInt(cardRowHeightAttr, 10);\n }\n\n if (hiddenColumnsAttr !== null) {\n // Parse comma-separated field names\n configUpdates.hiddenColumns = hiddenColumnsAttr\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n if (hideHeaderAttr !== null) {\n configUpdates.hideHeader = hideHeaderAttr !== 'false';\n }\n\n if (debounceMsAttr !== null) {\n const debounceMs = parseInt(debounceMsAttr, 10);\n if (!isNaN(debounceMs)) {\n configUpdates.debounceMs = debounceMs;\n }\n }\n\n // Get template content from innerHTML (only if no renderer already set)\n const templateHTML = cardEl.innerHTML.trim();\n if (templateHTML && !this.config.cardRenderer && !adapter?.parseResponsiveCardElement) {\n // Create a template-based renderer using the inner HTML\n configUpdates.cardRenderer = (row: T): HTMLElement => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row: row as Record<string, unknown> });\n // Sanitize the result to prevent XSS\n const sanitized = sanitizeHTML(evaluated);\n const container = document.createElement('div');\n container.className = 'tbw-responsive-card-content';\n container.innerHTML = sanitized;\n return container;\n };\n }\n\n // Merge updates into config (light DOM values override constructor config)\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n /**\n * Build the hidden and value-only column sets from config.\n */\n #buildHiddenColumnSets(hiddenColumns?: HiddenColumnConfig[]): void {\n this.#hiddenColumnSet.clear();\n this.#valueOnlyColumnSet.clear();\n\n if (!hiddenColumns) return;\n\n for (const col of hiddenColumns) {\n if (typeof col === 'string') {\n this.#hiddenColumnSet.add(col);\n } else if (col.showValue) {\n this.#valueOnlyColumnSet.add(col.field);\n } else {\n this.#hiddenColumnSet.add(col.field);\n }\n }\n }\n\n override detach(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = undefined;\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = undefined;\n\n // Clean up attribute\n if (this.gridElement) {\n this.gridElement.removeAttribute('data-responsive');\n }\n\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isCardMode') {\n return this.#isResponsive;\n }\n return undefined;\n }\n\n /**\n * Apply hidden and value-only columns.\n * In legacy mode (single breakpoint), only applies when in responsive mode.\n * In multi-breakpoint mode, applies whenever there's an active breakpoint.\n */\n override afterRender(): void {\n // Measure card height for virtualization calculations\n this.#measureCardHeightFromDOM();\n\n // In single breakpoint mode, only apply when responsive\n // In multi-breakpoint mode, apply when there's an active breakpoint\n const shouldApply = this.#sortedBreakpoints.length > 0 ? this.#activeBreakpoint !== null : this.#isResponsive;\n\n if (!shouldApply) {\n return;\n }\n\n const hasHiddenColumns = this.#hiddenColumnSet.size > 0;\n const hasValueOnlyColumns = this.#valueOnlyColumnSet.size > 0;\n\n if (!hasHiddenColumns && !hasValueOnlyColumns) {\n return;\n }\n\n // Mark cells for hidden columns and value-only columns\n const cells = this.gridElement.querySelectorAll('.cell[data-field]');\n for (const cell of cells) {\n const field = cell.getAttribute('data-field');\n if (!field) continue;\n\n // Apply hidden attribute\n if (this.#hiddenColumnSet.has(field)) {\n cell.setAttribute('data-responsive-hidden', '');\n cell.removeAttribute('data-responsive-value-only');\n }\n // Apply value-only attribute (shows value without header label)\n else if (this.#valueOnlyColumnSet.has(field)) {\n cell.setAttribute('data-responsive-value-only', '');\n cell.removeAttribute('data-responsive-hidden');\n }\n // Clear any previous responsive attributes\n else {\n cell.removeAttribute('data-responsive-hidden');\n cell.removeAttribute('data-responsive-value-only');\n }\n }\n }\n\n /**\n * Check if width has crossed any breakpoint threshold.\n * Handles both single breakpoint (legacy) and multi-breakpoint modes.\n */\n #checkBreakpoint(width: number): void {\n // Multi-breakpoint mode\n if (this.#sortedBreakpoints.length > 0) {\n this.#checkMultiBreakpoint(width);\n return;\n }\n\n // Legacy single breakpoint mode\n const breakpoint = this.config.breakpoint ?? 0;\n\n // Warn once if breakpoint not configured (0 means never responsive)\n if (breakpoint === 0 && !this.#warnedAboutMissingBreakpoint) {\n this.#warnedAboutMissingBreakpoint = true;\n console.warn(\n \"[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count.\",\n );\n }\n\n const shouldBeResponsive = breakpoint > 0 && width < breakpoint;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: shouldBeResponsive,\n width,\n breakpoint,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Check breakpoints in multi-breakpoint mode.\n * Evaluates breakpoints from largest to smallest, applying the first match.\n */\n #checkMultiBreakpoint(width: number): void {\n // Find the active breakpoint (first one where width <= maxWidth)\n // Since sorted largest to smallest, we find the largest matching breakpoint\n let newActiveBreakpoint: BreakpointConfig | null = null;\n\n for (const bp of this.#sortedBreakpoints) {\n if (width <= bp.maxWidth) {\n newActiveBreakpoint = bp;\n // Continue to find the most specific (smallest) matching breakpoint\n }\n }\n\n // Check if breakpoint changed\n const breakpointChanged = newActiveBreakpoint !== this.#activeBreakpoint;\n\n if (breakpointChanged) {\n this.#activeBreakpoint = newActiveBreakpoint;\n\n // Update hidden column sets from active breakpoint\n if (newActiveBreakpoint?.hiddenColumns) {\n this.#buildHiddenColumnSets(newActiveBreakpoint.hiddenColumns);\n } else {\n // Fall back to top-level hiddenColumns config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n }\n\n // Determine if we should be in card layout\n const shouldBeResponsive = newActiveBreakpoint?.cardLayout === true;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n }\n\n // Emit event for any breakpoint change\n this.emit('responsive-change', {\n isResponsive: this.#isResponsive,\n width,\n breakpoint: newActiveBreakpoint?.maxWidth ?? 0,\n } satisfies ResponsiveChangeDetail);\n\n this.requestRender();\n }\n }\n\n /** Original row height before entering responsive mode, for restoration on exit */\n #originalRowHeight?: number;\n\n /**\n * Apply the responsive state to the grid element.\n * Handles scroll reset when entering responsive mode and row height restoration on exit.\n */\n #applyResponsiveState(): void {\n this.gridElement.toggleAttribute('data-responsive', this.#isResponsive);\n\n // Apply animation attribute if enabled (default: true)\n const animate = this.config.animate !== false;\n this.gridElement.toggleAttribute('data-responsive-animate', animate);\n\n // Set custom animation duration if provided\n if (this.config.animationDuration) {\n this.gridElement.style.setProperty('--tbw-responsive-duration', `${this.config.animationDuration}ms`);\n }\n\n // Cast to internal type for virtualization access\n const internalGrid = this.#internalGrid;\n\n if (this.#isResponsive) {\n // Store original row height before responsive mode changes it\n if (internalGrid._virtualization) {\n this.#originalRowHeight = internalGrid._virtualization.rowHeight;\n }\n\n // Reset horizontal scroll position when entering responsive mode\n // The CSS hides overflow but doesn't reset the scroll position\n const scrollArea = this.gridElement.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (scrollArea) {\n scrollArea.scrollLeft = 0;\n }\n } else {\n // Exiting responsive mode - clean up inline styles set by renderRow\n // The rows are reused from the pool, so we need to remove the card-specific styles\n const rows = this.gridElement.querySelectorAll('.data-grid-row');\n for (const row of rows) {\n (row as HTMLElement).style.height = '';\n row.classList.remove('responsive-card');\n }\n\n // Restore original row height\n if (this.#originalRowHeight && this.#originalRowHeight > 0 && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = this.#originalRowHeight;\n this.#originalRowHeight = undefined;\n }\n\n // Clear cached measurements so they're remeasured fresh when re-entering responsive mode\n // Without this, stale measurements cause incorrect height calculations after scrolling\n this.#measuredCardHeight = undefined;\n this.#measuredGroupRowHeight = undefined;\n this.#lastCardRowCount = undefined;\n }\n }\n\n /**\n * Custom row rendering when cardRenderer is provided and in responsive mode.\n *\n * When a cardRenderer is configured, this hook takes over row rendering to display\n * the custom card layout instead of the default cell structure.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if rendered (prevents default), `void` for default rendering\n */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean | void {\n // Only override when in responsive mode AND cardRenderer is provided\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return; // Let default rendering proceed\n }\n\n // Skip group rows from GroupingRowsPlugin - they have special structure\n // and should use their own renderer\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return; // Let GroupingRowsPlugin handle group row rendering\n }\n\n // Clear existing content\n rowEl.replaceChildren();\n\n // Call user's cardRenderer to get custom content\n const cardContent = this.config.cardRenderer(row as T, rowIndex);\n\n // Reset className - clears any stale classes from previous use (e.g., 'group-row' from recycled element)\n // This follows the same pattern as GroupingRowsPlugin which sets className explicitly\n rowEl.className = 'data-grid-row responsive-card';\n\n // Handle card row height — when a numeric height is configured, use the effective\n // height from #getCardHeight() which incorporates DOM measurement after first render.\n // This keeps inline height in sync with the position cache used for virtualization.\n const configuredHeight = this.config.cardRowHeight;\n if (configuredHeight === 'auto' || configuredHeight === undefined) {\n rowEl.style.height = 'auto';\n } else {\n rowEl.style.height = `${this.#getCardHeight()}px`;\n }\n\n // Append the custom card content\n rowEl.appendChild(cardContent);\n\n return true; // We handled rendering\n }\n\n /**\n * Handle keyboard navigation in responsive mode.\n *\n * In responsive mode, the visual layout is inverted:\n * - Cells are stacked vertically within each \"card\" (row)\n * - DOWN/UP visually moves within the card (between fields)\n * - Page Down/Page Up or Ctrl+Down/Up moves between cards\n *\n * For custom cardRenderers, keyboard navigation is disabled entirely\n * since the implementor controls the card content and should handle\n * navigation via their own event handlers.\n *\n * @returns `true` if the event was handled and default behavior should be prevented\n */\n override onKeyDown(e: KeyboardEvent): boolean {\n if (!this.#isResponsive) {\n return false;\n }\n\n // If custom cardRenderer is provided, disable grid's keyboard navigation\n // The implementor is responsible for their own navigation\n if (this.config.cardRenderer) {\n const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];\n if (navKeys.includes(e.key)) {\n // Let the event bubble - implementor can handle it\n return false;\n }\n }\n\n // Swap arrow key behavior for CSS-only responsive mode\n // In card layout, cells are stacked vertically:\n // Card 1: Card 2:\n // ID: 1 ID: 2\n // Name: Alice Name: Bob <- ArrowRight goes here\n // Dept: Eng Dept: Mkt\n // ↓ ArrowDown goes here\n //\n // ArrowDown/Up = move within card (change column/field)\n // ArrowRight/Left = move between cards (change row)\n const maxRow = this.rows.length - 1;\n const maxCol = this.visibleColumns.length - 1;\n\n switch (e.key) {\n case 'ArrowDown':\n // Move down WITHIN card (to next field/column)\n if (this.grid._focusCol < maxCol) {\n this.grid._focusCol += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At bottom of card - optionally move to next card's first field\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n this.grid._focusCol = 0;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowUp':\n // Move up WITHIN card (to previous field/column)\n if (this.grid._focusCol > 0) {\n this.grid._focusCol -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At top of card - optionally move to previous card's last field\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n this.grid._focusCol = maxCol;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowRight':\n // Move to NEXT card (same field)\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowLeft':\n // Move to PREVIOUS card (same field)\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n }\n\n return false;\n }\n\n // ============================================\n // Variable Height Support for Mixed Row Types\n // ============================================\n\n /** Measured card height from DOM for virtualization calculations */\n #measuredCardHeight?: number;\n\n /** Measured group row height from DOM for virtualization calculations */\n #measuredGroupRowHeight?: number;\n\n /** Last known card row count for detecting changes (e.g., group expand/collapse) */\n #lastCardRowCount?: number;\n\n /**\n * Get the effective card height for virtualization calculations.\n * Prioritizes DOM-measured height (actual rendered size) over config,\n * since content can overflow the configured height.\n */\n #getCardHeight(): number {\n // Prefer measured height - it reflects actual rendered size including overflow\n if (this.#measuredCardHeight && this.#measuredCardHeight > 0) {\n return this.#measuredCardHeight;\n }\n // Fall back to explicit config\n const configHeight = this.config.cardRowHeight;\n if (typeof configHeight === 'number' && configHeight > 0) {\n return configHeight;\n }\n // Default fallback\n return 80;\n }\n\n /**\n * Get the effective group row height for virtualization calculations.\n * Uses DOM-measured height, falling back to original row height.\n */\n #getGroupRowHeight(): number {\n if (this.#measuredGroupRowHeight && this.#measuredGroupRowHeight > 0) {\n return this.#measuredGroupRowHeight;\n }\n // Fall back to original row height (before responsive mode)\n return this.#originalRowHeight ?? 28;\n }\n\n /**\n * Check if there are any group rows in the current dataset.\n * Used to determine if we have mixed row heights.\n */\n #hasGroupRows(): boolean {\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Count group rows and card rows in the current dataset.\n */\n #countRowTypes(): { groupCount: number; cardCount: number } {\n let groupCount = 0;\n let cardCount = 0;\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n groupCount++;\n } else {\n cardCount++;\n }\n }\n return { groupCount, cardCount };\n }\n\n /**\n * Return total extra height contributed by mixed row heights.\n * This is called by the grid's virtualization system to adjust scrollbar height.\n *\n * The grid calculates: totalRows * baseRowHeight + pluginExtraHeight\n *\n * For mixed layouts (groups + cards), we need to report the difference between\n * actual heights and what the base calculation assumes:\n * - Extra for groups: groupCount * (groupHeight - baseHeight)\n * - Extra for cards: cardCount * (cardHeight - baseHeight)\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeight(): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types (groups + cards)\n // If all rows are cards, we update the virtualization row height instead\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const { groupCount, cardCount } = this.#countRowTypes();\n\n // Calculate extra height for both row types\n const groupExtra = groupCount * Math.max(0, groupHeight - baseHeight);\n const cardExtra = cardCount * Math.max(0, cardHeight - baseHeight);\n\n return groupExtra + cardExtra;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * Used by virtualization to correctly calculate scroll positions.\n *\n * Like getExtraHeight, this accounts for both group and card row heights.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const groupHeightDiff = Math.max(0, groupHeight - baseHeight);\n const cardHeightDiff = Math.max(0, cardHeight - baseHeight);\n\n // Count group rows and card rows before the given index\n let groupsBefore = 0;\n let cardsBefore = 0;\n const rows = this.rows;\n const maxIndex = Math.min(beforeRowIndex, rows.length);\n\n for (let i = 0; i < maxIndex; i++) {\n if ((rows[i] as { __isGroupRow?: boolean }).__isGroupRow) {\n groupsBefore++;\n } else {\n cardsBefore++;\n }\n }\n\n return groupsBefore * groupHeightDiff + cardsBefore * cardHeightDiff;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.#internalGrid;\n const hasGroups = this.#hasGroupRows();\n\n // Check if card row count changed (e.g., group expanded/collapsed)\n const currentCardRowCount = this.#countCardRows();\n if (currentCardRowCount !== this.#lastCardRowCount) {\n this.#lastCardRowCount = currentCardRowCount;\n needsRefresh = true;\n }\n\n // Measure actual group row height from DOM (for mixed layouts)\n if (hasGroups) {\n const groupRow = this.gridElement.querySelector('.data-grid-row.group-row') as HTMLElement | null;\n if (groupRow) {\n const height = groupRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredGroupRowHeight) {\n this.#measuredGroupRowHeight = height;\n needsRefresh = true;\n }\n }\n }\n\n // Measure actual card height from DOM\n const cardRow = this.gridElement.querySelector('.data-grid-row.responsive-card') as HTMLElement | null;\n if (cardRow) {\n const height = cardRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredCardHeight) {\n this.#measuredCardHeight = height;\n needsRefresh = true;\n\n // For uniform card layouts (no groups), update virtualization row height directly\n // This ensures proper row recycling and translateY calculations\n if (!hasGroups && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = height;\n }\n }\n }\n\n // Defer virtualization refresh to avoid nested render cycles\n // This is called from afterRender, so we can't call refreshVirtualWindow synchronously\n // Use scheduler's VIRTUALIZATION phase to batch properly and avoid duplicate afterRender calls\n if (needsRefresh && !this.#pendingRefresh) {\n this.#pendingRefresh = true;\n queueMicrotask(() => {\n this.#pendingRefresh = false;\n // Only refresh if still attached and in responsive mode\n if (this.grid && this.#isResponsive) {\n // Request virtualization phase through grid's public API\n // This goes through the scheduler which batches and handles afterRender properly\n this.#internalGrid.refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","name","version","styles","static","incompatibleWith","reason","queries","type","description","resizeObserver","isResponsive","debounceTimer","warnedAboutMissingBreakpoint","currentWidth","hiddenColumnSet","Set","valueOnlyColumnSet","activeBreakpoint","sortedBreakpoints","internalGrid","this","grid","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","requestRender","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","getWidth","getActiveBreakpoint","attach","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","cardEl","querySelector","adapter","__frameworkAdapter","parseResponsiveCardElement","adapterRenderer","breakpointAttr","getAttribute","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","parseInt","isNaN","cardRowHeight","split","map","s","trim","filter","hideHeader","templateHTML","innerHTML","row","evaluated","evalTemplateString","value","sanitized","sanitizeHTML","container","document","createElement","className","Object","keys","clear","col","add","showValue","field","detach","disconnect","removeAttribute","handleQuery","query","afterRender","measureCardHeightFromDOM","hasHiddenColumns","size","hasValueOnlyColumns","cells","querySelectorAll","cell","has","setAttribute","checkMultiBreakpoint","console","warn","shouldBeResponsive","newActiveBreakpoint","bp","cardLayout","originalRowHeight","toggleAttribute","animate","animationDuration","style","setProperty","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","configuredHeight","getCardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","configHeight","getGroupRowHeight","hasGroupRows","countRowTypes","groupCount","cardCount","getExtraHeight","baseHeight","groupHeight","cardHeight","Math","max","getExtraHeightBefore","beforeRowIndex","groupHeightDiff","cardHeightDiff","groupsBefore","cardsBefore","maxIndex","min","i","getRowHeight","_index","countCardRows","count","pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","getBoundingClientRect","cardRow","queueMicrotask","refreshVirtualWindow"],"mappings":"0fAiFO,MAAMA,UAAsCC,EAAAA,eACxCC,KAAO,aACEC,QAAU,QACVC,8hHAKlBC,gBAAoD,CAClDC,iBAAkB,CAChB,CACEJ,KAAM,eACNK,OACE,iJAINC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,OAAuCD,IAEvCE,GAA6C,KAE7CC,GAAyC,GAGzC,KAAIC,GACF,OAAOC,KAAKC,IACd,CAMA,YAAAX,GACE,OAAOU,MAAKV,CACd,CAOA,aAAAY,CAAcC,GACRA,IAAYH,MAAKV,IACnBU,MAAKV,EAAgBa,EACrBH,MAAKI,IACLJ,KAAKK,KAAK,oBAAqB,CAC7Bf,aAAca,EACdG,MAAON,MAAKP,EACZc,WAAYP,KAAKQ,OAAOD,YAAc,IAExCP,KAAKS,gBAET,CAMA,aAAAC,CAAcJ,GACZN,KAAKQ,OAAOD,WAAaD,EACzBN,MAAKW,EAAiBX,MAAKP,EAC7B,CAOA,eAAAmB,CAAgBC,GACdb,KAAKQ,OAAOM,aAAeD,EAEvBb,MAAKV,GACPU,KAAKS,eAET,CAMA,QAAAM,GACE,OAAOf,MAAKP,CACd,CAMA,mBAAAuB,GACE,OAAOhB,MAAKH,CACd,CAES,MAAAoB,CAAOhB,GACdiB,MAAMD,OAAOhB,GAGbD,MAAKmB,IAGLnB,MAAKoB,EAAuBpB,KAAKQ,OAAOa,eAGpCrB,KAAKQ,OAAO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AAKD,EAAc2K,wBAAuB,GAAM,KAIxD"}
1
+ {"version":3,"file":"responsive.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/responsive/ResponsivePlugin.ts"],"sourcesContent":["/**\n * Responsive Plugin\n *\n * Transforms the grid from tabular layout to a card/list layout when the grid\n * width falls below a configurable breakpoint. This enables grids to work in\n * narrow containers (split-pane UIs, mobile viewports, dashboard widgets).\n *\n * ## Installation\n *\n * ```ts\n * import { ResponsivePlugin } from '@toolbox-web/grid/plugins/responsive';\n *\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * ## How It Works\n *\n * 1. ResizeObserver monitors the grid element's width\n * 2. When `width < breakpoint`, adds `data-responsive` attribute to grid\n * 3. CSS transforms cells from horizontal to vertical layout\n * 4. Each cell displays \"Header: Value\" using CSS `::before` pseudo-element\n *\n * @see [Responsive Demo](?path=/story/grid-plugins-responsive--default)\n */\n\nimport { MISSING_BREAKPOINT } from '../../core/internal/diagnostics';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, type GridElement, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport styles from './responsive.css?inline';\nimport type { BreakpointConfig, HiddenColumnConfig, ResponsiveChangeDetail, ResponsivePluginConfig } from './types';\n\n/**\n * Responsive Plugin for tbw-grid\n *\n * Adds automatic card layout mode when the grid width falls below a configurable\n * breakpoint. Perfect for responsive designs, split-pane UIs, and mobile viewports.\n *\n * @template T The row data type\n *\n * @example\n * ```ts\n * // Basic usage - switch to card layout below 500px\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Hide less important columns in card mode\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 600,\n * hiddenColumns: ['createdAt', 'updatedAt'],\n * }),\n * ],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Custom card renderer for advanced layouts\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 400,\n * cardRenderer: (row) => {\n * const card = document.createElement('div');\n * card.className = 'custom-card';\n * card.innerHTML = `<strong>${row.name}</strong><br>${row.email}`;\n * return card;\n * },\n * }),\n * ],\n * };\n * ```\n */\nexport class ResponsivePlugin<T = unknown> extends BaseGridPlugin<ResponsivePluginConfig<T>> {\n readonly name = 'responsive';\n override readonly version = '1.0.0';\n override readonly styles = styles;\n\n /**\n * Plugin manifest declaring incompatibilities with other plugins.\n */\n static override readonly manifest: PluginManifest = {\n incompatibleWith: [\n {\n name: 'groupingRows',\n reason:\n 'Responsive card layout does not yet support row grouping. ' +\n 'The variable row heights (cards vs group headers) cause scroll calculation issues.',\n },\n ],\n queries: [\n {\n type: 'isCardMode',\n description: 'Returns whether the grid is currently in responsive card mode',\n },\n ],\n };\n\n #resizeObserver?: ResizeObserver;\n #isResponsive = false;\n #debounceTimer?: ReturnType<typeof setTimeout>;\n #warnedAboutMissingBreakpoint = false;\n #currentWidth = 0;\n /** Set of column fields to completely hide */\n #hiddenColumnSet: Set<string> = new Set();\n /** Set of column fields to show value only (no header label) */\n #valueOnlyColumnSet: Set<string> = new Set();\n /** Currently active breakpoint, or null if none */\n #activeBreakpoint: BreakpointConfig | null = null;\n /** Sorted breakpoints from largest to smallest */\n #sortedBreakpoints: BreakpointConfig[] = [];\n\n /** Typed internal grid accessor — centralizes the single required cast. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if currently in responsive mode.\n * @returns `true` if the grid is in card layout mode\n */\n isResponsive(): boolean {\n return this.#isResponsive;\n }\n\n /**\n * Force responsive mode regardless of width.\n * Useful for testing or manual control.\n * @param enabled - Whether to enable responsive mode\n */\n setResponsive(enabled: boolean): void {\n if (enabled !== this.#isResponsive) {\n this.#isResponsive = enabled;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: enabled,\n width: this.#currentWidth,\n breakpoint: this.config.breakpoint ?? 0,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Update breakpoint dynamically.\n * @param width - New breakpoint width in pixels\n */\n setBreakpoint(width: number): void {\n this.config.breakpoint = width;\n this.#checkBreakpoint(this.#currentWidth);\n }\n\n /**\n * Set a custom card renderer.\n * This allows framework adapters to provide template-based renderers at runtime.\n * @param renderer - The card renderer function, or undefined to use default\n */\n setCardRenderer(renderer: ResponsivePluginConfig<T>['cardRenderer']): void {\n this.config.cardRenderer = renderer;\n // If already in responsive mode, trigger a re-render to apply the new renderer\n if (this.#isResponsive) {\n this.requestRender();\n }\n }\n\n /**\n * Get current grid width.\n * @returns Width of the grid element in pixels\n */\n getWidth(): number {\n return this.#currentWidth;\n }\n\n /**\n * Get the currently active breakpoint config (multi-breakpoint mode only).\n * @returns The active BreakpointConfig, or null if no breakpoint is active\n */\n getActiveBreakpoint(): BreakpointConfig | null {\n return this.#activeBreakpoint;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Parse light DOM configuration first (may update this.config)\n this.#parseLightDomCard();\n\n // Build hidden column sets from config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n\n // Sort breakpoints from largest to smallest for evaluation\n if (this.config.breakpoints?.length) {\n this.#sortedBreakpoints = [...this.config.breakpoints].sort((a, b) => b.maxWidth - a.maxWidth);\n }\n\n // Observe the grid element itself (not internal viewport)\n // This captures the container width including when shell panels open/close\n this.#resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width ?? 0;\n this.#currentWidth = width;\n\n // Debounce to avoid thrashing during resize drag\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = setTimeout(() => {\n this.#checkBreakpoint(width);\n }, this.config.debounceMs ?? 100);\n });\n\n this.#resizeObserver.observe(this.gridElement);\n }\n\n // #region Light DOM Parsing\n\n /**\n * Parse `<tbw-grid-responsive-card>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-responsive-card breakpoint=\"500\" card-row-height=\"80\">\n * <div class=\"custom-card\">\n * <strong>{{ row.name }}</strong>\n * <span>{{ row.email }}</span>\n * </div>\n * </tbw-grid-responsive-card>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `breakpoint`: number - Width threshold for responsive mode\n * - `card-row-height`: number | 'auto' - Card height (default: 'auto')\n * - `hidden-columns`: string - Comma-separated fields to hide\n * - `hide-header`: 'true' | 'false' - Hide header row (default: 'true')\n * - `debounce-ms`: number - Resize debounce delay (default: 100)\n */\n #parseLightDomCard(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const cardEl = gridEl.querySelector('tbw-grid-responsive-card');\n if (!cardEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., React adapter intercepts for JSX rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseResponsiveCardElement) {\n const adapterRenderer = adapter.parseResponsiveCardElement(cardEl);\n if (adapterRenderer) {\n this.config = { ...this.config, cardRenderer: adapterRenderer };\n // Continue to parse attributes even if adapter provides renderer\n }\n }\n\n // Parse attributes for configuration\n const breakpointAttr = cardEl.getAttribute('breakpoint');\n const cardRowHeightAttr = cardEl.getAttribute('card-row-height');\n const hiddenColumnsAttr = cardEl.getAttribute('hidden-columns');\n const hideHeaderAttr = cardEl.getAttribute('hide-header');\n const debounceMsAttr = cardEl.getAttribute('debounce-ms');\n\n const configUpdates: Partial<ResponsivePluginConfig<T>> = {};\n\n if (breakpointAttr !== null) {\n const breakpoint = parseInt(breakpointAttr, 10);\n if (!isNaN(breakpoint)) {\n configUpdates.breakpoint = breakpoint;\n }\n }\n\n if (cardRowHeightAttr !== null) {\n configUpdates.cardRowHeight = cardRowHeightAttr === 'auto' ? 'auto' : parseInt(cardRowHeightAttr, 10);\n }\n\n if (hiddenColumnsAttr !== null) {\n // Parse comma-separated field names\n configUpdates.hiddenColumns = hiddenColumnsAttr\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n if (hideHeaderAttr !== null) {\n configUpdates.hideHeader = hideHeaderAttr !== 'false';\n }\n\n if (debounceMsAttr !== null) {\n const debounceMs = parseInt(debounceMsAttr, 10);\n if (!isNaN(debounceMs)) {\n configUpdates.debounceMs = debounceMs;\n }\n }\n\n // Get template content from innerHTML (only if no renderer already set)\n const templateHTML = cardEl.innerHTML.trim();\n if (templateHTML && !this.config.cardRenderer && !adapter?.parseResponsiveCardElement) {\n // Create a template-based renderer using the inner HTML\n configUpdates.cardRenderer = (row: T): HTMLElement => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row: row as Record<string, unknown> });\n // Sanitize the result to prevent XSS\n const sanitized = sanitizeHTML(evaluated);\n const container = document.createElement('div');\n container.className = 'tbw-responsive-card-content';\n container.innerHTML = sanitized;\n return container;\n };\n }\n\n // Merge updates into config (light DOM values override constructor config)\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n /**\n * Build the hidden and value-only column sets from config.\n */\n #buildHiddenColumnSets(hiddenColumns?: HiddenColumnConfig[]): void {\n this.#hiddenColumnSet.clear();\n this.#valueOnlyColumnSet.clear();\n\n if (!hiddenColumns) return;\n\n for (const col of hiddenColumns) {\n if (typeof col === 'string') {\n this.#hiddenColumnSet.add(col);\n } else if (col.showValue) {\n this.#valueOnlyColumnSet.add(col.field);\n } else {\n this.#hiddenColumnSet.add(col.field);\n }\n }\n }\n\n override detach(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = undefined;\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = undefined;\n\n // Clean up attribute\n if (this.gridElement) {\n this.gridElement.removeAttribute('data-responsive');\n }\n\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isCardMode') {\n return this.#isResponsive;\n }\n return undefined;\n }\n\n /**\n * Apply hidden and value-only columns.\n * In legacy mode (single breakpoint), only applies when in responsive mode.\n * In multi-breakpoint mode, applies whenever there's an active breakpoint.\n */\n override afterRender(): void {\n // Measure card height for virtualization calculations\n this.#measureCardHeightFromDOM();\n\n // In single breakpoint mode, only apply when responsive\n // In multi-breakpoint mode, apply when there's an active breakpoint\n const shouldApply = this.#sortedBreakpoints.length > 0 ? this.#activeBreakpoint !== null : this.#isResponsive;\n\n if (!shouldApply) {\n return;\n }\n\n const hasHiddenColumns = this.#hiddenColumnSet.size > 0;\n const hasValueOnlyColumns = this.#valueOnlyColumnSet.size > 0;\n\n if (!hasHiddenColumns && !hasValueOnlyColumns) {\n return;\n }\n\n // Mark cells for hidden columns and value-only columns\n const cells = this.gridElement.querySelectorAll('.cell[data-field]');\n for (const cell of cells) {\n const field = cell.getAttribute('data-field');\n if (!field) continue;\n\n // Apply hidden attribute\n if (this.#hiddenColumnSet.has(field)) {\n cell.setAttribute('data-responsive-hidden', '');\n cell.removeAttribute('data-responsive-value-only');\n }\n // Apply value-only attribute (shows value without header label)\n else if (this.#valueOnlyColumnSet.has(field)) {\n cell.setAttribute('data-responsive-value-only', '');\n cell.removeAttribute('data-responsive-hidden');\n }\n // Clear any previous responsive attributes\n else {\n cell.removeAttribute('data-responsive-hidden');\n cell.removeAttribute('data-responsive-value-only');\n }\n }\n }\n\n /**\n * Check if width has crossed any breakpoint threshold.\n * Handles both single breakpoint (legacy) and multi-breakpoint modes.\n */\n #checkBreakpoint(width: number): void {\n // Multi-breakpoint mode\n if (this.#sortedBreakpoints.length > 0) {\n this.#checkMultiBreakpoint(width);\n return;\n }\n\n // Legacy single breakpoint mode\n const breakpoint = this.config.breakpoint ?? 0;\n\n // Warn once if breakpoint not configured (0 means never responsive)\n if (breakpoint === 0 && !this.#warnedAboutMissingBreakpoint) {\n this.#warnedAboutMissingBreakpoint = true;\n this.warn(\n MISSING_BREAKPOINT,\n \"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count.\",\n );\n }\n\n const shouldBeResponsive = breakpoint > 0 && width < breakpoint;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: shouldBeResponsive,\n width,\n breakpoint,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Check breakpoints in multi-breakpoint mode.\n * Evaluates breakpoints from largest to smallest, applying the first match.\n */\n #checkMultiBreakpoint(width: number): void {\n // Find the active breakpoint (first one where width <= maxWidth)\n // Since sorted largest to smallest, we find the largest matching breakpoint\n let newActiveBreakpoint: BreakpointConfig | null = null;\n\n for (const bp of this.#sortedBreakpoints) {\n if (width <= bp.maxWidth) {\n newActiveBreakpoint = bp;\n // Continue to find the most specific (smallest) matching breakpoint\n }\n }\n\n // Check if breakpoint changed\n const breakpointChanged = newActiveBreakpoint !== this.#activeBreakpoint;\n\n if (breakpointChanged) {\n this.#activeBreakpoint = newActiveBreakpoint;\n\n // Update hidden column sets from active breakpoint\n if (newActiveBreakpoint?.hiddenColumns) {\n this.#buildHiddenColumnSets(newActiveBreakpoint.hiddenColumns);\n } else {\n // Fall back to top-level hiddenColumns config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n }\n\n // Determine if we should be in card layout\n const shouldBeResponsive = newActiveBreakpoint?.cardLayout === true;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n }\n\n // Emit event for any breakpoint change\n this.emit('responsive-change', {\n isResponsive: this.#isResponsive,\n width,\n breakpoint: newActiveBreakpoint?.maxWidth ?? 0,\n } satisfies ResponsiveChangeDetail);\n\n this.requestRender();\n }\n }\n\n /** Original row height before entering responsive mode, for restoration on exit */\n #originalRowHeight?: number;\n\n /**\n * Apply the responsive state to the grid element.\n * Handles scroll reset when entering responsive mode and row height restoration on exit.\n */\n #applyResponsiveState(): void {\n this.gridElement.toggleAttribute('data-responsive', this.#isResponsive);\n\n // Apply animation attribute if enabled (default: true)\n const animate = this.config.animate !== false;\n this.gridElement.toggleAttribute('data-responsive-animate', animate);\n\n // Set custom animation duration if provided\n if (this.config.animationDuration) {\n this.gridElement.style.setProperty('--tbw-responsive-duration', `${this.config.animationDuration}ms`);\n }\n\n // Cast to internal type for virtualization access\n const internalGrid = this.#internalGrid;\n\n if (this.#isResponsive) {\n // Store original row height before responsive mode changes it\n if (internalGrid._virtualization) {\n this.#originalRowHeight = internalGrid._virtualization.rowHeight;\n }\n\n // Reset horizontal scroll position when entering responsive mode\n // The CSS hides overflow but doesn't reset the scroll position\n const scrollArea = this.gridElement.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (scrollArea) {\n scrollArea.scrollLeft = 0;\n }\n } else {\n // Exiting responsive mode - clean up inline styles set by renderRow\n // The rows are reused from the pool, so we need to remove the card-specific styles\n const rows = this.gridElement.querySelectorAll('.data-grid-row');\n for (const row of rows) {\n (row as HTMLElement).style.height = '';\n row.classList.remove('responsive-card');\n }\n\n // Restore original row height\n if (this.#originalRowHeight && this.#originalRowHeight > 0 && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = this.#originalRowHeight;\n this.#originalRowHeight = undefined;\n }\n\n // Clear cached measurements so they're remeasured fresh when re-entering responsive mode\n // Without this, stale measurements cause incorrect height calculations after scrolling\n this.#measuredCardHeight = undefined;\n this.#measuredGroupRowHeight = undefined;\n this.#lastCardRowCount = undefined;\n }\n }\n\n /**\n * Custom row rendering when cardRenderer is provided and in responsive mode.\n *\n * When a cardRenderer is configured, this hook takes over row rendering to display\n * the custom card layout instead of the default cell structure.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if rendered (prevents default), `void` for default rendering\n */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean | void {\n // Only override when in responsive mode AND cardRenderer is provided\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return; // Let default rendering proceed\n }\n\n // Skip group rows from GroupingRowsPlugin - they have special structure\n // and should use their own renderer\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return; // Let GroupingRowsPlugin handle group row rendering\n }\n\n // Clear existing content\n rowEl.replaceChildren();\n\n // Call user's cardRenderer to get custom content\n const cardContent = this.config.cardRenderer(row as T, rowIndex);\n\n // Reset className - clears any stale classes from previous use (e.g., 'group-row' from recycled element)\n // This follows the same pattern as GroupingRowsPlugin which sets className explicitly\n rowEl.className = 'data-grid-row responsive-card';\n\n // Handle card row height — when a numeric height is configured, use the effective\n // height from #getCardHeight() which incorporates DOM measurement after first render.\n // This keeps inline height in sync with the position cache used for virtualization.\n const configuredHeight = this.config.cardRowHeight;\n if (configuredHeight === 'auto' || configuredHeight === undefined) {\n rowEl.style.height = 'auto';\n } else {\n rowEl.style.height = `${this.#getCardHeight()}px`;\n }\n\n // Append the custom card content\n rowEl.appendChild(cardContent);\n\n return true; // We handled rendering\n }\n\n /**\n * Handle keyboard navigation in responsive mode.\n *\n * In responsive mode, the visual layout is inverted:\n * - Cells are stacked vertically within each \"card\" (row)\n * - DOWN/UP visually moves within the card (between fields)\n * - Page Down/Page Up or Ctrl+Down/Up moves between cards\n *\n * For custom cardRenderers, keyboard navigation is disabled entirely\n * since the implementor controls the card content and should handle\n * navigation via their own event handlers.\n *\n * @returns `true` if the event was handled and default behavior should be prevented\n */\n override onKeyDown(e: KeyboardEvent): boolean {\n if (!this.#isResponsive) {\n return false;\n }\n\n // If custom cardRenderer is provided, disable grid's keyboard navigation\n // The implementor is responsible for their own navigation\n if (this.config.cardRenderer) {\n const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];\n if (navKeys.includes(e.key)) {\n // Let the event bubble - implementor can handle it\n return false;\n }\n }\n\n // Swap arrow key behavior for CSS-only responsive mode\n // In card layout, cells are stacked vertically:\n // Card 1: Card 2:\n // ID: 1 ID: 2\n // Name: Alice Name: Bob <- ArrowRight goes here\n // Dept: Eng Dept: Mkt\n // ↓ ArrowDown goes here\n //\n // ArrowDown/Up = move within card (change column/field)\n // ArrowRight/Left = move between cards (change row)\n const maxRow = this.rows.length - 1;\n const maxCol = this.visibleColumns.length - 1;\n\n switch (e.key) {\n case 'ArrowDown':\n // Move down WITHIN card (to next field/column)\n if (this.grid._focusCol < maxCol) {\n this.grid._focusCol += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At bottom of card - optionally move to next card's first field\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n this.grid._focusCol = 0;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowUp':\n // Move up WITHIN card (to previous field/column)\n if (this.grid._focusCol > 0) {\n this.grid._focusCol -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At top of card - optionally move to previous card's last field\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n this.grid._focusCol = maxCol;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowRight':\n // Move to NEXT card (same field)\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowLeft':\n // Move to PREVIOUS card (same field)\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n }\n\n return false;\n }\n\n // ============================================\n // Variable Height Support for Mixed Row Types\n // ============================================\n\n /** Measured card height from DOM for virtualization calculations */\n #measuredCardHeight?: number;\n\n /** Measured group row height from DOM for virtualization calculations */\n #measuredGroupRowHeight?: number;\n\n /** Last known card row count for detecting changes (e.g., group expand/collapse) */\n #lastCardRowCount?: number;\n\n /**\n * Get the effective card height for virtualization calculations.\n * Prioritizes DOM-measured height (actual rendered size) over config,\n * since content can overflow the configured height.\n */\n #getCardHeight(): number {\n // Prefer measured height - it reflects actual rendered size including overflow\n if (this.#measuredCardHeight && this.#measuredCardHeight > 0) {\n return this.#measuredCardHeight;\n }\n // Fall back to explicit config\n const configHeight = this.config.cardRowHeight;\n if (typeof configHeight === 'number' && configHeight > 0) {\n return configHeight;\n }\n // Default fallback\n return 80;\n }\n\n /**\n * Get the effective group row height for virtualization calculations.\n * Uses DOM-measured height, falling back to original row height.\n */\n #getGroupRowHeight(): number {\n if (this.#measuredGroupRowHeight && this.#measuredGroupRowHeight > 0) {\n return this.#measuredGroupRowHeight;\n }\n // Fall back to original row height (before responsive mode)\n return this.#originalRowHeight ?? 28;\n }\n\n /**\n * Check if there are any group rows in the current dataset.\n * Used to determine if we have mixed row heights.\n */\n #hasGroupRows(): boolean {\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Count group rows and card rows in the current dataset.\n */\n #countRowTypes(): { groupCount: number; cardCount: number } {\n let groupCount = 0;\n let cardCount = 0;\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n groupCount++;\n } else {\n cardCount++;\n }\n }\n return { groupCount, cardCount };\n }\n\n /**\n * Return total extra height contributed by mixed row heights.\n * This is called by the grid's virtualization system to adjust scrollbar height.\n *\n * The grid calculates: totalRows * baseRowHeight + pluginExtraHeight\n *\n * For mixed layouts (groups + cards), we need to report the difference between\n * actual heights and what the base calculation assumes:\n * - Extra for groups: groupCount * (groupHeight - baseHeight)\n * - Extra for cards: cardCount * (cardHeight - baseHeight)\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeight(): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types (groups + cards)\n // If all rows are cards, we update the virtualization row height instead\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const { groupCount, cardCount } = this.#countRowTypes();\n\n // Calculate extra height for both row types\n const groupExtra = groupCount * Math.max(0, groupHeight - baseHeight);\n const cardExtra = cardCount * Math.max(0, cardHeight - baseHeight);\n\n return groupExtra + cardExtra;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * Used by virtualization to correctly calculate scroll positions.\n *\n * Like getExtraHeight, this accounts for both group and card row heights.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const groupHeightDiff = Math.max(0, groupHeight - baseHeight);\n const cardHeightDiff = Math.max(0, cardHeight - baseHeight);\n\n // Count group rows and card rows before the given index\n let groupsBefore = 0;\n let cardsBefore = 0;\n const rows = this.rows;\n const maxIndex = Math.min(beforeRowIndex, rows.length);\n\n for (let i = 0; i < maxIndex; i++) {\n if ((rows[i] as { __isGroupRow?: boolean }).__isGroupRow) {\n groupsBefore++;\n } else {\n cardsBefore++;\n }\n }\n\n return groupsBefore * groupHeightDiff + cardsBefore * cardHeightDiff;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.#internalGrid;\n const hasGroups = this.#hasGroupRows();\n\n // Check if card row count changed (e.g., group expanded/collapsed)\n const currentCardRowCount = this.#countCardRows();\n if (currentCardRowCount !== this.#lastCardRowCount) {\n this.#lastCardRowCount = currentCardRowCount;\n needsRefresh = true;\n }\n\n // Measure actual group row height from DOM (for mixed layouts)\n if (hasGroups) {\n const groupRow = this.gridElement.querySelector('.data-grid-row.group-row') as HTMLElement | null;\n if (groupRow) {\n const height = groupRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredGroupRowHeight) {\n this.#measuredGroupRowHeight = height;\n needsRefresh = true;\n }\n }\n }\n\n // Measure actual card height from DOM\n const cardRow = this.gridElement.querySelector('.data-grid-row.responsive-card') as HTMLElement | null;\n if (cardRow) {\n const height = cardRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredCardHeight) {\n this.#measuredCardHeight = height;\n needsRefresh = true;\n\n // For uniform card layouts (no groups), update virtualization row height directly\n // This ensures proper row recycling and translateY calculations\n if (!hasGroups && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = height;\n }\n }\n }\n\n // Defer virtualization refresh to avoid nested render cycles\n // This is called from afterRender, so we can't call refreshVirtualWindow synchronously\n // Use scheduler's VIRTUALIZATION phase to batch properly and avoid duplicate afterRender calls\n if (needsRefresh && !this.#pendingRefresh) {\n this.#pendingRefresh = true;\n queueMicrotask(() => {\n this.#pendingRefresh = false;\n // Only refresh if still attached and in responsive mode\n if (this.grid && this.#isResponsive) {\n // Request virtualization phase through grid's public API\n // This goes through the scheduler which batches and handles afterRender properly\n this.#internalGrid.refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","name","version","styles","static","incompatibleWith","reason","queries","type","description","resizeObserver","isResponsive","debounceTimer","warnedAboutMissingBreakpoint","currentWidth","hiddenColumnSet","Set","valueOnlyColumnSet","activeBreakpoint","sortedBreakpoints","internalGrid","this","grid","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","requestRender","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","getWidth","getActiveBreakpoint","attach","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","cardEl","querySelector","adapter","__frameworkAdapter","parseResponsiveCardElement","adapterRenderer","breakpointAttr","getAttribute","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","parseInt","isNaN","cardRowHeight","split","map","s","trim","filter","hideHeader","templateHTML","innerHTML","row","evaluated","evalTemplateString","value","sanitized","sanitizeHTML","container","document","createElement","className","Object","keys","clear","col","add","showValue","field","detach","disconnect","removeAttribute","handleQuery","query","afterRender","measureCardHeightFromDOM","hasHiddenColumns","size","hasValueOnlyColumns","cells","querySelectorAll","cell","has","setAttribute","checkMultiBreakpoint","warn","MISSING_BREAKPOINT","shouldBeResponsive","newActiveBreakpoint","bp","cardLayout","originalRowHeight","toggleAttribute","animate","animationDuration","style","setProperty","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","configuredHeight","getCardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","configHeight","getGroupRowHeight","hasGroupRows","countRowTypes","groupCount","cardCount","getExtraHeight","baseHeight","groupHeight","cardHeight","Math","max","getExtraHeightBefore","beforeRowIndex","groupHeightDiff","cardHeightDiff","groupsBefore","cardsBefore","maxIndex","min","i","getRowHeight","_index","countCardRows","count","pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","getBoundingClientRect","cardRow","queueMicrotask","refreshVirtualWindow"],"mappings":"mlBAkFO,MAAMA,UAAsCC,EAAAA,eACxCC,KAAO,aACEC,QAAU,QACVC,8hHAKlBC,gBAAoD,CAClDC,iBAAkB,CAChB,CACEJ,KAAM,eACNK,OACE,iJAINC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,OAAuCD,IAEvCE,GAA6C,KAE7CC,GAAyC,GAGzC,KAAIC,GACF,OAAOC,KAAKC,IACd,CAMA,YAAAX,GACE,OAAOU,MAAKV,CACd,CAOA,aAAAY,CAAcC,GACRA,IAAYH,MAAKV,IACnBU,MAAKV,EAAgBa,EACrBH,MAAKI,IACLJ,KAAKK,KAAK,oBAAqB,CAC7Bf,aAAca,EACdG,MAAON,MAAKP,EACZc,WAAYP,KAAKQ,OAAOD,YAAc,IAExCP,KAAKS,gBAET,CAMA,aAAAC,CAAcJ,GACZN,KAAKQ,OAAOD,WAAaD,EACzBN,MAAKW,EAAiBX,MAAKP,EAC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X,MAAMzD,EAASyD,EAAQD,wBAAwBxD,OAC3CA,EAAS,GAAKA,IAAW/G,MAAKkH,IAChClH,MAAKkH,EAAsBH,EAC3BoD,GAAe,GAIVC,GAAarK,EAAa2G,kBAC7B3G,EAAa2G,gBAAgBC,UAAYI,GAG/C,CAKIoD,IAAiBnK,MAAKkK,IACxBlK,MAAKkK,GAAkB,EACvBO,eAAe,KACbzK,MAAKkK,GAAkB,EAEnBlK,KAAKC,MAAQD,MAAKV,GAGpBU,MAAKD,EAAc2K,wBAAuB,GAAM,KAIxD"}
@@ -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 '@toolbox-web/grid';\n * import { TreePlugin } from '@toolbox-web/grid/plugins/tree';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name' },\n * { field: 'type', header: 'Type' },\n * { field: 'size', header: 'Size' },\n * ],\n * plugins: [new TreePlugin({ childrenField: 'children', indentWidth: 24 })],\n * };\n * grid.rows = [\n * {\n * id: 1,\n * name: 'Documents',\n * type: 'folder',\n * children: [\n * { id: 2, name: 'Report.docx', type: 'file', size: '24 KB' },\n * ],\n * },\n * ];\n * ```\n *\n * @example Expanded by Default with Custom Animation\n * ```ts\n * new TreePlugin({\n * defaultExpanded: true,\n * animation: 'fade', // 'slide' | 'fade' | false\n * indentWidth: 32,\n * })\n * ```\n *\n * @see {@link TreeConfig} for all configuration options\n * @see {@link FlattenedTreeRow} for the flattened row structure\n *\n * @internal Extends BaseGridPlugin\n */\nexport class TreePlugin extends BaseGridPlugin<TreeConfig> {\n static override readonly manifest: PluginManifest = {\n events: [\n {\n type: 'tree-state-change',\n description: 'Emitted when tree expansion state changes (toggle, expand all, collapse all)',\n },\n ],\n queries: [\n {\n type: 'canMoveRow',\n description: 'Returns false for rows with children (parent nodes cannot be reordered)',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'tree';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<TreeConfig> {\n return {\n childrenField: 'children',\n autoDetect: true,\n defaultExpanded: false,\n indentWidth: 20,\n showExpandIcons: true,\n animation: 'slide',\n };\n }\n\n // #region State\n\n private expandedKeys = new Set<string>();\n private initialExpansionDone = false;\n private flattenedRows: FlattenedTreeRow[] = [];\n private rowKeyMap = new Map<string, FlattenedTreeRow>();\n private previousVisibleKeys = new Set<string>();\n private keysToAnimate = new Set<string>();\n private sortState: { field: string; direction: 1 | -1 } | null = null;\n\n /** @internal */\n override detach(): void {\n this.expandedKeys.clear();\n this.initialExpansionDone = false;\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n this.keysToAnimate.clear();\n this.sortState = null;\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'canMoveRow') {\n // Tree rows with children cannot be reordered\n const row = query.context as { [key: string]: unknown } | null | undefined;\n const childrenField = this.config.childrenField ?? 'children';\n const children = row?.[childrenField];\n if (Array.isArray(children) && children.length > 0) {\n return false;\n }\n }\n return undefined;\n }\n\n // #endregion\n\n // #region Animation\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n // #endregion\n\n // #region Auto-Detection\n\n detect(rows: readonly unknown[]): boolean {\n if (!this.config.autoDetect) return false;\n const treeRows = rows as readonly TreeRow[];\n const field = this.config.childrenField ?? inferChildrenField(treeRows) ?? 'children';\n return detectTreeStructure(treeRows, field);\n }\n\n // #endregion\n\n // #region Data Processing\n\n /** @internal */\n override processRows(rows: readonly unknown[]): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const treeRows = rows as readonly TreeRow[];\n\n if (!detectTreeStructure(treeRows, childrenField)) {\n this.flattenedRows = [];\n this.rowKeyMap.clear();\n this.previousVisibleKeys.clear();\n return [...rows] as TreeRow[];\n }\n\n // Assign stable keys, then optionally sort\n let data = this.withStableKeys(treeRows);\n if (this.sortState) {\n data = this.sortTree(data, this.sortState.field, this.sortState.direction);\n }\n\n // Initialize expansion if needed\n if (this.config.defaultExpanded && !this.initialExpansionDone) {\n this.expandedKeys = expandAll(data, this.config);\n this.initialExpansionDone = true;\n }\n\n // Flatten and track animations\n this.flattenedRows = this.flattenTree(data, this.expandedKeys);\n this.rowKeyMap.clear();\n this.keysToAnimate.clear();\n const currentKeys = new Set<string>();\n\n for (const row of this.flattenedRows) {\n this.rowKeyMap.set(row.key, row);\n currentKeys.add(row.key);\n if (!this.previousVisibleKeys.has(row.key) && row.depth > 0) {\n this.keysToAnimate.add(row.key);\n }\n }\n this.previousVisibleKeys = currentKeys;\n\n return this.flattenedRows.map((r) => ({\n ...r.data,\n __treeKey: r.key,\n __treeDepth: r.depth,\n __treeHasChildren: r.hasChildren,\n __treeExpanded: r.isExpanded,\n }));\n }\n\n /** Assign stable keys to rows (preserves key across sort operations) */\n private withStableKeys(rows: readonly TreeRow[], parentKey: string | null = null): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n return rows.map((row, i) => {\n const stableKey = row.__stableKey as string | undefined;\n const key = row.id !== undefined ? String(row.id) : (stableKey ?? (parentKey ? `${parentKey}-${i}` : String(i)));\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n return {\n ...row,\n __stableKey: key,\n ...(hasChildren ? { [childrenField]: this.withStableKeys(children as TreeRow[], key) } : {}),\n };\n });\n }\n\n /** Flatten tree using stable keys */\n private flattenTree(rows: readonly TreeRow[], expanded: Set<string>, depth = 0): FlattenedTreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const result: FlattenedTreeRow[] = [];\n\n for (const row of rows) {\n const stableKey = row.__stableKey as string | undefined;\n const key = stableKey ?? String(row.id ?? '?');\n const children = row[childrenField];\n const hasChildren = Array.isArray(children) && children.length > 0;\n const isExpanded = expanded.has(key);\n\n result.push({\n key,\n data: row,\n depth,\n hasChildren,\n isExpanded,\n parentKey: depth > 0 ? key.substring(0, key.lastIndexOf('-')) || null : null,\n });\n\n if (hasChildren && isExpanded) {\n result.push(...this.flattenTree(children as TreeRow[], expanded, depth + 1));\n }\n }\n return result;\n }\n\n /** Sort tree recursively, keeping children with parents */\n private sortTree(rows: readonly TreeRow[], field: string, dir: 1 | -1): TreeRow[] {\n const childrenField = this.config.childrenField ?? 'children';\n const sorted = [...rows].sort((a, b) => {\n const aVal = a[field],\n bVal = b[field];\n if (aVal == null && bVal == null) return 0;\n if (aVal == null) return -1;\n if (bVal == null) return 1;\n return aVal > bVal ? dir : aVal < bVal ? -dir : 0;\n });\n return sorted.map((row) => {\n const children = row[childrenField];\n return Array.isArray(children) && children.length > 0\n ? { ...row, [childrenField]: this.sortTree(children as TreeRow[], field, dir) }\n : row;\n });\n }\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (this.flattenedRows.length === 0) return [...columns];\n\n const cols = [...columns] as ColumnConfig[];\n if (cols.length === 0) return cols;\n\n // Wrap the first column's renderer to add tree indentation and expand icons\n // This is the correct approach for trees because:\n // 1. Indentation can grow naturally with depth\n // 2. Expand icons appear inline with content\n // 3. Works with column reordering (icons stay with first visible column)\n const firstCol = cols[0];\n const originalRenderer = firstCol.viewRenderer;\n const getConfig = () => this.config;\n const setIcon = this.setIcon.bind(this);\n const resolveIcon = this.resolveIcon.bind(this);\n\n const wrappedRenderer: ColumnViewRenderer = (ctx) => {\n const { row, value } = ctx;\n const { showExpandIcons = true, indentWidth } = getConfig();\n const treeRow = row as TreeRow;\n const depth = treeRow.__treeDepth ?? 0;\n\n const container = document.createElement('span');\n container.className = 'tree-cell-wrapper';\n container.style.setProperty('--tbw-tree-depth', String(depth));\n // Allow config-based indentWidth to override CSS default\n if (indentWidth !== undefined) {\n container.style.setProperty('--tbw-tree-indent-width', `${indentWidth}px`);\n }\n\n // Add expand/collapse icon or spacer\n if (showExpandIcons) {\n if (treeRow.__treeHasChildren) {\n const icon = document.createElement('span');\n icon.className = `tree-toggle${treeRow.__treeExpanded ? ' expanded' : ''}`;\n setIcon(icon, resolveIcon(treeRow.__treeExpanded ? 'collapse' : 'expand'));\n icon.setAttribute('data-tree-key', String(treeRow.__treeKey ?? ''));\n container.appendChild(icon);\n } else {\n const spacer = document.createElement('span');\n spacer.className = 'tree-spacer';\n container.appendChild(spacer);\n }\n }\n\n // Add the original content\n const content = document.createElement('span');\n content.className = 'tree-content';\n if (originalRenderer) {\n const result = originalRenderer(ctx);\n if (result instanceof Node) {\n content.appendChild(result);\n } else if (typeof result === 'string') {\n content.innerHTML = result;\n }\n } else {\n content.textContent = value != null ? String(value) : '';\n }\n container.appendChild(content);\n\n return container;\n };\n\n cols[0] = { ...firstCol, viewRenderer: wrappedRenderer };\n return cols;\n }\n\n // #endregion\n\n // #region Event Handlers\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean {\n const target = event.originalEvent?.target as HTMLElement;\n if (!target?.classList.contains('tree-toggle')) return false;\n\n const key = target.getAttribute('data-tree-key');\n if (!key) return false;\n\n const flatRow = this.rowKeyMap.get(key);\n if (!flatRow) return false;\n\n this.expandedKeys = toggleExpand(this.expandedKeys, key);\n this.emit<TreeExpandDetail>('tree-expand', {\n key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(key),\n depth: flatRow.depth,\n });\n this.requestRender();\n return true;\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when on a row with children\n if (event.key !== ' ') return;\n\n const focusRow = this.grid._focusRow;\n const flatRow = this.flattenedRows[focusRow];\n if (!flatRow?.hasChildren) return;\n\n event.preventDefault();\n this.expandedKeys = toggleExpand(this.expandedKeys, flatRow.key);\n this.emit<TreeExpandDetail>('tree-expand', {\n key: flatRow.key,\n row: flatRow.data,\n expanded: this.expandedKeys.has(flatRow.key),\n depth: flatRow.depth,\n });\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override onHeaderClick(event: HeaderClickEvent): boolean {\n if (this.flattenedRows.length === 0 || !event.column.sortable) return false;\n\n const { field } = event.column;\n if (!this.sortState || this.sortState.field !== field) {\n this.sortState = { field, direction: 1 };\n } else if (this.sortState.direction === 1) {\n this.sortState = { field, direction: -1 };\n } else {\n this.sortState = null;\n }\n\n // Sync grid sort indicator\n const gridEl = this.grid as unknown as 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,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zC,QAC3DyC,KAAK4G,gBAAgB,oBAAqB,CAAE9J,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 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,EAAK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AAK8E,eACP,CAEA,MAAA6B,CAAO5J,GACLiD,KAAKlD,aAAeD,EAAamD,KAAKlD,aAAcC,GACpDiD,KAAK4G,gBAAgB,oBAAqB,CAAE9J,aAAc,IAAIkD,KAAKlD,gBACnEkD,KAAK8E,eACP,CAEA,SAAAzH,GACE2C,KAAKlD,aAAeO,EAAU2C,KAAK1C,KAAmB0C,KAAKzC,QAC3DyC,KAAK4G,gBAAgB,oBAAqB,CAAE9J,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,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/rows","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_undoRedo={},t.TbwGrid,t.TbwGrid)}(this,function(t,e,o){"use strict";function n(t,e,o){const n=[...t.undoStack,e];for(;n.length>o;)n.shift();return{undoStack:n,redoStack:[]}}function i(t){if(0===t.undoStack.length)return{newState:t,action:null};const e=[...t.undoStack],o=e.pop();return o?{newState:{undoStack:e,redoStack:[...t.redoStack,o]},action:o}:{newState:t,action:null}}function c(t){if(0===t.redoStack.length)return{newState:t,action:null};const e=[...t.redoStack],o=e.pop();return o?{newState:{undoStack:[...t.undoStack,o],redoStack:e},action:o}:{newState:t,action:null}}class a extends o.BaseGridPlugin{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#t=!1;#e=null;#o(t,e){const o=this.rows[t.rowIndex];if(o){try{const n=this.grid.getRowId(o);if(n)return void this.grid.updateRow(n,{[t.field]:e})}catch{}o[t.field]=e}}#n(t){const o=this.grid,n=o._visibleColumns?.findIndex(e=>e.field===t.field)??-1;if(n<0)return;o._focusRow=t.rowIndex,o._focusCol=n;const i=o.findRenderedRowElement?.(t.rowIndex);if(!i)return;const c=i.querySelector(`.cell[data-col="${n}"]`);if(c?.classList.contains("editing")){const t=c.querySelector(e.FOCUSABLE_EDITOR_SELECTOR);t?.focus({preventScroll:!0})}}#i(t,e){if(this.#t=!0,"compound"===t.type){const o="undo"===e?[...t.actions].reverse():t.actions;for(const t of o)this.#o(t,"undo"===e?t.oldValue:t.newValue)}else this.#o(t,"undo"===e?t.oldValue:t.newValue);this.#t=!1}#c(t){const e="compound"===t.type?t.actions[t.actions.length-1]:t;e&&this.#n(e)}attach(t){super.attach(t),this.on("cell-edit-committed",t=>{this.#t||this.recordEdit(t.rowIndex,t.field,t.oldValue,t.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#e=null}onKeyDown(t){const e=(t.ctrlKey||t.metaKey)&&"z"===t.key&&!t.shiftKey,o=(t.ctrlKey||t.metaKey)&&("y"===t.key||"z"===t.key&&t.shiftKey);if(e){t.preventDefault();const e=i({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#i(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("undo",{action:e.action,type:"undo"}),this.#c(e.action),this.requestRenderWithFocus()),!0}if(o){t.preventDefault();const e=c({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#i(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("redo",{action:e.action,type:"redo"}),this.#c(e.action),this.requestRenderWithFocus()),!0}return!1}recordEdit(t,e,o,i){const c=function(t,e,o,n){return{type:"cell-edit",rowIndex:t,field:e,oldValue:o,newValue:n,timestamp:Date.now()}}(t,e,o,i);if(this.#e)return void this.#e.push(c);const a=n({undoStack:this.undoStack,redoStack:this.redoStack},c,this.config.maxHistorySize??100);this.undoStack=a.undoStack,this.redoStack=a.redoStack}beginTransaction(){if(this.#e)throw new Error("UndoRedoPlugin: Transaction already in progress. Call endTransaction() first.");this.#e=[]}endTransaction(){const t=this.#e;if(!t)throw new Error("UndoRedoPlugin: No transaction in progress. Call beginTransaction() first.");if(this.#e=null,0===t.length)return;const e=1===t.length?t[0]:{type:"compound",actions:t,timestamp:Date.now()};const o=n({undoStack:this.undoStack,redoStack:this.redoStack},e,this.config.maxHistorySize??100);this.undoStack=o.undoStack,this.redoStack=o.redoStack}undo(){const t=i({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#c(t.action),this.requestRenderWithFocus()),t.action}redo(){const t=c({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#c(t.action),this.requestRenderWithFocus()),t.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const t={undoStack:[],redoStack:[]};this.undoStack=t.undoStack,this.redoStack=t.redoStack,this.#e=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}t.UndoRedoPlugin=a,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/diagnostics"),require("../../core/internal/rows"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/diagnostics","../../core/internal/rows","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_undoRedo={},t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,o,n){"use strict";function i(t,e,o){const n=[...t.undoStack,e];for(;n.length>o;)n.shift();return{undoStack:n,redoStack:[]}}function c(t){if(0===t.undoStack.length)return{newState:t,action:null};const e=[...t.undoStack],o=e.pop();return o?{newState:{undoStack:e,redoStack:[...t.redoStack,o]},action:o}:{newState:t,action:null}}function a(t){if(0===t.redoStack.length)return{newState:t,action:null};const e=[...t.redoStack],o=e.pop();return o?{newState:{undoStack:[...t.undoStack,o],redoStack:e},action:o}:{newState:t,action:null}}class r extends n.BaseGridPlugin{static dependencies=[{name:"editing",required:!0,reason:"UndoRedoPlugin tracks cell edit history"}];name="undoRedo";get defaultConfig(){return{maxHistorySize:100}}undoStack=[];redoStack=[];#t=!1;#e=null;#o(t,e){const o=this.rows[t.rowIndex];if(o){try{const n=this.grid.getRowId(o);if(n)return void this.grid.updateRow(n,{[t.field]:e})}catch{}o[t.field]=e}}#n(t){const e=this.grid,n=e._visibleColumns?.findIndex(e=>e.field===t.field)??-1;if(n<0)return;e._focusRow=t.rowIndex,e._focusCol=n;const i=e.findRenderedRowElement?.(t.rowIndex);if(!i)return;const c=i.querySelector(`.cell[data-col="${n}"]`);if(c?.classList.contains("editing")){const t=c.querySelector(o.FOCUSABLE_EDITOR_SELECTOR);t?.focus({preventScroll:!0})}}#i(t,e){if(this.#t=!0,"compound"===t.type){const o="undo"===e?[...t.actions].reverse():t.actions;for(const t of o)this.#o(t,"undo"===e?t.oldValue:t.newValue)}else this.#o(t,"undo"===e?t.oldValue:t.newValue);this.#t=!1}#c(t){const e="compound"===t.type?t.actions[t.actions.length-1]:t;e&&this.#n(e)}attach(t){super.attach(t),this.on("cell-edit-committed",t=>{this.#t||this.recordEdit(t.rowIndex,t.field,t.oldValue,t.newValue)})}detach(){this.undoStack=[],this.redoStack=[],this.#e=null}onKeyDown(t){const e=(t.ctrlKey||t.metaKey)&&"z"===t.key&&!t.shiftKey,o=(t.ctrlKey||t.metaKey)&&("y"===t.key||"z"===t.key&&t.shiftKey);if(e){t.preventDefault();const e=c({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#i(e.action,"undo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("undo",{action:e.action,type:"undo"}),this.#c(e.action),this.requestRenderWithFocus()),!0}if(o){t.preventDefault();const e=a({undoStack:this.undoStack,redoStack:this.redoStack});return e.action&&(this.#i(e.action,"redo"),this.undoStack=e.newState.undoStack,this.redoStack=e.newState.redoStack,this.emit("redo",{action:e.action,type:"redo"}),this.#c(e.action),this.requestRenderWithFocus()),!0}return!1}recordEdit(t,e,o,n){const c=function(t,e,o,n){return{type:"cell-edit",rowIndex:t,field:e,oldValue:o,newValue:n,timestamp:Date.now()}}(t,e,o,n);if(this.#e)return void this.#e.push(c);const a=i({undoStack:this.undoStack,redoStack:this.redoStack},c,this.config.maxHistorySize??100);this.undoStack=a.undoStack,this.redoStack=a.redoStack}beginTransaction(){this.#e&&e.throwDiagnostic(e.TRANSACTION_IN_PROGRESS,"Transaction already in progress. Call endTransaction() first."),this.#e=[]}endTransaction(){const t=this.#e;if(t||e.throwDiagnostic(e.NO_TRANSACTION,"No transaction in progress. Call beginTransaction() first."),this.#e=null,0===t.length)return;const o=1===t.length?t[0]:{type:"compound",actions:t,timestamp:Date.now()};const n=i({undoStack:this.undoStack,redoStack:this.redoStack},o,this.config.maxHistorySize??100);this.undoStack=n.undoStack,this.redoStack=n.redoStack}undo(){const t=c({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"undo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#c(t.action),this.requestRenderWithFocus()),t.action}redo(){const t=a({undoStack:this.undoStack,redoStack:this.redoStack});return t.action&&(this.#i(t.action,"redo"),this.undoStack=t.newState.undoStack,this.redoStack=t.newState.redoStack,this.#c(t.action),this.requestRenderWithFocus()),t.action}canUndo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.undoStack.length>0}canRedo(){return{undoStack:this.undoStack,redoStack:this.redoStack}.redoStack.length>0}clearHistory(){const t={undoStack:[],redoStack:[]};this.undoStack=t.undoStack,this.redoStack=t.redoStack,this.#e=null}getUndoStack(){return[...this.undoStack]}getRedoStack(){return[...this.redoStack]}}t.UndoRedoPlugin=r,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=undo-redo.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"undo-redo.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/undo-redo/history.ts","../../../../../libs/grid/src/lib/plugins/undo-redo/UndoRedoPlugin.ts"],"sourcesContent":["/**\n * Undo/Redo History Management\n *\n * Pure functions for managing the undo/redo stacks.\n * These functions are stateless and return new state objects.\n */\n\nimport type { 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 { 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 '@toolbox-web/grid';\n * import { EditingPlugin } from '@toolbox-web/grid/plugins/editing';\n * import { UndoRedoPlugin } from '@toolbox-web/grid/plugins/undo-redo';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'name', header: 'Name', editable: true },\n * { field: 'price', header: 'Price', type: 'number', editable: true },\n * ],\n * plugins: [\n * new EditingPlugin({ editOn: 'dblclick' }), // Required - must be first\n * new UndoRedoPlugin({ maxHistorySize: 50 }),\n * ],\n * };\n * ```\n *\n * @see {@link UndoRedoConfig} for configuration options\n * @see {@link EditingPlugin} for the required dependency\n *\n * @internal Extends BaseGridPlugin\n */\nexport class UndoRedoPlugin extends BaseGridPlugin<UndoRedoConfig> {\n /**\n * Plugin dependencies - UndoRedoPlugin requires EditingPlugin to track edits.\n *\n * The EditingPlugin must be loaded BEFORE this plugin in the plugins array.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'editing', required: true, reason: 'UndoRedoPlugin tracks cell edit history' },\n ];\n\n /** @internal */\n readonly name = 'undoRedo';\n\n /** @internal */\n protected override get defaultConfig(): Partial<UndoRedoConfig> {\n return {\n maxHistorySize: 100,\n };\n }\n\n // State as class properties\n private undoStack: 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 throw new Error('UndoRedoPlugin: 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 throw new Error('UndoRedoPlugin: 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","Error","endTransaction","buffer","canUndo","canRedo","clearHistory","getUndoStack","getRedoStack"],"mappings":"6ZAkBO,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,CCPO,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,KAAKI,KAAKC,SAASN,GACjC,GAAII,EAEF,YADAH,KAAKI,KAAKE,UAAUH,EAAO,CAAE,CAAC1B,EAAO8B,OAAQT,GAGjD,CAAA,MAEA,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B,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,OAAAwF,GACE,MAAe,CAAEtF,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,WDrUjDH,UAAUC,OAAS,CCsUhC,CAKA,OAAAsF,GACE,MAAe,CAAEvF,UAAWqB,KAAKrB,UAAWG,UAAWkB,KAAKlB,WDlUjDA,UAAUF,OAAS,CCmUhC,CAKA,YAAAuF,GACE,MAAMnF,EDhUD,CAAEL,UAAW,GAAIG,UAAW,ICiUjCkB,KAAKrB,UAAYK,EAASL,UAC1BqB,KAAKlB,UAAYE,EAASF,UAC1BkB,MAAKJ,EAAqB,IAC5B,CAKA,YAAAwE,GACE,MAAO,IAAIpE,KAAKrB,UAClB,CAKA,YAAA0F,GACE,MAAO,IAAIrE,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 {@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,IAE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