@toolbox-web/grid 1.26.1 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +2 -2
- package/all.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +64 -1
- package/lib/core/internal/diagnostics.d.ts +4 -3
- package/lib/core/internal/row-manager.d.ts +3 -1
- package/lib/core/plugin/base-plugin.d.ts +2 -2
- package/lib/core/types.d.ts +59 -3
- package/lib/features/registry.js.map +1 -1
- package/lib/plugins/clipboard/ClipboardPlugin.d.ts +1 -1
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/context-menu/ContextMenuPlugin.d.ts +24 -5
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/editing/EditingPlugin.d.ts +1 -1
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/export/ExportPlugin.d.ts +1 -1
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/filtering/index.d.ts +2 -2
- package/lib/plugins/filtering/index.js +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/grouping-columns/GroupingColumnsPlugin.d.ts +2 -2
- package/lib/plugins/grouping-columns/grouping-columns.d.ts +18 -3
- package/lib/plugins/grouping-columns/index.d.ts +0 -1
- package/lib/plugins/grouping-columns/index.js +1 -1
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-columns/types.d.ts +1 -7
- package/lib/plugins/grouping-rows/index.d.ts +2 -1
- package/lib/plugins/grouping-rows/index.js +1 -1
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +2 -0
- package/lib/plugins/master-detail/index.js +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/types.d.ts +20 -1
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/pinned-columns/PinnedColumnsPlugin.d.ts +8 -1
- package/lib/plugins/pinned-columns/index.js +1 -1
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-columns/pinned-columns.d.ts +11 -1
- package/lib/plugins/pinned-rows/index.d.ts +1 -1
- package/lib/plugins/pinned-rows/index.js +1 -1
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/types.d.ts +10 -3
- package/lib/plugins/pivot/PivotPlugin.d.ts +107 -1
- package/lib/plugins/pivot/index.d.ts +2 -1
- package/lib/plugins/pivot/index.js +1 -1
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/print/types.d.ts +0 -3
- package/lib/plugins/reorder-columns/ReorderPlugin.d.ts +19 -2
- package/lib/plugins/reorder-columns/index.js +1 -1
- package/lib/plugins/reorder-columns/index.js.map +1 -1
- package/lib/plugins/reorder-rows/index.d.ts +1 -1
- package/lib/plugins/reorder-rows/index.js.map +1 -1
- package/lib/plugins/responsive/ResponsivePlugin.d.ts +1 -1
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/selection/SelectionPlugin.d.ts +1 -1
- package/lib/plugins/selection/index.js +1 -1
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/types.d.ts +3 -3
- package/lib/plugins/server-side/ServerSidePlugin.d.ts +6 -1
- package/lib/plugins/server-side/index.js +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/tree/TreePlugin.d.ts +116 -0
- package/lib/plugins/tree/index.d.ts +1 -1
- package/lib/plugins/tree/index.js +1 -1
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/types.d.ts +16 -1
- package/lib/plugins/undo-redo/UndoRedoPlugin.d.ts +1 -1
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/undo-redo/types.d.ts +15 -3
- package/lib/plugins/visibility/VisibilityPlugin.d.ts +18 -5
- package/lib/plugins/visibility/index.js +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/package.json +1 -1
- package/public.d.ts +2 -4
- package/themes/dg-theme-material.css +16 -4
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/export.umd.js.map +1 -1
- package/umd/plugins/filtering.umd.js +1 -1
- package/umd/plugins/filtering.umd.js.map +1 -1
- package/umd/plugins/grouping-columns.umd.js +1 -1
- package/umd/plugins/grouping-columns.umd.js.map +1 -1
- package/umd/plugins/grouping-rows.umd.js +1 -1
- package/umd/plugins/grouping-rows.umd.js.map +1 -1
- package/umd/plugins/master-detail.umd.js +1 -1
- package/umd/plugins/master-detail.umd.js.map +1 -1
- package/umd/plugins/pinned-columns.umd.js +1 -1
- package/umd/plugins/pinned-columns.umd.js.map +1 -1
- package/umd/plugins/pinned-rows.umd.js +1 -1
- package/umd/plugins/pinned-rows.umd.js.map +1 -1
- package/umd/plugins/pivot.umd.js +1 -1
- package/umd/plugins/pivot.umd.js.map +1 -1
- package/umd/plugins/reorder-columns.umd.js +1 -1
- package/umd/plugins/reorder-columns.umd.js.map +1 -1
- package/umd/plugins/responsive.umd.js +1 -1
- package/umd/plugins/responsive.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +1 -1
- package/umd/plugins/selection.umd.js.map +1 -1
- package/umd/plugins/server-side.umd.js +1 -1
- package/umd/plugins/server-side.umd.js.map +1 -1
- package/umd/plugins/tree.umd.js +1 -1
- package/umd/plugins/tree.umd.js.map +1 -1
- package/umd/plugins/undo-redo.umd.js.map +1 -1
- package/umd/plugins/visibility.umd.js +1 -1
- package/umd/plugins/visibility.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reorder-columns.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/reorder-columns/column-drag.ts","../../../../../libs/grid/src/lib/plugins/reorder-columns/ReorderPlugin.ts"],"sourcesContent":["/**\n * Column Reordering Core Logic\n *\n * Pure functions for column drag and reordering operations.\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Check if a column can be moved based on its own metadata.\n * This checks column-level properties like lockPosition and suppressMovable.\n *\n * Note: For full movability checks including plugin constraints (e.g., pinned columns),\n * use `grid.query<boolean>('canMoveColumn', column)` which queries all plugins that\n * declare the 'canMoveColumn' query in their manifest.\n *\n * @param column - The column configuration to check\n * @returns True if the column can be moved based on its metadata\n */\nexport function canMoveColumn(column: { meta?: Record<string, unknown> }): boolean {\n // Check for lockPosition or suppressMovable properties in the column config\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Move a column from one position to another in the order array.\n *\n * @param columns - Array of field names in current order\n * @param fromIndex - The current index of the column to move\n * @param toIndex - The target index to move the column to\n * @returns New array with updated order\n */\nexport function moveColumn(columns: string[], fromIndex: number, toIndex: number): string[] {\n if (fromIndex === toIndex) return columns;\n if (fromIndex < 0 || fromIndex >= columns.length) return columns;\n if (toIndex < 0 || toIndex > columns.length) return columns;\n\n const result = [...columns];\n const [removed] = result.splice(fromIndex, 1);\n result.splice(toIndex, 0, removed);\n return result;\n}\n\n/**\n * Calculate the drop index based on the current drag position.\n *\n * @param dragX - The current X position of the drag\n * @param headerRect - The bounding rect of the header container\n * @param columnWidths - Array of column widths in order\n * @returns The index where the column should be dropped\n */\nexport function getDropIndex(dragX: number, headerRect: DOMRect, columnWidths: number[]): number {\n let x = headerRect.left;\n\n for (let i = 0; i < columnWidths.length; i++) {\n const mid = x + columnWidths[i] / 2;\n if (dragX < mid) return i;\n x += columnWidths[i];\n }\n\n return columnWidths.length;\n}\n\n/**\n * Reorder columns according to a specified order.\n * Columns not in the order array are appended at the end.\n *\n * @param columns - Array of column configurations\n * @param order - Array of field names specifying the desired order\n * @returns New array of columns in the specified order\n */\nexport function reorderColumns<TRow = unknown>(columns: ColumnConfig<TRow>[], order: string[]): ColumnConfig<TRow>[] {\n const columnMap = new Map<string, ColumnConfig<TRow>>(columns.map((c) => [c.field as string, c]));\n const reordered: ColumnConfig<TRow>[] = [];\n\n // Add columns in specified order\n for (const field of order) {\n const col = columnMap.get(field);\n if (col) {\n reordered.push(col);\n columnMap.delete(field);\n }\n }\n\n // Add any remaining columns not in order\n for (const col of columnMap.values()) {\n reordered.push(col);\n }\n\n return reordered;\n}\n","/**\n * Column Reordering Plugin (Class-based)\n *\n * Provides drag-and-drop column reordering functionality for tbw-grid.\n * Supports keyboard and mouse interactions with visual feedback.\n * Uses FLIP animation technique for smooth column transitions.\n *\n * Animation respects grid-level animation.mode setting but style is plugin-configured.\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, GridHost } from '../../core/types';\nimport { canMoveColumn, moveColumn } from './column-drag';\nimport styles from './reorder.css?inline';\nimport type { ColumnMoveDetail, ReorderConfig } from './types';\n\n/**\n * Column Reorder Plugin for tbw-grid\n *\n * Lets users rearrange columns by dragging and dropping column headers. Supports smooth\n * FLIP animations, fade transitions, or instant reordering. Animation respects the\n * grid-level `animation.mode` setting.\n *\n * ## Installation\n *\n * ```ts\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `animation` | `false \\| 'flip' \\| 'fade'` | `'flip'` | Animation type for column moves |\n * | `animationDuration` | `number` | `200` | Animation duration in ms |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Alt + ←` | Move focused column left |\n * | `Alt + →` | Move focused column right |\n *\n * ## Events\n *\n * | Event | Detail | Cancelable | Description |\n * |-------|--------|------------|-------------|\n * | `column-move` | `{ field, fromIndex, toIndex, columnOrder }` | Yes | Fired when a column move is attempted |\n *\n * @example Basic Drag-and-Drop Reordering\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ReorderPlugin({ animation: 'flip', animationDuration: 200 })],\n * };\n *\n * // Persist column order\n * grid.on('column-move', ({ columnOrder }) => {\n * localStorage.setItem('columnOrder', JSON.stringify(columnOrder));\n * });\n * ```\n *\n * @example Prevent Moves That Break Group Boundaries\n * ```ts\n * grid.on('column-move', (detail, e) => {\n * if (!isValidMoveWithinGroup(detail.field, detail.fromIndex, detail.toIndex)) {\n * e.preventDefault(); // Column snaps back to original position\n * }\n * });\n * ```\n *\n * @see {@link ReorderConfig} for all configuration options\n * @see {@link ColumnMoveDetail} for the event detail structure\n * @see {@link GroupingColumnsPlugin} for column group integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ReorderPlugin extends BaseGridPlugin<ReorderConfig> {\n /** @internal */\n readonly name = 'reorderColumns';\n /** @internal */\n override readonly aliases = ['reorder'] as const;\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<ReorderConfig> {\n return {\n animation: 'flip', // Plugin's own default\n };\n }\n\n /**\n * Resolve animation type from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationType(): false | 'flip' | 'fade' {\n // Check if animations are globally disabled\n if (!this.isAnimationEnabled) return false;\n\n // Plugin config (with default from defaultConfig)\n if (this.config.animation !== undefined) return this.config.animation;\n\n return 'flip'; // Plugin default\n }\n\n /**\n * Get animation duration, allowing plugin config override.\n * Uses base class animationDuration for default.\n */\n protected override get animationDuration(): number {\n // Plugin config override\n if (this.config.animationDuration !== undefined) {\n return this.config.animationDuration;\n }\n return super.animationDuration;\n }\n\n // #region Internal State\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n\n /** Typed internal grid accessor. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if a column can be moved, considering both column config and plugin queries.\n */\n private canMoveColumnWithPlugins(column: ColumnConfig | undefined): boolean {\n if (!column || !canMoveColumn(column)) return false;\n // Query plugins that respond to 'canMoveColumn' (e.g., PinnedColumnsPlugin)\n const responses = this.grid.query<boolean>('canMoveColumn', column);\n return !responses.includes(false);\n }\n\n /**\n * Clear all drag-related classes from header cells.\n */\n private clearDragClasses(): void {\n this.gridElement?.querySelectorAll('.header-row > .cell').forEach((h) => {\n h.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Listen for reorder requests from other plugins (e.g., VisibilityPlugin)\n // Uses disconnectSignal for automatic cleanup - no need for manual removeEventListener\n this.gridElement.addEventListener(\n 'column-reorder-request',\n (e: Event) => {\n const detail = (e as CustomEvent).detail;\n if (detail?.field && typeof detail.toIndex === 'number') {\n this.moveColumn(detail.field, detail.toIndex);\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const headers = gridEl.querySelectorAll('.header-row > .cell');\n\n headers.forEach((header) => {\n const headerEl = header as HTMLElement;\n const field = headerEl.getAttribute('data-field');\n if (!field) return;\n\n const column = this.columns.find((c) => c.field === field);\n if (!this.canMoveColumnWithPlugins(column)) {\n headerEl.draggable = false;\n return;\n }\n\n headerEl.draggable = true;\n\n // Remove existing listeners to prevent duplicates\n if (headerEl.getAttribute('data-dragstart-bound')) return;\n headerEl.setAttribute('data-dragstart-bound', 'true');\n\n headerEl.addEventListener('dragstart', (e: DragEvent) => {\n const currentOrder = this.getColumnOrder();\n const orderIndex = currentOrder.indexOf(field);\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = orderIndex;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n headerEl.classList.add('dragging');\n });\n\n headerEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.clearDragClasses();\n });\n\n headerEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging || this.draggedField === field) return;\n\n const rect = headerEl.getBoundingClientRect();\n const midX = rect.left + rect.width / 2;\n\n const currentOrder = this.getColumnOrder();\n const orderIndex = currentOrder.indexOf(field);\n this.dropIndex = e.clientX < midX ? orderIndex : orderIndex + 1;\n\n headerEl.classList.add('drop-target');\n headerEl.classList.toggle('drop-before', e.clientX < midX);\n headerEl.classList.toggle('drop-after', e.clientX >= midX);\n });\n\n headerEl.addEventListener('dragleave', () => {\n headerEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n headerEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (!this.isDragging || draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n const currentOrder = this.getColumnOrder();\n const newOrder = moveColumn(currentOrder, draggedIndex, effectiveToIndex);\n\n const detail: ColumnMoveDetail = {\n field: draggedField,\n fromIndex: draggedIndex,\n toIndex: effectiveToIndex,\n columnOrder: newOrder,\n };\n\n // Emit cancelable event first - only update if not cancelled\n const cancelled = this.emitCancelable('column-move', detail);\n if (!cancelled) {\n // Update the grid's column order (with optional view transition)\n this.updateColumnOrder(newOrder);\n }\n });\n });\n }\n\n /**\n * Handle Alt+Arrow keyboard shortcuts for column reordering.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n if (!event.altKey || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) {\n return;\n }\n\n const grid = this.#internalGrid;\n const focusCol = grid._focusCol;\n const columns = grid._visibleColumns;\n\n if (focusCol < 0 || focusCol >= columns.length) return;\n\n const column = columns[focusCol];\n if (!this.canMoveColumnWithPlugins(column)) return;\n\n const currentOrder = this.getColumnOrder();\n const fromIndex = currentOrder.indexOf(column.field);\n if (fromIndex === -1) return;\n\n const toIndex = event.key === 'ArrowLeft' ? fromIndex - 1 : fromIndex + 1;\n\n // Check bounds\n if (toIndex < 0 || toIndex >= currentOrder.length) return;\n\n // Check if target position is allowed (e.g., not into pinned area)\n const targetColumn = columns.find((c) => c.field === currentOrder[toIndex]);\n if (!this.canMoveColumnWithPlugins(targetColumn)) return;\n\n this.moveColumn(column.field, toIndex);\n\n // Update focus to follow the moved column and refresh visual focus state\n grid._focusCol = toIndex;\n ensureCellVisible(this.#internalGrid);\n\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current column order from the grid.\n * @returns Array of field names in display order\n */\n getColumnOrder(): string[] {\n return this.grid.getColumnOrder();\n }\n\n /**\n * Move a column to a new position.\n * @param field - The field name of the column to move\n * @param toIndex - The target index\n */\n moveColumn(field: string, toIndex: number): void {\n const currentOrder = this.getColumnOrder();\n const fromIndex = currentOrder.indexOf(field);\n if (fromIndex === -1) return;\n\n const newOrder = moveColumn(currentOrder, fromIndex, toIndex);\n\n // Emit cancelable event first - only update if not cancelled\n const cancelled = this.emitCancelable<ColumnMoveDetail>('column-move', {\n field,\n fromIndex,\n toIndex,\n columnOrder: newOrder,\n });\n if (!cancelled) {\n // Update with view transition\n this.updateColumnOrder(newOrder);\n }\n }\n\n /**\n * Set a specific column order.\n * @param order - Array of field names in desired order\n */\n setColumnOrder(order: string[]): void {\n this.updateColumnOrder(order);\n }\n\n /**\n * Reset column order to the original configuration order.\n */\n resetColumnOrder(): void {\n const originalOrder = this.columns.map((c) => c.field);\n this.updateColumnOrder(originalOrder);\n }\n // #endregion\n\n // #region View Transition\n\n /**\n * Capture header cell positions before reorder.\n */\n private captureHeaderPositions(): Map<string, number> {\n const positions = new Map<string, number>();\n this.gridElement?.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (field) positions.set(field, cell.getBoundingClientRect().left);\n });\n return positions;\n }\n\n /**\n * Apply FLIP animation for column reorder.\n * Uses CSS transitions - JS sets initial transform and toggles class.\n * @param oldPositions - Header positions captured before DOM change\n */\n private animateFLIP(oldPositions: Map<string, number>): void {\n const gridEl = this.gridElement;\n if (!gridEl || oldPositions.size === 0) return;\n\n // Compute deltas from header cells (one per column, stable reference).\n // All cells in the same column share the same horizontal offset.\n const deltas = new Map<string, number>();\n gridEl.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n const oldLeft = oldPositions.get(field);\n if (oldLeft === undefined) return;\n const deltaX = oldLeft - cell.getBoundingClientRect().left;\n if (Math.abs(deltaX) > 1) deltas.set(field, deltaX);\n });\n\n if (deltas.size === 0) return;\n\n // Apply transforms to ALL cells (headers + body).\n // After forceLayout(), body cells are fully rebuilt in new DOM order\n // with correct data-field attributes, so header-derived deltas apply correctly.\n const cells: HTMLElement[] = [];\n gridEl.querySelectorAll('.cell[data-field]').forEach((cell) => {\n const deltaX = deltas.get(cell.getAttribute('data-field') ?? '');\n if (deltaX !== undefined) {\n const el = cell as HTMLElement;\n el.style.transform = `translateX(${deltaX}px)`;\n cells.push(el);\n }\n });\n\n if (cells.length === 0) return;\n\n // Force reflow then animate to final position via CSS transition\n void gridEl.offsetHeight;\n\n const duration = this.animationDuration;\n\n requestAnimationFrame(() => {\n cells.forEach((el) => {\n el.classList.add('flip-animating');\n el.style.transform = '';\n });\n\n // Cleanup after animation\n setTimeout(() => {\n cells.forEach((el) => {\n el.style.transform = '';\n el.classList.remove('flip-animating');\n });\n }, duration + 50);\n });\n }\n\n /**\n * Apply crossfade animation for moved columns.\n * Uses CSS keyframes - JS just toggles classes.\n */\n private animateFade(applyChange: () => void): void {\n const gridEl = this.gridElement;\n if (!gridEl) {\n applyChange();\n return;\n }\n\n // Capture old positions to detect which columns moved\n const oldPositions = this.captureHeaderPositions();\n\n // Apply the change first\n applyChange();\n\n // Find which columns changed position\n const movedFields = new Set<string>();\n gridEl.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n const oldLeft = oldPositions.get(field);\n if (oldLeft === undefined) return;\n const newLeft = cell.getBoundingClientRect().left;\n if (Math.abs(oldLeft - newLeft) > 1) {\n movedFields.add(field);\n }\n });\n\n if (movedFields.size === 0) return;\n\n // Add animation class to moved columns (headers + body cells)\n const cells: HTMLElement[] = [];\n gridEl.querySelectorAll('.cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (field && movedFields.has(field)) {\n const el = cell as HTMLElement;\n el.classList.add('fade-animating');\n cells.push(el);\n }\n });\n\n if (cells.length === 0) return;\n\n // Remove class after animation completes\n const duration = this.animationDuration;\n setTimeout(() => {\n cells.forEach((el) => el.classList.remove('fade-animating'));\n }, duration + 50);\n }\n\n /**\n * Update column order with configured animation.\n */\n private updateColumnOrder(newOrder: string[]): void {\n const animation = this.animationType;\n\n if (animation === 'flip' && this.gridElement) {\n const oldPositions = this.captureHeaderPositions();\n this.grid.setColumnOrder(newOrder);\n // Force a full render cycle so body cells are rebuilt in new column order.\n // setColumnOrder rebuilds headers synchronously but body cells are async\n // (VIRTUALIZATION phase only patches content in place via fastPatchRow).\n // forceLayout triggers processColumns which bumps the row render epoch,\n // ensuring body cells are fully rebuilt with correct DOM order.\n if (typeof this.grid.forceLayout === 'function') {\n this.grid.forceLayout().then(() => {\n this.animateFLIP(oldPositions);\n });\n } else {\n // Fallback: animate headers only (body cells may not be rebuilt yet)\n requestAnimationFrame(() => {\n this.animateFLIP(oldPositions);\n });\n }\n } else if (animation === 'fade') {\n this.animateFade(() => this.grid.setColumnOrder(newOrder));\n } else {\n this.grid.setColumnOrder(newOrder);\n }\n\n this.grid.requestStateChange?.();\n }\n // #endregion\n}\n"],"names":["moveColumn","columns","fromIndex","toIndex","length","result","removed","splice","ReorderPlugin","BaseGridPlugin","name","aliases","styles","defaultConfig","animation","animationType","this","isAnimationEnabled","config","animationDuration","super","isDragging","draggedField","draggedIndex","dropIndex","internalGrid","grid","canMoveColumnWithPlugins","column","meta","lockPosition","suppressMovable","canMoveColumn","query","includes","clearDragClasses","gridElement","querySelectorAll","forEach","h","classList","remove","attach","addEventListener","e","detail","field","signal","disconnectSignal","detach","afterRender","gridEl","header","headerEl","getAttribute","find","c","draggable","setAttribute","orderIndex","getColumnOrder","indexOf","dataTransfer","effectAllowed","setData","add","preventDefault","rect","getBoundingClientRect","midX","left","width","clientX","toggle","effectiveToIndex","newOrder","columnOrder","emitCancelable","updateColumnOrder","onKeyDown","event","altKey","key","focusCol","_focusCol","_visibleColumns","currentOrder","targetColumn","ensureCellVisible","stopPropagation","setColumnOrder","order","resetColumnOrder","originalOrder","map","captureHeaderPositions","positions","Map","cell","set","animateFLIP","oldPositions","size","deltas","oldLeft","get","deltaX","Math","abs","cells","el","style","transform","push","offsetHeight","duration","requestAnimationFrame","setTimeout","animateFade","applyChange","movedFields","Set","newLeft","has","forceLayout","then","requestStateChange"],"mappings":"2aAiCO,SAASA,EAAWC,EAAmBC,EAAmBC,GAC/D,GAAID,IAAcC,EAAS,OAAOF,EAClC,GAAIC,EAAY,GAAKA,GAAaD,EAAQG,OAAQ,OAAOH,EACzD,GAAIE,EAAU,GAAKA,E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,CAAkBH,GACxB,MAAM7D,EAAYE,KAAKD,cAEvB,GAAkB,SAAdD,GAAwBE,KAAKoB,YAAa,CAC5C,MAAMiE,EAAerF,KAAK+E,yBAC1B/E,KAAKU,KAAKgE,eAAef,GAMY,mBAA1B3D,KAAKU,KAAKkG,YACnB5G,KAAKU,KAAKkG,cAAcC,KAAK,KAC3B7G,KAAKoF,YAAYC,KAInBe,sBAAsB,KACpBpG,KAAKoF,YAAYC,IAGvB,KAAyB,SAAdvF,EACTE,KAAKsG,YAAY,IAAMtG,KAAKU,KAAKgE,eAAef,IAEhD3D,KAAKU,KAAKgE,eAAef,GAG3B3D,KAAKU,KAAKoG,sBACZ"}
|
|
1
|
+
{"version":3,"file":"reorder-columns.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/reorder-columns/column-drag.ts","../../../../../libs/grid/src/lib/plugins/reorder-columns/ReorderPlugin.ts"],"sourcesContent":["/**\n * Column Reordering Core Logic\n *\n * Pure functions for column drag and reordering operations.\n */\n\nimport type { ColumnConfig } from '../../core/types';\n\n/**\n * Check if a column can be moved based on its own metadata.\n * This checks column-level properties like lockPosition and suppressMovable.\n *\n * Note: For full movability checks including plugin constraints (e.g., pinned columns),\n * use `grid.query<boolean>('canMoveColumn', column)` which queries all plugins that\n * declare the 'canMoveColumn' query in their manifest.\n *\n * @param column - The column configuration to check\n * @returns True if the column can be moved based on its metadata\n */\nexport function canMoveColumn(column: { meta?: Record<string, unknown> }): boolean {\n // Check for lockPosition or suppressMovable properties in the column config\n const meta = column.meta ?? {};\n return meta.lockPosition !== true && meta.suppressMovable !== true;\n}\n\n/**\n * Move a column from one position to another in the order array.\n *\n * @param columns - Array of field names in current order\n * @param fromIndex - The current index of the column to move\n * @param toIndex - The target index to move the column to\n * @returns New array with updated order\n */\nexport function moveColumn(columns: string[], fromIndex: number, toIndex: number): string[] {\n if (fromIndex === toIndex) return columns;\n if (fromIndex < 0 || fromIndex >= columns.length) return columns;\n if (toIndex < 0 || toIndex > columns.length) return columns;\n\n const result = [...columns];\n const [removed] = result.splice(fromIndex, 1);\n result.splice(toIndex, 0, removed);\n return result;\n}\n\n/**\n * Calculate the drop index based on the current drag position.\n *\n * @param dragX - The current X position of the drag\n * @param headerRect - The bounding rect of the header container\n * @param columnWidths - Array of column widths in order\n * @returns The index where the column should be dropped\n */\nexport function getDropIndex(dragX: number, headerRect: DOMRect, columnWidths: number[]): number {\n let x = headerRect.left;\n\n for (let i = 0; i < columnWidths.length; i++) {\n const mid = x + columnWidths[i] / 2;\n if (dragX < mid) return i;\n x += columnWidths[i];\n }\n\n return columnWidths.length;\n}\n\n/**\n * Reorder columns according to a specified order.\n * Columns not in the order array are appended at the end.\n *\n * @param columns - Array of column configurations\n * @param order - Array of field names specifying the desired order\n * @returns New array of columns in the specified order\n */\nexport function reorderColumns<TRow = unknown>(columns: ColumnConfig<TRow>[], order: string[]): ColumnConfig<TRow>[] {\n const columnMap = new Map<string, ColumnConfig<TRow>>(columns.map((c) => [c.field as string, c]));\n const reordered: ColumnConfig<TRow>[] = [];\n\n // Add columns in specified order\n for (const field of order) {\n const col = columnMap.get(field);\n if (col) {\n reordered.push(col);\n columnMap.delete(field);\n }\n }\n\n // Add any remaining columns not in order\n for (const col of columnMap.values()) {\n reordered.push(col);\n }\n\n return reordered;\n}\n","/**\n * Column Reordering Plugin (Class-based)\n *\n * Provides drag-and-drop column reordering functionality for tbw-grid.\n * Supports keyboard and mouse interactions with visual feedback.\n * Uses FLIP animation technique for smooth column transitions.\n *\n * Animation respects grid-level animation.mode setting but style is plugin-configured.\n */\n\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, GridHost } from '../../core/types';\nimport { canMoveColumn, moveColumn } from './column-drag';\nimport styles from './reorder.css?inline';\nimport type { ColumnMoveDetail, ReorderConfig } from './types';\n\n/**\n * Column Reorder Plugin for tbw-grid\n *\n * Lets users rearrange columns by dragging and dropping column headers. Supports smooth\n * FLIP animations, fade transitions, or instant reordering. Animation respects the\n * grid-level `animation.mode` setting.\n *\n * ## Installation\n *\n * ```ts\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `animation` | `false \\| 'flip' \\| 'fade'` | `'flip'` | Animation type for column moves |\n * | `animationDuration` | `number` | `200` | Animation duration in ms |\n *\n * ## Keyboard Shortcuts\n *\n * | Key | Action |\n * |-----|--------|\n * | `Alt + ←` | Move focused column left |\n * | `Alt + →` | Move focused column right |\n *\n * ## Events\n *\n * | Event | Detail | Cancelable | Description |\n * |-------|--------|------------|-------------|\n * | `column-move` | `{ field, fromIndex, toIndex, columnOrder }` | Yes | Fired when a column move is attempted |\n *\n * @example Basic Drag-and-Drop Reordering\n * ```ts\n * import { queryGrid } from '@toolbox-web/grid';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder-columns';\n *\n * const grid = queryGrid('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ReorderPlugin({ animation: 'flip', animationDuration: 200 })],\n * };\n *\n * // Persist column order\n * grid.on('column-move', ({ columnOrder }) => {\n * localStorage.setItem('columnOrder', JSON.stringify(columnOrder));\n * });\n * ```\n *\n * @example Prevent Moves That Break Group Boundaries\n * ```ts\n * grid.on('column-move', (detail, e) => {\n * if (!isValidMoveWithinGroup(detail.field, detail.fromIndex, detail.toIndex)) {\n * e.preventDefault(); // Column snaps back to original position\n * }\n * });\n * ```\n *\n * @see {@link ReorderConfig} for all configuration options\n * @see {@link ColumnMoveDetail} for the event detail structure\n * @see GroupingColumnsPlugin for column group integration\n *\n * @internal Extends BaseGridPlugin\n */\nexport class ReorderPlugin extends BaseGridPlugin<ReorderConfig> {\n /** @internal */\n readonly name = 'reorderColumns';\n /** @internal */\n override readonly aliases = ['reorder'] as const;\n /** @internal */\n override readonly styles = styles;\n\n /** @internal */\n protected override get defaultConfig(): Partial<ReorderConfig> {\n return {\n animation: 'flip', // Plugin's own default\n };\n }\n\n /**\n * Resolve animation type from plugin config.\n * Uses base class isAnimationEnabled to respect grid-level settings.\n */\n private get animationType(): false | 'flip' | 'fade' {\n // Check if animations are globally disabled\n if (!this.isAnimationEnabled) return false;\n\n // Plugin config (with default from defaultConfig)\n if (this.config.animation !== undefined) return this.config.animation;\n\n return 'flip'; // Plugin default\n }\n\n /**\n * Get animation duration, allowing plugin config override.\n * Uses base class animationDuration for default.\n */\n protected override get animationDuration(): number {\n // Plugin config override\n if (this.config.animationDuration !== undefined) {\n return this.config.animationDuration;\n }\n return super.animationDuration;\n }\n\n // #region Internal State\n private isDragging = false;\n private draggedField: string | null = null;\n private draggedIndex: number | null = null;\n private dropIndex: number | null = null;\n /** When dragging a group header, holds the field names in that fragment. */\n private draggedGroupFields: string[] = [];\n\n /** Typed internal grid accessor. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if a column can be moved, considering both column config and plugin queries.\n */\n private canMoveColumnWithPlugins(column: ColumnConfig | undefined): boolean {\n if (!column || !canMoveColumn(column)) return false;\n // Query plugins that respond to 'canMoveColumn' (e.g., PinnedColumnsPlugin)\n const responses = this.grid.query<boolean>('canMoveColumn', column);\n return !responses.includes(false);\n }\n\n /**\n * Clear all drag-related classes from header cells and group header cells.\n */\n private clearDragClasses(): void {\n this.gridElement?.querySelectorAll('.header-row > .cell, .header-group-row > .cell').forEach((h) => {\n h.classList.remove('dragging', 'drop-target', 'drop-before', 'drop-after');\n });\n }\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Listen for reorder requests from other plugins (e.g., VisibilityPlugin)\n // Uses disconnectSignal for automatic cleanup - no need for manual removeEventListener\n this.gridElement.addEventListener(\n 'column-reorder-request',\n (e: Event) => {\n const detail = (e as CustomEvent).detail;\n if (detail?.field && typeof detail.toIndex === 'number') {\n this.moveColumn(detail.field, detail.toIndex);\n }\n },\n { signal: this.disconnectSignal },\n );\n }\n\n /** @internal */\n override detach(): void {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.draggedGroupFields = [];\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override afterRender(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const headers = gridEl.querySelectorAll('.header-row > .cell');\n\n headers.forEach((header) => {\n const headerEl = header as HTMLElement;\n const field = headerEl.getAttribute('data-field');\n if (!field) return;\n\n const column = this.columns.find((c) => c.field === field);\n if (!this.canMoveColumnWithPlugins(column)) {\n headerEl.draggable = false;\n return;\n }\n\n headerEl.draggable = true;\n\n // Remove existing listeners to prevent duplicates\n if (headerEl.getAttribute('data-dragstart-bound')) return;\n headerEl.setAttribute('data-dragstart-bound', 'true');\n\n headerEl.addEventListener('dragstart', (e: DragEvent) => {\n const currentOrder = this.getColumnOrder();\n const orderIndex = currentOrder.indexOf(field);\n this.isDragging = true;\n this.draggedField = field;\n this.draggedIndex = orderIndex;\n this.draggedGroupFields = []; // Clear any stale group state\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', field);\n }\n\n headerEl.classList.add('dragging');\n });\n\n headerEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.draggedGroupFields = [];\n this.clearDragClasses();\n });\n\n headerEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n // Skip if dragging this same individual column\n if (this.draggedField === field && this.draggedGroupFields.length === 0) return;\n // Skip if this column is part of the dragged group fragment\n if (this.draggedGroupFields.includes(field)) return;\n\n const rect = headerEl.getBoundingClientRect();\n const midX = rect.left + rect.width / 2;\n\n const currentOrder = this.getColumnOrder();\n const orderIndex = currentOrder.indexOf(field);\n this.dropIndex = e.clientX < midX ? orderIndex : orderIndex + 1;\n\n this.clearDragClasses();\n // Re-mark dragged elements\n if (this.draggedGroupFields.length > 0) {\n for (const f of this.draggedGroupFields) {\n this.gridElement?.querySelector(`.header-row > .cell[data-field=\"${f}\"]`)?.classList.add('dragging');\n }\n } else if (this.draggedField) {\n this.gridElement\n ?.querySelector(`.header-row > .cell[data-field=\"${this.draggedField}\"]`)\n ?.classList.add('dragging');\n }\n headerEl.classList.add('drop-target');\n headerEl.classList.toggle('drop-before', e.clientX < midX);\n headerEl.classList.toggle('drop-after', e.clientX >= midX);\n });\n\n headerEl.addEventListener('dragleave', () => {\n headerEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n headerEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n\n // Group fragment drop onto individual column header\n if (this.draggedGroupFields.length > 0) {\n if (this.draggedGroupFields.includes(field)) return;\n const rect = headerEl.getBoundingClientRect();\n const before = e.clientX < rect.left + rect.width / 2;\n this.executeGroupBlockMove(this.draggedGroupFields, [field], before);\n return;\n }\n\n // Individual column drop\n const draggedField = this.draggedField;\n const draggedIndex = this.draggedIndex;\n const dropIndex = this.dropIndex;\n\n if (!this.isDragging || draggedField === null || draggedIndex === null || dropIndex === null) {\n return;\n }\n\n const effectiveToIndex = dropIndex > draggedIndex ? dropIndex - 1 : dropIndex;\n const currentOrder = this.getColumnOrder();\n const newOrder = moveColumn(currentOrder, draggedIndex, effectiveToIndex);\n\n const detail: ColumnMoveDetail = {\n field: draggedField,\n fromIndex: draggedIndex,\n toIndex: effectiveToIndex,\n columnOrder: newOrder,\n };\n\n // Emit cancelable event first - only update if not cancelled\n const cancelled = this.emitCancelable('column-move', detail);\n if (!cancelled) {\n // Update the grid's column order (with optional view transition)\n this.updateColumnOrder(newOrder);\n }\n });\n });\n\n // Set up drag listeners for group header cells (if column grouping is active).\n // Deferred to a microtask because GroupingColumnsPlugin.afterRender() creates the\n // .header-group-row DOM, and it may run after this plugin in hook order.\n queueMicrotask(() => this.setupGroupHeaderDrag(gridEl));\n }\n\n /**\n * Set up drag-and-drop listeners on group header cells (.header-group-row > .cell).\n * Dragging a group header moves all columns in that fragment as a block.\n * Implicit groups (ungrouped column spans) are not draggable.\n */\n private setupGroupHeaderDrag(gridEl: HTMLElement): void {\n const groupHeaders = gridEl.querySelectorAll('.header-group-row > .cell[data-group]');\n\n groupHeaders.forEach((gh) => {\n const groupHeaderEl = gh as HTMLElement;\n const groupId = groupHeaderEl.getAttribute('data-group');\n if (!groupId || groupId.startsWith('__implicit__')) return;\n\n // Already bound?\n if (groupHeaderEl.getAttribute('data-group-drag-bound')) return;\n groupHeaderEl.setAttribute('data-group-drag-bound', 'true');\n\n // Determine which columns are in this fragment by reading the grid-column style\n const fragmentFields = this.getGroupFragmentFields(groupHeaderEl, groupId);\n if (fragmentFields.length === 0) return;\n\n // Check if all columns in the fragment can be moved\n const allMovable = fragmentFields.every((f) => {\n const col = this.columns.find((c) => c.field === f);\n return this.canMoveColumnWithPlugins(col);\n });\n if (!allMovable) return;\n\n groupHeaderEl.draggable = true;\n groupHeaderEl.style.cursor = 'grab';\n\n groupHeaderEl.addEventListener('dragstart', (e: DragEvent) => {\n this.isDragging = true;\n this.draggedField = null;\n this.draggedIndex = null;\n this.draggedGroupFields = [...fragmentFields];\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', `group:${groupId}`);\n }\n\n groupHeaderEl.classList.add('dragging');\n // Also mark the individual column headers as dragging\n for (const f of fragmentFields) {\n gridEl.querySelector(`.header-row > .cell[data-field=\"${f}\"]`)?.classList.add('dragging');\n }\n });\n\n groupHeaderEl.addEventListener('dragend', () => {\n this.isDragging = false;\n this.draggedField = null;\n this.draggedIndex = null;\n this.dropIndex = null;\n this.draggedGroupFields = [];\n this.clearDragClasses();\n });\n\n // Group header is also a drop target for other groups / individual columns\n groupHeaderEl.addEventListener('dragover', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n // If dragging the same fragment, ignore\n if (\n this.draggedGroupFields.length > 0 &&\n this.draggedGroupFields.length === fragmentFields.length &&\n this.draggedGroupFields.every((f) => fragmentFields.includes(f))\n )\n return;\n\n const rect = groupHeaderEl.getBoundingClientRect();\n const midX = rect.left + rect.width / 2;\n const before = e.clientX < midX;\n\n this.clearDragClasses();\n groupHeaderEl.classList.add('drop-target');\n groupHeaderEl.classList.toggle('drop-before', before);\n groupHeaderEl.classList.toggle('drop-after', !before);\n });\n\n groupHeaderEl.addEventListener('dragleave', () => {\n groupHeaderEl.classList.remove('drop-target', 'drop-before', 'drop-after');\n });\n\n groupHeaderEl.addEventListener('drop', (e: DragEvent) => {\n e.preventDefault();\n if (!this.isDragging) return;\n\n const rect = groupHeaderEl.getBoundingClientRect();\n const before = e.clientX < rect.left + rect.width / 2;\n\n if (this.draggedGroupFields.length > 0) {\n // Group-to-group drop: move dragged fragment as block relative to this fragment\n if (\n this.draggedGroupFields.length === fragmentFields.length &&\n this.draggedGroupFields.every((f) => fragmentFields.includes(f))\n )\n return;\n this.executeGroupBlockMove(this.draggedGroupFields, fragmentFields, before);\n } else if (this.draggedField) {\n // Individual column dropped onto group header\n const currentOrder = this.getColumnOrder();\n const anchorField = before ? fragmentFields[0] : fragmentFields[fragmentFields.length - 1];\n const fromIndex = currentOrder.indexOf(this.draggedField);\n const toIndex = before ? currentOrder.indexOf(anchorField) : currentOrder.indexOf(anchorField) + 1;\n if (fromIndex === -1 || toIndex === -1) return;\n const effectiveToIndex = toIndex > fromIndex ? toIndex - 1 : toIndex;\n const newOrder = moveColumn(currentOrder, fromIndex, effectiveToIndex);\n const cancelled = this.emitCancelable<ColumnMoveDetail>('column-move', {\n field: this.draggedField,\n fromIndex,\n toIndex: effectiveToIndex,\n columnOrder: newOrder,\n });\n if (!cancelled) this.updateColumnOrder(newOrder);\n }\n });\n });\n }\n\n /**\n * Get the column field names that belong to a group header fragment.\n * Reads the grid-column CSS style of the header cell to determine the column range.\n */\n private getGroupFragmentFields(groupHeaderEl: HTMLElement, _groupId: string): string[] {\n // Parse grid-column (e.g., \"2 / span 3\") to get start index and span\n const gridColumn = groupHeaderEl.style.gridColumn;\n const match = /(\\d+)\\s*\\/\\s*span\\s+(\\d+)/.exec(gridColumn);\n if (!match) return [];\n\n const startCol = parseInt(match[1], 10); // 1-based CSS grid column\n const span = parseInt(match[2], 10);\n\n // Map CSS grid columns to visible column fields\n const visibleColumns = this.visibleColumns;\n const fields: string[] = [];\n for (let i = startCol - 1; i < startCol - 1 + span && i < visibleColumns.length; i++) {\n const col = visibleColumns[i];\n if (col) fields.push(col.field);\n }\n return fields;\n }\n\n /**\n * Move a group of columns as a block to a new position relative to target fields.\n */\n private executeGroupBlockMove(draggedFields: string[], targetFields: string[], before: boolean): void {\n const currentOrder = this.getColumnOrder();\n const remaining = currentOrder.filter((f) => !draggedFields.includes(f));\n\n const anchorField = before ? targetFields[0] : targetFields[targetFields.length - 1];\n const insertAt = remaining.indexOf(anchorField);\n if (insertAt === -1) return;\n\n const insertIndex = before ? insertAt : insertAt + 1;\n const draggedInOrder = currentOrder.filter((f) => draggedFields.includes(f));\n remaining.splice(insertIndex, 0, ...draggedInOrder);\n\n // Emit cancelable column-move for the first field so lockGroupOrder guard can check\n const cancelled = this.emitCancelable<ColumnMoveDetail>('column-move', {\n field: draggedFields[0],\n fromIndex: currentOrder.indexOf(draggedFields[0]),\n toIndex: insertIndex,\n columnOrder: remaining,\n });\n if (!cancelled) {\n this.updateColumnOrder(remaining);\n }\n }\n\n /**\n * Handle Alt+Arrow keyboard shortcuts for column reordering.\n * @internal\n */\n override onKeyDown(event: KeyboardEvent): boolean | void {\n if (!event.altKey || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) {\n return;\n }\n\n const grid = this.#internalGrid;\n const focusCol = grid._focusCol;\n const columns = grid._visibleColumns;\n\n if (focusCol < 0 || focusCol >= columns.length) return;\n\n const column = columns[focusCol];\n if (!this.canMoveColumnWithPlugins(column)) return;\n\n const currentOrder = this.getColumnOrder();\n const fromIndex = currentOrder.indexOf(column.field);\n if (fromIndex === -1) return;\n\n const toIndex = event.key === 'ArrowLeft' ? fromIndex - 1 : fromIndex + 1;\n\n // Check bounds\n if (toIndex < 0 || toIndex >= currentOrder.length) return;\n\n // Check if target position is allowed (e.g., not into pinned area)\n const targetColumn = columns.find((c) => c.field === currentOrder[toIndex]);\n if (!this.canMoveColumnWithPlugins(targetColumn)) return;\n\n this.moveColumn(column.field, toIndex);\n\n // Update focus to follow the moved column and refresh visual focus state\n grid._focusCol = toIndex;\n ensureCellVisible(this.#internalGrid);\n\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Get the current column order from the grid.\n * @returns Array of field names in display order\n */\n getColumnOrder(): string[] {\n return this.grid.getColumnOrder();\n }\n\n /**\n * Move a column to a new position.\n * @param field - The field name of the column to move\n * @param toIndex - The target index\n */\n moveColumn(field: string, toIndex: number): void {\n const currentOrder = this.getColumnOrder();\n const fromIndex = currentOrder.indexOf(field);\n if (fromIndex === -1) return;\n\n const newOrder = moveColumn(currentOrder, fromIndex, toIndex);\n\n // Emit cancelable event first - only update if not cancelled\n const cancelled = this.emitCancelable<ColumnMoveDetail>('column-move', {\n field,\n fromIndex,\n toIndex,\n columnOrder: newOrder,\n });\n if (!cancelled) {\n // Update with view transition\n this.updateColumnOrder(newOrder);\n }\n }\n\n /**\n * Set a specific column order.\n * @param order - Array of field names in desired order\n */\n setColumnOrder(order: string[]): void {\n this.updateColumnOrder(order);\n }\n\n /**\n * Reset column order to the original configuration order.\n */\n resetColumnOrder(): void {\n const originalOrder = this.columns.map((c) => c.field);\n this.updateColumnOrder(originalOrder);\n }\n // #endregion\n\n // #region View Transition\n\n /**\n * Capture header cell positions before reorder.\n */\n private captureHeaderPositions(): Map<string, number> {\n const positions = new Map<string, number>();\n this.gridElement?.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (field) positions.set(field, cell.getBoundingClientRect().left);\n });\n return positions;\n }\n\n /**\n * Apply FLIP animation for column reorder.\n * Uses CSS transitions - JS sets initial transform and toggles class.\n * @param oldPositions - Header positions captured before DOM change\n */\n private animateFLIP(oldPositions: Map<string, number>): void {\n const gridEl = this.gridElement;\n if (!gridEl || oldPositions.size === 0) return;\n\n // Compute deltas from header cells (one per column, stable reference).\n // All cells in the same column share the same horizontal offset.\n const deltas = new Map<string, number>();\n gridEl.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n const oldLeft = oldPositions.get(field);\n if (oldLeft === undefined) return;\n const deltaX = oldLeft - cell.getBoundingClientRect().left;\n if (Math.abs(deltaX) > 1) deltas.set(field, deltaX);\n });\n\n if (deltas.size === 0) return;\n\n // Apply transforms to ALL cells (headers + body).\n // After forceLayout(), body cells are fully rebuilt in new DOM order\n // with correct data-field attributes, so header-derived deltas apply correctly.\n const cells: HTMLElement[] = [];\n gridEl.querySelectorAll('.cell[data-field]').forEach((cell) => {\n const deltaX = deltas.get(cell.getAttribute('data-field') ?? '');\n if (deltaX !== undefined) {\n const el = cell as HTMLElement;\n el.style.transform = `translateX(${deltaX}px)`;\n cells.push(el);\n }\n });\n\n if (cells.length === 0) return;\n\n // Force reflow then animate to final position via CSS transition\n void gridEl.offsetHeight;\n\n const duration = this.animationDuration;\n\n requestAnimationFrame(() => {\n cells.forEach((el) => {\n el.classList.add('flip-animating');\n el.style.transform = '';\n });\n\n // Cleanup after animation\n setTimeout(() => {\n cells.forEach((el) => {\n el.style.transform = '';\n el.classList.remove('flip-animating');\n });\n }, duration + 50);\n });\n }\n\n /**\n * Apply crossfade animation for moved columns.\n * Uses CSS keyframes - JS just toggles classes.\n */\n private animateFade(applyChange: () => void): void {\n const gridEl = this.gridElement;\n if (!gridEl) {\n applyChange();\n return;\n }\n\n // Capture old positions to detect which columns moved\n const oldPositions = this.captureHeaderPositions();\n\n // Apply the change first\n applyChange();\n\n // Find which columns changed position\n const movedFields = new Set<string>();\n gridEl.querySelectorAll('.header-row > .cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (!field) return;\n const oldLeft = oldPositions.get(field);\n if (oldLeft === undefined) return;\n const newLeft = cell.getBoundingClientRect().left;\n if (Math.abs(oldLeft - newLeft) > 1) {\n movedFields.add(field);\n }\n });\n\n if (movedFields.size === 0) return;\n\n // Add animation class to moved columns (headers + body cells)\n const cells: HTMLElement[] = [];\n gridEl.querySelectorAll('.cell[data-field]').forEach((cell) => {\n const field = cell.getAttribute('data-field');\n if (field && movedFields.has(field)) {\n const el = cell as HTMLElement;\n el.classList.add('fade-animating');\n cells.push(el);\n }\n });\n\n if (cells.length === 0) return;\n\n // Remove class after animation completes\n const duration = this.animationDuration;\n setTimeout(() => {\n cells.forEach((el) => el.classList.remove('fade-animating'));\n }, duration + 50);\n }\n\n /**\n * Update column order with configured animation.\n */\n private updateColumnOrder(newOrder: string[]): void {\n const animation = this.animationType;\n\n if (animation === 'flip' && this.gridElement) {\n const oldPositions = this.captureHeaderPositions();\n this.grid.setColumnOrder(newOrder);\n // Force a full render cycle so body cells are rebuilt in new column order.\n // setColumnOrder rebuilds headers synchronously but body cells are async\n // (VIRTUALIZATION phase only patches content in place via fastPatchRow).\n // forceLayout triggers processColumns which bumps the row render epoch,\n // ensuring body cells are fully rebuilt with correct DOM order.\n if (typeof this.grid.forceLayout === 'function') {\n this.grid.forceLayout().then(() => {\n this.animateFLIP(oldPositions);\n });\n } else {\n // Fallback: animate headers only (body cells may not be rebuilt yet)\n requestAnimationFrame(() => {\n this.animateFLIP(oldPositions);\n });\n }\n } else if (animation === 'fade') {\n this.animateFade(() => this.grid.setColumnOrder(newOrder));\n } else {\n this.grid.setColumnOrder(newOrder);\n }\n\n this.grid.requestStateChange?.();\n }\n // #endregion\n}\n"],"names":["moveColumn","columns","fromIndex","toIndex","length","result","removed","splice","ReorderPlugin","BaseGridPlugin","name","aliases","styles","defaultConfig","animation","animationType","this","isAnimationEnabled","config","animationDuration","super","isDragging","draggedField","draggedIndex","dropIndex","draggedGroupFields","internalGrid","grid","canMoveColumnWithPlugins","column","meta","lockPosition","suppressMovable","canMoveColumn","query","includes","clearDragClasses","gridElement","querySelectorAll","forEach","h","classList","remove","attach","addEventListener","e","detail","field","signal","disconnectSignal","detach","afterRender","gridEl","header","headerEl","getAttribute","find","c","draggable","setAttribute","orderIndex","getColumnOrder","indexOf","dataTransfer","effectAllowed","setData","add","preventDefault","rect","getBoundingClientRect","midX","left","width","clientX","f","querySelector","toggle","before","executeGroupBlockMove","effectiveToIndex","newOrder","columnOrder","emitCancelable","updateColumnOrder","queueMicrotask","setupGroupHeaderDrag","gh","groupHeaderEl","groupId","startsWith","fragmentFields","getGroupFragmentFields","every","col","style","cursor","currentOrder","anchorField","_groupId","gridColumn","match","exec","startCol","parseInt","span","visibleColumns","fields","i","push","draggedFields","targetFields","remaining","filter","insertAt","insertIndex","draggedInOrder","onKeyDown","event","altKey","key","focusCol","_focusCol","_visibleColumns","targetColumn","ensureCellVisible","stopPropagation","setColumnOrder","order","resetColumnOrder","originalOrder","map","captureHeaderPositions","positions","Map","cell","set","animateFLIP","oldPositions","size","deltas","oldLeft","get","deltaX","Math","abs","cells","el","transform","offsetHeight","duration","requestAnimationFrame","setTimeout","animateFade","applyChange","movedFields","Set","newLeft","has","forceLayout","then","requestStateChange"],"mappings":"2aAiCO,SAASA,EAAWC,EAAmBC,EAAmBC,GAC/D,GAAID,IAAcC,EAAS,OAAOF,EAClC,GAAIC,EAAY,GAAKA,GAAaD,EAAQG,OAAQ,OAAOH,EACzD,GAAIE,EAAU,GAAKA,EAAUF,EAAQG,OAAQ,OAAOH,EAEpD,MAAMI,EAAS,IAAIJ,IACZK,GAAWD,EAAOE,OAAOL,EAAW,GAE3C,OADAG,EAAOE,OAAOJ,EAAS,EAAGG,GACnBD,C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E,aAAa,cAChC,GAAIR,GAAS2G,EAAYG,IAAI9G,GAAQ,CACnC,MAAMmG,EAAKZ,EACXY,EAAGzG,UAAUyB,IAAI,kBACjB+E,EAAMrC,KAAKsC,EACb,IAGmB,IAAjBD,EAAM7I,OAAc,OAGxB,MAAMiJ,EAAWrI,KAAKG,kBACtBoI,WAAW,KACTN,EAAM1G,QAAS2G,GAAOA,EAAGzG,UAAUC,OAAO,oBACzC2G,EAAW,GAChB,CAKQ,iBAAAlE,CAAkBH,GACxB,MAAMlE,EAAYE,KAAKD,cAEvB,GAAkB,SAAdD,GAAwBE,KAAKqB,YAAa,CAC5C,MAAMoG,EAAezH,KAAKmH,yBAC1BnH,KAAKW,KAAKmG,eAAe9C,GAMY,mBAA1BhE,KAAKW,KAAKmI,YACnB9I,KAAKW,KAAKmI,cAAcC,KAAK,KAC3B/I,KAAKwH,YAAYC,KAInBa,sBAAsB,KACpBtI,KAAKwH,YAAYC,IAGvB,KAAyB,SAAd3H,EACTE,KAAKwI,YAAY,IAAMxI,KAAKW,KAAKmG,eAAe9C,IAEhDhE,KAAKW,KAAKmG,eAAe9C,GAG3BhE,KAAKW,KAAKqI,sBACZ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/diagnostics"),require("../../core/internal/keyboard"),require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/diagnostics","../../core/internal/keyboard","../../core/internal/sanitize","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_responsive={},e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,i,r,s){"use strict";class o extends s.BaseGridPlugin{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={incompatibleWith:[{name:"groupingRows",reason:"Responsive card layout does not yet support row grouping. The variable row heights (cards vs group headers) cause scroll calculation issues."}],queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#e;#t=!1;#i;#r=!1;#s=0;#o=new Set;#n=new Set;#a=null;#d=[];get#h(){return this.grid}isResponsive(){return this.#t}setResponsive(e){e!==this.#t&&(this.#t=e,this.#l(),this.emit("responsive-change",{isResponsive:e,width:this.#s,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#u(this.#s)}setCardRenderer(e){this.config.cardRenderer=e,this.#t&&this.requestRender()}getWidth(){return this.#s}getActiveBreakpoint(){return this.#a}attach(e){super.attach(e),this.#p(),this.#g(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#d=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#e=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#s=t,clearTimeout(this.#i),this.#i=setTimeout(()=>{this.#u(t)},this.config.debounceMs??100)}),this.#e.observe(this.gridElement)}#p(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#h.__frameworkAdapter;if(i?.parseResponsiveCardElement){const e=i.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const s=t.getAttribute("breakpoint"),o=t.getAttribute("card-row-height"),n=t.getAttribute("hidden-columns"),a=t.getAttribute("hide-header"),d=t.getAttribute("debounce-ms"),h={};if(null!==s){const e=parseInt(s,10);isNaN(e)||(h.breakpoint=e)}if(null!==o&&(h.cardRowHeight="auto"===o?"auto":parseInt(o,10)),null!==n&&(h.hiddenColumns=n.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==a&&(h.hideHeader="false"!==a),null!==d){const e=parseInt(d,10);isNaN(e)||(h.debounceMs=e)}const l=t.innerHTML.trim();!l||this.config.cardRenderer||i?.parseResponsiveCardElement||(h.cardRenderer=e=>{const t=r.evalTemplateString(l,{value:e,row:e}),i=r.sanitizeHTML(t),s=document.createElement("div");return s.className="tbw-responsive-card-content",s.innerHTML=i,s}),Object.keys(h).length>0&&(this.config={...this.config,...h})}#g(e){if(this.#o.clear(),this.#n.clear(),e)for(const t of e)"string"==typeof t?this.#o.add(t):t.showValue?this.#n.add(t.field):this.#o.add(t.field)}detach(){this.#e?.disconnect(),this.#e=void 0,clearTimeout(this.#i),this.#i=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#t}afterRender(){this.#c();if(!(this.#d.length>0?null!==this.#a:this.#t))return;const e=this.#o.size>0,t=this.#n.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#o.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#n.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#u(e){if(this.#d.length>0)return void this.#w(e);const i=this.config.breakpoint??0;0!==i||this.#r||(this.#r=!0,this.warn(t.MISSING_BREAKPOINT,"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const r=i>0&&e<i;r!==this.#t&&(this.#t=r,this.#l(),this.emit("responsive-change",{isResponsive:r,width:e,breakpoint:i}),this.requestRender())}#w(e){let t=null;for(const i of this.#d)e<=i.maxWidth&&(t=i);if(t!==this.#a){this.#a=t,t?.hiddenColumns?this.#g(t.hiddenColumns):this.#g(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#t&&(this.#t=i,this.#l()),this.emit("responsive-change",{isResponsive:this.#t,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#v;#l(){this.gridElement.toggleAttribute("data-responsive",this.#t);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.#h;if(this.#t){t._virtualization&&(this.#v=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#v&&this.#v>0&&t._virtualization&&(t._virtualization.rowHeight=this.#v,this.#v=void 0),this.#m=void 0,this.#b=void 0,this.#f=void 0}}renderRow(e,t,i){if(!this.#t||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const s=this.config.cardRowHeight;return t.style.height="auto"===s||void 0===s?"auto":`${this.#R()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#t)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,r=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<r)return this.grid._focusCol+=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),i.ensureCellVisible(this.#h),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=r,e.preventDefault(),i.ensureCellVisible(this.#h),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0}return!1}#m;#b;#f;#R(){if(this.#m&&this.#m>0)return this.#m;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#C(){return this.#b&&this.#b>0?this.#b:this.#v??28}#y(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#k(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#y())return 0;const e=this.#v??28,t=this.#C(),i=this.#R(),{groupCount:r,cardCount:s}=this.#k();return r*Math.max(0,t-e)+s*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#y())return 0;const t=this.#v??28,i=this.#C(),r=this.#R(),s=Math.max(0,i-t),o=Math.max(0,r-t);let n=0,a=0;const d=this.rows,h=Math.min(e,d.length);for(let l=0;l<h;l++)d[l].__isGroupRow?n++:a++;return n*s+a*o}getRowHeight(e,t){if(this.#t&&this.config.cardRenderer)return e.__isGroupRow?this.#C():this.#R()}#H(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#G=!1;#c(){if(!this.#t||!this.config.cardRenderer)return;let e=!1;const t=this.#h,i=this.#y(),r=this.#H();if(r!==this.#f&&(this.#f=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#b&&(this.#b=i,e=!0)}}const s=this.gridElement.querySelector(".data-grid-row.responsive-card");if(s){const r=s.getBoundingClientRect().height;r>0&&r!==this.#m&&(this.#m=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#G&&(this.#G=!0,queueMicrotask(()=>{this.#G=!1,this.grid&&this.#t&&this.#h.refreshVirtualWindow?.(!0,!0)}))}}e.ResponsivePlugin=o,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/diagnostics"),require("../../core/internal/keyboard"),require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/diagnostics","../../core/internal/keyboard","../../core/internal/sanitize","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_responsive={},e.TbwGrid,e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,i,r,s){"use strict";class o extends s.BaseGridPlugin{name="responsive";version="1.0.0";styles='tbw-grid[data-responsive-animate] .data-grid-row,tbw-grid[data-responsive-animate] .data-grid-row>.cell{transition:opacity var(--tbw-responsive-duration, .2s) ease-out,transform var(--tbw-responsive-duration, .2s) ease-out}tbw-grid[data-responsive][data-responsive-animate] .data-grid-row{animation:responsive-card-enter var(--tbw-responsive-duration, .2s) ease-out}@keyframes responsive-card-enter{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}tbw-grid[data-responsive] .header{display:none!important}tbw-grid[data-responsive] .footer-row{display:none}tbw-grid[data-responsive] .tbw-scroll-area{overflow-x:hidden;min-width:0!important}tbw-grid[data-responsive] .rows-body-wrapper{min-width:0!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row){display:block!important;grid-template-columns:none!important;padding:var(--tbw-cell-padding);padding-inline-start:var(--tbw-spacing-xl);border-bottom:1px solid var(--tbw-color-border);min-height:auto!important;height:auto!important;contain:none!important;content-visibility:visible!important;background:var(--tbw-color-bg);position:relative}tbw-grid[data-responsive] .data-grid-row:not(.group-row):nth-child(2n){background:var(--tbw-color-row-alt)}tbw-grid[data-responsive] .data-grid-row:not(.group-row):hover{background:var(--tbw-color-row-hover)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]{background:var(--tbw-color-selection)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)[aria-selected=true]:before{content:"";position:absolute;inset-inline-start:0;top:0;bottom:0;width:4px;background:var(--tbw-color-accent)}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell{display:flex!important;justify-content:space-between;align-items:center;padding:var(--tbw-spacing-xs) var(--tbw-spacing-md);width:100%!important;min-width:0!important;min-height:auto!important;height:auto!important;line-height:1.5!important;position:static!important;left:auto!important;right:auto!important;border:none!important;border-bottom:none!important;border-inline-end:none!important;background:transparent!important;white-space:normal!important;overflow:visible!important}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:before{content:attr(data-header) ": ";font-weight:600;color:var(--tbw-color-header-fg);flex-shrink:0;margin-inline-end:var(--tbw-spacing-md);min-width:100px}tbw-grid[data-responsive] .data-grid-row:not(.group-row)>.cell:after{content:none}tbw-grid[data-responsive] .cell[data-utility]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .data-grid-row>.cell[data-responsive-value-only]:before{display:none!important}tbw-grid:not([data-responsive]) .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .tbw-footer,tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows{display:none!important}tbw-grid[data-responsive] .tbw-pinned-rows,tbw-grid[data-responsive] .tbw-aggregation-rows,tbw-grid[data-responsive] .tbw-aggregation-row{min-width:0!important}tbw-grid[data-responsive] .data-grid-row.responsive-card{display:block!important;padding:var(--tbw-cell-padding);border-bottom:1px solid var(--tbw-color-border)}tbw-grid[data-responsive] .data-grid-row.responsive-card>*{width:100%}tbw-grid[data-responsive] .data-grid-row.responsive-card .cell:before{display:none}';static manifest={queries:[{type:"isCardMode",description:"Returns whether the grid is currently in responsive card mode"}]};#e;#t=!1;#i;#r=!1;#s=0;#o=new Set;#n=new Set;#a=null;#d=[];get#h(){return this.grid}isResponsive(){return this.#t}setResponsive(e){e!==this.#t&&(this.#t=e,this.#l(),this.emit("responsive-change",{isResponsive:e,width:this.#s,breakpoint:this.config.breakpoint??0}),this.requestRender())}setBreakpoint(e){this.config.breakpoint=e,this.#p(this.#s)}setCardRenderer(e){this.config.cardRenderer=e,this.#t&&this.requestRender()}getWidth(){return this.#s}getActiveBreakpoint(){return this.#a}attach(e){super.attach(e),this.#u(),this.#g(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#d=[...this.config.breakpoints].sort((e,t)=>t.maxWidth-e.maxWidth)),this.#e=new ResizeObserver(e=>{const t=e[0]?.contentRect.width??0;this.#s=t,clearTimeout(this.#i),this.#i=setTimeout(()=>{this.#p(t)},this.config.debounceMs??100)}),this.#e.observe(this.gridElement)}#u(){const e=this.gridElement;if(!e)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const i=this.#h.__frameworkAdapter;if(i?.parseResponsiveCardElement){const e=i.parseResponsiveCardElement(t);e&&(this.config={...this.config,cardRenderer:e})}const s=t.getAttribute("breakpoint"),o=t.getAttribute("card-row-height"),n=t.getAttribute("hidden-columns"),a=t.getAttribute("hide-header"),d=t.getAttribute("debounce-ms"),h={};if(null!==s){const e=parseInt(s,10);isNaN(e)||(h.breakpoint=e)}if(null!==o&&(h.cardRowHeight="auto"===o?"auto":parseInt(o,10)),null!==n&&(h.hiddenColumns=n.split(",").map(e=>e.trim()).filter(e=>e.length>0)),null!==a&&(h.hideHeader="false"!==a),null!==d){const e=parseInt(d,10);isNaN(e)||(h.debounceMs=e)}const l=t.innerHTML.trim();!l||this.config.cardRenderer||i?.parseResponsiveCardElement||(h.cardRenderer=e=>{const t=r.evalTemplateString(l,{value:e,row:e}),i=r.sanitizeHTML(t),s=document.createElement("div");return s.className="tbw-responsive-card-content",s.innerHTML=i,s}),Object.keys(h).length>0&&(this.config={...this.config,...h})}#g(e){if(this.#o.clear(),this.#n.clear(),e)for(const t of e)"string"==typeof t?this.#o.add(t):t.showValue?this.#n.add(t.field):this.#o.add(t.field)}detach(){this.#e?.disconnect(),this.#e=void 0,clearTimeout(this.#i),this.#i=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(e){if("isCardMode"===e.type)return this.#t}afterRender(){this.#c();if(!(this.#d.length>0?null!==this.#a:this.#t))return;const e=this.#o.size>0,t=this.#n.size>0;if(!e&&!t)return;const i=this.gridElement.querySelectorAll(".cell[data-field]");for(const r of i){const e=r.getAttribute("data-field");e&&(this.#o.has(e)?(r.setAttribute("data-responsive-hidden",""),r.removeAttribute("data-responsive-value-only")):this.#n.has(e)?(r.setAttribute("data-responsive-value-only",""),r.removeAttribute("data-responsive-hidden")):(r.removeAttribute("data-responsive-hidden"),r.removeAttribute("data-responsive-value-only")))}}#p(e){if(this.#d.length>0)return void this.#w(e);const i=this.config.breakpoint??0;0!==i||this.#r||(this.#r=!0,this.warn(t.MISSING_BREAKPOINT,"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const r=i>0&&e<i;r!==this.#t&&(this.#t=r,this.#l(),this.emit("responsive-change",{isResponsive:r,width:e,breakpoint:i}),this.requestRender())}#w(e){let t=null;for(const i of this.#d)e<=i.maxWidth&&(t=i);if(t!==this.#a){this.#a=t,t?.hiddenColumns?this.#g(t.hiddenColumns):this.#g(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#t&&(this.#t=i,this.#l()),this.emit("responsive-change",{isResponsive:this.#t,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#v;#l(){this.gridElement.toggleAttribute("data-responsive",this.#t);const e=!1!==this.config.animate;this.gridElement.toggleAttribute("data-responsive-animate",e),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const t=this.#h;if(this.#t){t._virtualization&&(this.#v=t._virtualization.rowHeight);const e=this.gridElement.querySelector(".tbw-scroll-area");e&&(e.scrollLeft=0)}else{const e=this.gridElement.querySelectorAll(".data-grid-row");for(const t of e)t.style.height="",t.classList.remove("responsive-card");this.#v&&this.#v>0&&t._virtualization&&(t._virtualization.rowHeight=this.#v,this.#v=void 0),this.#m=void 0,this.#b=void 0,this.#f=void 0}}renderRow(e,t,i){if(!this.#t||!this.config.cardRenderer)return;if(e.__isGroupRow)return;t.replaceChildren();const r=this.config.cardRenderer(e,i);t.className="data-grid-row responsive-card";const s=this.config.cardRowHeight;return t.style.height="auto"===s||void 0===s?"auto":`${this.#R()}px`,t.appendChild(r),!0}onKeyDown(e){if(!this.#t)return!1;if(this.config.cardRenderer){if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return!1}const t=this.rows.length-1,r=this.visibleColumns.length-1;switch(e.key){case"ArrowDown":if(this.grid._focusCol<r)return this.grid._focusCol+=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0;if(this.grid._focusRow<t)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),i.ensureCellVisible(this.#h),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=r,e.preventDefault(),i.ensureCellVisible(this.#h),!0;break;case"ArrowRight":if(this.grid._focusRow<t)return this.grid._focusRow+=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),i.ensureCellVisible(this.#h),!0}return!1}#m;#b;#f;#R(){if(this.#m&&this.#m>0)return this.#m;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#C(){return this.#b&&this.#b>0?this.#b:this.#v??28}#y(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#k(){let e=0,t=0;for(const i of this.rows)i.__isGroupRow?e++:t++;return{groupCount:e,cardCount:t}}getExtraHeight(){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#y())return 0;const e=this.#v??28,t=this.#C(),i=this.#R(),{groupCount:r,cardCount:s}=this.#k();return r*Math.max(0,t-e)+s*Math.max(0,i-e)}getExtraHeightBefore(e){if(!this.#t||!this.config.cardRenderer)return 0;if(!this.#y())return 0;const t=this.#v??28,i=this.#C(),r=this.#R(),s=Math.max(0,i-t),o=Math.max(0,r-t);let n=0,a=0;const d=this.rows,h=Math.min(e,d.length);for(let l=0;l<h;l++)d[l].__isGroupRow?n++:a++;return n*s+a*o}getRowHeight(e,t){if(this.#t&&this.config.cardRenderer)return e.__isGroupRow?this.#C():this.#R()}#H(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#G=!1;#c(){if(!this.#t)return;let e=!1;const t=this.#h,i=this.#y(),r=this.#H();if(r!==this.#f&&(this.#f=r,e=!0),i){const t=this.gridElement.querySelector(".data-grid-row.group-row");if(t){const i=t.getBoundingClientRect().height;i>0&&i!==this.#b&&(this.#b=i,e=!0)}}const s=this.config.cardRenderer?".data-grid-row.responsive-card":".data-grid-row:not(.group-row)",o=this.gridElement.querySelector(s);if(o){const r=o.getBoundingClientRect().height;r>0&&r!==this.#m&&(this.#m=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#G&&(this.#G=!0,queueMicrotask(()=>{this.#G=!1,this.grid&&this.#t&&this.#h.refreshVirtualWindow?.(!0,!0)}))}}e.ResponsivePlugin=o,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=responsive.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responsive.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/responsive/ResponsivePlugin.ts"],"sourcesContent":["/**\n * Responsive Plugin\n *\n * Transforms the grid from tabular layout to a card/list layout when the grid\n * width falls below a configurable breakpoint. This enables grids to work in\n * narrow containers (split-pane UIs, mobile viewports, dashboard widgets).\n *\n * ## Installation\n *\n * ```ts\n * import { ResponsivePlugin } from '@toolbox-web/grid/plugins/responsive';\n *\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * ## How It Works\n *\n * 1. ResizeObserver monitors the grid element's width\n * 2. When `width < breakpoint`, adds `data-responsive` attribute to grid\n * 3. CSS transforms cells from horizontal to vertical layout\n * 4. Each cell displays \"Header: Value\" using CSS `::before` pseudo-element\n *\n * @see [Responsive Demo](?path=/story/grid-plugins-responsive--default)\n */\n\nimport { MISSING_BREAKPOINT } from '../../core/internal/diagnostics';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, type GridElement, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport styles from './responsive.css?inline';\nimport type { BreakpointConfig, HiddenColumnConfig, ResponsiveChangeDetail, ResponsivePluginConfig } from './types';\n\n/**\n * Responsive Plugin for tbw-grid\n *\n * Adds automatic card layout mode when the grid width falls below a configurable\n * breakpoint. Perfect for responsive designs, split-pane UIs, and mobile viewports.\n *\n * @template T The row data type\n *\n * @example\n * ```ts\n * // Basic usage - switch to card layout below 500px\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Hide less important columns in card mode\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 600,\n * hiddenColumns: ['createdAt', 'updatedAt'],\n * }),\n * ],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Custom card renderer for advanced layouts\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 400,\n * cardRenderer: (row) => {\n * const card = document.createElement('div');\n * card.className = 'custom-card';\n * card.innerHTML = `<strong>${row.name}</strong><br>${row.email}`;\n * return card;\n * },\n * }),\n * ],\n * };\n * ```\n */\nexport class ResponsivePlugin<T = unknown> extends BaseGridPlugin<ResponsivePluginConfig<T>> {\n readonly name = 'responsive';\n override readonly version = '1.0.0';\n override readonly styles = styles;\n\n /**\n * Plugin manifest declaring incompatibilities with other plugins.\n */\n static override readonly manifest: PluginManifest = {\n incompatibleWith: [\n {\n name: 'groupingRows',\n reason:\n 'Responsive card layout does not yet support row grouping. ' +\n 'The variable row heights (cards vs group headers) cause scroll calculation issues.',\n },\n ],\n queries: [\n {\n type: 'isCardMode',\n description: 'Returns whether the grid is currently in responsive card mode',\n },\n ],\n };\n\n #resizeObserver?: ResizeObserver;\n #isResponsive = false;\n #debounceTimer?: ReturnType<typeof setTimeout>;\n #warnedAboutMissingBreakpoint = false;\n #currentWidth = 0;\n /** Set of column fields to completely hide */\n #hiddenColumnSet: Set<string> = new Set();\n /** Set of column fields to show value only (no header label) */\n #valueOnlyColumnSet: Set<string> = new Set();\n /** Currently active breakpoint, or null if none */\n #activeBreakpoint: BreakpointConfig | null = null;\n /** Sorted breakpoints from largest to smallest */\n #sortedBreakpoints: BreakpointConfig[] = [];\n\n /** Typed internal grid accessor — centralizes the single required cast. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if currently in responsive mode.\n * @returns `true` if the grid is in card layout mode\n */\n isResponsive(): boolean {\n return this.#isResponsive;\n }\n\n /**\n * Force responsive mode regardless of width.\n * Useful for testing or manual control.\n * @param enabled - Whether to enable responsive mode\n */\n setResponsive(enabled: boolean): void {\n if (enabled !== this.#isResponsive) {\n this.#isResponsive = enabled;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: enabled,\n width: this.#currentWidth,\n breakpoint: this.config.breakpoint ?? 0,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Update breakpoint dynamically.\n * @param width - New breakpoint width in pixels\n */\n setBreakpoint(width: number): void {\n this.config.breakpoint = width;\n this.#checkBreakpoint(this.#currentWidth);\n }\n\n /**\n * Set a custom card renderer.\n * This allows framework adapters to provide template-based renderers at runtime.\n * @param renderer - The card renderer function, or undefined to use default\n */\n setCardRenderer(renderer: ResponsivePluginConfig<T>['cardRenderer']): void {\n this.config.cardRenderer = renderer;\n // If already in responsive mode, trigger a re-render to apply the new renderer\n if (this.#isResponsive) {\n this.requestRender();\n }\n }\n\n /**\n * Get current grid width.\n * @returns Width of the grid element in pixels\n */\n getWidth(): number {\n return this.#currentWidth;\n }\n\n /**\n * Get the currently active breakpoint config (multi-breakpoint mode only).\n * @returns The active BreakpointConfig, or null if no breakpoint is active\n */\n getActiveBreakpoint(): BreakpointConfig | null {\n return this.#activeBreakpoint;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Parse light DOM configuration first (may update this.config)\n this.#parseLightDomCard();\n\n // Build hidden column sets from config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n\n // Sort breakpoints from largest to smallest for evaluation\n if (this.config.breakpoints?.length) {\n this.#sortedBreakpoints = [...this.config.breakpoints].sort((a, b) => b.maxWidth - a.maxWidth);\n }\n\n // Observe the grid element itself (not internal viewport)\n // This captures the container width including when shell panels open/close\n this.#resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width ?? 0;\n this.#currentWidth = width;\n\n // Debounce to avoid thrashing during resize drag\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = setTimeout(() => {\n this.#checkBreakpoint(width);\n }, this.config.debounceMs ?? 100);\n });\n\n this.#resizeObserver.observe(this.gridElement);\n }\n\n // #region Light DOM Parsing\n\n /**\n * Parse `<tbw-grid-responsive-card>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-responsive-card breakpoint=\"500\" card-row-height=\"80\">\n * <div class=\"custom-card\">\n * <strong>{{ row.name }}</strong>\n * <span>{{ row.email }}</span>\n * </div>\n * </tbw-grid-responsive-card>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `breakpoint`: number - Width threshold for responsive mode\n * - `card-row-height`: number | 'auto' - Card height (default: 'auto')\n * - `hidden-columns`: string - Comma-separated fields to hide\n * - `hide-header`: 'true' | 'false' - Hide header row (default: 'true')\n * - `debounce-ms`: number - Resize debounce delay (default: 100)\n */\n #parseLightDomCard(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const cardEl = gridEl.querySelector('tbw-grid-responsive-card');\n if (!cardEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., React adapter intercepts for JSX rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseResponsiveCardElement) {\n const adapterRenderer = adapter.parseResponsiveCardElement(cardEl);\n if (adapterRenderer) {\n this.config = { ...this.config, cardRenderer: adapterRenderer };\n // Continue to parse attributes even if adapter provides renderer\n }\n }\n\n // Parse attributes for configuration\n const breakpointAttr = cardEl.getAttribute('breakpoint');\n const cardRowHeightAttr = cardEl.getAttribute('card-row-height');\n const hiddenColumnsAttr = cardEl.getAttribute('hidden-columns');\n const hideHeaderAttr = cardEl.getAttribute('hide-header');\n const debounceMsAttr = cardEl.getAttribute('debounce-ms');\n\n const configUpdates: Partial<ResponsivePluginConfig<T>> = {};\n\n if (breakpointAttr !== null) {\n const breakpoint = parseInt(breakpointAttr, 10);\n if (!isNaN(breakpoint)) {\n configUpdates.breakpoint = breakpoint;\n }\n }\n\n if (cardRowHeightAttr !== null) {\n configUpdates.cardRowHeight = cardRowHeightAttr === 'auto' ? 'auto' : parseInt(cardRowHeightAttr, 10);\n }\n\n if (hiddenColumnsAttr !== null) {\n // Parse comma-separated field names\n configUpdates.hiddenColumns = hiddenColumnsAttr\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n if (hideHeaderAttr !== null) {\n configUpdates.hideHeader = hideHeaderAttr !== 'false';\n }\n\n if (debounceMsAttr !== null) {\n const debounceMs = parseInt(debounceMsAttr, 10);\n if (!isNaN(debounceMs)) {\n configUpdates.debounceMs = debounceMs;\n }\n }\n\n // Get template content from innerHTML (only if no renderer already set)\n const templateHTML = cardEl.innerHTML.trim();\n if (templateHTML && !this.config.cardRenderer && !adapter?.parseResponsiveCardElement) {\n // Create a template-based renderer using the inner HTML\n configUpdates.cardRenderer = (row: T): HTMLElement => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row: row as Record<string, unknown> });\n // Sanitize the result to prevent XSS\n const sanitized = sanitizeHTML(evaluated);\n const container = document.createElement('div');\n container.className = 'tbw-responsive-card-content';\n container.innerHTML = sanitized;\n return container;\n };\n }\n\n // Merge updates into config (light DOM values override constructor config)\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n /**\n * Build the hidden and value-only column sets from config.\n */\n #buildHiddenColumnSets(hiddenColumns?: HiddenColumnConfig[]): void {\n this.#hiddenColumnSet.clear();\n this.#valueOnlyColumnSet.clear();\n\n if (!hiddenColumns) return;\n\n for (const col of hiddenColumns) {\n if (typeof col === 'string') {\n this.#hiddenColumnSet.add(col);\n } else if (col.showValue) {\n this.#valueOnlyColumnSet.add(col.field);\n } else {\n this.#hiddenColumnSet.add(col.field);\n }\n }\n }\n\n override detach(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = undefined;\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = undefined;\n\n // Clean up attribute\n if (this.gridElement) {\n this.gridElement.removeAttribute('data-responsive');\n }\n\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isCardMode') {\n return this.#isResponsive;\n }\n return undefined;\n }\n\n /**\n * Apply hidden and value-only columns.\n * In legacy mode (single breakpoint), only applies when in responsive mode.\n * In multi-breakpoint mode, applies whenever there's an active breakpoint.\n */\n override afterRender(): void {\n // Measure card height for virtualization calculations\n this.#measureCardHeightFromDOM();\n\n // In single breakpoint mode, only apply when responsive\n // In multi-breakpoint mode, apply when there's an active breakpoint\n const shouldApply = this.#sortedBreakpoints.length > 0 ? this.#activeBreakpoint !== null : this.#isResponsive;\n\n if (!shouldApply) {\n return;\n }\n\n const hasHiddenColumns = this.#hiddenColumnSet.size > 0;\n const hasValueOnlyColumns = this.#valueOnlyColumnSet.size > 0;\n\n if (!hasHiddenColumns && !hasValueOnlyColumns) {\n return;\n }\n\n // Mark cells for hidden columns and value-only columns\n const cells = this.gridElement.querySelectorAll('.cell[data-field]');\n for (const cell of cells) {\n const field = cell.getAttribute('data-field');\n if (!field) continue;\n\n // Apply hidden attribute\n if (this.#hiddenColumnSet.has(field)) {\n cell.setAttribute('data-responsive-hidden', '');\n cell.removeAttribute('data-responsive-value-only');\n }\n // Apply value-only attribute (shows value without header label)\n else if (this.#valueOnlyColumnSet.has(field)) {\n cell.setAttribute('data-responsive-value-only', '');\n cell.removeAttribute('data-responsive-hidden');\n }\n // Clear any previous responsive attributes\n else {\n cell.removeAttribute('data-responsive-hidden');\n cell.removeAttribute('data-responsive-value-only');\n }\n }\n }\n\n /**\n * Check if width has crossed any breakpoint threshold.\n * Handles both single breakpoint (legacy) and multi-breakpoint modes.\n */\n #checkBreakpoint(width: number): void {\n // Multi-breakpoint mode\n if (this.#sortedBreakpoints.length > 0) {\n this.#checkMultiBreakpoint(width);\n return;\n }\n\n // Legacy single breakpoint mode\n const breakpoint = this.config.breakpoint ?? 0;\n\n // Warn once if breakpoint not configured (0 means never responsive)\n if (breakpoint === 0 && !this.#warnedAboutMissingBreakpoint) {\n this.#warnedAboutMissingBreakpoint = true;\n this.warn(\n MISSING_BREAKPOINT,\n \"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count.\",\n );\n }\n\n const shouldBeResponsive = breakpoint > 0 && width < breakpoint;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: shouldBeResponsive,\n width,\n breakpoint,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Check breakpoints in multi-breakpoint mode.\n * Evaluates breakpoints from largest to smallest, applying the first match.\n */\n #checkMultiBreakpoint(width: number): void {\n // Find the active breakpoint (first one where width <= maxWidth)\n // Since sorted largest to smallest, we find the largest matching breakpoint\n let newActiveBreakpoint: BreakpointConfig | null = null;\n\n for (const bp of this.#sortedBreakpoints) {\n if (width <= bp.maxWidth) {\n newActiveBreakpoint = bp;\n // Continue to find the most specific (smallest) matching breakpoint\n }\n }\n\n // Check if breakpoint changed\n const breakpointChanged = newActiveBreakpoint !== this.#activeBreakpoint;\n\n if (breakpointChanged) {\n this.#activeBreakpoint = newActiveBreakpoint;\n\n // Update hidden column sets from active breakpoint\n if (newActiveBreakpoint?.hiddenColumns) {\n this.#buildHiddenColumnSets(newActiveBreakpoint.hiddenColumns);\n } else {\n // Fall back to top-level hiddenColumns config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n }\n\n // Determine if we should be in card layout\n const shouldBeResponsive = newActiveBreakpoint?.cardLayout === true;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n }\n\n // Emit event for any breakpoint change\n this.emit('responsive-change', {\n isResponsive: this.#isResponsive,\n width,\n breakpoint: newActiveBreakpoint?.maxWidth ?? 0,\n } satisfies ResponsiveChangeDetail);\n\n this.requestRender();\n }\n }\n\n /** Original row height before entering responsive mode, for restoration on exit */\n #originalRowHeight?: number;\n\n /**\n * Apply the responsive state to the grid element.\n * Handles scroll reset when entering responsive mode and row height restoration on exit.\n */\n #applyResponsiveState(): void {\n this.gridElement.toggleAttribute('data-responsive', this.#isResponsive);\n\n // Apply animation attribute if enabled (default: true)\n const animate = this.config.animate !== false;\n this.gridElement.toggleAttribute('data-responsive-animate', animate);\n\n // Set custom animation duration if provided\n if (this.config.animationDuration) {\n this.gridElement.style.setProperty('--tbw-responsive-duration', `${this.config.animationDuration}ms`);\n }\n\n // Cast to internal type for virtualization access\n const internalGrid = this.#internalGrid;\n\n if (this.#isResponsive) {\n // Store original row height before responsive mode changes it\n if (internalGrid._virtualization) {\n this.#originalRowHeight = internalGrid._virtualization.rowHeight;\n }\n\n // Reset horizontal scroll position when entering responsive mode\n // The CSS hides overflow but doesn't reset the scroll position\n const scrollArea = this.gridElement.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (scrollArea) {\n scrollArea.scrollLeft = 0;\n }\n } else {\n // Exiting responsive mode - clean up inline styles set by renderRow\n // The rows are reused from the pool, so we need to remove the card-specific styles\n const rows = this.gridElement.querySelectorAll('.data-grid-row');\n for (const row of rows) {\n (row as HTMLElement).style.height = '';\n row.classList.remove('responsive-card');\n }\n\n // Restore original row height\n if (this.#originalRowHeight && this.#originalRowHeight > 0 && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = this.#originalRowHeight;\n this.#originalRowHeight = undefined;\n }\n\n // Clear cached measurements so they're remeasured fresh when re-entering responsive mode\n // Without this, stale measurements cause incorrect height calculations after scrolling\n this.#measuredCardHeight = undefined;\n this.#measuredGroupRowHeight = undefined;\n this.#lastCardRowCount = undefined;\n }\n }\n\n /**\n * Custom row rendering when cardRenderer is provided and in responsive mode.\n *\n * When a cardRenderer is configured, this hook takes over row rendering to display\n * the custom card layout instead of the default cell structure.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if rendered (prevents default), `void` for default rendering\n */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean | void {\n // Only override when in responsive mode AND cardRenderer is provided\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return; // Let default rendering proceed\n }\n\n // Skip group rows from GroupingRowsPlugin - they have special structure\n // and should use their own renderer\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return; // Let GroupingRowsPlugin handle group row rendering\n }\n\n // Clear existing content\n rowEl.replaceChildren();\n\n // Call user's cardRenderer to get custom content\n const cardContent = this.config.cardRenderer(row as T, rowIndex);\n\n // Reset className - clears any stale classes from previous use (e.g., 'group-row' from recycled element)\n // This follows the same pattern as GroupingRowsPlugin which sets className explicitly\n rowEl.className = 'data-grid-row responsive-card';\n\n // Handle card row height — when a numeric height is configured, use the effective\n // height from #getCardHeight() which incorporates DOM measurement after first render.\n // This keeps inline height in sync with the position cache used for virtualization.\n const configuredHeight = this.config.cardRowHeight;\n if (configuredHeight === 'auto' || configuredHeight === undefined) {\n rowEl.style.height = 'auto';\n } else {\n rowEl.style.height = `${this.#getCardHeight()}px`;\n }\n\n // Append the custom card content\n rowEl.appendChild(cardContent);\n\n return true; // We handled rendering\n }\n\n /**\n * Handle keyboard navigation in responsive mode.\n *\n * In responsive mode, the visual layout is inverted:\n * - Cells are stacked vertically within each \"card\" (row)\n * - DOWN/UP visually moves within the card (between fields)\n * - Page Down/Page Up or Ctrl+Down/Up moves between cards\n *\n * For custom cardRenderers, keyboard navigation is disabled entirely\n * since the implementor controls the card content and should handle\n * navigation via their own event handlers.\n *\n * @returns `true` if the event was handled and default behavior should be prevented\n */\n override onKeyDown(e: KeyboardEvent): boolean {\n if (!this.#isResponsive) {\n return false;\n }\n\n // If custom cardRenderer is provided, disable grid's keyboard navigation\n // The implementor is responsible for their own navigation\n if (this.config.cardRenderer) {\n const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];\n if (navKeys.includes(e.key)) {\n // Let the event bubble - implementor can handle it\n return false;\n }\n }\n\n // Swap arrow key behavior for CSS-only responsive mode\n // In card layout, cells are stacked vertically:\n // Card 1: Card 2:\n // ID: 1 ID: 2\n // Name: Alice Name: Bob <- ArrowRight goes here\n // Dept: Eng Dept: Mkt\n // ↓ ArrowDown goes here\n //\n // ArrowDown/Up = move within card (change column/field)\n // ArrowRight/Left = move between cards (change row)\n const maxRow = this.rows.length - 1;\n const maxCol = this.visibleColumns.length - 1;\n\n switch (e.key) {\n case 'ArrowDown':\n // Move down WITHIN card (to next field/column)\n if (this.grid._focusCol < maxCol) {\n this.grid._focusCol += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At bottom of card - optionally move to next card's first field\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n this.grid._focusCol = 0;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowUp':\n // Move up WITHIN card (to previous field/column)\n if (this.grid._focusCol > 0) {\n this.grid._focusCol -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At top of card - optionally move to previous card's last field\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n this.grid._focusCol = maxCol;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowRight':\n // Move to NEXT card (same field)\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowLeft':\n // Move to PREVIOUS card (same field)\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n }\n\n return false;\n }\n\n // ============================================\n // Variable Height Support for Mixed Row Types\n // ============================================\n\n /** Measured card height from DOM for virtualization calculations */\n #measuredCardHeight?: number;\n\n /** Measured group row height from DOM for virtualization calculations */\n #measuredGroupRowHeight?: number;\n\n /** Last known card row count for detecting changes (e.g., group expand/collapse) */\n #lastCardRowCount?: number;\n\n /**\n * Get the effective card height for virtualization calculations.\n * Prioritizes DOM-measured height (actual rendered size) over config,\n * since content can overflow the configured height.\n */\n #getCardHeight(): number {\n // Prefer measured height - it reflects actual rendered size including overflow\n if (this.#measuredCardHeight && this.#measuredCardHeight > 0) {\n return this.#measuredCardHeight;\n }\n // Fall back to explicit config\n const configHeight = this.config.cardRowHeight;\n if (typeof configHeight === 'number' && configHeight > 0) {\n return configHeight;\n }\n // Default fallback\n return 80;\n }\n\n /**\n * Get the effective group row height for virtualization calculations.\n * Uses DOM-measured height, falling back to original row height.\n */\n #getGroupRowHeight(): number {\n if (this.#measuredGroupRowHeight && this.#measuredGroupRowHeight > 0) {\n return this.#measuredGroupRowHeight;\n }\n // Fall back to original row height (before responsive mode)\n return this.#originalRowHeight ?? 28;\n }\n\n /**\n * Check if there are any group rows in the current dataset.\n * Used to determine if we have mixed row heights.\n */\n #hasGroupRows(): boolean {\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Count group rows and card rows in the current dataset.\n */\n #countRowTypes(): { groupCount: number; cardCount: number } {\n let groupCount = 0;\n let cardCount = 0;\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n groupCount++;\n } else {\n cardCount++;\n }\n }\n return { groupCount, cardCount };\n }\n\n /**\n * Return total extra height contributed by mixed row heights.\n * This is called by the grid's virtualization system to adjust scrollbar height.\n *\n * The grid calculates: totalRows * baseRowHeight + pluginExtraHeight\n *\n * For mixed layouts (groups + cards), we need to report the difference between\n * actual heights and what the base calculation assumes:\n * - Extra for groups: groupCount * (groupHeight - baseHeight)\n * - Extra for cards: cardCount * (cardHeight - baseHeight)\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeight(): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types (groups + cards)\n // If all rows are cards, we update the virtualization row height instead\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const { groupCount, cardCount } = this.#countRowTypes();\n\n // Calculate extra height for both row types\n const groupExtra = groupCount * Math.max(0, groupHeight - baseHeight);\n const cardExtra = cardCount * Math.max(0, cardHeight - baseHeight);\n\n return groupExtra + cardExtra;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * Used by virtualization to correctly calculate scroll positions.\n *\n * Like getExtraHeight, this accounts for both group and card row heights.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const groupHeightDiff = Math.max(0, groupHeight - baseHeight);\n const cardHeightDiff = Math.max(0, cardHeight - baseHeight);\n\n // Count group rows and card rows before the given index\n let groupsBefore = 0;\n let cardsBefore = 0;\n const rows = this.rows;\n const maxIndex = Math.min(beforeRowIndex, rows.length);\n\n for (let i = 0; i < maxIndex; i++) {\n if ((rows[i] as { __isGroupRow?: boolean }).__isGroupRow) {\n groupsBefore++;\n } else {\n cardsBefore++;\n }\n }\n\n return groupsBefore * groupHeightDiff + cardsBefore * cardHeightDiff;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.#internalGrid;\n const hasGroups = this.#hasGroupRows();\n\n // Check if card row count changed (e.g., group expanded/collapsed)\n const currentCardRowCount = this.#countCardRows();\n if (currentCardRowCount !== this.#lastCardRowCount) {\n this.#lastCardRowCount = currentCardRowCount;\n needsRefresh = true;\n }\n\n // Measure actual group row height from DOM (for mixed layouts)\n if (hasGroups) {\n const groupRow = this.gridElement.querySelector('.data-grid-row.group-row') as HTMLElement | null;\n if (groupRow) {\n const height = groupRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredGroupRowHeight) {\n this.#measuredGroupRowHeight = height;\n needsRefresh = true;\n }\n }\n }\n\n // Measure actual card height from DOM\n const cardRow = this.gridElement.querySelector('.data-grid-row.responsive-card') as HTMLElement | null;\n if (cardRow) {\n const height = cardRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredCardHeight) {\n this.#measuredCardHeight = height;\n needsRefresh = true;\n\n // For uniform card layouts (no groups), update virtualization row height directly\n // This ensures proper row recycling and translateY calculations\n if (!hasGroups && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = height;\n }\n }\n }\n\n // Defer virtualization refresh to avoid nested render cycles\n // This is called from afterRender, so we can't call refreshVirtualWindow synchronously\n // Use scheduler's VIRTUALIZATION phase to batch properly and avoid duplicate afterRender calls\n if (needsRefresh && !this.#pendingRefresh) {\n this.#pendingRefresh = true;\n queueMicrotask(() => {\n this.#pendingRefresh = false;\n // Only refresh if still attached and in responsive mode\n if (this.grid && this.#isResponsive) {\n // Request virtualization phase through grid's public API\n // This goes through the scheduler which batches and handles afterRender properly\n this.#internalGrid.refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","name","version","styles","static","incompatibleWith","reason","queries","type","description","resizeObserver","isResponsive","debounceTimer","warnedAboutMissingBreakpoint","currentWidth","hiddenColumnSet","Set","valueOnlyColumnSet","activeBreakpoint","sortedBreakpoints","internalGrid","this","grid","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","requestRender","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","getWidth","getActiveBreakpoint","attach","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","cardEl","querySelector","adapter","__frameworkAdapter","parseResponsiveCardElement","adapterRenderer","breakpointAttr","getAttribute","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","parseInt","isNaN","cardRowHeight","split","map","s","trim","filter","hideHeader","templateHTML","innerHTML","row","evaluated","evalTemplateString","value","sanitized","sanitizeHTML","container","document","createElement","className","Object","keys","clear","col","add","showValue","field","detach","disconnect","removeAttribute","handleQuery","query","afterRender","measureCardHeightFromDOM","hasHiddenColumns","size","hasValueOnlyColumns","cells","querySelectorAll","cell","has","setAttribute","checkMultiBreakpoint","warn","MISSING_BREAKPOINT","shouldBeResponsive","newActiveBreakpoint","bp","cardLayout","originalRowHeight","toggleAttribute","animate","animationDuration","style","setProperty","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","configuredHeight","getCardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","configHeight","getGroupRowHeight","hasGroupRows","countRowTypes","groupCount","cardCount","getExtraHeight","baseHeight","groupHeight","cardHeight","Math","max","getExtraHeightBefore","beforeRowIndex","groupHeightDiff","cardHeightDiff","groupsBefore","cardsBefore","maxIndex","min","i","getRowHeight","_index","countCardRows","count","pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","getBoundingClientRect","cardRow","queueMicrotask","refreshVirtualWindow"],"mappings":"mlBAkFO,MAAMA,UAAsCC,EAAAA,eACxCC,KAAO,aACEC,QAAU,QACVC,8hHAKlBC,gBAAoD,CAClDC,iBAAkB,CAChB,CACEJ,KAAM,eACNK,OACE,iJAINC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,OAAuCD,IAEvCE,GAA6C,KAE7CC,GAAyC,GAGzC,KAAIC,GACF,OAAOC,KAAKC,IACd,CAMA,YAAAX,GACE,OAAOU,MAAKV,CACd,CAOA,aAAAY,CAAcC,GACRA,IAAYH,MAAKV,IACnBU,MAAKV,EAAgBa,EACrBH,MAAKI,IACLJ,KAAKK,KAAK,oBAAqB,CAC7Bf,aAAca,EACdG,MAAON,MAAKP,EACZc,WAAYP,KAAKQ,OAAOD,YAAc,IAExCP,KAAKS,gBAET,CAMA,aAAA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CACF,CAGA,MAAMK,EAAUxK,KAAKmC,YAAYG,cAAc,kCAC/C,GAAIkI,EAAS,CACX,MAAMzD,EAASyD,EAAQD,wBAAwBxD,OAC3CA,EAAS,GAAKA,IAAW/G,MAAKkH,IAChClH,MAAKkH,EAAsBH,EAC3BoD,GAAe,GAIVC,GAAarK,EAAa2G,kBAC7B3G,EAAa2G,gBAAgBC,UAAYI,GAG/C,CAKIoD,IAAiBnK,MAAKkK,IACxBlK,MAAKkK,GAAkB,EACvBO,eAAe,KACbzK,MAAKkK,GAAkB,EAEnBlK,KAAKC,MAAQD,MAAKV,GAGpBU,MAAKD,EAAc2K,wBAAuB,GAAM,KAIxD"}
|
|
1
|
+
{"version":3,"file":"responsive.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/responsive/ResponsivePlugin.ts"],"sourcesContent":["/**\n * Responsive Plugin\n *\n * Transforms the grid from tabular layout to a card/list layout when the grid\n * width falls below a configurable breakpoint. This enables grids to work in\n * narrow containers (split-pane UIs, mobile viewports, dashboard widgets).\n *\n * ## Installation\n *\n * ```ts\n * import { ResponsivePlugin } from '@toolbox-web/grid/plugins/responsive';\n *\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * ## How It Works\n *\n * 1. ResizeObserver monitors the grid element's width\n * 2. When `width < breakpoint`, adds `data-responsive` attribute to grid\n * 3. CSS transforms cells from horizontal to vertical layout\n * 4. Each cell displays \"Header: Value\" using CSS `::before` pseudo-element\n *\n * @see [Responsive Demo](?path=/story/grid-plugins-responsive--default)\n */\n\nimport { MISSING_BREAKPOINT } from '../../core/internal/diagnostics';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, type GridElement, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport styles from './responsive.css?inline';\nimport type { BreakpointConfig, HiddenColumnConfig, ResponsiveChangeDetail, ResponsivePluginConfig } from './types';\n\n/**\n * Responsive Plugin for tbw-grid\n *\n * Adds automatic card layout mode when the grid width falls below a configurable\n * breakpoint. Perfect for responsive designs, split-pane UIs, and mobile viewports.\n *\n * @template T The row data type\n *\n * @example\n * ```ts\n * // Basic usage - switch to card layout below 500px\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Hide less important columns in card mode\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 600,\n * hiddenColumns: ['createdAt', 'updatedAt'],\n * }),\n * ],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Custom card renderer for advanced layouts\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 400,\n * cardRenderer: (row) => {\n * const card = document.createElement('div');\n * card.className = 'custom-card';\n * card.innerHTML = `<strong>${row.name}</strong><br>${row.email}`;\n * return card;\n * },\n * }),\n * ],\n * };\n * ```\n */\nexport class ResponsivePlugin<T = unknown> extends BaseGridPlugin<ResponsivePluginConfig<T>> {\n readonly name = 'responsive';\n override readonly version = '1.0.0';\n override readonly styles = styles;\n\n /**\n * Plugin manifest declaring queries this plugin handles.\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'isCardMode',\n description: 'Returns whether the grid is currently in responsive card mode',\n },\n ],\n };\n\n #resizeObserver?: ResizeObserver;\n #isResponsive = false;\n #debounceTimer?: ReturnType<typeof setTimeout>;\n #warnedAboutMissingBreakpoint = false;\n #currentWidth = 0;\n /** Set of column fields to completely hide */\n #hiddenColumnSet: Set<string> = new Set();\n /** Set of column fields to show value only (no header label) */\n #valueOnlyColumnSet: Set<string> = new Set();\n /** Currently active breakpoint, or null if none */\n #activeBreakpoint: BreakpointConfig | null = null;\n /** Sorted breakpoints from largest to smallest */\n #sortedBreakpoints: BreakpointConfig[] = [];\n\n /** Typed internal grid accessor — centralizes the single required cast. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if currently in responsive mode.\n * @returns `true` if the grid is in card layout mode\n */\n isResponsive(): boolean {\n return this.#isResponsive;\n }\n\n /**\n * Force responsive mode regardless of width.\n * Useful for testing or manual control.\n * @param enabled - Whether to enable responsive mode\n */\n setResponsive(enabled: boolean): void {\n if (enabled !== this.#isResponsive) {\n this.#isResponsive = enabled;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: enabled,\n width: this.#currentWidth,\n breakpoint: this.config.breakpoint ?? 0,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Update breakpoint dynamically.\n * @param width - New breakpoint width in pixels\n */\n setBreakpoint(width: number): void {\n this.config.breakpoint = width;\n this.#checkBreakpoint(this.#currentWidth);\n }\n\n /**\n * Set a custom card renderer.\n * This allows framework adapters to provide template-based renderers at runtime.\n * @param renderer - The card renderer function, or undefined to use default\n */\n setCardRenderer(renderer: ResponsivePluginConfig<T>['cardRenderer']): void {\n this.config.cardRenderer = renderer;\n // If already in responsive mode, trigger a re-render to apply the new renderer\n if (this.#isResponsive) {\n this.requestRender();\n }\n }\n\n /**\n * Get current grid width.\n * @returns Width of the grid element in pixels\n */\n getWidth(): number {\n return this.#currentWidth;\n }\n\n /**\n * Get the currently active breakpoint config (multi-breakpoint mode only).\n * @returns The active BreakpointConfig, or null if no breakpoint is active\n */\n getActiveBreakpoint(): BreakpointConfig | null {\n return this.#activeBreakpoint;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Parse light DOM configuration first (may update this.config)\n this.#parseLightDomCard();\n\n // Build hidden column sets from config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n\n // Sort breakpoints from largest to smallest for evaluation\n if (this.config.breakpoints?.length) {\n this.#sortedBreakpoints = [...this.config.breakpoints].sort((a, b) => b.maxWidth - a.maxWidth);\n }\n\n // Observe the grid element itself (not internal viewport)\n // This captures the container width including when shell panels open/close\n this.#resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width ?? 0;\n this.#currentWidth = width;\n\n // Debounce to avoid thrashing during resize drag\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = setTimeout(() => {\n this.#checkBreakpoint(width);\n }, this.config.debounceMs ?? 100);\n });\n\n this.#resizeObserver.observe(this.gridElement);\n }\n\n // #region Light DOM Parsing\n\n /**\n * Parse `<tbw-grid-responsive-card>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-responsive-card breakpoint=\"500\" card-row-height=\"80\">\n * <div class=\"custom-card\">\n * <strong>{{ row.name }}</strong>\n * <span>{{ row.email }}</span>\n * </div>\n * </tbw-grid-responsive-card>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `breakpoint`: number - Width threshold for responsive mode\n * - `card-row-height`: number | 'auto' - Card height (default: 'auto')\n * - `hidden-columns`: string - Comma-separated fields to hide\n * - `hide-header`: 'true' | 'false' - Hide header row (default: 'true')\n * - `debounce-ms`: number - Resize debounce delay (default: 100)\n */\n #parseLightDomCard(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const cardEl = gridEl.querySelector('tbw-grid-responsive-card');\n if (!cardEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., React adapter intercepts for JSX rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseResponsiveCardElement) {\n const adapterRenderer = adapter.parseResponsiveCardElement(cardEl);\n if (adapterRenderer) {\n this.config = { ...this.config, cardRenderer: adapterRenderer };\n // Continue to parse attributes even if adapter provides renderer\n }\n }\n\n // Parse attributes for configuration\n const breakpointAttr = cardEl.getAttribute('breakpoint');\n const cardRowHeightAttr = cardEl.getAttribute('card-row-height');\n const hiddenColumnsAttr = cardEl.getAttribute('hidden-columns');\n const hideHeaderAttr = cardEl.getAttribute('hide-header');\n const debounceMsAttr = cardEl.getAttribute('debounce-ms');\n\n const configUpdates: Partial<ResponsivePluginConfig<T>> = {};\n\n if (breakpointAttr !== null) {\n const breakpoint = parseInt(breakpointAttr, 10);\n if (!isNaN(breakpoint)) {\n configUpdates.breakpoint = breakpoint;\n }\n }\n\n if (cardRowHeightAttr !== null) {\n configUpdates.cardRowHeight = cardRowHeightAttr === 'auto' ? 'auto' : parseInt(cardRowHeightAttr, 10);\n }\n\n if (hiddenColumnsAttr !== null) {\n // Parse comma-separated field names\n configUpdates.hiddenColumns = hiddenColumnsAttr\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n if (hideHeaderAttr !== null) {\n configUpdates.hideHeader = hideHeaderAttr !== 'false';\n }\n\n if (debounceMsAttr !== null) {\n const debounceMs = parseInt(debounceMsAttr, 10);\n if (!isNaN(debounceMs)) {\n configUpdates.debounceMs = debounceMs;\n }\n }\n\n // Get template content from innerHTML (only if no renderer already set)\n const templateHTML = cardEl.innerHTML.trim();\n if (templateHTML && !this.config.cardRenderer && !adapter?.parseResponsiveCardElement) {\n // Create a template-based renderer using the inner HTML\n configUpdates.cardRenderer = (row: T): HTMLElement => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row: row as Record<string, unknown> });\n // Sanitize the result to prevent XSS\n const sanitized = sanitizeHTML(evaluated);\n const container = document.createElement('div');\n container.className = 'tbw-responsive-card-content';\n container.innerHTML = sanitized;\n return container;\n };\n }\n\n // Merge updates into config (light DOM values override constructor config)\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n /**\n * Build the hidden and value-only column sets from config.\n */\n #buildHiddenColumnSets(hiddenColumns?: HiddenColumnConfig[]): void {\n this.#hiddenColumnSet.clear();\n this.#valueOnlyColumnSet.clear();\n\n if (!hiddenColumns) return;\n\n for (const col of hiddenColumns) {\n if (typeof col === 'string') {\n this.#hiddenColumnSet.add(col);\n } else if (col.showValue) {\n this.#valueOnlyColumnSet.add(col.field);\n } else {\n this.#hiddenColumnSet.add(col.field);\n }\n }\n }\n\n override detach(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = undefined;\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = undefined;\n\n // Clean up attribute\n if (this.gridElement) {\n this.gridElement.removeAttribute('data-responsive');\n }\n\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isCardMode') {\n return this.#isResponsive;\n }\n return undefined;\n }\n\n /**\n * Apply hidden and value-only columns.\n * In legacy mode (single breakpoint), only applies when in responsive mode.\n * In multi-breakpoint mode, applies whenever there's an active breakpoint.\n */\n override afterRender(): void {\n // Measure card height for virtualization calculations\n this.#measureCardHeightFromDOM();\n\n // In single breakpoint mode, only apply when responsive\n // In multi-breakpoint mode, apply when there's an active breakpoint\n const shouldApply = this.#sortedBreakpoints.length > 0 ? this.#activeBreakpoint !== null : this.#isResponsive;\n\n if (!shouldApply) {\n return;\n }\n\n const hasHiddenColumns = this.#hiddenColumnSet.size > 0;\n const hasValueOnlyColumns = this.#valueOnlyColumnSet.size > 0;\n\n if (!hasHiddenColumns && !hasValueOnlyColumns) {\n return;\n }\n\n // Mark cells for hidden columns and value-only columns\n const cells = this.gridElement.querySelectorAll('.cell[data-field]');\n for (const cell of cells) {\n const field = cell.getAttribute('data-field');\n if (!field) continue;\n\n // Apply hidden attribute\n if (this.#hiddenColumnSet.has(field)) {\n cell.setAttribute('data-responsive-hidden', '');\n cell.removeAttribute('data-responsive-value-only');\n }\n // Apply value-only attribute (shows value without header label)\n else if (this.#valueOnlyColumnSet.has(field)) {\n cell.setAttribute('data-responsive-value-only', '');\n cell.removeAttribute('data-responsive-hidden');\n }\n // Clear any previous responsive attributes\n else {\n cell.removeAttribute('data-responsive-hidden');\n cell.removeAttribute('data-responsive-value-only');\n }\n }\n }\n\n /**\n * Check if width has crossed any breakpoint threshold.\n * Handles both single breakpoint (legacy) and multi-breakpoint modes.\n */\n #checkBreakpoint(width: number): void {\n // Multi-breakpoint mode\n if (this.#sortedBreakpoints.length > 0) {\n this.#checkMultiBreakpoint(width);\n return;\n }\n\n // Legacy single breakpoint mode\n const breakpoint = this.config.breakpoint ?? 0;\n\n // Warn once if breakpoint not configured (0 means never responsive)\n if (breakpoint === 0 && !this.#warnedAboutMissingBreakpoint) {\n this.#warnedAboutMissingBreakpoint = true;\n this.warn(\n MISSING_BREAKPOINT,\n \"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count.\",\n );\n }\n\n const shouldBeResponsive = breakpoint > 0 && width < breakpoint;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: shouldBeResponsive,\n width,\n breakpoint,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Check breakpoints in multi-breakpoint mode.\n * Evaluates breakpoints from largest to smallest, applying the first match.\n */\n #checkMultiBreakpoint(width: number): void {\n // Find the active breakpoint (first one where width <= maxWidth)\n // Since sorted largest to smallest, we find the largest matching breakpoint\n let newActiveBreakpoint: BreakpointConfig | null = null;\n\n for (const bp of this.#sortedBreakpoints) {\n if (width <= bp.maxWidth) {\n newActiveBreakpoint = bp;\n // Continue to find the most specific (smallest) matching breakpoint\n }\n }\n\n // Check if breakpoint changed\n const breakpointChanged = newActiveBreakpoint !== this.#activeBreakpoint;\n\n if (breakpointChanged) {\n this.#activeBreakpoint = newActiveBreakpoint;\n\n // Update hidden column sets from active breakpoint\n if (newActiveBreakpoint?.hiddenColumns) {\n this.#buildHiddenColumnSets(newActiveBreakpoint.hiddenColumns);\n } else {\n // Fall back to top-level hiddenColumns config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n }\n\n // Determine if we should be in card layout\n const shouldBeResponsive = newActiveBreakpoint?.cardLayout === true;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n }\n\n // Emit event for any breakpoint change\n this.emit('responsive-change', {\n isResponsive: this.#isResponsive,\n width,\n breakpoint: newActiveBreakpoint?.maxWidth ?? 0,\n } satisfies ResponsiveChangeDetail);\n\n this.requestRender();\n }\n }\n\n /** Original row height before entering responsive mode, for restoration on exit */\n #originalRowHeight?: number;\n\n /**\n * Apply the responsive state to the grid element.\n * Handles scroll reset when entering responsive mode and row height restoration on exit.\n */\n #applyResponsiveState(): void {\n this.gridElement.toggleAttribute('data-responsive', this.#isResponsive);\n\n // Apply animation attribute if enabled (default: true)\n const animate = this.config.animate !== false;\n this.gridElement.toggleAttribute('data-responsive-animate', animate);\n\n // Set custom animation duration if provided\n if (this.config.animationDuration) {\n this.gridElement.style.setProperty('--tbw-responsive-duration', `${this.config.animationDuration}ms`);\n }\n\n // Cast to internal type for virtualization access\n const internalGrid = this.#internalGrid;\n\n if (this.#isResponsive) {\n // Store original row height before responsive mode changes it\n if (internalGrid._virtualization) {\n this.#originalRowHeight = internalGrid._virtualization.rowHeight;\n }\n\n // Reset horizontal scroll position when entering responsive mode\n // The CSS hides overflow but doesn't reset the scroll position\n const scrollArea = this.gridElement.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (scrollArea) {\n scrollArea.scrollLeft = 0;\n }\n } else {\n // Exiting responsive mode - clean up inline styles set by renderRow\n // The rows are reused from the pool, so we need to remove the card-specific styles\n const rows = this.gridElement.querySelectorAll('.data-grid-row');\n for (const row of rows) {\n (row as HTMLElement).style.height = '';\n row.classList.remove('responsive-card');\n }\n\n // Restore original row height\n if (this.#originalRowHeight && this.#originalRowHeight > 0 && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = this.#originalRowHeight;\n this.#originalRowHeight = undefined;\n }\n\n // Clear cached measurements so they're remeasured fresh when re-entering responsive mode\n // Without this, stale measurements cause incorrect height calculations after scrolling\n this.#measuredCardHeight = undefined;\n this.#measuredGroupRowHeight = undefined;\n this.#lastCardRowCount = undefined;\n }\n }\n\n /**\n * Custom row rendering when cardRenderer is provided and in responsive mode.\n *\n * When a cardRenderer is configured, this hook takes over row rendering to display\n * the custom card layout instead of the default cell structure.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if rendered (prevents default), `void` for default rendering\n */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean | void {\n // Only override when in responsive mode AND cardRenderer is provided\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return; // Let default rendering proceed\n }\n\n // Skip group rows from GroupingRowsPlugin - they have special structure\n // and should use their own renderer\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return; // Let GroupingRowsPlugin handle group row rendering\n }\n\n // Clear existing content\n rowEl.replaceChildren();\n\n // Call user's cardRenderer to get custom content\n const cardContent = this.config.cardRenderer(row as T, rowIndex);\n\n // Reset className - clears any stale classes from previous use (e.g., 'group-row' from recycled element)\n // This follows the same pattern as GroupingRowsPlugin which sets className explicitly\n rowEl.className = 'data-grid-row responsive-card';\n\n // Handle card row height — when a numeric height is configured, use the effective\n // height from #getCardHeight() which incorporates DOM measurement after first render.\n // This keeps inline height in sync with the position cache used for virtualization.\n const configuredHeight = this.config.cardRowHeight;\n if (configuredHeight === 'auto' || configuredHeight === undefined) {\n rowEl.style.height = 'auto';\n } else {\n rowEl.style.height = `${this.#getCardHeight()}px`;\n }\n\n // Append the custom card content\n rowEl.appendChild(cardContent);\n\n return true; // We handled rendering\n }\n\n /**\n * Handle keyboard navigation in responsive mode.\n *\n * In responsive mode, the visual layout is inverted:\n * - Cells are stacked vertically within each \"card\" (row)\n * - DOWN/UP visually moves within the card (between fields)\n * - Page Down/Page Up or Ctrl+Down/Up moves between cards\n *\n * For custom cardRenderers, keyboard navigation is disabled entirely\n * since the implementor controls the card content and should handle\n * navigation via their own event handlers.\n *\n * @returns `true` if the event was handled and default behavior should be prevented\n */\n override onKeyDown(e: KeyboardEvent): boolean {\n if (!this.#isResponsive) {\n return false;\n }\n\n // If custom cardRenderer is provided, disable grid's keyboard navigation\n // The implementor is responsible for their own navigation\n if (this.config.cardRenderer) {\n const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];\n if (navKeys.includes(e.key)) {\n // Let the event bubble - implementor can handle it\n return false;\n }\n }\n\n // Swap arrow key behavior for CSS-only responsive mode\n // In card layout, cells are stacked vertically:\n // Card 1: Card 2:\n // ID: 1 ID: 2\n // Name: Alice Name: Bob <- ArrowRight goes here\n // Dept: Eng Dept: Mkt\n // ↓ ArrowDown goes here\n //\n // ArrowDown/Up = move within card (change column/field)\n // ArrowRight/Left = move between cards (change row)\n const maxRow = this.rows.length - 1;\n const maxCol = this.visibleColumns.length - 1;\n\n switch (e.key) {\n case 'ArrowDown':\n // Move down WITHIN card (to next field/column)\n if (this.grid._focusCol < maxCol) {\n this.grid._focusCol += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At bottom of card - optionally move to next card's first field\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n this.grid._focusCol = 0;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowUp':\n // Move up WITHIN card (to previous field/column)\n if (this.grid._focusCol > 0) {\n this.grid._focusCol -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At top of card - optionally move to previous card's last field\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n this.grid._focusCol = maxCol;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowRight':\n // Move to NEXT card (same field)\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowLeft':\n // Move to PREVIOUS card (same field)\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n }\n\n return false;\n }\n\n // ============================================\n // Variable Height Support for Mixed Row Types\n // ============================================\n\n /** Measured card height from DOM for virtualization calculations */\n #measuredCardHeight?: number;\n\n /** Measured group row height from DOM for virtualization calculations */\n #measuredGroupRowHeight?: number;\n\n /** Last known card row count for detecting changes (e.g., group expand/collapse) */\n #lastCardRowCount?: number;\n\n /**\n * Get the effective card height for virtualization calculations.\n * Prioritizes DOM-measured height (actual rendered size) over config,\n * since content can overflow the configured height.\n */\n #getCardHeight(): number {\n // Prefer measured height - it reflects actual rendered size including overflow\n if (this.#measuredCardHeight && this.#measuredCardHeight > 0) {\n return this.#measuredCardHeight;\n }\n // Fall back to explicit config\n const configHeight = this.config.cardRowHeight;\n if (typeof configHeight === 'number' && configHeight > 0) {\n return configHeight;\n }\n // Default fallback\n return 80;\n }\n\n /**\n * Get the effective group row height for virtualization calculations.\n * Uses DOM-measured height, falling back to original row height.\n */\n #getGroupRowHeight(): number {\n if (this.#measuredGroupRowHeight && this.#measuredGroupRowHeight > 0) {\n return this.#measuredGroupRowHeight;\n }\n // Fall back to original row height (before responsive mode)\n return this.#originalRowHeight ?? 28;\n }\n\n /**\n * Check if there are any group rows in the current dataset.\n * Used to determine if we have mixed row heights.\n */\n #hasGroupRows(): boolean {\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Count group rows and card rows in the current dataset.\n */\n #countRowTypes(): { groupCount: number; cardCount: number } {\n let groupCount = 0;\n let cardCount = 0;\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n groupCount++;\n } else {\n cardCount++;\n }\n }\n return { groupCount, cardCount };\n }\n\n /**\n * Return total extra height contributed by mixed row heights.\n * This is called by the grid's virtualization system to adjust scrollbar height.\n *\n * The grid calculates: totalRows * baseRowHeight + pluginExtraHeight\n *\n * For mixed layouts (groups + cards), we need to report the difference between\n * actual heights and what the base calculation assumes:\n * - Extra for groups: groupCount * (groupHeight - baseHeight)\n * - Extra for cards: cardCount * (cardHeight - baseHeight)\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeight(): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types (groups + cards)\n // If all rows are cards, we update the virtualization row height instead\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const { groupCount, cardCount } = this.#countRowTypes();\n\n // Calculate extra height for both row types\n const groupExtra = groupCount * Math.max(0, groupHeight - baseHeight);\n const cardExtra = cardCount * Math.max(0, cardHeight - baseHeight);\n\n return groupExtra + cardExtra;\n }\n\n /**\n * Return extra height that appears before a given row index.\n * Used by virtualization to correctly calculate scroll positions.\n *\n * Like getExtraHeight, this accounts for both group and card row heights.\n *\n * @deprecated Use getRowHeight() instead. This hook will be removed in v2.0.\n */\n override getExtraHeightBefore(beforeRowIndex: number): number {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return 0;\n }\n\n // Only report extra height when there are mixed row types\n if (!this.#hasGroupRows()) {\n return 0;\n }\n\n const baseHeight = this.#originalRowHeight ?? 28;\n const groupHeight = this.#getGroupRowHeight();\n const cardHeight = this.#getCardHeight();\n\n const groupHeightDiff = Math.max(0, groupHeight - baseHeight);\n const cardHeightDiff = Math.max(0, cardHeight - baseHeight);\n\n // Count group rows and card rows before the given index\n let groupsBefore = 0;\n let cardsBefore = 0;\n const rows = this.rows;\n const maxIndex = Math.min(beforeRowIndex, rows.length);\n\n for (let i = 0; i < maxIndex; i++) {\n if ((rows[i] as { __isGroupRow?: boolean }).__isGroupRow) {\n groupsBefore++;\n } else {\n cardsBefore++;\n }\n }\n\n return groupsBefore * groupHeightDiff + cardsBefore * cardHeightDiff;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.#internalGrid;\n const hasGroups = this.#hasGroupRows();\n\n // Check if card row count changed (e.g., group expanded/collapsed)\n const currentCardRowCount = this.#countCardRows();\n if (currentCardRowCount !== this.#lastCardRowCount) {\n this.#lastCardRowCount = currentCardRowCount;\n needsRefresh = true;\n }\n\n // Measure actual group row height from DOM (for mixed layouts)\n if (hasGroups) {\n const groupRow = this.gridElement.querySelector('.data-grid-row.group-row') as HTMLElement | null;\n if (groupRow) {\n const height = groupRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredGroupRowHeight) {\n this.#measuredGroupRowHeight = height;\n needsRefresh = true;\n }\n }\n }\n\n // Measure actual card height from DOM.\n // With cardRenderer, rows have the `.responsive-card` class.\n // Without cardRenderer (CSS-only card mode), rows are plain `.data-grid-row`\n // elements whose CSS height is `auto` — we need to measure their actual\n // rendered height so the faux scrollbar spacer is sized correctly.\n const cardSelector = this.config.cardRenderer ? '.data-grid-row.responsive-card' : '.data-grid-row:not(.group-row)';\n const cardRow = this.gridElement.querySelector(cardSelector) as HTMLElement | null;\n if (cardRow) {\n const height = cardRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredCardHeight) {\n this.#measuredCardHeight = height;\n needsRefresh = true;\n\n // For uniform card layouts (no groups), update virtualization row height directly\n // This ensures proper row recycling and translateY calculations\n if (!hasGroups && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = height;\n }\n }\n }\n\n // Defer virtualization refresh to avoid nested render cycles\n // This is called from afterRender, so we can't call refreshVirtualWindow synchronously\n // Use scheduler's VIRTUALIZATION phase to batch properly and avoid duplicate afterRender calls\n if (needsRefresh && !this.#pendingRefresh) {\n this.#pendingRefresh = true;\n queueMicrotask(() => {\n this.#pendingRefresh = false;\n // Only refresh if still attached and in responsive mode\n if (this.grid && this.#isResponsive) {\n // Request virtualization phase through grid's public API\n // This goes through the scheduler which batches and handles afterRender properly\n this.#internalGrid.refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","name","version","styles","static","queries","type","description","resizeObserver","isResponsive","debounceTimer","warnedAboutMissingBreakpoint","currentWidth","hiddenColumnSet","Set","valueOnlyColumnSet","activeBreakpoint","sortedBreakpoints","internalGrid","this","grid","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","requestRender","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","getWidth","getActiveBreakpoint","attach","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","cardEl","querySelector","adapter","__frameworkAdapter","parseResponsiveCardElement","adapterRenderer","breakpointAttr","getAttribute","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","parseInt","isNaN","cardRowHeight","split","map","s","trim","filter","hideHeader","templateHTML","innerHTML","row","evaluated","evalTemplateString","value","sanitized","sanitizeHTML","container","document","createElement","className","Object","keys","clear","col","add","showValue","field","detach","disconnect","removeAttribute","handleQuery","query","afterRender","measureCardHeightFromDOM","hasHiddenColumns","size","hasValueOnlyColumns","cells","querySelectorAll","cell","has","setAttribute","checkMultiBreakpoint","warn","MISSING_BREAKPOINT","shouldBeResponsive","newActiveBreakpoint","bp","cardLayout","originalRowHeight","toggleAttribute","animate","animationDuration","style","setProperty","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","configuredHeight","getCardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","configHeight","getGroupRowHeight","hasGroupRows","countRowTypes","groupCount","cardCount","getExtraHeight","baseHeight","groupHeight","cardHeight","Math","max","getExtraHeightBefore","beforeRowIndex","groupHeightDiff","cardHeightDiff","groupsBefore","cardsBefore","maxIndex","min","i","getRowHeight","_index","countCardRows","count","pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","getBoundingClientRect","cardSelector","cardRow","queueMicrotask","refreshVirtualWindow"],"mappings":"mlBAkFO,MAAMA,UAAsCC,EAAAA,eACxCC,KAAO,aACEC,QAAU,QACVC,8hHAKlBC,gBAAoD,CAClDC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,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B0B,EAAsBrK,MAAKgK,IAOjC,GANIK,IAAwBrK,MAAKoH,IAC/BpH,MAAKoH,EAAoBiD,EACzBF,GAAe,GAIbC,EAAW,CACb,MAAME,EAAWtK,KAAKmC,YAAYG,cAAc,4BAChD,GAAIgI,EAAU,CACZ,MAAMvD,EAASuD,EAASC,wBAAwBxD,OAC5CA,EAAS,GAAKA,IAAW/G,MAAKmH,IAChCnH,MAAKmH,EAA0BJ,EAC/BoD,GAAe,EAEnB,CACF,CAOA,MAAMK,EAAexK,KAAKQ,OAAOM,aAAe,iCAAmC,iCAC7E2J,EAAUzK,KAAKmC,YAAYG,cAAckI,GAC/C,GAAIC,EAAS,CACX,MAAM1D,EAAS0D,EAAQF,wBAAwBxD,OAC3CA,EAAS,GAAKA,IAAW/G,MAAKkH,IAChClH,MAAKkH,EAAsBH,EAC3BoD,GAAe,GAIVC,GAAarK,EAAa2G,kBAC7B3G,EAAa2G,gBAAgBC,UAAYI,GAG/C,CAKIoD,IAAiBnK,MAAKkK,IACxBlK,MAAKkK,GAAkB,EACvBQ,eAAe,KACb1K,MAAKkK,GAAkB,EAEnBlK,KAAKC,MAAQD,MAAKV,GAGpBU,MAAKD,EAAc4K,wBAAuB,GAAM,KAIxD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/utils"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/utils","../../core/plugin/base-plugin","../../core/plugin/expander-column"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_selection={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,s,i){"use strict";function l(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function o(e){const t=l(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function r(e){return e.map(o)}function n(e,t,s){return s.some(s=>function(e,t,s){const i=l(s);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,s))}function c(e){const t=[],s=l(e);for(let i=s.startRow;i<=s.endRow;i++)for(let e=s.startCol;e<=s.endCol;e++)t.push({row:i,col:e});return t}function a(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function d(e,t){const s=l(e),i=l(t);return s.startRow===i.startRow&&s.startCol===i.startCol&&s.endRow===i.endRow&&s.endCol===i.endCol}const h="__tbw_checkbox";class g extends s.BaseGridPlugin{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===e.mode&&"dblclick"===e.triggerOn}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid[data-selection-mode=row] .cell-focus,tbw-grid[data-selection-mode=row] .row-focus,tbw-grid[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;pendingRowKeyUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:s}=this.config;if(!s)return!0;const i=this.rows[e];if(!i)return!1;return s(i,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){return"getSelection"===e.type?this.getSelection():"getSelectedRowIndices"===e.type?this.getSelectedRowIndices():"getSelectedRows"===e.type?this.getSelectedRows():"selectRows"===e.type?(this.selectRows(e.context),!0):void 0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.pendingRowKeyUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:l}=e,{mode:o,triggerOn:r="click"}=this.config;if(l.type!==r)return!1;const n=e.column,c=n&&i.isUtilityColumn(n);if("cell"===o){if(c)return!1;if(!this.isCellSelectable(t,s))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()),this.requestAfterRender()),!1}if("row"===o){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,s=l.shiftKey&&e,i=(l.ctrlKey||l.metaKey)&&e,o=!0===n?.meta?.checkboxColumn;if(s&&null!==this.anchor){const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);i||this.selected.clear();for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(i||o&&e)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}if("range"===o){if(c)return!1;if(!this.isCellSelectable(t,s))return!1;const e=l.shiftKey,i=(l.ctrlKey||l.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=a(this.cellAnchor,{row:t,col:s}),l=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(l&&d(l,e))return!1;i?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(i){const e={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:s}}else{const e={startRow:t,startCol:s,endRow:t,endCol:s};if(1===this.ranges.length&&d(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if("Escape"===e.key){return!this.grid.query("isEditing").some(Boolean)&&("cell"===t?this.selectedCell=null:"row"===t?(this.selected.clear(),this.anchor=null):"range"===t&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}if("cell"===t&&s)return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.isCellSelectable(e,t)?this.selectedCell={row:e,col:t}:this.selectedCell=null,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key||"PageUp"===e.key||"PageDown"===e.key||(e.ctrlKey||e.metaKey)&&("Home"===e.key||"End"===e.key)){const s=e.shiftKey&&t;return s&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}}if("range"===t&&s){const t="Tab"===e.key,s=e.shiftKey&&!t;return s&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(e.column&&i.isUtilityColumn(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,s=e.colIndex,l=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,o={startRow:t,startCol:s,endRow:t,endCol:s};return!l&&1===this.ranges.length&&d(this.ranges[0],o)?(this.cellAnchor={row:t,col:s},!0):(this.cellAnchor={row:t,col:s},l||(this.ranges=[]),this.ranges.push(o),this.activeRange=o,this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const s=this.visibleColumns[t];if(s&&i.isUtilityColumn(s)){const e=this.visibleColumns.findIndex(e=>!i.isUtilityColumn(e));e>=0&&(t=e)}const l=a(this.cellAnchor,{row:e.rowIndex,col:t}),o=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return o&&d(o,l)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=l:this.ranges.push(l),this.activeRange=l,this.emit("selection-change",this.#e()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.config.mode)return this.isDragging?(this.isDragging=!1,!0):void 0}processColumns(e){if(this.config.checkbox&&"row"===this.config.mode){if(e.some(e=>e.field===h))return e;const t=this.#t(),s=e.findIndex(i.isExpanderColumn),l=s>=0?s+1:0;return[...e.slice(0,l),t,...e.slice(l)]}return e}#t(){return{field:h,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const s=e.cellEl;if(s){const e=parseInt(s.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#s(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const s=e.closest(".cell"),i=s?t.getRowIndexFromCell(s):-1;i>=0&&(e.checked=this.selected.has(i))});const s=e.querySelector(".tbw-select-all-checkbox");if(s){const e=this.rows.length;let t=0;if(this.config.isSelectable)for(let s=0;s<e;s++)this.isRowSelectable(s)&&t++;else t=e;const i=t>0&&this.selected.size>=t,l=this.selected.size>0;s.checked=i,s.indeterminate=l&&!i}}#i(e){const t=this.grid._focusRow,s=this.grid._focusCol;if("row"===e){if(this.explicitSelection)return this.explicitSelection=!1,void(this.lastSyncedFocusRow=t);t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(this.selected.has(t)&&1===this.selected.size||(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#e()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const e=this.selectedCell;e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()))}}}#l(){const e=this.gridElement;if(!e)return;const{mode:s}=this.config,o=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(e=>{e.classList.remove("selected","top","bottom","first","last"),o&&e.removeAttribute("data-selectable")});const r=e.querySelectorAll(".data-grid-row");if(r.forEach(e=>{e.classList.remove("selected","row-focus"),e.setAttribute("aria-selected","false"),o&&e.removeAttribute("data-selectable")}),"row"===s&&(t.clearCellFocus(e),r.forEach(e=>{const s=e.querySelector(".cell[data-row]"),i=t.getRowIndexFromCell(s);i>=0&&(o&&!this.isRowSelectable(i)&&e.setAttribute("data-selectable","false"),this.selected.has(i)&&(e.classList.add("selected","row-focus"),e.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#s(e)),("cell"===s||"range"===s)&&o){e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&s>=0&&(this.isCellSelectable(t,s)||e.setAttribute("data-selectable","false"))})}if("range"===s&&this.ranges.length>0){t.clearCellFocus(e);const s=this.ranges.map(l),o=(e,t)=>{for(const i of s)if(e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&s>=0){const l=this.visibleColumns[s];if(l&&i.isUtilityColumn(l))return;o(t,s)&&(e.classList.add("selected"),e.setAttribute("aria-selected","true"),o(t-1,s)||e.classList.add("top"),o(t+1,s)||e.classList.add("bottom"),o(t,s-1)||e.classList.add("first"),o(t,s+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.children[0],{mode:s}=this.config;if(this.pendingRowKeyUpdate&&"row"===s){const{shiftKey:e}=this.pendingRowKeyUpdate;this.pendingRowKeyUpdate=null;const t=this.grid._focusRow;if(e&&null!==this.anchor){this.selected.clear();const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else this.isRowSelectable(t)?(this.selected.clear(),this.selected.add(t),this.anchor=t):this.selected.clear();this.lastSelected=t,this.emit("selection-change",this.#e())}if(this.pendingKeyboardUpdate&&"range"===s){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,s=this.grid._focusCol;if(e&&this.cellAnchor){const e=a(this.cellAnchor,{row:t,col:s});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:s});this.emit("selection-change",this.#e())}this.#i(s),this.gridElement.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#l()}onScrollRender(){this.isSelectionEnabled()&&this.#l()}getSelection(){return{mode:this.config.mode,ranges:this.#e().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const s of e)for(const e of c(s))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return n(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const s={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[s],this.activeRange=s,this.emit("selection-change",this.#e()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.config.mode)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=new Set;for(const s of this.ranges){const i=Math.max(0,Math.min(s.startRow,s.endRow)),l=Math.min(t.length-1,Math.max(s.startRow,s.endRow));for(let t=i;t<=l;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:r(this.ranges)}),this.requestAfterRender()}#e(){return function(e,t,s){if("cell"===e&&t.selectedCell)return{mode:e,ranges:[{from:{row:t.selectedCell.row,col:t.selectedCell.col},to:{row:t.selectedCell.row,col:t.selectedCell.col}}]};if("row"===e&&t.selected.size>0){const i=[...t.selected].sort((e,t)=>e-t),l=[];let o=i[0],r=o;for(let e=1;e<i.length;e++)i[e]===r+1?r=i[e]:(l.push({from:{row:o,col:0},to:{row:r,col:s-1}}),o=i[e],r=o);return l.push({from:{row:o,col:0},to:{row:r,col:s-1}}),{mode:e,ranges:l}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:r(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}e.SelectionPlugin=g,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/utils"),require("../../core/plugin/base-plugin"),require("../../core/plugin/expander-column")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/utils","../../core/plugin/base-plugin","../../core/plugin/expander-column"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_selection={},e.TbwGrid,e.TbwGrid,e.TbwGrid)}(this,function(e,t,s,i){"use strict";function l(e){return{startRow:Math.min(e.startRow,e.endRow),startCol:Math.min(e.startCol,e.endCol),endRow:Math.max(e.startRow,e.endRow),endCol:Math.max(e.startCol,e.endCol)}}function o(e){const t=l(e);return{from:{row:t.startRow,col:t.startCol},to:{row:t.endRow,col:t.endCol}}}function r(e){return e.map(o)}function n(e,t,s){return s.some(s=>function(e,t,s){const i=l(s);return e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol}(e,t,s))}function c(e){const t=[],s=l(e);for(let i=s.startRow;i<=s.endRow;i++)for(let e=s.startCol;e<=s.endCol;e++)t.push({row:i,col:e});return t}function a(e,t){return{startRow:e.row,startCol:e.col,endRow:t.row,endCol:t.col}}function d(e,t){const s=l(e),i=l(t);return s.startRow===i.startRow&&s.startCol===i.startCol&&s.endRow===i.endRow&&s.endCol===i.endCol}const h="__tbw_checkbox";class g extends s.BaseGridPlugin{static manifest={queries:[{type:"getSelection",description:"Get the current selection state"},{type:"selectRows",description:"Select specific rows by index (row mode only)"},{type:"getSelectedRowIndices",description:"Get sorted array of selected row indices"},{type:"getSelectedRows",description:"Get actual row objects for the current selection (works in all modes)"}],configRules:[{id:"selection/range-dblclick",severity:"warn",message:'"triggerOn: \'dblclick\'" has no effect when mode is "range".\n → Range selection uses drag interaction (mousedown → mousemove), not click events.\n → The "triggerOn" option only affects "cell" and "row" selection modes.',check:e=>"range"===e.mode&&"dblclick"===e.triggerOn}]};name="selection";styles='@layer tbw-plugins{tbw-grid.selecting .data-grid-row>.cell{-webkit-user-select:none;user-select:none}tbw-grid:has(.selection){-webkit-user-select:none;user-select:none}tbw-grid:has(.selection)[data-selection-mode=row] .cell-focus,tbw-grid:has(.selection)[data-selection-mode=row] .row-focus,tbw-grid:has(.selection)[data-selection-mode=range] .cell-focus{outline:none}tbw-grid .data-grid-row.row-focus{background-color:var(--tbw-focus-background, rgba(from var(--tbw-color-accent) r g b / 12%));outline:none;position:relative}tbw-grid .data-grid-row.row-focus:after{content:"";position:absolute;inset:0;pointer-events:none;border-width:0;border-style:var(--tbw-selection-border-style, var(--tbw-border-style));border-color:var(--tbw-range-border-color, var(--tbw-color-accent));border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width));border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width));z-index:1}tbw-grid .data-grid-row.row-focus+.data-grid-row.row-focus:after{border-top-width:0}tbw-grid .data-grid-row.row-focus:has(+.data-grid-row.row-focus):after{border-bottom-width:0}tbw-grid .data-grid-row>.cell.selected{background-color:var(--tbw-range-selection-bg);position:relative}tbw-grid .data-grid-row>.cell.selected:after{content:"";position:absolute;inset:0;pointer-events:none;border:0 var(--tbw-selection-border-style, var(--tbw-border-style)) var(--tbw-range-border-color);z-index:1}tbw-grid .data-grid-row>.cell.selected.top:after{border-top-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.bottom:after{border-bottom-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.first:after{border-left-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row>.cell.selected.last:after{border-right-width:var(--tbw-selection-border-width, var(--tbw-border-width))}tbw-grid .data-grid-row[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row[data-selectable=false].row-focus{background-color:var(--tbw-color-row-alt)}tbw-grid .data-grid-row>.cell[data-selectable=false]{cursor:not-allowed;opacity:.6}tbw-grid .data-grid-row>.cell[data-selectable=false].selected{background-color:var(--tbw-selection-warning-bg, rgba(from var(--tbw-color-error) r g b / 50%))}tbw-grid .tbw-selection-summary{font-size:var(--tbw-font-size-sm, .8125rem);color:var(--tbw-color-fg-muted);white-space:nowrap}tbw-grid .data-grid-row>.cell[data-field=__tbw_checkbox],tbw-grid .header-row>.cell[data-field=__tbw_checkbox]{text-align:center;cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}tbw-grid .tbw-select-row-checkbox{pointer-events:none;margin:0;cursor:pointer}tbw-grid .tbw-checkbox-header{display:flex;justify-content:center;align-items:center;height:100%}tbw-grid .tbw-select-all-checkbox{margin:0;cursor:pointer}}';get defaultConfig(){return{mode:"cell",triggerOn:"click",enabled:!0,multiSelect:!0}}selected=new Set;lastSelected=null;anchor=null;ranges=[];activeRange=null;cellAnchor=null;isDragging=!1;pendingKeyboardUpdate=null;pendingRowKeyUpdate=null;selectedCell=null;lastSyncedFocusRow=-1;lastSyncedFocusCol=-1;explicitSelection=!1;isSelectionEnabled(){return!1!==this.config.enabled&&!1!==this.grid.effectiveConfig?.selectable}checkSelectable(e,t){const{isSelectable:s}=this.config;if(!s)return!0;const i=this.rows[e];if(!i)return!1;return s(i,e,void 0!==t?this.visibleColumns[t]:void 0,t)}isRowSelectable(e){return this.checkSelectable(e)}isCellSelectable(e,t){return this.checkSelectable(e,t)}attach(e){super.attach(e),this.on("filter-applied",()=>this.clearSelectionSilent()),this.on("grouping-state-change",()=>this.clearSelectionSilent()),this.on("tree-state-change",()=>this.clearSelectionSilent())}handleQuery(e){return"getSelection"===e.type?this.getSelection():"getSelectedRowIndices"===e.type?this.getSelectedRowIndices():"getSelectedRows"===e.type?this.getSelectedRows():"selectRows"===e.type?(this.selectRows(e.context),!0):void 0}detach(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.isDragging=!1,this.selectedCell=null,this.pendingKeyboardUpdate=null,this.pendingRowKeyUpdate=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1}clearSelectionSilent(){this.selected.clear(),this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.selectedCell=null,this.lastSelected=null,this.anchor=null,this.lastSyncedFocusRow=-1,this.lastSyncedFocusCol=-1,this.requestAfterRender()}onCellClick(e){if(!this.isSelectionEnabled())return!1;const{rowIndex:t,colIndex:s,originalEvent:l}=e,{mode:o,triggerOn:r="click"}=this.config;if(l.type!==r)return!1;const n=e.column,c=n&&i.isUtilityColumn(n);if("cell"===o){if(c)return!1;if(!this.isCellSelectable(t,s))return!1;const e=this.selectedCell;return e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()),this.requestAfterRender()),!1}if("row"===o){if(!this.isRowSelectable(t))return!1;const e=!1!==this.config.multiSelect,s=l.shiftKey&&e,i=(l.ctrlKey||l.metaKey)&&e,o=!0===n?.meta?.checkboxColumn;if(s&&null!==this.anchor){const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);i||this.selected.clear();for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else if(i||o&&e)this.selected.has(t)?this.selected.delete(t):this.selected.add(t),this.anchor=t;else{if(1===this.selected.size&&this.selected.has(t))return!1;this.selected.clear(),this.selected.add(t),this.anchor=t}return this.lastSelected=t,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}if("range"===o){if(c)return!1;if(!this.isCellSelectable(t,s))return!1;const e=l.shiftKey,i=(l.ctrlKey||l.metaKey)&&!1!==this.config.multiSelect;if(e&&this.cellAnchor){const e=a(this.cellAnchor,{row:t,col:s}),l=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;if(l&&d(l,e))return!1;i?this.ranges.length>0?this.ranges[this.ranges.length-1]=e:this.ranges.push(e):this.ranges=[e],this.activeRange=e}else if(i){const e={startRow:t,startCol:s,endRow:t,endCol:s};this.ranges.push(e),this.activeRange=e,this.cellAnchor={row:t,col:s}}else{const e={startRow:t,startCol:s,endRow:t,endCol:s};if(1===this.ranges.length&&d(this.ranges[0],e))return!1;this.ranges=[e],this.activeRange=e,this.cellAnchor={row:t,col:s}}return this.emit("selection-change",this.#e()),this.requestAfterRender(),!1}return!1}onKeyDown(e){if(!this.isSelectionEnabled())return!1;const{mode:t}=this.config,s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End","PageUp","PageDown"].includes(e.key);if("Escape"===e.key){return!this.grid.query("isEditing").some(Boolean)&&("cell"===t?this.selectedCell=null:"row"===t?(this.selected.clear(),this.anchor=null):"range"===t&&(this.ranges=[],this.activeRange=null,this.cellAnchor=null),this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}if("cell"===t&&s)return queueMicrotask(()=>{const e=this.grid._focusRow,t=this.grid._focusCol;this.isCellSelectable(e,t)?this.selectedCell={row:e,col:t}:this.selectedCell=null,this.emit("selection-change",this.#e()),this.requestAfterRender()}),!1;if("row"===t){const t=!1!==this.config.multiSelect;if("ArrowUp"===e.key||"ArrowDown"===e.key||"PageUp"===e.key||"PageDown"===e.key||(e.ctrlKey||e.metaKey)&&("Home"===e.key||"End"===e.key)){const s=e.shiftKey&&t;return s&&null===this.anchor&&(this.anchor=this.grid._focusRow),this.explicitSelection=!0,this.pendingRowKeyUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if(t&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}}if("range"===t&&s){const t="Tab"===e.key,s=e.shiftKey&&!t;return s&&!this.cellAnchor&&(this.cellAnchor={row:this.grid._focusRow,col:this.grid._focusCol}),this.pendingKeyboardUpdate={shiftKey:s},queueMicrotask(()=>this.requestAfterRender()),!1}if("range"===t&&!1!==this.config.multiSelect&&"a"===e.key&&(e.ctrlKey||e.metaKey)){return!this.grid.query("isEditing").some(Boolean)&&(e.preventDefault(),e.stopPropagation(),this.selectAll(),!0)}return!1}onCellMouseDown(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;if(e.column&&i.isUtilityColumn(e.column))return;if(!this.isCellSelectable(e.rowIndex,e.colIndex))return;if(e.originalEvent.shiftKey&&this.cellAnchor)return;this.isDragging=!0;const t=e.rowIndex,s=e.colIndex,l=(e.originalEvent.ctrlKey||e.originalEvent.metaKey)&&!1!==this.config.multiSelect,o={startRow:t,startCol:s,endRow:t,endCol:s};return!l&&1===this.ranges.length&&d(this.ranges[0],o)?(this.cellAnchor={row:t,col:s},!0):(this.cellAnchor={row:t,col:s},l||(this.ranges=[]),this.ranges.push(o),this.activeRange=o,this.emit("selection-change",this.#e()),this.requestAfterRender(),!0)}onCellMouseMove(e){if(!this.isSelectionEnabled())return;if("range"!==this.config.mode)return;if(!this.isDragging||!this.cellAnchor)return;if(void 0===e.rowIndex||void 0===e.colIndex)return;if(e.rowIndex<0)return;let t=e.colIndex;const s=this.visibleColumns[t];if(s&&i.isUtilityColumn(s)){const e=this.visibleColumns.findIndex(e=>!i.isUtilityColumn(e));e>=0&&(t=e)}const l=a(this.cellAnchor,{row:e.rowIndex,col:t}),o=this.ranges.length>0?this.ranges[this.ranges.length-1]:null;return o&&d(o,l)||(this.ranges.length>0?this.ranges[this.ranges.length-1]=l:this.ranges.push(l),this.activeRange=l,this.emit("selection-change",this.#e()),this.requestAfterRender()),!0}onCellMouseUp(e){if(this.isSelectionEnabled()&&"range"===this.config.mode)return this.isDragging?(this.isDragging=!1,!0):void 0}processColumns(e){if(this.config.checkbox&&"row"===this.config.mode){if(e.some(e=>e.field===h))return e;const t=this.#t(),s=e.findIndex(i.isExpanderColumn),l=s>=0?s+1:0;return[...e.slice(0,l),t,...e.slice(l)]}return e}#t(){return{field:h,header:"",width:32,resizable:!1,sortable:!1,meta:{lockPosition:!0,suppressMovable:!0,utility:!0,checkboxColumn:!0},headerRenderer:()=>{const e=document.createElement("div");if(e.className="tbw-checkbox-header",!1===this.config.multiSelect)return e;const t=document.createElement("input");return t.type="checkbox",t.className="tbw-select-all-checkbox",t.addEventListener("click",e=>{e.stopPropagation(),e.target.checked?this.selectAll():this.clearSelection()}),e.appendChild(t),e},renderer:e=>{const t=document.createElement("input");t.type="checkbox",t.className="tbw-select-row-checkbox";const s=e.cellEl;if(s){const e=parseInt(s.getAttribute("data-row")??"-1",10);e>=0&&(t.checked=this.selected.has(e))}return t}}}#s(e){e.querySelectorAll(".tbw-select-row-checkbox").forEach(e=>{const s=e.closest(".cell"),i=s?t.getRowIndexFromCell(s):-1;i>=0&&(e.checked=this.selected.has(i))});const s=e.querySelector(".tbw-select-all-checkbox");if(s){const e=this.rows.length;let t=0;if(this.config.isSelectable)for(let s=0;s<e;s++)this.isRowSelectable(s)&&t++;else t=e;const i=t>0&&this.selected.size>=t,l=this.selected.size>0;s.checked=i,s.indeterminate=l&&!i}}#i(e){const t=this.grid._focusRow,s=this.grid._focusCol;if("row"===e){if(this.explicitSelection)return this.explicitSelection=!1,void(this.lastSyncedFocusRow=t);t!==this.lastSyncedFocusRow&&(this.lastSyncedFocusRow=t,this.isRowSelectable(t)&&(this.selected.has(t)&&1===this.selected.size||(this.selected.clear(),this.selected.add(t),this.lastSelected=t,this.anchor=t,this.emit("selection-change",this.#e()))))}if("cell"===e){if(this.explicitSelection)return this.explicitSelection=!1,this.lastSyncedFocusRow=t,void(this.lastSyncedFocusCol=s);if((t!==this.lastSyncedFocusRow||s!==this.lastSyncedFocusCol)&&(this.lastSyncedFocusRow=t,this.lastSyncedFocusCol=s,this.isCellSelectable(t,s))){const e=this.selectedCell;e&&e.row===t&&e.col===s||(this.selectedCell={row:t,col:s},this.emit("selection-change",this.#e()))}}}#l(){const e=this.gridElement;if(!e)return;const{mode:s}=this.config,o=!!this.config.isSelectable;e.querySelectorAll(".cell").forEach(e=>{e.classList.remove("selected","top","bottom","first","last"),o&&e.removeAttribute("data-selectable")});const r=e.querySelectorAll(".data-grid-row");if(r.forEach(e=>{e.classList.remove("selected","row-focus"),e.setAttribute("aria-selected","false"),o&&e.removeAttribute("data-selectable")}),"row"===s&&(t.clearCellFocus(e),r.forEach(e=>{const s=e.querySelector(".cell[data-row]"),i=t.getRowIndexFromCell(s);i>=0&&(o&&!this.isRowSelectable(i)&&e.setAttribute("data-selectable","false"),this.selected.has(i)&&(e.classList.add("selected","row-focus"),e.setAttribute("aria-selected","true")))}),this.config.checkbox&&this.#s(e)),("cell"===s||"range"===s)&&o){e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);t>=0&&s>=0&&(this.isCellSelectable(t,s)||e.setAttribute("data-selectable","false"))})}if("range"===s&&this.ranges.length>0){t.clearCellFocus(e);const s=this.ranges.map(l),o=(e,t)=>{for(const i of s)if(e>=i.startRow&&e<=i.endRow&&t>=i.startCol&&t<=i.endCol)return!0;return!1};e.querySelectorAll(".cell[data-row][data-col]").forEach(e=>{const t=parseInt(e.getAttribute("data-row")??"-1",10),s=parseInt(e.getAttribute("data-col")??"-1",10);if(t>=0&&s>=0){const l=this.visibleColumns[s];if(l&&i.isUtilityColumn(l))return;o(t,s)&&(e.classList.add("selected"),e.setAttribute("aria-selected","true"),o(t-1,s)||e.classList.add("top"),o(t+1,s)||e.classList.add("bottom"),o(t,s-1)||e.classList.add("first"),o(t,s+1)||e.classList.add("last"))}})}}afterRender(){if(!this.isSelectionEnabled())return;const e=this.gridElement;if(!e)return;const t=e.querySelector(".tbw-grid-root"),{mode:s}=this.config;if(this.pendingRowKeyUpdate&&"row"===s){const{shiftKey:e}=this.pendingRowKeyUpdate;this.pendingRowKeyUpdate=null;const t=this.grid._focusRow;if(e&&null!==this.anchor){this.selected.clear();const e=Math.min(this.anchor,t),s=Math.max(this.anchor,t);for(let t=e;t<=s;t++)this.isRowSelectable(t)&&this.selected.add(t)}else this.isRowSelectable(t)?(this.selected.clear(),this.selected.add(t),this.anchor=t):this.selected.clear();this.lastSelected=t,this.emit("selection-change",this.#e())}if(this.pendingKeyboardUpdate&&"range"===s){const{shiftKey:e}=this.pendingKeyboardUpdate;this.pendingKeyboardUpdate=null;const t=this.grid._focusRow,s=this.grid._focusCol;if(e&&this.cellAnchor){const e=a(this.cellAnchor,{row:t,col:s});this.ranges=[e],this.activeRange=e}else e||(this.ranges=[],this.activeRange=null,this.cellAnchor={row:t,col:s});this.emit("selection-change",this.#e())}this.#i(s),this.gridElement.setAttribute("data-selection-mode",s),t&&t.classList.toggle("selecting",this.isDragging),this.#l()}onScrollRender(){this.isSelectionEnabled()&&this.#l()}getSelection(){return{mode:this.config.mode,ranges:this.#e().ranges,anchor:this.cellAnchor}}getSelectedCells(){return function(e){const t=new Map;for(const s of e)for(const e of c(s))t.set(`${e.row},${e.col}`,e);return[...t.values()]}(this.ranges)}isCellSelected(e,t){return n(e,t,this.ranges)}selectAll(){const{mode:e,multiSelect:t}=this.config;if(!1!==t)if("row"===e){this.selected.clear();for(let e=0;e<this.rows.length;e++)this.isRowSelectable(e)&&this.selected.add(e);this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}else if("range"===e){const e=this.rows.length,t=this.columns.length;if(e>0&&t>0){const s={startRow:0,startCol:0,endRow:e-1,endCol:t-1};this.ranges=[s],this.activeRange=s,this.emit("selection-change",this.#e()),this.requestAfterRender()}}}selectRows(e){if("row"!==this.config.mode)return;const t=!1===this.config.multiSelect&&e.length>1?[e[e.length-1]]:e;this.selected.clear();for(const s of t)s>=0&&s<this.rows.length&&this.isRowSelectable(s)&&this.selected.add(s);this.anchor=t.length>0?t[t.length-1]:null,this.explicitSelection=!0,this.emit("selection-change",this.#e()),this.requestAfterRender()}getSelectedRowIndices(){return[...this.selected].sort((e,t)=>e-t)}getSelectedRows(){const{mode:e}=this.config,t=this.rows;if("row"===e)return this.getSelectedRowIndices().filter(e=>e>=0&&e<t.length).map(e=>t[e]);if("cell"===e&&this.selectedCell){const{row:e}=this.selectedCell;return e>=0&&e<t.length?[t[e]]:[]}if("range"===e&&this.ranges.length>0){const e=new Set;for(const s of this.ranges){const i=Math.max(0,Math.min(s.startRow,s.endRow)),l=Math.min(t.length-1,Math.max(s.startRow,s.endRow));for(let t=i;t<=l;t++)e.add(t)}return[...e].sort((e,t)=>e-t).map(e=>t[e])}return[]}clearSelection(){this.selectedCell=null,this.selected.clear(),this.anchor=null,this.ranges=[],this.activeRange=null,this.cellAnchor=null,this.emit("selection-change",{mode:this.config.mode,ranges:[]}),this.requestAfterRender()}setRanges(e){this.ranges=e.map(e=>({startRow:e.from.row,startCol:e.from.col,endRow:e.to.row,endCol:e.to.col})),this.activeRange=this.ranges.length>0?this.ranges[this.ranges.length-1]:null,this.emit("selection-change",{mode:this.config.mode,ranges:r(this.ranges)}),this.requestAfterRender()}#e(){return function(e,t,s){if("cell"===e&&t.selectedCell)return{mode:e,ranges:[{from:{row:t.selectedCell.row,col:t.selectedCell.col},to:{row:t.selectedCell.row,col:t.selectedCell.col}}]};if("row"===e&&t.selected.size>0){const i=[...t.selected].sort((e,t)=>e-t),l=[];let o=i[0],r=o;for(let e=1;e<i.length;e++)i[e]===r+1?r=i[e]:(l.push({from:{row:o,col:0},to:{row:r,col:s-1}}),o=i[e],r=o);return l.push({from:{row:o,col:0},to:{row:r,col:s-1}}),{mode:e,ranges:l}}return"range"===e&&t.ranges.length>0?{mode:e,ranges:r(t.ranges)}:{mode:e,ranges:[]}}(this.config.mode,{selectedCell:this.selectedCell,selected:this.selected,ranges:this.ranges},this.columns.length)}}e.SelectionPlugin=g,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=selection.umd.js.map
|