@toolbox-web/grid 1.21.1 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +6 -8
  2. package/all.js +2 -6850
  3. package/all.js.map +1 -1
  4. package/index.js +1 -4352
  5. package/index.js.map +1 -1
  6. package/lib/core/grid.d.ts +75 -8
  7. package/lib/core/grid.d.ts.map +1 -1
  8. package/lib/core/internal/rows.d.ts.map +1 -1
  9. package/lib/core/plugin/base-plugin.d.ts +8 -2
  10. package/lib/core/plugin/base-plugin.d.ts.map +1 -1
  11. package/lib/core/styles/index.d.ts.map +1 -1
  12. package/lib/core/types.d.ts +84 -2
  13. package/lib/core/types.d.ts.map +1 -1
  14. package/lib/plugins/clipboard/index.js +1 -733
  15. package/lib/plugins/clipboard/index.js.map +1 -1
  16. package/lib/plugins/clipboard/types.d.ts +5 -0
  17. package/lib/plugins/clipboard/types.d.ts.map +1 -1
  18. package/lib/plugins/column-virtualization/index.js +1 -560
  19. package/lib/plugins/column-virtualization/index.js.map +1 -1
  20. package/lib/plugins/column-virtualization/types.d.ts +5 -0
  21. package/lib/plugins/column-virtualization/types.d.ts.map +1 -1
  22. package/lib/plugins/context-menu/index.js +1 -754
  23. package/lib/plugins/context-menu/index.js.map +1 -1
  24. package/lib/plugins/context-menu/types.d.ts +5 -0
  25. package/lib/plugins/context-menu/types.d.ts.map +1 -1
  26. package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
  27. package/lib/plugins/editing/index.d.ts +1 -1
  28. package/lib/plugins/editing/index.d.ts.map +1 -1
  29. package/lib/plugins/editing/index.js +1 -1539
  30. package/lib/plugins/editing/index.js.map +1 -1
  31. package/lib/plugins/editing/types.d.ts +49 -0
  32. package/lib/plugins/editing/types.d.ts.map +1 -1
  33. package/lib/plugins/export/index.js +1 -589
  34. package/lib/plugins/export/index.js.map +1 -1
  35. package/lib/plugins/export/types.d.ts +5 -0
  36. package/lib/plugins/export/types.d.ts.map +1 -1
  37. package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
  38. package/lib/plugins/filtering/filter-model.d.ts.map +1 -1
  39. package/lib/plugins/filtering/index.js +1 -1283
  40. package/lib/plugins/filtering/index.js.map +1 -1
  41. package/lib/plugins/filtering/types.d.ts +7 -2
  42. package/lib/plugins/filtering/types.d.ts.map +1 -1
  43. package/lib/plugins/grouping-columns/index.js +1 -726
  44. package/lib/plugins/grouping-columns/index.js.map +1 -1
  45. package/lib/plugins/grouping-columns/types.d.ts +3 -0
  46. package/lib/plugins/grouping-columns/types.d.ts.map +1 -1
  47. package/lib/plugins/grouping-rows/index.js +2 -905
  48. package/lib/plugins/grouping-rows/index.js.map +1 -1
  49. package/lib/plugins/grouping-rows/types.d.ts +5 -0
  50. package/lib/plugins/grouping-rows/types.d.ts.map +1 -1
  51. package/lib/plugins/master-detail/index.js +1 -950
  52. package/lib/plugins/master-detail/index.js.map +1 -1
  53. package/lib/plugins/master-detail/types.d.ts +5 -0
  54. package/lib/plugins/master-detail/types.d.ts.map +1 -1
  55. package/lib/plugins/multi-sort/index.js +1 -553
  56. package/lib/plugins/multi-sort/index.js.map +1 -1
  57. package/lib/plugins/multi-sort/types.d.ts +5 -0
  58. package/lib/plugins/multi-sort/types.d.ts.map +1 -1
  59. package/lib/plugins/pinned-columns/index.js +1 -688
  60. package/lib/plugins/pinned-columns/index.js.map +1 -1
  61. package/lib/plugins/pinned-columns/types.d.ts +3 -0
  62. package/lib/plugins/pinned-columns/types.d.ts.map +1 -1
  63. package/lib/plugins/pinned-rows/index.js +1 -704
  64. package/lib/plugins/pinned-rows/index.js.map +1 -1
  65. package/lib/plugins/pinned-rows/types.d.ts +5 -0
  66. package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
  67. package/lib/plugins/pivot/index.js +1 -1191
  68. package/lib/plugins/pivot/index.js.map +1 -1
  69. package/lib/plugins/pivot/types.d.ts +5 -0
  70. package/lib/plugins/pivot/types.d.ts.map +1 -1
  71. package/lib/plugins/print/index.js +1 -691
  72. package/lib/plugins/print/index.js.map +1 -1
  73. package/lib/plugins/print/types.d.ts +3 -0
  74. package/lib/plugins/print/types.d.ts.map +1 -1
  75. package/lib/plugins/reorder/index.js +1 -703
  76. package/lib/plugins/reorder/index.js.map +1 -1
  77. package/lib/plugins/reorder/types.d.ts +5 -0
  78. package/lib/plugins/reorder/types.d.ts.map +1 -1
  79. package/lib/plugins/responsive/index.js +1 -971
  80. package/lib/plugins/responsive/index.js.map +1 -1
  81. package/lib/plugins/responsive/types.d.ts +5 -0
  82. package/lib/plugins/responsive/types.d.ts.map +1 -1
  83. package/lib/plugins/row-reorder/index.js +1 -728
  84. package/lib/plugins/row-reorder/index.js.map +1 -1
  85. package/lib/plugins/row-reorder/types.d.ts +5 -0
  86. package/lib/plugins/row-reorder/types.d.ts.map +1 -1
  87. package/lib/plugins/selection/index.js +1 -1071
  88. package/lib/plugins/selection/index.js.map +1 -1
  89. package/lib/plugins/selection/types.d.ts +3 -0
  90. package/lib/plugins/selection/types.d.ts.map +1 -1
  91. package/lib/plugins/server-side/index.js +1 -521
  92. package/lib/plugins/server-side/index.js.map +1 -1
  93. package/lib/plugins/server-side/types.d.ts +5 -0
  94. package/lib/plugins/server-side/types.d.ts.map +1 -1
  95. package/lib/plugins/tree/index.js +1 -686
  96. package/lib/plugins/tree/index.js.map +1 -1
  97. package/lib/plugins/tree/types.d.ts +5 -0
  98. package/lib/plugins/tree/types.d.ts.map +1 -1
  99. package/lib/plugins/undo-redo/index.js +1 -584
  100. package/lib/plugins/undo-redo/index.js.map +1 -1
  101. package/lib/plugins/undo-redo/types.d.ts +5 -0
  102. package/lib/plugins/undo-redo/types.d.ts.map +1 -1
  103. package/lib/plugins/visibility/index.js +1 -792
  104. package/lib/plugins/visibility/index.js.map +1 -1
  105. package/lib/plugins/visibility/types.d.ts +5 -0
  106. package/lib/plugins/visibility/types.d.ts.map +1 -1
  107. package/package.json +1 -1
  108. package/umd/grid.all.umd.js +1 -186
  109. package/umd/grid.all.umd.js.map +1 -1
  110. package/umd/grid.umd.js +1 -90
  111. package/umd/grid.umd.js.map +1 -1
  112. package/umd/plugins/clipboard.umd.js +1 -6
  113. package/umd/plugins/clipboard.umd.js.map +1 -1
  114. package/umd/plugins/column-virtualization.umd.js +1 -1
  115. package/umd/plugins/column-virtualization.umd.js.map +1 -1
  116. package/umd/plugins/context-menu.umd.js +1 -1
  117. package/umd/plugins/context-menu.umd.js.map +1 -1
  118. package/umd/plugins/editing.umd.js +1 -1
  119. package/umd/plugins/editing.umd.js.map +1 -1
  120. package/umd/plugins/export.umd.js +1 -13
  121. package/umd/plugins/export.umd.js.map +1 -1
  122. package/umd/plugins/filtering.umd.js +1 -1
  123. package/umd/plugins/filtering.umd.js.map +1 -1
  124. package/umd/plugins/grouping-columns.umd.js +1 -1
  125. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  126. package/umd/plugins/grouping-rows.umd.js +1 -4
  127. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  128. package/umd/plugins/master-detail.umd.js +1 -1
  129. package/umd/plugins/master-detail.umd.js.map +1 -1
  130. package/umd/plugins/multi-sort.umd.js +1 -1
  131. package/umd/plugins/multi-sort.umd.js.map +1 -1
  132. package/umd/plugins/pinned-columns.umd.js +1 -1
  133. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  134. package/umd/plugins/pinned-rows.umd.js +1 -1
  135. package/umd/plugins/pinned-rows.umd.js.map +1 -1
  136. package/umd/plugins/pivot.umd.js +1 -1
  137. package/umd/plugins/pivot.umd.js.map +1 -1
  138. package/umd/plugins/print.umd.js +1 -75
  139. package/umd/plugins/print.umd.js.map +1 -1
  140. package/umd/plugins/reorder.umd.js +1 -1
  141. package/umd/plugins/reorder.umd.js.map +1 -1
  142. package/umd/plugins/responsive.umd.js +1 -1
  143. package/umd/plugins/responsive.umd.js.map +1 -1
  144. package/umd/plugins/row-reorder.umd.js +1 -1
  145. package/umd/plugins/row-reorder.umd.js.map +1 -1
  146. package/umd/plugins/selection.umd.js +1 -3
  147. package/umd/plugins/selection.umd.js.map +1 -1
  148. package/umd/plugins/server-side.umd.js +1 -1
  149. package/umd/plugins/server-side.umd.js.map +1 -1
  150. package/umd/plugins/tree.umd.js +1 -1
  151. package/umd/plugins/tree.umd.js.map +1 -1
  152. package/umd/plugins/undo-redo.umd.js +1 -1
  153. package/umd/plugins/undo-redo.umd.js.map +1 -1
  154. package/umd/plugins/visibility.umd.js +1 -1
  155. 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 { InternalGrid } 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 /**\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 }\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.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') 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 gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseResponsiveCardElement?: (el: Element) => ((row: T, rowIndex: number) => HTMLElement) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseResponsiveCardElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.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 && !gridWithAdapter.__frameworkAdapter?.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.grid as unknown as 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 cardRowHeight\n const cardHeight = this.config.cardRowHeight ?? 'auto';\n if (cardHeight !== 'auto') {\n rowEl.style.height = `${cardHeight}px`;\n } else {\n // Remove any virtualization-set height for auto mode\n rowEl.style.height = 'auto';\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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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 v3.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 v3.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.grid as unknown as 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.grid as unknown as InternalGrid).refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","styles","#resizeObserver","#isResponsive","#debounceTimer","#warnedAboutMissingBreakpoint","#currentWidth","#hiddenColumnSet","#valueOnlyColumnSet","#activeBreakpoint","#sortedBreakpoints","enabled","#applyResponsiveState","width","#checkBreakpoint","renderer","grid","#parseLightDomCard","#buildHiddenColumnSets","a","b","entries","gridEl","cardEl","gridWithAdapter","adapterRenderer","breakpointAttr","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","breakpoint","s","debounceMs","templateHTML","row","evaluated","evalTemplateString","sanitized","sanitizeHTML","container","hiddenColumns","col","query","#measureCardHeightFromDOM","hasHiddenColumns","hasValueOnlyColumns","cells","cell","field","#checkMultiBreakpoint","shouldBeResponsive","newActiveBreakpoint","bp","#originalRowHeight","animate","internalGrid","scrollArea","rows","#measuredCardHeight","#measuredGroupRowHeight","#lastCardRowCount","rowEl","rowIndex","cardContent","cardHeight","e","maxRow","maxCol","ensureCellVisible","#getCardHeight","configHeight","#getGroupRowHeight","#hasGroupRows","#countRowTypes","groupCount","cardCount","baseHeight","groupHeight","groupExtra","cardExtra","beforeRowIndex","groupHeightDiff","cardHeightDiff","groupsBefore","cardsBefore","maxIndex","i","_index","#countCardRows","count","#pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","height","cardRow"],"mappings":"89HAiFO,MAAMA,UAAsCC,EAAAA,cAA0C,CAClF,KAAO,aACE,QAAU,QACV,OAASC,EAK3B,OAAyB,SAA2B,CAClD,iBAAkB,CAChB,CACE,KAAM,eACN,OACE,8IAAA,CAEJ,EAEF,QAAS,CACP,CACE,KAAM,aACN,YAAa,+DAAA,CACf,CACF,EAGFC,GACAC,GAAgB,GAChBC,GACAC,GAAgC,GAChCC,GAAgB,EAEhBC,OAAoC,IAEpCC,OAAuC,IAEvCC,GAA6C,KAE7CC,GAAyC,CAAA,EAMzC,cAAwB,CACtB,OAAO,KAAKP,EACd,CAOA,cAAcQ,EAAwB,CAChCA,IAAY,KAAKR,KACnB,KAAKA,GAAgBQ,EACrB,KAAKC,GAAA,EACL,KAAK,KAAK,oBAAqB,CAC7B,aAAcD,EACd,MAAO,KAAKL,GACZ,WAAY,KAAK,OAAO,YAAc,CAAA,CACN,EAEtC,CAMA,cAAcO,EAAqB,CACjC,KAAK,OAAO,WAAaA,EACzB,KAAKC,GAAiB,KAAKR,EAAa,CAC1C,CAOA,gBAAgBS,EAA2D,CACzE,KAAK,OAAO,aAAeA,EAEvB,KAAKZ,IACP,KAAK,cAAA,CAET,CAMA,UAAmB,CACjB,OAAO,KAAKG,EACd,CAMA,qBAA+C,CAC7C,OAAO,KAAKG,EACd,CAES,OAAOO,EAAyB,C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,EAAe,GAIX,CAACC,GAAarC,EAAa,kBAC7BA,EAAa,gBAAgB,UAAYwC,GAG/C,CAKIJ,GAAgB,CAAC,KAAKD,KACxB,KAAKA,GAAkB,GACvB,eAAe,IAAM,CACnB,KAAKA,GAAkB,GAEnB,KAAK,MAAQ,KAAKzF,IAGnB,KAAK,KAAiC,uBAAuB,GAAM,EAAI,CAE5E,CAAC,EAEL,CACF"}
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 { InternalGrid } 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 /**\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 }\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.grid as unknown as Element;\n if (!gridEl || typeof gridEl.querySelector !== 'function') 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 gridWithAdapter = gridEl as unknown as {\n __frameworkAdapter?: {\n parseResponsiveCardElement?: (el: Element) => ((row: T, rowIndex: number) => HTMLElement) | undefined;\n };\n };\n if (gridWithAdapter.__frameworkAdapter?.parseResponsiveCardElement) {\n const adapterRenderer = gridWithAdapter.__frameworkAdapter.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 && !gridWithAdapter.__frameworkAdapter?.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.grid as unknown as 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 cardRowHeight\n const cardHeight = this.config.cardRowHeight ?? 'auto';\n if (cardHeight !== 'auto') {\n rowEl.style.height = `${cardHeight}px`;\n } else {\n // Remove any virtualization-set height for auto mode\n rowEl.style.height = 'auto';\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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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.grid as unknown as 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 v3.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 v3.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.grid as unknown as 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.grid as unknown as 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","this","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","requestRender","getWidth","getActiveBreakpoint","attach","grid","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","querySelector","cardEl","gridWithAdapter","__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","internalGrid","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","cardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","getCardHeight","configHeight","getGroupRowHeight","hasGroupRows","countRowTypes","groupCount","cardCount","getExtraHeight","baseHeight","groupHeight","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,i/GAKlBC,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,GAMzC,YAAAR,GACE,OAAOS,MAAKT,CACd,CAOA,aAAAU,CAAcC,GACRA,IAAYF,MAAKT,IACnBS,MAAKT,EAAgBW,EACrBF,M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,CACZ,MAAMtD,EAASsD,EAASC,wBAAwBvD,OAC5CA,EAAS,GAAKA,IAAWhH,MAAKoH,IAChCpH,MAAKoH,EAA0BJ,EAC/BmD,GAAe,EAEnB,CACF,CAGA,MAAMK,EAAUxK,KAAKmC,YAAYE,cAAc,kCAC/C,GAAImI,EAAS,CACX,MAAMxD,EAASwD,EAAQD,wBAAwBvD,OAC3CA,EAAS,GAAKA,IAAWhH,MAAKmH,IAChCnH,MAAKmH,EAAsBH,EAC3BmD,GAAe,GAIVC,GAAa1D,EAAaC,kBAC7BD,EAAaC,gBAAgBC,UAAYI,GAG/C,CAKImD,IAAiBnK,MAAKkK,IACxBlK,MAAKkK,GAAkB,EACvBO,eAAe,KACbzK,MAAKkK,GAAkB,EAEnBlK,KAAKiB,MAAQjB,MAAKT,GAGnBS,KAAKiB,KAAiCyJ,wBAAuB,GAAM,KAI5E"}
@@ -1,2 +1,2 @@
1
- (function(l,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("../../core/internal/keyboard"),require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/keyboard","../../core/plugin/base-plugin"],c):(l=typeof globalThis<"u"?globalThis:l||self,c(l.TbwGridPlugin_rowReorder={},l.TbwGrid,l.TbwGrid))})(this,(function(l,c,b){"use strict";const v='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}',f="__tbw_row_drag";class m extends b.BaseGridPlugin{name="rowReorder";styles=v;get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return this.isAnimationEnabled?this.config.animation!==void 0?this.config.animation:"flip":!1}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const r={field:f,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const t=document.createElement("div");return t.className="dg-row-drag-handle",t.setAttribute("aria-label","Drag to reorder"),t.setAttribute("role","button"),t.setAttribute("tabindex","-1"),t.draggable=!0,this.setIcon(t,this.resolveIcon("dragHandle")),t}};return this.config.dragHandlePosition==="right"?[...e,r]:[r,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(o=>{const i=o;if(i.getAttribute("data-drag-bound"))return;i.setAttribute("data-drag-bound","true");const n=i.closest(".data-grid-row");n&&this.setupHandleDragListeners(i,n)}),e.querySelectorAll(".data-grid-row").forEach(o=>{const i=o;i.getAttribute("data-drop-bound")||(i.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(i))})}onKeyDown(e){if(!this.config.enableKeyboard||!e.ctrlKey||e.key!=="ArrowUp"&&e.key!=="ArrowDown")return;const r=this.grid,t=r._focusRow,o=r._rows??this.sourceRows;if(t<0||t>=o.length)return;const i=e.key==="ArrowUp"?"up":"down",n=i==="up"?t-1:t+1;if(n<0||n>=o.length)return;const s=o[t];if(!(this.config.canMove&&!this.config.canMove(s,t,n,i)))return this.handleKeyboardMove(s,t,n,i,r._focusCol),e.preventDefault(),e.stopPropagation(),!0}onCellClick(){this.flushPendingMove()}moveRow(e,r){const t=[...this.sourceRows];if(e<0||e>=t.length||r<0||r>=t.length||e===r)return;const o=r<e?"up":"down",i=t[e];this.config.canMove&&!this.config.canMove(i,e,r,o)||this.executeMove(i,e,r,"keyboard")}canMoveRow(e,r){const t=this.sourceRows;if(e<0||e>=t.length||r<0||r>=t.length||e===r)return!1;if(!this.config.canMove)return!0;const o=r<e?"up":"down";return this.config.canMove(t[e],e,r,o)}setupHandleDragListeners(e,r){e.addEventListener("dragstart",t=>{const o=this.getRowIndex(r);o<0||(this.isDragging=!0,this.draggedRowIndex=o,t.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",String(o))),r.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",r=>{if(r.preventDefault(),!this.isDragging||this.draggedRowIndex===null)return;const t=this.getRowIndex(e);if(t<0||t===this.draggedRowIndex)return;const o=e.getBoundingClientRect(),i=o.top+o.height/2,n=r.clientY<i;this.dropRowIndex=n?t:t+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",n),e.classList.toggle("drop-after",!n)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",r=>{r.preventDefault();const t=this.draggedRowIndex;let o=this.dropRowIndex;if(!(!this.isDragging||t===null||o===null)&&(o>t&&o--,t!==o)){const n=this.sourceRows[t],s=o<t?"up":"down";(!this.config.canMove||this.config.canMove(n,t,o,s))&&this.executeMove(n,t,o,"drag")}})}handleKeyboardMove(e,r,t,o,i){this.pendingMove?this.pendingMove.currentIndex=t:this.pendingMove={originalIndex:r,currentIndex:t,row:e},this.lastFocusCol=i;const n=this.grid,s=[...n._rows??this.sourceRows],[d]=s.splice(r,1);s.splice(t,0,d),n._rows=s,n._focusRow=t,n._focusCol=i,n.refreshVirtualWindow(!0),c.ensureCellVisible(n),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:r,row:t}=this.pendingMove;if(this.pendingMove=null,e===r)return;const o={row:t,fromIndex:e,toIndex:r,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",o)){const n=[...this.sourceRows],[s]=n.splice(r,1);n.splice(e,0,s);const d=this.grid;d._rows=n,d._focusRow=e,d._focusCol=this.lastFocusCol,d.refreshVirtualWindow(!0),c.ensureCellVisible(d)}}executeMove(e,r,t,o){const i=[...this.sourceRows],[n]=i.splice(r,1);i.splice(t,0,n);const s={row:e,fromIndex:r,toIndex:t,rows:i,source:o};if(!this.emitCancelable("row-move",s))if(this.animationType==="flip"&&this.gridElement){const a=this.captureRowPositions();this.grid.rows=i,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(a,r,t)})}else this.grid.rows=i}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(r=>{const t=this.getRowIndex(r);t>=0&&e.set(t,r.getBoundingClientRect().top)}),e}animateFLIP(e,r,t){const o=this.gridElement;if(!o||e.size===0)return;const i=Math.min(r,t),n=Math.max(r,t),s=[];if(o.querySelectorAll(".data-grid-row").forEach(a=>{const u=a,g=this.getRowIndex(u);if(g<0||g<i||g>n)return;let h;g===t?h=r:r<t?h=g+1:h=g-1;const w=e.get(h);if(w===void 0)return;const R=u.getBoundingClientRect().top,p=w-R;Math.abs(p)>1&&s.push({el:u,deltaY:p})}),s.length===0)return;s.forEach(({el:a,deltaY:u})=>{a.style.transform=`translateY(${u}px)`}),o.offsetHeight;const d=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:a})=>{a.classList.add("flip-animating"),a.style.transform=""}),setTimeout(()=>{s.forEach(({el:a})=>{a.style.transform="",a.classList.remove("flip-animating")})},d+50)})}getRowIndex(e){const r=e.querySelector(".cell[data-row]");return r?parseInt(r.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}l.ROW_DRAG_HANDLE_FIELD=f,l.RowReorderPlugin=m,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_rowReorder={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,r){"use strict";const o="__tbw_row_drag";class n extends r.BaseGridPlugin{name="rowReorder";styles='@layer tbw-plugins{[data-field=__tbw_row_drag]{display:flex;align-items:center;justify-content:center}.dg-row-drag-handle{display:flex;align-items:center;justify-content:center;min-width:1em;min-height:1em;cursor:grab;-webkit-user-select:none;user-select:none;color:var(--tbw-row-reorder-handle-color, var(--tbw-color-fg-muted));transition:color var(--tbw-transition-duration, .12s) var(--tbw-transition-ease, ease);font-size:var(--tbw-font-size, 1em);letter-spacing:-2px}.dg-row-drag-handle:hover{color:var(--tbw-row-reorder-handle-hover, var(--tbw-color-fg))}.dg-row-drag-handle:active{cursor:grabbing}.data-grid-row.dragging{opacity:.6}.data-grid-row.drop-target{position:relative}.data-grid-row.drop-target.drop-before:before{content:"";position:absolute;top:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.drop-target.drop-after:after{content:"";position:absolute;bottom:0;left:0;right:0;height:2px;background-color:var(--tbw-row-reorder-indicator, var(--tbw-color-accent));z-index:10}.data-grid-row.keyboard-moving{background-color:var(--tbw-row-reorder-moving-bg, var(--tbw-focus-background));box-shadow:0 0 0 1px var(--tbw-row-reorder-moving-border, var(--tbw-color-accent)) inset}.data-grid-row.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}}';get defaultConfig(){return{enableKeyboard:!0,showDragHandle:!0,dragHandlePosition:"left",dragHandleWidth:40,debounceMs:150,animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}isDragging=!1;draggedRowIndex=null;dropRowIndex=null;pendingMove=null;debounceTimer=null;lastFocusCol=0;detach(){this.clearDebounceTimer(),this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.pendingMove=null}processColumns(e){if(!this.config.showDragHandle)return[...e];const t={field:o,header:"",width:this.config.dragHandleWidth??40,resizable:!1,sortable:!1,filterable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0},viewRenderer:()=>{const e=document.createElement("div");return e.className="dg-row-drag-handle",e.setAttribute("aria-label","Drag to reorder"),e.setAttribute("role","button"),e.setAttribute("tabindex","-1"),e.draggable=!0,this.setIcon(e,this.resolveIcon("dragHandle")),e}};return"right"===this.config.dragHandlePosition?[...e,t]:[t,...e]}afterRender(){if(!this.config.showDragHandle)return;const e=this.gridElement;if(!e)return;e.querySelectorAll(".dg-row-drag-handle").forEach(e=>{const t=e;if(t.getAttribute("data-drag-bound"))return;t.setAttribute("data-drag-bound","true");const r=t.closest(".data-grid-row");r&&this.setupHandleDragListeners(t,r)});e.querySelectorAll(".data-grid-row").forEach(e=>{const t=e;t.getAttribute("data-drop-bound")||(t.setAttribute("data-drop-bound","true"),this.setupRowDropListeners(t))})}onKeyDown(e){if(!this.config.enableKeyboard)return;if(!e.ctrlKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key)return;const t=this.grid,r=t._focusRow,o=t._rows??this.sourceRows;if(r<0||r>=o.length)return;const n="ArrowUp"===e.key?"up":"down",i="up"===n?r-1:r+1;if(i<0||i>=o.length)return;const s=o[r];return!this.config.canMove||this.config.canMove(s,r,i,n)?(this.handleKeyboardMove(s,r,i,n,t._focusCol),e.preventDefault(),e.stopPropagation(),!0):void 0}onCellClick(){this.flushPendingMove()}moveRow(e,t){const r=[...this.sourceRows];if(e<0||e>=r.length)return;if(t<0||t>=r.length)return;if(e===t)return;const o=t<e?"up":"down",n=r[e];this.config.canMove&&!this.config.canMove(n,e,t,o)||this.executeMove(n,e,t,"keyboard")}canMoveRow(e,t){const r=this.sourceRows;if(e<0||e>=r.length)return!1;if(t<0||t>=r.length)return!1;if(e===t)return!1;if(!this.config.canMove)return!0;const o=t<e?"up":"down";return this.config.canMove(r[e],e,t,o)}setupHandleDragListeners(e,t){e.addEventListener("dragstart",e=>{const r=this.getRowIndex(t);r<0||(this.isDragging=!0,this.draggedRowIndex=r,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",String(r))),t.classList.add("dragging"))}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedRowIndex=null,this.dropRowIndex=null,this.clearDragClasses()})}setupRowDropListeners(e){e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging||null===this.draggedRowIndex)return;const r=this.getRowIndex(e);if(r<0||r===this.draggedRowIndex)return;const o=e.getBoundingClientRect(),n=o.top+o.height/2,i=t.clientY<n;this.dropRowIndex=i?r:r+1,e.classList.add("drop-target"),e.classList.toggle("drop-before",i),e.classList.toggle("drop-after",!i)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedRowIndex;let r=this.dropRowIndex;if(this.isDragging&&null!==t&&null!==r&&(r>t&&r--,t!==r)){const e=this.sourceRows[t],o=r<t?"up":"down";this.config.canMove&&!this.config.canMove(e,t,r,o)||this.executeMove(e,t,r,"drag")}})}handleKeyboardMove(e,r,o,n,i){this.pendingMove?this.pendingMove.currentIndex=o:this.pendingMove={originalIndex:r,currentIndex:o,row:e},this.lastFocusCol=i;const s=this.grid,a=[...s._rows??this.sourceRows],[d]=a.splice(r,1);a.splice(o,0,d),s._rows=a,s._focusRow=o,s._focusCol=i,s.refreshVirtualWindow(!0),t.ensureCellVisible(s),this.clearDebounceTimer(),this.debounceTimer=setTimeout(()=>{this.flushPendingMove()},this.config.debounceMs??300)}flushPendingMove(){if(this.clearDebounceTimer(),!this.pendingMove)return;const{originalIndex:e,currentIndex:r,row:o}=this.pendingMove;if(this.pendingMove=null,e===r)return;const n={row:o,fromIndex:e,toIndex:r,rows:[...this.sourceRows],source:"keyboard"};if(this.emitCancelable("row-move",n)){const o=[...this.sourceRows],[n]=o.splice(r,1);o.splice(e,0,n);const i=this.grid;i._rows=o,i._focusRow=e,i._focusCol=this.lastFocusCol,i.refreshVirtualWindow(!0),t.ensureCellVisible(i)}}executeMove(e,t,r,o){const n=[...this.sourceRows],[i]=n.splice(t,1);n.splice(r,0,i);const s={row:e,fromIndex:t,toIndex:r,rows:n,source:o};if(!this.emitCancelable("row-move",s))if("flip"===this.animationType&&this.gridElement){const e=this.captureRowPositions();this.grid.rows=n,requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(e,t,r)})}else this.grid.rows=n}captureRowPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".data-grid-row").forEach(t=>{const r=this.getRowIndex(t);r>=0&&e.set(r,t.getBoundingClientRect().top)}),e}animateFLIP(e,t,r){const o=this.gridElement;if(!o||0===e.size)return;const n=Math.min(t,r),i=Math.max(t,r),s=[];if(o.querySelectorAll(".data-grid-row").forEach(o=>{const a=o,d=this.getRowIndex(a);if(d<0||d<n||d>i)return;let l;l=d===r?t:t<r?d+1:d-1;const c=e.get(l);if(void 0===c)return;const g=c-a.getBoundingClientRect().top;Math.abs(g)>1&&s.push({el:a,deltaY:g})}),0===s.length)return;s.forEach(({el:e,deltaY:t})=>{e.style.transform=`translateY(${t}px)`}),o.offsetHeight;const a=this.animationDuration;requestAnimationFrame(()=>{s.forEach(({el:e})=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{s.forEach(({el:e})=>{e.style.transform="",e.classList.remove("flip-animating")})},a+50)})}getRowIndex(e){const t=e.querySelector(".cell[data-row]");return t?parseInt(t.getAttribute("data-row")??"-1",10):-1}clearDragClasses(){this.gridElement?.querySelectorAll(".data-grid-row").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}e.ROW_DRAG_HANDLE_FIELD=o,e.RowReorderPlugin=n,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=row-reorder.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"row-reorder.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/row-reorder/RowReorderPlugin.ts"],"sourcesContent":["/**\n * Row Reordering Plugin\n *\n * Provides keyboard and drag-drop row reordering functionality for tbw-grid.\n * Supports Ctrl+Up/Down keyboard shortcuts and optional drag handle column.\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, InternalGrid } from '../../core/types';\nimport styles from './row-reorder.css?inline';\nimport type { PendingMove, RowMoveDetail, RowReorderConfig } from './types';\n\n/** Field name for the drag handle column */\nexport const ROW_DRAG_HANDLE_FIELD = '__tbw_row_drag';\n\n/**\n * Row Reorder Plugin for tbw-grid\n *\n * Enables row reordering via keyboard shortcuts (Ctrl+Up/Down) and drag-drop.\n * Supports validation callbacks and debounced keyboard moves.\n *\n * ## Installation\n *\n * ```ts\n * import { RowReorderPlugin } from '@toolbox-web/grid/plugins/row-reorder';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `enableKeyboard` | `boolean` | `true` | Enable Ctrl+Up/Down shortcuts |\n * | `showDragHandle` | `boolean` | `true` | Show drag handle column |\n * | `dragHandlePosition` | `'left' \\| 'right'` | `'left'` | Drag handle column position |\n * | `dragHandleWidth` | `number` | `40` | Drag handle column width |\n * | `canMove` | `function` | - | Validation callback |\n * | `debounceMs` | `number` | `300` | Debounce time for keyboard moves |\n * | `animation` | `false \\| 'flip'` | `'flip'` | Animation for row moves |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Ctrl + ↑` | Move focused row up |\n * | `Ctrl + ↓` | Move focused row down |\n *\n * ## Events\n *\n * | Event | Detail | Cancelable | Description |\n * |-------|--------|------------|-------------|\n * | `row-move` | `RowMoveDetail` | Yes | Fired when a row move is attempted |\n *\n * @example Basic Row Reordering\n * ```ts\n * import '@toolbox-web/grid';\n * import { RowReorderPlugin } from '@toolbox-web/grid/plugins/row-reorder';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * ],\n * plugins: [new RowReorderPlugin()],\n * };\n *\n * grid.addEventListener('row-move', (e) => {\n * console.log('Row moved from', e.detail.fromIndex, 'to', e.detail.toIndex);\n * });\n * ```\n *\n * @example With Validation\n * ```ts\n * new RowReorderPlugin({\n * canMove: (row, fromIndex, toIndex, direction) => {\n * // Prevent moving locked rows\n * return !row.locked;\n * },\n * })\n * ```\n *\n * @see {@link RowReorderConfig} for all configuration options\n * @see {@link RowMoveDetail} for the event detail structure\n */\nexport class RowReorderPlugin extends BaseGridPlugin<RowReorderConfig> {\n /** @internal */\n readonly name = 'rowReorder';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<RowReorderConfig> {\n return {\n enableKeyboard: true,\n showDragHandle: true,\n dragHandlePosition: 'left',\n dragHandleWidth: 40,\n debounceMs: 150,\n animation: 'flip',\n };\n }\n\n /**\n * Resolve animation type from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationType(): false | 'flip' {\n // Check if animations are globally disabled\n if (!this.isAnimationEnabled) return false;\n\n // Plugin config (with default from defaultConfig)\n if (this.config.animation !== undefined) return this.config.animation;\n\n return 'flip'; // Plugin default\n }\n\n // #region Internal State\n private isDragging = false;\n private draggedRowIndex: number | null = null;\n private dropRowIndex: number | null = null;\n private pendingMove: PendingMove | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Column index to use when flushing pending move */\n private lastFocusCol = 0;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.clearDebounceTimer();\n this.isDragging = false;\n this.draggedRowIndex = null;\n this.dropRowIndex = null;\n this.pendingMove = null;\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (!this.config.showDragHandle) {\n return [...columns];\n }\n\n const dragHandleColumn: ColumnConfig = {\n field: ROW_DRAG_HANDLE_FIELD,\n header: '',\n width: this.config.dragHandleWidth ?? 40,\n resizable: false,\n sortable: false,\n filterable: false,\n meta: {\n lockPosition: true,\n suppressMovable: true,\n utility: true,\n },\n viewRenderer: () => {\n const container = document.createElement('div');\n container.className = 'dg-row-drag-handle';\n container.setAttribute('aria-label', 'Drag to reorder');\n container.setAttribute('role', 'button');\n container.setAttribute('tabindex', '-1');\n // Set draggable as property (not just attribute) for proper HTML5 drag-drop\n container.draggable = true;\n\n // Use the grid's configured dragHandle icon\n this.setIcon(container, this.resolveIcon('dragHandle'));\n\n return container;\n },\n };\n\n // Position the drag handle column\n if (this.config.dragHandlePosition === 'right') {\n return [...columns, dragHandleColumn];\n }\n return [dragHandleColumn, ...columns];\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.config.showDragHandle) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Set up drag start/end listeners on drag handles\n const handles = gridEl.querySelectorAll('.dg-row-drag-handle');\n handles.forEach((handle) => {\n const handleEl = handle as HTMLElement;\n if (handleEl.getAttribute('data-drag-bound')) return;\n handleEl.setAttribute('data-drag-bound', 'true');\n\n const rowEl = handleEl.closest('.data-grid-row') as HTMLElement;\n if (!rowEl) return;\n\n // Set up dragstart/dragend on the handle\n this.setupHandleDragListeners(handleEl, rowEl);\n });\n\n // Set up drop target listeners on ALL rows (not just the handle's row)\n const rows = gridEl.querySelectorAll('.data-grid-row');\n rows.forEach((row) => {\n const rowEl = row as HTMLElement;\n if (rowEl.getAttribute('data-drop-bound')) return;\n rowEl.setAttribute('data-drop-bound', 'true');\n\n this.setupRowDropListeners(rowEl);\n });\n }\n\n /**\n * Handle Ctrl+Arrow keyboard shortcuts for row reordering.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n if (!this.config.enableKeyboard) return;\n if (!event.ctrlKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) {\n return;\n }\n\n const grid = this.grid as unknown as InternalGrid;\n const focusRow = grid._focusRow;\n // Use _rows (current visual state) for keyboard moves, not sourceRows\n // This ensures rapid moves work correctly since we update _rows directly\n // Fallback to sourceRows for compatibility with tests\n const rows = grid._rows ?? this.sourceRows;\n\n if (focusRow < 0 || focusRow >= rows.length) return;\n\n const direction = event.key === 'ArrowUp' ? 'up' : 'down';\n const toIndex = direction === 'up' ? focusRow - 1 : focusRow + 1;\n\n // Check bounds\n if (toIndex < 0 || toIndex >= rows.length) return;\n\n const row = rows[focusRow];\n\n // Validate move\n if (this.config.canMove && !this.config.canMove(row, focusRow, toIndex, direction)) {\n return;\n }\n\n // Debounce keyboard moves\n this.handleKeyboardMove(row, focusRow, toIndex, direction, grid._focusCol);\n\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n\n /**\n * Flush pending keyboard moves when user clicks a cell.\n * This commits the move immediately so focus works correctly.\n * @internal\n */\n override onCellClick(): void {\n // If there's a pending keyboard move, flush it immediately\n // so the user's click focus isn't overridden\n this.flushPendingMove();\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Move a row to a new position programmatically.\n * @param fromIndex - Current index of the row\n * @param toIndex - Target index\n */\n moveRow(fromIndex: number, toIndex: number): void {\n const rows = [...this.sourceRows];\n if (fromIndex < 0 || fromIndex >= rows.length) return;\n if (toIndex < 0 || toIndex >= rows.length) return;\n if (fromIndex === toIndex) return;\n\n const direction = toIndex < fromIndex ? 'up' : 'down';\n const row = rows[fromIndex];\n\n // Validate move\n if (this.config.canMove && !this.config.canMove(row, fromIndex, toIndex, direction)) {\n return;\n }\n\n this.executeMove(row, fromIndex, toIndex, 'keyboard');\n }\n\n /**\n * Check if a row can be moved to a position.\n * @param fromIndex - Current index of the row\n * @param toIndex - Target index\n */\n canMoveRow(fromIndex: number, toIndex: number): boolean {\n const rows = this.sourceRows;\n if (fromIndex < 0 || fromIndex >= rows.length) return false;\n if (toIndex < 0 || toIndex >= rows.length) return false;\n if (fromIndex === toIndex) return false;\n\n if (!this.config.canMove) return true;\n\n const direction = toIndex < fromIndex ? 'up' : 'down';\n return this.config.canMove(rows[fromIndex], fromIndex, toIndex, direction);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Set up drag start/end listeners on the drag handle element.\n */\n private setupHandleDragListeners(handleEl: HTMLElement, rowEl: HTMLElement): void {\n handleEl.addEventListener('dragstart', (e: DragEvent) => {\n const rowIndex = this.getRowIndex(rowEl);\n if (rowIndex < 0) return;\n\n this.isDragging = true;\n this.draggedRowIndex = rowIndex;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', String(rowIndex));\n }\n\n rowEl.classList.add('dragging');\n });\n\n handleEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedRowIndex = null;\n this.dropRowIndex = null;\n this.clearDragClasses();\n });\n }\n\n /**\n * Set up drop target listeners on a row element.\n * All rows are valid drop targets during drag operations.\n */\n private setupRowDropListeners(rowEl: HTMLElement): void {\n rowEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || this.draggedRowIndex === null) return;\n\n const targetIndex = this.getRowIndex(rowEl);\n if (targetIndex < 0 || targetIndex === this.draggedRowIndex) return;\n\n const rect = rowEl.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const isBefore = e.clientY < midY;\n\n this.dropRowIndex = isBefore ? targetIndex : targetIndex + 1;\n\n rowEl.classList.add('drop-target');\n rowEl.classList.toggle('drop-before', isBefore);\n rowEl.classList.toggle('drop-after', !isBefore);\n });\n\n rowEl.addEventListener('dragleave', () => {\n rowEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n rowEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n const fromIndex = this.draggedRowIndex;\n let toIndex = this.dropRowIndex;\n\n if (!this.isDragging || fromIndex === null || toIndex === null) {\n return;\n }\n\n // Adjust toIndex if dropping after the dragged row\n if (toIndex > fromIndex) {\n toIndex--;\n }\n\n if (fromIndex !== toIndex) {\n const rows = this.sourceRows;\n const row = rows[fromIndex];\n const direction = toIndex < fromIndex ? 'up' : 'down';\n\n // Validate move\n if (!this.config.canMove || this.config.canMove(row, fromIndex, toIndex, direction)) {\n this.executeMove(row, fromIndex, toIndex, 'drag');\n }\n }\n });\n }\n\n /**\n * Handle debounced keyboard moves.\n * Rows move immediately for visual feedback, but the event emission is debounced.\n */\n private handleKeyboardMove(\n row: unknown,\n fromIndex: number,\n toIndex: number,\n direction: 'up' | 'down',\n focusCol: number,\n ): void {\n // Track move for debounced event emission\n if (!this.pendingMove) {\n this.pendingMove = {\n originalIndex: fromIndex,\n currentIndex: toIndex,\n row,\n };\n } else {\n // Update the current index for rapid moves\n this.pendingMove.currentIndex = toIndex;\n }\n\n // Store focus column for flush\n this.lastFocusCol = focusCol;\n\n // Move rows immediately for visual feedback\n // Use _rows (current visual state) for rapid moves, not sourceRows\n // Fallback to sourceRows for compatibility with tests\n const grid = this.grid as unknown as InternalGrid;\n const rows = [...(grid._rows ?? this.sourceRows)];\n const [movedRow] = rows.splice(fromIndex, 1);\n rows.splice(toIndex, 0, movedRow);\n\n // Update grid rows immediately (without triggering change events)\n grid._rows = rows;\n\n // Update focus to follow the row\n grid._focusRow = toIndex;\n grid._focusCol = focusCol;\n\n // Refresh virtual window directly - this re-renders from _rows\n // without overwriting _rows from #rows (which requestRender does)\n grid.refreshVirtualWindow(true);\n\n // Ensure focus styling is applied after the row rebuild\n ensureCellVisible(grid);\n\n // Debounce the event emission only\n this.clearDebounceTimer();\n this.debounceTimer = setTimeout(() => {\n this.flushPendingMove();\n }, this.config.debounceMs ?? 300);\n }\n\n /**\n * Flush the pending move by emitting the event.\n * Called when debounce timer fires or user clicks elsewhere.\n */\n private flushPendingMove(): void {\n this.clearDebounceTimer();\n\n if (!this.pendingMove) return;\n\n const { originalIndex, currentIndex, row: movedRow } = this.pendingMove;\n this.pendingMove = null;\n\n if (originalIndex === currentIndex) return;\n\n // Emit cancelable event\n const detail: RowMoveDetail = {\n row: movedRow,\n fromIndex: originalIndex,\n toIndex: currentIndex,\n rows: [...this.sourceRows],\n source: 'keyboard',\n };\n\n const cancelled = this.emitCancelable('row-move', detail);\n if (cancelled) {\n // Revert to original position\n const rows = [...this.sourceRows];\n const [row] = rows.splice(currentIndex, 1);\n rows.splice(originalIndex, 0, row);\n\n const grid = this.grid as unknown as InternalGrid;\n grid._rows = rows;\n grid._focusRow = originalIndex;\n grid._focusCol = this.lastFocusCol;\n grid.refreshVirtualWindow(true);\n ensureCellVisible(grid);\n }\n }\n\n /**\n * Execute a row move and emit the event.\n */\n private executeMove(row: unknown, fromIndex: number, toIndex: number, source: 'keyboard' | 'drag'): void {\n const rows = [...this.sourceRows];\n const [movedRow] = rows.splice(fromIndex, 1);\n rows.splice(toIndex, 0, movedRow);\n\n const detail: RowMoveDetail = {\n row,\n fromIndex,\n toIndex,\n rows,\n source,\n };\n\n // Emit cancelable event\n const cancelled = this.emitCancelable('row-move', detail);\n if (!cancelled) {\n // Apply with animation if enabled\n if (this.animationType === 'flip' && this.gridElement) {\n const oldPositions = this.captureRowPositions();\n this.grid.rows = rows;\n // Wait for the scheduler to process the virtual window update (RAF)\n // before running FLIP animation on the new rows\n requestAnimationFrame(() => {\n void this.gridElement.offsetHeight;\n this.animateFLIP(oldPositions, fromIndex, toIndex);\n });\n } else {\n // No animation, just update rows\n this.grid.rows = rows;\n }\n }\n }\n\n /**\n * Capture row positions before reorder.\n * Maps visual row index to its top position.\n */\n private captureRowPositions(): Map<number, number> {\n const positions = new Map<number, number>();\n this.gridElement?.querySelectorAll('.data-grid-row').forEach((row) => {\n const rowIndex = this.getRowIndex(row as HTMLElement);\n if (rowIndex >= 0) {\n positions.set(rowIndex, row.getBoundingClientRect().top);\n }\n });\n return positions;\n }\n\n /**\n * Apply FLIP animation for row reorder.\n * Uses CSS transitions - JS sets initial transform and toggles class.\n * @param oldPositions - Row positions captured before DOM change\n * @param fromIndex - Original index of moved row\n * @param toIndex - New index of moved row\n */\n private animateFLIP(oldPositions: Map<number, number>, fromIndex: number, toIndex: number): void {\n const gridEl = this.gridElement;\n if (!gridEl || oldPositions.size === 0) return;\n\n // Calculate which row indices were affected and their new positions\n const minIndex = Math.min(fromIndex, toIndex);\n const maxIndex = Math.max(fromIndex, toIndex);\n\n // Build a map of new row index -> delta Y\n const rowsToAnimate: { el: HTMLElement; deltaY: number }[] = [];\n\n gridEl.querySelectorAll('.data-grid-row').forEach((row) => {\n const rowEl = row as HTMLElement;\n const newRowIndex = this.getRowIndex(rowEl);\n if (newRowIndex < 0 || newRowIndex < minIndex || newRowIndex > maxIndex) return;\n\n // Figure out what this row's old index was\n let oldIndex: number;\n if (newRowIndex === toIndex) {\n // This is the moved row\n oldIndex = fromIndex;\n } else if (fromIndex < toIndex) {\n // Row moved down: rows in between shifted up by 1\n oldIndex = newRowIndex + 1;\n } else {\n // Row moved up: rows in between shifted down by 1\n oldIndex = newRowIndex - 1;\n }\n\n const oldTop = oldPositions.get(oldIndex);\n if (oldTop === undefined) return;\n\n const newTop = rowEl.getBoundingClientRect().top;\n const deltaY = oldTop - newTop;\n\n if (Math.abs(deltaY) > 1) {\n rowsToAnimate.push({ el: rowEl, deltaY });\n }\n });\n\n if (rowsToAnimate.length === 0) return;\n\n // Set initial transform (First → Last position offset)\n rowsToAnimate.forEach(({ el, deltaY }) => {\n el.style.transform = `translateY(${deltaY}px)`;\n });\n\n // Force reflow then animate to final position via CSS transition\n void gridEl.offsetHeight;\n\n const duration = this.animationDuration;\n\n requestAnimationFrame(() => {\n rowsToAnimate.forEach(({ el }) => {\n el.classList.add('flip-animating');\n el.style.transform = '';\n });\n\n // Cleanup after animation\n setTimeout(() => {\n rowsToAnimate.forEach(({ el }) => {\n el.style.transform = '';\n el.classList.remove('flip-animating');\n });\n }, duration + 50);\n });\n }\n\n /**\n * Get the row index from a row element by checking data-row attribute on cells.\n * This is consistent with how other plugins retrieve row indices.\n */\n private getRowIndex(rowEl: HTMLElement): number {\n const cell = rowEl.querySelector('.cell[data-row]');\n return cell ? parseInt(cell.getAttribute('data-row') ?? '-1', 10) : -1;\n }\n\n /**\n * Clear all drag-related classes from rows.\n */\n private clearDragClasses(): void {\n this.gridElement?.querySelectorAll('.data-grid-row').forEach((row) => {\n row.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n\n /**\n * Clear the debounce timer.\n */\n private clearDebounceTimer(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n // #endregion\n}\n"],"names":["ROW_DRAG_HANDLE_FIELD","RowReorderPlugin","BaseGridPlugin","styles","columns","dragHandleColumn","container","gridEl","handle","handleEl","rowEl","row","event","grid","focusRow","rows","direction","toIndex","fromIndex","e","rowIndex","targetIndex","rect","midY","isBefore","focusCol","movedRow","ensureCellVisible","originalIndex","currentIndex","detail","source","oldPositions","positions","minIndex","maxIndex","rowsToAnimate","newRowIndex","oldIndex","oldTop","newTop","deltaY","el","duration","cell"],"mappings":"0xDAcaA,EAAwB,iBAuE9B,MAAMC,UAAyBC,EAAAA,cAAiC,CAE5D,KAAO,aAEE,OAASC,EAG3B,IAAuB,eAA2C,CAChE,MAAO,CACL,eAAgB,GAChB,eAAgB,GAChB,mBAAoB,OACpB,gBAAiB,GACjB,WAAY,IACZ,UAAW,MAAA,CAEf,CAMA,IAAY,eAAgC,CAE1C,OAAK,KAAK,mBAGN,KAAK,OAAO,YAAc,OAAkB,KAAK,OAAO,UAErD,OAL8B,EAMvC,CAGQ,WAAa,GACb,gBAAiC,KACjC,aAA8B,KAC9B,YAAkC,KAClC,cAAsD,KAEtD,aAAe,EAMd,QAAe,CACtB,KAAK,mBAAA,EACL,KAAK,WAAa,GAClB,KAAK,gBAAkB,KACvB,KAAK,aAAe,KACpB,KAAK,YAAc,IACrB,CAMS,eAAeC,EAAkD,CACxE,GAAI,CAAC,KAAK,OAAO,eACf,MAAO,CAAC,GAAGA,CAAO,EAGpB,MAAMC,EAAiC,CACrC,MAAOL,EACP,OAAQ,GACR,MAAO,KAAK,OAAO,iBAAmB,GACtC,UAAW,GACX,SAAU,GACV,WAAY,GACZ,KAAM,CACJ,aAAc,GACd,gBAAiB,GACjB,QAAS,EAAA,EAEX,aAAc,IAAM,CAClB,MAAMM,EAAY,SAAS,cAAc,KAAK,EAC9C,OAAAA,EAAU,UAAY,qBACtBA,EAAU,aAAa,aAAc,iBAAiB,EACtDA,EAAU,aAAa,OAAQ,QAAQ,EACvCA,EAAU,aAAa,WAAY,IAAI,EAEvCA,EAAU,UAAY,GAGtB,KAAK,QAAQA,EAAW,KAAK,YAAY,YAAY,CAAC,E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,CAAC,CAAE,GAAAM,EAAI,OAAAD,KAAa,CACxCC,EAAG,MAAM,UAAY,cAAcD,CAAM,KAC3C,CAAC,EAGIlC,EAAO,aAEZ,MAAMoC,EAAW,KAAK,kBAEtB,sBAAsB,IAAM,CAC1BP,EAAc,QAAQ,CAAC,CAAE,GAAAM,KAAS,CAChCA,EAAG,UAAU,IAAI,gBAAgB,EACjCA,EAAG,MAAM,UAAY,EACvB,CAAC,EAGD,WAAW,IAAM,CACfN,EAAc,QAAQ,CAAC,CAAE,GAAAM,KAAS,CAChCA,EAAG,MAAM,UAAY,GACrBA,EAAG,UAAU,OAAO,gBAAgB,CACtC,CAAC,CACH,EAAGC,EAAW,EAAE,CAClB,CAAC,CACH,CAMQ,YAAYjC,EAA4B,CAC9C,MAAMkC,EAAOlC,EAAM,cAAc,iBAAiB,EAClD,OAAOkC,EAAO,SAASA,EAAK,aAAa,UAAU,GAAK,KAAM,EAAE,EAAI,EACtE,CAKQ,kBAAyB,CAC/B,KAAK,aAAa,iBAAiB,gBAAgB,EAAE,QAASjC,GAAQ,CACpEA,EAAI,UAAU,OAAO,WAAY,cAAe,cAAe,YAAY,CAC7E,CAAC,CACH,CAKQ,oBAA2B,CAC7B,KAAK,gBACP,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,KAEzB,CAEF"}
1
+ {"version":3,"file":"row-reorder.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/row-reorder/RowReorderPlugin.ts"],"sourcesContent":["/**\n * Row Reordering Plugin\n *\n * Provides keyboard and drag-drop row reordering functionality for tbw-grid.\n * Supports Ctrl+Up/Down keyboard shortcuts and optional drag handle column.\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, InternalGrid } from '../../core/types';\nimport styles from './row-reorder.css?inline';\nimport type { PendingMove, RowMoveDetail, RowReorderConfig } from './types';\n\n/** Field name for the drag handle column */\nexport const ROW_DRAG_HANDLE_FIELD = '__tbw_row_drag';\n\n/**\n * Row Reorder Plugin for tbw-grid\n *\n * Enables row reordering via keyboard shortcuts (Ctrl+Up/Down) and drag-drop.\n * Supports validation callbacks and debounced keyboard moves.\n *\n * ## Installation\n *\n * ```ts\n * import { RowReorderPlugin } from '@toolbox-web/grid/plugins/row-reorder';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `enableKeyboard` | `boolean` | `true` | Enable Ctrl+Up/Down shortcuts |\n * | `showDragHandle` | `boolean` | `true` | Show drag handle column |\n * | `dragHandlePosition` | `'left' \\| 'right'` | `'left'` | Drag handle column position |\n * | `dragHandleWidth` | `number` | `40` | Drag handle column width |\n * | `canMove` | `function` | - | Validation callback |\n * | `debounceMs` | `number` | `300` | Debounce time for keyboard moves |\n * | `animation` | `false \\| 'flip'` | `'flip'` | Animation for row moves |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Ctrl + ↑` | Move focused row up |\n * | `Ctrl + ↓` | Move focused row down |\n *\n * ## Events\n *\n * | Event | Detail | Cancelable | Description |\n * |-------|--------|------------|-------------|\n * | `row-move` | `RowMoveDetail` | Yes | Fired when a row move is attempted |\n *\n * @example Basic Row Reordering\n * ```ts\n * import '@toolbox-web/grid';\n * import { RowReorderPlugin } from '@toolbox-web/grid/plugins/row-reorder';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * ],\n * plugins: [new RowReorderPlugin()],\n * };\n *\n * grid.addEventListener('row-move', (e) => {\n * console.log('Row moved from', e.detail.fromIndex, 'to', e.detail.toIndex);\n * });\n * ```\n *\n * @example With Validation\n * ```ts\n * new RowReorderPlugin({\n * canMove: (row, fromIndex, toIndex, direction) => {\n * // Prevent moving locked rows\n * return !row.locked;\n * },\n * })\n * ```\n *\n * @see {@link RowReorderConfig} for all configuration options\n * @see {@link RowMoveDetail} for the event detail structure\n */\nexport class RowReorderPlugin extends BaseGridPlugin<RowReorderConfig> {\n /** @internal */\n readonly name = 'rowReorder';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<RowReorderConfig> {\n return {\n enableKeyboard: true,\n showDragHandle: true,\n dragHandlePosition: 'left',\n dragHandleWidth: 40,\n debounceMs: 150,\n animation: 'flip',\n };\n }\n\n /**\n * Resolve animation type from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationType(): false | 'flip' {\n // Check if animations are globally disabled\n if (!this.isAnimationEnabled) return false;\n\n // Plugin config (with default from defaultConfig)\n if (this.config.animation !== undefined) return this.config.animation;\n\n return 'flip'; // Plugin default\n }\n\n // #region Internal State\n private isDragging = false;\n private draggedRowIndex: number | null = null;\n private dropRowIndex: number | null = null;\n private pendingMove: PendingMove | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Column index to use when flushing pending move */\n private lastFocusCol = 0;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.clearDebounceTimer();\n this.isDragging = false;\n this.draggedRowIndex = null;\n this.dropRowIndex = null;\n this.pendingMove = null;\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n if (!this.config.showDragHandle) {\n return [...columns];\n }\n\n const dragHandleColumn: ColumnConfig = {\n field: ROW_DRAG_HANDLE_FIELD,\n header: '',\n width: this.config.dragHandleWidth ?? 40,\n resizable: false,\n sortable: false,\n filterable: false,\n meta: {\n lockPosition: true,\n suppressMovable: true,\n utility: true,\n },\n viewRenderer: () => {\n const container = document.createElement('div');\n container.className = 'dg-row-drag-handle';\n container.setAttribute('aria-label', 'Drag to reorder');\n container.setAttribute('role', 'button');\n container.setAttribute('tabindex', '-1');\n // Set draggable as property (not just attribute) for proper HTML5 drag-drop\n container.draggable = true;\n\n // Use the grid's configured dragHandle icon\n this.setIcon(container, this.resolveIcon('dragHandle'));\n\n return container;\n },\n };\n\n // Position the drag handle column\n if (this.config.dragHandlePosition === 'right') {\n return [...columns, dragHandleColumn];\n }\n return [dragHandleColumn, ...columns];\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.config.showDragHandle) return;\n\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n // Set up drag start/end listeners on drag handles\n const handles = gridEl.querySelectorAll('.dg-row-drag-handle');\n handles.forEach((handle) => {\n const handleEl = handle as HTMLElement;\n if (handleEl.getAttribute('data-drag-bound')) return;\n handleEl.setAttribute('data-drag-bound', 'true');\n\n const rowEl = handleEl.closest('.data-grid-row') as HTMLElement;\n if (!rowEl) return;\n\n // Set up dragstart/dragend on the handle\n this.setupHandleDragListeners(handleEl, rowEl);\n });\n\n // Set up drop target listeners on ALL rows (not just the handle's row)\n const rows = gridEl.querySelectorAll('.data-grid-row');\n rows.forEach((row) => {\n const rowEl = row as HTMLElement;\n if (rowEl.getAttribute('data-drop-bound')) return;\n rowEl.setAttribute('data-drop-bound', 'true');\n\n this.setupRowDropListeners(rowEl);\n });\n }\n\n /**\n * Handle Ctrl+Arrow keyboard shortcuts for row reordering.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n if (!this.config.enableKeyboard) return;\n if (!event.ctrlKey || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) {\n return;\n }\n\n const grid = this.grid as unknown as InternalGrid;\n const focusRow = grid._focusRow;\n // Use _rows (current visual state) for keyboard moves, not sourceRows\n // This ensures rapid moves work correctly since we update _rows directly\n // Fallback to sourceRows for compatibility with tests\n const rows = grid._rows ?? this.sourceRows;\n\n if (focusRow < 0 || focusRow >= rows.length) return;\n\n const direction = event.key === 'ArrowUp' ? 'up' : 'down';\n const toIndex = direction === 'up' ? focusRow - 1 : focusRow + 1;\n\n // Check bounds\n if (toIndex < 0 || toIndex >= rows.length) return;\n\n const row = rows[focusRow];\n\n // Validate move\n if (this.config.canMove && !this.config.canMove(row, focusRow, toIndex, direction)) {\n return;\n }\n\n // Debounce keyboard moves\n this.handleKeyboardMove(row, focusRow, toIndex, direction, grid._focusCol);\n\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n\n /**\n * Flush pending keyboard moves when user clicks a cell.\n * This commits the move immediately so focus works correctly.\n * @internal\n */\n override onCellClick(): void {\n // If there's a pending keyboard move, flush it immediately\n // so the user's click focus isn't overridden\n this.flushPendingMove();\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Move a row to a new position programmatically.\n * @param fromIndex - Current index of the row\n * @param toIndex - Target index\n */\n moveRow(fromIndex: number, toIndex: number): void {\n const rows = [...this.sourceRows];\n if (fromIndex < 0 || fromIndex >= rows.length) return;\n if (toIndex < 0 || toIndex >= rows.length) return;\n if (fromIndex === toIndex) return;\n\n const direction = toIndex < fromIndex ? 'up' : 'down';\n const row = rows[fromIndex];\n\n // Validate move\n if (this.config.canMove && !this.config.canMove(row, fromIndex, toIndex, direction)) {\n return;\n }\n\n this.executeMove(row, fromIndex, toIndex, 'keyboard');\n }\n\n /**\n * Check if a row can be moved to a position.\n * @param fromIndex - Current index of the row\n * @param toIndex - Target index\n */\n canMoveRow(fromIndex: number, toIndex: number): boolean {\n const rows = this.sourceRows;\n if (fromIndex < 0 || fromIndex >= rows.length) return false;\n if (toIndex < 0 || toIndex >= rows.length) return false;\n if (fromIndex === toIndex) return false;\n\n if (!this.config.canMove) return true;\n\n const direction = toIndex < fromIndex ? 'up' : 'down';\n return this.config.canMove(rows[fromIndex], fromIndex, toIndex, direction);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Set up drag start/end listeners on the drag handle element.\n */\n private setupHandleDragListeners(handleEl: HTMLElement, rowEl: HTMLElement): void {\n handleEl.addEventListener('dragstart', (e: DragEvent) => {\n const rowIndex = this.getRowIndex(rowEl);\n if (rowIndex < 0) return;\n\n this.isDragging = true;\n this.draggedRowIndex = rowIndex;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', String(rowIndex));\n }\n\n rowEl.classList.add('dragging');\n });\n\n handleEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedRowIndex = null;\n this.dropRowIndex = null;\n this.clearDragClasses();\n });\n }\n\n /**\n * Set up drop target listeners on a row element.\n * All rows are valid drop targets during drag operations.\n */\n private setupRowDropListeners(rowEl: HTMLElement): void {\n rowEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || this.draggedRowIndex === null) return;\n\n const targetIndex = this.getRowIndex(rowEl);\n if (targetIndex < 0 || targetIndex === this.draggedRowIndex) return;\n\n const rect = rowEl.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const isBefore = e.clientY < midY;\n\n this.dropRowIndex = isBefore ? targetIndex : targetIndex + 1;\n\n rowEl.classList.add('drop-target');\n rowEl.classList.toggle('drop-before', isBefore);\n rowEl.classList.toggle('drop-after', !isBefore);\n });\n\n rowEl.addEventListener('dragleave', () => {\n rowEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n rowEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n const fromIndex = this.draggedRowIndex;\n let toIndex = this.dropRowIndex;\n\n if (!this.isDragging || fromIndex === null || toIndex === null) {\n return;\n }\n\n // Adjust toIndex if dropping after the dragged row\n if (toIndex > fromIndex) {\n toIndex--;\n }\n\n if (fromIndex !== toIndex) {\n const rows = this.sourceRows;\n const row = rows[fromIndex];\n const direction = toIndex < fromIndex ? 'up' : 'down';\n\n // Validate move\n if (!this.config.canMove || this.config.canMove(row, fromIndex, toIndex, direction)) {\n this.executeMove(row, fromIndex, toIndex, 'drag');\n }\n }\n });\n }\n\n /**\n * Handle debounced keyboard moves.\n * Rows move immediately for visual feedback, but the event emission is debounced.\n */\n private handleKeyboardMove(\n row: unknown,\n fromIndex: number,\n toIndex: number,\n direction: 'up' | 'down',\n focusCol: number,\n ): void {\n // Track move for debounced event emission\n if (!this.pendingMove) {\n this.pendingMove = {\n originalIndex: fromIndex,\n currentIndex: toIndex,\n row,\n };\n } else {\n // Update the current index for rapid moves\n this.pendingMove.currentIndex = toIndex;\n }\n\n // Store focus column for flush\n this.lastFocusCol = focusCol;\n\n // Move rows immediately for visual feedback\n // Use _rows (current visual state) for rapid moves, not sourceRows\n // Fallback to sourceRows for compatibility with tests\n const grid = this.grid as unknown as InternalGrid;\n const rows = [...(grid._rows ?? this.sourceRows)];\n const [movedRow] = rows.splice(fromIndex, 1);\n rows.splice(toIndex, 0, movedRow);\n\n // Update grid rows immediately (without triggering change events)\n grid._rows = rows;\n\n // Update focus to follow the row\n grid._focusRow = toIndex;\n grid._focusCol = focusCol;\n\n // Refresh virtual window directly - this re-renders from _rows\n // without overwriting _rows from #rows (which requestRender does)\n grid.refreshVirtualWindow(true);\n\n // Ensure focus styling is applied after the row rebuild\n ensureCellVisible(grid);\n\n // Debounce the event emission only\n this.clearDebounceTimer();\n this.debounceTimer = setTimeout(() => {\n this.flushPendingMove();\n }, this.config.debounceMs ?? 300);\n }\n\n /**\n * Flush the pending move by emitting the event.\n * Called when debounce timer fires or user clicks elsewhere.\n */\n private flushPendingMove(): void {\n this.clearDebounceTimer();\n\n if (!this.pendingMove) return;\n\n const { originalIndex, currentIndex, row: movedRow } = this.pendingMove;\n this.pendingMove = null;\n\n if (originalIndex === currentIndex) return;\n\n // Emit cancelable event\n const detail: RowMoveDetail = {\n row: movedRow,\n fromIndex: originalIndex,\n toIndex: currentIndex,\n rows: [...this.sourceRows],\n source: 'keyboard',\n };\n\n const cancelled = this.emitCancelable('row-move', detail);\n if (cancelled) {\n // Revert to original position\n const rows = [...this.sourceRows];\n const [row] = rows.splice(currentIndex, 1);\n rows.splice(originalIndex, 0, row);\n\n const grid = this.grid as unknown as InternalGrid;\n grid._rows = rows;\n grid._focusRow = originalIndex;\n grid._focusCol = this.lastFocusCol;\n grid.refreshVirtualWindow(true);\n ensureCellVisible(grid);\n }\n }\n\n /**\n * Execute a row move and emit the event.\n */\n private executeMove(row: unknown, fromIndex: number, toIndex: number, source: 'keyboard' | 'drag'): void {\n const rows = [...this.sourceRows];\n const [movedRow] = rows.splice(fromIndex, 1);\n rows.splice(toIndex, 0, movedRow);\n\n const detail: RowMoveDetail = {\n row,\n fromIndex,\n toIndex,\n rows,\n source,\n };\n\n // Emit cancelable event\n const cancelled = this.emitCancelable('row-move', detail);\n if (!cancelled) {\n // Apply with animation if enabled\n if (this.animationType === 'flip' && this.gridElement) {\n const oldPositions = this.captureRowPositions();\n this.grid.rows = rows;\n // Wait for the scheduler to process the virtual window update (RAF)\n // before running FLIP animation on the new rows\n requestAnimationFrame(() => {\n void this.gridElement.offsetHeight;\n this.animateFLIP(oldPositions, fromIndex, toIndex);\n });\n } else {\n // No animation, just update rows\n this.grid.rows = rows;\n }\n }\n }\n\n /**\n * Capture row positions before reorder.\n * Maps visual row index to its top position.\n */\n private captureRowPositions(): Map<number, number> {\n const positions = new Map<number, number>();\n this.gridElement?.querySelectorAll('.data-grid-row').forEach((row) => {\n const rowIndex = this.getRowIndex(row as HTMLElement);\n if (rowIndex >= 0) {\n positions.set(rowIndex, row.getBoundingClientRect().top);\n }\n });\n return positions;\n }\n\n /**\n * Apply FLIP animation for row reorder.\n * Uses CSS transitions - JS sets initial transform and toggles class.\n * @param oldPositions - Row positions captured before DOM change\n * @param fromIndex - Original index of moved row\n * @param toIndex - New index of moved row\n */\n private animateFLIP(oldPositions: Map<number, number>, fromIndex: number, toIndex: number): void {\n const gridEl = this.gridElement;\n if (!gridEl || oldPositions.size === 0) return;\n\n // Calculate which row indices were affected and their new positions\n const minIndex = Math.min(fromIndex, toIndex);\n const maxIndex = Math.max(fromIndex, toIndex);\n\n // Build a map of new row index -> delta Y\n const rowsToAnimate: { el: HTMLElement; deltaY: number }[] = [];\n\n gridEl.querySelectorAll('.data-grid-row').forEach((row) => {\n const rowEl = row as HTMLElement;\n const newRowIndex = this.getRowIndex(rowEl);\n if (newRowIndex < 0 || newRowIndex < minIndex || newRowIndex > maxIndex) return;\n\n // Figure out what this row's old index was\n let oldIndex: number;\n if (newRowIndex === toIndex) {\n // This is the moved row\n oldIndex = fromIndex;\n } else if (fromIndex < toIndex) {\n // Row moved down: rows in between shifted up by 1\n oldIndex = newRowIndex + 1;\n } else {\n // Row moved up: rows in between shifted down by 1\n oldIndex = newRowIndex - 1;\n }\n\n const oldTop = oldPositions.get(oldIndex);\n if (oldTop === undefined) return;\n\n const newTop = rowEl.getBoundingClientRect().top;\n const deltaY = oldTop - newTop;\n\n if (Math.abs(deltaY) > 1) {\n rowsToAnimate.push({ el: rowEl, deltaY });\n }\n });\n\n if (rowsToAnimate.length === 0) return;\n\n // Set initial transform (First → Last position offset)\n rowsToAnimate.forEach(({ el, deltaY }) => {\n el.style.transform = `translateY(${deltaY}px)`;\n });\n\n // Force reflow then animate to final position via CSS transition\n void gridEl.offsetHeight;\n\n const duration = this.animationDuration;\n\n requestAnimationFrame(() => {\n rowsToAnimate.forEach(({ el }) => {\n el.classList.add('flip-animating');\n el.style.transform = '';\n });\n\n // Cleanup after animation\n setTimeout(() => {\n rowsToAnimate.forEach(({ el }) => {\n el.style.transform = '';\n el.classList.remove('flip-animating');\n });\n }, duration + 50);\n });\n }\n\n /**\n * Get the row index from a row element by checking data-row attribute on cells.\n * This is consistent with how other plugins retrieve row indices.\n */\n private getRowIndex(rowEl: HTMLElement): number {\n const cell = rowEl.querySelector('.cell[data-row]');\n return cell ? parseInt(cell.getAttribute('data-row') ?? '-1', 10) : -1;\n }\n\n /**\n * Clear all drag-related classes from rows.\n */\n private clearDragClasses(): void {\n this.gridElement?.querySelectorAll('.data-grid-row').forEach((row) => {\n row.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n\n /**\n * Clear the debounce timer.\n */\n private clearDebounceTimer(): void {\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n // #endregion\n}\n"],"names":["ROW_DRAG_HANDLE_FIELD","RowReorderPlugin","BaseGridPlugin","name","styles","defaultConfig","enableKeyboard","showDragHandle","dragHandlePosition","dragHandleWidth","debounceMs","animation","animationType","this","isAnimationEnabled","config","isDragging","draggedRowIndex","dropRowIndex","pendingMove","debounceTimer","lastFocusCol","detach","clearDebounceTimer","processColumns","columns","dragHandleColumn","field","header","width","resizable","sortable","filterable","meta","lockPosition","suppressMovable","utility","viewRenderer","container","document","createElement","className","setAttribute","draggable","setIcon","resolveIcon","afterRender","gridEl","gridElement","querySelectorAll","forEach","handle","handleEl","getAttribute","rowEl","closest","setupHandleDragListeners","row","setupRowDropListeners","onKeyDown","event","ctrlKey","key","grid","focusRow","_focusRow","rows","_rows","sourceRows","length","direction","toIndex","canMove","handleKeyboardMove","_focusCol","preventDefault","stopPropagation","onCellClick","flushPendingMove","moveRow","fromIndex","executeMove","canMoveRow","addEventListener","e","rowIndex","getRowIndex","dataTransfer","effectAllowed","setData","String","classList","add","clearDragClasses","targetIndex","rect","getBoundingClientRect","midY","top","height","isBefore","clientY","toggle","remove","focusCol","currentIndex","originalIndex","movedRow","splice","refreshVirtualWindow","ensureCellVisible","setTimeout","detail","source","emitCancelable","oldPositions","captureRowPositions","requestAnimationFrame","offsetHeight","animateFLIP","positions","Map","set","size","minIndex","Math","min","maxIndex","max","rowsToAnimate","newRowIndex","oldIndex","oldTop","get","deltaY","abs","push","el","style","transform","duration","animationDuration","cell","querySelector","parseInt","clearTimeout"],"mappings":"6aAcaA,EAAwB,iBAuE9B,MAAMC,UAAyBC,EAAAA,eAE3BC,KAAO,aAEEC,g4CAGlB,iBAAuBC,GACrB,MAAO,CACLC,gBAAgB,EAChBC,gBAAgB,EAChBC,mBAAoB,OACpBC,gBAAiB,GACjBC,WAAY,IACZC,UAAW,OAEf,CAMA,iBAAYC,GAEV,QAAKC,KAAKC,0BAGoB,IAA1BD,KAAKE,OAAOJ,UAAgCE,KAAKE,OAAOJ,UAErD,OACT,CAGQK,YAAa,EACbC,gBAAiC,KACjCC,aA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AYhC,GACrC,GAAI4E,EAAc,GAAKA,EAAcN,GAAYM,EAAcH,EAAU,OAGzE,IAAII,EAGFA,EAFED,IAAgB3D,EAEPS,EACFA,EAAYT,EAEV2D,EAAc,EAGdA,EAAc,EAG3B,MAAME,EAASjB,EAAakB,IAAIF,GAChC,QAAe,IAAXC,EAAsB,OAE1B,MACME,EAASF,EADA9E,EAAM0C,wBAAwBE,IAGzC2B,KAAKU,IAAID,GAAU,GACrBL,EAAcO,KAAK,CAAEC,GAAInF,EAAOgF,aAIP,IAAzBL,EAAc5D,OAAc,OAGhC4D,EAAc/E,QAAQ,EAAGuF,KAAIH,aAC3BG,EAAGC,MAAMC,UAAY,cAAcL,SAIhCvF,EAAOuE,aAEZ,MAAMsB,EAAW/H,KAAKgI,kBAEtBxB,sBAAsB,KACpBY,EAAc/E,QAAQ,EAAGuF,SACvBA,EAAG9C,UAAUC,IAAI,kBACjB6C,EAAGC,MAAMC,UAAY,KAIvB5B,WAAW,KACTkB,EAAc/E,QAAQ,EAAGuF,SACvBA,EAAGC,MAAMC,UAAY,GACrBF,EAAG9C,UAAUY,OAAO,qBAErBqC,EAAW,KAElB,CAMQ,WAAAtD,CAAYhC,GAClB,MAAMwF,EAAOxF,EAAMyF,cAAc,mBACjC,OAAOD,EAAOE,SAASF,EAAKzF,aAAa,aAAe,KAAM,KAAM,CACtE,CAKQ,gBAAAwC,GACNhF,KAAKmC,aAAaC,iBAAiB,kBAAkBC,QAASO,IAC5DA,EAAIkC,UAAUY,OAAO,WAAY,cAAe,cAAe,eAEnE,CAKQ,kBAAAhF,GACFV,KAAKO,gBACP6H,aAAapI,KAAKO,eAClBP,KAAKO,cAAgB,KAEzB"}
@@ -1,4 +1,2 @@
1
- (function(f,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("../../core/internal/utils"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/utils","../../core/plugin/base-plugin","../../core/plugin/expander-column"],g):(f=typeof globalThis<"u"?globalThis:f||self,g(f.TbwGridPlugin_selection={},f.TbwGrid,f.TbwGrid,f.TbwGrid))})(this,(function(f,g,y,w){"use strict";function b(n){return{startRow:Math.min(n.startRow,n.endRow),startCol:Math.min(n.startCol,n.endCol),endRow:Math.max(n.startRow,n.endRow),endCol:Math.max(n.startCol,n.endCol)}}function x(n){const e=b(n);return{from:{row:e.startRow,col:e.startCol},to:{row:e.endRow,col:e.endCol}}}function S(n){return n.map(x)}function A(n,e,t){const s=b(t);return n>=s.startRow&&n<=s.endRow&&e>=s.startCol&&e<=s.endCol}function k(n,e,t){return t.some(s=>A(n,e,s))}function v(n){const e=[],t=b(n);for(let s=t.startRow;s<=t.endRow;s++)for(let i=t.startCol;i<=t.endCol;i++)e.push({row:s,col:i});return e}function E(n){const e=new Map;for(const t of n)for(const s of v(t))e.set(`${s.row},${s.col}`,s);return[...e.values()]}function p(n,e){return{startRow:n.row,startCol:n.col,endRow:e.row,endCol:e.col}}function m(n,e){const t=b(n),s=b(e);return t.startRow===s.startRow&&t.startCol===s.startCol&&t.endRow===s.endRow&&t.endCol===s.endCol}const I='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}',C="__tbw_checkbox";function K(n,e,t){if(n==="cell"&&e.selectedCell)return{mode:n,ranges:[{from:{row:e.selectedCell.row,col:e.selectedCell.col},to:{row:e.selectedCell.row,col:e.selectedCell.col}}]};if(n==="row"&&e.selected.size>0){const s=[...e.selected].sort((o,d)=>o-d),i=[];let l=s[0],r=l;for(let o=1;o<s.length;o++)s[o]===r+1?r=s[o]:(i.push({from:{row:l,col:0},to:{row:r,col:t-1}}),l=s[o],r=l);return i.push({from:{row:l,col:0},to:{row:r,col:t-1}}),{mode:n,ranges:i}}return n==="range"&&e.ranges.length>0?{mode:n,ranges:S(e.ranges)}:{mode:n,ranges:[]}}class q extends y.BaseGridPlugin{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:`"triggerOn: 'dblclick'" has no effect when mode is "range".
2
- → Range selection uses drag interaction (mousedown → mousemove), not click events.
3
- → The "triggerOn" option only affects "cell" and "row" selection modes.`,check:e=>e.mode==="range"&&e.triggerOn==="dblclick"}]};name="selection";styles=I;get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return this.config.enabled===!1?!1:this.grid.effectiveConfig?.selectable!==!1}checkSelectable(e,t){const{isSelectable:s}=this.config;if(!s)return!0;const i=this.rows[e];if(!i)return!1;const l=t!==void 0?this.visibleColumns[t]:void 0;return s(i,e,l,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){if(e.type==="getSelection")return this.getSelection();if(e.type==="getSelectedRowIndices")return this.getSelectedRowIndices();if(e.type==="getSelectedRows")return this.getSelectedRows();if(e.type==="selectRows")return this.selectRows(e.context),!0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:i}=e,{mode:l,triggerOn:r="click"}=this.config;if(i.type!==r)return!1;const o=e.column,d=o&&w.isUtilityColumn(o);if(l==="cell"){if(d||!this.isCellSelectable(t,s))return!1;const a=this.selectedCell;return a&&a.row===t&&a.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()),this.requestAfterRender()),!1}if(l==="row"){if(!this.isRowSelectable(t))return!1;const a=this.config.multiSelect!==!1,h=i.shiftKey&&a,c=(i.ctrlKey||i.metaKey)&&a,u=o?.meta?.checkboxColumn===!0;if(h&&this.anchor!==null){const M=Math.min(this.anchor,t),_=Math.max(this.anchor,t);c||this.selected.clear();for(let R=M;R<=_;R++)this.isRowSelectable(R)&&this.selected.add(R)}else if(c||u&&a)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(this.selected.size===1&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}if(l==="range"){if(d||!this.isCellSelectable(t,s))return!1;const a=i.shiftKey,h=(i.ctrlKey||i.metaKey)&&this.config.multiSelect!==!1;if(a&&this.cellAnchor){const c=p(this.cellAnchor,{row:t,col:s}),u=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(u&&m(u,c))return!1;h?this.ranges.length>0?this.ranges[this.ranges.length-1]=c:this.ranges.push(c):this.ranges=[c],this.activeRange=c}else if(h){const c={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(c),this.activeRange=c,this.cellAnchor={row:t,col:s}}else{const c={startRow:t,startCol:s,endRow:t,endCol:s};if(this.ranges.length===1&&m(this.ranges[0],c))return!1;this.ranges=[c],this.activeRange=c,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,i=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if(e.key==="Escape")return this.grid.query("isEditing").some(Boolean)?!1:(t==="cell"?this.selectedCell=null:t==="row"?(this.selected.clear(),this.anchor=null):t==="range"&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#e()),this.requestAfterRender(),!0);if(t==="cell"&&i)return queueMicrotask(()=>{const l=this.grid._focusRow,r=this.grid._focusCol;this.isCellSelectable(l,r)?this.selectedCell={row:l,col:r}:this.selectedCell=null,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1;if(t==="row"){const l=this.config.multiSelect!==!1;if(e.key==="ArrowUp"||e.key==="ArrowDown"){const r=e.shiftKey&&l;return r&&this.anchor===null&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const o=this.grid._focusRow;if(r&&this.anchor!==null){this.selected.clear();const d=Math.min(this.anchor,o),a=Math.max(this.anchor,o);for(let h=d;h<=a;h++)this.isRowSelectable(h)&&this.selected.add(h)}else this.isRowSelectable(o)?(this.selected.clear(),this.selected.add(o),this.anchor=o):this.selected.clear();this.lastSelected=o,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1}if(l&&e.key==="a"&&(e.ctrlKey||e.metaKey))return this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}if(t==="range"&&i){const l=e.key==="Tab",r=e.shiftKey&&!l;return r&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:r},queueMicrotask(()=>this.requestAfterRender()),!1}return t==="range"&&this.config.multiSelect!==!1&&e.key==="a"&&(e.ctrlKey||e.metaKey)?this.grid.query("isEditing").some(Boolean)?!1:(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0):!1}onCellMouseDown(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0||e.column&&w.isUtilityColumn(e.column)||!this.isCellSelectable(e.rowIndex,e.colIndex)||e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,s=e.colIndex,i=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&this.config.multiSelect!==!1,l={startRow:t,startCol:s,endRow:t,endCol:s};return!i&&this.ranges.length===1&&m(this.ranges[0],l)?(this.cellAnchor={row:t,col:s},!0):(this.cellAnchor={row:t,col:s},i||(this.ranges=[]),this.ranges.push(l),this.activeRange=l,this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled()||this.config.mode!=="range"||!this.isDragging||!this.cellAnchor||e.rowIndex===void 0||e.colIndex===void 0||e.rowIndex<0)return;let t=e.colIndex;const s=this.visibleColumns[t];if(s&&w.isUtilityColumn(s)){const r=this.visibleColumns.findIndex(o=>!w.isUtilityColumn(o));r>=0&&(t=r)}const i=p(this.cellAnchor,{row:e.rowIndex,col:t}),l=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return l&&m(l,i)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=i:this.ranges.push(i),this.activeRange=i,this.emit("selection-change",this.#e()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&this.config.mode==="range"&&this.isDragging)return this.isDragging=!1,!0}processColumns(e){if(this.config.checkbox&&this.config.mode==="row"){if(e.some(l=>l.field===C))return e;const t=this.#s(),s=e.findIndex(w.isExpanderColumn),i=s>=0?s+1:0;return[...e.slice(0,i),t,...e.slice(i)]}return e}#s(){return{field:C,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",this.config.multiSelect===!1)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",s=>{s.stopPropagation(),s.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const s=e.cellEl;if(s){const i=parseInt(s.getAttribute("data-row")??"-1",10);i>=0&&(t.checked=this.selected.has(i))}return t}}}#i(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(i=>{const l=i.closest(".cell"),r=l?g.getRowIndexFromCell(l):-1;r>=0&&(i.checked=this.selected.has(r))});const s=e.querySelector(".tbw-select-all-checkbox");if(s){const i=this.rows.length;let l=0;if(this.config.isSelectable)for(let d=0;d<i;d++)this.isRowSelectable(d)&&l++;else l=i;const r=l>0&&this.selected.size>=l,o=this.selected.size>0;s.checked=r,s.indeterminate=o&&!r}}#l(e){const t=this.grid._focusRow,s=this.grid._focusCol;if(e==="row"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t;return}t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(!this.selected.has(t)||this.selected.size!==1)&&(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#e())))}if(e==="cell"){if(this.explicitSelection){this.explicitSelection=!1,this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s;return}if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const i=this.selectedCell;(!i||i.row!==t||i.col!==s)&&(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()))}}}#t(){const e=this.gridElement;if(!e)return;const{mode:t}=this.config,s=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(r=>{r.classList.remove("selected","top","bottom","first","last"),s&&r.removeAttribute("data-selectable")});const l=e.querySelectorAll(".data-grid-row");if(l.forEach(r=>{r.classList.remove("selected","row-focus"),s&&r.removeAttribute("data-selectable")}),t==="row"&&(g.clearCellFocus(e),l.forEach(r=>{const o=r.querySelector(".cell[data-row]"),d=g.getRowIndexFromCell(o);d>=0&&(s&&!this.isRowSelectable(d)&&r.setAttribute("data-selectable","false"),this.selected.has(d)&&r.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#i(e)),(t==="cell"||t==="range")&&s&&e.querySelectorAll(".cell[data-row][data-col]").forEach(o=>{const d=parseInt(o.getAttribute("data-row")??"-1",10),a=parseInt(o.getAttribute("data-col")??"-1",10);d>=0&&a>=0&&(this.isCellSelectable(d,a)||o.setAttribute("data-selectable","false"))}),t==="range"&&this.ranges.length>0){g.clearCellFocus(e);const r=this.ranges.map(b),o=(a,h)=>{for(const c of r)if(a>=c.startRow&&a<=c.endRow&&h>=c.startCol&&h<=c.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(a=>{const h=parseInt(a.getAttribute("data-row")??"-1",10),c=parseInt(a.getAttribute("data-col")??"-1",10);if(h>=0&&c>=0){const u=this.visibleColumns[c];if(u&&w.isUtilityColumn(u))return;o(h,c)&&(a.classList.add("selected"),o(h-1,c)||a.classList.add("top"),o(h+1,c)||a.classList.add("bottom"),o(h,c-1)||a.classList.add("first"),o(h,c+1)||a.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:s}=this.config;if(this.pendingKeyboardUpdate&&s==="range"){const{shiftKey:i}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const l=this.grid._focusRow,r=this.grid._focusCol;if(i&&this.cellAnchor){const o=p(this.cellAnchor,{row:l,col:r});this.ranges=[o],this.activeRange=o}else i||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:l,col:r});this.emit("selection-change",this.#e())}this.#l(s),this.grid.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#t()}onScrollRender(){this.isSelectionEnabled()&&this.#t()}getSelection(){return{mode:this.config.mode,ranges:this.#e().ranges,anchor:this.cellAnchor}}getSelectedCells(){return E(this.ranges)}isCellSelected(e,t){return k(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(t!==!1){if(e==="row"){this.selected.clear();for(let s=0;s<this.rows.length;s++)this.isRowSelectable(s)&&this.selected.add(s);this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}else if(e==="range"){const s=this.rows.length,i=this.columns.length;if(s>0&&i>0){const l={startRow:0,startCol:0,endRow:s-1,endCol:i-1};this.ranges=[l],this.activeRange=l,this.emit("selection-change",this.#e()),this.requestAfterRender()}}}}selectRows(e){if(this.config.mode!=="row")return;const t=this.config.multiSelect===!1&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if(e==="row")return this.getSelectedRowIndices().filter(s=>s>=0&&s<t.length).map(s=>t[s]);if(e==="cell"&&this.selectedCell){const{row:s}=this.selectedCell;return s>=0&&s<t.length?[t[s]]:[]}if(e==="range"&&this.ranges.length>0){const s=new Set;for(const i of this.ranges){const l=Math.max(0,Math.min(i.startRow,i.endRow)),r=Math.min(t.length-1,Math.max(i.startRow,i.endRow));for(let o=l;o<=r;o++)s.add(o)}return[...s].sort((i,l)=>i-l).map(i=>t[i])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(t=>({startRow:t.from.row,startCol:t.from.col,endRow:t.to.row,endCol:t.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:S(this.ranges)}),this.requestAfterRender()}#e(){return K(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}f.SelectionPlugin=q,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/utils"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/utils","../../core/plugin/base-plugin","../../core/plugin/expander-column"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_selection={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,s,i){"use strict";function l(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function o(e){const t=l(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function r(e){return e.map(o)}function n(e,t,s){return s.some(s=>function(e,t,s){const i=l(s);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,s))}function c(e){const t=[],s=l(e);for(let i=s.startRow;i<=s.endRow;i++)for(let e=s.startCol;e<=s.endCol;e++)t.push({row:i,col:e});return t}function a(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function d(e,t){const s=l(e),i=l(t);return s.startRow===i.startRow&&s.startCol===i.startCol&&s.endRow===i.endRow&&s.endCol===i.endCol}const h="__tbw_checkbox";class g extends s.BaseGridPlugin{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===e.mode&&"dblclick"===e.triggerOn}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:s}=this.config;if(!s)return!0;const i=this.rows[e];if(!i)return!1;return s(i,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){return"getSelection"===e.type?this.getSelection():"getSelectedRowIndices"===e.type?this.getSelectedRowIndices():"getSelectedRows"===e.type?this.getSelectedRows():"selectRows"===e.type?(this.selectRows(e.context),!0):void 0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:l}=e,{mode:o,triggerOn:r="click"}=this.config;if(l.type!==r)return!1;const n=e.column,c=n&&i.isUtilityColumn(n);if("cell"===o){if(c)return!1;if(!this.isCellSelectable(t,s))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()),this.requestAfterRender()),!1}if("row"===o){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,s=l.shiftKey&&e,i=(l.ctrlKey||l.metaKey)&&e,o=!0===n?.meta?.checkboxColumn;if(s&&null!==this.anchor){const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);i||this.selected.clear();for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(i||o&&e)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}if("range"===o){if(c)return!1;if(!this.isCellSelectable(t,s))return!1;const e=l.shiftKey,i=(l.ctrlKey||l.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=a(this.cellAnchor,{row:t,col:s}),l=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(l&&d(l,e))return!1;i?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(i){const e={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:s}}else{const e={startRow:t,startCol:s,endRow:t,endCol:s};if(1===this.ranges.length&&d(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if("Escape"===e.key){return!this.grid.query("isEditing").some(Boolean)&&("cell"===t?this.selectedCell=null:"row"===t?(this.selected.clear(),this.anchor=null):"range"===t&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}if("cell"===t&&s)return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.isCellSelectable(e,t)?this.selectedCell={row:e,col:t}:this.selectedCell=null,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key){const s=e.shiftKey&&t;return s&&null===this.anchor&&(this.anchor=this.grid._focusRow),queueMicrotask(()=>{const e=this.grid._focusRow;if(s&&null!==this.anchor){this.selected.clear();const t=Math.min(this.anchor,e),s=Math.max(this.anchor,e);for(let e=t;e<=s;e++)this.isRowSelectable(e)&&this.selected.add(e)}else this.isRowSelectable(e)?(this.selected.clear(),this.selected.add(e),this.anchor=e):this.selected.clear();this.lastSelected=e,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}}if("range"===t&&s){const t="Tab"===e.key,s=e.shiftKey&&!t;return s&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(e.column&&i.isUtilityColumn(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,s=e.colIndex,l=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,o={startRow:t,startCol:s,endRow:t,endCol:s};return!l&&1===this.ranges.length&&d(this.ranges[0],o)?(this.cellAnchor={row:t,col:s},!0):(this.cellAnchor={row:t,col:s},l||(this.ranges=[]),this.ranges.push(o),this.activeRange=o,this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const s=this.visibleColumns[t];if(s&&i.isUtilityColumn(s)){const e=this.visibleColumns.findIndex(e=>!i.isUtilityColumn(e));e>=0&&(t=e)}const l=a(this.cellAnchor,{row:e.rowIndex,col:t}),o=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return o&&d(o,l)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=l:this.ranges.push(l),this.activeRange=l,this.emit("selection-change",this.#e()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.config.mode)return this.isDragging?(this.isDragging=!1,!0):void 0}processColumns(e){if(this.config.checkbox&&"row"===this.config.mode){if(e.some(e=>e.field===h))return e;const t=this.#t(),s=e.findIndex(i.isExpanderColumn),l=s>=0?s+1:0;return[...e.slice(0,l),t,...e.slice(l)]}return e}#t(){return{field:h,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const s=e.cellEl;if(s){const e=parseInt(s.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#s(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const s=e.closest(".cell"),i=s?t.getRowIndexFromCell(s):-1;i>=0&&(e.checked=this.selected.has(i))});const s=e.querySelector(".tbw-select-all-checkbox");if(s){const e=this.rows.length;let t=0;if(this.config.isSelectable)for(let s=0;s<e;s++)this.isRowSelectable(s)&&t++;else t=e;const i=t>0&&this.selected.size>=t,l=this.selected.size>0;s.checked=i,s.indeterminate=l&&!i}}#i(e){const t=this.grid._focusRow,s=this.grid._focusCol;if("row"===e){if(this.explicitSelection)return this.explicitSelection=!1,void(this.lastSyncedFocusRow=t);t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(this.selected.has(t)&&1===this.selected.size||(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#e()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const e=this.selectedCell;e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()))}}}#l(){const e=this.gridElement;if(!e)return;const{mode:s}=this.config,o=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(e=>{e.classList.remove("selected","top","bottom","first","last"),o&&e.removeAttribute("data-selectable")});const r=e.querySelectorAll(".data-grid-row");if(r.forEach(e=>{e.classList.remove("selected","row-focus"),o&&e.removeAttribute("data-selectable")}),"row"===s&&(t.clearCellFocus(e),r.forEach(e=>{const s=e.querySelector(".cell[data-row]"),i=t.getRowIndexFromCell(s);i>=0&&(o&&!this.isRowSelectable(i)&&e.setAttribute("data-selectable","false"),this.selected.has(i)&&e.classList.add("selected","row-focus"))}),this.config.checkbox&&this.#s(e)),("cell"===s||"range"===s)&&o){e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&s>=0&&(this.isCellSelectable(t,s)||e.setAttribute("data-selectable","false"))})}if("range"===s&&this.ranges.length>0){t.clearCellFocus(e);const s=this.ranges.map(l),o=(e,t)=>{for(const i of s)if(e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&s>=0){const l=this.visibleColumns[s];if(l&&i.isUtilityColumn(l))return;o(t,s)&&(e.classList.add("selected"),o(t-1,s)||e.classList.add("top"),o(t+1,s)||e.classList.add("bottom"),o(t,s-1)||e.classList.add("first"),o(t,s+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:s}=this.config;if(this.pendingKeyboardUpdate&&"range"===s){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,s=this.grid._focusCol;if(e&&this.cellAnchor){const e=a(this.cellAnchor,{row:t,col:s});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:s});this.emit("selection-change",this.#e())}this.#i(s),this.grid.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#l()}onScrollRender(){this.isSelectionEnabled()&&this.#l()}getSelection(){return{mode:this.config.mode,ranges:this.#e().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const s of e)for(const e of c(s))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return n(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const s={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[s],this.activeRange=s,this.emit("selection-change",this.#e()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.config.mode)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=new Set;for(const s of this.ranges){const i=Math.max(0,Math.min(s.startRow,s.endRow)),l=Math.min(t.length-1,Math.max(s.startRow,s.endRow));for(let t=i;t<=l;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:r(this.ranges)}),this.requestAfterRender()}#e(){return function(e,t,s){if("cell"===e&&t.selectedCell)return{mode:e,ranges:[{from:{row:t.selectedCell.row,col:t.selectedCell.col},to:{row:t.selectedCell.row,col:t.selectedCell.col}}]};if("row"===e&&t.selected.size>0){const i=[...t.selected].sort((e,t)=>e-t),l=[];let o=i[0],r=o;for(let e=1;e<i.length;e++)i[e]===r+1?r=i[e]:(l.push({from:{row:o,col:0},to:{row:r,col:s-1}}),o=i[e],r=o);return l.push({from:{row:o,col:0},to:{row:r,col:s-1}}),{mode:e,ranges:l}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:r(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}e.SelectionPlugin=g,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
4
2
  //# sourceMappingURL=selection.umd.js.map