@toolbox-web/grid 2.6.0 → 2.7.1

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 (60) hide show
  1. package/all.d.ts +1 -0
  2. package/all.js +2 -2
  3. package/all.js.map +1 -1
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/core/internal/aria.d.ts +4 -0
  7. package/lib/core/types.d.ts +43 -0
  8. package/lib/features/sticky-rows.d.ts +9 -0
  9. package/lib/features/sticky-rows.js +2 -0
  10. package/lib/features/sticky-rows.js.map +1 -0
  11. package/lib/plugins/clipboard/index.js.map +1 -1
  12. package/lib/plugins/column-virtualization/index.js.map +1 -1
  13. package/lib/plugins/context-menu/index.js +1 -1
  14. package/lib/plugins/context-menu/index.js.map +1 -1
  15. package/lib/plugins/editing/index.js.map +1 -1
  16. package/lib/plugins/export/index.js.map +1 -1
  17. package/lib/plugins/filtering/index.js.map +1 -1
  18. package/lib/plugins/grouping-columns/index.js.map +1 -1
  19. package/lib/plugins/grouping-rows/GroupingRowsPlugin.d.ts +15 -0
  20. package/lib/plugins/grouping-rows/index.js +2 -2
  21. package/lib/plugins/grouping-rows/index.js.map +1 -1
  22. package/lib/plugins/master-detail/index.js +1 -1
  23. package/lib/plugins/master-detail/index.js.map +1 -1
  24. package/lib/plugins/multi-sort/index.js.map +1 -1
  25. package/lib/plugins/pinned-columns/index.js.map +1 -1
  26. package/lib/plugins/pinned-rows/index.js.map +1 -1
  27. package/lib/plugins/pivot/index.js.map +1 -1
  28. package/lib/plugins/print/index.js.map +1 -1
  29. package/lib/plugins/reorder-columns/index.js.map +1 -1
  30. package/lib/plugins/reorder-rows/index.js.map +1 -1
  31. package/lib/plugins/responsive/index.js.map +1 -1
  32. package/lib/plugins/row-drag-drop/index.js.map +1 -1
  33. package/lib/plugins/selection/index.js.map +1 -1
  34. package/lib/plugins/server-side/index.js.map +1 -1
  35. package/lib/plugins/sticky-rows/StickyRowsPlugin.d.ts +114 -0
  36. package/lib/plugins/sticky-rows/index.d.ts +7 -0
  37. package/lib/plugins/sticky-rows/index.js +2 -0
  38. package/lib/plugins/sticky-rows/index.js.map +1 -0
  39. package/lib/plugins/sticky-rows/types.d.ts +67 -0
  40. package/lib/plugins/tooltip/index.js.map +1 -1
  41. package/lib/plugins/tree/index.js +1 -1
  42. package/lib/plugins/tree/index.js.map +1 -1
  43. package/lib/plugins/tree/types.d.ts +4 -0
  44. package/lib/plugins/undo-redo/index.js.map +1 -1
  45. package/lib/plugins/visibility/index.js.map +1 -1
  46. package/package.json +1 -1
  47. package/umd/grid.all.umd.js +1 -1
  48. package/umd/grid.all.umd.js.map +1 -1
  49. package/umd/grid.umd.js +1 -1
  50. package/umd/grid.umd.js.map +1 -1
  51. package/umd/plugins/context-menu.umd.js +1 -1
  52. package/umd/plugins/context-menu.umd.js.map +1 -1
  53. package/umd/plugins/grouping-rows.umd.js +1 -1
  54. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  55. package/umd/plugins/master-detail.umd.js +1 -1
  56. package/umd/plugins/master-detail.umd.js.map +1 -1
  57. package/umd/plugins/sticky-rows.umd.js +2 -0
  58. package/umd/plugins/sticky-rows.umd.js.map +1 -0
  59. package/umd/plugins/tree.umd.js +1 -1
  60. package/umd/plugins/tree.umd.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Mutates the Set in-place and returns it (avoids O(n) copy per toggle).\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n if (expandedRows.has(row)) {\n expandedRows.delete(row);\n } else {\n expandedRows.add(row);\n }\n return expandedRows;\n}\n\n/**\n * Expand a detail row.\n * Mutates the Set in-place and returns it (avoids O(n) copy).\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n expandedRows.add(row);\n return expandedRows;\n}\n\n/**\n * Collapse a detail row.\n * Mutates the Set in-place and returns it (avoids O(n) copy).\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n expandedRows.delete(row);\n return expandedRows;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number,\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig, GridHost } from '../../core/types';\nimport type { DataSourceChildrenDetail, FetchChildrenQuery } from '../server-side/datasource-types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /**\n * Optional dependency on ServerSide for async detail data.\n * When loaded, MasterDetail can fetch detail data via `datasource:fetch-children`.\n */\n static override readonly dependencies = [\n { name: 'serverSide', required: false, reason: 'Fetches detail data via datasource:fetch-children on expand' },\n ];\n\n /** Typed internal grid accessor. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n\n // Listen for datasource:children — receive async detail data from ServerSide\n this.on('datasource:children', (detail: unknown) => {\n const d = detail as DataSourceChildrenDetail;\n if (d.context?.source !== 'master-detail') return;\n d.claimed = true;\n\n const row = d.context.row;\n if (row && this.expandedRows.has(row)) {\n this.detailDataMap.set(row, d.rows);\n this.loadingDetails.delete(row);\n // Re-render: remove existing detail element so #syncDetailRows recreates it\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n existingDetail.remove();\n this.detailElements.delete(row);\n this.measuredDetailHeights.delete(row);\n }\n this.requestRender();\n }\n });\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseDetailElement) {\n const adapterRenderer = adapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n /** Rows currently waiting for datasource:children response. */\n private loadingDetails: Set<any> = new Set();\n /** Child rows received via datasource:children, keyed by parent row reference. */\n private detailDataMap: Map<any, unknown[]> = new Map();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n * Skips synthetic rows (e.g., group headers from GroupingRowsPlugin).\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n // Synthetic rows (e.g., group headers) don't have detail content\n if (row?.__isGroupRow) return;\n\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n\n // Request detail data from ServerSide if available and not already cached\n if (!this.detailDataMap.has(row)) {\n const isServerSideActive = this.grid?.query?.('datasource:is-active', null);\n if (isServerSideActive) {\n this.loadingDetails.add(row);\n this.grid.query('datasource:fetch-children', {\n context: { source: 'master-detail', row, rowIndex },\n } satisfies FetchChildrenQuery);\n }\n }\n } else {\n this.loadingDetails.delete(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n this.loadingDetails.clear();\n this.detailDataMap.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, isExpanded ? 'collapse' : 'expand');\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n // _focusCol is a visible-column index (set from data-col), so use visibleColumns\n const column = this.visibleColumns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#fixExpanderHeaderSpan();\n this.#syncDetailRows();\n }\n\n /**\n * The expander header cell is hidden (display:none), so the next sibling\n * header cell must span two CSS grid tracks (the expander's + its own)\n * to keep the header aligned with data rows. The column position is\n * computed dynamically so that pinned columns can appear before the expander.\n */\n #fixExpanderHeaderSpan(): void {\n const expanderHeader = this.gridElement?.querySelector(\n '.header-row .cell[data-field=\"__tbw_expander\"]',\n ) as HTMLElement | null;\n if (!expanderHeader) return;\n\n const colIdx = parseInt(expanderHeader.getAttribute('data-col') || '0', 10);\n const nextCell = expanderHeader.nextElementSibling as HTMLElement | null;\n if (nextCell) {\n // CSS grid columns are 1-based; span from the expander's track to the next cell's track.\n nextCell.style.gridColumn = `${colIdx + 1} / ${colIdx + 3}`;\n }\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row || !this.expandedRows.has(row)) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\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 (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row && !row.__isGroupRow) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row && !row.__isGroupRow) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n * Skips synthetic rows (e.g., group headers from GroupingRowsPlugin).\n */\n expandAll(): void {\n for (const row of this.rows) {\n if (row?.__isGroupRow) continue;\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Get async detail data fetched via `ServerSidePlugin` for a specific row.\n *\n * Returns the child rows received from `datasource:children` after a\n * `datasource:fetch-children` query was fired on expand. Returns `undefined`\n * when ServerSide is not loaded or data has not arrived yet.\n *\n * @param rowIndex - Index of the row\n * @returns Array of child rows or undefined\n */\n getDetailData(rowIndex: number): unknown[] | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailDataMap.get(row) : undefined;\n }\n\n /**\n * Check if detail data is currently being loaded for a row.\n * @param rowIndex - Index of the row\n * @returns Whether the detail is loading\n */\n isDetailLoading(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? this.loadingDetails.has(row) : false;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.#internalGrid;\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","has","delete","add","createDetailElement","rowIndex","renderer","columnCount","detailRow","document","createElement","className","setAttribute","String","detailCell","style","gridColumn","content","innerHTML","HTMLElement","appendChild","MasterDetailPlugin","BaseGridPlugin","name","styles","static","required","reason","internalGrid","this","grid","defaultConfig","detailHeight","expandOnRowClick","collapseOnClickOutside","animation","attach","super","parseLightDomDetail","on","detail","d","context","source","claimed","detailDataMap","set","rows","loadingDetails","existingDetail","detailElements","get","remove","measuredDetailHeights","requestRender","gridEl","gridElement","detailEl","querySelector","adapter","__frameworkAdapter","parseDetailElement","adapterRenderer","config","detailRenderer","getAttribute","showExpandColumn","heightAttr","configUpdates","parseInt","templateHTML","trim","_rowIndex","evaluated","evalTemplateString","value","sanitizeHTML","Object","keys","length","animationStyle","isAnimationEnabled","animateExpand","classList","measured","measureOnce","measureAndCacheDetailHeight","addEventListener","once","setTimeout","animationDuration","animateCollapse","onComplete","cleanup","isConnected","height","offsetHeight","previousHeight","invalidateRowHeight","Set","Map","rowsToAnimate","getDetailHeight","contains","cachedHeight","DEFAULT_DETAIL_HEIGHT","toggleAndEmit","__isGroupRow","expanded","isServerSideActive","query","emit","detach","clear","processColumns","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","viewRenderer","renderCtx","isExpanded","container","toggle","setIcon","onRowClick","event","onCellClick","target","originalEvent","size","queueMicrotask","syncDetailRows","onKeyDown","key","focusCol","_focusCol","focusRow","_focusRow","column","visibleColumns","isExpanderColumn","preventDefault","requestRenderWithFocus","afterRender","fixExpanderHeaderSpan","expanderHeader","colIdx","nextCell","nextElementSibling","onScrollRender","body","gridInternal","rowPool","_rowPool","vStart","_virtualization","start","vEnd","end","visibleStart","visibleEnd","visibleRowMap","poolLen","Math","min","i","rowEl","parentNode","dataRows","querySelectorAll","firstCell","indexOf","isStillExpanded","isRowVisible","unmount","firstElementChild","previousElementSibling","after","shouldAnimate","requestAnimationFrame","getRowHeight","_index","defaultRowHeight","adjustVirtualStart","scrollTop","rowHeight","positionCache","minStart","offset","expandedIndices","index","push","sort","a","b","cumulativeExtraHeight","actualRowTop","expand","expandDetailRow","collapse","collapseDetailRow","isDetailExpanded","expandAll","collapseAll","getExpandedRows","indices","idx","getDetailElement","getDetailData","isDetailLoading","refreshDetailRenderer","currentRenderer","refreshColumns"],"mappings":"sgBAaO,SAASA,EAAgBC,EAA2BC,GAMzD,OALID,EAAaE,IAAID,GACnBD,EAAaG,OAAOF,GAEpBD,EAAaI,IAAIH,GAEZD,CACT,CA+BO,SAASK,EACdJ,EACAK,EACAC,EACAC,GAEA,MAAMC,EAAYC,SAASC,cAAc,OACzCF,EAAUG,UAAY,oBACtBH,EAAUI,aAAa,kB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AAgB,GAChDnC,KAAKS,uBAGAT,KAAKkC,OAAOC,gBAAkBqJ,IACjCxL,KAAKkC,OAAS,IAAKlC,KAAKkC,OAAQC,eAAgBqJ,IAO9CxL,KAAKkC,OAAOC,eAAgB,CAC9B,MAAMlC,EAAOD,MAAKD,EACiB,mBAAxBE,EAAKwL,eACdxL,EAAKwL,iBAGLzL,KAAKyB,eAET,CACF"}
