@toolbox-web/grid 1.21.1 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -8
- package/all.js +2 -6850
- package/all.js.map +1 -1
- package/index.js +1 -4352
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +75 -8
- package/lib/core/grid.d.ts.map +1 -1
- package/lib/core/internal/rows.d.ts.map +1 -1
- package/lib/core/plugin/base-plugin.d.ts +8 -2
- package/lib/core/plugin/base-plugin.d.ts.map +1 -1
- package/lib/core/styles/index.d.ts.map +1 -1
- package/lib/core/types.d.ts +84 -2
- package/lib/core/types.d.ts.map +1 -1
- package/lib/plugins/clipboard/index.js +1 -733
- package/lib/plugins/clipboard/index.js.map +1 -1
- package/lib/plugins/clipboard/types.d.ts +5 -0
- package/lib/plugins/clipboard/types.d.ts.map +1 -1
- package/lib/plugins/column-virtualization/index.js +1 -560
- package/lib/plugins/column-virtualization/index.js.map +1 -1
- package/lib/plugins/column-virtualization/types.d.ts +5 -0
- package/lib/plugins/column-virtualization/types.d.ts.map +1 -1
- package/lib/plugins/context-menu/index.js +1 -754
- package/lib/plugins/context-menu/index.js.map +1 -1
- package/lib/plugins/context-menu/types.d.ts +5 -0
- package/lib/plugins/context-menu/types.d.ts.map +1 -1
- package/lib/plugins/editing/EditingPlugin.d.ts.map +1 -1
- package/lib/plugins/editing/index.d.ts +1 -1
- package/lib/plugins/editing/index.d.ts.map +1 -1
- package/lib/plugins/editing/index.js +1 -1539
- package/lib/plugins/editing/index.js.map +1 -1
- package/lib/plugins/editing/types.d.ts +49 -0
- package/lib/plugins/editing/types.d.ts.map +1 -1
- package/lib/plugins/export/index.js +1 -589
- package/lib/plugins/export/index.js.map +1 -1
- package/lib/plugins/export/types.d.ts +5 -0
- package/lib/plugins/export/types.d.ts.map +1 -1
- package/lib/plugins/filtering/FilteringPlugin.d.ts.map +1 -1
- package/lib/plugins/filtering/filter-model.d.ts.map +1 -1
- package/lib/plugins/filtering/index.js +1 -1283
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/filtering/types.d.ts +7 -2
- package/lib/plugins/filtering/types.d.ts.map +1 -1
- package/lib/plugins/grouping-columns/index.js +1 -726
- package/lib/plugins/grouping-columns/index.js.map +1 -1
- package/lib/plugins/grouping-columns/types.d.ts +3 -0
- package/lib/plugins/grouping-columns/types.d.ts.map +1 -1
- package/lib/plugins/grouping-rows/index.js +2 -905
- package/lib/plugins/grouping-rows/index.js.map +1 -1
- package/lib/plugins/grouping-rows/types.d.ts +5 -0
- package/lib/plugins/grouping-rows/types.d.ts.map +1 -1
- package/lib/plugins/master-detail/index.js +1 -950
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/types.d.ts +5 -0
- package/lib/plugins/master-detail/types.d.ts.map +1 -1
- package/lib/plugins/multi-sort/index.js +1 -553
- package/lib/plugins/multi-sort/index.js.map +1 -1
- package/lib/plugins/multi-sort/types.d.ts +5 -0
- package/lib/plugins/multi-sort/types.d.ts.map +1 -1
- package/lib/plugins/pinned-columns/index.js +1 -688
- package/lib/plugins/pinned-columns/index.js.map +1 -1
- package/lib/plugins/pinned-columns/types.d.ts +3 -0
- package/lib/plugins/pinned-columns/types.d.ts.map +1 -1
- package/lib/plugins/pinned-rows/index.js +1 -704
- package/lib/plugins/pinned-rows/index.js.map +1 -1
- package/lib/plugins/pinned-rows/types.d.ts +5 -0
- package/lib/plugins/pinned-rows/types.d.ts.map +1 -1
- package/lib/plugins/pivot/index.js +1 -1191
- package/lib/plugins/pivot/index.js.map +1 -1
- package/lib/plugins/pivot/types.d.ts +5 -0
- package/lib/plugins/pivot/types.d.ts.map +1 -1
- package/lib/plugins/print/index.js +1 -691
- package/lib/plugins/print/index.js.map +1 -1
- package/lib/plugins/print/types.d.ts +3 -0
- package/lib/plugins/print/types.d.ts.map +1 -1
- package/lib/plugins/reorder/index.js +1 -703
- package/lib/plugins/reorder/index.js.map +1 -1
- package/lib/plugins/reorder/types.d.ts +5 -0
- package/lib/plugins/reorder/types.d.ts.map +1 -1
- package/lib/plugins/responsive/index.js +1 -971
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/responsive/types.d.ts +5 -0
- package/lib/plugins/responsive/types.d.ts.map +1 -1
- package/lib/plugins/row-reorder/index.js +1 -728
- package/lib/plugins/row-reorder/index.js.map +1 -1
- package/lib/plugins/row-reorder/types.d.ts +5 -0
- package/lib/plugins/row-reorder/types.d.ts.map +1 -1
- package/lib/plugins/selection/index.js +1 -1071
- package/lib/plugins/selection/index.js.map +1 -1
- package/lib/plugins/selection/types.d.ts +3 -0
- package/lib/plugins/selection/types.d.ts.map +1 -1
- package/lib/plugins/server-side/index.js +1 -521
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/server-side/types.d.ts +5 -0
- package/lib/plugins/server-side/types.d.ts.map +1 -1
- package/lib/plugins/tree/index.js +1 -686
- package/lib/plugins/tree/index.js.map +1 -1
- package/lib/plugins/tree/types.d.ts +5 -0
- package/lib/plugins/tree/types.d.ts.map +1 -1
- package/lib/plugins/undo-redo/index.js +1 -584
- package/lib/plugins/undo-redo/index.js.map +1 -1
- package/lib/plugins/undo-redo/types.d.ts +5 -0
- package/lib/plugins/undo-redo/types.d.ts.map +1 -1
- package/lib/plugins/visibility/index.js +1 -792
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +5 -0
- package/lib/plugins/visibility/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/umd/grid.all.umd.js +1 -186
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -90
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/clipboard.umd.js +1 -6
- package/umd/plugins/clipboard.umd.js.map +1 -1
- package/umd/plugins/column-virtualization.umd.js +1 -1
- package/umd/plugins/column-virtualization.umd.js.map +1 -1
- package/umd/plugins/context-menu.umd.js +1 -1
- package/umd/plugins/context-menu.umd.js.map +1 -1
- package/umd/plugins/editing.umd.js +1 -1
- package/umd/plugins/editing.umd.js.map +1 -1
- package/umd/plugins/export.umd.js +1 -13
- 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 -4
- 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/multi-sort.umd.js +1 -1
- package/umd/plugins/multi-sort.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/print.umd.js +1 -75
- package/umd/plugins/print.umd.js.map +1 -1
- package/umd/plugins/reorder.umd.js +1 -1
- package/umd/plugins/reorder.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/row-reorder.umd.js +1 -1
- package/umd/plugins/row-reorder.umd.js.map +1 -1
- package/umd/plugins/selection.umd.js +1 -3
- 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 +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":"print.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/print/print-isolated.ts","../../../../../libs/grid/src/lib/plugins/print/PrintPlugin.ts"],"sourcesContent":["/**\n * Utility for printing a grid in isolation by hiding all other page content.\n *\n * This approach keeps the grid in place (with virtualization disabled by PrintPlugin)\n * and uses CSS to hide everything else on the page during printing.\n */\n\nimport type { PrintOrientation } from './types';\n\nexport interface PrintIsolatedOptions {\n /** Page orientation hint */\n orientation?: PrintOrientation;\n}\n\n/** ID for the isolation stylesheet */\nconst ISOLATION_STYLE_ID = 'tbw-print-isolation-style';\n\n/**\n * Create a stylesheet that hides everything except the target grid.\n * Uses the grid's ID to target it specifically.\n */\nfunction createIsolationStylesheet(gridId: string, orientation: PrintOrientation): HTMLStyleElement {\n const style = document.createElement('style');\n style.id = ISOLATION_STYLE_ID;\n style.textContent = `\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${gridId}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${gridId} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${gridId},\n #${gridId} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${gridId}),\n body *:has(#${gridId}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${gridId}) > *:not(:has(#${gridId})):not(#${gridId}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${orientation};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `;\n return style;\n}\n\n/**\n * Print a grid in isolation by hiding all other page content.\n *\n * This function adds a temporary stylesheet that uses CSS to hide everything\n * on the page except the target grid during printing. The grid stays in place\n * with all its data (virtualization should be disabled separately).\n *\n * @param gridElement - The tbw-grid element to print (must have an ID)\n * @param options - Optional configuration\n * @returns Promise that resolves when the print dialog closes\n *\n * @example\n * ```typescript\n * import { printGridIsolated } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * await printGridIsolated(grid, { orientation: 'landscape' });\n * ```\n */\nexport async function printGridIsolated(gridElement: HTMLElement, options: PrintIsolatedOptions = {}): Promise<void> {\n const { orientation = 'landscape' } = options;\n\n const gridId = gridElement.id;\n\n // Warn if multiple elements share this ID (user-set IDs could collide)\n const elementsWithId = document.querySelectorAll(`#${CSS.escape(gridId)}`);\n if (elementsWithId.length > 1) {\n console.warn(\n `[tbw-grid:print] Multiple elements found with id=\"${gridId}\". ` +\n `Print isolation may not work correctly. Ensure each grid has a unique ID.`,\n );\n }\n\n // Remove any existing isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n\n // Add the isolation stylesheet\n const isolationStyle = createIsolationStylesheet(gridId, orientation);\n document.head.appendChild(isolationStyle);\n\n return new Promise((resolve) => {\n // Listen for afterprint event to cleanup\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n // Remove isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n }, 5000);\n });\n}\n","/**\n * Print Plugin (Class-based)\n *\n * Provides print layout functionality for tbw-grid.\n * Temporarily disables virtualization to render all rows and uses\n * @media print CSS for print-optimized styling.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { InternalGrid, ToolbarContentDefinition } from '../../core/types';\nimport { printGridIsolated } from './print-isolated';\nimport styles from './print.css?inline';\nimport type { PrintCompleteDetail, PrintConfig, PrintParams, PrintStartDetail } from './types';\n\n/**\n * Extended grid interface for PrintPlugin internal access.\n * Includes registerToolbarContent which is available on the grid class\n * but not exposed in the standard plugin API.\n */\ninterface PrintGridRef extends InternalGrid {\n registerToolbarContent?(content: ToolbarContentDefinition): void;\n unregisterToolbarContent?(contentId: string): void;\n}\n\n/** Default configuration */\nconst DEFAULT_CONFIG: Required<PrintConfig> = {\n button: false,\n orientation: 'landscape',\n warnThreshold: 500,\n maxRows: 0,\n includeTitle: true,\n includeTimestamp: true,\n title: '',\n isolate: false,\n};\n\n/**\n * Print Plugin for tbw-grid\n *\n * Enables printing the full grid content by temporarily disabling virtualization\n * and applying print-optimized styles. Handles large datasets gracefully with\n * configurable row limits.\n *\n * ## Installation\n *\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `button` | `boolean` | `false` | Show print button in toolbar |\n * | `orientation` | `'portrait' \\| 'landscape'` | `'landscape'` | Page orientation |\n * | `warnThreshold` | `number` | `500` | Show confirmation dialog when rows exceed this (0 = no warning) |\n * | `maxRows` | `number` | `0` | Hard limit on printed rows (0 = unlimited) |\n * | `includeTitle` | `boolean` | `true` | Include grid title in print |\n * | `includeTimestamp` | `boolean` | `true` | Include timestamp in footer |\n * | `title` | `string` | `''` | Custom print title |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `print` | `(params?) => Promise<void>` | Trigger print dialog |\n * | `isPrinting` | `() => boolean` | Check if print is in progress |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `print-start` | `PrintStartDetail` | Fired when print begins |\n * | `print-complete` | `PrintCompleteDetail` | Fired when print completes |\n *\n * @example Basic Print\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * plugins: [new PrintPlugin()],\n * };\n *\n * // Trigger print\n * const printPlugin = grid.getPlugin(PrintPlugin);\n * await printPlugin.print();\n * ```\n *\n * @example With Toolbar Button\n * ```ts\n * grid.gridConfig = {\n * plugins: [new PrintPlugin({ button: true, orientation: 'landscape' })],\n * };\n * ```\n *\n * @see {@link PrintConfig} for all configuration options\n */\nexport class PrintPlugin extends BaseGridPlugin<PrintConfig> {\n /** @internal */\n readonly name = 'print';\n\n /** @internal */\n override readonly version = '1.0.0';\n\n /** CSS styles for print mode */\n override readonly styles = styles;\n\n /** Current print state */\n #printing = false;\n\n /** Saved column visibility state */\n #savedHiddenColumns: Map<string, boolean> | null = null;\n\n /** Saved virtualization state */\n #savedVirtualization: { bypassThreshold: number } | null = null;\n\n /** Saved rows when maxRows limit is applied */\n #savedRows: unknown[] | null = null;\n\n /** Print header element */\n #printHeader: HTMLElement | null = null;\n\n /** Print footer element */\n #printFooter: HTMLElement | null = null;\n\n /** Applied scale factor (legacy, used for cleanup) */\n #appliedScale: number | null = null;\n\n /**\n * Get the grid typed as PrintGridRef for internal access.\n */\n get #internalGrid(): PrintGridRef {\n return this.grid as unknown as PrintGridRef;\n }\n\n /**\n * Check if print is currently in progress\n */\n isPrinting(): boolean {\n return this.#printing;\n }\n\n /**\n * Trigger the browser print dialog\n *\n * This method:\n * 1. Validates row count against maxRows limit\n * 2. Disables virtualization to render all rows\n * 3. Applies print-specific CSS classes\n * 4. Opens the browser print dialog (or isolated window if `isolate: true`)\n * 5. Restores normal state after printing\n *\n * @param params - Optional parameters to override config for this print\n * @param params.isolate - If true, prints in an isolated window containing only the grid\n * @returns Promise that resolves when print dialog closes\n */\n async print(params?: PrintParams): Promise<void> {\n if (this.#printing) {\n console.warn('[PrintPlugin] Print already in progress');\n return;\n }\n\n const grid = this.gridElement;\n if (!grid) {\n console.warn('[PrintPlugin] Grid not available');\n return;\n }\n\n const config = { ...DEFAULT_CONFIG, ...this.config, ...params };\n const rows = this.rows;\n const originalRowCount = rows.length;\n let rowCount = originalRowCount;\n let limitApplied = false;\n\n // Check if we should warn about large datasets\n if (config.warnThreshold > 0 && originalRowCount > config.warnThreshold) {\n const limitInfo =\n config.maxRows > 0 ? `\\n\\nNote: Output will be limited to ${config.maxRows.toLocaleString()} rows.` : '';\n const proceed = confirm(\n `This grid has ${originalRowCount.toLocaleString()} rows. ` +\n `Printing large datasets may cause performance issues or browser slowdowns.${limitInfo}\\n\\n` +\n `Click OK to continue, or Cancel to abort.`,\n );\n if (!proceed) {\n return;\n }\n }\n\n // Apply hard row limit if configured\n if (config.maxRows > 0 && originalRowCount > config.maxRows) {\n rowCount = config.maxRows;\n limitApplied = true;\n }\n\n this.#printing = true;\n\n // Track timing for duration reporting\n const startTime = performance.now();\n\n // Emit print-start event\n this.emit<PrintStartDetail>('print-start', {\n rowCount,\n limitApplied,\n originalRowCount,\n });\n\n try {\n // Save current virtualization state\n const internalGrid = this.#internalGrid;\n this.#savedVirtualization = {\n bypassThreshold: internalGrid._virtualization?.bypassThreshold ?? 24,\n };\n\n // Hide columns marked with printHidden\n this.#hidePrintColumns();\n\n // Apply row limit if configured\n if (limitApplied) {\n this.#savedRows = this.sourceRows;\n // Set limited rows on the grid\n (this.grid as unknown as { rows: unknown[] }).rows = this.sourceRows.slice(0, rowCount);\n // Wait for grid to process new rows\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Add print header if configured\n if (config.includeTitle || config.includeTimestamp) {\n this.#addPrintHeader(config);\n }\n\n // Disable virtualization to render all rows\n // This forces the grid to render all rows in the DOM\n await this.#disableVirtualization();\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Add orientation class for @page rules\n grid.classList.add(`print-${config.orientation}`);\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Trigger browser print dialog (isolated or inline)\n if (config.isolate) {\n await this.#printInIsolatedWindow(config);\n } else {\n await this.#triggerPrint();\n }\n\n // Emit print-complete event\n this.emit<PrintCompleteDetail>('print-complete', {\n success: true,\n rowCount,\n duration: Math.round(performance.now() - startTime),\n });\n } catch (error) {\n console.error('[PrintPlugin] Print failed:', error);\n this.emit<PrintCompleteDetail>('print-complete', {\n success: false,\n rowCount: 0,\n duration: Math.round(performance.now() - startTime),\n });\n } finally {\n // Restore normal state\n this.#cleanup();\n this.#printing = false;\n }\n }\n\n /**\n * Add print header with title and timestamp\n */\n #addPrintHeader(config: Required<PrintConfig>): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Create print header\n this.#printHeader = document.createElement('div');\n this.#printHeader.className = 'tbw-print-header';\n\n // Title\n if (config.includeTitle) {\n const title = config.title || this.grid.effectiveConfig?.shell?.header?.title || 'Grid Data';\n const titleEl = document.createElement('div');\n titleEl.className = 'tbw-print-header-title';\n titleEl.textContent = title;\n this.#printHeader.appendChild(titleEl);\n }\n\n // Timestamp\n if (config.includeTimestamp) {\n const timestampEl = document.createElement('div');\n timestampEl.className = 'tbw-print-header-timestamp';\n timestampEl.textContent = `Printed: ${new Date().toLocaleString()}`;\n this.#printHeader.appendChild(timestampEl);\n }\n\n // Insert at the beginning of the grid\n grid.insertBefore(this.#printHeader, grid.firstChild);\n\n // Create print footer\n this.#printFooter = document.createElement('div');\n this.#printFooter.className = 'tbw-print-footer';\n this.#printFooter.textContent = `Page generated from ${window.location.hostname}`;\n grid.appendChild(this.#printFooter);\n }\n\n /**\n * Disable virtualization to render all rows\n */\n async #disableVirtualization(): Promise<void> {\n const internalGrid = this.#internalGrid;\n if (!internalGrid._virtualization) return;\n\n // Set bypass threshold higher than total row count to disable virtualization\n // This makes the grid render all rows (up to maxRows) instead of just visible ones\n const totalRows = this.rows.length;\n internalGrid._virtualization.bypassThreshold = totalRows + 100;\n\n // Force a full refresh to re-render with virtualization disabled\n internalGrid.refreshVirtualWindow(true);\n\n // Wait for render to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Trigger the browser print dialog\n */\n async #triggerPrint(): Promise<void> {\n return new Promise((resolve) => {\n // Listen for afterprint event\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n // Guard against test environment teardown where window may be undefined\n if (typeof window !== 'undefined') {\n window.removeEventListener('afterprint', onAfterPrint);\n }\n resolve();\n }, 1000);\n });\n }\n\n /**\n * Print in isolation by hiding all other page content.\n * This excludes navigation, sidebars, etc. while keeping the grid in place.\n */\n async #printInIsolatedWindow(config: Required<PrintConfig>): Promise<void> {\n const grid = this.gridElement;\n if (!grid) return;\n\n await printGridIsolated(grid, {\n orientation: config.orientation,\n });\n }\n\n /**\n * Hide columns marked with printHidden: true\n */\n #hidePrintColumns(): void {\n const columns = this.columns;\n if (!columns) return;\n\n // Save current hidden state and hide print columns\n this.#savedHiddenColumns = new Map();\n\n for (const col of columns) {\n if (col.printHidden && col.field) {\n // Save current visibility state (true = visible, false = hidden)\n this.#savedHiddenColumns.set(col.field, !col.hidden);\n // Hide the column for printing\n this.grid.setColumnVisible(col.field, false);\n }\n }\n }\n\n /**\n * Restore columns that were hidden for printing\n */\n #restorePrintColumns(): void {\n if (!this.#savedHiddenColumns) return;\n\n for (const [field, wasVisible] of this.#savedHiddenColumns) {\n // Restore original visibility\n this.grid.setColumnVisible(field, wasVisible);\n }\n\n this.#savedHiddenColumns = null;\n }\n\n /**\n * Cleanup after printing\n */\n #cleanup(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Restore columns that were hidden for printing\n this.#restorePrintColumns();\n\n // Remove orientation classes (both original and possibly switched)\n grid.classList.remove('print-portrait', 'print-landscape');\n\n // Remove scaling transform if applied (legacy)\n if (this.#appliedScale !== null) {\n grid.style.transform = '';\n grid.style.transformOrigin = '';\n grid.style.width = '';\n this.#appliedScale = null;\n }\n\n // Remove print header/footer\n if (this.#printHeader) {\n this.#printHeader.remove();\n this.#printHeader = null;\n }\n if (this.#printFooter) {\n this.#printFooter.remove();\n this.#printFooter = null;\n }\n\n // Restore virtualization\n const internalGrid = this.#internalGrid;\n if (this.#savedVirtualization && internalGrid._virtualization) {\n internalGrid._virtualization.bypassThreshold = this.#savedVirtualization.bypassThreshold;\n internalGrid.refreshVirtualWindow(true);\n this.#savedVirtualization = null;\n }\n\n // Restore original rows if they were limited\n if (this.#savedRows !== null) {\n (this.grid as unknown as { rows: unknown[] }).rows = this.#savedRows;\n this.#savedRows = null;\n }\n }\n\n /**\n * Register toolbar button if configured\n * @internal\n */\n override afterRender(): void {\n // Register toolbar on first render when button is enabled\n if (this.config?.button && !this.#toolbarRegistered) {\n this.#registerToolbarButton();\n this.#toolbarRegistered = true;\n }\n }\n\n /** Track if toolbar button is registered */\n #toolbarRegistered = false;\n\n /**\n * Register print button in toolbar\n */\n #registerToolbarButton(): void {\n const grid = this.#internalGrid;\n\n // Register toolbar content\n grid.registerToolbarContent?.({\n id: 'print-button',\n order: 900, // High order to appear at the end\n render: (container: HTMLElement) => {\n const button = document.createElement('button');\n button.className = 'tbw-toolbar-btn tbw-print-btn';\n button.title = 'Print grid';\n button.type = 'button';\n\n // Use print icon\n const icon = this.resolveIcon('print') || '🖨️';\n this.setIcon(button, icon);\n\n button.addEventListener(\n 'click',\n () => {\n this.print();\n },\n { signal: this.disconnectSignal },\n );\n\n container.appendChild(button);\n },\n });\n }\n}\n"],"names":["ISOLATION_STYLE_ID","createIsolationStylesheet","gridId","orientation","style","printGridIsolated","gridElement","options","isolationStyle","resolve","onAfterPrint","DEFAULT_CONFIG","PrintPlugin","BaseGridPlugin","styles","#printing","#savedHiddenColumns","#savedVirtualization","#savedRows","#printHeader","#printFooter","#appliedScale","#internalGrid","params","grid","config","originalRowCount","rowCount","limitApplied","limitInfo","startTime","internalGrid","#hidePrintColumns","#addPrintHeader","#disableVirtualization","#printInIsolatedWindow","#triggerPrint","error","#cleanup","title","titleEl","timestampEl","totalRows","columns","col","#restorePrintColumns","field","wasVisible","#toolbarRegistered","#registerToolbarButton","container","button","icon"],"mappings":"iUAeA,MAAMA,EAAqB,4BAM3B,SAASC,EAA0BC,EAAgBC,EAAiD,CAClG,MAAMC,EAAQ,SAAS,cAAc,OAAO,EAC5C,OAAAA,EAAM,GAAKJ,EACXI,EAAM,YAAc;AAAA;AAAA;AAAA;AAAA,sBAIAF,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,SAKnBA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAeNA,CAAM;AAAA,SACNA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA,sBAKOA,CAAM;AAAA,oBACRA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAeNA,CAAM,mBAAmBA,CAAM,WAAWA,CAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAMpDC,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAmBlBC,CACT,CAqBA,eAAsBC,EAAkBC,EAA0BC,EAAgC,GAAmB,CACnH,KAAM,CAAE,YAAAJ,EAAc,WAAA,EAAgBI,EAEhCL,EAASI,EAAY,GAGJ,SAAS,iBAA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AwBc,EAAa,kBAC5CA,EAAa,gBAAgB,gBAAkB,KAAKd,GAAqB,gBACzEc,EAAa,qBAAqB,EAAI,EACtC,KAAKd,GAAuB,MAI1B,KAAKC,KAAe,OACrB,KAAK,KAAwC,KAAO,KAAKA,GAC1D,KAAKA,GAAa,KAEtB,CAMS,aAAoB,CAEvB,KAAK,QAAQ,QAAU,CAAC,KAAK8B,KAC/B,KAAKC,GAAA,EACL,KAAKD,GAAqB,GAE9B,CAGAA,GAAqB,GAKrBC,IAA+B,CAChB,KAAK3B,GAGb,yBAAyB,CAC5B,GAAI,eACJ,MAAO,IACP,OAAS4B,GAA2B,CAClC,MAAMC,EAAS,SAAS,cAAc,QAAQ,EAC9CA,EAAO,UAAY,gCACnBA,EAAO,MAAQ,aACfA,EAAO,KAAO,SAGd,MAAMC,EAAO,KAAK,YAAY,OAAO,GAAK,MAC1C,KAAK,QAAQD,EAAQC,CAAI,EAEzBD,EAAO,iBACL,QACA,IAAM,CACJ,KAAK,MAAA,CACP,EACA,CAAE,OAAQ,KAAK,gBAAA,CAAiB,EAGlCD,EAAU,YAAYC,CAAM,CAC9B,CAAA,CACD,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"print.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/print/print-isolated.ts","../../../../../libs/grid/src/lib/plugins/print/PrintPlugin.ts"],"sourcesContent":["/**\n * Utility for printing a grid in isolation by hiding all other page content.\n *\n * This approach keeps the grid in place (with virtualization disabled by PrintPlugin)\n * and uses CSS to hide everything else on the page during printing.\n */\n\nimport type { PrintOrientation } from './types';\n\nexport interface PrintIsolatedOptions {\n /** Page orientation hint */\n orientation?: PrintOrientation;\n}\n\n/** ID for the isolation stylesheet */\nconst ISOLATION_STYLE_ID = 'tbw-print-isolation-style';\n\n/**\n * Create a stylesheet that hides everything except the target grid.\n * Uses the grid's ID to target it specifically.\n */\nfunction createIsolationStylesheet(gridId: string, orientation: PrintOrientation): HTMLStyleElement {\n const style = document.createElement('style');\n style.id = ISOLATION_STYLE_ID;\n style.textContent = `\n /* Print isolation: hide everything except the target grid */\n @media print {\n /* Hide all body children by default */\n body > *:not(#${gridId}) {\n display: none !important;\n }\n\n /* But show the grid and ensure it's not hidden by ancestor rules */\n #${gridId} {\n display: block !important;\n position: static !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n width: 100% !important;\n max-height: none !important;\n margin: 0 !important;\n padding: 0 !important;\n transform: none !important;\n }\n\n /* If grid is nested, we need to show its ancestors too */\n #${gridId},\n #${gridId} * {\n visibility: visible !important;\n }\n\n /* Walk up the DOM and show all ancestors of the grid */\n body *:has(> #${gridId}),\n body *:has(#${gridId}) {\n display: block !important;\n visibility: visible !important;\n opacity: 1 !important;\n overflow: visible !important;\n height: auto !important;\n position: static !important;\n transform: none !important;\n background: transparent !important;\n border: none !important;\n padding: 0 !important;\n margin: 0 !important;\n }\n\n /* Hide siblings of ancestors (everything that's not in the path to the grid) */\n body *:has(#${gridId}) > *:not(:has(#${gridId})):not(#${gridId}) {\n display: none !important;\n }\n\n /* Page settings */\n @page {\n size: ${orientation};\n margin: 1cm;\n }\n\n /* Ensure proper print styling */\n body {\n margin: 0 !important;\n padding: 0 !important;\n background: white !important;\n color-scheme: light !important;\n }\n }\n\n /* Screen: also apply isolation for print preview */\n @media screen {\n /* When this stylesheet is active, we're about to print */\n /* No screen-specific rules needed - isolation only applies to print */\n }\n `;\n return style;\n}\n\n/**\n * Print a grid in isolation by hiding all other page content.\n *\n * This function adds a temporary stylesheet that uses CSS to hide everything\n * on the page except the target grid during printing. The grid stays in place\n * with all its data (virtualization should be disabled separately).\n *\n * @param gridElement - The tbw-grid element to print (must have an ID)\n * @param options - Optional configuration\n * @returns Promise that resolves when the print dialog closes\n *\n * @example\n * ```typescript\n * import { printGridIsolated } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * await printGridIsolated(grid, { orientation: 'landscape' });\n * ```\n */\nexport async function printGridIsolated(gridElement: HTMLElement, options: PrintIsolatedOptions = {}): Promise<void> {\n const { orientation = 'landscape' } = options;\n\n const gridId = gridElement.id;\n\n // Warn if multiple elements share this ID (user-set IDs could collide)\n const elementsWithId = document.querySelectorAll(`#${CSS.escape(gridId)}`);\n if (elementsWithId.length > 1) {\n console.warn(\n `[tbw-grid:print] Multiple elements found with id=\"${gridId}\". ` +\n `Print isolation may not work correctly. Ensure each grid has a unique ID.`,\n );\n }\n\n // Remove any existing isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n\n // Add the isolation stylesheet\n const isolationStyle = createIsolationStylesheet(gridId, orientation);\n document.head.appendChild(isolationStyle);\n\n return new Promise((resolve) => {\n // Listen for afterprint event to cleanup\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n // Remove isolation stylesheet\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n window.removeEventListener('afterprint', onAfterPrint);\n document.getElementById(ISOLATION_STYLE_ID)?.remove();\n resolve();\n }, 5000);\n });\n}\n","/**\n * Print Plugin (Class-based)\n *\n * Provides print layout functionality for tbw-grid.\n * Temporarily disables virtualization to render all rows and uses\n * @media print CSS for print-optimized styling.\n */\n\nimport { BaseGridPlugin } from '../../core/plugin/base-plugin';\nimport type { InternalGrid, ToolbarContentDefinition } from '../../core/types';\nimport { printGridIsolated } from './print-isolated';\nimport styles from './print.css?inline';\nimport type { PrintCompleteDetail, PrintConfig, PrintParams, PrintStartDetail } from './types';\n\n/**\n * Extended grid interface for PrintPlugin internal access.\n * Includes registerToolbarContent which is available on the grid class\n * but not exposed in the standard plugin API.\n */\ninterface PrintGridRef extends InternalGrid {\n registerToolbarContent?(content: ToolbarContentDefinition): void;\n unregisterToolbarContent?(contentId: string): void;\n}\n\n/** Default configuration */\nconst DEFAULT_CONFIG: Required<PrintConfig> = {\n button: false,\n orientation: 'landscape',\n warnThreshold: 500,\n maxRows: 0,\n includeTitle: true,\n includeTimestamp: true,\n title: '',\n isolate: false,\n};\n\n/**\n * Print Plugin for tbw-grid\n *\n * Enables printing the full grid content by temporarily disabling virtualization\n * and applying print-optimized styles. Handles large datasets gracefully with\n * configurable row limits.\n *\n * ## Installation\n *\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n * ```\n *\n * ## Configuration Options\n *\n * | Option | Type | Default | Description |\n * |--------|------|---------|-------------|\n * | `button` | `boolean` | `false` | Show print button in toolbar |\n * | `orientation` | `'portrait' \\| 'landscape'` | `'landscape'` | Page orientation |\n * | `warnThreshold` | `number` | `500` | Show confirmation dialog when rows exceed this (0 = no warning) |\n * | `maxRows` | `number` | `0` | Hard limit on printed rows (0 = unlimited) |\n * | `includeTitle` | `boolean` | `true` | Include grid title in print |\n * | `includeTimestamp` | `boolean` | `true` | Include timestamp in footer |\n * | `title` | `string` | `''` | Custom print title |\n *\n * ## Programmatic API\n *\n * | Method | Signature | Description |\n * |--------|-----------|-------------|\n * | `print` | `(params?) => Promise<void>` | Trigger print dialog |\n * | `isPrinting` | `() => boolean` | Check if print is in progress |\n *\n * ## Events\n *\n * | Event | Detail | Description |\n * |-------|--------|-------------|\n * | `print-start` | `PrintStartDetail` | Fired when print begins |\n * | `print-complete` | `PrintCompleteDetail` | Fired when print completes |\n *\n * @example Basic Print\n * ```ts\n * import { PrintPlugin } from '@toolbox-web/grid/plugins/print';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * plugins: [new PrintPlugin()],\n * };\n *\n * // Trigger print\n * const printPlugin = grid.getPlugin(PrintPlugin);\n * await printPlugin.print();\n * ```\n *\n * @example With Toolbar Button\n * ```ts\n * grid.gridConfig = {\n * plugins: [new PrintPlugin({ button: true, orientation: 'landscape' })],\n * };\n * ```\n *\n * @see {@link PrintConfig} for all configuration options\n */\nexport class PrintPlugin extends BaseGridPlugin<PrintConfig> {\n /** @internal */\n readonly name = 'print';\n\n /** @internal */\n override readonly version = '1.0.0';\n\n /** CSS styles for print mode */\n override readonly styles = styles;\n\n /** Current print state */\n #printing = false;\n\n /** Saved column visibility state */\n #savedHiddenColumns: Map<string, boolean> | null = null;\n\n /** Saved virtualization state */\n #savedVirtualization: { bypassThreshold: number } | null = null;\n\n /** Saved rows when maxRows limit is applied */\n #savedRows: unknown[] | null = null;\n\n /** Print header element */\n #printHeader: HTMLElement | null = null;\n\n /** Print footer element */\n #printFooter: HTMLElement | null = null;\n\n /** Applied scale factor (legacy, used for cleanup) */\n #appliedScale: number | null = null;\n\n /**\n * Get the grid typed as PrintGridRef for internal access.\n */\n get #internalGrid(): PrintGridRef {\n return this.grid as unknown as PrintGridRef;\n }\n\n /**\n * Check if print is currently in progress\n */\n isPrinting(): boolean {\n return this.#printing;\n }\n\n /**\n * Trigger the browser print dialog\n *\n * This method:\n * 1. Validates row count against maxRows limit\n * 2. Disables virtualization to render all rows\n * 3. Applies print-specific CSS classes\n * 4. Opens the browser print dialog (or isolated window if `isolate: true`)\n * 5. Restores normal state after printing\n *\n * @param params - Optional parameters to override config for this print\n * @param params.isolate - If true, prints in an isolated window containing only the grid\n * @returns Promise that resolves when print dialog closes\n */\n async print(params?: PrintParams): Promise<void> {\n if (this.#printing) {\n console.warn('[PrintPlugin] Print already in progress');\n return;\n }\n\n const grid = this.gridElement;\n if (!grid) {\n console.warn('[PrintPlugin] Grid not available');\n return;\n }\n\n const config = { ...DEFAULT_CONFIG, ...this.config, ...params };\n const rows = this.rows;\n const originalRowCount = rows.length;\n let rowCount = originalRowCount;\n let limitApplied = false;\n\n // Check if we should warn about large datasets\n if (config.warnThreshold > 0 && originalRowCount > config.warnThreshold) {\n const limitInfo =\n config.maxRows > 0 ? `\\n\\nNote: Output will be limited to ${config.maxRows.toLocaleString()} rows.` : '';\n const proceed = confirm(\n `This grid has ${originalRowCount.toLocaleString()} rows. ` +\n `Printing large datasets may cause performance issues or browser slowdowns.${limitInfo}\\n\\n` +\n `Click OK to continue, or Cancel to abort.`,\n );\n if (!proceed) {\n return;\n }\n }\n\n // Apply hard row limit if configured\n if (config.maxRows > 0 && originalRowCount > config.maxRows) {\n rowCount = config.maxRows;\n limitApplied = true;\n }\n\n this.#printing = true;\n\n // Track timing for duration reporting\n const startTime = performance.now();\n\n // Emit print-start event\n this.emit<PrintStartDetail>('print-start', {\n rowCount,\n limitApplied,\n originalRowCount,\n });\n\n try {\n // Save current virtualization state\n const internalGrid = this.#internalGrid;\n this.#savedVirtualization = {\n bypassThreshold: internalGrid._virtualization?.bypassThreshold ?? 24,\n };\n\n // Hide columns marked with printHidden\n this.#hidePrintColumns();\n\n // Apply row limit if configured\n if (limitApplied) {\n this.#savedRows = this.sourceRows;\n // Set limited rows on the grid\n (this.grid as unknown as { rows: unknown[] }).rows = this.sourceRows.slice(0, rowCount);\n // Wait for grid to process new rows\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n\n // Add print header if configured\n if (config.includeTitle || config.includeTimestamp) {\n this.#addPrintHeader(config);\n }\n\n // Disable virtualization to render all rows\n // This forces the grid to render all rows in the DOM\n await this.#disableVirtualization();\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Add orientation class for @page rules\n grid.classList.add(`print-${config.orientation}`);\n\n // Wait for next frame to ensure DOM is updated\n await new Promise((resolve) => requestAnimationFrame(resolve));\n await new Promise((resolve) => requestAnimationFrame(resolve));\n\n // Trigger browser print dialog (isolated or inline)\n if (config.isolate) {\n await this.#printInIsolatedWindow(config);\n } else {\n await this.#triggerPrint();\n }\n\n // Emit print-complete event\n this.emit<PrintCompleteDetail>('print-complete', {\n success: true,\n rowCount,\n duration: Math.round(performance.now() - startTime),\n });\n } catch (error) {\n console.error('[PrintPlugin] Print failed:', error);\n this.emit<PrintCompleteDetail>('print-complete', {\n success: false,\n rowCount: 0,\n duration: Math.round(performance.now() - startTime),\n });\n } finally {\n // Restore normal state\n this.#cleanup();\n this.#printing = false;\n }\n }\n\n /**\n * Add print header with title and timestamp\n */\n #addPrintHeader(config: Required<PrintConfig>): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Create print header\n this.#printHeader = document.createElement('div');\n this.#printHeader.className = 'tbw-print-header';\n\n // Title\n if (config.includeTitle) {\n const title = config.title || this.grid.effectiveConfig?.shell?.header?.title || 'Grid Data';\n const titleEl = document.createElement('div');\n titleEl.className = 'tbw-print-header-title';\n titleEl.textContent = title;\n this.#printHeader.appendChild(titleEl);\n }\n\n // Timestamp\n if (config.includeTimestamp) {\n const timestampEl = document.createElement('div');\n timestampEl.className = 'tbw-print-header-timestamp';\n timestampEl.textContent = `Printed: ${new Date().toLocaleString()}`;\n this.#printHeader.appendChild(timestampEl);\n }\n\n // Insert at the beginning of the grid\n grid.insertBefore(this.#printHeader, grid.firstChild);\n\n // Create print footer\n this.#printFooter = document.createElement('div');\n this.#printFooter.className = 'tbw-print-footer';\n this.#printFooter.textContent = `Page generated from ${window.location.hostname}`;\n grid.appendChild(this.#printFooter);\n }\n\n /**\n * Disable virtualization to render all rows\n */\n async #disableVirtualization(): Promise<void> {\n const internalGrid = this.#internalGrid;\n if (!internalGrid._virtualization) return;\n\n // Set bypass threshold higher than total row count to disable virtualization\n // This makes the grid render all rows (up to maxRows) instead of just visible ones\n const totalRows = this.rows.length;\n internalGrid._virtualization.bypassThreshold = totalRows + 100;\n\n // Force a full refresh to re-render with virtualization disabled\n internalGrid.refreshVirtualWindow(true);\n\n // Wait for render to complete\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n /**\n * Trigger the browser print dialog\n */\n async #triggerPrint(): Promise<void> {\n return new Promise((resolve) => {\n // Listen for afterprint event\n const onAfterPrint = () => {\n window.removeEventListener('afterprint', onAfterPrint);\n resolve();\n };\n window.addEventListener('afterprint', onAfterPrint);\n\n // Trigger print\n window.print();\n\n // Fallback timeout in case afterprint doesn't fire (some browsers)\n setTimeout(() => {\n // Guard against test environment teardown where window may be undefined\n if (typeof window !== 'undefined') {\n window.removeEventListener('afterprint', onAfterPrint);\n }\n resolve();\n }, 1000);\n });\n }\n\n /**\n * Print in isolation by hiding all other page content.\n * This excludes navigation, sidebars, etc. while keeping the grid in place.\n */\n async #printInIsolatedWindow(config: Required<PrintConfig>): Promise<void> {\n const grid = this.gridElement;\n if (!grid) return;\n\n await printGridIsolated(grid, {\n orientation: config.orientation,\n });\n }\n\n /**\n * Hide columns marked with printHidden: true\n */\n #hidePrintColumns(): void {\n const columns = this.columns;\n if (!columns) return;\n\n // Save current hidden state and hide print columns\n this.#savedHiddenColumns = new Map();\n\n for (const col of columns) {\n if (col.printHidden && col.field) {\n // Save current visibility state (true = visible, false = hidden)\n this.#savedHiddenColumns.set(col.field, !col.hidden);\n // Hide the column for printing\n this.grid.setColumnVisible(col.field, false);\n }\n }\n }\n\n /**\n * Restore columns that were hidden for printing\n */\n #restorePrintColumns(): void {\n if (!this.#savedHiddenColumns) return;\n\n for (const [field, wasVisible] of this.#savedHiddenColumns) {\n // Restore original visibility\n this.grid.setColumnVisible(field, wasVisible);\n }\n\n this.#savedHiddenColumns = null;\n }\n\n /**\n * Cleanup after printing\n */\n #cleanup(): void {\n const grid = this.gridElement;\n if (!grid) return;\n\n // Restore columns that were hidden for printing\n this.#restorePrintColumns();\n\n // Remove orientation classes (both original and possibly switched)\n grid.classList.remove('print-portrait', 'print-landscape');\n\n // Remove scaling transform if applied (legacy)\n if (this.#appliedScale !== null) {\n grid.style.transform = '';\n grid.style.transformOrigin = '';\n grid.style.width = '';\n this.#appliedScale = null;\n }\n\n // Remove print header/footer\n if (this.#printHeader) {\n this.#printHeader.remove();\n this.#printHeader = null;\n }\n if (this.#printFooter) {\n this.#printFooter.remove();\n this.#printFooter = null;\n }\n\n // Restore virtualization\n const internalGrid = this.#internalGrid;\n if (this.#savedVirtualization && internalGrid._virtualization) {\n internalGrid._virtualization.bypassThreshold = this.#savedVirtualization.bypassThreshold;\n internalGrid.refreshVirtualWindow(true);\n this.#savedVirtualization = null;\n }\n\n // Restore original rows if they were limited\n if (this.#savedRows !== null) {\n (this.grid as unknown as { rows: unknown[] }).rows = this.#savedRows;\n this.#savedRows = null;\n }\n }\n\n /**\n * Register toolbar button if configured\n * @internal\n */\n override afterRender(): void {\n // Register toolbar on first render when button is enabled\n if (this.config?.button && !this.#toolbarRegistered) {\n this.#registerToolbarButton();\n this.#toolbarRegistered = true;\n }\n }\n\n /** Track if toolbar button is registered */\n #toolbarRegistered = false;\n\n /**\n * Register print button in toolbar\n */\n #registerToolbarButton(): void {\n const grid = this.#internalGrid;\n\n // Register toolbar content\n grid.registerToolbarContent?.({\n id: 'print-button',\n order: 900, // High order to appear at the end\n render: (container: HTMLElement) => {\n const button = document.createElement('button');\n button.className = 'tbw-toolbar-btn tbw-print-btn';\n button.title = 'Print grid';\n button.type = 'button';\n\n // Use print icon\n const icon = this.resolveIcon('print') || '🖨️';\n this.setIcon(button, icon);\n\n button.addEventListener(\n 'click',\n () => {\n this.print();\n },\n { signal: this.disconnectSignal },\n );\n\n container.appendChild(button);\n },\n });\n }\n}\n"],"names":["ISOLATION_STYLE_ID","async","printGridIsolated","gridElement","options","orientation","gridId","id","document","querySelectorAll","CSS","escape","length","console","warn","getElementById","remove","isolationStyle","style","createElement","textContent","createIsolationStylesheet","head","appendChild","Promise","resolve","onAfterPrint","window","removeEventListener","addEventListener","print","setTimeout","DEFAULT_CONFIG","button","warnThreshold","maxRows","includeTitle","includeTimestamp","title","isolate","PrintPlugin","BaseGridPlugin","name","version","styles","printing","savedHiddenColumns","savedVirtualization","savedRows","printHeader","printFooter","appliedScale","internalGrid","this","grid","isPrinting","params","config","originalRowCount","rows","rowCount","limitApplied","limitInfo","toLocaleString","confirm","startTime","performance","now","emit","bypassThreshold","_virtualization","hidePrintColumns","sourceRows","slice","addPrintHeader","disableVirtualization","requestAnimationFrame","classList","add","printInIsolatedWindow","triggerPrint","success","duration","Math","round","error","cleanup","className","effectiveConfig","shell","header","titleEl","timestampEl","Date","insertBefore","firstChild","location","hostname","totalRows","refreshVirtualWindow","columns","Map","col","printHidden","field","set","hidden","setColumnVisible","restorePrintColumns","wasVisible","transform","transformOrigin","width","afterRender","toolbarRegistered","registerToolbarButton","registerToolbarContent","order","render","container","type","icon","resolveIcon","setIcon","signal","disconnectSignal"],"mappings":"+UAeA,MAAMA,EAAqB,4BAsG3BC,eAAsBC,EAAkBC,EAA0BC,EAAgC,IAChG,MAAMC,YAAEA,EAAc,aAAgBD,EAEhCE,EAASH,EAAYI,GAGJC,SAASC,iBAAiB,IAAIC,IAAIC,OAAOL,MAC7CM,OAAS,GAC1BC,QAAQC,KACN,qDAAqDR,iFAMzDE,SAASO,eAAef,IAAqBgB,SAG7C,MAAMC,EAlHR,SAAmCX,EAAgBD,GACjD,MAAMa,EAAQV,SAASW,cAAc,SAyErC,OAxEAD,EAAMX,GAAKP,EACXkB,EAAME,YAAc,+JAIAd,0IAKbA,meAeAA,cACAA,kJAKaA,0BACFA,6gBAeAA,oBAAyBA,YAAiBA,+GAM9CD,yeAmBPa,CACT,CAuCyBG,CAA0Bf,EAAQD,GAGzD,OAFAG,SAASc,KAAKC,YAAYN,GAEnB,IAAIO,QAASC,IAElB,MAAMC,EAAe,KACnBC,OAAOC,oBAAoB,aAAcF,GAEzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KAEFE,OAAOE,iBAAiB,aAAcH,GAGtCC,OAAOG,QAGPC,WAAW,KACTJ,OAAOC,oBAAoB,aAAcF,GACzClB,SAASO,eAAef,IAAqBgB,SAC7CS,KACC,MAEP,OCrIMO,EAAwC,CAC5CC,QAAQ,EACR5B,YAAa,YACb6B,cAAe,IACfC,QAAS,EACTC,cAAc,EACdC,kBAAkB,EAClBC,MAAO,GACPC,SAAS,GAiEJ,MAAMC,UAAoBC,EAAAA,eAEtBC,KAAO,QAGEC,QAAU,QAGVC,kwEAGlBC,IAAY,EAGZC,GAAmD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M8F,MAAQ,GACnB3D,MAAKF,EAAgB,MAInBE,MAAKJ,IACPI,MAAKJ,EAAajC,SAClBqC,MAAKJ,EAAe,MAElBI,MAAKH,IACPG,MAAKH,EAAalC,SAClBqC,MAAKH,EAAe,MAItB,MAAME,EAAeC,MAAKD,EACtBC,MAAKN,GAAwBK,EAAakB,kBAC5ClB,EAAakB,gBAAgBD,gBAAkBhB,MAAKN,EAAqBsB,gBACzEjB,EAAa+C,sBAAqB,GAClC9C,MAAKN,EAAuB,MAIN,OAApBM,MAAKL,IACNK,KAAKC,KAAwCK,KAAON,MAAKL,EAC1DK,MAAKL,EAAa,KAEtB,CAMS,WAAAiE,GAEH5D,KAAKI,QAAQxB,SAAWoB,MAAK6D,IAC/B7D,MAAK8D,IACL9D,MAAK6D,GAAqB,EAE9B,CAGAA,IAAqB,EAKrB,EAAAC,GACE,MAAM7D,EAAOD,MAAKD,EAGlBE,EAAK8D,yBAAyB,CAC5B7G,GAAI,eACJ8G,MAAO,IACPC,OAASC,IACP,MAAMtF,EAASzB,SAASW,cAAc,UACtCc,EAAOsD,UAAY,gCACnBtD,EAAOK,MAAQ,aACfL,EAAOuF,KAAO,SAGd,MAAMC,EAAOpE,KAAKqE,YAAY,UAAY,MAC1CrE,KAAKsE,QAAQ1F,EAAQwF,GAErBxF,EAAOJ,iBACL,QACA,KACEwB,KAAKvB,SAEP,CAAE8F,OAAQvE,KAAKwE,mBAGjBN,EAAUhG,YAAYU,KAG5B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/keyboard","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_reorder={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,r){"use strict";function i(e,t,r){if(t===r)return e;if(t<0||t>=e.length)return e;if(r<0||r>e.length)return e;const i=[...e],[n]=i.splice(t,1);return i.splice(r,0,n),i}class n extends r.BaseGridPlugin{name="reorder";styles='@layer tbw-plugins{.header-row>.cell[draggable=true]{cursor:grab;position:relative}.header-row>.cell.dragging{opacity:.5;cursor:grabbing}.header-row>.cell.drop-before:before{content:"";position:absolute;left:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.header-row>.cell.drop-after:after{content:"";position:absolute;right:0;top:0;bottom:0;width:2px;background:var(--tbw-reorder-indicator, var(--tbw-color-accent));z-index:1}.cell.flip-animating{transition:transform var(--tbw-animation-duration, .2s) ease-out;will-change:transform;z-index:1}@keyframes reorder-fade-in{0%{opacity:0}to{opacity:1}}.cell.fade-animating{animation:reorder-fade-in var(--tbw-animation-duration, .2s) ease-out backwards}}';get defaultConfig(){return{animation:"flip"}}get animationType(){return!!this.isAnimationEnabled&&(void 0!==this.config.animation?this.config.animation:"flip")}get animationDuration(){return void 0!==this.config.animationDuration?this.config.animationDuration:super.animationDuration}isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;canMoveColumnWithPlugins(e){if(!e||!function(e){const t=e.meta??{};return!0!==t.lockPosition&&!0!==t.suppressMovable}(e))return!1;return!this.grid.query("canMoveColumn",e).includes(!1)}clearDragClasses(){this.gridElement?.querySelectorAll(".header-row > .cell").forEach(e=>{e.classList.remove("dragging","drop-target","drop-before","drop-after")})}attach(e){super.attach(e),e.addEventListener("column-reorder-request",e=>{const t=e.detail;t?.field&&"number"==typeof t.toIndex&&this.moveColumn(t.field,t.toIndex)},{signal:this.disconnectSignal})}detach(){this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}afterRender(){const e=this.gridElement;if(!e)return;e.querySelectorAll(".header-row > .cell").forEach(e=>{const t=e,r=t.getAttribute("data-field");if(!r)return;const n=this.columns.find(e=>e.field===r);this.canMoveColumnWithPlugins(n)?(t.draggable=!0,t.getAttribute("data-dragstart-bound")||(t.setAttribute("data-dragstart-bound","true"),t.addEventListener("dragstart",e=>{const i=this.getColumnOrder().indexOf(r);this.isDragging=!0,this.draggedField=r,this.draggedIndex=i,e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",r)),t.classList.add("dragging")}),t.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses()}),t.addEventListener("dragover",e=>{if(e.preventDefault(),!this.isDragging||this.draggedField===r)return;const i=t.getBoundingClientRect(),n=i.left+i.width/2,a=this.getColumnOrder().indexOf(r);this.dropIndex=e.clientX<n?a:a+1,t.classList.add("drop-target"),t.classList.toggle("drop-before",e.clientX<n),t.classList.toggle("drop-after",e.clientX>=n)}),t.addEventListener("dragleave",()=>{t.classList.remove("drop-target","drop-before","drop-after")}),t.addEventListener("drop",e=>{e.preventDefault();const t=this.draggedField,r=this.draggedIndex,n=this.dropIndex;if(!this.isDragging||null===t||null===r||null===n)return;const a=n>r?n-1:n,o=i(this.getColumnOrder(),r,a),s={field:t,fromIndex:r,toIndex:a,columnOrder:o};this.emitCancelable("column-move",s)||this.updateColumnOrder(o)}))):t.draggable=!1})}onKeyDown(e){if(!e.altKey||"ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;const r=this.grid,i=r._focusCol,n=r._visibleColumns;if(i<0||i>=n.length)return;const a=n[i];if(!this.canMoveColumnWithPlugins(a))return;const o=this.getColumnOrder(),s=o.indexOf(a.field);if(-1===s)return;const d="ArrowLeft"===e.key?s-1:s+1;if(d<0||d>=o.length)return;const l=n.find(e=>e.field===o[d]);return this.canMoveColumnWithPlugins(l)?(this.moveColumn(a.field,d),r._focusCol=d,t.ensureCellVisible(this.grid),e.preventDefault(),e.stopPropagation(),!0):void 0}getColumnOrder(){return this.grid.getColumnOrder()}moveColumn(e,t){const r=this.getColumnOrder(),n=r.indexOf(e);if(-1===n)return;const a=i(r,n,t);this.emitCancelable("column-move",{field:e,fromIndex:n,toIndex:t,columnOrder:a})||this.updateColumnOrder(a)}setColumnOrder(e){this.updateColumnOrder(e)}resetColumnOrder(){const e=this.columns.map(e=>e.field);this.updateColumnOrder(e)}captureHeaderPositions(){const e=new Map;return this.gridElement?.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const r=t.getAttribute("data-field");r&&e.set(r,t.getBoundingClientRect().left)}),e}animateFLIP(e){const t=this.gridElement;if(!t||0===e.size)return;const r=new Map;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(t=>{const i=t.getAttribute("data-field");if(!i)return;const n=e.get(i);if(void 0===n)return;const a=n-t.getBoundingClientRect().left;Math.abs(a)>1&&r.set(i,a)}),0===r.size)return;const i=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=r.get(e.getAttribute("data-field")??"");if(void 0!==t){const r=e;r.style.transform=`translateX(${t}px)`,i.push(r)}}),0===i.length)return;this.gridElement.offsetHeight;const n=this.animationDuration;requestAnimationFrame(()=>{i.forEach(e=>{e.classList.add("flip-animating"),e.style.transform=""}),setTimeout(()=>{i.forEach(e=>{e.style.transform="",e.classList.remove("flip-animating")})},n+50)})}animateFade(e){const t=this.gridElement;if(!t)return void e();const r=this.captureHeaderPositions();e();const i=new Set;if(t.querySelectorAll(".header-row > .cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(!t)return;const n=r.get(t);if(void 0===n)return;const a=e.getBoundingClientRect().left;Math.abs(n-a)>1&&i.add(t)}),0===i.size)return;const n=[];if(t.querySelectorAll(".cell[data-field]").forEach(e=>{const t=e.getAttribute("data-field");if(t&&i.has(t)){const t=e;t.classList.add("fade-animating"),n.push(t)}}),0===n.length)return;const a=this.animationDuration;setTimeout(()=>{n.forEach(e=>e.classList.remove("fade-animating"))},a+50)}updateColumnOrder(e){const t=this.animationType;if("flip"===t&&this.gridElement){const t=this.captureHeaderPositions();this.grid.setColumnOrder(e),requestAnimationFrame(()=>{this.gridElement.offsetHeight,this.animateFLIP(t)})}else"fade"===t?this.animateFade(()=>this.grid.setColumnOrder(e)):this.grid.setColumnOrder(e);this.grid.requestStateChange?.()}}e.ReorderPlugin=n,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=reorder.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reorder.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/reorder/column-drag.ts","../../../../../libs/grid/src/lib/plugins/reorder/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<TRow = unknown>(column: ColumnConfig<TRow>): 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, InternalGrid } 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';\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 '@toolbox-web/grid';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ReorderPlugin({ animation: 'flip', animationDuration: 200 })],\n * };\n *\n * // Persist column order\n * grid.addEventListener('column-move', (e) => {\n * localStorage.setItem('columnOrder', JSON.stringify(e.detail.columnOrder));\n * });\n * ```\n *\n * @example Prevent Moves That Break Group Boundaries\n * ```ts\n * grid.addEventListener('column-move', (e) => {\n * if (!isValidMoveWithinGroup(e.detail.field, e.detail.fromIndex, e.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 = 'reorder';\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 /**\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 (grid as unknown as HTMLElement).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.grid as unknown as { _focusCol: number; _visibleColumns: ColumnConfig[] };\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.grid as unknown as 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 (stable reference points)\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 // Set initial transform (First → Last position offset)\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 this.gridElement.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 // Wait for the scheduler to process the virtual window update (RAF)\n // before running FLIP animation on the new cells\n requestAnimationFrame(() => {\n void this.gridElement.offsetHeight;\n this.animateFLIP(oldPositions);\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":["canMoveColumn","column","meta","moveColumn","columns","fromIndex","toIndex","result","removed","ReorderPlugin","BaseGridPlugin","styles","h","grid","e","detail","gridEl","header","headerEl","field","c","orderIndex","rect","midX","draggedField","draggedIndex","dropIndex","effectiveToIndex","currentOrder","newOrder","event","focusCol","targetColumn","ensureCellVisible","order","originalOrder","positions","cell","oldPositions","deltas","oldLeft","deltaX","cells","el","duration","applyChange","movedFields","newLeft","animation"],"mappings":"sZAmBO,SAASA,EAA8BC,EAAqC,CAEjF,MAAMC,EAAOD,EAAO,MAAQ,CAAA,EAC5B,OAAOC,EAAK,eAAiB,IAAQA,EAAK,kBAAoB,EAChE,CAUO,SAASC,EAAWC,EAAmBC,EAAmBC,EAA2B,CAG1F,GAFID,IAAcC,GACdD,EAAY,GAAKA,GAAaD,EAAQ,QACtCE,EAAU,GAAKA,EAAUF,EAAQ,OAAQ,OAAOA,EAEpD,MAAMG,EAAS,CAAC,GAAGH,CAAO,EACpB,CAACI,CAAO,EAAID,EAAO,OAAOF,EAAW,CAAC,EAC5C,OAAAE,EAAO,OAAOD,EAAS,EAAGE,CAAO,EAC1BD,CACT,gwBC4CO,MAAME,UAAsBC,EAAAA,cAA8B,CAEtD,KAAO,UAEE,OAASC,EAG3B,IAAuB,eAAwC,CAC7D,MAAO,CACL,UAAW,MAAA,CAEf,CAMA,IAAY,eAAyC,CAEnD,OAAK,KAAK,mBAGN,KAAK,OAAO,YAAc,OAAkB,KAAK,OAAO,UAErD,OAL8B,EAMvC,CAMA,IAAuB,mBAA4B,CAEjD,OAAI,KAAK,OAAO,oBAAsB,OAC7B,KAAK,OAAO,kBAEd,MAAM,iBACf,CAGQ,WAAa,GACb,aAA8B,KAC9B,aAA8B,KAC9B,UAA2B,KAK3B,yBAAyBV,EAA2C,CAC1E,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Y,CAC/B,CAAC,CACH,MAAWU,IAAc,OACvB,KAAK,YAAY,IAAM,KAAK,KAAK,eAAenB,CAAQ,CAAC,EAEzD,KAAK,KAAK,eAAeA,CAAQ,EAGnC,KAAK,KAAK,qBAAA,CACZ,CAEF"}
|
|
1
|
+
{"version":3,"file":"reorder.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/reorder/column-drag.ts","../../../../../libs/grid/src/lib/plugins/reorder/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<TRow = unknown>(column: ColumnConfig<TRow>): 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, InternalGrid } 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';\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 '@toolbox-web/grid';\n * import { ReorderPlugin } from '@toolbox-web/grid/plugins/reorder';\n *\n * const grid = document.querySelector('tbw-grid');\n * grid.gridConfig = {\n * columns: [\n * { field: 'id', header: 'ID' },\n * { field: 'name', header: 'Name' },\n * { field: 'email', header: 'Email' },\n * ],\n * plugins: [new ReorderPlugin({ animation: 'flip', animationDuration: 200 })],\n * };\n *\n * // Persist column order\n * grid.addEventListener('column-move', (e) => {\n * localStorage.setItem('columnOrder', JSON.stringify(e.detail.columnOrder));\n * });\n * ```\n *\n * @example Prevent Moves That Break Group Boundaries\n * ```ts\n * grid.addEventListener('column-move', (e) => {\n * if (!isValidMoveWithinGroup(e.detail.field, e.detail.fromIndex, e.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 = 'reorder';\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 /**\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 (grid as unknown as HTMLElement).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.grid as unknown as { _focusCol: number; _visibleColumns: ColumnConfig[] };\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.grid as unknown as 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 (stable reference points)\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 // Set initial transform (First → Last position offset)\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 this.gridElement.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 // Wait for the scheduler to process the virtual window update (RAF)\n // before running FLIP animation on the new cells\n requestAnimationFrame(() => {\n void this.gridElement.offsetHeight;\n this.animateFLIP(oldPositions);\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","styles","defaultConfig","animation","animationType","this","isAnimationEnabled","config","animationDuration","super","isDragging","draggedField","draggedIndex","dropIndex","canMoveColumnWithPlugins","column","meta","lockPosition","suppressMovable","canMoveColumn","grid","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","requestStateChange"],"mappings":"oaAiCO,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,CACT,CC4CO,MAAMG,UAAsBC,EAAAA,eAExBC,KAAO,UAEEC,8vBAGlB,iBAAuBC,GACrB,MAAO,CACLC,UAAW,OAEf,CA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G3B1D,KAAKe,KAAK4F,sBACZ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("../../core/internal/keyboard"),require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin")):typeof define=="function"&&define.amd?define(["exports","../../core/internal/keyboard","../../core/internal/sanitize","../../core/plugin/base-plugin"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l.TbwGridPlugin_responsive={},l.TbwGrid,l.TbwGrid,l.TbwGrid))})(this,(function(l,h,g,f){"use strict";const w='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] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .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}';class v extends f.BaseGridPlugin{name="responsive";version="1.0.0";styles=w;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"}]};#o;#t=!1;#n;#b=!1;#a=0;#s=new Set;#d=new Set;#h=null;#l=[];isResponsive(){return this.#t}setResponsive(t){t!==this.#t&&(this.#t=t,this.#u(),this.emit("responsive-change",{isResponsive:t,width:this.#a,breakpoint:this.config.breakpoint??0}))}setBreakpoint(t){this.config.breakpoint=t,this.#m(this.#a)}setCardRenderer(t){this.config.cardRenderer=t,this.#t&&this.requestRender()}getWidth(){return this.#a}getActiveBreakpoint(){return this.#h}attach(t){super.attach(t),this.#R(),this.#c(this.config.hiddenColumns),this.config.breakpoints?.length&&(this.#l=[...this.config.breakpoints].sort((e,i)=>i.maxWidth-e.maxWidth)),this.#o=new ResizeObserver(e=>{const i=e[0]?.contentRect.width??0;this.#a=i,clearTimeout(this.#n),this.#n=setTimeout(()=>{this.#m(i)},this.config.debounceMs??100)}),this.#o.observe(this.gridElement)}#R(){const t=this.grid;if(!t||typeof t.querySelector!="function")return;const e=t.querySelector("tbw-grid-responsive-card");if(!e)return;const i=t;if(i.__frameworkAdapter?.parseResponsiveCardElement){const o=i.__frameworkAdapter.parseResponsiveCardElement(e);o&&(this.config={...this.config,cardRenderer:o})}const r=e.getAttribute("breakpoint"),s=e.getAttribute("card-row-height"),n=e.getAttribute("hidden-columns"),a=e.getAttribute("hide-header"),c=e.getAttribute("debounce-ms"),d={};if(r!==null){const o=parseInt(r,10);isNaN(o)||(d.breakpoint=o)}if(s!==null&&(d.cardRowHeight=s==="auto"?"auto":parseInt(s,10)),n!==null&&(d.hiddenColumns=n.split(",").map(o=>o.trim()).filter(o=>o.length>0)),a!==null&&(d.hideHeader=a!=="false"),c!==null){const o=parseInt(c,10);isNaN(o)||(d.debounceMs=o)}const u=e.innerHTML.trim();u&&!this.config.cardRenderer&&!i.__frameworkAdapter?.parseResponsiveCardElement&&(d.cardRenderer=o=>{const b=g.evalTemplateString(u,{value:o,row:o}),m=g.sanitizeHTML(b),p=document.createElement("div");return p.className="tbw-responsive-card-content",p.innerHTML=m,p}),Object.keys(d).length>0&&(this.config={...this.config,...d})}#c(t){if(this.#s.clear(),this.#d.clear(),!!t)for(const e of t)typeof e=="string"?this.#s.add(e):e.showValue?this.#d.add(e.field):this.#s.add(e.field)}detach(){this.#o?.disconnect(),this.#o=void 0,clearTimeout(this.#n),this.#n=void 0,this.gridElement&&this.gridElement.removeAttribute("data-responsive"),super.detach()}handleQuery(t){if(t.type==="isCardMode")return this.#t}afterRender(){if(this.#A(),!(this.#l.length>0?this.#h!==null:this.#t))return;const e=this.#s.size>0,i=this.#d.size>0;if(!e&&!i)return;const r=this.gridElement.querySelectorAll(".cell[data-field]");for(const s of r){const n=s.getAttribute("data-field");n&&(this.#s.has(n)?(s.setAttribute("data-responsive-hidden",""),s.removeAttribute("data-responsive-value-only")):this.#d.has(n)?(s.setAttribute("data-responsive-value-only",""),s.removeAttribute("data-responsive-hidden")):(s.removeAttribute("data-responsive-hidden"),s.removeAttribute("data-responsive-value-only")))}}#m(t){if(this.#l.length>0){this.#y(t);return}const e=this.config.breakpoint??0;e===0&&!this.#b&&(this.#b=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=e>0&&t<e;i!==this.#t&&(this.#t=i,this.#u(),this.emit("responsive-change",{isResponsive:i,width:t,breakpoint:e}),this.requestRender())}#y(t){let e=null;for(const r of this.#l)t<=r.maxWidth&&(e=r);if(e!==this.#h){this.#h=e,e?.hiddenColumns?this.#c(e.hiddenColumns):this.#c(this.config.hiddenColumns);const r=e?.cardLayout===!0;r!==this.#t&&(this.#t=r,this.#u()),this.emit("responsive-change",{isResponsive:this.#t,width:t,breakpoint:e?.maxWidth??0}),this.requestRender()}}#e;#u(){this.gridElement.toggleAttribute("data-responsive",this.#t);const t=this.config.animate!==!1;this.gridElement.toggleAttribute("data-responsive-animate",t),this.config.animationDuration&&this.gridElement.style.setProperty("--tbw-responsive-duration",`${this.config.animationDuration}ms`);const e=this.grid;if(this.#t){e._virtualization&&(this.#e=e._virtualization.rowHeight);const i=this.gridElement.querySelector(".tbw-scroll-area");i&&(i.scrollLeft=0)}else{const i=this.gridElement.querySelectorAll(".data-grid-row");for(const r of i)r.style.height="",r.classList.remove("responsive-card");this.#e&&this.#e>0&&e._virtualization&&(e._virtualization.rowHeight=this.#e,this.#e=void 0),this.#i=void 0,this.#r=void 0,this.#p=void 0}}renderRow(t,e,i){if(!this.#t||!this.config.cardRenderer||t.__isGroupRow)return;e.replaceChildren();const r=this.config.cardRenderer(t,i);e.className="data-grid-row responsive-card";const s=this.config.cardRowHeight??"auto";return s!=="auto"?e.style.height=`${s}px`:e.style.height="auto",e.appendChild(r),!0}onKeyDown(t){if(!this.#t||this.config.cardRenderer&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key))return!1;const e=this.rows.length-1,i=this.visibleColumns.length-1;switch(t.key){case"ArrowDown":if(this.grid._focusCol<i)return this.grid._focusCol+=1,t.preventDefault(),h.ensureCellVisible(this.grid),!0;if(this.grid._focusRow<e)return this.grid._focusRow+=1,this.grid._focusCol=0,t.preventDefault(),h.ensureCellVisible(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,t.preventDefault(),h.ensureCellVisible(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=i,t.preventDefault(),h.ensureCellVisible(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<e)return this.grid._focusRow+=1,t.preventDefault(),h.ensureCellVisible(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,t.preventDefault(),h.ensureCellVisible(this.grid),!0;break}return!1}#i;#r;#p;#g(){if(this.#i&&this.#i>0)return this.#i;const t=this.config.cardRowHeight;return typeof t=="number"&&t>0?t:80}#f(){return this.#r&&this.#r>0?this.#r:this.#e??28}#w(){for(const t of this.rows)if(t.__isGroupRow)return!0;return!1}#C(){let t=0,e=0;for(const i of this.rows)i.__isGroupRow?t++:e++;return{groupCount:t,cardCount:e}}getExtraHeight(){if(!this.#t||!this.config.cardRenderer||!this.#w())return 0;const t=this.#e??28,e=this.#f(),i=this.#g(),{groupCount:r,cardCount:s}=this.#C(),n=r*Math.max(0,e-t),a=s*Math.max(0,i-t);return n+a}getExtraHeightBefore(t){if(!this.#t||!this.config.cardRenderer||!this.#w())return 0;const e=this.#e??28,i=this.#f(),r=this.#g(),s=Math.max(0,i-e),n=Math.max(0,r-e);let a=0,c=0;const d=this.rows,u=Math.min(t,d.length);for(let o=0;o<u;o++)d[o].__isGroupRow?a++:c++;return a*s+c*n}getRowHeight(t,e){if(!(!this.#t||!this.config.cardRenderer))return t.__isGroupRow?this.#f():this.#g()}#k(){let t=0;for(const e of this.rows)e.__isGroupRow||t++;return t}#v=!1;#A(){if(!this.#t||!this.config.cardRenderer)return;let t=!1;const e=this.grid,i=this.#w(),r=this.#k();if(r!==this.#p&&(this.#p=r,t=!0),i){const n=this.gridElement.querySelector(".data-grid-row.group-row");if(n){const a=n.getBoundingClientRect().height;a>0&&a!==this.#r&&(this.#r=a,t=!0)}}const s=this.gridElement.querySelector(".data-grid-row.responsive-card");if(s){const n=s.getBoundingClientRect().height;n>0&&n!==this.#i&&(this.#i=n,t=!0,!i&&e._virtualization&&(e._virtualization.rowHeight=n))}t&&!this.#v&&(this.#v=!0,queueMicrotask(()=>{this.#v=!1,this.grid&&this.#t&&this.grid.refreshVirtualWindow?.(!0,!0)}))}}l.ResponsivePlugin=v,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/internal/keyboard"),require("../../core/internal/sanitize"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../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)}(this,function(e,t,i,r){"use strict";class s extends r.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] .cell[data-responsive-hidden]{display:none!important}tbw-grid[data-responsive] .cell[data-responsive-value-only]{justify-content:flex-start!important;font-weight:500}tbw-grid[data-responsive] .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=[];isResponsive(){return this.#t}setResponsive(e){e!==this.#t&&(this.#t=e,this.#h(),this.emit("responsive-change",{isResponsive:e,width:this.#s,breakpoint:this.config.breakpoint??0}))}setBreakpoint(e){this.config.breakpoint=e,this.#l(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.#u(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.#l(t)},this.config.debounceMs??100)}),this.#e.observe(this.gridElement)}#p(){const e=this.grid;if(!e||"function"!=typeof e.querySelector)return;const t=e.querySelector("tbw-grid-responsive-card");if(!t)return;const r=e;if(r.__frameworkAdapter?.parseResponsiveCardElement){const e=r.__frameworkAdapter.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||r.__frameworkAdapter?.parseResponsiveCardElement||(h.cardRenderer=e=>{const t=i.evalTemplateString(l,{value:e,row:e}),r=i.sanitizeHTML(t),s=document.createElement("div");return s.className="tbw-responsive-card-content",s.innerHTML=r,s}),Object.keys(h).length>0&&(this.config={...this.config,...h})}#u(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.#g();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")))}}#l(e){if(this.#d.length>0)return void this.#c(e);const t=this.config.breakpoint??0;0!==t||this.#r||(this.#r=!0,console.warn("[tbw-grid:ResponsivePlugin] No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count."));const i=t>0&&e<t;i!==this.#t&&(this.#t=i,this.#h(),this.emit("responsive-change",{isResponsive:i,width:e,breakpoint:t}),this.requestRender())}#c(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.#u(t.hiddenColumns):this.#u(this.config.hiddenColumns);const i=!0===t?.cardLayout;i!==this.#t&&(this.#t=i,this.#h()),this.emit("responsive-change",{isResponsive:this.#t,width:e,breakpoint:t?.maxWidth??0}),this.requestRender()}}#w;#h(){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.grid;if(this.#t){t._virtualization&&(this.#w=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.#w&&this.#w>0&&t._virtualization&&(t._virtualization.rowHeight=this.#w,this.#w=void 0),this.#v=void 0,this.#m=void 0,this.#b=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??"auto";return t.style.height="auto"!==s?`${s}px`:"auto",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 i=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(),t.ensureCellVisible(this.grid),!0;if(this.grid._focusRow<i)return this.grid._focusRow+=1,this.grid._focusCol=0,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowUp":if(this.grid._focusCol>0)return this.grid._focusCol-=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;if(this.grid._focusRow>0)return this.grid._focusRow-=1,this.grid._focusCol=r,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowRight":if(this.grid._focusRow<i)return this.grid._focusRow+=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0;break;case"ArrowLeft":if(this.grid._focusRow>0)return this.grid._focusRow-=1,e.preventDefault(),t.ensureCellVisible(this.grid),!0}return!1}#v;#m;#b;#f(){if(this.#v&&this.#v>0)return this.#v;const e=this.config.cardRowHeight;return"number"==typeof e&&e>0?e:80}#R(){return this.#m&&this.#m>0?this.#m:this.#w??28}#C(){for(const e of this.rows)if(e.__isGroupRow)return!0;return!1}#y(){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.#C())return 0;const e=this.#w??28,t=this.#R(),i=this.#f(),{groupCount:r,cardCount:s}=this.#y();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.#C())return 0;const t=this.#w??28,i=this.#R(),r=this.#f(),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.#R():this.#f()}#k(){let e=0;for(const t of this.rows)t.__isGroupRow||e++;return e}#H=!1;#g(){if(!this.#t||!this.config.cardRenderer)return;let e=!1;const t=this.grid,i=this.#C(),r=this.#k();if(r!==this.#b&&(this.#b=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.#m&&(this.#m=i,e=!0)}}const s=this.gridElement.querySelector(".data-grid-row.responsive-card");if(s){const r=s.getBoundingClientRect().height;r>0&&r!==this.#v&&(this.#v=r,e=!0,!i&&t._virtualization&&(t._virtualization.rowHeight=r))}e&&!this.#H&&(this.#H=!0,queueMicrotask(()=>{this.#H=!1,this.grid&&this.#t&&this.grid.refreshVirtualWindow?.(!0,!0)}))}}e.ResponsivePlugin=s,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=responsive.umd.js.map
|