@toolbox-web/grid 1.23.4 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +35 -6
  2. package/all.d.ts +2 -2
  3. package/all.d.ts.map +1 -1
  4. package/all.js +2 -2
  5. package/all.js.map +1 -1
  6. package/index.js +1 -1
  7. package/index.js.map +1 -1
  8. package/lib/core/grid.d.ts +21 -0
  9. package/lib/core/grid.d.ts.map +1 -1
  10. package/lib/core/internal/feature-hook.d.ts +8 -0
  11. package/lib/core/internal/feature-hook.d.ts.map +1 -0
  12. package/lib/core/plugin/base-plugin.d.ts +8 -2
  13. package/lib/core/plugin/base-plugin.d.ts.map +1 -1
  14. package/lib/core/plugin/types.d.ts +1 -1
  15. package/lib/core/types.d.ts +59 -0
  16. package/lib/core/types.d.ts.map +1 -1
  17. package/lib/features/clipboard.d.ts +8 -0
  18. package/lib/features/clipboard.d.ts.map +1 -0
  19. package/lib/features/clipboard.js +2 -0
  20. package/lib/features/clipboard.js.map +1 -0
  21. package/lib/features/column-virtualization.d.ts +8 -0
  22. package/lib/features/column-virtualization.d.ts.map +1 -0
  23. package/lib/features/column-virtualization.js +2 -0
  24. package/lib/features/column-virtualization.js.map +1 -0
  25. package/lib/features/context-menu.d.ts +8 -0
  26. package/lib/features/context-menu.d.ts.map +1 -0
  27. package/lib/features/context-menu.js +2 -0
  28. package/lib/features/context-menu.js.map +1 -0
  29. package/lib/features/editing.d.ts +8 -0
  30. package/lib/features/editing.d.ts.map +1 -0
  31. package/lib/features/editing.js +2 -0
  32. package/lib/features/editing.js.map +1 -0
  33. package/lib/features/export.d.ts +8 -0
  34. package/lib/features/export.d.ts.map +1 -0
  35. package/lib/features/export.js +2 -0
  36. package/lib/features/export.js.map +1 -0
  37. package/lib/features/filtering.d.ts +8 -0
  38. package/lib/features/filtering.d.ts.map +1 -0
  39. package/lib/features/filtering.js +2 -0
  40. package/lib/features/filtering.js.map +1 -0
  41. package/lib/features/grouping-columns.d.ts +8 -0
  42. package/lib/features/grouping-columns.d.ts.map +1 -0
  43. package/lib/features/grouping-columns.js +2 -0
  44. package/lib/features/grouping-columns.js.map +1 -0
  45. package/lib/features/grouping-rows.d.ts +8 -0
  46. package/lib/features/grouping-rows.d.ts.map +1 -0
  47. package/lib/features/grouping-rows.js +2 -0
  48. package/lib/features/grouping-rows.js.map +1 -0
  49. package/lib/features/magic-string.es-CkyDP9Ir.mjs.map +1 -0
  50. package/lib/features/master-detail.d.ts +8 -0
  51. package/lib/features/master-detail.d.ts.map +1 -0
  52. package/lib/features/master-detail.js +2 -0
  53. package/lib/features/master-detail.js.map +1 -0
  54. package/lib/features/multi-sort.d.ts +10 -0
  55. package/lib/features/multi-sort.d.ts.map +1 -0
  56. package/lib/features/multi-sort.js +2 -0
  57. package/lib/features/multi-sort.js.map +1 -0
  58. package/lib/features/pinned-columns.d.ts +18 -0
  59. package/lib/features/pinned-columns.d.ts.map +1 -0
  60. package/lib/features/pinned-columns.js +2 -0
  61. package/lib/features/pinned-columns.js.map +1 -0
  62. package/lib/features/pinned-rows.d.ts +8 -0
  63. package/lib/features/pinned-rows.d.ts.map +1 -0
  64. package/lib/features/pinned-rows.js +2 -0
  65. package/lib/features/pinned-rows.js.map +1 -0
  66. package/lib/features/pivot.d.ts +8 -0
  67. package/lib/features/pivot.d.ts.map +1 -0
  68. package/lib/features/pivot.js +2 -0
  69. package/lib/features/pivot.js.map +1 -0
  70. package/lib/features/print.d.ts +8 -0
  71. package/lib/features/print.d.ts.map +1 -0
  72. package/lib/features/print.js +2 -0
  73. package/lib/features/print.js.map +1 -0
  74. package/lib/features/registry.d.ts +50 -0
  75. package/lib/features/registry.d.ts.map +1 -0
  76. package/lib/features/registry.js +2 -0
  77. package/lib/features/registry.js.map +1 -0
  78. package/lib/features/registry.spec.js +5 -0
  79. package/lib/features/registry.spec.js.map +1 -0
  80. package/lib/features/reorder-columns.d.ts +10 -0
  81. package/lib/features/reorder-columns.d.ts.map +1 -0
  82. package/lib/features/reorder-columns.js +2 -0
  83. package/lib/features/reorder-columns.js.map +1 -0
  84. package/lib/features/reorder-rows.d.ts +10 -0
  85. package/lib/features/reorder-rows.d.ts.map +1 -0
  86. package/lib/features/reorder-rows.js +2 -0
  87. package/lib/features/reorder-rows.js.map +1 -0
  88. package/lib/features/responsive.d.ts +8 -0
  89. package/lib/features/responsive.d.ts.map +1 -0
  90. package/lib/features/responsive.js +2 -0
  91. package/lib/features/responsive.js.map +1 -0
  92. package/lib/features/selection.d.ts +8 -0
  93. package/lib/features/selection.d.ts.map +1 -0
  94. package/lib/features/selection.js +2 -0
  95. package/lib/features/selection.js.map +1 -0
  96. package/lib/features/server-side.d.ts +8 -0
  97. package/lib/features/server-side.d.ts.map +1 -0
  98. package/lib/features/server-side.js +2 -0
  99. package/lib/features/server-side.js.map +1 -0
  100. package/lib/features/tree.d.ts +8 -0
  101. package/lib/features/tree.d.ts.map +1 -0
  102. package/lib/features/tree.js +2 -0
  103. package/lib/features/tree.js.map +1 -0
  104. package/lib/features/undo-redo.d.ts +8 -0
  105. package/lib/features/undo-redo.d.ts.map +1 -0
  106. package/lib/features/undo-redo.js +2 -0
  107. package/lib/features/undo-redo.js.map +1 -0
  108. package/lib/features/visibility.d.ts +8 -0
  109. package/lib/features/visibility.d.ts.map +1 -0
  110. package/lib/features/visibility.js +2 -0
  111. package/lib/features/visibility.js.map +1 -0
  112. package/lib/plugins/clipboard/index.js +1 -1
  113. package/lib/plugins/clipboard/index.js.map +1 -1
  114. package/lib/plugins/column-virtualization/index.js +1 -1
  115. package/lib/plugins/column-virtualization/index.js.map +1 -1
  116. package/lib/plugins/context-menu/index.js +1 -1
  117. package/lib/plugins/context-menu/index.js.map +1 -1
  118. package/lib/plugins/editing/index.js +1 -1
  119. package/lib/plugins/editing/index.js.map +1 -1
  120. package/lib/plugins/export/index.js +1 -1
  121. package/lib/plugins/export/index.js.map +1 -1
  122. package/lib/plugins/filtering/index.js +1 -1
  123. package/lib/plugins/filtering/index.js.map +1 -1
  124. package/lib/plugins/filtering/types.d.ts +428 -27
  125. package/lib/plugins/filtering/types.d.ts.map +1 -1
  126. package/lib/plugins/grouping-columns/index.d.ts +1 -1
  127. package/lib/plugins/grouping-columns/index.js +1 -1
  128. package/lib/plugins/grouping-columns/index.js.map +1 -1
  129. package/lib/plugins/grouping-rows/index.d.ts +2 -2
  130. package/lib/plugins/grouping-rows/index.d.ts.map +1 -1
  131. package/lib/plugins/grouping-rows/index.js +1 -1
  132. package/lib/plugins/grouping-rows/index.js.map +1 -1
  133. package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +2 -2
  134. package/lib/plugins/master-detail/index.js +1 -1
  135. package/lib/plugins/master-detail/index.js.map +1 -1
  136. package/lib/plugins/multi-sort/index.js +1 -1
  137. package/lib/plugins/multi-sort/index.js.map +1 -1
  138. package/lib/plugins/pinned-columns/index.js +1 -1
  139. package/lib/plugins/pinned-columns/index.js.map +1 -1
  140. package/lib/plugins/pinned-columns/types.d.ts +3 -3
  141. package/lib/plugins/pinned-rows/index.js +1 -1
  142. package/lib/plugins/pinned-rows/index.js.map +1 -1
  143. package/lib/plugins/pivot/index.js +1 -1
  144. package/lib/plugins/pivot/index.js.map +1 -1
  145. package/lib/plugins/print/index.js +1 -1
  146. package/lib/plugins/print/index.js.map +1 -1
  147. package/lib/plugins/{reorder → reorder-columns}/ReorderPlugin.d.ts +5 -3
  148. package/lib/plugins/reorder-columns/ReorderPlugin.d.ts.map +1 -0
  149. package/lib/plugins/reorder-columns/column-drag.d.ts.map +1 -0
  150. package/lib/plugins/{reorder → reorder-columns}/index.d.ts +2 -2
  151. package/lib/plugins/reorder-columns/index.d.ts.map +1 -0
  152. package/lib/plugins/reorder-columns/index.js +2 -0
  153. package/lib/plugins/reorder-columns/index.js.map +1 -0
  154. package/lib/plugins/{reorder → reorder-columns}/types.d.ts +5 -0
  155. package/lib/plugins/reorder-columns/types.d.ts.map +1 -0
  156. package/lib/plugins/{row-reorder → reorder-rows}/RowReorderPlugin.d.ts +5 -3
  157. package/lib/plugins/reorder-rows/RowReorderPlugin.d.ts.map +1 -0
  158. package/lib/plugins/{row-reorder → reorder-rows}/index.d.ts +2 -2
  159. package/lib/plugins/reorder-rows/index.d.ts.map +1 -0
  160. package/lib/plugins/reorder-rows/index.js +2 -0
  161. package/lib/plugins/reorder-rows/index.js.map +1 -0
  162. package/lib/plugins/{row-reorder → reorder-rows}/types.d.ts +5 -0
  163. package/lib/plugins/reorder-rows/types.d.ts.map +1 -0
  164. package/lib/plugins/responsive/ResponsivePlugin.d.ts +2 -2
  165. package/lib/plugins/responsive/index.js +1 -1
  166. package/lib/plugins/responsive/index.js.map +1 -1
  167. package/lib/plugins/selection/index.js +1 -1
  168. package/lib/plugins/selection/index.js.map +1 -1
  169. package/lib/plugins/server-side/index.js +1 -1
  170. package/lib/plugins/server-side/index.js.map +1 -1
  171. package/lib/plugins/tree/index.js +1 -1
  172. package/lib/plugins/tree/index.js.map +1 -1
  173. package/lib/plugins/undo-redo/index.js +1 -1
  174. package/lib/plugins/undo-redo/index.js.map +1 -1
  175. package/lib/plugins/visibility/VisibilityPlugin.d.ts +1 -1
  176. package/lib/plugins/visibility/index.js +1 -1
  177. package/lib/plugins/visibility/index.js.map +1 -1
  178. package/package.json +17 -2
  179. package/public.d.ts +9 -2
  180. package/public.d.ts.map +1 -1
  181. package/umd/grid.all.umd.js +1 -1
  182. package/umd/grid.all.umd.js.map +1 -1
  183. package/umd/grid.umd.js +1 -1
  184. package/umd/grid.umd.js.map +1 -1
  185. package/umd/plugins/master-detail.umd.js.map +1 -1
  186. package/umd/plugins/reorder-columns.umd.js +2 -0
  187. package/umd/plugins/reorder-columns.umd.js.map +1 -0
  188. package/umd/plugins/reorder-rows.umd.js +2 -0
  189. package/umd/plugins/reorder-rows.umd.js.map +1 -0
  190. package/umd/plugins/responsive.umd.js.map +1 -1
  191. package/umd/plugins/visibility.umd.js.map +1 -1
  192. package/lib/plugins/reorder/ReorderPlugin.d.ts.map +0 -1
  193. package/lib/plugins/reorder/column-drag.d.ts.map +0 -1
  194. package/lib/plugins/reorder/index.d.ts.map +0 -1
  195. package/lib/plugins/reorder/index.js +0 -2
  196. package/lib/plugins/reorder/index.js.map +0 -1
  197. package/lib/plugins/reorder/types.d.ts.map +0 -1
  198. package/lib/plugins/row-reorder/RowReorderPlugin.d.ts.map +0 -1
  199. package/lib/plugins/row-reorder/index.d.ts.map +0 -1
  200. package/lib/plugins/row-reorder/index.js +0 -2
  201. package/lib/plugins/row-reorder/index.js.map +0 -1
  202. package/lib/plugins/row-reorder/types.d.ts.map +0 -1
  203. package/umd/plugins/reorder.umd.js +0 -2
  204. package/umd/plugins/reorder.umd.js.map +0 -1
  205. package/umd/plugins/row-reorder.umd.js +0 -2
  206. package/umd/plugins/row-reorder.umd.js.map +0 -1
  207. /package/lib/plugins/{reorder → reorder-columns}/column-drag.d.ts +0 -0