1
+ {"version":3,"file":"master-detail.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/master-detail/master-detail.ts","../../../../../libs/grid/src/lib/plugins/master-detail/MasterDetailPlugin.ts"],"sourcesContent":["/**\n * Master/Detail Core Logic\n *\n * Pure functions for managing detail row expansion state.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Uses `any` for maximum flexibility with user-defined row types.\n\n/**\n * Toggle the expansion state of a detail row.\n * Mutates the Set in-place and returns it (avoids O(n) copy per toggle).\n */\nexport function toggleDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n if (expandedRows.has(row)) {\n expandedRows.delete(row);\n } else {\n expandedRows.add(row);\n }\n return expandedRows;\n}\n\n/**\n * Expand a detail row.\n * Mutates the Set in-place and returns it (avoids O(n) copy).\n */\nexport function expandDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n expandedRows.add(row);\n return expandedRows;\n}\n\n/**\n * Collapse a detail row.\n * Mutates the Set in-place and returns it (avoids O(n) copy).\n */\nexport function collapseDetailRow(expandedRows: Set<object>, row: object): Set<object> {\n expandedRows.delete(row);\n return expandedRows;\n}\n\n/**\n * Check if a detail row is expanded.\n */\nexport function isDetailExpanded(expandedRows: Set<object>, row: object): boolean {\n return expandedRows.has(row);\n}\n\n/**\n * Create a detail element for a given row.\n * The element spans all columns and contains the rendered content.\n */\nexport function createDetailElement(\n row: any,\n rowIndex: number,\n renderer: (row: any, rowIndex: number) => HTMLElement | string,\n columnCount: number,\n): HTMLElement {\n const detailRow = document.createElement('div');\n detailRow.className = 'master-detail-row';\n detailRow.setAttribute('data-detail-for', String(rowIndex));\n detailRow.setAttribute('role', 'row');\n\n const detailCell = document.createElement('div');\n detailCell.className = 'master-detail-cell';\n detailCell.setAttribute('role', 'cell');\n detailCell.style.gridColumn = `1 / ${columnCount + 1}`;\n\n const content = renderer(row, rowIndex);\n if (typeof content === 'string') {\n detailCell.innerHTML = content;\n } else if (content instanceof HTMLElement) {\n detailCell.appendChild(content);\n }\n\n detailRow.appendChild(detailCell);\n return detailRow;\n}\n","/**\n * Master/Detail Plugin (Class-based)\n *\n * Enables expandable detail rows showing additional content for each row.\n * Animation style is plugin-configured; respects grid-level animation.mode.\n */\n\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, CellClickEvent, GridElement, RowClickEvent } from '../../core/plugin/base-plugin';\nimport { createExpanderColumnConfig, findExpanderColumn, isExpanderColumn } from '../../core/plugin/expander-column';\nimport type { ColumnConfig, GridHost } from '../../core/types';\nimport type { DataSourceChildrenDetail, FetchChildrenQuery } from '../server-side/datasource-types';\nimport {\n collapseDetailRow,\n createDetailElement,\n expandDetailRow,\n isDetailExpanded,\n toggleDetailRow,\n} from './master-detail';\nimport styles from './master-detail.css?inline';\nimport type { DetailExpandDetail, ExpandCollapseAnimation, MasterDetailConfig } from './types';\n\n/**\n * Master-Detail Plugin for tbw-grid\n *\n * Creates expandable detail rows that reveal additional content beneath each master row.\n * Perfect for order/line-item UIs, employee/department views, or any scenario where\n * you need to show related data without navigating away.\n *\n * ## Installation\n *\n * ```ts\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n * ```\n *\n * ## CSS Custom Properties\n *\n * | Property | Default | Description |\n * |----------|---------|-------------|\n * | `--tbw-master-detail-bg` | `var(--tbw-color-row-alt)` | Detail row background |\n * | `--tbw-master-detail-border` | `var(--tbw-color-border)` | Detail row border |\n * | `--tbw-detail-padding` | `1em` | Detail content padding |\n * | `--tbw-animation-duration` | `200ms` | Expand/collapse animation |\n *\n * @example Basic Master-Detail with HTML Template\n * ```ts\n * import '@toolbox-web/grid';\n * import { MasterDetailPlugin } from '@toolbox-web/grid/plugins/master-detail';\n *\n * grid.gridConfig = {\n * columns: [\n * { field: 'orderId', header: 'Order ID' },\n * { field: 'customer', header: 'Customer' },\n * { field: 'total', header: 'Total', type: 'currency' },\n * ],\n * plugins: [\n * new MasterDetailPlugin({\n * detailRenderer: (row) => `\n * <div class=\"order-details\">\n * <h4>Order Items</h4>\n * <ul>${row.items.map(i => `<li>${i.name} - $${i.price}</li>`).join('')}</ul>\n * </div>\n * `,\n * }),\n * ],\n * };\n * ```\n *\n * @example Nested Grid in Detail\n * ```ts\n * new MasterDetailPlugin({\n * detailRenderer: (row) => {\n * const childGrid = document.createElement('tbw-grid');\n * childGrid.style.height = '200px';\n * childGrid.gridConfig = { columns: [...] };\n * childGrid.rows = row.items || [];\n * return childGrid;\n * },\n * })\n * ```\n *\n * @see {@link MasterDetailConfig} for all configuration options\n * @see {@link DetailExpandDetail} for expand/collapse event details\n *\n * @internal Extends BaseGridPlugin\n */\nexport class MasterDetailPlugin extends BaseGridPlugin<MasterDetailConfig> {\n /** @internal */\n readonly name = 'masterDetail';\n /** @internal */\n override readonly styles = styles;\n\n /**\n * Optional dependency on ServerSide for async detail data.\n * When loaded, MasterDetail can fetch detail data via `datasource:fetch-children`.\n */\n static override readonly dependencies = [\n { name: 'serverSide', required: false, reason: 'Fetches detail data via datasource:fetch-children on expand' },\n ];\n\n /** Typed internal grid accessor. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /** @internal */\n protected override get defaultConfig(): Partial<MasterDetailConfig> {\n return {\n detailHeight: 'auto',\n expandOnRowClick: false,\n collapseOnClickOutside: false,\n // Note: showExpandColumn is intentionally NOT defaulted here.\n // If undefined, processColumns() adds expander only when detailRenderer is provided.\n // Set to true for framework adapters that register renderers asynchronously.\n animation: 'slide', // Plugin's own default\n };\n }\n\n // #region Light DOM Parsing\n\n /**\n * Called when plugin is attached to the grid.\n * Parses light DOM for `<tbw-grid-detail>` elements to configure detail templates.\n * @internal\n */\n override attach(grid: GridElement): void {\n super.attach(grid);\n this.parseLightDomDetail();\n\n // Listen for datasource:children — receive async detail data from ServerSide\n this.on('datasource:children', (detail: unknown) => {\n const d = detail as DataSourceChildrenDetail;\n if (d.context?.source !== 'master-detail') return;\n d.claimed = true;\n\n const row = d.context.row;\n if (row && this.expandedRows.has(row)) {\n this.detailDataMap.set(row, d.rows);\n this.loadingDetails.delete(row);\n // Re-render: remove existing detail element so #syncDetailRows recreates it\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n existingDetail.remove();\n this.detailElements.delete(row);\n this.measuredDetailHeights.delete(row);\n }\n this.requestRender();\n }\n });\n }\n\n /**\n * Parse `<tbw-grid-detail>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-detail>\n * <div class=\"detail-content\">\n * <p>Name: {{ row.name }}</p>\n * <p>Email: {{ row.email }}</p>\n * </div>\n * </tbw-grid-detail>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `animation`: 'slide' | 'fade' | 'false' (default: 'slide')\n * - `show-expand-column`: 'true' | 'false' (default: 'true')\n * - `expand-on-row-click`: 'true' | 'false' (default: 'false')\n * - `collapse-on-click-outside`: 'true' | 'false' (default: 'false')\n * - `height`: number (pixels) or 'auto' (default: 'auto')\n */\n private parseLightDomDetail(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const detailEl = gridEl.querySelector('tbw-grid-detail');\n if (!detailEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., Angular adapter intercepts for ng-template rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseDetailElement) {\n const adapterRenderer = adapter.parseDetailElement(detailEl);\n if (adapterRenderer) {\n this.config = { ...this.config, detailRenderer: adapterRenderer };\n return;\n }\n }\n\n // Parse attributes for configuration\n const animation = detailEl.getAttribute('animation');\n const showExpandColumn = detailEl.getAttribute('show-expand-column');\n const expandOnRowClick = detailEl.getAttribute('expand-on-row-click');\n const collapseOnClickOutside = detailEl.getAttribute('collapse-on-click-outside');\n const heightAttr = detailEl.getAttribute('height');\n\n const configUpdates: Partial<MasterDetailConfig> = {};\n\n if (animation !== null) {\n configUpdates.animation = animation === 'false' ? false : (animation as 'slide' | 'fade');\n }\n if (showExpandColumn !== null) {\n configUpdates.showExpandColumn = showExpandColumn !== 'false';\n }\n if (expandOnRowClick !== null) {\n configUpdates.expandOnRowClick = expandOnRowClick === 'true';\n }\n if (collapseOnClickOutside !== null) {\n configUpdates.collapseOnClickOutside = collapseOnClickOutside === 'true';\n }\n if (heightAttr !== null) {\n configUpdates.detailHeight = heightAttr === 'auto' ? 'auto' : parseInt(heightAttr, 10);\n }\n\n // Get template content from innerHTML\n const templateHTML = detailEl.innerHTML.trim();\n if (templateHTML && !this.config.detailRenderer) {\n // Create a template-based renderer using the inner HTML\n configUpdates.detailRenderer = (row: any, _rowIndex: number): string => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row });\n // Sanitize the result to prevent XSS\n return sanitizeHTML(evaluated);\n };\n }\n\n // Merge updates into config\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n // #region Animation Helpers\n\n /**\n * Get expand/collapse animation style from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationStyle(): ExpandCollapseAnimation {\n if (!this.isAnimationEnabled) return false;\n return this.config.animation ?? 'slide';\n }\n\n /**\n * Apply expand animation to a detail element.\n * Returns true if animation was applied, false if skipped.\n * When animated, height measurement is deferred to animationend to avoid\n * measuring during the max-height: 0 CSS animation constraint.\n */\n private animateExpand(detailEl: HTMLElement, row?: any, rowIndex?: number): boolean {\n if (!this.isAnimationEnabled || this.animationStyle === false) return false;\n\n detailEl.classList.add('tbw-expanding');\n\n let measured = false;\n const measureOnce = () => {\n if (measured) return;\n measured = true;\n detailEl.classList.remove('tbw-expanding');\n\n // Measure height AFTER animation completes - the element now has its\n // natural height without the max-height constraint from the animation.\n if (row !== undefined && rowIndex !== undefined) {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n }\n };\n\n detailEl.addEventListener('animationend', measureOnce, { once: true });\n // Fallback timeout in case animationend doesn't fire (e.g., element detached,\n // animation removed, or framework rendering delays). Matches animateCollapse pattern.\n setTimeout(measureOnce, this.animationDuration + 50);\n return true;\n }\n\n /**\n * Apply collapse animation to a detail element and remove after animation.\n */\n private animateCollapse(detailEl: HTMLElement, onComplete: () => void): void {\n if (!this.isAnimationEnabled || this.animationStyle === false) {\n onComplete();\n return;\n }\n\n detailEl.classList.add('tbw-collapsing');\n const cleanup = () => {\n detailEl.classList.remove('tbw-collapsing');\n onComplete();\n };\n detailEl.addEventListener('animationend', cleanup, { once: true });\n // Fallback timeout in case animation doesn't fire\n setTimeout(cleanup, this.animationDuration + 50);\n }\n\n /**\n * Measure a detail element's height and update the position cache if it changed.\n * Used after layout settles (RAF) or after animation completes (animationend).\n */\n #measureAndCacheDetailHeight(detailEl: HTMLElement, row: any, rowIndex: number): void {\n if (!detailEl.isConnected) return;\n\n const height = detailEl.offsetHeight;\n if (height > 0) {\n const previousHeight = this.measuredDetailHeights.get(row);\n this.measuredDetailHeights.set(row, height);\n\n // Only invalidate if height actually changed\n // This triggers an incremental position cache update, not a full rebuild\n if (previousHeight !== height) {\n this.grid.invalidateRowHeight(rowIndex);\n }\n }\n }\n\n // #endregion\n\n // #region Internal State\n private expandedRows: Set<any> = new Set();\n private detailElements: Map<any, HTMLElement> = new Map();\n /** Cached measured heights - persists even when elements are virtualized out */\n private measuredDetailHeights: Map<any, number> = new Map();\n /** Rows that were just expanded by user action and should animate.\n * Prevents re-animation when rows scroll back into the virtual window. */\n private rowsToAnimate: Set<any> = new Set();\n /** Rows currently waiting for datasource:children response. */\n private loadingDetails: Set<any> = new Set();\n /** Child rows received via datasource:children, keyed by parent row reference. */\n private detailDataMap: Map<any, unknown[]> = new Map();\n\n /** Default height for detail rows when not configured */\n private static readonly DEFAULT_DETAIL_HEIGHT = 150;\n\n /**\n * Get the estimated height for a detail row.\n * Uses cached measured height when available (survives virtualization).\n * Avoids reading offsetHeight during CSS animations to prevent poisoning the cache.\n */\n private getDetailHeight(row: any): number {\n // Try DOM element first - works for tests and when element is connected\n const detailEl = this.detailElements.get(row);\n if (detailEl) {\n // Skip DOM measurement if currently animating (max-height constraint gives wrong value)\n const isAnimating = detailEl.classList.contains('tbw-expanding') || detailEl.classList.contains('tbw-collapsing');\n if (!isAnimating) {\n const height = detailEl.offsetHeight;\n if (height > 0) {\n // Cache the measurement for when this row is virtualized out\n this.measuredDetailHeights.set(row, height);\n return height;\n }\n }\n }\n\n // DOM element missing, detached, or animating - check cached measurement\n const cachedHeight = this.measuredDetailHeights.get(row);\n if (cachedHeight && cachedHeight > 0) {\n return cachedHeight;\n }\n\n // Fallback to config or default\n return typeof this.config?.detailHeight === 'number'\n ? this.config.detailHeight\n : MasterDetailPlugin.DEFAULT_DETAIL_HEIGHT;\n }\n\n /**\n * Toggle a row's detail and emit event.\n * Skips synthetic rows (e.g., group headers from GroupingRowsPlugin).\n */\n private toggleAndEmit(row: any, rowIndex: number): void {\n // Synthetic rows (e.g., group headers) don't have detail content\n if (row?.__isGroupRow) return;\n\n this.expandedRows = toggleDetailRow(this.expandedRows, row as object);\n const expanded = this.expandedRows.has(row as object);\n if (expanded) {\n this.rowsToAnimate.add(row);\n\n // Request detail data from ServerSide if available and not already cached\n if (!this.detailDataMap.has(row)) {\n const isServerSideActive = this.grid?.query?.('datasource:is-active', null);\n if (isServerSideActive) {\n this.loadingDetails.add(row);\n this.grid.query('datasource:fetch-children', {\n context: { source: 'master-detail', row, rowIndex },\n } satisfies FetchChildrenQuery);\n }\n }\n } else {\n this.loadingDetails.delete(row);\n }\n this.emit<DetailExpandDetail>('detail-expand', {\n rowIndex,\n row: row as Record<string, unknown>,\n expanded,\n });\n this.requestRender();\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override detach(): void {\n this.expandedRows.clear();\n this.detailElements.clear();\n this.measuredDetailHeights.clear();\n this.rowsToAnimate.clear();\n this.loadingDetails.clear();\n this.detailDataMap.clear();\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processColumns(columns: readonly ColumnConfig[]): ColumnConfig[] {\n // Determine whether to add the expander column:\n // 1. If showExpandColumn === false: never add (explicit opt-out)\n // 2. If showExpandColumn === true: always add (explicit opt-in, for framework adapters)\n // 3. If showExpandColumn is undefined: add only if detailRenderer is provided\n //\n // This supports React/Angular adapters which register renderers asynchronously via light DOM.\n // They must set showExpandColumn: true to get the column immediately, avoiding layout shift.\n const shouldAddExpander =\n this.config.showExpandColumn === true || (this.config.showExpandColumn !== false && !!this.config.detailRenderer);\n\n if (!shouldAddExpander) {\n return [...columns];\n }\n\n const cols = [...columns];\n\n // Check if expander column already exists (from this or another plugin)\n const existingExpander = findExpanderColumn(cols);\n if (existingExpander) {\n // Another plugin already added an expander column - don't add duplicate\n // Our expand logic will be handled via onCellClick on the expander column\n return cols;\n }\n\n // Create dedicated expander column that stays fixed at position 0\n const expanderCol = createExpanderColumnConfig(this.name);\n expanderCol.viewRenderer = (renderCtx) => {\n const { row } = renderCtx;\n const isExpanded = this.expandedRows.has(row as object);\n\n const container = document.createElement('span');\n container.className = 'master-detail-expander expander-cell';\n\n // Expand/collapse toggle icon\n const toggle = document.createElement('span');\n toggle.className = `master-detail-toggle${isExpanded ? ' expanded' : ''}`;\n // Use grid-level icons (fall back to defaults)\n this.setIcon(toggle, isExpanded ? 'collapse' : 'expand');\n // role=\"button\" is required for aria-expanded to be valid\n toggle.setAttribute('role', 'button');\n toggle.setAttribute('tabindex', '0');\n toggle.setAttribute('aria-expanded', String(isExpanded));\n toggle.setAttribute('aria-label', isExpanded ? 'Collapse details' : 'Expand details');\n container.appendChild(toggle);\n\n return container;\n };\n\n // Prepend expander column to ensure it's always first\n return [expanderCol, ...cols];\n }\n\n /** @internal */\n override onRowClick(event: RowClickEvent): boolean | void {\n if (!this.config.expandOnRowClick || !this.config.detailRenderer) return;\n this.toggleAndEmit(event.row, event.rowIndex);\n return false;\n }\n\n /** @internal */\n override onCellClick(event: CellClickEvent): boolean | void {\n // Handle click on master-detail toggle icon (same pattern as TreePlugin)\n const target = event.originalEvent?.target as HTMLElement;\n if (target?.classList.contains('master-detail-toggle')) {\n this.toggleAndEmit(event.row, event.rowIndex);\n return true; // Prevent default handling\n }\n\n // Sync detail rows after cell click triggers refreshVirtualWindow\n // This runs in microtask to ensure DOM updates are complete\n if (this.expandedRows.size > 0) {\n queueMicrotask(() => this.#syncDetailRows());\n }\n return; // Don't prevent default\n }\n\n /** @internal */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n // SPACE toggles expansion when focus is on the expander column\n if (event.key !== ' ') return;\n\n const focusCol = this.grid._focusCol;\n const focusRow = this.grid._focusRow;\n // _focusCol is a visible-column index (set from data-col), so use visibleColumns\n const column = this.visibleColumns[focusCol];\n\n // Only handle SPACE on expander column\n if (!column || !isExpanderColumn(column)) return;\n\n const row = this.rows[focusRow];\n if (!row) return;\n\n event.preventDefault();\n this.toggleAndEmit(row, focusRow);\n\n // Restore focus styling after render completes via render pipeline\n this.requestRenderWithFocus();\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n this.#fixExpanderHeaderSpan();\n this.#syncDetailRows();\n }\n\n /**\n * The expander header cell is hidden (display:none), so the next sibling\n * header cell must span two CSS grid tracks (the expander's + its own)\n * to keep the header aligned with data rows. The column position is\n * computed dynamically so that pinned columns can appear before the expander.\n */\n #fixExpanderHeaderSpan(): void {\n const expanderHeader = this.gridElement?.querySelector(\n '.header-row .cell[data-field=\"__tbw_expander\"]',\n ) as HTMLElement | null;\n if (!expanderHeader) return;\n\n const colIdx = parseInt(expanderHeader.getAttribute('data-col') || '0', 10);\n const nextCell = expanderHeader.nextElementSibling as HTMLElement | null;\n if (nextCell) {\n // CSS grid columns are 1-based; span from the expander's track to the next cell's track.\n nextCell.style.gridColumn = `${colIdx + 1} / ${colIdx + 3}`;\n }\n }\n\n /**\n * Called on scroll to sync detail elements with visible rows.\n * Removes details for rows that scrolled out of view and reattaches for visible rows.\n * @internal\n */\n override onScrollRender(): void {\n if (!this.config.detailRenderer || this.expandedRows.size === 0) return;\n // Full sync needed on scroll to clean up orphaned details\n this.#syncDetailRows();\n }\n\n /**\n * Full sync of detail rows - cleans up stale elements and creates new ones.\n * Detail rows are inserted as siblings AFTER their master row to survive row rebuilds.\n *\n * PERF: Uses the grid's row pool (_rowPool) and virtual window (_virtualization.start/end)\n * to avoid querySelectorAll on every scroll frame. The pool is index-aligned with the\n * virtual window, so pool[i] corresponds to row index (start + i).\n */\n #syncDetailRows(): void {\n if (!this.config.detailRenderer) return;\n\n const body = this.gridElement?.querySelector('.rows');\n if (!body) return;\n\n // Use grid's virtualization state and row pool for O(1) lookups instead of querySelectorAll.\n // The row pool is an array of DOM elements aligned to the virtual window:\n // _rowPool[i] renders row data at index (_virtualization.start + i).\n const gridInternal = this.grid as any;\n const rowPool: HTMLElement[] | undefined = gridInternal._rowPool;\n const vStart: number = gridInternal._virtualization?.start ?? 0;\n const vEnd: number = gridInternal._virtualization?.end ?? 0;\n const columnCount = this.columns.length;\n\n // Build visible row index set from the virtual window range\n const visibleStart = vStart;\n const visibleEnd = vEnd;\n\n // Build a map of row index -> row element using the pool (O(n) where n = visible rows)\n const visibleRowMap = new Map<number, Element>();\n if (rowPool) {\n const poolLen = Math.min(rowPool.length, visibleEnd - visibleStart);\n for (let i = 0; i < poolLen; i++) {\n const rowEl = rowPool[i];\n if (rowEl.parentNode === body) {\n visibleRowMap.set(visibleStart + i, rowEl);\n }\n }\n } else {\n // Fallback: use querySelectorAll if pool is not accessible\n const dataRows = body.querySelectorAll('.data-grid-row');\n for (const rowEl of dataRows) {\n const firstCell = rowEl.querySelector('.cell[data-row]');\n const rowIndex = firstCell ? parseInt(firstCell.getAttribute('data-row') ?? '-1', 10) : -1;\n if (rowIndex >= 0) {\n visibleRowMap.set(rowIndex, rowEl);\n }\n }\n }\n\n // Remove detail rows whose parent row is no longer visible or no longer expanded.\n // Iterate the detailElements map (which we own) instead of querySelectorAll.\n for (const [row, detailEl] of this.detailElements) {\n const rowIndex = this.rows.indexOf(row);\n const isStillExpanded = this.expandedRows.has(row);\n const isRowVisible = rowIndex >= 0 && visibleRowMap.has(rowIndex);\n\n if (!isStillExpanded || !isRowVisible) {\n // Clean up framework adapter resources (React root, Vue app, Angular view)\n // before removing to prevent memory leaks.\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.unmount) {\n const detailCell = detailEl.querySelector('.master-detail-cell');\n const container = detailCell?.firstElementChild as HTMLElement | null;\n if (container) adapter.unmount(container);\n }\n if (detailEl.parentNode) detailEl.remove();\n this.detailElements.delete(row);\n }\n }\n\n // Insert detail rows for expanded rows that are visible. We also toggle\n // `.tbw-row-expanded` on every visible master row (matches Tree /\n // GroupingRows) so devs can style expanded rows via CSS instead of\n // depending on `[aria-expanded=\"true\"]` (which lives on the toggle\n // button, not the row). MUST clear on the negative branch \\u2014 the row\n // pool recycles elements as the virtual window slides.\n for (const [rowIndex, rowEl] of visibleRowMap) {\n const row = this.rows[rowIndex];\n if (!row) continue;\n const isExpanded = this.expandedRows.has(row);\n rowEl.classList.toggle('tbw-row-expanded', isExpanded);\n if (!isExpanded) continue;\n\n // Check if detail already exists for this row\n const existingDetail = this.detailElements.get(row);\n if (existingDetail) {\n // Ensure it's positioned correctly (as next sibling of row element)\n if (existingDetail.previousElementSibling !== rowEl) {\n rowEl.after(existingDetail);\n }\n continue;\n }\n\n // Create new detail element\n const detailEl = createDetailElement(row, rowIndex, this.config.detailRenderer, columnCount);\n\n if (typeof this.config.detailHeight === 'number') {\n detailEl.style.height = `${this.config.detailHeight}px`;\n }\n\n // Insert as sibling after the row element (not as child)\n rowEl.after(detailEl);\n this.detailElements.set(row, detailEl);\n\n // Only animate if this row was just expanded by a user action (click, keyboard, API).\n // Rows re-appearing from scroll (virtualization) should not re-animate.\n const shouldAnimate = this.rowsToAnimate.has(row);\n if (shouldAnimate) {\n this.rowsToAnimate.delete(row);\n }\n\n const willAnimate = shouldAnimate && this.animateExpand(detailEl, row, rowIndex);\n\n if (!willAnimate) {\n // No animation - measure height after layout settles via RAF\n requestAnimationFrame(() => {\n this.#measureAndCacheDetailHeight(detailEl, row, rowIndex);\n });\n }\n // When animating, measurement is deferred to animationend callback\n // (inside animateExpand) to avoid measuring during max-height: 0 constraint\n }\n }\n\n /**\n * Get the height of a specific row, including any expanded detail content.\n * Always returns a height to ensure the position cache uses plugin-controlled values\n * rather than stale DOM measurements.\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 (base height for collapsed, base + detail for expanded)\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n const isExpanded = this.expandedRows.has(row as object);\n\n if (!isExpanded) {\n // Collapsed row - return undefined to let the grid use its measured/estimated height.\n // This ensures the position cache uses the correct row height from CSS/config.\n return undefined;\n }\n\n // Row is expanded - return base height plus detail height\n // Use grid's defaultRowHeight which reflects the actual measured/configured height\n const baseHeight = this.grid.defaultRowHeight ?? 28;\n const detailHeight = this.getDetailHeight(row);\n\n return baseHeight + detailHeight;\n }\n\n /**\n * Adjust the virtualization start index to keep expanded row visible while its detail is visible.\n * This ensures the detail scrolls smoothly out of view instead of disappearing abruptly.\n */\n override adjustVirtualStart(start: number, scrollTop: number, rowHeight: number): number {\n if (this.expandedRows.size === 0) return start;\n\n // Use position cache for accurate row positions when available (variable heights mode)\n const positionCache = (this.grid as any)?._virtualization?.positionCache as\n | Array<{ offset: number; height: number }>\n | undefined;\n\n let minStart = start;\n\n if (positionCache && positionCache.length > 0) {\n // Variable heights: use position cache for accurate offset\n for (const row of this.expandedRows) {\n const rowIndex = this.rows.indexOf(row);\n if (rowIndex < 0 || rowIndex >= start) continue;\n\n // Position cache already includes cumulative heights from all expanded details\n const detailBottom = positionCache[rowIndex].offset + positionCache[rowIndex].height;\n\n if (detailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n } else {\n // Fixed heights fallback: accumulate detail heights manually\n // Build sorted list of expanded row indices for cumulative height calculation\n const expandedIndices: Array<{ index: number; row: any }> = [];\n for (const row of this.expandedRows) {\n const index = this.rows.indexOf(row);\n if (index >= 0) {\n expandedIndices.push({ index, row });\n }\n }\n expandedIndices.sort((a, b) => a.index - b.index);\n\n let cumulativeExtraHeight = 0;\n\n for (const { index: rowIndex, row } of expandedIndices) {\n const actualRowTop = rowIndex * rowHeight + cumulativeExtraHeight;\n const detailHeight = this.getDetailHeight(row);\n const actualDetailBottom = actualRowTop + rowHeight + detailHeight;\n\n cumulativeExtraHeight += detailHeight;\n\n if (rowIndex >= start) continue;\n\n if (actualDetailBottom > scrollTop && rowIndex < minStart) {\n minStart = rowIndex;\n }\n }\n }\n\n return minStart;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Expand the detail row at the given index.\n * @param rowIndex - Index of the row to expand\n */\n expand(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row && !row.__isGroupRow) {\n this.rowsToAnimate.add(row);\n this.expandedRows = expandDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Collapse the detail row at the given index.\n * @param rowIndex - Index of the row to collapse\n */\n collapse(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row) {\n this.expandedRows = collapseDetailRow(this.expandedRows, row);\n this.requestRender();\n }\n }\n\n /**\n * Toggle the detail row at the given index.\n * @param rowIndex - Index of the row to toggle\n */\n toggle(rowIndex: number): void {\n const row = this.rows[rowIndex];\n if (row && !row.__isGroupRow) {\n this.expandedRows = toggleDetailRow(this.expandedRows, row);\n if (this.expandedRows.has(row)) {\n this.rowsToAnimate.add(row);\n }\n this.requestRender();\n }\n }\n\n /**\n * Check if the detail row at the given index is expanded.\n * @param rowIndex - Index of the row to check\n * @returns Whether the detail row is expanded\n */\n isExpanded(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? isDetailExpanded(this.expandedRows, row) : false;\n }\n\n /**\n * Expand all detail rows.\n * Skips synthetic rows (e.g., group headers from GroupingRowsPlugin).\n */\n expandAll(): void {\n for (const row of this.rows) {\n if (row?.__isGroupRow) continue;\n this.rowsToAnimate.add(row);\n this.expandedRows.add(row);\n }\n this.requestRender();\n }\n\n /**\n * Collapse all detail rows.\n */\n collapseAll(): void {\n this.expandedRows.clear();\n this.requestRender();\n }\n\n /**\n * Get the indices of all expanded rows.\n * @returns Array of row indices that are expanded\n */\n getExpandedRows(): number[] {\n const indices: number[] = [];\n for (const row of this.expandedRows) {\n const idx = this.rows.indexOf(row);\n if (idx >= 0) indices.push(idx);\n }\n return indices;\n }\n\n /**\n * Get the detail element for a specific row.\n * @param rowIndex - Index of the row\n * @returns The detail HTMLElement or undefined\n */\n getDetailElement(rowIndex: number): HTMLElement | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailElements.get(row) : undefined;\n }\n\n /**\n * Get async detail data fetched via `ServerSidePlugin` for a specific row.\n *\n * Returns the child rows received from `datasource:children` after a\n * `datasource:fetch-children` query was fired on expand. Returns `undefined`\n * when ServerSide is not loaded or data has not arrived yet.\n *\n * @param rowIndex - Index of the row\n * @returns Array of child rows or undefined\n */\n getDetailData(rowIndex: number): unknown[] | undefined {\n const row = this.rows[rowIndex];\n return row ? this.detailDataMap.get(row) : undefined;\n }\n\n /**\n * Check if detail data is currently being loaded for a row.\n * @param rowIndex - Index of the row\n * @returns Whether the detail is loading\n */\n isDetailLoading(rowIndex: number): boolean {\n const row = this.rows[rowIndex];\n return row ? this.loadingDetails.has(row) : false;\n }\n\n /**\n * Re-parse light DOM to refresh the detail renderer.\n * Call this after framework templates are registered (e.g., Angular ngAfterContentInit).\n *\n * This allows frameworks to register templates asynchronously and then\n * update the plugin's detailRenderer.\n */\n refreshDetailRenderer(): void {\n // Force re-parse by temporarily clearing the renderer\n const currentRenderer = this.config.detailRenderer;\n this.config = { ...this.config, detailRenderer: undefined };\n this.parseLightDomDetail();\n\n // If no new renderer was found, restore the original\n if (!this.config.detailRenderer && currentRenderer) {\n this.config = { ...this.config, detailRenderer: currentRenderer };\n }\n\n // Request a COLUMNS phase re-render so processColumns runs again with the new detailRenderer\n // This ensures the expand toggle is added to the first column.\n // Must use refreshColumns() (COLUMNS phase) not requestRender() (ROWS phase)\n // because processColumns only runs at COLUMNS phase or higher.\n if (this.config.detailRenderer) {\n const grid = this.#internalGrid;\n if (typeof grid.refreshColumns === 'function') {\n grid.refreshColumns();\n } else {\n // Fallback to requestRender if refreshColumns not available\n this.requestRender();\n }\n }\n }\n // #endregion\n}\n"],"names":["toggleDetailRow","expandedRows","row","has","delete","add","createDetailElement","rowIndex","renderer","columnCount","detailRow","document","createElement","className","setAttribute","String","detailCell","style","gridColumn","content","innerHTML","HTMLElement","appendChild","MasterDetailPlugin","BaseGridPlugin","name","styles","static","required","reason","internalGrid","this","grid","defaultConfig","detailHeight","expandOnRowClick","collapseOnClickOutside","animation","attach","super","parseLightDomDetail","on","detail","d","context","source","claimed","detailDataMap","set","rows","loadingDetails","existingDetail","detailElements","get","remove","measuredDetailHeights","requestRender","gridEl","gridElement","detailEl","querySelector","adapter","__frameworkAdapter","parseDetailElement","adapterRenderer","config","detailRenderer","getAttribute","showExpandColumn","heightAttr","configUpdates","parseInt","templateHTML","trim","_rowIndex","evaluated","evalTemplateString","value","sanitizeHTML","Object","keys","length","animationStyle","isAnimationEnabled","animateExpand","classList","measured","measureOnce","measureAndCacheDetailHeight","addEventListener","once","setTimeout","animationDuration","animateCollapse","onComplete","cleanup","isConnected","height","offsetHeight","previousHeight","invalidateRowHeight","Set","Map","rowsToAnimate","getDetailHeight","contains","cachedHeight","DEFAULT_DETAIL_HEIGHT","toggleAndEmit","__isGroupRow","expanded","isServerSideActive","query","emit","detach","clear","processColumns","columns","cols","findExpanderColumn","expanderCol","createExpanderColumnConfig","viewRenderer","renderCtx","isExpanded","container","toggle","setIcon","onRowClick","event","onCellClick","target","originalEvent","size","queueMicrotask","syncDetailRows","onKeyDown","key","focusCol","_focusCol","focusRow","_focusRow","column","visibleColumns","isExpanderColumn","preventDefault","requestRenderWithFocus","afterRender","fixExpanderHeaderSpan","expanderHeader","colIdx","nextCell","nextElementSibling","onScrollRender","body","gridInternal","rowPool","_rowPool","vStart","_virtualization","start","vEnd","end","visibleStart","visibleEnd","visibleRowMap","poolLen","Math","min","i","rowEl","parentNode","dataRows","querySelectorAll","firstCell","indexOf","isStillExpanded","isRowVisible","unmount","firstElementChild","previousElementSibling","after","shouldAnimate","requestAnimationFrame","getRowHeight","_index","defaultRowHeight","adjustVirtualStart","scrollTop","rowHeight","positionCache","minStart","offset","expandedIndices","index","push","sort","a","b","cumulativeExtraHeight","actualRowTop","expand","expandDetailRow","collapse","collapseDetailRow","isDetailExpanded","expandAll","collapseAll","getExpandedRows","indices","idx","getDetailElement","getDetailData","isDetailLoading","refreshDetailRenderer","currentRenderer","refreshColumns"],"mappings":"sgBAaO,SAASA,EAAgBC,EAA2BC,GAMzD,OALID,EAAaE,IAAID,GACnBD,EAAaG,OAAOF,GAEpBD,EAAaI,IAAIH,GAEZD,CACT,CA+BO,SAASK,EACdJ,EACAK,EACAC,EACAC,GAEA,MAAMC,EAAYC,SAASC,cAAc,OACzCF,EAAUG,UAAY,oBACtBH,EAAUI,aAAa,kBAAmBC,OAAOR,IACjDG,EAAUI,aAAa,OAAQ,OAE/B,MAAME,EAAaL,SAASC,cAAc,OAC1CI,EAAWH,UAAY,qBACvBG,EAAWF,aAAa,OAAQ,QAChCE,EAAWC,MAAMC,WAAa,OAAOT,EAAc,IAEnD,MAAMU,EAAUX,EAASN,EAAKK,GAQ9B,MAPuB,iBAAZY,EACTH,EAAWI,UAAYD,EACdA,aAAmBE,aAC5BL,EAAWM,YAAYH,GAGzBT,EAAUY,YAAYN,GACfN,CACT,CCUO,MAAMa,UAA2BC,EAAAA,eAE7BC,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"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_stickyRows={},t.TbwGrid)}(this,function(t,e){"use strict";class i extends e.BaseGridPlugin{name="stickyRows";styles="@layer tbw-plugins{.tbw-sticky-rows{position:absolute;top:0;left:0;display:block;z-index:var(--tbw-z-layer-sticky-rows, 22);background:var(--tbw-color-bg, var(--tbw-color-panel-bg));min-width:100%;width:fit-content;overflow:visible}.tbw-sticky-rows:empty{display:none}.tbw-sticky-rows .tbw-sticky-row{box-shadow:0 1px 0 var(--tbw-color-border);background:var(--tbw-color-bg, var(--tbw-color-panel-bg))}.tbw-sticky-rows[data-mode=push] .tbw-sticky-row{will-change:transform}}";get defaultConfig(){return{mode:"push",maxStacked:1/0}}container=null;stickyIndices=[];cloneCache=new Map;displayedIndices=[];lastPushOffset=0;detach(){this.container?.remove(),this.container=null,this.cloneCache.clear(),this.stickyIndices=[],this.displayedIndices=[],this.lastPushOffset=0}afterRender(){this.recomputeStickyIndices(),this.ensureContainer(),this.primeCloneCache(),this.refreshDisplay()}onScrollRender(){this.primeCloneCache(),this.refreshClonesInWindow(),this.refreshDisplay()}onScroll(t){this.refreshDisplay(t.scrollTop)}resolvePredicate(){const t=this.config.isSticky;if("function"==typeof t)return t;if("string"==typeof t){const e=t;return t=>null!=t&&"object"==typeof t&&Boolean(t[e])}return()=>!1}recomputeStickyIndices(){const t=this.rows,e=this.resolvePredicate(),i=[];for(let s=0;s<t.length;s++)e(t[s],s)&&i.push(s);(i.length!==this.stickyIndices.length||i.some((t,e)=>t!==this.stickyIndices[e]))&&this.cloneCache.clear(),this.stickyIndices=i}ensureContainer(){const t=this.gridElement;if(!t)return;const e=t.querySelector(".rows-viewport");e?this.container&&e.contains(this.container)||(this.container=document.createElement("div"),this.container.className="tbw-sticky-rows",this.container.setAttribute("role","presentation"),this.container.dataset.mode=this.config.mode??"push",this.config.className&&this.container.classList.add(this.config.className),e.insertBefore(this.container,e.firstChild)):this.container=null}offsetOf(t){const e=this.getVirtualState(),i=e?.positionCache;if(i&&i[t])return i[t].offset;return t*(e?.rowHeight??28)}heightOf(t){const e=this.getVirtualState(),i=e?.positionCache;return i&&i[t]?i[t].height:e?.rowHeight??28}getVirtualState(){return this.grid?._virtualization}getCurrentScrollTop(){const t=this.getVirtualState(),e=t?.container?.scrollTop;return"number"==typeof e?e:"number"!=typeof t?.start||"number"!=typeof t?.rowHeight||t.positionCache&&t.positionCache.length?t?.positionCache&&"number"==typeof t.start&&t.positionCache[t.start]?t.positionCache[t.start].offset:0:t.start*t.rowHeight}computeDisplay(t){if("stack"===this.config.mode){const e=this.config.maxStacked??1/0,i=[];let s=0;for(const n of this.stickyIndices)if(i.length<e){if(!(this.offsetOf(n)<t+s))break;i.push(n),s+=this.heightOf(n)}else{const e=this.heightOf(i[0]);if(!(this.offsetOf(n)<t+s-e))break;i.shift(),s-=e,i.push(n),s+=this.heightOf(n)}if(i.length===e&&i.length>0){const e=this.findNextSticky(i[i.length-1]);if(null!=e){const n=this.offsetOf(e)-(t+s);if(n<0){const t=this.heightOf(i[0]);return{indices:i,pushOffset:Math.min(-n,t)}}}}return{indices:i,pushOffset:0}}const e=[];for(const o of this.stickyIndices){if(!(this.offsetOf(o)<t))break;e.push(o)}if(0===e.length)return{indices:e,pushOffset:0};const i=e[e.length-1],s=this.findNextSticky(i);let n=0;if(null!=s){const e=this.heightOf(i),o=this.offsetOf(s)-t;o<e&&(n=e-Math.max(0,o))}return{indices:[i],pushOffset:n}}findRenderedRow(t){const e=this.gridElement;if(!e)return null;const i=e.querySelector(`.rows .data-grid-row .cell[data-row="${t}"]`);return i?.parentElement??null}buildClone(t){const e=this.findRenderedRow(t);if(!e)return this.cloneCache.get(t)??null;const i=e.cloneNode(!0);return i.classList.add("tbw-sticky-row"),i.removeAttribute("aria-rowindex"),i.setAttribute("aria-hidden","true"),i.dataset.stickyRow=String(t),i.classList.remove("row-focus","cell-focus"),i.querySelectorAll(".cell-focus, .row-focus").forEach(t=>t.classList.remove("cell-focus","row-focus")),i.removeAttribute("tabindex"),i.querySelectorAll("[tabindex]").forEach(t=>t.removeAttribute("tabindex")),this.cloneCache.set(t,i),i}refreshClonesInWindow(){if(this.displayedIndices.length)for(const t of this.displayedIndices){if(this.findRenderedRow(t)){const e=this.buildClone(t),i=this.container?.querySelector(`[data-sticky-row="${t}"]`);e&&i&&i!==e&&i.replaceWith(e)}}}primeCloneCache(){if(this.stickyIndices.length)for(const t of this.stickyIndices)this.findRenderedRow(t)&&this.buildClone(t)}refreshDisplay(t){if(!this.container)return;const e=t??this.getCurrentScrollTop(),{indices:i,pushOffset:s}=this.computeDisplay(e);this.container.dataset.mode!==this.config.mode&&(this.container.dataset.mode=this.config.mode??"push");if(!(i.length===this.displayedIndices.length&&i.every((t,e)=>t===this.displayedIndices[e]))){const t=document.createDocumentFragment(),e=[];for(const s of i){let i=this.cloneCache.get(s)??null;i=this.buildClone(s)??i,i&&(t.appendChild(i),e.push(s))}this.container.replaceChildren(t),this.displayedIndices=e}s!==this.lastPushOffset&&(this.container.style.transform=s>0?`translateY(${-s}px)`:"",this.lastPushOffset=s)}findNextSticky(t){for(const e of this.stickyIndices)if(e>t)return e;return null}}t.StickyRowsPlugin=i,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
2
+ //# sourceMappingURL=sticky-rows.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sticky-rows.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/sticky-rows/StickyRowsPlugin.ts"],"sourcesContent":["/**\n * Sticky Rows Plugin (Class-based)\n *\n * Pins selected data rows below the header as the user scrolls past them.\n * See `types.ts` for configuration.\n *\n * @module Plugins/Sticky Rows\n */\n\nimport type { RowPosition } from '../../core/internal/virtualization';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ScrollEvent } from '../../core/plugin/types';\nimport styles from './sticky-rows.css?inline';\nimport type { StickyPredicate, StickyRowsConfig } from './types';\n\n/** Internal shape of the virtualization state we read from the grid. */\ninterface VirtualStateLike {\n start?: number;\n end?: number;\n rowHeight?: number;\n positionCache?: RowPosition[] | null;\n /** The faux-scroll element — the source of truth for the live scroll\n * position (per-pixel, unlike `start` which only updates when the\n * rendered window shifts). */\n container?: HTMLElement | null;\n}\n\n/**\n * Sticky Rows plugin for `<tbw-grid>`.\n *\n * Marks specific rows as \"sticky\" so they pin below the grid header when their\n * natural scroll position would take them off-screen. Behavior when multiple\n * sticky rows would be stuck simultaneously is controlled by `mode`:\n *\n * - `'push'` (default) — only one stuck at a time; the next sticky row pushes\n * the previous one out of view (iOS section-header behavior).\n * - `'stack'` — sticky rows stack below the header up to `maxStacked`.\n *\n * The plugin renders **clones** of the real rows; the originals continue to\n * exist in the data flow. Clones inherit the row's grid-template alignment so\n * they line up perfectly with the column boundaries below.\n *\n * @example\n * ```ts\n * import '@toolbox-web/grid/features/sticky-rows';\n *\n * grid.gridConfig = {\n * features: { stickyRows: { isSticky: 'isSection', mode: 'stack' } },\n * };\n * ```\n *\n * @see {@link StickyRowsConfig} for all configuration options.\n *\n * @internal Extends BaseGridPlugin.\n */\nexport class StickyRowsPlugin extends BaseGridPlugin<StickyRowsConfig> {\n /** @internal */\n readonly name = 'stickyRows';\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<StickyRowsConfig> {\n return {\n mode: 'push',\n maxStacked: Infinity,\n };\n }\n\n // #region Internal State\n /** Container element that holds the stuck-row clones. */\n private container: HTMLElement | null = null;\n\n /** Indices in `grid.rows` whose rows are sticky, sorted ascending. */\n private stickyIndices: number[] = [];\n\n /** Cached clone DOM keyed by row index. Survives the row leaving the\n * virtualization window so we can keep showing it while stuck. */\n private cloneCache: Map<number, HTMLElement> = new Map();\n\n /** Currently displayed indices (in DOM order). Used to skip work when the\n * set hasn't changed between scroll ticks. */\n private displayedIndices: number[] = [];\n\n /** Last applied push-mode translation, to skip writes on no-op ticks. */\n private lastPushOffset = 0;\n // #endregion\n\n // #region Lifecycle\n /** @internal */\n override detach(): void {\n this.container?.remove();\n this.container = null;\n this.cloneCache.clear();\n this.stickyIndices = [];\n this.displayedIndices = [];\n this.lastPushOffset = 0;\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal Recompute the sticky-index list and refresh display. */\n override afterRender(): void {\n this.recomputeStickyIndices();\n this.ensureContainer();\n // Pre-cache clones for any sticky row currently in the rendered window\n // BEFORE it scrolls out — otherwise findRenderedRow() returns null at\n // display time and we'd render an empty container.\n this.primeCloneCache();\n this.refreshDisplay();\n }\n\n /** @internal Re-render clones after a scroll-driven row pool refresh. */\n override onScrollRender(): void {\n // The pool may have repopulated rows we're tracking. Refresh clone DOM\n // for any displayed indices that are now back in the rendered window,\n // and pre-cache any sticky rows that just entered the window so we have\n // a clone ready when they scroll past.\n this.primeCloneCache();\n this.refreshClonesInWindow();\n this.refreshDisplay();\n }\n\n /** @internal Update which clones show / how they're positioned. */\n override onScroll(event: ScrollEvent): void {\n this.refreshDisplay(event.scrollTop);\n }\n\n // #endregion\n\n // #region Private — predicate + indices\n\n private resolvePredicate(): StickyPredicate {\n const cfg = this.config.isSticky;\n if (typeof cfg === 'function') return cfg;\n if (typeof cfg === 'string') {\n const field = cfg;\n return (row) => {\n if (row == null || typeof row !== 'object') return false;\n return Boolean((row as Record<string, unknown>)[field]);\n };\n }\n return () => false;\n }\n\n private recomputeStickyIndices(): void {\n const rows = this.rows;\n const predicate = this.resolvePredicate();\n const next: number[] = [];\n for (let i = 0; i < rows.length; i++) {\n if (predicate(rows[i], i)) next.push(i);\n }\n // Drop cache entries whose indices are no longer sticky (e.g. data\n // shuffled, predicate flipped). Indices that remain may still point at a\n // different row after re-sort — drop those too so we re-clone from the\n // fresh DOM on the next render.\n if (next.length !== this.stickyIndices.length || next.some((v, i) => v !== this.stickyIndices[i])) {\n this.cloneCache.clear();\n }\n this.stickyIndices = next;\n }\n\n // #endregion\n\n // #region Private — DOM container\n\n private ensureContainer(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Container is an OVERLAY positioned at the top of the rows-viewport\n // (not a flex child of rows-body). Why: a flow-positioned container\n // takes vertical space, which pushes the rows-viewport down by the\n // sticky height. The rows are positioned in scroll coordinates that\n // are agnostic of that shift, so live-row geometry ends up partially\n // overlapping the sticky container — producing duplicate visible rows\n // during the push transition (#279 follow-up). Overlaying on top of\n // the row pool, with `overflow: clip` on rows-viewport hiding the\n // live row underneath, eliminates the overlap entirely.\n const rowsViewport = grid.querySelector('.rows-viewport');\n if (!rowsViewport) {\n // Grid hasn't built its DOM yet; bail and try again on next afterRender.\n this.container = null;\n return;\n }\n\n if (this.container && rowsViewport.contains(this.container)) return;\n\n // Container was either never created or got wiped out. Re-create.\n this.container = document.createElement('div');\n this.container.className = 'tbw-sticky-rows';\n this.container.setAttribute('role', 'presentation');\n this.container.dataset['mode'] = this.config.mode ?? 'push';\n if (this.config.className) this.container.classList.add(this.config.className);\n\n // Insert as the FIRST child of rows-viewport so it overlays on top of\n // the row pool. Z-index in CSS keeps it above `.rows`.\n rowsViewport.insertBefore(this.container, rowsViewport.firstChild);\n }\n\n // #endregion\n\n // #region Private — offsets + which-to-display\n\n /** Pixel offset of the top of `index` from the start of the scroll area. */\n private offsetOf(index: number): number {\n const v = this.getVirtualState();\n const cache = v?.positionCache;\n if (cache && cache[index]) return cache[index].offset;\n const h = v?.rowHeight ?? 28;\n return index * h;\n }\n\n /** Estimated height of `index` (used for push-mode displacement). */\n private heightOf(index: number): number {\n const v = this.getVirtualState();\n const cache = v?.positionCache;\n if (cache && cache[index]) return cache[index].height;\n return v?.rowHeight ?? 28;\n }\n\n private getVirtualState(): VirtualStateLike | undefined {\n return (this.grid as unknown as { _virtualization?: VirtualStateLike })?._virtualization;\n }\n\n private getCurrentScrollTop(): number {\n const v = this.getVirtualState();\n // PRIMARY source: the live `scrollTop` of the faux-scroll element. This\n // updates per-pixel as the user drags, unlike `_virtualization.start`\n // which only ticks over when the rendered window shifts (every\n // `rowHeight` px). Reading the stale start-derived value caused\n // `afterRender` to clobber the correct displayed-set that `onScroll`\n // had just computed (#279 follow-up).\n const liveScrollTop = v?.container?.scrollTop;\n if (typeof liveScrollTop === 'number') return liveScrollTop;\n // Fallbacks (unit tests / pre-mount): derive from window-start.\n if (\n typeof v?.start === 'number' &&\n typeof v?.rowHeight === 'number' &&\n (!v.positionCache || !v.positionCache.length)\n ) {\n return v.start * v.rowHeight;\n }\n if (v?.positionCache && typeof v.start === 'number' && v.positionCache[v.start]) {\n return v.positionCache[v.start].offset;\n }\n return 0;\n }\n\n /**\n * Compute the displayed sticky indices and any upward push offset, given\n * the current scroll offset.\n *\n * - `'push'` mode: a row qualifies once its top has scrolled past the\n * viewport top (strict `<`); only the highest qualifying index is\n * shown. As the next sticky approaches from below, the stuck clone\n * slides upward by `heightOfStuck - distance` (iOS section-header\n * behavior).\n * - `'stack'` mode: each subsequent sticky qualifies once its top\n * reaches the bottom of the existing stack (`offsetOf(idx) < scrollTop\n * + cumulativeHeightOfStuck`), so `— B —` latches when it meets\n * `— A —`'s bottom — not after `— A —` covers it. When the stack is\n * at `maxStacked` and the **live** next sticky row's top crosses the\n * bottom of the stack (`distance <= 0`), the entire stack translates\n * upward by `-distance`. Live rows above the stack (including the\n * incoming sticky) scroll up naturally beneath the overlay; rows-\n * viewport's `overflow: clip` hides anything above the top edge. When\n * the oldest is fully off (pushOffset ≥ heightOf(oldest)), the next\n * tick qualifies the new sticky and we slice to `last max` with\n * transform reset — at that exact pixel the live new sticky is sitting\n * precisely behind its slot in the new stack, producing a seamless\n * swap with no duplicate row visible.\n *\n * Strict `<` keeps the qualification edge symmetric with push mode and\n * avoids briefly rendering both a clone and the live row at the swap\n * pixel.\n */\n private computeDisplay(scrollTop: number): { indices: number[]; pushOffset: number } {\n if (this.config.mode === 'stack') {\n const max = this.config.maxStacked ?? Infinity;\n const qualifying: number[] = [];\n let stuckHeight = 0;\n for (const idx of this.stickyIndices) {\n if (qualifying.length < max) {\n // Within the cap: a sticky qualifies once its top reaches the\n // bottom of the existing stack.\n if (this.offsetOf(idx) < scrollTop + stuckHeight) {\n qualifying.push(idx);\n stuckHeight += this.heightOf(idx);\n } else {\n break; // sorted ascending — anything after won't qualify either\n }\n } else {\n // At cap: evict-and-promote only after `idx` has fully crossed\n // the slot of the current oldest. WHY: while `idx` is mid-cross\n // (its top is past the stack bottom but the oldest isn't yet\n // off the top), we want to ANIMATE that transition by sliding\n // the existing stack upward — not snap to the post-evict state.\n // Without this clamp, qualification fires the instant the new\n // sticky crosses the stack bottom (same scrollTop where the\n // anticipation block would otherwise activate), and the\n // anticipation never gets a chance to render.\n const oldestH = this.heightOf(qualifying[0]);\n if (this.offsetOf(idx) < scrollTop + stuckHeight - oldestH) {\n qualifying.shift();\n stuckHeight -= oldestH;\n qualifying.push(idx);\n stuckHeight += this.heightOf(idx);\n } else {\n break;\n }\n }\n }\n\n // Anticipation: at-cap and the live next sticky has crossed the\n // stack bottom but not yet fully past the oldest's slot. Translate\n // the entire stack up by `-distance` so the user sees the live\n // next-sticky scrolling up against the bottom of the stack while\n // the oldest slides off the top — exactly mirroring iOS Contacts.\n // Do NOT add the new sticky to the displayed list during this\n // window: it's still in the row pool and visible there. Adding a\n // clone too would produce a visible duplicate AND would cover the\n // last regular row under the previous section while live-next is\n // still approaching.\n if (qualifying.length === max && qualifying.length > 0) {\n const next = this.findNextSticky(qualifying[qualifying.length - 1]);\n if (next != null) {\n const distance = this.offsetOf(next) - (scrollTop + stuckHeight);\n if (distance < 0) {\n const oldestH = this.heightOf(qualifying[0]);\n return { indices: qualifying, pushOffset: Math.min(-distance, oldestH) };\n }\n }\n }\n return { indices: qualifying, pushOffset: 0 };\n }\n\n // 'push' mode.\n const qualifying: number[] = [];\n for (const idx of this.stickyIndices) {\n if (this.offsetOf(idx) < scrollTop) qualifying.push(idx);\n else break;\n }\n if (qualifying.length === 0) return { indices: qualifying, pushOffset: 0 };\n const stuck = qualifying[qualifying.length - 1];\n const next = this.findNextSticky(stuck);\n let pushOffset = 0;\n if (next != null) {\n const stuckH = this.heightOf(stuck);\n const distance = this.offsetOf(next) - scrollTop;\n if (distance < stuckH) {\n pushOffset = stuckH - Math.max(0, distance);\n }\n }\n return { indices: [stuck], pushOffset };\n }\n\n // #endregion\n\n // #region Private — clone management\n\n /** Locate a rendered row in the viewport by its data index. */\n private findRenderedRow(index: number): HTMLElement | null {\n const grid = this.gridElement;\n if (!grid) return null;\n // Cells carry `data-row=\"<index>\"`. The row element is the parent.\n const cell = grid.querySelector(`.rows .data-grid-row .cell[data-row=\"${index}\"]`);\n return (cell?.parentElement as HTMLElement | null) ?? null;\n }\n\n /** Build (or refresh) a clone for `index`, using the live row when present. */\n private buildClone(index: number): HTMLElement | null {\n const live = this.findRenderedRow(index);\n if (!live) return this.cloneCache.get(index) ?? null;\n const clone = live.cloneNode(true) as HTMLElement;\n clone.classList.add('tbw-sticky-row');\n clone.removeAttribute('aria-rowindex');\n // Stuck clones are decorative — the original row is still present in the\n // accessibility tree below. Hide clones from AT to avoid double-reads.\n clone.setAttribute('aria-hidden', 'true');\n clone.dataset['stickyRow'] = String(index);\n // Drop any focus styling from the source — clones are non-interactive.\n clone.classList.remove('row-focus', 'cell-focus');\n clone.querySelectorAll('.cell-focus, .row-focus').forEach((el) => el.classList.remove('cell-focus', 'row-focus'));\n // Strip tabindex on cells so the clone isn't a tab target.\n clone.removeAttribute('tabindex');\n clone.querySelectorAll('[tabindex]').forEach((el) => el.removeAttribute('tabindex'));\n\n this.cloneCache.set(index, clone);\n return clone;\n }\n\n /** Refresh cached clones for any displayed indices that are now in-window.\n * Pulls fresh DOM so edits / re-renders are reflected when the row swings\n * back into view. */\n private refreshClonesInWindow(): void {\n if (!this.displayedIndices.length) return;\n for (const idx of this.displayedIndices) {\n const live = this.findRenderedRow(idx);\n if (live) {\n // Re-clone to pick up any post-render changes.\n const fresh = this.buildClone(idx);\n const existingClone = this.container?.querySelector(`[data-sticky-row=\"${idx}\"]`);\n if (fresh && existingClone && existingClone !== fresh) {\n existingClone.replaceWith(fresh);\n }\n }\n }\n }\n\n /** Build clones for any sticky row currently rendered in the viewport so we\n * have one ready when the row scrolls past. Without this, a sticky row\n * that's never been displayed-as-stuck won't have a cache entry, and once\n * the live row leaves the rendered window we have nothing to render. */\n private primeCloneCache(): void {\n if (!this.stickyIndices.length) return;\n for (const idx of this.stickyIndices) {\n if (this.findRenderedRow(idx)) {\n // buildClone() handles the live → cache path itself.\n this.buildClone(idx);\n }\n }\n }\n\n /** Reconcile the container DOM with the desired displayed indices. */\n private refreshDisplay(scrollTopOverride?: number): void {\n if (!this.container) return;\n\n const scrollTop = scrollTopOverride ?? this.getCurrentScrollTop();\n const { indices: desired, pushOffset } = this.computeDisplay(scrollTop);\n\n // Update the container's mode marker (in case config changed).\n if (this.container.dataset['mode'] !== this.config.mode) {\n this.container.dataset['mode'] = this.config.mode ?? 'push';\n }\n\n const sameSet =\n desired.length === this.displayedIndices.length && desired.every((v, i) => v === this.displayedIndices[i]);\n\n if (!sameSet) {\n // Rebuild the container's children. cloneCache survives between calls so\n // we re-use existing clones for indices that remain displayed.\n const fragment = document.createDocumentFragment();\n const appended: number[] = [];\n for (const idx of desired) {\n let clone = this.cloneCache.get(idx) ?? null;\n // Always try to refresh from live DOM if available.\n const fresh = this.buildClone(idx);\n clone = fresh ?? clone;\n if (clone) {\n fragment.appendChild(clone);\n appended.push(idx);\n }\n }\n this.container.replaceChildren(fragment);\n // Track only the indices we actually appended so a subsequent refresh\n // (after a missing index gets primed via onScrollRender) will detect a\n // diff and retry rather than incorrectly believing the set is settled.\n this.displayedIndices = appended;\n }\n\n // Apply the upward translation to the entire container so push-mode\n // (1 child) and stack-mode anticipation (max+1 children) both slide\n // uniformly. CSS `overflow: clip` on `.rows-viewport` hides anything\n // translated above its top edge.\n if (pushOffset !== this.lastPushOffset) {\n this.container.style.transform = pushOffset > 0 ? `translateY(${-pushOffset}px)` : '';\n this.lastPushOffset = pushOffset;\n }\n }\n\n /** Find the next sticky index strictly greater than `current`. */\n private findNextSticky(current: number): number | null {\n for (const idx of this.stickyIndices) {\n if (idx > current) return idx;\n }\n return null;\n }\n\n // #endregion\n}\n"],"names":["StickyRowsPlugin","BaseGridPlugin","name","styles","defaultConfig","mode","maxStacked","Infinity","container","stickyIndices","cloneCache","Map","displayedIndices","lastPushOffset","detach","this","remove","clear","afterRender","recomputeStickyIndices","ensureContainer","primeCloneCache","refreshDisplay","onScrollRender","refreshClonesInWindow","onScroll","event","scrollTop","resolvePredicate","cfg","config","isSticky","field","row","Boolean","rows","predicate","next","i","length","push","some","v","grid","gridElement","rowsViewport","querySelector","contains","document","createElement","className","setAttribute","dataset","classList","add","insertBefore","firstChild","offsetOf","index","getVirtualState","cache","positionCache","offset","rowHeight","heightOf","height","_virtualization","getCurrentScrollTop","liveScrollTop","start","computeDisplay","max","qualifying","stuckHeight","idx","oldestH","shift","findNextSticky","distance","indices","pushOffset","Math","min","stuck","stuckH","findRenderedRow","cell","parentElement","buildClone","live","get","clone","cloneNode","removeAttribute","String","querySelectorAll","forEach","el","set","fresh","existingClone","replaceWith","scrollTopOverride","desired","every","fragment","createDocumentFragment","appended","appendChild","replaceChildren","style","transform","current"],"mappings":"oVAuDO,MAAMA,UAAyBC,EAAAA,eAE3BC,KAAO,aAEEC,oeAGlB,iBAAuBC,GACrB,MAAO,CACLC,KAAM,OACNC,WAAYC,IAEhB,CAIQC,UAAgC,KAGhCC,cAA0B,GAI1BC,eAA2CC,IAI3CC,iBAA6B,GAG7BC,eAAiB,EAKhB,MAAAC,GACPC,KAAKP,WAAWQ,SAChBD,KAAKP,UAAY,KACjBO,KAAKL,WAAWO,QAChBF,KAAKN,cAAgB,GACrBM,KAAKH,iBAAmB,GACxBG,KAAKF,eAAiB,CACxB,CAMS,WAAAK,GACPH,KAAKI,yBACLJ,KAAKK,kBAILL,KAAKM,kBACLN,KAAKO,gBACP,CAGS,cAAAC,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AAS,CACzB,IAAIZ,EAAQ5E,KAAKL,WAAWgF,IAAIhB,IAAQ,KAGxCiB,EADc5E,KAAKyE,WAAWd,IACbiB,EACbA,IACFc,EAASG,YAAYjB,GACrBgB,EAASnE,KAAKkC,GAElB,CACA3D,KAAKP,UAAUqG,gBAAgBJ,GAI/B1F,KAAKH,iBAAmB+F,CAC1B,CAMI3B,IAAejE,KAAKF,iBACtBE,KAAKP,UAAUsG,MAAMC,UAAY/B,EAAa,EAAI,eAAeA,OAAkB,GACnFjE,KAAKF,eAAiBmE,EAE1B,CAGQ,cAAAH,CAAemC,GACrB,IAAA,MAAWtC,KAAO3D,KAAKN,cACrB,GAAIiE,EAAMsC,EAAS,OAAOtC,EAE5B,OAAO,IACT"}
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/internal/sorting"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/sorting","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_tree={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,n,i){"use strict";function r(e,t,n){return void 0!==e.id?String(e.id):n?`${n}-${t}`:String(t)}function s(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function a(e,t,n=null,i=0){const s=t.childrenField??"children",o=new Set;for(let d=0;d<e.length;d++){const l=e[d],h=r(l,d,n),c=l[s];if(Array.isArray(c)&&c.length>0){o.add(h);const e=a(c,t,h,i+1);for(const t of e)o.add(t)}}return o}function o(e,t,n,i=null,s=0){const a=n.childrenField??"children";for(let d=0;d<e.length;d++){const l=e[d],h=r(l,d,i);if(h===t)return[h];const c=l[a];if(Array.isArray(c)&&c.length>0){const e=o(c,t,n,h,s+1);if(e)return[h,...e]}}return null}function d(e,t,n,i){const r=o(e,t,n);if(!r)return i;const s=new Set(i);for(let a=0;a<r.length-1;a++)s.add(r[a]);return s}function l(e,t){const n=Math.min(t,e.length-1);if(n<0)return 0;let i=n;for(;i>0&&e[i].depth>0;)i--;let r=0;for(let s=0;s<=i;s++)0===e[s].depth&&r++;return r-1}function h(e,t="children"){if(!Array.isArray(e)||0===e.length)return!1;for(const n of e){if(!n)continue;const e=n[t];if(Array.isArray(e)&&e.length>0)return!0;if(null!=e&&!Array.isArray(e)&&e)return!0}return!1}class c extends i.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10},incompatibleWith:[{name:"groupingRows",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin replaces the entire row and column structure with aggregated pivot data. Tree hierarchy cannot coexist with pivot aggregation."}],events:[{type:"tree-expand",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus."}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level node indices for ServerSide pagination."}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated tree sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded tree data"}];name="tree";styles='@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-inline-end:none!important;padding:0;display:flex;align-items:center;justify-content:flex-start}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .tree-cell-wrapper{display:inline-flex;align-items:center;vertical-align:middle;overflow:visible;padding-inline-start:calc(var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em)))}tbw-grid .tree-expander{display:flex;align-items:center;justify-content:flex-start;width:100%;height:100%;box-sizing:border-box}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);flex-shrink:0}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);display:inline-block;flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}tbw-grid.tbw-tree-loading .rows-viewport:after{content:"";display:block;height:2px;background:linear-gradient(90deg,transparent,var(--tbw-color-accent, #2563eb),transparent);animation:tbw-tree-loading-bar 1s ease-in-out infinite;position:sticky;bottom:0;left:0;right:0}@keyframes tbw-tree-loading-bar{0%{transform:translate(-100%)}to{transform:translate(100%)}}}';get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;loadingKeys=new Set;#e=new WeakMap;#t=new WeakMap;originalTreeColumnRenderer;wrappedTreeColumnField;detach(){this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null,this.loadingKeys.clear(),this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,n=this.config.childrenField??"children",i=t?.[n];if(Array.isArray(i)&&i.length>0)return!1}if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:n}=e.context;if(0===this.flattenedRows.length)return;return{startNode:l(this.flattenedRows,t),endNode:l(this.flattenedRows,n)+1,totalLoadedNodes:function(e){let t=0;for(const n of e)0===n.depth&&t++;return t}(this.flattenedRows)}}}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0)}),this.on("datasource:children",e=>{const t=e;if("tree"!==t.context?.source)return;t.claimed=!0;const n=t.context.parentNode;if(n){n[this.config.childrenField??"children"]=t.rows;const e=this.#e.get(n)??String(n.id??"?");this.loadingKeys.delete(e),this.requestRender()}})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,n=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const n of e)if(n&&"object"==typeof n)for(const e of t){const t=n[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return h(t,n)}processRows(e){const t=this.config.childrenField??"children",n=e;if(0===n.length||!h(n,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];const i=this.resolveEffectiveSortState();this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=a(n,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.#n(n,this.expandedKeys,i,null,0),this.#t=new WeakMap,this.rowKeyMap.clear(),this.keysToAnimate.clear();const r=new Set;for(const s of this.flattenedRows)this.rowKeyMap.set(s.key,s),this.#t.set(s.data,s),r.add(s.key),!this.previousVisibleKeys.has(s.key)&&s.depth>0&&this.keysToAnimate.add(s.key);return this.previousVisibleKeys=r,this.flattenedRows.map(e=>e.data)}#i(e,t,n){if(void 0!==e.id){const t=String(e.id);return this.#e.set(e,t),t}const i=this.#e.get(e);if(void 0!==i)return i;const r=n?`${n}-${t}`:String(t);return this.#e.set(e,r),r}#n(e,t,n,i,r){const s=this.config.childrenField??"children";for(let d=0;d<e.length;d++)this.#i(e[d],d,i);const a=n?this.#r(e,n.field,n.direction):e,o=[];for(let d=0;d<a.length;d++){const e=a[d],l=this.#i(e,d,i),h=e[s],c=Array.isArray(h)&&h.length>0,p=null!=h&&!Array.isArray(h)&&!!h,u=c||p,f=t.has(l);o.push({key:l,data:e,depth:r,hasChildren:u,isExpanded:f,parentKey:i}),c&&f&&o.push(...this.#n(h,t,n,l,r+1))}return o}#r(e,t,i){const r=this.grid,s=r?._columns??[],a={field:t,direction:i},o=[...e],d=(r?.effectiveConfig?.sortHandler??n.builtInSort)(o,a,s);return d&&"function"==typeof d.then?(d.catch(()=>{}),n.builtInSort(o,a,s)):d}requestLazyChildren(e){if(this.loadingKeys.has(e.key))return;const t=this.config.childrenField??"children",n=e.data[t];if(Array.isArray(n)&&n.length>0)return;const i=this.grid?.query?.("datasource:is-active",null);i&&(this.loadingKeys.add(e.key),this.grid.query("datasource:fetch-children",{context:{source:"tree",parentNode:e.data,nodePath:[e.key]}}))}resolveEffectiveSortState(){const e=this.grid?.query?.("sort:get-model",null);if(Array.isArray(e)&&e.length>0){const t=e[0];if(Array.isArray(t)&&t.length>0)return{field:t[0].field,direction:"desc"===t[0].direction?-1:1}}return this.sortState}processColumns(e){if(0===this.flattenedRows.length)return[...e];const n=[...e];if(0===n.length)return n;const{treeColumn:i}=this.config;let r=0;if(i){const e=n.findIndex(e=>e.field===i);e>=0&&(r=e)}const s=n[r],a=s.field;this.wrappedTreeColumnField!==a&&(this.originalTreeColumnRenderer=s.viewRenderer,this.wrappedTreeColumnField=a);const o=this.originalTreeColumnRenderer,d=()=>this.config,l=this.setIcon.bind(this);return n[r]={...s,viewRenderer:e=>{const{row:n,value:i}=e,{showExpandIcons:r=!0,indentWidth:s}=d(),a=this.#t.get(n),h=a?.depth??0,c=document.createElement("span");if(c.className="tree-cell-wrapper",c.style.setProperty("--tbw-tree-depth",String(h)),void 0!==s&&c.style.setProperty("--tbw-tree-indent-width",`${s}px`),r)if(a&&a.hasChildren){const e=document.createElement("span");e.className=`${t.GridClasses.TREE_TOGGLE}${a.isExpanded?` ${t.GridClasses.EXPANDED}`:""}`,l(e,a.isExpanded?"collapse":"expand"),e.setAttribute("data-tree-key",a.key),c.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",c.appendChild(e)}const p=document.createElement("span");if(p.className="tree-content",o){const t=o(e);t instanceof Node?p.appendChild(t):"string"==typeof t&&(p.innerHTML=t)}else p.textContent=null!=i?String(i):"";return c.appendChild(p),c}},n}onCellClick(e){const n=e.originalEvent?.target;if(!n?.classList.contains(t.GridClasses.TREE_TOGGLE))return!1;const i=n.getAttribute("data-tree-key");if(!i)return!1;const r=this.rowKeyMap.get(i);return!!r&&(this.expandedKeys=s(this.expandedKeys,i),this.expandedKeys.has(i)&&this.requestLazyChildren(r),this.broadcast("tree-expand",{key:i,row:r.data,expanded:this.expandedKeys.has(i),depth:r.depth,expandedKeys:[...this.expandedKeys]}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,n=this.flattenedRows[t];return n?.hasChildren?(e.preventDefault(),this.expandedKeys=s(this.expandedKeys,n.key),this.expandedKeys.has(n.key)&&this.requestLazyChildren(n),this.broadcast("tree-expand",{key:n.key,row:n.data,expanded:this.expandedKeys.has(n.key),depth:n.depth,expandedKeys:[...this.expandedKeys]}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0)return!1;const{field:n}=e.column;this.sortState&&this.sortState.field===n?1===this.sortState.direction?this.sortState={field:n,direction:-1}:this.sortState=null:this.sortState={field:n,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.broadcast("sort-change",{field:n,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.gridElement?.querySelector(".rows");if(!e)return;const t=this.animationStyle,n=!1!==t&&this.keysToAnimate.size>0,i="fade"===t?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const r of e.querySelectorAll(".data-grid-row")){const e=r.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,s=this.flattenedRows[t];s?.hasChildren&&r.setAttribute("aria-expanded",String(s.isExpanded)),n&&s?.key&&this.keysToAnimate.has(s.key)&&(r.classList.add(i),r.addEventListener("animationend",()=>r.classList.remove(i),{once:!0}))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e);const t=this.rowKeyMap.get(e);t&&this.requestLazyChildren(t),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=s(this.expandedKeys,e);const t=this.rowKeyMap.get(e);t?(this.expandedKeys.has(e)&&this.requestLazyChildren(t),this.broadcast("tree-expand",{key:e,row:t.data,expanded:this.expandedKeys.has(e),depth:t.depth,expandedKeys:[...this.expandedKeys]})):this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=a(this.rows,this.config),this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowMeta(e){return this.#t.get(e)}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=d(this.rows,e,this.config,this.expandedKeys),this.requestRender()}}e.TreePlugin=c,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/internal/sorting"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/internal/sorting","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_tree={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,r,i){"use strict";function n(e,t,r){return void 0!==e.id?String(e.id):r?`${r}-${t}`:String(t)}function s(e,t){const r=new Set(e);return r.has(t)?r.delete(t):r.add(t),r}function a(e,t,r=null,i=0){const s=t.childrenField??"children",o=new Set;for(let d=0;d<e.length;d++){const l=e[d],h=n(l,d,r),c=l[s];if(Array.isArray(c)&&c.length>0){o.add(h);const e=a(c,t,h,i+1);for(const t of e)o.add(t)}}return o}function o(e,t,r,i=null,s=0){const a=r.childrenField??"children";for(let d=0;d<e.length;d++){const l=e[d],h=n(l,d,i);if(h===t)return[h];const c=l[a];if(Array.isArray(c)&&c.length>0){const e=o(c,t,r,h,s+1);if(e)return[h,...e]}}return null}function d(e,t,r,i){const n=o(e,t,r);if(!n)return i;const s=new Set(i);for(let a=0;a<n.length-1;a++)s.add(n[a]);return s}function l(e,t){const r=Math.min(t,e.length-1);if(r<0)return 0;let i=r;for(;i>0&&e[i].depth>0;)i--;let n=0;for(let s=0;s<=i;s++)0===e[s].depth&&n++;return n-1}function h(e,t="children"){if(!Array.isArray(e)||0===e.length)return!1;for(const r of e){if(!r)continue;const e=r[t];if(Array.isArray(e)&&e.length>0)return!0;if(null!=e&&!Array.isArray(e)&&e)return!0}return!1}class c extends i.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:10},incompatibleWith:[{name:"groupingRows",reason:"Both plugins transform the entire row model. TreePlugin flattens nested hierarchies while GroupingRowsPlugin groups flat rows with synthetic headers. Use one approach per grid."},{name:"pivot",reason:"PivotPlugin replaces the entire row and column structure with aggregated pivot data. Tree hierarchy cannot coexist with pivot aggregation."}],events:[{type:"tree-expand",description:"Emitted when tree expansion state changes (toggle, expand all, collapse all). Broadcast to both DOM consumers and plugin bus."}],queries:[{type:"canMoveRow",description:"Returns false for rows with children (parent nodes cannot be reordered)"},{type:"datasource:viewport-mapping",description:"Translates flat viewport row indices to top-level node indices for ServerSide pagination."}]};static dependencies=[{name:"multiSort",required:!1,reason:"Queries sort model for coordinated tree sorting"},{name:"serverSide",required:!1,reason:"Consumes datasource events for lazy-loaded tree data"}];name="tree";styles='@layer tbw-plugins{tbw-grid .cell[data-field=__tbw_expander]{border-inline-end:none!important;padding:0;display:flex;align-items:center;justify-content:flex-start}tbw-grid .header-row .cell[data-field=__tbw_expander]{display:none}tbw-grid .header-row .cell[data-field=__tbw_expander]+.cell{grid-column:1 / 3}tbw-grid .tree-cell-wrapper{display:inline-flex;align-items:center;vertical-align:middle;overflow:visible;padding-inline-start:calc(var(--tbw-tree-depth, 0) * var(--tbw-tree-indent-width, var(--tbw-tree-toggle-size, 1.25em)))}tbw-grid .tree-expander{display:flex;align-items:center;justify-content:flex-start;width:100%;height:100%;box-sizing:border-box}tbw-grid .tree-toggle{cursor:pointer;-webkit-user-select:none;user-select:none;display:inline-flex;align-items:center;justify-content:center;width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);flex-shrink:0}tbw-grid .tree-toggle:hover{color:var(--tbw-tree-accent, var(--tbw-color-accent))}tbw-grid .tree-spacer{width:var(--tbw-tree-toggle-size, 1.25em);height:var(--tbw-tree-toggle-size, 1.25em);display:inline-block;flex-shrink:0}tbw-grid .data-grid-row.tbw-tree-slide-in{animation:tbw-tree-slide-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}tbw-grid .data-grid-row.tbw-tree-fade-in{animation:tbw-tree-fade-in var(--tbw-animation-duration, .2s) var(--tbw-animation-easing, ease-out) forwards}@keyframes tbw-tree-slide-in{0%{opacity:0;transform:translate(-8px)}to{opacity:1;transform:translate(0)}}@keyframes tbw-tree-fade-in{0%{opacity:0}to{opacity:1}}tbw-grid.tbw-tree-loading .rows-viewport:after{content:"";display:block;height:2px;background:linear-gradient(90deg,transparent,var(--tbw-color-accent, #2563eb),transparent);animation:tbw-tree-loading-bar 1s ease-in-out infinite;position:sticky;bottom:0;left:0;right:0}@keyframes tbw-tree-loading-bar{0%{transform:translate(-100%)}to{transform:translate(100%)}}}';get defaultConfig(){return{childrenField:"children",autoDetect:!0,defaultExpanded:!1,indentWidth:20,showExpandIcons:!0,animation:"slide"}}expandedKeys=new Set;initialExpansionDone=!1;flattenedRows=[];rowKeyMap=new Map;previousVisibleKeys=new Set;keysToAnimate=new Set;sortState=null;loadingKeys=new Set;#e=new WeakMap;#t=new WeakMap;originalTreeColumnRenderer;wrappedTreeColumnField;detach(){const e=this.gridElement?.querySelector(".rows-body");e?.setAttribute("role","grid"),this.expandedKeys.clear(),this.initialExpansionDone=!1,this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),this.keysToAnimate.clear(),this.sortState=null,this.loadingKeys.clear(),this.originalTreeColumnRenderer=void 0,this.wrappedTreeColumnField=void 0}handleQuery(e){if("canMoveRow"===e.type){const t=e.context,r=this.config.childrenField??"children",i=t?.[r];if(Array.isArray(i)&&i.length>0)return!1}if("datasource:viewport-mapping"===e.type){const{viewportStart:t,viewportEnd:r}=e.context;if(0===this.flattenedRows.length)return;return{startNode:l(this.flattenedRows,t),endNode:l(this.flattenedRows,r)+1,totalLoadedNodes:function(e){let t=0;for(const r of e)0===r.depth&&t++;return t}(this.flattenedRows)}}}attach(e){super.attach(e),this.on("datasource:data",e=>{const t=e;t.claimed||(t.claimed=!0)}),this.on("datasource:children",e=>{const t=e;if("tree"!==t.context?.source)return;t.claimed=!0;const r=t.context.parentNode;if(r){r[this.config.childrenField??"children"]=t.rows;const e=this.#e.get(r)??String(r.id??"?");this.loadingKeys.delete(e),this.requestRender()}})}get animationStyle(){return!!this.isAnimationEnabled&&(this.config.animation??"slide")}detect(e){if(!this.config.autoDetect)return!1;const t=e,r=this.config.childrenField??function(e){if(!Array.isArray(e)||0===e.length)return null;const t=["children","items","nodes","subRows","nested"];for(const r of e)if(r&&"object"==typeof r)for(const e of t){const t=r[e];if(Array.isArray(t)&&t.length>0)return e}return null}(t)??"children";return h(t,r)}processRows(e){const t=this.config.childrenField??"children",r=e;if(0===r.length||!h(r,t))return this.flattenedRows=[],this.rowKeyMap.clear(),this.previousVisibleKeys.clear(),[...e];const i=this.resolveEffectiveSortState();this.config.defaultExpanded&&!this.initialExpansionDone&&(this.expandedKeys=a(r,this.config),this.initialExpansionDone=!0),this.flattenedRows=this.#r(r,this.expandedKeys,i,null,0),this.#t=new WeakMap,this.rowKeyMap.clear(),this.keysToAnimate.clear();const n=new Set;for(const s of this.flattenedRows)this.rowKeyMap.set(s.key,s),this.#t.set(s.data,s),n.add(s.key),!this.previousVisibleKeys.has(s.key)&&s.depth>0&&this.keysToAnimate.add(s.key);return this.previousVisibleKeys=n,this.flattenedRows.map(e=>e.data)}#i(e,t,r){if(void 0!==e.id){const t=String(e.id);return this.#e.set(e,t),t}const i=this.#e.get(e);if(void 0!==i)return i;const n=r?`${r}-${t}`:String(t);return this.#e.set(e,n),n}#r(e,t,r,i,n){const s=this.config.childrenField??"children";for(let d=0;d<e.length;d++)this.#i(e[d],d,i);const a=r?this.#n(e,r.field,r.direction):e,o=[];for(let d=0;d<a.length;d++){const e=a[d],l=this.#i(e,d,i),h=e[s],c=Array.isArray(h)&&h.length>0,p=null!=h&&!Array.isArray(h)&&!!h,u=c||p,f=t.has(l);o.push({key:l,data:e,depth:n,hasChildren:u,isExpanded:f,parentKey:i,posInSet:d+1,setSize:a.length}),c&&f&&o.push(...this.#r(h,t,r,l,n+1))}return o}#n(e,t,i){const n=this.grid,s=n?._columns??[],a={field:t,direction:i},o=[...e],d=(n?.effectiveConfig?.sortHandler??r.builtInSort)(o,a,s);return d&&"function"==typeof d.then?(d.catch(()=>{}),r.builtInSort(o,a,s)):d}requestLazyChildren(e){if(this.loadingKeys.has(e.key))return;const t=this.config.childrenField??"children",r=e.data[t];if(Array.isArray(r)&&r.length>0)return;const i=this.grid?.query?.("datasource:is-active",null);i&&(this.loadingKeys.add(e.key),this.grid.query("datasource:fetch-children",{context:{source:"tree",parentNode:e.data,nodePath:[e.key]}}))}resolveEffectiveSortState(){const e=this.grid?.query?.("sort:get-model",null);if(Array.isArray(e)&&e.length>0){const t=e[0];if(Array.isArray(t)&&t.length>0)return{field:t[0].field,direction:"desc"===t[0].direction?-1:1}}return this.sortState}processColumns(e){if(0===this.flattenedRows.length)return[...e];const r=[...e];if(0===r.length)return r;const{treeColumn:i}=this.config;let n=0;if(i){const e=r.findIndex(e=>e.field===i);e>=0&&(n=e)}const s=r[n],a=s.field;this.wrappedTreeColumnField!==a&&(this.originalTreeColumnRenderer=s.viewRenderer,this.wrappedTreeColumnField=a);const o=this.originalTreeColumnRenderer,d=()=>this.config,l=this.setIcon.bind(this);return r[n]={...s,viewRenderer:e=>{const{row:r,value:i}=e,{showExpandIcons:n=!0,indentWidth:s}=d(),a=this.#t.get(r),h=a?.depth??0,c=document.createElement("span");if(c.className="tree-cell-wrapper",c.style.setProperty("--tbw-tree-depth",String(h)),void 0!==s&&c.style.setProperty("--tbw-tree-indent-width",`${s}px`),n)if(a&&a.hasChildren){const e=document.createElement("span");e.className=`${t.GridClasses.TREE_TOGGLE}${a.isExpanded?` ${t.GridClasses.EXPANDED}`:""}`,l(e,a.isExpanded?"collapse":"expand"),e.setAttribute("data-tree-key",a.key),c.appendChild(e)}else{const e=document.createElement("span");e.className="tree-spacer",c.appendChild(e)}const p=document.createElement("span");if(p.className="tree-content",o){const t=o(e);t instanceof Node?p.appendChild(t):"string"==typeof t&&(p.innerHTML=t)}else p.textContent=null!=i?String(i):"";return c.appendChild(p),c}},r}onCellClick(e){const r=e.originalEvent?.target;if(!r?.classList.contains(t.GridClasses.TREE_TOGGLE))return!1;const i=r.getAttribute("data-tree-key");if(!i)return!1;const n=this.rowKeyMap.get(i);return!!n&&(this.expandedKeys=s(this.expandedKeys,i),this.expandedKeys.has(i)&&this.requestLazyChildren(n),this.broadcast("tree-expand",{key:i,row:n.data,expanded:this.expandedKeys.has(i),depth:n.depth,expandedKeys:[...this.expandedKeys]}),this.requestRender(),!0)}onKeyDown(e){if(" "!==e.key)return;const t=this.grid._focusRow,r=this.flattenedRows[t];return r?.hasChildren?(e.preventDefault(),this.expandedKeys=s(this.expandedKeys,r.key),this.expandedKeys.has(r.key)&&this.requestLazyChildren(r),this.broadcast("tree-expand",{key:r.key,row:r.data,expanded:this.expandedKeys.has(r.key),depth:r.depth,expandedKeys:[...this.expandedKeys]}),this.requestRenderWithFocus(),!0):void 0}onHeaderClick(e){if(0===this.flattenedRows.length||!e.column.sortable)return!1;const t=this.grid?.query?.("sort:get-model",null);if(Array.isArray(t)&&t.length>0)return!1;const{field:r}=e.column;this.sortState&&this.sortState.field===r?1===this.sortState.direction?this.sortState={field:r,direction:-1}:this.sortState=null:this.sortState={field:r,direction:1};const i=this.grid;return void 0!==i._sortState&&(i._sortState=this.sortState?{...this.sortState}:null),this.broadcast("sort-change",{field:r,direction:this.sortState?.direction??0}),this.requestRender(),!0}afterRender(){const e=this.gridElement?.querySelector(".rows-body");e&&"treegrid"!==e.getAttribute("role")&&e.setAttribute("role","treegrid");const t=this.gridElement?.querySelector(".rows");if(!t)return;const r=this.animationStyle,i=!1!==r&&this.keysToAnimate.size>0,n="fade"===r?"tbw-tree-fade-in":"tbw-tree-slide-in";for(const s of t.querySelectorAll(".data-grid-row")){const e=s.querySelector(".cell[data-row]"),t=e?parseInt(e.getAttribute("data-row")??"-1",10):-1,r=this.flattenedRows[t];r&&(s.setAttribute("aria-level",String(r.depth+1)),s.setAttribute("aria-setsize",String(r.setSize)),s.setAttribute("aria-posinset",String(r.posInSet)),r.hasChildren?s.setAttribute("aria-expanded",String(r.isExpanded)):s.hasAttribute("aria-expanded")&&s.removeAttribute("aria-expanded"),s.classList.toggle("tbw-row-expanded",r.hasChildren&&r.isExpanded),i&&r.key&&this.keysToAnimate.has(r.key)&&(s.classList.add(n),s.addEventListener("animationend",()=>s.classList.remove(n),{once:!0})))}this.keysToAnimate.clear()}expand(e){this.expandedKeys.add(e);const t=this.rowKeyMap.get(e);t&&this.requestLazyChildren(t),this.requestRender()}collapse(e){this.expandedKeys.delete(e),this.requestRender()}toggle(e){this.expandedKeys=s(this.expandedKeys,e);const t=this.rowKeyMap.get(e);t?(this.expandedKeys.has(e)&&this.requestLazyChildren(t),this.broadcast("tree-expand",{key:e,row:t.data,expanded:this.expandedKeys.has(e),depth:t.depth,expandedKeys:[...this.expandedKeys]})):this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}expandAll(){this.expandedKeys=a(this.rows,this.config),this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}collapseAll(){this.expandedKeys=new Set,this.emitPluginEvent("tree-expand",{expandedKeys:[...this.expandedKeys]}),this.requestRender()}isExpanded(e){return this.expandedKeys.has(e)}getExpandedKeys(){return[...this.expandedKeys]}getFlattenedRows(){return[...this.flattenedRows]}getRowMeta(e){return this.#t.get(e)}getRowByKey(e){return this.rowKeyMap.get(e)?.data}expandToKey(e){this.expandedKeys=d(this.rows,e,this.config,this.expandedKeys),this.requestRender()}}e.TreePlugin=c,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=tree.umd.js.map