@@ -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","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,8hHAKlB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AGAC,IAAkB,EAiBlB,EAAA9E,GACE,IAAKpF,MAAKT,IAAkBS,KAAKO,OAAOK,aACtC,OAGF,IAAIuJ,GAAe,EACnB,MAAMzD,EAAe1G,KAAKiB,KACpBmJ,EAAYpK,MAAK4I,IAGjByB,EAAsBrK,MAAKgK,IAOjC,GANIK,IAAwBrK,MAAKqH,IAC/BrH,MAAKqH,EAAoBgD,EACzBF,GAAe,GAIbC,EAAW,CACb,MAAME,EAAWtK,KAAKmC,YAAYE,cAAc,4BAChD,GAAIiI,EAAU,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
+ {"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 v2.0.\n */\n override getExtraHeight(): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types (groups + cards)\n // If all rows are cards, we update the virtualization row height instead\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const { groupCount, cardCount } = this.#countRowTypes();\n\n // Calculate extra height for both row types\n const groupExtra = groupCount * Math.max(0, groupHeight - baseHeight);\n const cardExtra = cardCount * Math.max(0, cardHeight - baseHeight);\n\n return groupExtra + cardExtra;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * Used by virtualization to correctly calculate scroll positions.\n *\n * Like getExtraHeight, this accounts for both group and card row heights.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const groupHeightDiff = Math.max(0, groupHeight - baseHeight);\n const cardHeightDiff = Math.max(0, cardHeight - baseHeight);\n\n // Count group rows and card rows before the given index\n let groupsBefore = 0;\n let cardsBefore = 0;\n const rows = this.rows;\n const maxIndex = Math.min(beforeRowIndex, rows.length);\n\n for (let i = 0; i < maxIndex; i++) {\n if ((rows[i] as { __isGroupRow?: boolean }).__isGroupRow) {\n groupsBefore++;\n } else {\n cardsBefore++;\n }\n }\n\n return groupsBefore * groupHeightDiff + cardsBefore * cardHeightDiff;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.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,8hHAKlBC,gBAAoD,CAClDC,iBAAkB,CAChB,CACEJ,KAAM,eACNK,OACE,iJAINC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,OAAuCD,IAEvCE,GAA6C,KAE7CC,GAAyC,GAMzC,YAAAR,GACE,OAAOS,MAAKT,CACd,CAOA,aAAAU,CAAcC,GACRA,IAAYF,MAAKT,IACnBS,MAAKT,EAAgBW,EACrBF,MAAKG,IACLH,KAAKI,KAAK,oBAAqB,CAC7Bb,aAAcW,EACdG,MAAOL,MAAKN,EACZY,WAAYN,KAAKO,OAAOD,YAAc,IAG5C,CAMA,aAAAE,CAAcH,GACZL,KAAKO,OAAOD,WAAaD,EACzBL,MAAKS,EAAiBT,MAAKN,EAC7B,CAOA,eAAAgB,CAAgBC,GACdX,KAAKO,OAAOK,aAAeD,EAEvBX,MAAKT,GACPS,KAAKa,eAET,CAMA,QAAAC,GACE,OAAOd,MAAKN,CACd,CAMA,mBAAAqB,GACE,OAAOf,MAAKF,CACd,CAES,MAAAkB,CAAOC,GACdC,MAAMF,OAAOC,GAGbjB,MAAKmB,IAGLnB,MAAKoB,EAAuBpB,KAAKO,OAAOc,eAGpCrB,KAAKO,OAAOe,aAAaC,SAC3BvB,MAAKD,EAAqB,IAAIC,KAAKO,OAAOe,aAAaE,KAAK,CAACC,EAAGC,IAAMA,EAAEC,SAAWF,EAAEE,WAKvF3B,MAAKV,E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/src/lib/plugins/visibility/VisibilityPlugin.ts"],"sourcesContent":["/**\n * Column Visibility Plugin (Class-based)\n *\n * Provides a UI for column visibility control via the shell's tool panel system.\n * Column visibility is a core grid feature - this plugin provides:\n * - A tool panel for column visibility management (registered with the shell)\n * - Backward-compatible API methods that delegate to grid.setColumnVisible(), etc.\n *\n * The grid emits 'column-visibility' events when columns are shown/hidden,\n * allowing consumers to save user preferences.\n *\n * When a reorder plugin is present, column rows become draggable for reordering.\n * Drag-drop emits 'column-reorder-request' events that the ReorderPlugin can listen for.\n */\n\nimport {\n BaseGridPlugin,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ToolPanelDefinition } from '../../core/types';\nimport type { ContextMenuParams, HeaderContextMenuItem } from '../context-menu/types';\nimport type { ColumnGroupInfo, VisibilityConfig } from './types';\nimport styles from './visibility.css?inline';\n\n/**\n * Detail for column-reorder-request events emitted when users drag-drop in the visibility panel.\n */\nexport interface ColumnReorderRequestDetail {\n /** The field name of the column to move */\n field: string;\n /** The source index (before move) */\n fromIndex: number;\n /** The target index (after move) */\n toIndex: number;\n}\n\n/**\n * Check if a column can be moved (respects lockPosition/suppressMovable).\n * Inlined to avoid importing from reorder plugin.\n */\nfunction canMoveColumn(column: ColumnConfig): boolean {\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Column Visibility Plugin for tbw-grid\n *\n * Gives users control over which columns are displayed. Hide less important columns\n * by default, let users toggle them via a column chooser UI, or programmatically\n * show/hide columns based on user preferences or screen size.\n *\n * > **Optional Enhancement:** When ReorderPlugin is also loaded, columns in the\n * > visibility panel become draggable for reordering.\n *\n * ## Installation\n *\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `allowHideAll` | `boolean` | `false` | Allow hiding all columns (no minimum) |\n *\n * ## Column Configuration\n *\n * | Property | Type | Default | Description |\n * |----------|------|---------|-------------|\n * | `visible` | `boolean` | `true` | Initial visibility state |\n * | `meta.lockVisibility` | `boolean` | `false` | Prevent user from toggling |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `hideColumn` | `(field: string) => void` | Hide a column |\n * | `showColumn` | `(field: string) => void` | Show a column |\n * | `toggleColumn` | `(field: string) => void` | Toggle visibility |\n * | `showAllColumns` | `() => void` | Show all columns |\n * | `getHiddenColumns` | `() => string[]` | Get list of hidden column fields |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-visibility-hover` | `var(--tbw-color-row-hover)` | Row hover background |\n * | `--tbw-panel-padding` | `0.75em` | Panel content padding |\n * | `--tbw-panel-gap` | `0.5em` | Gap between items |\n *\n * @example Columns Hidden by Default\n * ```ts\n * import '@toolbox-web/grid';\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'phone', header: 'Phone', visible: false }, // Hidden by default\n * { field: 'address', header: 'Address', visible: false },\n * ],\n * plugins: [new VisibilityPlugin()],\n * };\n *\n * // Toggle programmatically\n * const plugin = grid.getPluginByName('visibility');\n * plugin.showColumn('phone');\n * ```\n *\n * @example With Drag-to-Reorder\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ReorderPlugin(), // Enables drag-drop in visibility panel\n * new VisibilityPlugin(),\n * ],\n * };\n * ```\n *\n * @see {@link VisibilityConfig} for configuration options\n * @see {@link ReorderPlugin} for drag-to-reorder integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class VisibilityPlugin extends BaseGridPlugin<VisibilityConfig> {\n /**\n * Plugin dependencies - VisibilityPlugin optionally uses ReorderPlugin for drag-drop reordering.\n *\n * When ReorderPlugin is present, columns in the visibility panel become draggable.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'reorder', required: false, reason: 'Enables drag-to-reorder columns in visibility panel' },\n ];\n\n /**\n * Plugin manifest - declares handled queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'getContextMenuItems',\n description: 'Contributes \"Hide column\" item to the header context menu',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'visibility';\n\n /** Tool panel ID for shell integration */\n static readonly PANEL_ID = 'columns';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<VisibilityConfig> {\n return {\n allowHideAll: false,\n };\n }\n\n // #region Internal State\n private columnListElement: HTMLElement | null = null;\n\n // Drag state for reorder integration\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n /** When dragging a group, holds the group ID; null for individual column drags. */\n private draggedGroupId: string | null = null;\n /** Fields belonging to the group currently being dragged. */\n private draggedGroupFields: string[] = [];\n\n /** Clear drag-related classes from all rows and group headers in a list. */\n private clearDragClasses(container: HTMLElement): void {\n container.querySelectorAll('.tbw-visibility-row, .tbw-visibility-group-header').forEach((r) => {\n r.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Listen for column-move events (emitted by ReorderPlugin after any reorder,\n // including header drag-drop and visibility panel drag-drop) to keep the\n // panel list in sync with the grid's column order.\n (grid as unknown as HTMLElement).addEventListener(\n 'column-move',\n () => {\n if (this.columnListElement) {\n // column-move fires BEFORE setColumnOrder runs. Defer the rebuild\n // to allow the full reorder cycle (setColumnOrder + renderHeader +\n // refreshVirtualWindow) to complete before reading the new order.\n // Use RAF to run after the current synchronous work and any\n // animation frames queued by the animation system.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.columnListElement = null;\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n }\n // #endregion\n\n // #region Query Handlers\n\n /**\n * Handle inter-plugin queries.\n * Contributes a \"Hide column\" item to the header context menu.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getContextMenuItems') {\n const params = query.context as ContextMenuParams;\n if (!params.isHeader) return undefined;\n\n const column = params.column as ColumnConfig;\n if (!column?.field) return undefined;\n\n // Don't offer \"Hide\" for locked-visibility columns\n if (column.meta?.lockVisibility) return undefined;\n\n const items: HeaderContextMenuItem[] = [\n {\n id: 'visibility/hide-column',\n label: 'Hide Column',\n icon: '👁',\n order: 30,\n action: () => this.hideColumn(column.field),\n },\n ];\n\n return items;\n }\n return undefined;\n }\n // #endregion\n\n // #region Shell Integration\n\n /**\n * Register the column visibility tool panel with the shell.\n * @internal\n */\n override getToolPanel(): ToolPanelDefinition | undefined {\n return {\n id: VisibilityPlugin.PANEL_ID,\n title: 'Columns',\n icon: '☰',\n tooltip: 'Column visibility',\n order: 100, // High order so it appears last\n render: (container) => this.renderPanelContent(container),\n };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Show the visibility sidebar panel.\n * Opens the tool panel and ensures this section is expanded.\n */\n show(): void {\n this.grid.openToolPanel();\n // Ensure our section is expanded\n if (!this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID)) {\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n }\n\n /**\n * Hide the visibility sidebar panel.\n */\n hide(): void {\n this.grid.closeToolPanel();\n }\n\n /**\n * Toggle the visibility sidebar panel section.\n */\n toggle(): void {\n // If tool panel is closed, open it first\n if (!this.grid.isToolPanelOpen) {\n this.grid.openToolPanel();\n }\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n\n /**\n * Check if a specific column is visible.\n * Delegates to grid.isColumnVisible().\n * @param field - The field name to check\n * @returns True if the column is visible\n */\n isColumnVisible(field: string): boolean {\n return this.grid.isColumnVisible(field);\n }\n\n /**\n * Set visibility for a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column\n * @param visible - Whether the column should be visible\n */\n setColumnVisible(field: string, visible: boolean): void {\n this.grid.setColumnVisible(field, visible);\n }\n\n /**\n * Get list of all visible column fields.\n * @returns Array of visible field names\n */\n getVisibleColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Get list of all hidden column fields.\n * @returns Array of hidden field names\n */\n getHiddenColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => !c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Show all columns.\n * Delegates to grid.showAllColumns().\n */\n showAll(): void {\n this.grid.showAllColumns();\n }\n\n /**\n * Toggle visibility for a specific column.\n * Delegates to grid.toggleColumnVisibility().\n * @param field - The field name of the column\n */\n toggleColumn(field: string): void {\n this.grid.toggleColumnVisibility(field);\n }\n\n /**\n * Show a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to show\n */\n showColumn(field: string): void {\n this.setColumnVisible(field, true);\n }\n\n /**\n * Hide a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to hide\n */\n hideColumn(field: string): void {\n this.setColumnVisible(field, false);\n }\n\n /**\n * Get all columns with their visibility status.\n * Useful for building visibility UI.\n * @returns Array of column info with visibility status\n */\n getAllColumns(): Array<{\n field: string;\n header: string;\n visible: boolean;\n lockVisible?: boolean;\n utility?: boolean;\n }> {\n return this.grid.getAllColumns();\n }\n\n /**\n * Check if the sidebar panel is currently open.\n * @returns True if the panel section is expanded\n */\n isPanelVisible(): boolean {\n return this.grid.isToolPanelOpen && this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Render the panel content into the shell's tool panel container.\n * Returns a cleanup function.\n */\n private renderPanelContent(container: HTMLElement): (() => void) | void {\n // Create content wrapper\n const wrapper = document.createElement('div');\n wrapper.className = 'tbw-visibility-content';\n\n // Column list container\n const columnList = document.createElement('div');\n columnList.className = 'tbw-visibility-list';\n wrapper.appendChild(columnList);\n\n // Show all button\n const showAllBtn = document.createElement('button');\n showAllBtn.className = 'tbw-visibility-show-all';\n showAllBtn.textContent = 'Show All';\n showAllBtn.addEventListener('click', () => {\n this.grid.showAllColumns();\n this.rebuildToggles(columnList);\n });\n wrapper.appendChild(showAllBtn);\n\n // Store reference\n this.columnListElement = columnList;\n\n // Build initial toggles\n this.rebuildToggles(columnList);\n\n // Append to container\n container.appendChild(wrapper);\n\n // Return cleanup function\n return () => {\n this.columnListElement = null;\n wrapper.remove();\n };\n }\n\n /**\n * Check if a reorder plugin is present (by name to avoid static import).\n */\n private hasReorderPlugin(): boolean {\n const plugin = this.grid?.getPluginByName?.('reorder');\n // Duck-type check - just verify the plugin exists and has a moveColumn method\n return !!(plugin && typeof (plugin as { moveColumn?: unknown }).moveColumn === 'function');\n }\n\n /**\n * Build the column toggle checkboxes.\n * When GroupingColumnsPlugin is present, renders columns under collapsible group headers.\n * When a reorder plugin is present, adds drag handles for reordering.\n */\n private rebuildToggles(columnList: HTMLElement): void {\n const reorderEnabled = this.hasReorderPlugin();\n\n columnList.innerHTML = '';\n\n // getAllColumns() returns columns in their effective display order\n // Filter out utility columns (e.g., expander column) as they're internal\n const allColumns = this.grid.getAllColumns().filter((c) => !c.utility);\n\n // Query for column grouping info from GroupingColumnsPlugin (or any responder)\n const groupResults = this.grid.query<ColumnGroupInfo[]>('getColumnGrouping');\n const groups: ColumnGroupInfo[] = groupResults?.flat().filter((g) => g && g.fields.length > 0) ?? [];\n\n if (groups.length === 0) {\n // No grouping — render flat list (original behavior)\n this.renderFlatColumnList(allColumns, reorderEnabled, columnList);\n return;\n }\n\n // Build field → group lookup\n const fieldToGroup = new Map<string, ColumnGroupInfo>();\n for (const group of groups) {\n for (const field of group.fields) fieldToGroup.set(field, group);\n }\n\n // Walk columns in display order, interleaving groups and ungrouped columns.\n // When we encounter the first column of a group, render the entire group section.\n const renderedGroups = new Set<string>();\n\n for (const col of allColumns) {\n const group = fieldToGroup.get(col.field);\n\n if (group) {\n // Column belongs to a group — render entire group section at first encounter\n if (!renderedGroups.has(group.id)) {\n renderedGroups.add(group.id);\n // Filter allColumns (which is in display order) to group members.\n // This preserves the current column order after reordering,\n // rather than using group.fields which may be in static/original order.\n const groupFieldSet = new Set(group.fields);\n const groupCols = allColumns.filter((c) => groupFieldSet.has(c.field));\n if (groupCols.length > 0) {\n this.renderGroupSection(group, groupCols, reorderEnabled, columnList);\n }\n }\n // Subsequent columns of the same group are already rendered — skip\n } else {\n // Ungrouped column — render as individual row at its natural position\n const fullIndex = allColumns.indexOf(col);\n columnList.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, columnList));\n }\n }\n }\n\n /**\n * Render a group section with header checkbox and indented column rows.\n */\n private renderGroupSection(\n group: ColumnGroupInfo,\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n // Group header row\n const header = document.createElement('div');\n header.className = 'tbw-visibility-group-header';\n header.setAttribute('data-group-id', group.id);\n\n // Make group header draggable when reorder is enabled\n if (reorderEnabled) {\n header.draggable = true;\n header.classList.add('reorderable');\n this.setupGroupDragListeners(header, group, container);\n }\n\n const headerLabel = document.createElement('label');\n headerLabel.className = 'tbw-visibility-label';\n\n const groupCheckbox = document.createElement('input');\n groupCheckbox.type = 'checkbox';\n\n // Calculate tri-state: all visible, all hidden, or mixed\n const visibleCount = columns.filter((c) => c.visible).length;\n const allLocked = columns.every((c) => c.lockVisible);\n if (visibleCount === columns.length) {\n groupCheckbox.checked = true;\n groupCheckbox.indeterminate = false;\n } else if (visibleCount === 0) {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = false;\n } else {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = true;\n }\n groupCheckbox.disabled = allLocked;\n\n // Toggle all columns in group\n groupCheckbox.addEventListener('change', () => {\n const newVisible = groupCheckbox.checked;\n for (const col of columns) {\n if (col.lockVisible) continue;\n this.grid.setColumnVisible(col.field, newVisible);\n }\n setTimeout(() => this.rebuildToggles(container), 0);\n });\n\n const headerText = document.createElement('span');\n headerText.textContent = group.label;\n\n headerLabel.appendChild(groupCheckbox);\n headerLabel.appendChild(headerText);\n header.appendChild(headerLabel);\n\n // Add drag handle icon for group if reorderable\n if (reorderEnabled) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder group';\n // Insert handle before the label\n header.insertBefore(handle, headerLabel);\n }\n\n container.appendChild(header);\n\n // Render indented column rows\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n const row = this.createColumnRow(col, fullIndex, reorderEnabled, container);\n row.classList.add('tbw-visibility-row--grouped');\n container.appendChild(row);\n }\n }\n\n /**\n * Render a flat (ungrouped) list of column rows.\n */\n private renderFlatColumnList(\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n container.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, container));\n }\n }\n\n /**\n * Create a single column visibility row element.\n */\n private createColumnRow(\n col: ReturnType<typeof this.grid.getAllColumns>[number],\n index: number,\n reorderEnabled: boolean,\n columnList: HTMLElement,\n ): HTMLElement {\n const label = col.header || col.field;\n\n const row = document.createElement('div');\n row.className = col.lockVisible ? 'tbw-visibility-row locked' : 'tbw-visibility-row';\n row.setAttribute('data-field', col.field);\n row.setAttribute('data-index', String(index));\n\n // Add drag handle if reorder is enabled\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n row.draggable = true;\n row.classList.add('reorderable');\n this.setupDragListeners(row, col.field, index, columnList);\n }\n\n const labelWrapper = document.createElement('label');\n labelWrapper.className = 'tbw-visibility-label';\n\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.checked = col.visible;\n checkbox.disabled = col.lockVisible ?? false;\n checkbox.addEventListener('change', () => {\n this.grid.toggleColumnVisibility(col.field);\n // Refresh after toggle (grid may re-render)\n setTimeout(() => this.rebuildToggles(columnList), 0);\n });\n\n const text = document.createElement('span');\n text.textContent = label;\n\n labelWrapper.appendChild(checkbox);\n labelWrapper.appendChild(text);\n\n // Add drag handle icon if reorderable\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder';\n row.appendChild(handle);\n }\n\n row.appendChild(labelWrapper);\n return row;\n }\n\n /**\n * Set up drag-and-drop listeners for a group header row.\n * Dragging a group moves all its member columns as a block.\n */\n private setupGroupDragListeners(header: HTMLElement, group: ColumnGroupInfo, columnList: HTMLElement): void {\n header.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedGroupId = group.id;\n this.draggedGroupFields = [...group.fields];\n // Use first field as representative for dataTransfer\n this.draggedField = null;\n this.draggedIndex = null;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `group:${group.id}`);\n }\n\n // Mark entire group (header + children) as dragging\n header.classList.add('dragging');\n columnList.querySelectorAll(`.tbw-visibility-row--grouped`).forEach((row) => {\n const field = row.getAttribute('data-field');\n if (field && this.draggedGroupFields.includes(field)) {\n row.classList.add('dragging');\n }\n });\n });\n\n header.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n // Group headers are also drop targets for other groups\n header.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n // Can't drop onto self\n if (this.draggedGroupId === group.id) return;\n // Can't drop individual columns onto group headers\n if (!this.draggedGroupId) return;\n\n const rect = header.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const before = e.clientY < midY;\n\n this.clearDragClasses(columnList);\n header.classList.add('drop-target');\n header.classList.toggle('drop-before', before);\n header.classList.toggle('drop-after', !before);\n });\n\n header.addEventListener('dragleave', () => {\n header.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n header.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || !this.draggedGroupId || this.draggedGroupId === group.id) return;\n\n const rect = header.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n\n this.executeGroupDrop(this.draggedGroupFields, group.fields, before, columnList);\n });\n }\n\n /**\n * Execute a group drop — move the dragged group's fields as a block\n * to the position relative to the target group or column.\n */\n private executeGroupDrop(\n draggedFields: string[],\n targetFields: string[],\n before: boolean,\n columnList: HTMLElement,\n ): void {\n const allColumns = this.grid.getAllColumns();\n const currentOrder = allColumns.map((c) => c.field);\n\n // Remove dragged fields from current order\n const remaining = currentOrder.filter((f) => !draggedFields.includes(f));\n\n // Find insertion point relative to target\n // Use the first field of target group if inserting before, last if after\n const anchorField = before ? targetFields[0] : targetFields[targetFields.length - 1];\n const insertAt = remaining.indexOf(anchorField);\n if (insertAt === -1) return;\n\n // Insert the dragged group block at the correct position\n const insertIndex = before ? insertAt : insertAt + 1;\n\n // Preserve the dragged fields' original relative order\n const draggedInOrder = currentOrder.filter((f) => draggedFields.includes(f));\n remaining.splice(insertIndex, 0, ...draggedInOrder);\n\n this.grid.setColumnOrder(remaining);\n // Panel rebuild handled by column-move listener — but since we're calling\n // setColumnOrder directly (not through ReorderPlugin.moveColumn), we need\n // to manually trigger a rebuild.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n\n /**\n * Set up drag-and-drop event listeners for a row.\n * On drop, emits a 'column-reorder-request' event for other plugins to handle.\n */\n private setupDragListeners(row: HTMLElement, field: string, index: number, columnList: HTMLElement): void {\n row.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = index;\n // Clear any stale group drag state\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n row.classList.add('dragging');\n });\n\n row.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n row.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n\n // If dragging a group, only allow drop on ungrouped rows\n if (this.draggedGroupId) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n } else if (this.draggedField === field) {\n return;\n }\n\n const rect = row.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n\n this.dropIndex = e.clientY < midY ? index : index + 1;\n\n // Clear other highlights\n this.clearDragClasses(columnList);\n // Re-mark dragged elements\n if (this.draggedGroupId) {\n columnList\n .querySelector(`.tbw-visibility-group-header[data-group-id=\"${this.draggedGroupId}\"]`)\n ?.classList.add('dragging');\n columnList.querySelectorAll('.tbw-visibility-row--grouped').forEach((r) => {\n const f = r.getAttribute('data-field');\n if (f && this.draggedGroupFields.includes(f)) r.classList.add('dragging');\n });\n } else if (this.draggedField) {\n columnList.querySelector(`.tbw-visibility-row[data-field=\"${this.draggedField}\"]`)?.classList.add('dragging');\n }\n\n row.classList.add('drop-target');\n row.classList.toggle('drop-before', e.clientY < midY);\n row.classList.toggle('drop-after', e.clientY >= midY);\n });\n\n row.addEventListener('dragleave', () => {\n row.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n row.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n\n if (!this.isDragging) return;\n\n // Group drop onto an ungrouped row\n if (this.draggedGroupId && this.draggedGroupFields.length > 0) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n const rect = row.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n this.executeGroupDrop(this.draggedGroupFields, [field], before, columnList);\n return;\n }\n\n // Individual column drop\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n // Calculate the effective target index (in the filtered non-utility list)\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n\n if (effectiveToIndex !== draggedIndex) {\n // Convert from non-utility index to full column order index\n // by counting how many utility columns come before the target position\n const allColumns = this.grid.getAllColumns();\n const nonUtilityColumns = allColumns.filter((c) => !c.utility);\n\n // Find the target field at effectiveToIndex in non-utility list\n const targetField = nonUtilityColumns[effectiveToIndex]?.field;\n // Find its actual index in the full column order\n const fullOrderToIndex = targetField ? allColumns.findIndex((c) => c.field === targetField) : allColumns.length;\n\n // Emit a request event - other plugins (like ReorderPlugin) can listen and handle\n const detail: ColumnReorderRequestDetail = {\n field: draggedField,\n fromIndex: draggedIndex, // Not used by ReorderPlugin, just for info\n toIndex: fullOrderToIndex,\n };\n this.emit<ColumnReorderRequestDetail>('column-reorder-request', detail);\n // Panel rebuild is handled by the column-move listener in attach()\n }\n });\n }\n // #endregion\n}\n"],"names":["canMoveColumn","column","meta","lockPosition","suppressMovable","VisibilityPlugin","BaseGridPlugin","static","name","required","reason","queries","type","description","styles","defaultConfig","allowHideAll","columnListElement","isDragging","draggedField","draggedIndex","dropIndex","draggedGroupId","draggedGroupFields","clearDragClasses","container","querySelectorAll","forEach","r","classList","remove","attach","grid","super","addEventListener","this","requestAnimationFrame","rebuildToggles","signal","disconnectSignal","detach","handleQuery","query","params","context","isHeader","field","lockVisibility","id","label","icon","order","action","hideColumn","getToolPanel","PANEL_ID","title","tooltip","render","renderPanelContent","show","openToolPanel","expandedToolPanelSections","includes","toggleToolPanelSection","hide","closeToolPanel","toggle","isToolPanelOpen","isColumnVisible","setColumnVisible","visible","getVisibleColumns","getAllColumns","filter","c","map","getHiddenColumns","showAll","showAllColumns","toggleColumn","toggleColumnVisibility","showColumn","isPanelVisible","wrapper","document","createElement","className","columnList","appendChild","showAllBtn","textContent","hasReorderPlugin","plugin","getPluginByName","moveColumn","reorderEnabled","innerHTML","allColumns","utility","groupResults","groups","flat","g","fields","length","renderFlatColumnList","fieldToGroup","Map","group","set","renderedGroups","Set","col","get","has","add","groupFieldSet","groupCols","renderGroupSection","fullIndex","indexOf","createColumnRow","columns","header","setAttribute","draggable","setupGroupDragListeners","headerLabel","groupCheckbox","visibleCount","allLocked","every","lockVisible","checked","indeterminate","disabled","newVisible","setTimeout","headerText","handle","setIcon","resolveIcon","insertBefore","allColumnsFullList","findIndex","row","index","String","setupDragListeners","labelWrapper","checkbox","text","e","dataTransfer","effectAllowed","setData","getAttribute","preventDefault","rect","getBoundingClientRect","midY","top","height","before","clientY","executeGroupDrop","draggedFields","targetFields","currentOrder","remaining","f","anchorField","insertAt","insertIndex","draggedInOrder","splice","setColumnOrder","contains","querySelector","effectiveToIndex","nonUtilityColumns","targetField","detail","fromIndex","toIndex","emit"],"mappings":"oVA0CA,SAASA,EAAcC,GACrB,MAAMC,EAAOD,EAAOC,MAAQ,CAAA,EAC5B,OAA6B,IAAtBA,EAAKC,eAAkD,IAAzBD,EAAKE,eAC5C,CAwFO,MAAMC,UAAyBC,EAAAA,eAOpCC,oBAA4D,CAC1D,CAAEC,KAAM,UAAWC,UAAU,EAAOC,O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AAO,aAAcsF,EAAEY,SAAWJ,KAGlDf,EAAIhH,iBAAiB,YAAa,KAChCgH,EAAIrH,UAAUC,OAAO,cAAe,cAAe,gBAGrDoH,EAAIhH,iBAAiB,OAASuH,IAG5B,GAFAA,EAAEK,kBAEG3H,KAAKjB,WAAY,OAGtB,GAAIiB,KAAKb,gBAAkBa,KAAKZ,mBAAmBkF,OAAS,EAAG,CAC7D,GAAIyC,EAAIrH,UAAUqJ,SAAS,+BAAgC,OAC3D,MAAMnB,EAAOb,EAAIc,wBACXI,EAASX,EAAEY,QAAUN,EAAKG,IAAMH,EAAKI,OAAS,EAEpD,YADAhI,KAAKmI,iBAAiBnI,KAAKZ,mBAAoB,CAACuB,GAAQsH,EAAQ5E,EAElE,CAGA,MAAMrE,EAAegB,KAAKhB,aACpBC,EAAee,KAAKf,aACpBC,EAAYc,KAAKd,UAEvB,GAAqB,OAAjBF,GAA0C,OAAjBC,GAAuC,OAAdC,EACpD,OAIF,MAAM+J,EAAmB/J,EAAYD,EAAeC,EAAY,EAAIA,EAEpE,GAAI+J,IAAqBhK,EAAc,CAGrC,MAAM8E,EAAa/D,KAAKH,KAAKyC,gBACvB4G,EAAoBnF,EAAWxB,OAAQC,IAAOA,EAAEwB,SAGhDmF,EAAcD,EAAkBD,IAAmBtI,MAKnDyI,EAAqC,CACzCzI,MAAO3B,EACPqK,UAAWpK,EACXqK,QANuBH,EAAcpF,EAAW+C,UAAWtE,GAAMA,EAAE7B,QAAUwI,GAAepF,EAAWO,QAQzGtE,KAAKuJ,KAAiC,yBAA0BH,EAElE,GAEJ"}
1
+ {"version":3,"file":"visibility.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/visibility/VisibilityPlugin.ts"],"sourcesContent":["/**\n * Column Visibility Plugin (Class-based)\n *\n * Provides a UI for column visibility control via the shell's tool panel system.\n * Column visibility is a core grid feature - this plugin provides:\n * - A tool panel for column visibility management (registered with the shell)\n * - Backward-compatible API methods that delegate to grid.setColumnVisible(), etc.\n *\n * The grid emits 'column-visibility' events when columns are shown/hidden,\n * allowing consumers to save user preferences.\n *\n * When a reorder plugin is present, column rows become draggable for reordering.\n * Drag-drop emits 'column-reorder-request' events that the ReorderPlugin can listen for.\n */\n\nimport {\n BaseGridPlugin,\n type PluginDependency,\n type PluginManifest,\n type PluginQuery,\n} from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, ToolPanelDefinition } from '../../core/types';\nimport type { ContextMenuParams, HeaderContextMenuItem } from '../context-menu/types';\nimport type { ColumnGroupInfo, VisibilityConfig } from './types';\nimport styles from './visibility.css?inline';\n\n/**\n * Detail for column-reorder-request events emitted when users drag-drop in the visibility panel.\n */\nexport interface ColumnReorderRequestDetail {\n /** The field name of the column to move */\n field: string;\n /** The source index (before move) */\n fromIndex: number;\n /** The target index (after move) */\n toIndex: number;\n}\n\n/**\n * Check if a column can be moved (respects lockPosition/suppressMovable).\n * Inlined to avoid importing from reorder plugin.\n */\nfunction canMoveColumn(column: ColumnConfig): boolean {\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Column Visibility Plugin for tbw-grid\n *\n * Gives users control over which columns are displayed. Hide less important columns\n * by default, let users toggle them via a column chooser UI, or programmatically\n * show/hide columns based on user preferences or screen size.\n *\n * > **Optional Enhancement:** When ReorderPlugin is also loaded, columns in the\n * > visibility panel become draggable for reordering.\n *\n * ## Installation\n *\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `allowHideAll` | `boolean` | `false` | Allow hiding all columns (no minimum) |\n *\n * ## Column Configuration\n *\n * | Property | Type | Default | Description |\n * |----------|------|---------|-------------|\n * | `visible` | `boolean` | `true` | Initial visibility state |\n * | `meta.lockVisibility` | `boolean` | `false` | Prevent user from toggling |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `hideColumn` | `(field: string) => void` | Hide a column |\n * | `showColumn` | `(field: string) => void` | Show a column |\n * | `toggleColumn` | `(field: string) => void` | Toggle visibility |\n * | `showAllColumns` | `() => void` | Show all columns |\n * | `getHiddenColumns` | `() => string[]` | Get list of hidden column fields |\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-visibility-hover` | `var(--tbw-color-row-hover)` | Row hover background |\n * | `--tbw-panel-padding` | `0.75em` | Panel content padding |\n * | `--tbw-panel-gap` | `0.5em` | Gap between items |\n *\n * @example Columns Hidden by Default\n * ```ts\n * import '@toolbox-web/grid';\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'phone', header: 'Phone', visible: false }, // Hidden by default\n * { field: 'address', header: 'Address', visible: false },\n * ],\n * plugins: [new VisibilityPlugin()],\n * };\n *\n * // Toggle programmatically\n * const plugin = grid.getPluginByName('visibility');\n * plugin.showColumn('phone');\n * ```\n *\n * @example With Drag-to-Reorder\n * ```ts\n * import { VisibilityPlugin } from '@toolbox-web/grid/plugins/visibility';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n *\n * grid.gridConfig = {\n * plugins: [\n * new ReorderPlugin(), // Enables drag-drop in visibility panel\n * new VisibilityPlugin(),\n * ],\n * };\n * ```\n *\n * @see {@link VisibilityConfig} for configuration options\n * @see {@link ReorderPlugin} for drag-to-reorder integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class VisibilityPlugin extends BaseGridPlugin<VisibilityConfig> {\n /**\n * Plugin dependencies - VisibilityPlugin optionally uses ReorderPlugin for drag-drop reordering.\n *\n * When ReorderPlugin is present, columns in the visibility panel become draggable.\n * @internal\n */\n static override readonly dependencies: PluginDependency[] = [\n { name: 'reorder', required: false, reason: 'Enables drag-to-reorder columns in visibility panel' },\n ];\n\n /**\n * Plugin manifest - declares handled queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'getContextMenuItems',\n description: 'Contributes \"Hide column\" item to the header context menu',\n },\n ],\n };\n\n /** @internal */\n readonly name = 'visibility';\n\n /** Tool panel ID for shell integration */\n static readonly PANEL_ID = 'columns';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<VisibilityConfig> {\n return {\n allowHideAll: false,\n };\n }\n\n // #region Internal State\n private columnListElement: HTMLElement | null = null;\n\n // Drag state for reorder integration\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n /** When dragging a group, holds the group ID; null for individual column drags. */\n private draggedGroupId: string | null = null;\n /** Fields belonging to the group currently being dragged. */\n private draggedGroupFields: string[] = [];\n\n /** Clear drag-related classes from all rows and group headers in a list. */\n private clearDragClasses(container: HTMLElement): void {\n container.querySelectorAll('.tbw-visibility-row, .tbw-visibility-group-header').forEach((r) => {\n r.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Listen for column-move events (emitted by ReorderPlugin after any reorder,\n // including header drag-drop and visibility panel drag-drop) to keep the\n // panel list in sync with the grid's column order.\n (grid as unknown as HTMLElement).addEventListener(\n 'column-move',\n () => {\n if (this.columnListElement) {\n // column-move fires BEFORE setColumnOrder runs. Defer the rebuild\n // to allow the full reorder cycle (setColumnOrder + renderHeader +\n // refreshVirtualWindow) to complete before reading the new order.\n // Use RAF to run after the current synchronous work and any\n // animation frames queued by the animation system.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.columnListElement = null;\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n }\n // #endregion\n\n // #region Query Handlers\n\n /**\n * Handle inter-plugin queries.\n * Contributes a \"Hide column\" item to the header context menu.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'getContextMenuItems') {\n const params = query.context as ContextMenuParams;\n if (!params.isHeader) return undefined;\n\n const column = params.column as ColumnConfig;\n if (!column?.field) return undefined;\n\n // Don't offer \"Hide\" for locked-visibility columns\n if (column.meta?.lockVisibility) return undefined;\n\n const items: HeaderContextMenuItem[] = [\n {\n id: 'visibility/hide-column',\n label: 'Hide Column',\n icon: '👁',\n order: 30,\n action: () => this.hideColumn(column.field),\n },\n ];\n\n return items;\n }\n return undefined;\n }\n // #endregion\n\n // #region Shell Integration\n\n /**\n * Register the column visibility tool panel with the shell.\n * @internal\n */\n override getToolPanel(): ToolPanelDefinition | undefined {\n return {\n id: VisibilityPlugin.PANEL_ID,\n title: 'Columns',\n icon: '☰',\n tooltip: 'Column visibility',\n order: 100, // High order so it appears last\n render: (container) => this.renderPanelContent(container),\n };\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Show the visibility sidebar panel.\n * Opens the tool panel and ensures this section is expanded.\n */\n show(): void {\n this.grid.openToolPanel();\n // Ensure our section is expanded\n if (!this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID)) {\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n }\n\n /**\n * Hide the visibility sidebar panel.\n */\n hide(): void {\n this.grid.closeToolPanel();\n }\n\n /**\n * Toggle the visibility sidebar panel section.\n */\n toggle(): void {\n // If tool panel is closed, open it first\n if (!this.grid.isToolPanelOpen) {\n this.grid.openToolPanel();\n }\n this.grid.toggleToolPanelSection(VisibilityPlugin.PANEL_ID);\n }\n\n /**\n * Check if a specific column is visible.\n * Delegates to grid.isColumnVisible().\n * @param field - The field name to check\n * @returns True if the column is visible\n */\n isColumnVisible(field: string): boolean {\n return this.grid.isColumnVisible(field);\n }\n\n /**\n * Set visibility for a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column\n * @param visible - Whether the column should be visible\n */\n setColumnVisible(field: string, visible: boolean): void {\n this.grid.setColumnVisible(field, visible);\n }\n\n /**\n * Get list of all visible column fields.\n * @returns Array of visible field names\n */\n getVisibleColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Get list of all hidden column fields.\n * @returns Array of hidden field names\n */\n getHiddenColumns(): string[] {\n return this.grid\n .getAllColumns()\n .filter((c) => !c.visible)\n .map((c) => c.field);\n }\n\n /**\n * Show all columns.\n * Delegates to grid.showAllColumns().\n */\n showAll(): void {\n this.grid.showAllColumns();\n }\n\n /**\n * Toggle visibility for a specific column.\n * Delegates to grid.toggleColumnVisibility().\n * @param field - The field name of the column\n */\n toggleColumn(field: string): void {\n this.grid.toggleColumnVisibility(field);\n }\n\n /**\n * Show a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to show\n */\n showColumn(field: string): void {\n this.setColumnVisible(field, true);\n }\n\n /**\n * Hide a specific column.\n * Delegates to grid.setColumnVisible().\n * @param field - The field name of the column to hide\n */\n hideColumn(field: string): void {\n this.setColumnVisible(field, false);\n }\n\n /**\n * Get all columns with their visibility status.\n * Useful for building visibility UI.\n * @returns Array of column info with visibility status\n */\n getAllColumns(): Array<{\n field: string;\n header: string;\n visible: boolean;\n lockVisible?: boolean;\n utility?: boolean;\n }> {\n return this.grid.getAllColumns();\n }\n\n /**\n * Check if the sidebar panel is currently open.\n * @returns True if the panel section is expanded\n */\n isPanelVisible(): boolean {\n return this.grid.isToolPanelOpen && this.grid.expandedToolPanelSections.includes(VisibilityPlugin.PANEL_ID);\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Render the panel content into the shell's tool panel container.\n * Returns a cleanup function.\n */\n private renderPanelContent(container: HTMLElement): (() => void) | void {\n // Create content wrapper\n const wrapper = document.createElement('div');\n wrapper.className = 'tbw-visibility-content';\n\n // Column list container\n const columnList = document.createElement('div');\n columnList.className = 'tbw-visibility-list';\n wrapper.appendChild(columnList);\n\n // Show all button\n const showAllBtn = document.createElement('button');\n showAllBtn.className = 'tbw-visibility-show-all';\n showAllBtn.textContent = 'Show All';\n showAllBtn.addEventListener('click', () => {\n this.grid.showAllColumns();\n this.rebuildToggles(columnList);\n });\n wrapper.appendChild(showAllBtn);\n\n // Store reference\n this.columnListElement = columnList;\n\n // Build initial toggles\n this.rebuildToggles(columnList);\n\n // Append to container\n container.appendChild(wrapper);\n\n // Return cleanup function\n return () => {\n this.columnListElement = null;\n wrapper.remove();\n };\n }\n\n /**\n * Check if a reorder plugin is present (by name to avoid static import).\n */\n private hasReorderPlugin(): boolean {\n const plugin = this.grid?.getPluginByName?.('reorder');\n // Duck-type check - just verify the plugin exists and has a moveColumn method\n return !!(plugin && typeof (plugin as { moveColumn?: unknown }).moveColumn === 'function');\n }\n\n /**\n * Build the column toggle checkboxes.\n * When GroupingColumnsPlugin is present, renders columns under collapsible group headers.\n * When a reorder plugin is present, adds drag handles for reordering.\n */\n private rebuildToggles(columnList: HTMLElement): void {\n const reorderEnabled = this.hasReorderPlugin();\n\n columnList.innerHTML = '';\n\n // getAllColumns() returns columns in their effective display order\n // Filter out utility columns (e.g., expander column) as they're internal\n const allColumns = this.grid.getAllColumns().filter((c) => !c.utility);\n\n // Query for column grouping info from GroupingColumnsPlugin (or any responder)\n const groupResults = this.grid.query<ColumnGroupInfo[]>('getColumnGrouping');\n const groups: ColumnGroupInfo[] = groupResults?.flat().filter((g) => g && g.fields.length > 0) ?? [];\n\n if (groups.length === 0) {\n // No grouping — render flat list (original behavior)\n this.renderFlatColumnList(allColumns, reorderEnabled, columnList);\n return;\n }\n\n // Build field → group lookup\n const fieldToGroup = new Map<string, ColumnGroupInfo>();\n for (const group of groups) {\n for (const field of group.fields) fieldToGroup.set(field, group);\n }\n\n // Walk columns in display order, interleaving groups and ungrouped columns.\n // When we encounter the first column of a group, render the entire group section.\n const renderedGroups = new Set<string>();\n\n for (const col of allColumns) {\n const group = fieldToGroup.get(col.field);\n\n if (group) {\n // Column belongs to a group — render entire group section at first encounter\n if (!renderedGroups.has(group.id)) {\n renderedGroups.add(group.id);\n // Filter allColumns (which is in display order) to group members.\n // This preserves the current column order after reordering,\n // rather than using group.fields which may be in static/original order.\n const groupFieldSet = new Set(group.fields);\n const groupCols = allColumns.filter((c) => groupFieldSet.has(c.field));\n if (groupCols.length > 0) {\n this.renderGroupSection(group, groupCols, reorderEnabled, columnList);\n }\n }\n // Subsequent columns of the same group are already rendered — skip\n } else {\n // Ungrouped column — render as individual row at its natural position\n const fullIndex = allColumns.indexOf(col);\n columnList.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, columnList));\n }\n }\n }\n\n /**\n * Render a group section with header checkbox and indented column rows.\n */\n private renderGroupSection(\n group: ColumnGroupInfo,\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n // Group header row\n const header = document.createElement('div');\n header.className = 'tbw-visibility-group-header';\n header.setAttribute('data-group-id', group.id);\n\n // Make group header draggable when reorder is enabled\n if (reorderEnabled) {\n header.draggable = true;\n header.classList.add('reorderable');\n this.setupGroupDragListeners(header, group, container);\n }\n\n const headerLabel = document.createElement('label');\n headerLabel.className = 'tbw-visibility-label';\n\n const groupCheckbox = document.createElement('input');\n groupCheckbox.type = 'checkbox';\n\n // Calculate tri-state: all visible, all hidden, or mixed\n const visibleCount = columns.filter((c) => c.visible).length;\n const allLocked = columns.every((c) => c.lockVisible);\n if (visibleCount === columns.length) {\n groupCheckbox.checked = true;\n groupCheckbox.indeterminate = false;\n } else if (visibleCount === 0) {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = false;\n } else {\n groupCheckbox.checked = false;\n groupCheckbox.indeterminate = true;\n }\n groupCheckbox.disabled = allLocked;\n\n // Toggle all columns in group\n groupCheckbox.addEventListener('change', () => {\n const newVisible = groupCheckbox.checked;\n for (const col of columns) {\n if (col.lockVisible) continue;\n this.grid.setColumnVisible(col.field, newVisible);\n }\n setTimeout(() => this.rebuildToggles(container), 0);\n });\n\n const headerText = document.createElement('span');\n headerText.textContent = group.label;\n\n headerLabel.appendChild(groupCheckbox);\n headerLabel.appendChild(headerText);\n header.appendChild(headerLabel);\n\n // Add drag handle icon for group if reorderable\n if (reorderEnabled) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder group';\n // Insert handle before the label\n header.insertBefore(handle, headerLabel);\n }\n\n container.appendChild(header);\n\n // Render indented column rows\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n const row = this.createColumnRow(col, fullIndex, reorderEnabled, container);\n row.classList.add('tbw-visibility-row--grouped');\n container.appendChild(row);\n }\n }\n\n /**\n * Render a flat (ungrouped) list of column rows.\n */\n private renderFlatColumnList(\n columns: ReturnType<typeof this.grid.getAllColumns>,\n reorderEnabled: boolean,\n container: HTMLElement,\n ): void {\n const allColumnsFullList = this.grid.getAllColumns().filter((c) => !c.utility);\n for (const col of columns) {\n const fullIndex = allColumnsFullList.findIndex((c) => c.field === col.field);\n container.appendChild(this.createColumnRow(col, fullIndex, reorderEnabled, container));\n }\n }\n\n /**\n * Create a single column visibility row element.\n */\n private createColumnRow(\n col: ReturnType<typeof this.grid.getAllColumns>[number],\n index: number,\n reorderEnabled: boolean,\n columnList: HTMLElement,\n ): HTMLElement {\n const label = col.header || col.field;\n\n const row = document.createElement('div');\n row.className = col.lockVisible ? 'tbw-visibility-row locked' : 'tbw-visibility-row';\n row.setAttribute('data-field', col.field);\n row.setAttribute('data-index', String(index));\n\n // Add drag handle if reorder is enabled\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n row.draggable = true;\n row.classList.add('reorderable');\n this.setupDragListeners(row, col.field, index, columnList);\n }\n\n const labelWrapper = document.createElement('label');\n labelWrapper.className = 'tbw-visibility-label';\n\n const checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.checked = col.visible;\n checkbox.disabled = col.lockVisible ?? false;\n checkbox.addEventListener('change', () => {\n this.grid.toggleColumnVisibility(col.field);\n // Refresh after toggle (grid may re-render)\n setTimeout(() => this.rebuildToggles(columnList), 0);\n });\n\n const text = document.createElement('span');\n text.textContent = label;\n\n labelWrapper.appendChild(checkbox);\n labelWrapper.appendChild(text);\n\n // Add drag handle icon if reorderable\n if (reorderEnabled && canMoveColumn(col as unknown as ColumnConfig)) {\n const handle = document.createElement('span');\n handle.className = 'tbw-visibility-handle';\n this.setIcon(handle, this.resolveIcon('dragHandle'));\n handle.title = 'Drag to reorder';\n row.appendChild(handle);\n }\n\n row.appendChild(labelWrapper);\n return row;\n }\n\n /**\n * Set up drag-and-drop listeners for a group header row.\n * Dragging a group moves all its member columns as a block.\n */\n private setupGroupDragListeners(header: HTMLElement, group: ColumnGroupInfo, columnList: HTMLElement): void {\n header.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedGroupId = group.id;\n this.draggedGroupFields = [...group.fields];\n // Use first field as representative for dataTransfer\n this.draggedField = null;\n this.draggedIndex = null;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `group:${group.id}`);\n }\n\n // Mark entire group (header + children) as dragging\n header.classList.add('dragging');\n columnList.querySelectorAll(`.tbw-visibility-row--grouped`).forEach((row) => {\n const field = row.getAttribute('data-field');\n if (field && this.draggedGroupFields.includes(field)) {\n row.classList.add('dragging');\n }\n });\n });\n\n header.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n // Group headers are also drop targets for other groups\n header.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n // Can't drop onto self\n if (this.draggedGroupId === group.id) return;\n // Can't drop individual columns onto group headers\n if (!this.draggedGroupId) return;\n\n const rect = header.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n const before = e.clientY < midY;\n\n this.clearDragClasses(columnList);\n header.classList.add('drop-target');\n header.classList.toggle('drop-before', before);\n header.classList.toggle('drop-after', !before);\n });\n\n header.addEventListener('dragleave', () => {\n header.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n header.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || !this.draggedGroupId || this.draggedGroupId === group.id) return;\n\n const rect = header.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n\n this.executeGroupDrop(this.draggedGroupFields, group.fields, before, columnList);\n });\n }\n\n /**\n * Execute a group drop — move the dragged group's fields as a block\n * to the position relative to the target group or column.\n */\n private executeGroupDrop(\n draggedFields: string[],\n targetFields: string[],\n before: boolean,\n columnList: HTMLElement,\n ): void {\n const allColumns = this.grid.getAllColumns();\n const currentOrder = allColumns.map((c) => c.field);\n\n // Remove dragged fields from current order\n const remaining = currentOrder.filter((f) => !draggedFields.includes(f));\n\n // Find insertion point relative to target\n // Use the first field of target group if inserting before, last if after\n const anchorField = before ? targetFields[0] : targetFields[targetFields.length - 1];\n const insertAt = remaining.indexOf(anchorField);\n if (insertAt === -1) return;\n\n // Insert the dragged group block at the correct position\n const insertIndex = before ? insertAt : insertAt + 1;\n\n // Preserve the dragged fields' original relative order\n const draggedInOrder = currentOrder.filter((f) => draggedFields.includes(f));\n remaining.splice(insertIndex, 0, ...draggedInOrder);\n\n this.grid.setColumnOrder(remaining);\n // Panel rebuild handled by column-move listener — but since we're calling\n // setColumnOrder directly (not through ReorderPlugin.moveColumn), we need\n // to manually trigger a rebuild.\n requestAnimationFrame(() => {\n if (this.columnListElement) {\n this.rebuildToggles(this.columnListElement);\n }\n });\n }\n\n /**\n * Set up drag-and-drop event listeners for a row.\n * On drop, emits a 'column-reorder-request' event for other plugins to handle.\n */\n private setupDragListeners(row: HTMLElement, field: string, index: number, columnList: HTMLElement): void {\n row.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = index;\n // Clear any stale group drag state\n this.draggedGroupId = null;\n this.draggedGroupFields = [];\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n row.classList.add('dragging');\n });\n\n row.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses(columnList);\n });\n\n row.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n\n // If dragging a group, only allow drop on ungrouped rows\n if (this.draggedGroupId) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n } else if (this.draggedField === field) {\n return;\n }\n\n const rect = row.getBoundingClientRect();\n const midY = rect.top + rect.height / 2;\n\n this.dropIndex = e.clientY < midY ? index : index + 1;\n\n // Clear other highlights\n this.clearDragClasses(columnList);\n // Re-mark dragged elements\n if (this.draggedGroupId) {\n columnList\n .querySelector(`.tbw-visibility-group-header[data-group-id=\"${this.draggedGroupId}\"]`)\n ?.classList.add('dragging');\n columnList.querySelectorAll('.tbw-visibility-row--grouped').forEach((r) => {\n const f = r.getAttribute('data-field');\n if (f && this.draggedGroupFields.includes(f)) r.classList.add('dragging');\n });\n } else if (this.draggedField) {\n columnList.querySelector(`.tbw-visibility-row[data-field=\"${this.draggedField}\"]`)?.classList.add('dragging');\n }\n\n row.classList.add('drop-target');\n row.classList.toggle('drop-before', e.clientY < midY);\n row.classList.toggle('drop-after', e.clientY >= midY);\n });\n\n row.addEventListener('dragleave', () => {\n row.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n row.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n\n if (!this.isDragging) return;\n\n // Group drop onto an ungrouped row\n if (this.draggedGroupId && this.draggedGroupFields.length > 0) {\n if (row.classList.contains('tbw-visibility-row--grouped')) return;\n const rect = row.getBoundingClientRect();\n const before = e.clientY < rect.top + rect.height / 2;\n this.executeGroupDrop(this.draggedGroupFields, [field], before, columnList);\n return;\n }\n\n // Individual column drop\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n // Calculate the effective target index (in the filtered non-utility list)\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n\n if (effectiveToIndex !== draggedIndex) {\n // Convert from non-utility index to full column order index\n // by counting how many utility columns come before the target position\n const allColumns = this.grid.getAllColumns();\n const nonUtilityColumns = allColumns.filter((c) => !c.utility);\n\n // Find the target field at effectiveToIndex in non-utility list\n const targetField = nonUtilityColumns[effectiveToIndex]?.field;\n // Find its actual index in the full column order\n const fullOrderToIndex = targetField ? allColumns.findIndex((c) => c.field === targetField) : allColumns.length;\n\n // Emit a request event - other plugins (like ReorderPlugin) can listen and handle\n const detail: ColumnReorderRequestDetail = {\n field: draggedField,\n fromIndex: draggedIndex, // Not used by ReorderPlugin, just for info\n toIndex: fullOrderToIndex,\n };\n this.emit<ColumnReorderRequestDetail>('column-reorder-request', detail);\n // Panel rebuild is handled by the column-move listener in attach()\n }\n });\n }\n // #endregion\n}\n"],"names":["canMoveColumn","column","meta","lockPosition","suppressMovable","VisibilityPlugin","BaseGridPlugin","static","name","required","reason","queries","type","description","styles","defaultConfig","allowHideAll","columnListElement","isDragging","draggedField","draggedIndex","dropIndex","draggedGroupId","draggedGroupFields","clearDragClasses","container","querySelectorAll","forEach","r","classList","remove","attach","grid","super","addEventListener","this","requestAnimationFrame","rebuildToggles","signal","disconnectSignal","detach","handleQuery","query","params","context","isHeader","field","lockVisibility","id","label","icon","order","action","hideColumn","getToolPanel","PANEL_ID","title","tooltip","render","renderPanelContent","show","openToolPanel","expandedToolPanelSections","includes","toggleToolPanelSection","hide","closeToolPanel","toggle","isToolPanelOpen","isColumnVisible","setColumnVisible","visible","getVisibleColumns","getAllColumns","filter","c","map","getHiddenColumns","showAll","showAllColumns","toggleColumn","toggleColumnVisibility","showColumn","isPanelVisible","wrapper","document","createElement","className","columnList","appendChild","showAllBtn","textContent","hasReorderPlugin","plugin","getPluginByName","moveColumn","reorderEnabled","innerHTML","allColumns","utility","groupResults","groups","flat","g","fields","length","renderFlatColumnList","fieldToGroup","Map","group","set","renderedGroups","Set","col","get","has","add","groupFieldSet","groupCols","renderGroupSection","fullIndex","indexOf","createColumnRow","columns","header","setAttribute","draggable","setupGroupDragListeners","headerLabel","groupCheckbox","visibleCount","allLocked","every","lockVisible","checked","indeterminate","disabled","newVisible","setTimeout","headerText","handle","setIcon","resolveIcon","insertBefore","allColumnsFullList","findIndex","row","index","String","setupDragListeners","labelWrapper","checkbox","text","e","dataTransfer","effectAllowed","setData","getAttribute","preventDefault","rect","getBoundingClientRect","midY","top","height","before","clientY","executeGroupDrop","draggedFields","targetFields","currentOrder","remaining","f","anchorField","insertAt","insertIndex","draggedInOrder","splice","setColumnOrder","contains","querySelector","effectiveToIndex","nonUtilityColumns","targetField","detail","fromIndex","toIndex","emit"],"mappings":"oVA0CA,SAASA,EAAcC,GACrB,MAAMC,EAAOD,EAAOC,MAAQ,CAAA,EAC5B,OAA6B,IAAtBA,EAAKC,eAAkD,IAAzBD,EAAKE,eAC5C,CAwFO,MAAMC,UAAyBC,EAAAA,eAOpCC,oBAA4D,CAC1D,CAAEC,KAAM,UAAWC,UAAU,EAAOC,OAAQ,wDAO9CH,gBAAoD,CAClDI,QAAS,CACP,CACEC,KAAM,sBACNC,YAAa,+DAMVL,KAAO,aAGhBD,gBAA2B,UAETO,65GAGlB,iBAAuBC,GACrB,MAAO,CACLC,cAAc,EAElB,CAGQC,kBAAwC,KAGxCC,YAAa,EACbC,aAA8B,KAC9BC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gB;IAChB,SAAkB,MAAM,SAAU;IAElC,gBAAgB;IAChB,cAAuB,aAAa,IAAI,OAAO,CAAC,aAAa,CAAC,CAI7D;IAED;;;OAGG;IACH,OAAO,KAAK,aAAa,GAQxB;IAED;;;OAGG;IACH,cAAuB,iBAAiB,IAAI,MAAM,CAMjD;IAGD,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,SAAS,CAAuB;IAExC;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAOhC;;OAEG;IACH,OAAO,CAAC,gBAAgB;IASxB,gBAAgB;IACP,MAAM,CAAC,IAAI,EAAE,OAAO,+BAA+B,EAAE,WAAW,GAAG,IAAI;IAiBhF,gBAAgB;IACP,MAAM,IAAI,IAAI;IAUvB,gBAAgB;IACP,WAAW,IAAI,IAAI;IAiG5B;;;OAGG;IACM,SAAS,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,GAAG,IAAI;IAyCxD;;;OAGG;IACH,cAAc,IAAI,MAAM,EAAE;IAI1B;;;;OAIG;IACH,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAoBhD;;;OAGG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI;IAIrC;;OAEG;IACH,gBAAgB,IAAI,IAAI;IAQxB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAS9B;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAmDnB;;;OAGG;IACH,OAAO,CAAC,WAAW;IAgDnB;;OAEG;IACH,OAAO,CAAC,iBAAiB;CAqB1B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"column-drag.d.ts","sourceRoot":"","sources":["../../../../../../libs/grid/src/lib/plugins/reorder/column-drag.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAErD;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,IAAI,GAAG,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,IAAI,CAAC,GAAG,OAAO,CAIjF;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAS1F;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,MAAM,CAU/F;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,GAAG,OAAO,EAAE,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAmBnH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../libs/grid/src/lib/plugins/reorder/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC"}
@@ -1,2 +0,0 @@
1
- document.createElement("template").innerHTML='<div class="cell" role="gridcell" part="cell"></div>';document.createElement("template").innerHTML='<div class="data-grid-row" role="row" part="row"></div>';const e='<svg viewBox="0 0 16 16" width="12" height="12"><path fill="currentColor" d="M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z"/></svg>',t={expand:"▶",collapse:"▼",sortAsc:"▲",sortDesc:"▼",sortNone:"⇅",submenuArrow:"▶",dragHandle:"⋮⋮",toolPanel:"☰",filter:e,filterActive:e,print:"🖨️"};class r{static dependencies;static manifest;version="undefined"!=typeof __GRID_VERSION__?__GRID_VERSION__:"dev";styles;cellRenderers;headerRenderers;cellEditors;grid;config;userConfig;#e;get defaultConfig(){return{}}constructor(e={}){this.userConfig=e}attach(e){this.#e?.abort(),this.#e=new AbortController,this.grid=e,this.config={...this.defaultConfig,...this.userConfig}}detach(){this.#e?.abort(),this.#e=void 0}getPlugin(e){return this.grid?.getPlugin(e)}emit(e,t){this.grid?.dispatchEvent?.(new CustomEvent(e,{detail:t,bubbles:!0}))}emitCancelable(e,t){const r=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});return this.grid?.dispatchEvent?.(r),r.defaultPrevented}on(e,t){this.grid?._pluginManager?.subscribe(this,e,t)}off(e){this.grid?._pluginManager?.unsubscribe(this,e)}emitPluginEvent(e,t){this.grid?._pluginManager?.emitPluginEvent(e,t)}requestRender(){this.grid?.requestRender?.()}requestColumnsRender(){this.grid?.requestColumnsRender?.()}requestRenderWithFocus(){this.grid?.requestRenderWithFocus?.()}requestAfterRender(){this.grid?.requestAfterRender?.()}get rows(){return this.grid?.rows??[]}get sourceRows(){return this.grid?.sourceRows??[]}get columns(){return this.grid?.columns??[]}get visibleColumns(){return this.grid?._visibleColumns??[]}get gridElement(){return this.grid}get disconnectSignal(){return this.#e?.signal??this.grid?.disconnectSignal}get gridIcons(){const e=this.grid?.gridConfig?.icons??{};return{...t,...e}}get isAnimationEnabled(){const e=this.grid?.effectiveConfig?.animation?.mode??"reduced-motion";if(!1===e||"off"===e)return!1;if(!0===e||"on"===e)return!0;const t=this.gridElement;if(t){return"0"!==getComputedStyle(t).getPropertyValue("--tbw-animation-enabled").trim()}return!0}get animationDuration(){const e=this.gridElement;if(e){const t=getComputedStyle(e).getPropertyValue("--tbw-animation-duration").trim(),r=parseInt(t,10);if(!isNaN(r))return r}return 200}resolveIcon(e,t){return void 0!==t?t:this.gridIcons[e]}setIcon(e,t){"string"==typeof t?e.innerHTML=t:t instanceof HTMLElement&&(e.innerHTML="",e.appendChild(t.cloneNode(!0)))}warn(e){console.warn(`[tbw-grid:${this.name}] ${e}`)}}function i(e,t,r){if(t===r)return e;if(t<0||t>=e.length)return e;if(r<0||r>e.length)return e;const i=[...e],[n]=i.splice(t,1);return i.splice(r,0,n),i}class n extends r{name="reorder";styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){if(!e||!function(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}(e))return!1;return!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(e=>{const t=e,r=t.getAttribute("data-field");if(!r)return;const n=this.columns.find(e=>e.field===r);this.canMoveColumnWithPlugins(n)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const i=this.getColumnOrder().indexOf(r);this.isDragging=!0,this.draggedField=r,this.draggedIndex=i,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",r)),t.classList.add("dragging")}),t.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging||this.draggedField===r)return;const i=t.getBoundingClientRect(),n=i.left+i.width/2,o=this.getColumnOrder().indexOf(r);this.dropIndex=e.clientX<n?o:o+1,t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<n),t.classList.toggle("drop-after",e.clientX>=n)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedField,r=this.draggedIndex,n=this.dropIndex;if(!this.isDragging||null===t||null===r||null===n)return;const o=n>r?n-1:n,s=i(this.getColumnOrder(),r,o),a={field:t,fromIndex:r,toIndex:o,columnOrder:s};this.emitCancelable("column-move",a)||this.updateColumnOrder(s)}))):t.draggable=!1})}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const t=this.grid,r=t._focusCol,i=t._visibleColumns;if(r<0||r>=i.length)return;const n=i[r];if(!this.canMoveColumnWithPlugins(n))return;const o=this.getColumnOrder(),s=o.indexOf(n.field);if(-1===s)return;const a="ArrowLeft"===e.key?s-1:s+1;if(a<0||a>=o.length)return;const l=i.find(e=>e.field===o[a]);return this.canMoveColumnWithPlugins(l)?(this.moveColumn(n.field,a),t._focusCol=a,function(e,t){if(e._virtualization?.enabled){const{rowHeight:t,container:r,viewportEl:i}=e._virtualization,n=r,o=i?.clientHeight??n?.clientHeight??0;if(n&&o>0){const r=e._focusRow*t;r<n.scrollTop?n.scrollTop=r:r+t>n.scrollTop+o&&(n.scrollTop=r-o+t)}}const r=void 0!==e._activeEditRows&&-1!==e._activeEditRows||!!e._isGridEditMode;var i;r||e.refreshVirtualWindow(!1),(i=e._bodyEl)&&i.querySelectorAll(".cell-focus").forEach(e=>e.classList.remove("cell-focus")),Array.from(e._bodyEl.querySelectorAll('[aria-selected="true"]')).forEach(e=>{e.setAttribute("aria-selected","false")});const n=e._focusRow,o=e._virtualization.start??0,s=e._virtualization.end??e._rows.length;if(n>=o&&n<s){const i=e._bodyEl.querySelectorAll(".data-grid-row")[n-o];let s=i?.children[e._focusCol];if(s&&s.classList?.contains("cell")||(s=i?.querySelector(`.cell[data-col="${e._focusCol}"]`)??i?.querySelector(".cell[data-col]")),s){s.classList.add("cell-focus"),s.setAttribute("aria-selected","true");const n=e.querySelector(".tbw-scroll-area");if(n&&s&&(!r||t?.forceHorizontalScroll)){const t=e._getHorizontalScrollOffsets?.(i??void 0,s)??{left:0,right:0};if(!t.skipScroll){const e=s.getBoundingClientRect(),r=n.getBoundingClientRect(),i=e.left-r.left+n.scrollLeft,o=i+e.width,a=n.scrollLeft+t.left,l=n.scrollLeft+n.clientWidth-t.right;i<a?n.scrollLeft=i-t.left:o>l&&(n.scrollLeft=o-n.clientWidth+t.right)}}if(r&&s.classList.contains("editing")){const e=s.querySelector('input,select,textarea,[contenteditable="true"],[contenteditable=""],[tabindex]:not([tabindex="-1"])');if(e&&document.activeElement!==e)try{e.focus({preventScroll:!0})}catch{}}else if(r&&!s.contains(document.activeElement)){s.hasAttribute("tabindex")||s.setAttribute("tabindex","-1");try{s.focus({preventScroll:!0})}catch{}}else if(!r){const t=e;document.activeElement!==t&&t.focus({preventScroll:!0})}}}}(this.grid),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const r=this.getColumnOrder(),n=r.indexOf(e);if(-1===n)return;const o=i(r,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:o})||this.updateColumnOrder(o)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=/* @__PURE__ */new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");r&&e.set(r,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const r=/* @__PURE__ */new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");if(!i)return;const n=e.get(i);if(void 0===n)return;const o=n-t.getBoundingClientRect().left;Math.abs(o)>1&&r.set(i,o)}),0===r.size)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=r.get(e.getAttribute("data-field")??"");if(void 0!==t){const r=e;r.style.transform=`translateX(${t}px)`,i.push(r)}}),0===i.length)return;this.gridElement.offsetHeight;const n=this.animationDuration;requestAnimationFrame(()=>{i.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{i.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},n+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const r=this.captureHeaderPositions();e();const i=/* @__PURE__ */new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const n=r.get(t);if(void 0===n)return;const o=e.getBoundingClientRect().left;Math.abs(n-o)>1&&i.add(t)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&i.has(t)){const t=e;t.classList.add("fade-animating"),n.push(t)}}),0===n.length)return;const o=this.animationDuration;setTimeout(()=>{n.forEach(e=>e.classList.remove("fade-animating"))},o+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}}export{n as ReorderPlugin};
2
- //# sourceMappingURL=index.js.map