@toolbox-web/grid 2.13.1 → 2.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/all.js +2 -2
- package/all.js.map +1 -1
- package/custom-elements.json +18 -0
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/lib/core/grid.d.ts +23 -0
- package/lib/core/internal/style-injector.d.ts +0 -8
- package/lib/plugins/filtering/index.js +1 -1
- package/lib/plugins/filtering/index.js.map +1 -1
- package/lib/plugins/filtering/types.d.ts +0 -28
- package/lib/plugins/master-detail/MasterDetailPlugin.d.ts +0 -1
- package/lib/plugins/master-detail/index.js +1 -1
- package/lib/plugins/master-detail/index.js.map +1 -1
- package/lib/plugins/master-detail/types.d.ts +0 -2
- package/lib/plugins/responsive/index.js +1 -1
- package/lib/plugins/responsive/index.js.map +1 -1
- package/lib/plugins/responsive/types.d.ts +11 -2
- package/lib/plugins/server-side/datasource-types.d.ts +8 -0
- package/lib/plugins/server-side/index.js +1 -1
- package/lib/plugins/server-side/index.js.map +1 -1
- package/lib/plugins/server-side/types.d.ts +9 -10
- package/lib/plugins/visibility/index.js +1 -1
- package/lib/plugins/visibility/index.js.map +1 -1
- package/lib/plugins/visibility/types.d.ts +5 -10
- package/lib/plugins/visibility/visibility.d.ts +5 -3
- package/package.json +1 -1
- package/themes/dg-theme-bootstrap.css +2 -2
- package/themes/dg-theme-contrast.css +1 -1
- package/themes/dg-theme-large.css +1 -1
- package/themes/dg-theme-material.css +2 -2
- package/themes/dg-theme-standard.css +1 -1
- package/themes/dg-theme-vibrant.css +1 -1
- package/umd/grid.all.umd.js +1 -1
- package/umd/grid.all.umd.js.map +1 -1
- package/umd/grid.umd.js +1 -1
- package/umd/grid.umd.js.map +1 -1
- package/umd/plugins/filtering.umd.js +1 -1
- package/umd/plugins/filtering.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/responsive.umd.js +1 -1
- package/umd/plugins/responsive.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/visibility.umd.js +1 -1
- package/umd/plugins/visibility.umd.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responsive.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/responsive/ResponsivePlugin.ts"],"sourcesContent":["/**\n * Responsive Plugin\n *\n * Transforms the grid from tabular layout to a card/list layout when the grid\n * width falls below a configurable breakpoint. This enables grids to work in\n * narrow containers (split-pane UIs, mobile viewports, dashboard widgets).\n *\n * ## Installation\n *\n * ```ts\n * import { ResponsivePlugin } from '@toolbox-web/grid/plugins/responsive';\n *\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * ## How It Works\n *\n * 1. ResizeObserver monitors the grid element's width\n * 2. When `width < breakpoint`, adds `data-responsive` attribute to grid\n * 3. CSS transforms cells from horizontal to vertical layout\n * 4. Each cell displays \"Header: Value\" using CSS `::before` pseudo-element\n *\n * @see [Responsive Demo](?path=/story/grid-plugins-responsive--default)\n */\n\nimport { MISSING_BREAKPOINT } from '../../core/internal/diagnostics';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, type GridElement, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport styles from './responsive.css?inline';\nimport type { BreakpointConfig, HiddenColumnConfig, ResponsiveChangeDetail, ResponsivePluginConfig } from './types';\n\n/**\n * Responsive Plugin for tbw-grid\n *\n * Adds automatic card layout mode when the grid width falls below a configurable\n * breakpoint. Perfect for responsive designs, split-pane UIs, and mobile viewports.\n *\n * @template T The row data type\n *\n * @example\n * ```ts\n * // Basic usage - switch to card layout below 500px\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Hide less important columns in card mode\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 600,\n * hiddenColumns: ['createdAt', 'updatedAt'],\n * }),\n * ],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Custom card renderer for advanced layouts\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 400,\n * cardRenderer: (row) => {\n * const card = document.createElement('div');\n * card.className = 'custom-card';\n * card.innerHTML = `<strong>${row.name}</strong><br>${row.email}`;\n * return card;\n * },\n * }),\n * ],\n * };\n * ```\n * @since 1.1.0\n */\nexport class ResponsivePlugin<T = unknown> extends BaseGridPlugin<ResponsivePluginConfig<T>> {\n readonly name = 'responsive';\n override readonly version = '1.0.0';\n override readonly styles = styles;\n\n /**\n * Plugin manifest declaring queries this plugin handles.\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'isCardMode',\n description: 'Returns whether the grid is currently in responsive card mode',\n },\n ],\n };\n\n #resizeObserver?: ResizeObserver;\n #isResponsive = false;\n #debounceTimer?: ReturnType<typeof setTimeout>;\n #warnedAboutMissingBreakpoint = false;\n #currentWidth = 0;\n /** Set of column fields to completely hide */\n #hiddenColumnSet: Set<string> = new Set();\n /** Set of column fields to show value only (no header label) */\n #valueOnlyColumnSet: Set<string> = new Set();\n /** Currently active breakpoint, or null if none */\n #activeBreakpoint: BreakpointConfig | null = null;\n /** Sorted breakpoints from largest to smallest */\n #sortedBreakpoints: BreakpointConfig[] = [];\n\n /** Typed internal grid accessor — centralizes the single required cast. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if currently in responsive mode.\n * @returns `true` if the grid is in card layout mode\n */\n isResponsive(): boolean {\n return this.#isResponsive;\n }\n\n /**\n * Force responsive mode regardless of width.\n * Useful for testing or manual control.\n * @param enabled - Whether to enable responsive mode\n */\n setResponsive(enabled: boolean): void {\n if (enabled !== this.#isResponsive) {\n this.#isResponsive = enabled;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: enabled,\n width: this.#currentWidth,\n breakpoint: this.config.breakpoint ?? 0,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Update breakpoint dynamically.\n * @param width - New breakpoint width in pixels\n */\n setBreakpoint(width: number): void {\n this.config.breakpoint = width;\n this.#checkBreakpoint(this.#currentWidth);\n }\n\n /**\n * Set a custom card renderer.\n * This allows framework adapters to provide template-based renderers at runtime.\n * @param renderer - The card renderer function, or undefined to use default\n */\n setCardRenderer(renderer: ResponsivePluginConfig<T>['cardRenderer']): void {\n this.config.cardRenderer = renderer;\n // If already in responsive mode, trigger a re-render to apply the new renderer\n if (this.#isResponsive) {\n this.requestRender();\n }\n }\n\n /**\n * Get current grid width.\n * @returns Width of the grid element in pixels\n */\n getWidth(): number {\n return this.#currentWidth;\n }\n\n /**\n * Get the currently active breakpoint config (multi-breakpoint mode only).\n * @returns The active BreakpointConfig, or null if no breakpoint is active\n */\n getActiveBreakpoint(): BreakpointConfig | null {\n return this.#activeBreakpoint;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Parse light DOM configuration first (may update this.config)\n this.#parseLightDomCard();\n\n // Build hidden column sets from config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n\n // Sort breakpoints from largest to smallest for evaluation\n if (this.config.breakpoints?.length) {\n this.#sortedBreakpoints = [...this.config.breakpoints].sort((a, b) => b.maxWidth - a.maxWidth);\n }\n\n // Observe the grid element itself (not internal viewport)\n // This captures the container width including when shell panels open/close\n this.#resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width ?? 0;\n this.#currentWidth = width;\n\n // Debounce to avoid thrashing during resize drag\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = setTimeout(() => {\n this.#checkBreakpoint(width);\n }, this.config.debounceMs ?? 100);\n });\n\n this.#resizeObserver.observe(this.gridElement);\n }\n\n // #region Light DOM Parsing\n\n /**\n * Parse `<tbw-grid-responsive-card>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-responsive-card breakpoint=\"500\" card-row-height=\"80\">\n * <div class=\"custom-card\">\n * <strong>{{ row.name }}</strong>\n * <span>{{ row.email }}</span>\n * </div>\n * </tbw-grid-responsive-card>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `breakpoint`: number - Width threshold for responsive mode\n * - `card-row-height`: number | 'auto' - Card height (default: 'auto')\n * - `hidden-columns`: string - Comma-separated fields to hide\n * - `hide-header`: 'true' | 'false' - Hide header row (default: 'true')\n * - `debounce-ms`: number - Resize debounce delay (default: 100)\n */\n #parseLightDomCard(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const cardEl = gridEl.querySelector('tbw-grid-responsive-card');\n if (!cardEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., React adapter intercepts for JSX rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseResponsiveCardElement) {\n const adapterRenderer = adapter.parseResponsiveCardElement(cardEl);\n if (adapterRenderer) {\n this.config = { ...this.config, cardRenderer: adapterRenderer };\n // Continue to parse attributes even if adapter provides renderer\n }\n }\n\n // Parse attributes for configuration\n const breakpointAttr = cardEl.getAttribute('breakpoint');\n const cardRowHeightAttr = cardEl.getAttribute('card-row-height');\n const hiddenColumnsAttr = cardEl.getAttribute('hidden-columns');\n const hideHeaderAttr = cardEl.getAttribute('hide-header');\n const debounceMsAttr = cardEl.getAttribute('debounce-ms');\n\n const configUpdates: Partial<ResponsivePluginConfig<T>> = {};\n\n if (breakpointAttr !== null) {\n const breakpoint = parseInt(breakpointAttr, 10);\n if (!isNaN(breakpoint)) {\n configUpdates.breakpoint = breakpoint;\n }\n }\n\n if (cardRowHeightAttr !== null) {\n configUpdates.cardRowHeight = cardRowHeightAttr === 'auto' ? 'auto' : parseInt(cardRowHeightAttr, 10);\n }\n\n if (hiddenColumnsAttr !== null) {\n // Parse comma-separated field names\n configUpdates.hiddenColumns = hiddenColumnsAttr\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n if (hideHeaderAttr !== null) {\n configUpdates.hideHeader = hideHeaderAttr !== 'false';\n }\n\n if (debounceMsAttr !== null) {\n const debounceMs = parseInt(debounceMsAttr, 10);\n if (!isNaN(debounceMs)) {\n configUpdates.debounceMs = debounceMs;\n }\n }\n\n // Get template content from innerHTML (only if no renderer already set)\n const templateHTML = cardEl.innerHTML.trim();\n if (templateHTML && !this.config.cardRenderer && !adapter?.parseResponsiveCardElement) {\n // Create a template-based renderer using the inner HTML\n configUpdates.cardRenderer = (row: T): HTMLElement => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row: row as Record<string, unknown> });\n // Sanitize the result to prevent XSS\n const sanitized = sanitizeHTML(evaluated);\n const container = document.createElement('div');\n container.className = 'tbw-responsive-card-content';\n container.innerHTML = sanitized;\n return container;\n };\n }\n\n // Merge updates into config (light DOM values override constructor config)\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n /**\n * Build the hidden and value-only column sets from config.\n */\n #buildHiddenColumnSets(hiddenColumns?: HiddenColumnConfig[]): void {\n this.#hiddenColumnSet.clear();\n this.#valueOnlyColumnSet.clear();\n\n if (!hiddenColumns) return;\n\n for (const col of hiddenColumns) {\n if (typeof col === 'string') {\n this.#hiddenColumnSet.add(col);\n } else if (col.showValue) {\n this.#valueOnlyColumnSet.add(col.field);\n } else {\n this.#hiddenColumnSet.add(col.field);\n }\n }\n }\n\n override detach(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = undefined;\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = undefined;\n\n // Clean up attribute\n if (this.gridElement) {\n this.gridElement.removeAttribute('data-responsive');\n }\n\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isCardMode') {\n return this.#isResponsive;\n }\n return undefined;\n }\n\n /**\n * Apply hidden and value-only columns.\n * In legacy mode (single breakpoint), only applies when in responsive mode.\n * In multi-breakpoint mode, applies whenever there's an active breakpoint.\n */\n override afterRender(): void {\n // Measure card height for virtualization calculations\n this.#measureCardHeightFromDOM();\n\n // In single breakpoint mode, only apply when responsive\n // In multi-breakpoint mode, apply when there's an active breakpoint\n const shouldApply = this.#sortedBreakpoints.length > 0 ? this.#activeBreakpoint !== null : this.#isResponsive;\n\n if (!shouldApply) {\n return;\n }\n\n const hasHiddenColumns = this.#hiddenColumnSet.size > 0;\n const hasValueOnlyColumns = this.#valueOnlyColumnSet.size > 0;\n\n if (!hasHiddenColumns && !hasValueOnlyColumns) {\n return;\n }\n\n // Mark cells for hidden columns and value-only columns\n const cells = this.gridElement.querySelectorAll('.cell[data-field]');\n for (const cell of cells) {\n const field = cell.getAttribute('data-field');\n if (!field) continue;\n\n // Apply hidden attribute\n if (this.#hiddenColumnSet.has(field)) {\n cell.setAttribute('data-responsive-hidden', '');\n cell.removeAttribute('data-responsive-value-only');\n }\n // Apply value-only attribute (shows value without header label)\n else if (this.#valueOnlyColumnSet.has(field)) {\n cell.setAttribute('data-responsive-value-only', '');\n cell.removeAttribute('data-responsive-hidden');\n }\n // Clear any previous responsive attributes\n else {\n cell.removeAttribute('data-responsive-hidden');\n cell.removeAttribute('data-responsive-value-only');\n }\n }\n }\n\n /**\n * Check if width has crossed any breakpoint threshold.\n * Handles both single breakpoint (legacy) and multi-breakpoint modes.\n */\n #checkBreakpoint(width: number): void {\n // Multi-breakpoint mode\n if (this.#sortedBreakpoints.length > 0) {\n this.#checkMultiBreakpoint(width);\n return;\n }\n\n // Legacy single breakpoint mode\n const breakpoint = this.config.breakpoint ?? 0;\n\n // Warn once if breakpoint not configured (0 means never responsive)\n if (breakpoint === 0 && !this.#warnedAboutMissingBreakpoint) {\n this.#warnedAboutMissingBreakpoint = true;\n this.warn(\n MISSING_BREAKPOINT,\n \"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count.\",\n );\n }\n\n const shouldBeResponsive = breakpoint > 0 && width < breakpoint;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: shouldBeResponsive,\n width,\n breakpoint,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Check breakpoints in multi-breakpoint mode.\n * Evaluates breakpoints from largest to smallest, applying the first match.\n */\n #checkMultiBreakpoint(width: number): void {\n // Find the active breakpoint (first one where width <= maxWidth)\n // Since sorted largest to smallest, we find the largest matching breakpoint\n let newActiveBreakpoint: BreakpointConfig | null = null;\n\n for (const bp of this.#sortedBreakpoints) {\n if (width <= bp.maxWidth) {\n newActiveBreakpoint = bp;\n // Continue to find the most specific (smallest) matching breakpoint\n }\n }\n\n // Check if breakpoint changed\n const breakpointChanged = newActiveBreakpoint !== this.#activeBreakpoint;\n\n if (breakpointChanged) {\n this.#activeBreakpoint = newActiveBreakpoint;\n\n // Update hidden column sets from active breakpoint\n if (newActiveBreakpoint?.hiddenColumns) {\n this.#buildHiddenColumnSets(newActiveBreakpoint.hiddenColumns);\n } else {\n // Fall back to top-level hiddenColumns config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n }\n\n // Determine if we should be in card layout\n const shouldBeResponsive = newActiveBreakpoint?.cardLayout === true;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n }\n\n // Emit event for any breakpoint change\n this.emit('responsive-change', {\n isResponsive: this.#isResponsive,\n width,\n breakpoint: newActiveBreakpoint?.maxWidth ?? 0,\n } satisfies ResponsiveChangeDetail);\n\n this.requestRender();\n }\n }\n\n /** Original row height before entering responsive mode, for restoration on exit */\n #originalRowHeight?: number;\n\n /**\n * Apply the responsive state to the grid element.\n * Handles scroll reset when entering responsive mode and row height restoration on exit.\n */\n #applyResponsiveState(): void {\n this.gridElement.toggleAttribute('data-responsive', this.#isResponsive);\n\n // Apply animation attribute if enabled (default: true)\n const animate = this.config.animate !== false;\n this.gridElement.toggleAttribute('data-responsive-animate', animate);\n\n // Set custom animation duration if provided\n if (this.config.animationDuration) {\n this.gridElement.style.setProperty('--tbw-responsive-duration', `${this.config.animationDuration}ms`);\n }\n\n // Cast to internal type for virtualization access\n const internalGrid = this.#internalGrid;\n\n if (this.#isResponsive) {\n // Store original row height before responsive mode changes it\n if (internalGrid._virtualization) {\n this.#originalRowHeight = internalGrid._virtualization.rowHeight;\n }\n\n // Reset horizontal scroll position when entering responsive mode\n // The CSS hides overflow but doesn't reset the scroll position\n const scrollArea = this.gridElement.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (scrollArea) {\n scrollArea.scrollLeft = 0;\n }\n } else {\n // Exiting responsive mode - clean up inline styles set by renderRow\n // The rows are reused from the pool, so we need to remove the card-specific styles\n const rows = this.gridElement.querySelectorAll('.data-grid-row');\n for (const row of rows) {\n (row as HTMLElement).style.height = '';\n row.classList.remove('responsive-card');\n }\n\n // Restore original row height\n if (this.#originalRowHeight && this.#originalRowHeight > 0 && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = this.#originalRowHeight;\n this.#originalRowHeight = undefined;\n }\n\n // Clear cached measurements so they're remeasured fresh when re-entering responsive mode\n // Without this, stale measurements cause incorrect height calculations after scrolling\n this.#measuredCardHeight = undefined;\n this.#measuredGroupRowHeight = undefined;\n this.#lastCardRowCount = undefined;\n }\n }\n\n /**\n * Custom row rendering when cardRenderer is provided and in responsive mode.\n *\n * When a cardRenderer is configured, this hook takes over row rendering to display\n * the custom card layout instead of the default cell structure.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if rendered (prevents default), `void` for default rendering\n */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean | void {\n // Only override when in responsive mode AND cardRenderer is provided\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return; // Let default rendering proceed\n }\n\n // Skip group rows from GroupingRowsPlugin - they have special structure\n // and should use their own renderer\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return; // Let GroupingRowsPlugin handle group row rendering\n }\n\n // Clear existing content\n rowEl.replaceChildren();\n\n // Call user's cardRenderer to get custom content\n const cardContent = this.config.cardRenderer(row as T, rowIndex);\n\n // Reset className - clears any stale classes from previous use (e.g., 'group-row' from recycled element)\n // This follows the same pattern as GroupingRowsPlugin which sets className explicitly\n rowEl.className = 'data-grid-row responsive-card';\n\n // Handle card row height — when a numeric height is configured, use the effective\n // height from #getCardHeight() which incorporates DOM measurement after first render.\n // This keeps inline height in sync with the position cache used for virtualization.\n const configuredHeight = this.config.cardRowHeight;\n if (configuredHeight === 'auto' || configuredHeight === undefined) {\n rowEl.style.height = 'auto';\n } else {\n rowEl.style.height = `${this.#getCardHeight()}px`;\n }\n\n // Append the custom card content\n rowEl.appendChild(cardContent);\n\n return true; // We handled rendering\n }\n\n /**\n * Handle keyboard navigation in responsive mode.\n *\n * In responsive mode, the visual layout is inverted:\n * - Cells are stacked vertically within each \"card\" (row)\n * - DOWN/UP visually moves within the card (between fields)\n * - Page Down/Page Up or Ctrl+Down/Up moves between cards\n *\n * For custom cardRenderers, keyboard navigation is disabled entirely\n * since the implementor controls the card content and should handle\n * navigation via their own event handlers.\n *\n * @returns `true` if the event was handled and default behavior should be prevented\n */\n override onKeyDown(e: KeyboardEvent): boolean {\n if (!this.#isResponsive) {\n return false;\n }\n\n // If custom cardRenderer is provided, disable grid's keyboard navigation\n // The implementor is responsible for their own navigation\n if (this.config.cardRenderer) {\n const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];\n if (navKeys.includes(e.key)) {\n // Let the event bubble - implementor can handle it\n return false;\n }\n }\n\n // Swap arrow key behavior for CSS-only responsive mode\n // In card layout, cells are stacked vertically:\n // Card 1: Card 2:\n // ID: 1 ID: 2\n // Name: Alice Name: Bob <- ArrowRight goes here\n // Dept: Eng Dept: Mkt\n // ↓ ArrowDown goes here\n //\n // ArrowDown/Up = move within card (change column/field)\n // ArrowRight/Left = move between cards (change row)\n const maxRow = this.rows.length - 1;\n const maxCol = this.visibleColumns.length - 1;\n\n switch (e.key) {\n case 'ArrowDown':\n // Move down WITHIN card (to next field/column)\n if (this.grid._focusCol < maxCol) {\n this.grid._focusCol += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At bottom of card - optionally move to next card's first field\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n this.grid._focusCol = 0;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowUp':\n // Move up WITHIN card (to previous field/column)\n if (this.grid._focusCol > 0) {\n this.grid._focusCol -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At top of card - optionally move to previous card's last field\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n this.grid._focusCol = maxCol;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowRight':\n // Move to NEXT card (same field)\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowLeft':\n // Move to PREVIOUS card (same field)\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n }\n\n return false;\n }\n\n // ============================================\n // Variable Height Support for Mixed Row Types\n // ============================================\n\n /** Measured card height from DOM for virtualization calculations */\n #measuredCardHeight?: number;\n\n /** Measured group row height from DOM for virtualization calculations */\n #measuredGroupRowHeight?: number;\n\n /** Last known card row count for detecting changes (e.g., group expand/collapse) */\n #lastCardRowCount?: number;\n\n /**\n * Get the effective card height for virtualization calculations.\n * Prioritizes DOM-measured height (actual rendered size) over config,\n * since content can overflow the configured height.\n */\n #getCardHeight(): number {\n // Prefer measured height - it reflects actual rendered size including overflow\n if (this.#measuredCardHeight && this.#measuredCardHeight > 0) {\n return this.#measuredCardHeight;\n }\n // Fall back to explicit config\n const configHeight = this.config.cardRowHeight;\n if (typeof configHeight === 'number' && configHeight > 0) {\n return configHeight;\n }\n // Default fallback\n return 80;\n }\n\n /**\n * Get the effective group row height for virtualization calculations.\n * Uses DOM-measured height, falling back to original row height.\n */\n #getGroupRowHeight(): number {\n if (this.#measuredGroupRowHeight && this.#measuredGroupRowHeight > 0) {\n return this.#measuredGroupRowHeight;\n }\n // Fall back to original row height (before responsive mode)\n return this.#originalRowHeight ?? 28;\n }\n\n /**\n * Check if there are any group rows in the current dataset.\n * Used to determine if we have mixed row heights.\n */\n #hasGroupRows(): boolean {\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.#internalGrid;\n const hasGroups = this.#hasGroupRows();\n\n // Check if card row count changed (e.g., group expanded/collapsed)\n const currentCardRowCount = this.#countCardRows();\n if (currentCardRowCount !== this.#lastCardRowCount) {\n this.#lastCardRowCount = currentCardRowCount;\n needsRefresh = true;\n }\n\n // Measure actual group row height from DOM (for mixed layouts)\n if (hasGroups) {\n const groupRow = this.gridElement.querySelector('.data-grid-row.group-row') as HTMLElement | null;\n if (groupRow) {\n const height = groupRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredGroupRowHeight) {\n this.#measuredGroupRowHeight = height;\n needsRefresh = true;\n }\n }\n }\n\n // Measure actual card height from DOM.\n // With cardRenderer, rows have the `.responsive-card` class.\n // Without cardRenderer (CSS-only card mode), rows are plain `.data-grid-row`\n // elements whose CSS height is `auto` — we need to measure their actual\n // rendered height so the faux scrollbar spacer is sized correctly.\n const cardSelector = this.config.cardRenderer ? '.data-grid-row.responsive-card' : '.data-grid-row:not(.group-row)';\n const cardRow = this.gridElement.querySelector(cardSelector) as HTMLElement | null;\n if (cardRow) {\n const height = cardRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredCardHeight) {\n this.#measuredCardHeight = height;\n needsRefresh = true;\n\n // For uniform card layouts (no groups), update virtualization row height directly\n // This ensures proper row recycling and translateY calculations\n if (!hasGroups && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = height;\n }\n }\n }\n\n // Defer virtualization refresh to avoid nested render cycles\n // This is called from afterRender, so we can't call refreshVirtualWindow synchronously\n // Use scheduler's VIRTUALIZATION phase to batch properly and avoid duplicate afterRender calls\n if (needsRefresh && !this.#pendingRefresh) {\n this.#pendingRefresh = true;\n queueMicrotask(() => {\n this.#pendingRefresh = false;\n // Only refresh if still attached and in responsive mode\n if (this.grid && this.#isResponsive) {\n // Request virtualization phase through grid's public API\n // This goes through the scheduler which batches and handles afterRender properly\n this.#internalGrid.refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","name","version","styles","static","queries","type","description","resizeObserver","isResponsive","debounceTimer","warnedAboutMissingBreakpoint","currentWidth","hiddenColumnSet","Set","valueOnlyColumnSet","activeBreakpoint","sortedBreakpoints","internalGrid","this","grid","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","requestRender","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","getWidth","getActiveBreakpoint","attach","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","cardEl","querySelector","adapter","__frameworkAdapter","parseResponsiveCardElement","adapterRenderer","breakpointAttr","getAttribute","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","parseInt","isNaN","cardRowHeight","split","map","s","trim","filter","hideHeader","templateHTML","innerHTML","row","evaluated","evalTemplateString","value","sanitized","sanitizeHTML","container","document","createElement","className","Object","keys","clear","col","add","showValue","field","detach","disconnect","removeAttribute","handleQuery","query","afterRender","measureCardHeightFromDOM","hasHiddenColumns","size","hasValueOnlyColumns","cells","querySelectorAll","cell","has","setAttribute","checkMultiBreakpoint","warn","MISSING_BREAKPOINT","shouldBeResponsive","newActiveBreakpoint","bp","cardLayout","originalRowHeight","toggleAttribute","animate","animationDuration","style","setProperty","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","configuredHeight","getCardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","configHeight","getGroupRowHeight","hasGroupRows","getRowHeight","_index","countCardRows","count","pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","getBoundingClientRect","cardSelector","cardRow","queueMicrotask","refreshVirtualWindow"],"mappings":"mlBAmFO,MAAMA,UAAsCC,EAAAA,eACxCC,KAAO,aACEC,QAAU,QACVC,2kHAKlBC,gBAAoD,CAClDC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,OAAuCD,IAEvCE,GAA6C,KAE7CC,GAAyC,GAGzC,KAAIC,GACF,OAAOC,KAAKC,IACd,CAMA,YAAAX,GACE,OAAOU,MAAKV,CACd,CAOA,aAAAY,CAAcC,GACRA,IAAYH,MAAKV,IACnBU,MAAKV,EAAgBa,EACrBH,MAAKI,IACLJ,KAAKK,KAAK,oBAAqB,CAC7Bf,aAAca,EACdG,MAAON,MAAKP,EACZc,WAAYP,KAAKQ,OAAOD,YAAc,IAExCP,KAAKS,gBAET,CAMA,aAAAC,CAAcJ,GACZN,KAAKQ,OAAOD,WAAaD,EACzBN,MAAKW,EAAiBX,MAAKP,EAC7B,CAOA,eAAAmB,CAAgBC,GACdb,KAAKQ,OAAOM,aAAeD,EAEvBb,MAAKV,GACPU,KAAKS,eAET,CAMA,QAAAM,GACE,OAAOf,MAAKP,CACd,CAMA,mBAAAuB,GACE,OAAOhB,MAAKH,CACd,CAES,MAAAoB,CAAOhB,GACdiB,MAAMD,OAAOhB,GAGbD,MAAKmB,IAGLnB,MAAKoB,EAAuBpB,KAAKQ,OAAOa,eAGpCrB,KAAKQ,OAAOc,aAAaC,SAC3BvB,MAAKF,EAAqB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H,EAAsBH,EAC3BkC,GAAe,GAIVC,GAAanJ,EAAa2G,kBAC7B3G,EAAa2G,gBAAgBC,UAAYI,GAG/C,CAKIkC,IAAiBjJ,MAAKgJ,IACxBhJ,MAAKgJ,GAAkB,EACvBQ,eAAe,KACbxJ,MAAKgJ,GAAkB,EAEnBhJ,KAAKC,MAAQD,MAAKV,GAGpBU,MAAKD,EAAc0J,wBAAuB,GAAM,KAIxD"}
|
|
1
|
+
{"version":3,"file":"responsive.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/responsive/ResponsivePlugin.ts"],"sourcesContent":["/**\n * Responsive Plugin\n *\n * Transforms the grid from tabular layout to a card/list layout when the grid\n * width falls below a configurable breakpoint. This enables grids to work in\n * narrow containers (split-pane UIs, mobile viewports, dashboard widgets).\n *\n * ## Installation\n *\n * ```ts\n * import { ResponsivePlugin } from '@toolbox-web/grid/plugins/responsive';\n *\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * ## How It Works\n *\n * 1. ResizeObserver monitors the grid element's width\n * 2. When `width < breakpoint`, adds `data-responsive` attribute to grid\n * 3. CSS transforms cells from horizontal to vertical layout\n * 4. Each cell displays \"Header: Value\" using CSS `::before` pseudo-element\n *\n * @see [Responsive Demo](?path=/story/grid-plugins-responsive--default)\n */\n\nimport { MISSING_BREAKPOINT } from '../../core/internal/diagnostics';\nimport { ensureCellVisible } from '../../core/internal/keyboard';\nimport { evalTemplateString, sanitizeHTML } from '../../core/internal/sanitize';\nimport { BaseGridPlugin, type GridElement, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { GridHost } from '../../core/types';\nimport styles from './responsive.css?inline';\nimport type { BreakpointConfig, HiddenColumnConfig, ResponsiveChangeDetail, ResponsivePluginConfig } from './types';\n\n/**\n * Responsive Plugin for tbw-grid\n *\n * Adds automatic card layout mode when the grid width falls below a configurable\n * breakpoint. Perfect for responsive designs, split-pane UIs, and mobile viewports.\n *\n * @template T The row data type\n *\n * @example\n * ```ts\n * // Basic usage - switch to card layout below 500px\n * const config: GridConfig = {\n * plugins: [new ResponsivePlugin({ breakpoint: 500 })],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Hide less important columns in card mode\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 600,\n * hiddenColumns: ['createdAt', 'updatedAt'],\n * }),\n * ],\n * };\n * ```\n *\n * @example\n * ```ts\n * // Custom card renderer for advanced layouts\n * const config: GridConfig = {\n * plugins: [\n * new ResponsivePlugin({\n * breakpoint: 400,\n * cardRenderer: (row) => {\n * const card = document.createElement('div');\n * card.className = 'custom-card';\n * card.innerHTML = `<strong>${row.name}</strong><br>${row.email}`;\n * return card;\n * },\n * }),\n * ],\n * };\n * ```\n * @since 1.1.0\n */\nexport class ResponsivePlugin<T = unknown> extends BaseGridPlugin<ResponsivePluginConfig<T>> {\n readonly name = 'responsive';\n override readonly version = '1.0.0';\n override readonly styles = styles;\n\n /**\n * Plugin manifest declaring queries this plugin handles.\n */\n static override readonly manifest: PluginManifest = {\n queries: [\n {\n type: 'isCardMode',\n description: 'Returns whether the grid is currently in responsive card mode',\n },\n ],\n };\n\n #resizeObserver?: ResizeObserver;\n #isResponsive = false;\n #debounceTimer?: ReturnType<typeof setTimeout>;\n #warnedAboutMissingBreakpoint = false;\n #currentWidth = 0;\n /** Set of column fields to completely hide */\n #hiddenColumnSet: Set<string> = new Set();\n /** Set of column fields to show value only (no header label) */\n #valueOnlyColumnSet: Set<string> = new Set();\n /** Currently active breakpoint, or null if none */\n #activeBreakpoint: BreakpointConfig | null = null;\n /** Sorted breakpoints from largest to smallest */\n #sortedBreakpoints: BreakpointConfig[] = [];\n\n /** Typed internal grid accessor — centralizes the single required cast. */\n get #internalGrid(): GridHost {\n return this.grid as unknown as GridHost;\n }\n\n /**\n * Check if currently in responsive mode.\n * @returns `true` if the grid is in card layout mode\n */\n isResponsive(): boolean {\n return this.#isResponsive;\n }\n\n /**\n * Force responsive mode regardless of width.\n * Useful for testing or manual control.\n * @param enabled - Whether to enable responsive mode\n */\n setResponsive(enabled: boolean): void {\n if (enabled !== this.#isResponsive) {\n this.#isResponsive = enabled;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: enabled,\n width: this.#currentWidth,\n breakpoint: this.config.breakpoint ?? 0,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Update breakpoint dynamically.\n * @param width - New breakpoint width in pixels\n */\n setBreakpoint(width: number): void {\n this.config.breakpoint = width;\n this.#checkBreakpoint(this.#currentWidth);\n }\n\n /**\n * Set a custom card renderer.\n * This allows framework adapters to provide template-based renderers at runtime.\n * @param renderer - The card renderer function, or undefined to use default\n */\n setCardRenderer(renderer: ResponsivePluginConfig<T>['cardRenderer']): void {\n this.config.cardRenderer = renderer;\n // If already in responsive mode, trigger a re-render to apply the new renderer\n if (this.#isResponsive) {\n this.requestRender();\n }\n }\n\n /**\n * Get current grid width.\n * @returns Width of the grid element in pixels\n */\n getWidth(): number {\n return this.#currentWidth;\n }\n\n /**\n * Get the currently active breakpoint config (multi-breakpoint mode only).\n * @returns The active BreakpointConfig, or null if no breakpoint is active\n */\n getActiveBreakpoint(): BreakpointConfig | null {\n return this.#activeBreakpoint;\n }\n\n override attach(grid: GridElement): void {\n super.attach(grid);\n\n // Parse light DOM configuration first (may update this.config)\n this.#parseLightDomCard();\n\n // Build hidden column sets from config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n\n // Sort breakpoints from largest to smallest for evaluation\n if (this.config.breakpoints?.length) {\n this.#sortedBreakpoints = [...this.config.breakpoints].sort((a, b) => b.maxWidth - a.maxWidth);\n }\n\n // Observe the grid element itself (not internal viewport)\n // This captures the container width including when shell panels open/close\n this.#resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width ?? 0;\n this.#currentWidth = width;\n\n // Debounce to avoid thrashing during resize drag\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = setTimeout(() => {\n this.#checkBreakpoint(width);\n }, this.config.debounceMs ?? 100);\n });\n\n this.#resizeObserver.observe(this.gridElement);\n }\n\n // #region Light DOM Parsing\n\n /**\n * Parse `<tbw-grid-responsive-card>` elements from the grid's light DOM.\n *\n * Allows declarative configuration:\n * ```html\n * <tbw-grid [rows]=\"data\">\n * <tbw-grid-responsive-card breakpoint=\"500\" card-row-height=\"80\">\n * <div class=\"custom-card\">\n * <strong>{{ row.name }}</strong>\n * <span>{{ row.email }}</span>\n * </div>\n * </tbw-grid-responsive-card>\n * </tbw-grid>\n * ```\n *\n * Attributes:\n * - `breakpoint`: number - Width threshold for responsive mode\n * - `card-row-height`: number | 'auto' - Card height (default: 'auto')\n * - `hidden-columns`: string - Comma-separated fields to hide\n * - `hide-header`: 'true' | 'false' - Hide per-card field labels (default: 'false')\n * - `debounce-ms`: number - Resize debounce delay (default: 100)\n */\n #parseLightDomCard(): void {\n const gridEl = this.gridElement;\n if (!gridEl) return;\n\n const cardEl = gridEl.querySelector('tbw-grid-responsive-card');\n if (!cardEl) return;\n\n // Check if a framework adapter wants to handle this element\n // (e.g., React adapter intercepts for JSX rendering)\n const adapter = this.#internalGrid.__frameworkAdapter;\n if (adapter?.parseResponsiveCardElement) {\n const adapterRenderer = adapter.parseResponsiveCardElement(cardEl);\n if (adapterRenderer) {\n this.config = { ...this.config, cardRenderer: adapterRenderer };\n // Continue to parse attributes even if adapter provides renderer\n }\n }\n\n // Parse attributes for configuration\n const breakpointAttr = cardEl.getAttribute('breakpoint');\n const cardRowHeightAttr = cardEl.getAttribute('card-row-height');\n const hiddenColumnsAttr = cardEl.getAttribute('hidden-columns');\n const hideHeaderAttr = cardEl.getAttribute('hide-header');\n const debounceMsAttr = cardEl.getAttribute('debounce-ms');\n\n const configUpdates: Partial<ResponsivePluginConfig<T>> = {};\n\n if (breakpointAttr !== null) {\n const breakpoint = parseInt(breakpointAttr, 10);\n if (!isNaN(breakpoint)) {\n configUpdates.breakpoint = breakpoint;\n }\n }\n\n if (cardRowHeightAttr !== null) {\n configUpdates.cardRowHeight = cardRowHeightAttr === 'auto' ? 'auto' : parseInt(cardRowHeightAttr, 10);\n }\n\n if (hiddenColumnsAttr !== null) {\n // Parse comma-separated field names\n configUpdates.hiddenColumns = hiddenColumnsAttr\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n\n if (hideHeaderAttr !== null) {\n configUpdates.hideHeader = hideHeaderAttr !== 'false';\n }\n\n if (debounceMsAttr !== null) {\n const debounceMs = parseInt(debounceMsAttr, 10);\n if (!isNaN(debounceMs)) {\n configUpdates.debounceMs = debounceMs;\n }\n }\n\n // Get template content from innerHTML (only if no renderer already set)\n const templateHTML = cardEl.innerHTML.trim();\n if (templateHTML && !this.config.cardRenderer && !adapter?.parseResponsiveCardElement) {\n // Create a template-based renderer using the inner HTML\n configUpdates.cardRenderer = (row: T): HTMLElement => {\n // Evaluate template expressions like {{ row.field }}\n const evaluated = evalTemplateString(templateHTML, { value: row, row: row as Record<string, unknown> });\n // Sanitize the result to prevent XSS\n const sanitized = sanitizeHTML(evaluated);\n const container = document.createElement('div');\n container.className = 'tbw-responsive-card-content';\n container.innerHTML = sanitized;\n return container;\n };\n }\n\n // Merge updates into config (light DOM values override constructor config)\n if (Object.keys(configUpdates).length > 0) {\n this.config = { ...this.config, ...configUpdates };\n }\n }\n\n // #endregion\n\n /**\n * Build the hidden and value-only column sets from config.\n */\n #buildHiddenColumnSets(hiddenColumns?: HiddenColumnConfig[]): void {\n this.#hiddenColumnSet.clear();\n this.#valueOnlyColumnSet.clear();\n\n if (!hiddenColumns) return;\n\n for (const col of hiddenColumns) {\n if (typeof col === 'string') {\n this.#hiddenColumnSet.add(col);\n } else if (col.showValue) {\n this.#valueOnlyColumnSet.add(col.field);\n } else {\n this.#hiddenColumnSet.add(col.field);\n }\n }\n }\n\n override detach(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = undefined;\n clearTimeout(this.#debounceTimer);\n this.#debounceTimer = undefined;\n\n // Clean up attribute\n if (this.gridElement) {\n this.gridElement.removeAttribute('data-responsive');\n }\n\n super.detach();\n }\n\n /**\n * Handle plugin queries.\n * @internal\n */\n override handleQuery(query: PluginQuery): unknown {\n if (query.type === 'isCardMode') {\n return this.#isResponsive;\n }\n return undefined;\n }\n\n /**\n * Apply hidden and value-only columns.\n * In legacy mode (single breakpoint), only applies when in responsive mode.\n * In multi-breakpoint mode, applies whenever there's an active breakpoint.\n */\n override afterRender(): void {\n // Measure card height for virtualization calculations\n this.#measureCardHeightFromDOM();\n\n // In single breakpoint mode, only apply when responsive\n // In multi-breakpoint mode, apply when there's an active breakpoint\n const shouldApply = this.#sortedBreakpoints.length > 0 ? this.#activeBreakpoint !== null : this.#isResponsive;\n\n if (!shouldApply) {\n return;\n }\n\n const hasHiddenColumns = this.#hiddenColumnSet.size > 0;\n const hasValueOnlyColumns = this.#valueOnlyColumnSet.size > 0;\n\n if (!hasHiddenColumns && !hasValueOnlyColumns) {\n return;\n }\n\n // Mark cells for hidden columns and value-only columns\n const cells = this.gridElement.querySelectorAll('.cell[data-field]');\n for (const cell of cells) {\n const field = cell.getAttribute('data-field');\n if (!field) continue;\n\n // Apply hidden attribute\n if (this.#hiddenColumnSet.has(field)) {\n cell.setAttribute('data-responsive-hidden', '');\n cell.removeAttribute('data-responsive-value-only');\n }\n // Apply value-only attribute (shows value without header label)\n else if (this.#valueOnlyColumnSet.has(field)) {\n cell.setAttribute('data-responsive-value-only', '');\n cell.removeAttribute('data-responsive-hidden');\n }\n // Clear any previous responsive attributes\n else {\n cell.removeAttribute('data-responsive-hidden');\n cell.removeAttribute('data-responsive-value-only');\n }\n }\n }\n\n /**\n * Check if width has crossed any breakpoint threshold.\n * Handles both single breakpoint (legacy) and multi-breakpoint modes.\n */\n #checkBreakpoint(width: number): void {\n // Multi-breakpoint mode\n if (this.#sortedBreakpoints.length > 0) {\n this.#checkMultiBreakpoint(width);\n return;\n }\n\n // Legacy single breakpoint mode\n const breakpoint = this.config.breakpoint ?? 0;\n\n // Warn once if breakpoint not configured (0 means never responsive)\n if (breakpoint === 0 && !this.#warnedAboutMissingBreakpoint) {\n this.#warnedAboutMissingBreakpoint = true;\n this.warn(\n MISSING_BREAKPOINT,\n \"No breakpoint configured. Responsive mode is disabled. Set a breakpoint based on your grid's column count.\",\n );\n }\n\n const shouldBeResponsive = breakpoint > 0 && width < breakpoint;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n this.emit('responsive-change', {\n isResponsive: shouldBeResponsive,\n width,\n breakpoint,\n } satisfies ResponsiveChangeDetail);\n this.requestRender();\n }\n }\n\n /**\n * Check breakpoints in multi-breakpoint mode.\n * Evaluates breakpoints from largest to smallest, applying the first match.\n */\n #checkMultiBreakpoint(width: number): void {\n // Find the active breakpoint (first one where width <= maxWidth)\n // Since sorted largest to smallest, we find the largest matching breakpoint\n let newActiveBreakpoint: BreakpointConfig | null = null;\n\n for (const bp of this.#sortedBreakpoints) {\n if (width <= bp.maxWidth) {\n newActiveBreakpoint = bp;\n // Continue to find the most specific (smallest) matching breakpoint\n }\n }\n\n // Check if breakpoint changed\n const breakpointChanged = newActiveBreakpoint !== this.#activeBreakpoint;\n\n if (breakpointChanged) {\n this.#activeBreakpoint = newActiveBreakpoint;\n\n // Update hidden column sets from active breakpoint\n if (newActiveBreakpoint?.hiddenColumns) {\n this.#buildHiddenColumnSets(newActiveBreakpoint.hiddenColumns);\n } else {\n // Fall back to top-level hiddenColumns config\n this.#buildHiddenColumnSets(this.config.hiddenColumns);\n }\n\n // Determine if we should be in card layout\n const shouldBeResponsive = newActiveBreakpoint?.cardLayout === true;\n\n if (shouldBeResponsive !== this.#isResponsive) {\n this.#isResponsive = shouldBeResponsive;\n this.#applyResponsiveState();\n }\n\n // Emit event for any breakpoint change\n this.emit('responsive-change', {\n isResponsive: this.#isResponsive,\n width,\n breakpoint: newActiveBreakpoint?.maxWidth ?? 0,\n } satisfies ResponsiveChangeDetail);\n\n this.requestRender();\n }\n }\n\n /** Original row height before entering responsive mode, for restoration on exit */\n #originalRowHeight?: number;\n\n /**\n * Apply the responsive state to the grid element.\n * Handles scroll reset when entering responsive mode and row height restoration on exit.\n */\n #applyResponsiveState(): void {\n this.gridElement.toggleAttribute('data-responsive', this.#isResponsive);\n\n // Apply animation attribute if enabled (default: true)\n const animate = this.config.animate !== false;\n this.gridElement.toggleAttribute('data-responsive-animate', animate);\n\n // Toggle per-card label visibility based on hideHeader config.\n // Attribute only meaningful while in card mode; clear it otherwise so\n // the CSS rule cannot accidentally apply to non-responsive layouts.\n this.gridElement.toggleAttribute(\n 'data-responsive-hide-header',\n this.#isResponsive && this.config.hideHeader === true,\n );\n\n // Set custom animation duration if provided\n if (this.config.animationDuration) {\n this.gridElement.style.setProperty('--tbw-responsive-duration', `${this.config.animationDuration}ms`);\n }\n\n // Cast to internal type for virtualization access\n const internalGrid = this.#internalGrid;\n\n if (this.#isResponsive) {\n // Store original row height before responsive mode changes it\n if (internalGrid._virtualization) {\n this.#originalRowHeight = internalGrid._virtualization.rowHeight;\n }\n\n // Reset horizontal scroll position when entering responsive mode\n // The CSS hides overflow but doesn't reset the scroll position\n const scrollArea = this.gridElement.querySelector('.tbw-scroll-area') as HTMLElement | null;\n if (scrollArea) {\n scrollArea.scrollLeft = 0;\n }\n } else {\n // Exiting responsive mode - clean up inline styles set by renderRow\n // The rows are reused from the pool, so we need to remove the card-specific styles\n const rows = this.gridElement.querySelectorAll('.data-grid-row');\n for (const row of rows) {\n (row as HTMLElement).style.height = '';\n row.classList.remove('responsive-card');\n }\n\n // Restore original row height\n if (this.#originalRowHeight && this.#originalRowHeight > 0 && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = this.#originalRowHeight;\n this.#originalRowHeight = undefined;\n }\n\n // Clear cached measurements so they're remeasured fresh when re-entering responsive mode\n // Without this, stale measurements cause incorrect height calculations after scrolling\n this.#measuredCardHeight = undefined;\n this.#measuredGroupRowHeight = undefined;\n this.#lastCardRowCount = undefined;\n }\n }\n\n /**\n * Custom row rendering when cardRenderer is provided and in responsive mode.\n *\n * When a cardRenderer is configured, this hook takes over row rendering to display\n * the custom card layout instead of the default cell structure.\n *\n * @param row - The row data object\n * @param rowEl - The row DOM element to render into\n * @param rowIndex - The index of the row in the data array\n * @returns `true` if rendered (prevents default), `void` for default rendering\n */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean | void {\n // Only override when in responsive mode AND cardRenderer is provided\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return; // Let default rendering proceed\n }\n\n // Skip group rows from GroupingRowsPlugin - they have special structure\n // and should use their own renderer\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return; // Let GroupingRowsPlugin handle group row rendering\n }\n\n // Clear existing content\n rowEl.replaceChildren();\n\n // Call user's cardRenderer to get custom content\n const cardContent = this.config.cardRenderer(row as T, rowIndex);\n\n // Reset className - clears any stale classes from previous use (e.g., 'group-row' from recycled element)\n // This follows the same pattern as GroupingRowsPlugin which sets className explicitly\n rowEl.className = 'data-grid-row responsive-card';\n\n // Handle card row height — when a numeric height is configured, use the effective\n // height from #getCardHeight() which incorporates DOM measurement after first render.\n // This keeps inline height in sync with the position cache used for virtualization.\n const configuredHeight = this.config.cardRowHeight;\n if (configuredHeight === 'auto' || configuredHeight === undefined) {\n rowEl.style.height = 'auto';\n } else {\n rowEl.style.height = `${this.#getCardHeight()}px`;\n }\n\n // Append the custom card content\n rowEl.appendChild(cardContent);\n\n return true; // We handled rendering\n }\n\n /**\n * Handle keyboard navigation in responsive mode.\n *\n * In responsive mode, the visual layout is inverted:\n * - Cells are stacked vertically within each \"card\" (row)\n * - DOWN/UP visually moves within the card (between fields)\n * - Page Down/Page Up or Ctrl+Down/Up moves between cards\n *\n * For custom cardRenderers, keyboard navigation is disabled entirely\n * since the implementor controls the card content and should handle\n * navigation via their own event handlers.\n *\n * @returns `true` if the event was handled and default behavior should be prevented\n */\n override onKeyDown(e: KeyboardEvent): boolean {\n if (!this.#isResponsive) {\n return false;\n }\n\n // If custom cardRenderer is provided, disable grid's keyboard navigation\n // The implementor is responsible for their own navigation\n if (this.config.cardRenderer) {\n const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];\n if (navKeys.includes(e.key)) {\n // Let the event bubble - implementor can handle it\n return false;\n }\n }\n\n // Swap arrow key behavior for CSS-only responsive mode\n // In card layout, cells are stacked vertically:\n // Card 1: Card 2:\n // ID: 1 ID: 2\n // Name: Alice Name: Bob <- ArrowRight goes here\n // Dept: Eng Dept: Mkt\n // ↓ ArrowDown goes here\n //\n // ArrowDown/Up = move within card (change column/field)\n // ArrowRight/Left = move between cards (change row)\n const maxRow = this.rows.length - 1;\n const maxCol = this.visibleColumns.length - 1;\n\n switch (e.key) {\n case 'ArrowDown':\n // Move down WITHIN card (to next field/column)\n if (this.grid._focusCol < maxCol) {\n this.grid._focusCol += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At bottom of card - optionally move to next card's first field\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n this.grid._focusCol = 0;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowUp':\n // Move up WITHIN card (to previous field/column)\n if (this.grid._focusCol > 0) {\n this.grid._focusCol -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n // At top of card - optionally move to previous card's last field\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n this.grid._focusCol = maxCol;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowRight':\n // Move to NEXT card (same field)\n if (this.grid._focusRow < maxRow) {\n this.grid._focusRow += 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n\n case 'ArrowLeft':\n // Move to PREVIOUS card (same field)\n if (this.grid._focusRow > 0) {\n this.grid._focusRow -= 1;\n e.preventDefault();\n ensureCellVisible(this.#internalGrid);\n return true;\n }\n break;\n }\n\n return false;\n }\n\n // ============================================\n // Variable Height Support for Mixed Row Types\n // ============================================\n\n /** Measured card height from DOM for virtualization calculations */\n #measuredCardHeight?: number;\n\n /** Measured group row height from DOM for virtualization calculations */\n #measuredGroupRowHeight?: number;\n\n /** Last known card row count for detecting changes (e.g., group expand/collapse) */\n #lastCardRowCount?: number;\n\n /**\n * Get the effective card height for virtualization calculations.\n * Prioritizes DOM-measured height (actual rendered size) over config,\n * since content can overflow the configured height.\n */\n #getCardHeight(): number {\n // Prefer measured height - it reflects actual rendered size including overflow\n if (this.#measuredCardHeight && this.#measuredCardHeight > 0) {\n return this.#measuredCardHeight;\n }\n // Fall back to explicit config\n const configHeight = this.config.cardRowHeight;\n if (typeof configHeight === 'number' && configHeight > 0) {\n return configHeight;\n }\n // Default fallback\n return 80;\n }\n\n /**\n * Get the effective group row height for virtualization calculations.\n * Uses DOM-measured height, falling back to original row height.\n */\n #getGroupRowHeight(): number {\n if (this.#measuredGroupRowHeight && this.#measuredGroupRowHeight > 0) {\n return this.#measuredGroupRowHeight;\n }\n // Fall back to original row height (before responsive mode)\n return this.#originalRowHeight ?? 28;\n }\n\n /**\n * Check if there are any group rows in the current dataset.\n * Used to determine if we have mixed row heights.\n */\n #hasGroupRows(): boolean {\n for (const row of this.rows) {\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the height of a specific row based on its type (group row vs card row).\n * Returns undefined if not in responsive mode.\n *\n * @param row - The row data\n * @param _index - The row index (unused, but part of the interface)\n * @returns The row height in pixels, or undefined if not in responsive mode\n */\n override getRowHeight(row: unknown, _index: number): number | undefined {\n // Only applies when in responsive mode with cardRenderer\n if (!this.#isResponsive || !this.config.cardRenderer) {\n return undefined;\n }\n\n // Check if this is a group row\n if ((row as { __isGroupRow?: boolean }).__isGroupRow) {\n return this.#getGroupRowHeight();\n }\n\n // Regular card row\n return this.#getCardHeight();\n }\n\n /**\n * Count the number of card rows (non-group rows) in the current dataset.\n */\n #countCardRows(): number {\n let count = 0;\n for (const row of this.rows) {\n if (!(row as { __isGroupRow?: boolean }).__isGroupRow) {\n count++;\n }\n }\n return count;\n }\n\n /** Pending refresh scheduled via microtask */\n #pendingRefresh = false;\n\n /**\n * Measure card height from DOM after render and detect row count changes.\n * Called in afterRender to ensure scroll calculations are accurate.\n *\n * This handles two scenarios:\n * 1. Card height changes (content overflow, dynamic sizing)\n * 2. Card row count changes (group expand/collapse)\n * 3. Group row height changes\n *\n * For uniform card layouts (no groups), we update the virtualization row height\n * directly to the card height. For mixed layouts (groups + cards), we use the\n * getExtraHeight mechanism to report height differences.\n *\n * The refresh is deferred via microtask to avoid nested render cycles.\n */\n #measureCardHeightFromDOM(): void {\n if (!this.#isResponsive) {\n return;\n }\n\n let needsRefresh = false;\n const internalGrid = this.#internalGrid;\n const hasGroups = this.#hasGroupRows();\n\n // Check if card row count changed (e.g., group expanded/collapsed)\n const currentCardRowCount = this.#countCardRows();\n if (currentCardRowCount !== this.#lastCardRowCount) {\n this.#lastCardRowCount = currentCardRowCount;\n needsRefresh = true;\n }\n\n // Measure actual group row height from DOM (for mixed layouts)\n if (hasGroups) {\n const groupRow = this.gridElement.querySelector('.data-grid-row.group-row') as HTMLElement | null;\n if (groupRow) {\n const height = groupRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredGroupRowHeight) {\n this.#measuredGroupRowHeight = height;\n needsRefresh = true;\n }\n }\n }\n\n // Measure actual card height from DOM.\n // With cardRenderer, rows have the `.responsive-card` class.\n // Without cardRenderer (CSS-only card mode), rows are plain `.data-grid-row`\n // elements whose CSS height is `auto` — we need to measure their actual\n // rendered height so the faux scrollbar spacer is sized correctly.\n const cardSelector = this.config.cardRenderer ? '.data-grid-row.responsive-card' : '.data-grid-row:not(.group-row)';\n const cardRow = this.gridElement.querySelector(cardSelector) as HTMLElement | null;\n if (cardRow) {\n const height = cardRow.getBoundingClientRect().height;\n if (height > 0 && height !== this.#measuredCardHeight) {\n this.#measuredCardHeight = height;\n needsRefresh = true;\n\n // For uniform card layouts (no groups), update virtualization row height directly\n // This ensures proper row recycling and translateY calculations\n if (!hasGroups && internalGrid._virtualization) {\n internalGrid._virtualization.rowHeight = height;\n }\n }\n }\n\n // Defer virtualization refresh to avoid nested render cycles\n // This is called from afterRender, so we can't call refreshVirtualWindow synchronously\n // Use scheduler's VIRTUALIZATION phase to batch properly and avoid duplicate afterRender calls\n if (needsRefresh && !this.#pendingRefresh) {\n this.#pendingRefresh = true;\n queueMicrotask(() => {\n this.#pendingRefresh = false;\n // Only refresh if still attached and in responsive mode\n if (this.grid && this.#isResponsive) {\n // Request virtualization phase through grid's public API\n // This goes through the scheduler which batches and handles afterRender properly\n this.#internalGrid.refreshVirtualWindow?.(true, true);\n }\n });\n }\n }\n}\n"],"names":["ResponsivePlugin","BaseGridPlugin","name","version","styles","static","queries","type","description","resizeObserver","isResponsive","debounceTimer","warnedAboutMissingBreakpoint","currentWidth","hiddenColumnSet","Set","valueOnlyColumnSet","activeBreakpoint","sortedBreakpoints","internalGrid","this","grid","setResponsive","enabled","applyResponsiveState","emit","width","breakpoint","config","requestRender","setBreakpoint","checkBreakpoint","setCardRenderer","renderer","cardRenderer","getWidth","getActiveBreakpoint","attach","super","parseLightDomCard","buildHiddenColumnSets","hiddenColumns","breakpoints","length","sort","a","b","maxWidth","ResizeObserver","entries","contentRect","clearTimeout","setTimeout","debounceMs","observe","gridElement","gridEl","cardEl","querySelector","adapter","__frameworkAdapter","parseResponsiveCardElement","adapterRenderer","breakpointAttr","getAttribute","cardRowHeightAttr","hiddenColumnsAttr","hideHeaderAttr","debounceMsAttr","configUpdates","parseInt","isNaN","cardRowHeight","split","map","s","trim","filter","hideHeader","templateHTML","innerHTML","row","evaluated","evalTemplateString","value","sanitized","sanitizeHTML","container","document","createElement","className","Object","keys","clear","col","add","showValue","field","detach","disconnect","removeAttribute","handleQuery","query","afterRender","measureCardHeightFromDOM","hasHiddenColumns","size","hasValueOnlyColumns","cells","querySelectorAll","cell","has","setAttribute","checkMultiBreakpoint","warn","MISSING_BREAKPOINT","shouldBeResponsive","newActiveBreakpoint","bp","cardLayout","originalRowHeight","toggleAttribute","animate","animationDuration","style","setProperty","_virtualization","rowHeight","scrollArea","scrollLeft","rows","height","classList","remove","measuredCardHeight","measuredGroupRowHeight","lastCardRowCount","renderRow","rowEl","rowIndex","__isGroupRow","replaceChildren","cardContent","configuredHeight","getCardHeight","appendChild","onKeyDown","e","includes","key","maxRow","maxCol","visibleColumns","_focusCol","preventDefault","ensureCellVisible","_focusRow","configHeight","getGroupRowHeight","hasGroupRows","getRowHeight","_index","countCardRows","count","pendingRefresh","needsRefresh","hasGroups","currentCardRowCount","groupRow","getBoundingClientRect","cardSelector","cardRow","queueMicrotask","refreshVirtualWindow"],"mappings":"mlBAmFO,MAAMA,UAAsCC,EAAAA,eACxCC,KAAO,aACEC,QAAU,QACVC,qsHAKlBC,gBAAoD,CAClDC,QAAS,CACP,CACEC,KAAM,aACNC,YAAa,mEAKnBC,GACAC,IAAgB,EAChBC,GACAC,IAAgC,EAChCC,GAAgB,EAEhBC,OAAoCC,IAEpCC,OAAuCD,IAEvCE,GAA6C,KAE7CC,GAAyC,GAGzC,KAAIC,GACF,OAAOC,KAAKC,IACd,CAMA,YAAAX,GACE,OAAOU,MAAKV,CACd,CAOA,aAAAY,CAAcC,GACRA,IAAYH,MAAKV,IACnBU,MAAKV,EAAgBa,EACrBH,MAAKI,IACLJ,KAAKK,KAAK,oBAAqB,CAC7Bf,aAAca,EACdG,MAAON,MAAKP,EACZc,WAAYP,KAAKQ,OAAOD,YAAc,IAExCP,KAAKS,gBAET,CAMA,aAAAC,CAAcJ,GACZN,KAAKQ,OAAOD,WAAaD,EACzBN,MAAKW,EAAiBX,MAAKP,EAC7B,CAOA,eAAAmB,CAAgBC,GACdb,KAAKQ,OAAOM,aAAeD,EAEvBb,MAAK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Z,MAAMrC,EAASqC,EAASC,wBAAwBtC,OAC5CA,EAAS,GAAKA,IAAW/G,MAAKmH,IAChCnH,MAAKmH,EAA0BJ,EAC/BkC,GAAe,EAEnB,CACF,CAOA,MAAMK,EAAetJ,KAAKQ,OAAOM,aAAe,iCAAmC,iCAC7EyI,EAAUvJ,KAAKmC,YAAYG,cAAcgH,GAC/C,GAAIC,EAAS,CACX,MAAMxC,EAASwC,EAAQF,wBAAwBtC,OAC3CA,EAAS,GAAKA,IAAW/G,MAAKkH,IAChClH,MAAKkH,EAAsBH,EAC3BkC,GAAe,GAIVC,GAAanJ,EAAa2G,kBAC7B3G,EAAa2G,gBAAgBC,UAAYI,GAG/C,CAKIkC,IAAiBjJ,MAAKgJ,IACxBhJ,MAAKgJ,GAAkB,EACvBQ,eAAe,KACbxJ,MAAKgJ,GAAkB,EAEnBhJ,KAAKC,MAAQD,MAAKV,GAGpBU,MAAKD,EAAc0J,wBAAuB,GAAM,KAIxD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/diagnostics"),require("../../core/internal/sorting"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/diagnostics","../../core/internal/sorting","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_serverSide={},t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,o,i){"use strict";function s(t,e){return Math.floor(t/e)}function r(){return new DOMException("Aborted","AbortError")}function a(t,e,o,i,s){const a=function(t,e){return{start:t*e,end:(t+1)*e}}(e,o);return function(t,e){return e.aborted?Promise.reject(r()):"object"!=typeof(o=t)||null===o||"function"!=typeof o.subscribe||"function"==typeof o.then?new Promise((o,i)=>{const s=()=>i(r());e.addEventListener("abort",s,{once:!0}),Promise.resolve(t).then(t=>{e.removeEventListener("abort",s),o(t)},t=>{e.removeEventListener("abort",s),i(t)})}):new Promise((o,i)=>{let s=!1;const a=t.subscribe({next:t=>{s||(s=!0,o(t),a.unsubscribe())},error:t=>{s||(s=!0,i(t))},complete:()=>{s||(s=!0,i(new Error("getRows observable completed without emitting a value")))}});s||e.addEventListener("abort",()=>{s||(s=!0,a.unsubscribe(),i(r()))},{once:!0})});var o}(t.getRows({startNode:a.start,endNode:a.end,sortModel:i.sortModel,filterModel:i.filterModel,signal:s}),s)}function n(t,e,o){const i=s(t,e),r=o.get(i);if(!r)return;return r[t%e]}class d extends i.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:-10},incompatibleWith:[{name:"pivot",reason:"PivotPlugin requires the full dataset to compute aggregations. ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side."}],events:[{type:"datasource:data",description:"Root data page/block loaded"},{type:"datasource:children",description:"Child data loaded for a parent context"},{type:"datasource:loading",description:"Loading state changed"},{type:"datasource:error",description:"Fetch operation failed"}],queries:[{type:"datasource:fetch-children",description:"Request child rows for a parent context"},{type:"datasource:is-active",description:"Check if ServerSide plugin has an active data source"}]};name="serverSide";get defaultConfig(){return{pageSize:100,cacheBlockSize:100,maxConcurrentRequests:2}}dataSource=null;totalNodeCount=0;infiniteScrollMode=!1;loadedBlocks=new Map;loadingBlocks=new Set;blockControllers=new Map;lastRequestId=0;scrollDebounceTimer;managedNodes=[];attach(t){super.attach(t),this.on("sort-change",()=>{"local"===this.config.sortMode?this.requestRender():this.onModelChange()}),this.on("filter-change",()=>{"local"===this.config.filterMode?this.requestRender():this.onModelChange()}),this.config.dataSource&&this.setDataSource(this.config.dataSource)}detach(){this.dataSource=null,this.totalNodeCount=0,this.infiniteScrollMode=!1,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.abortAllBlocks(),this.managedNodes=[],this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}abortAllBlocks(){for(const t of this.blockControllers.values())t.abort();this.blockControllers.clear()}getEnrichmentParams(){const t="local"===this.config.sortMode,e="local"===this.config.filterMode,o=t?void 0:this.grid?.query?.("sort:get-model",null),i=e?void 0:this.grid?.query?.("filter:get-model",null);let s=o?.[0];const r=this.grid;if(!t&&!s&&r?._sortState){const{field:t,direction:e}=r._sortState;s=[{field:t,direction:1===e?"asc":"desc"}]}return{sortModel:s,filterModel:i?.[0]}}getViewportMapping(t,e){const o={viewportStart:t,viewportEnd:e},i=this.grid?.query?.("datasource:viewport-mapping",o);return i?.[0]?i[0]:{startNode:t,endNode:e,totalLoadedNodes:this.totalNodeCount}}onModelChange(){this.dataSource&&(this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.requestRender(),this.loadRequiredBlocks())}applyServerResult(t,e,o){void 0!==t.lastNode?(this.totalNodeCount=t.lastNode+1,this.infiniteScrollMode=!1):-1===t.totalNodeCount?this.infiniteScrollMode=!0:(this.totalNodeCount=t.totalNodeCount,this.infiniteScrollMode=!1),this.infiniteScrollMode&&t.rows.length<o&&(this.totalNodeCount=e*o+t.rows.length,this.infiniteScrollMode=!1)}getInfiniteScrollEstimate(t){let e=0;for(const[o,i]of this.loadedBlocks){const s=o*t+i.length;s>e&&(e=s)}return e+t}loadRequiredBlocks(){if(!this.dataSource)return;const t=this.grid,o=this.config.cacheBlockSize??100,i=this.getViewportMapping(t._virtualization.start,t._virtualization.end),r=Math.max(0,this.config.loadThreshold??0),n=Math.max(0,i.startNode-r),d=this.totalNodeCount>0?this.totalNodeCount:1/0,l=Math.min(d,i.endNode+r);if(l<=n)return;const c=function(t,e,o){const i=s(t,o),r=s(e-1,o),a=[];for(let s=i;s<=r;s++)a.push(s);return a}(n,l,o),h=this.getEnrichmentParams(),u=this.grid?.getAttribute?.("id")??void 0;for(const s of c){if(this.loadedBlocks.has(s)||this.loadingBlocks.has(s))continue;if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2)){e.debugDiagnostic(e.DATASOURCE_THROTTLED,"Concurrent request limit reached, deferring block load",u);break}this.loadingBlocks.add(s);const t=new AbortController;this.blockControllers.set(s,t),this.broadcast("datasource:loading",{loading:!0}),a(this.dataSource,s,o,h,t.signal).then(e=>{if(this.blockControllers.delete(s),t.signal.aborted)return this.loadingBlocks.delete(s),void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));this.loadedBlocks.set(s,e.rows);const i=this.managedNodes.length;this.applyServerResult(e,s,o),this.loadingBlocks.delete(s);const r=s*o;for(let t=0;t<e.rows.length;t++)r+t<this.managedNodes.length&&(this.managedNodes[r+t]=e.rows[t]);const a={rows:e.rows,totalNodeCount:e.totalNodeCount,startNode:r,endNode:r+e.rows.length,claimed:!1};this.broadcast("datasource:data",a),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1});0===i||this.managedNodes.length<(Number.isFinite(this.totalNodeCount)?this.totalNodeCount:0)?this.requestRender():this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(o=>{if(this.blockControllers.delete(s),this.loadingBlocks.delete(s),t.signal.aborted)return void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));const i=o instanceof Error?o:new Error(String(o));e.errorDiagnostic(e.DATASOURCE_FETCH_ERROR,`getRows() failed: ${i.message}`,u),this.broadcast("datasource:error",{error:i}),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1})})}}processRows(t){if(!this.dataSource)return[...t];const e=this.config.cacheBlockSize??100,i=this.infiniteScrollMode?this.getInfiniteScrollEstimate(e):Number.isFinite(this.totalNodeCount)&&this.totalNodeCount>=0?this.totalNodeCount:0;for(;this.managedNodes.length<i;){const t=this.managedNodes.length;this.managedNodes.push({__loading:!0,__index:t})}this.managedNodes.length=i;for(let o=0;o<i;o++){const t=n(o,e,this.loadedBlocks);t&&(this.managedNodes[o]=t)}const s=this.grid;if("local"===this.config.sortMode&&s?._sortState){const t=s._columns??[],e=(s.effectiveConfig?.sortHandler??o.builtInSort)(this.managedNodes,s._sortState,t);return e&&"function"==typeof e.then?(e.catch(()=>{}),this.managedNodes):e}return this.managedNodes}onScroll(t){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}handleQuery(t){switch(t.type){case"datasource:is-active":return null!=this.dataSource;case"datasource:fetch-children":{const{context:e}=t.context;return void this.fetchChildren(e)}}}fetchChildren(t){if(!this.dataSource)return;const o=this.grid?.getAttribute?.("id")??void 0;if(!this.dataSource.getChildRows)return void e.warnDiagnostic(e.DATASOURCE_NO_CHILD_HANDLER,`Plugin "${t.source}" requested child rows but getChildRows() is not implemented on the dataSource`,o);const i=this.getEnrichmentParams();this.broadcast("datasource:loading",{loading:!0,context:t}),this.dataSource.getChildRows({context:t,sortModel:i.sortModel,filterModel:i.filterModel}).then(e=>{const o={rows:e.rows,context:t,claimed:!1};this.broadcast("datasource:children",o),this.broadcast("datasource:loading",{loading:!1,context:t})}).catch(i=>{const s=i instanceof Error?i:new Error(String(i));e.errorDiagnostic(e.DATASOURCE_CHILD_FETCH_ERROR,`getChildRows() failed: ${s.message}`,o),this.broadcast("datasource:error",{error:s,context:t}),this.broadcast("datasource:loading",{loading:!1,context:t})})}setDataSource(t){this.abortAllBlocks(),this.dataSource=t,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1;const o=this.config.cacheBlockSize??100,i=this.getEnrichmentParams(),s=this.grid?.getAttribute?.("id")??void 0,r=new AbortController;this.blockControllers.set(0,r),this.loadingBlocks.add(0),this.broadcast("datasource:loading",{loading:!0}),a(t,0,o,i,r.signal).then(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),r.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});this.loadedBlocks.set(0,t.rows),this.applyServerResult(t,0,o);const e={rows:t.rows,totalNodeCount:t.totalNodeCount,startNode:0,endNode:t.rows.length,claimed:!1};this.broadcast("datasource:data",e),this.broadcast("datasource:loading",{loading:!1}),this.requestRender(),(this.config.loadThreshold??0)>0&&this.loadRequiredBlocks()}).catch(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),r.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});const o=t instanceof Error?t:new Error(String(t));e.errorDiagnostic(e.DATASOURCE_FETCH_ERROR,`getRows() failed: ${o.message}`,s),this.broadcast("datasource:error",{error:o}),this.broadcast("datasource:loading",{loading:!1})})}refresh(){if(!this.dataSource)return;const t=this.dataSource;this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.setDataSource(t)}purgeCache(){this.abortAllBlocks(),this.loadedBlocks.clear(),this.managedNodes=[]}getTotalNodeCount(){return this.totalNodeCount}getTotalRowCount(){return this.totalNodeCount}isNodeLoaded(t){const e=s(t,this.config.cacheBlockSize??100);return this.loadedBlocks.has(e)}isRowLoaded(t){return this.isNodeLoaded(t)}getLoadedBlockCount(){return this.loadedBlocks.size}}t.ServerSidePlugin=d,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("../../core/internal/diagnostics"),require("../../core/internal/sorting"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/internal/diagnostics","../../core/internal/sorting","../../core/plugin/base-plugin"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TbwGridPlugin_serverSide={},t.TbwGrid,t.TbwGrid,t.TbwGrid)}(this,function(t,e,o,i){"use strict";function s(t,e){return Math.floor(t/e)}function r(){return new DOMException("Aborted","AbortError")}function a(t,e,o,i,s){const a=function(t,e){return{start:t*e,end:(t+1)*e}}(e,o);return function(t,e){return e.aborted?Promise.reject(r()):"object"!=typeof(o=t)||null===o||"function"!=typeof o.subscribe||"function"==typeof o.then?new Promise((o,i)=>{const s=()=>i(r());e.addEventListener("abort",s,{once:!0}),Promise.resolve(t).then(t=>{e.removeEventListener("abort",s),o(t)},t=>{e.removeEventListener("abort",s),i(t)})}):new Promise((o,i)=>{let s=!1;const a=t.subscribe({next:t=>{s||(s=!0,o(t),a.unsubscribe())},error:t=>{s||(s=!0,i(t))},complete:()=>{s||(s=!0,i(new Error("getRows observable completed without emitting a value")))}});s||e.addEventListener("abort",()=>{s||(s=!0,a.unsubscribe(),i(r()))},{once:!0})});var o}(t.getRows({startNode:a.start,endNode:a.end,pageSize:a.end-a.start,sortModel:i.sortModel,filterModel:i.filterModel,signal:s}),s)}function n(t,e,o){const i=s(t,e),r=o.get(i);if(!r)return;return r[t%e]}class d extends i.BaseGridPlugin{static manifest={modifiesRowStructure:!0,hookPriority:{processRows:-10},incompatibleWith:[{name:"pivot",reason:"PivotPlugin requires the full dataset to compute aggregations. ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side."}],events:[{type:"datasource:data",description:"Root data page/block loaded"},{type:"datasource:children",description:"Child data loaded for a parent context"},{type:"datasource:loading",description:"Loading state changed"},{type:"datasource:error",description:"Fetch operation failed"}],queries:[{type:"datasource:fetch-children",description:"Request child rows for a parent context"},{type:"datasource:is-active",description:"Check if ServerSide plugin has an active data source"}]};name="serverSide";get defaultConfig(){return{maxConcurrentRequests:2}}dataSource=null;totalNodeCount=0;infiniteScrollMode=!1;loadedBlocks=new Map;loadingBlocks=new Set;blockControllers=new Map;lastRequestId=0;scrollDebounceTimer;managedNodes=[];attach(t){super.attach(t),this.on("sort-change",()=>{"local"===this.config.sortMode?this.requestRender():this.onModelChange()}),this.on("filter-change",()=>{"local"===this.config.filterMode?this.requestRender():this.onModelChange()}),this.config.dataSource&&this.setDataSource(this.config.dataSource)}detach(){this.dataSource=null,this.totalNodeCount=0,this.infiniteScrollMode=!1,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.abortAllBlocks(),this.managedNodes=[],this.lastRequestId=0,this.scrollDebounceTimer&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=void 0)}abortAllBlocks(){for(const t of this.blockControllers.values())t.abort();this.blockControllers.clear()}getEnrichmentParams(){const t="local"===this.config.sortMode,e="local"===this.config.filterMode,o=t?void 0:this.grid?.query?.("sort:get-model",null),i=e?void 0:this.grid?.query?.("filter:get-model",null);let s=o?.[0];const r=this.grid;if(!t&&!s&&r?._sortState){const{field:t,direction:e}=r._sortState;s=[{field:t,direction:1===e?"asc":"desc"}]}return{sortModel:s,filterModel:i?.[0]}}getViewportMapping(t,e){const o={viewportStart:t,viewportEnd:e},i=this.grid?.query?.("datasource:viewport-mapping",o);return i?.[0]?i[0]:{startNode:t,endNode:e,totalLoadedNodes:this.totalNodeCount}}onModelChange(){this.dataSource&&(this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.requestRender(),this.loadRequiredBlocks())}applyServerResult(t,e,o){void 0!==t.lastNode?(this.totalNodeCount=t.lastNode+1,this.infiniteScrollMode=!1):-1===t.totalNodeCount?this.infiniteScrollMode=!0:(this.totalNodeCount=t.totalNodeCount,this.infiniteScrollMode=!1),this.infiniteScrollMode&&t.rows.length<o&&(this.totalNodeCount=e*o+t.rows.length,this.infiniteScrollMode=!1)}getInfiniteScrollEstimate(t){let e=0;for(const[o,i]of this.loadedBlocks){const s=o*t+i.length;s>e&&(e=s)}return e+t}loadRequiredBlocks(){if(!this.dataSource)return;const t=this.grid,o=this.config.pageSize??this.config.cacheBlockSize??100,i=this.getViewportMapping(t._virtualization.start,t._virtualization.end),r=Math.max(0,this.config.loadThreshold??0),n=Math.max(0,i.startNode-r),d=this.totalNodeCount>0?this.totalNodeCount:1/0,l=Math.min(d,i.endNode+r);if(l<=n)return;const c=function(t,e,o){const i=s(t,o),r=s(e-1,o),a=[];for(let s=i;s<=r;s++)a.push(s);return a}(n,l,o),h=this.getEnrichmentParams(),u=this.grid?.getAttribute?.("id")??void 0;for(const s of c){if(this.loadedBlocks.has(s)||this.loadingBlocks.has(s))continue;if(this.loadingBlocks.size>=(this.config.maxConcurrentRequests??2)){e.debugDiagnostic(e.DATASOURCE_THROTTLED,"Concurrent request limit reached, deferring block load",u);break}this.loadingBlocks.add(s);const t=new AbortController;this.blockControllers.set(s,t),this.broadcast("datasource:loading",{loading:!0}),a(this.dataSource,s,o,h,t.signal).then(e=>{if(this.blockControllers.delete(s),t.signal.aborted)return this.loadingBlocks.delete(s),void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));this.loadedBlocks.set(s,e.rows);const i=this.managedNodes.length;this.applyServerResult(e,s,o),this.loadingBlocks.delete(s);const r=s*o;for(let t=0;t<e.rows.length;t++)r+t<this.managedNodes.length&&(this.managedNodes[r+t]=e.rows[t]);const a={rows:e.rows,totalNodeCount:e.totalNodeCount,startNode:r,endNode:r+e.rows.length,claimed:!1};this.broadcast("datasource:data",a),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1});0===i||this.managedNodes.length<(Number.isFinite(this.totalNodeCount)?this.totalNodeCount:0)?this.requestRender():this.requestVirtualRefresh(),this.loadRequiredBlocks()}).catch(o=>{if(this.blockControllers.delete(s),this.loadingBlocks.delete(s),t.signal.aborted)return void(0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1}));const i=o instanceof Error?o:new Error(String(o));e.errorDiagnostic(e.DATASOURCE_FETCH_ERROR,`getRows() failed: ${i.message}`,u),this.broadcast("datasource:error",{error:i}),0===this.loadingBlocks.size&&this.broadcast("datasource:loading",{loading:!1})})}}processRows(t){if(!this.dataSource)return[...t];const e=this.config.pageSize??this.config.cacheBlockSize??100,i=this.infiniteScrollMode?this.getInfiniteScrollEstimate(e):Number.isFinite(this.totalNodeCount)&&this.totalNodeCount>=0?this.totalNodeCount:0;for(;this.managedNodes.length<i;){const t=this.managedNodes.length;this.managedNodes.push({__loading:!0,__index:t})}this.managedNodes.length=i;for(let o=0;o<i;o++){const t=n(o,e,this.loadedBlocks);t&&(this.managedNodes[o]=t)}const s=this.grid;if("local"===this.config.sortMode&&s?._sortState){const t=s._columns??[],e=(s.effectiveConfig?.sortHandler??o.builtInSort)(this.managedNodes,s._sortState,t);return e&&"function"==typeof e.then?(e.catch(()=>{}),this.managedNodes):e}return this.managedNodes}onScroll(t){this.dataSource&&(this.loadRequiredBlocks(),this.scrollDebounceTimer&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=setTimeout(()=>{this.loadRequiredBlocks()},100))}handleQuery(t){switch(t.type){case"datasource:is-active":return null!=this.dataSource;case"datasource:fetch-children":{const{context:e}=t.context;return void this.fetchChildren(e)}}}fetchChildren(t){if(!this.dataSource)return;const o=this.grid?.getAttribute?.("id")??void 0;if(!this.dataSource.getChildRows)return void e.warnDiagnostic(e.DATASOURCE_NO_CHILD_HANDLER,`Plugin "${t.source}" requested child rows but getChildRows() is not implemented on the dataSource`,o);const i=this.getEnrichmentParams();this.broadcast("datasource:loading",{loading:!0,context:t}),this.dataSource.getChildRows({context:t,sortModel:i.sortModel,filterModel:i.filterModel}).then(e=>{const o={rows:e.rows,context:t,claimed:!1};this.broadcast("datasource:children",o),this.broadcast("datasource:loading",{loading:!1,context:t})}).catch(i=>{const s=i instanceof Error?i:new Error(String(i));e.errorDiagnostic(e.DATASOURCE_CHILD_FETCH_ERROR,`getChildRows() failed: ${s.message}`,o),this.broadcast("datasource:error",{error:s,context:t}),this.broadcast("datasource:loading",{loading:!1,context:t})})}setDataSource(t){this.abortAllBlocks(),this.dataSource=t,this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1;const o=this.config.pageSize??this.config.cacheBlockSize??100,i=this.getEnrichmentParams(),s=this.grid?.getAttribute?.("id")??void 0,r=new AbortController;this.blockControllers.set(0,r),this.loadingBlocks.add(0),this.broadcast("datasource:loading",{loading:!0}),a(t,0,o,i,r.signal).then(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),r.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});this.loadedBlocks.set(0,t.rows),this.applyServerResult(t,0,o);const e={rows:t.rows,totalNodeCount:t.totalNodeCount,startNode:0,endNode:t.rows.length,claimed:!1};this.broadcast("datasource:data",e),this.broadcast("datasource:loading",{loading:!1}),this.requestRender(),(this.config.loadThreshold??0)>0&&this.loadRequiredBlocks()}).catch(t=>{if(this.blockControllers.delete(0),this.loadingBlocks.delete(0),r.signal.aborted)return void this.broadcast("datasource:loading",{loading:!1});const o=t instanceof Error?t:new Error(String(t));e.errorDiagnostic(e.DATASOURCE_FETCH_ERROR,`getRows() failed: ${o.message}`,s),this.broadcast("datasource:error",{error:o}),this.broadcast("datasource:loading",{loading:!1})})}refresh(){if(!this.dataSource)return;const t=this.dataSource;this.abortAllBlocks(),this.loadedBlocks.clear(),this.loadingBlocks.clear(),this.managedNodes=[],this.totalNodeCount=0,this.infiniteScrollMode=!1,this.setDataSource(t)}purgeCache(){this.abortAllBlocks(),this.loadedBlocks.clear(),this.managedNodes=[]}getTotalNodeCount(){return this.totalNodeCount}getTotalRowCount(){return this.totalNodeCount}isNodeLoaded(t){const e=s(t,this.config.pageSize??this.config.cacheBlockSize??100);return this.loadedBlocks.has(e)}isRowLoaded(t){return this.isNodeLoaded(t)}getLoadedBlockCount(){return this.loadedBlocks.size}}t.ServerSidePlugin=d,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=server-side.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-side.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/server-side/datasource.ts","../../../../../libs/grid/src/lib/plugins/server-side/ServerSidePlugin.ts"],"sourcesContent":["import type { GetRowsParams, GetRowsResult, ServerSideDataSource, Subscribable } from './datasource-types';\n\nexport function getBlockNumber(nodeIndex: number, blockSize: number): number {\n return Math.floor(nodeIndex / blockSize);\n}\n\nexport function getBlockRange(blockNumber: number, blockSize: number): { start: number; end: number } {\n return {\n start: blockNumber * blockSize,\n end: (blockNumber + 1) * blockSize,\n };\n}\n\nexport function getRequiredBlocks(startNode: number, endNode: number, blockSize: number): number[] {\n const startBlock = getBlockNumber(startNode, blockSize);\n const endBlock = getBlockNumber(endNode - 1, blockSize);\n\n const blocks: number[] = [];\n for (let i = startBlock; i <= endBlock; i++) {\n blocks.push(i);\n }\n return blocks;\n}\n\nfunction isSubscribable<T>(value: unknown): value is Subscribable<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { subscribe?: unknown }).subscribe === 'function' &&\n // Promises don't have `.subscribe`, but defensively rule them out.\n typeof (value as { then?: unknown }).then !== 'function'\n );\n}\n\nfunction makeAbortError(): DOMException {\n return new DOMException('Aborted', 'AbortError');\n}\n\n/**\n * Bridge a `Promise | Subscribable` getRows return value into a single\n * `Promise<GetRowsResult>`. For Subscribables, abort triggers `unsubscribe()`\n * so the underlying request (e.g. Angular `HttpClient` XHR) is cancelled.\n * Promise sources should pass `signal` to `fetch` themselves — we still reject\n * on abort either way so the plugin's abort path is consistent.\n */\nexport function toResultPromise<T>(\n source: Promise<T> | Subscribable<T>,\n signal: AbortSignal,\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(makeAbortError());\n }\n if (!isSubscribable<T>(source)) {\n // Promise path: reject on abort so the plugin's catch sees a consistent\n // signal even if the underlying fetch ignored params.signal.\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(makeAbortError());\n signal.addEventListener('abort', onAbort, { once: true });\n Promise.resolve(source).then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n }\n // Subscribable path: subscribe once, settle on next/error/complete, and\n // unsubscribe on abort — that's what cancels HttpClient's XHR.\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n const subscription = source.subscribe({\n next: (value) => {\n if (settled) return;\n settled = true;\n resolve(value);\n subscription.unsubscribe();\n },\n error: (err) => {\n if (settled) return;\n settled = true;\n reject(err);\n },\n complete: () => {\n if (settled) return;\n settled = true;\n reject(new Error('getRows observable completed without emitting a value'));\n },\n });\n if (settled) return; // synchronous emit\n const onAbort = () => {\n if (settled) return;\n settled = true;\n subscription.unsubscribe();\n reject(makeAbortError());\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport function loadBlock(\n dataSource: ServerSideDataSource,\n blockNumber: number,\n blockSize: number,\n params: Partial<GetRowsParams>,\n signal: AbortSignal,\n): Promise<GetRowsResult> {\n const range = getBlockRange(blockNumber, blockSize);\n\n const result = dataSource.getRows({\n startNode: range.start,\n endNode: range.end,\n sortModel: params.sortModel,\n filterModel: params.filterModel,\n signal,\n });\n return toResultPromise(result, signal);\n}\n\nexport function getRowFromCache(\n nodeIndex: number,\n blockSize: number,\n loadedBlocks: Map<number, unknown[]>,\n): unknown | undefined {\n const blockNumber = getBlockNumber(nodeIndex, blockSize);\n const block = loadedBlocks.get(blockNumber);\n if (!block) return undefined;\n\n const indexInBlock = nodeIndex % blockSize;\n return block[indexInBlock];\n}\n\nexport function isBlockLoaded(blockNumber: number, loadedBlocks: Map<number, unknown[]>): boolean {\n return loadedBlocks.has(blockNumber);\n}\n\nexport function isBlockLoading(blockNumber: number, loadingBlocks: Set<number>): boolean {\n return loadingBlocks.has(blockNumber);\n}\n","/**\n * Server-Side Data Plugin (Class-based)\n *\n * Central data orchestrator for the grid. Owns fetch + cache + row-model management.\n * Structural plugins (Tree, GroupingRows) claim data via events; core grid uses it\n * as flat rows when unclaimed.\n */\n\nimport {\n DATASOURCE_CHILD_FETCH_ERROR,\n DATASOURCE_FETCH_ERROR,\n DATASOURCE_NO_CHILD_HANDLER,\n DATASOURCE_THROTTLED,\n debugDiagnostic,\n errorDiagnostic,\n warnDiagnostic,\n} from '../../core/internal/diagnostics';\nimport { builtInSort } from '../../core/internal/sorting';\nimport { BaseGridPlugin, ScrollEvent, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, GridHost } from '../../core/types';\nimport { getBlockNumber, getRequiredBlocks, getRowFromCache, loadBlock } from './datasource';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n DataSourceLoadingDetail,\n FetchChildrenQuery,\n GetRowsParams,\n GetRowsResult,\n ServerSideDataSource,\n ViewportMappingQuery,\n ViewportMappingResponse,\n} from './datasource-types';\nimport type { ServerSideConfig } from './types';\n\n/** Scroll debounce delay in ms */\nconst SCROLL_DEBOUNCE_MS = 100;\n\n/**\n * Server-Side Data Plugin for tbw-grid\n *\n * Central data orchestrator for the grid. Manages fetch, cache, and row-model for\n * server-side data loading. Structural plugins (Tree, GroupingRows) can claim data\n * via events; the core grid uses it as flat rows when unclaimed.\n *\n * ## Installation\n *\n * ```ts\n * import { ServerSidePlugin } from '@toolbox-web/grid/plugins/server-side';\n * ```\n *\n * ## DataSource Interface\n *\n * ```ts\n * interface ServerSideDataSource {\n * getRows(params: GetRowsParams): Promise<GetRowsResult>;\n * getChildRows?(params: GetChildRowsParams): Promise<GetChildRowsResult>;\n * }\n * ```\n *\n * @example Basic Server-Side Loading\n * ```ts\n * import '@toolbox-web/grid';\n * import '@toolbox-web/grid/features/server-side';\n *\n * grid.gridConfig = {\n * columns: [...],\n * features: {\n * serverSide: {\n * pageSize: 50,\n * dataSource: {\n * async getRows(params) {\n * const response = await fetch(\n * `/api/data?start=${params.startNode}&end=${params.endNode}`\n * );\n * const data = await response.json();\n * return { rows: data.rows, totalNodeCount: data.total };\n * },\n * },\n * },\n * },\n * };\n * ```\n *\n * @see {@link ServerSideConfig} for configuration options\n * @see {@link ServerSideDataSource} for data source interface\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class ServerSidePlugin extends BaseGridPlugin<ServerSideConfig> {\n /**\n * Plugin manifest declaring capabilities, hooks, events, and queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n hookPriority: {\n processRows: -10, // Run before structural plugins (Tree, GroupingRows)\n },\n incompatibleWith: [\n {\n name: 'pivot',\n reason:\n 'PivotPlugin requires the full dataset to compute aggregations. ' +\n 'ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side.',\n },\n ],\n events: [\n { type: 'datasource:data', description: 'Root data page/block loaded' },\n { type: 'datasource:children', description: 'Child data loaded for a parent context' },\n { type: 'datasource:loading', description: 'Loading state changed' },\n { type: 'datasource:error', description: 'Fetch operation failed' },\n ],\n queries: [\n { type: 'datasource:fetch-children', description: 'Request child rows for a parent context' },\n { type: 'datasource:is-active', description: 'Check if ServerSide plugin has an active data source' },\n ],\n };\n\n /** @internal */\n readonly name = 'serverSide';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ServerSideConfig> {\n return {\n pageSize: 100,\n cacheBlockSize: 100,\n maxConcurrentRequests: 2,\n };\n }\n\n // #region Internal State\n private dataSource: ServerSideDataSource | null = null;\n private totalNodeCount = 0;\n private infiniteScrollMode = false;\n private loadedBlocks = new Map<number, unknown[]>();\n private loadingBlocks = new Set<number>();\n /**\n * Per-block AbortControllers for in-flight requests. Aborted when a block\n * is superseded (sort/filter change, refresh, purgeCache, detach) so data\n * sources that honor `params.signal` (e.g. `fetch`, RxJS via `fromObservable`)\n * can cancel the underlying network call.\n */\n private blockControllers = new Map<number, AbortController>();\n private lastRequestId = 0;\n private scrollDebounceTimer?: ReturnType<typeof setTimeout>;\n /** Persistent node array with stable placeholder references to avoid unnecessary DOM rebuilds. */\n private managedNodes: unknown[] = [];\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 // Invalidate cache and refetch on sort/filter changes — gated by sortMode/filterMode.\n // 'local' (opt-in): keep cache; sort/filter the loaded rows in place via a re-render.\n // See getEnrichmentParams() — local-mode state is also omitted from block fetch params\n // so scroll-triggered loadRequiredBlocks() doesn't leak local state to the backend.\n this.on('sort-change', () => {\n if (this.config.sortMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n this.on('filter-change', () => {\n if (this.config.filterMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n\n // Auto-initialize from config when dataSource is provided declaratively\n if (this.config.dataSource) {\n this.setDataSource(this.config.dataSource);\n }\n }\n\n /** @internal */\n override detach(): void {\n this.dataSource = null;\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.abortAllBlocks();\n this.managedNodes = [];\n this.lastRequestId = 0;\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n this.scrollDebounceTimer = undefined;\n }\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Abort all in-flight block requests. Called when the plugin tears down,\n * the data source is replaced, the cache is purged, or the sort/filter\n * model changes (the previously loaded block coordinates no longer apply).\n */\n private abortAllBlocks(): void {\n for (const controller of this.blockControllers.values()) {\n controller.abort();\n }\n this.blockControllers.clear();\n }\n\n /**\n * Build enrichment params by querying sort/filter models from loaded plugins.\n *\n * When `sortMode === 'local'` the `sortModel` is omitted so scroll-triggered\n * block fetches don't ask the backend for an ordering it isn't applying.\n * Same for `filterMode === 'local'` and `filterModel`.\n */\n private getEnrichmentParams(): Partial<GetRowsParams> {\n const sortLocal = this.config.sortMode === 'local';\n const filterLocal = this.config.filterMode === 'local';\n const sortResults = sortLocal\n ? undefined\n : (this.grid?.query?.('sort:get-model', null) as\n | Array<{ field: string; direction: 'asc' | 'desc' }>[]\n | undefined);\n const filterResults = filterLocal\n ? undefined\n : (this.grid?.query?.('filter:get-model', null) as Record<string, unknown>[] | undefined);\n\n // Fallback to core single-column sort state when no plugin answers the\n // 'sort:get-model' query (e.g. MultiSortPlugin not loaded). Translate the\n // numeric direction (1/-1) to the public 'asc'/'desc' string form.\n let sortModel = sortResults?.[0];\n const host = this.grid as unknown as GridHost | undefined;\n if (!sortLocal && !sortModel && host?._sortState) {\n const { field, direction } = host._sortState;\n sortModel = [{ field, direction: direction === 1 ? 'asc' : 'desc' }];\n }\n\n return {\n sortModel,\n filterModel: filterResults?.[0],\n };\n }\n\n /**\n * Translate visible viewport indices to node-space indices via structural plugins.\n * Falls back to 1:1 mapping (flat data) when no structural plugin responds.\n */\n private getViewportMapping(viewportStart: number, viewportEnd: number): ViewportMappingResponse {\n const query: ViewportMappingQuery = { viewportStart, viewportEnd };\n const results = this.grid?.query?.('datasource:viewport-mapping', query) as ViewportMappingResponse[] | undefined;\n\n // Structural plugin responded — use its mapping\n if (results?.[0]) return results[0];\n\n // No structural plugin → 1:1 mapping (flat data)\n return {\n startNode: viewportStart,\n endNode: viewportEnd,\n totalLoadedNodes: this.totalNodeCount,\n };\n }\n\n /**\n * Handle sort or filter model changes.\n * Purge cache and refetch current viewport with new enrichment params.\n */\n private onModelChange(): void {\n if (!this.dataSource) return;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.requestRender();\n // Eagerly fetch the current viewport with the new enrichment params.\n // Without this, the table stays blank until the user scrolls (no other\n // path triggers a fetch — processRows just rebuilds from cached blocks).\n this.loadRequiredBlocks();\n }\n\n /**\n * Apply server response metadata: resolve totalNodeCount and infinite scroll mode.\n * When `lastNode` is provided, it takes priority and finalizes the total.\n * When `totalNodeCount` is -1, switch to infinite scroll (growing array).\n * When a block returns fewer rows than blockSize, detect end-of-data.\n */\n private applyServerResult(result: GetRowsResult, blockNum: number, blockSize: number): void {\n if (result.lastNode !== undefined) {\n // Server declared the exact end\n this.totalNodeCount = result.lastNode + 1;\n this.infiniteScrollMode = false;\n } else if (result.totalNodeCount === -1) {\n this.infiniteScrollMode = true;\n } else {\n this.totalNodeCount = result.totalNodeCount;\n this.infiniteScrollMode = false;\n }\n\n // Auto-detect end of data: short block means server has no more rows\n if (this.infiniteScrollMode && result.rows.length < blockSize) {\n this.totalNodeCount = blockNum * blockSize + result.rows.length;\n this.infiniteScrollMode = false;\n }\n }\n\n /**\n * Estimate the row count for infinite scroll mode.\n * Returns loaded rows + one extra block of placeholders to trigger next fetch.\n */\n private getInfiniteScrollEstimate(blockSize: number): number {\n let maxLoadedEnd = 0;\n for (const [block, rows] of this.loadedBlocks) {\n const end = block * blockSize + rows.length;\n if (end > maxLoadedEnd) maxLoadedEnd = end;\n }\n return maxLoadedEnd + blockSize;\n }\n\n /**\n * Check current viewport and load any missing blocks.\n */\n private loadRequiredBlocks(): void {\n if (!this.dataSource) return;\n\n const gridRef = this.grid as unknown as GridHost;\n const blockSize = this.config.cacheBlockSize ?? 100;\n\n // Translate viewport to node space via structural plugins\n const viewport = this.getViewportMapping(gridRef._virtualization.start, gridRef._virtualization.end);\n\n // Expand the viewport by loadThreshold in both directions to prefetch\n // blocks the user is about to scroll into. The end is clamped to\n // totalNodeCount when known so we don't request blocks past the end of\n // data — but `totalNodeCount = 0` means \"not yet loaded\" (e.g. just after\n // purgeCache or before the first fetch resolves), in which case we leave\n // it unclamped so the initial block can be fetched.\n const threshold = Math.max(0, this.config.loadThreshold ?? 0);\n const expandedStart = Math.max(0, viewport.startNode - threshold);\n const knownTotal = this.totalNodeCount > 0 ? this.totalNodeCount : Infinity;\n const expandedEnd = Math.min(knownTotal, viewport.endNode + threshold);\n if (expandedEnd <= expandedStart) return;\n\n // Determine which blocks are needed for current viewport (in node space)\n const requiredBlocks = getRequiredBlocks(expandedStart, expandedEnd, blockSize);\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n // Load missing blocks\n for (const blockNum of requiredBlocks) {\n if (this.loadedBlocks.has(blockNum) || this.loadingBlocks.has(blockNum)) {\n continue;\n }\n\n // Check concurrent request limit\n if (this.loadingBlocks.size >= (this.config.maxConcurrentRequests ?? 2)) {\n debugDiagnostic(DATASOURCE_THROTTLED, 'Concurrent request limit reached, deferring block load', gridId);\n break;\n }\n\n this.loadingBlocks.add(blockNum);\n const controller = new AbortController();\n this.blockControllers.set(blockNum, controller);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(this.dataSource, blockNum, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.blockControllers.delete(blockNum);\n // Drop results from a request that was superseded after the await\n // resolved (data source ignored the abort signal). Without this guard\n // a stale block would land in the cache after a sort/filter change.\n if (controller.signal.aborted) {\n this.loadingBlocks.delete(blockNum);\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n this.loadedBlocks.set(blockNum, result.rows);\n // Capture pre-update length so we can detect whether processRows must\n // re-run to grow the managedNodes array (e.g. after onModelChange reset).\n const previousManagedLength = this.managedNodes.length;\n this.applyServerResult(result, blockNum, blockSize);\n this.loadingBlocks.delete(blockNum);\n\n // Update managed nodes in place for this block (avoids full processRows rebuild)\n const start = blockNum * blockSize;\n for (let i = 0; i < result.rows.length; i++) {\n if (start + i < this.managedNodes.length) {\n this.managedNodes[start + i] = result.rows[i];\n }\n }\n\n // Broadcast data event with claimed flag\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: start,\n endNode: start + result.rows.length,\n claimed: false,\n };\n this.broadcast('datasource:data', detail);\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n\n // If managedNodes still hasn't been sized for the (possibly newly known)\n // totalNodeCount — typically because onModelChange() reset it to 0 right\n // before this fetch — we MUST run processRows to grow the array. The\n // in-place writes above are no-ops in that case (length is 0).\n // Without this, sort/filter changes leave the grid permanently blank\n // until something else triggers a ROWS phase.\n const needsRowModelRebuild =\n previousManagedLength === 0 ||\n this.managedNodes.length < (Number.isFinite(this.totalNodeCount) ? this.totalNodeCount : 0);\n\n if (needsRowModelRebuild) {\n this.requestRender();\n } else {\n // Re-render visible rows without force geometry recalculation.\n // requestVirtualRefresh() skips spacer height writes that cause oscillation\n // with the scheduler's afterRender microtask. Node count hasn't changed —\n // only cached data replaced placeholders — so geometry is stable.\n this.requestVirtualRefresh();\n }\n\n // Re-check with fresh viewport: user may have scrolled further\n this.loadRequiredBlocks();\n })\n .catch((error: unknown) => {\n this.blockControllers.delete(blockNum);\n this.loadingBlocks.delete(blockNum);\n // A superseded request may surface as either an AbortError or as a\n // user-thrown error after the data source detected the abort —\n // suppress diagnostics in both cases. Real failures still surface.\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n });\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processRows(rows: readonly unknown[]): unknown[] {\n if (!this.dataSource) return [...rows];\n\n const blockSize = this.config.cacheBlockSize ?? 100;\n\n // Guard against invalid totalNodeCount (e.g. undefined from a malformed datasource response).\n // In infinite scroll mode, estimate the total from loaded data + one extra block.\n const nodeCount = this.infiniteScrollMode\n ? this.getInfiniteScrollEstimate(blockSize)\n : Number.isFinite(this.totalNodeCount) && this.totalNodeCount >= 0\n ? this.totalNodeCount\n : 0;\n\n // Grow array with stable placeholder objects (created once, reused across renders)\n while (this.managedNodes.length < nodeCount) {\n const i = this.managedNodes.length;\n this.managedNodes.push({ __loading: true, __index: i });\n }\n // Shrink if total decreased\n this.managedNodes.length = nodeCount;\n\n // Replace placeholders with cached data (stable refs for unchanged entries)\n for (let i = 0; i < nodeCount; i++) {\n const cached = getRowFromCache(i, blockSize, this.loadedBlocks);\n if (cached) {\n this.managedNodes[i] = cached;\n }\n }\n\n // Local-mode sort: when sortMode === 'local' the plugin owns ordering of\n // the loaded rows itself (core sort ran on the input but we discarded it\n // by returning managedNodes). Apply the current core sort state on top of\n // managedNodes so the user sees in-place sorting without a refetch.\n // Note: any plugin sort that runs after us (priority > -10, e.g. multi-sort)\n // will further re-sort our output, which is the intended chain.\n const host = this.grid as unknown as GridHost | undefined;\n if (this.config.sortMode === 'local' && host?._sortState) {\n const columns = (host._columns ?? []) as ColumnConfig[];\n // Honor user's gridConfig.sortHandler when provided — same resolution\n // as core's reapplyCoreSort/applySort. processRows is synchronous, so\n // async handlers cannot be awaited here: keep the current managedNodes\n // order for this pass and swallow any rejection so it doesn't surface\n // as an unhandled promise rejection. The next core sort cycle (or the\n // next block load) will re-invoke this path with up-to-date state.\n const handler = host.effectiveConfig?.sortHandler ?? builtInSort;\n const result = handler(this.managedNodes, host._sortState, columns);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n void (result as Promise<unknown[]>).catch(() => undefined);\n return this.managedNodes;\n }\n return result as unknown[];\n }\n\n return this.managedNodes;\n }\n\n /** @internal */\n override onScroll(_event: ScrollEvent): void {\n if (!this.dataSource) return;\n\n // Immediate check for blocks\n this.loadRequiredBlocks();\n\n // Debounce: when scrolling stops, do a final check with fresh viewport\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n }\n this.scrollDebounceTimer = setTimeout(() => {\n this.loadRequiredBlocks();\n }, SCROLL_DEBOUNCE_MS);\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n switch (query.type) {\n case 'datasource:is-active':\n return this.dataSource != null;\n\n case 'datasource:fetch-children': {\n const { context } = query.context as FetchChildrenQuery;\n this.fetchChildren(context);\n return undefined;\n }\n }\n return undefined;\n }\n // #endregion\n\n // #region Child Data Fetching\n\n /**\n * Fetch child rows via the datasource and broadcast the result.\n */\n private fetchChildren(context: { source: string; [key: string]: unknown }): void {\n if (!this.dataSource) return;\n\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n if (!this.dataSource.getChildRows) {\n warnDiagnostic(\n DATASOURCE_NO_CHILD_HANDLER,\n `Plugin \"${context.source}\" requested child rows but getChildRows() is not implemented on the dataSource`,\n gridId,\n );\n return;\n }\n\n const enrichment = this.getEnrichmentParams();\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true, context });\n\n this.dataSource\n .getChildRows({ context, sortModel: enrichment.sortModel, filterModel: enrichment.filterModel })\n .then((result) => {\n const detail: DataSourceChildrenDetail = {\n rows: result.rows,\n context,\n claimed: false,\n };\n this.broadcast('datasource:children', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n })\n .catch((error: unknown) => {\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_CHILD_FETCH_ERROR, `getChildRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err, context });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Set the data source for server-side loading.\n * @param dataSource - Data source implementing the getRows method (and optionally getChildRows)\n */\n setDataSource(dataSource: ServerSideDataSource): void {\n this.abortAllBlocks();\n this.dataSource = dataSource;\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n\n // Load first block with enrichment params\n const blockSize = this.config.cacheBlockSize ?? 100;\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n const controller = new AbortController();\n this.blockControllers.set(0, controller);\n this.loadingBlocks.add(0);\n\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(dataSource, 0, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.blockControllers.delete(0);\n this.loadingBlocks.delete(0);\n if (controller.signal.aborted) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n return;\n }\n this.loadedBlocks.set(0, result.rows);\n this.applyServerResult(result, 0, blockSize);\n\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: 0,\n endNode: result.rows.length,\n claimed: false,\n };\n this.broadcast('datasource:data', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n this.requestRender();\n\n // When loadThreshold is configured, re-check the viewport so the\n // prefetch can pull in additional blocks immediately rather than\n // waiting for the user's first scroll. Gated on the threshold to\n // preserve the historical \"first fetch loads block 0 only\" behavior.\n if ((this.config.loadThreshold ?? 0) > 0) {\n this.loadRequiredBlocks();\n }\n })\n .catch((error: unknown) => {\n this.blockControllers.delete(0);\n this.loadingBlocks.delete(0);\n if (controller.signal.aborted) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n });\n }\n\n /**\n * Refresh all data from the server.\n * Purges cache and refetches from block 0.\n */\n refresh(): void {\n if (!this.dataSource) return;\n const ds = this.dataSource;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n // Re-trigger load via setDataSource which handles enrichment and broadcasting\n this.setDataSource(ds);\n }\n\n /**\n * Clear all cached data without refreshing.\n */\n purgeCache(): void {\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.managedNodes = [];\n }\n\n /**\n * Get the total node count from the server.\n */\n getTotalNodeCount(): number {\n return this.totalNodeCount;\n }\n\n /**\n * @deprecated Use {@link getTotalNodeCount} instead. Will be removed in a future version.\n */\n getTotalRowCount(): number {\n return this.totalNodeCount;\n }\n\n /**\n * Check if a specific node is loaded in the cache.\n * @param nodeIndex - Node index to check\n */\n isNodeLoaded(nodeIndex: number): boolean {\n const blockSize = this.config.cacheBlockSize ?? 100;\n const blockNum = getBlockNumber(nodeIndex, blockSize);\n return this.loadedBlocks.has(blockNum);\n }\n\n /**\n * @deprecated Use {@link isNodeLoaded} instead. Will be removed in a future version.\n */\n isRowLoaded(rowIndex: number): boolean {\n return this.isNodeLoaded(rowIndex);\n }\n\n /**\n * Get the number of loaded cache blocks.\n */\n getLoadedBlockCount(): number {\n return this.loadedBlocks.size;\n }\n // #endregion\n}\n"],"names":["getBlockNumber","nodeIndex","blockSize","Math","floor","makeAbortError","DOMException","loadBlock","dataSource","blockNumber","params","signal","range","start","end","getBlockRange","source","aborted","Promise","reject","value","subscribe","then","resolve","onAbort","addEventListener","once","v","removeEventListener","e","settled","subscription","next","unsubscribe","error","err","complete","Error","toResultPromise","getRows","startNode","endNode","sortModel","filterModel","getRowFromCache","loadedBlocks","block","get","ServerSidePlugin","BaseGridPlugin","static","modifiesRowStructure","hookPriority","processRows","incompatibleWith","name","reason","events","type","description","queries","defaultConfig","pageSize","cacheBlockSize","maxConcurrentRequests","totalNodeCount","infiniteScrollMode","Map","loadingBlocks","Set","blockControllers","lastRequestId","scrollDebounceTimer","managedNodes","attach","grid","super","this","on","config","sortMode","requestRender","onModelChange","filterMode","setDataSource","detach","clear","abortAllBlocks","clearTimeout","controller","values","abort","getEnrichmentParams","sortLocal","filterLocal","sortResults","query","filterResults","host","_sortState","field","direction","getViewportMapping","viewportStart","viewportEnd","results","totalLoadedNodes","loadRequiredBlocks","applyServerResult","result","blockNum","lastNode","rows","length","getInfiniteScrollEstimate","maxLoadedEnd","gridRef","viewport","_virtualization","threshold","max","loadThreshold","expandedStart","knownTotal","Infinity","expandedEnd","min","requiredBlocks","startBlock","endBlock","blocks","i","push","getRequiredBlocks","enrichment","gridId","getAttribute","has","size","debugDiagnostic","DATASOURCE_THROTTLED","add","AbortController","set","broadcast","loading","delete","previousManagedLength","detail","claimed","Number","isFinite","requestVirtualRefresh","catch","String","errorDiagnostic","DATASOURCE_FETCH_ERROR","message","nodeCount","__loading","__index","cached","columns","_columns","effectiveConfig","sortHandler","builtInSort","onScroll","_event","setTimeout","handleQuery","context","fetchChildren","getChildRows","warnDiagnostic","DATASOURCE_NO_CHILD_HANDLER","DATASOURCE_CHILD_FETCH_ERROR","refresh","ds","purgeCache","getTotalNodeCount","getTotalRowCount","isNodeLoaded","isRowLoaded","rowIndex","getLoadedBlockCount"],"mappings":"8fAEO,SAASA,EAAeC,EAAmBC,GAChD,OAAOC,KAAKC,MAAMH,EAAYC,EAChC,CA8BA,SAASG,IACP,OAAO,IAAIC,aAAa,UAAW,aACrC,CAmEO,SAASC,EACdC,EACAC,EACAP,EACAQ,EACAC,GAEA,MAAMC,EAxGD,SAAuBH,EAAqBP,GACjD,MAAO,CACLW,MAAOJ,EAAcP,EACrBY,KAAML,EAAc,GAAKP,EAE7B,CAmGgBa,CAAcN,EAAaP,GASzC,OA1EK,SACLc,EACAL,GAEA,OAAIA,EAAOM,QACFC,QAAQC,OAAOd,KAxBL,iBAFMe,EA4BFJ,IAzBX,OAAVI,GACwD,mBAAhDA,EAAkCC,WAEI,mBAAtCD,EAA6BE,KAyB9B,IAAIJ,QAAW,CAACK,EAASJ,KAC9B,MAAMK,EAAU,IAAML,EAAOd,KAC7BM,EAAOc,iBAAiB,QAASD,EAAS,CAAEE,MAAM,IAClDR,QAAQK,QAAQP,GAAQM,KACrBK,IACChB,EAAOiB,oBAAoB,QAASJ,GACpCD,EAAQI,IAETE,IACClB,EAAOiB,oBAAoB,QAASJ,GACpCL,EAAOU,OAOR,IAAIX,QAAW,CAACK,EAASJ,KAC9B,IAAIW,GAAU,EACd,MAAMC,EAAef,EAAOK,UAAU,CACpCW,KAAOZ,IACDU,IACJA,GAAU,EACVP,EAAQH,GACRW,EAAaE,gBAEfC,MAAQC,IACFL,IACJA,GAAU,EACVX,EAAOgB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,EAAW9G,EAAeC,EADd4E,KAAKE,OAAOhB,gBAAkB,KAEhD,OAAOc,KAAKhC,aAAa4F,IAAI3B,EAC/B,CAKA,WAAAyE,CAAYC,GACV,OAAO3G,KAAKyG,aAAaE,EAC3B,CAKA,mBAAAC,GACE,OAAO5G,KAAKhC,aAAa6F,IAC3B"}
|
|
1
|
+
{"version":3,"file":"server-side.umd.js","sources":["../../../../../libs/grid/src/lib/plugins/server-side/datasource.ts","../../../../../libs/grid/src/lib/plugins/server-side/ServerSidePlugin.ts"],"sourcesContent":["import type { GetRowsParams, GetRowsResult, ServerSideDataSource, Subscribable } from './datasource-types';\n\nexport function getBlockNumber(nodeIndex: number, blockSize: number): number {\n return Math.floor(nodeIndex / blockSize);\n}\n\nexport function getBlockRange(blockNumber: number, blockSize: number): { start: number; end: number } {\n return {\n start: blockNumber * blockSize,\n end: (blockNumber + 1) * blockSize,\n };\n}\n\nexport function getRequiredBlocks(startNode: number, endNode: number, blockSize: number): number[] {\n const startBlock = getBlockNumber(startNode, blockSize);\n const endBlock = getBlockNumber(endNode - 1, blockSize);\n\n const blocks: number[] = [];\n for (let i = startBlock; i <= endBlock; i++) {\n blocks.push(i);\n }\n return blocks;\n}\n\nfunction isSubscribable<T>(value: unknown): value is Subscribable<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { subscribe?: unknown }).subscribe === 'function' &&\n // Promises don't have `.subscribe`, but defensively rule them out.\n typeof (value as { then?: unknown }).then !== 'function'\n );\n}\n\nfunction makeAbortError(): DOMException {\n return new DOMException('Aborted', 'AbortError');\n}\n\n/**\n * Bridge a `Promise | Subscribable` getRows return value into a single\n * `Promise<GetRowsResult>`. For Subscribables, abort triggers `unsubscribe()`\n * so the underlying request (e.g. Angular `HttpClient` XHR) is cancelled.\n * Promise sources should pass `signal` to `fetch` themselves — we still reject\n * on abort either way so the plugin's abort path is consistent.\n */\nexport function toResultPromise<T>(source: Promise<T> | Subscribable<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(makeAbortError());\n }\n if (!isSubscribable<T>(source)) {\n // Promise path: reject on abort so the plugin's catch sees a consistent\n // signal even if the underlying fetch ignored params.signal.\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(makeAbortError());\n signal.addEventListener('abort', onAbort, { once: true });\n Promise.resolve(source).then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n }\n // Subscribable path: subscribe once, settle on next/error/complete, and\n // unsubscribe on abort — that's what cancels HttpClient's XHR.\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n const subscription = source.subscribe({\n next: (value) => {\n if (settled) return;\n settled = true;\n resolve(value);\n subscription.unsubscribe();\n },\n error: (err) => {\n if (settled) return;\n settled = true;\n reject(err);\n },\n complete: () => {\n if (settled) return;\n settled = true;\n reject(new Error('getRows observable completed without emitting a value'));\n },\n });\n if (settled) return; // synchronous emit\n const onAbort = () => {\n if (settled) return;\n settled = true;\n subscription.unsubscribe();\n reject(makeAbortError());\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport function loadBlock(\n dataSource: ServerSideDataSource,\n blockNumber: number,\n blockSize: number,\n params: Partial<GetRowsParams>,\n signal: AbortSignal,\n): Promise<GetRowsResult> {\n const range = getBlockRange(blockNumber, blockSize);\n\n const result = dataSource.getRows({\n startNode: range.start,\n endNode: range.end,\n pageSize: range.end - range.start,\n sortModel: params.sortModel,\n filterModel: params.filterModel,\n signal,\n });\n return toResultPromise(result, signal);\n}\n\nexport function getRowFromCache(\n nodeIndex: number,\n blockSize: number,\n loadedBlocks: Map<number, unknown[]>,\n): unknown | undefined {\n const blockNumber = getBlockNumber(nodeIndex, blockSize);\n const block = loadedBlocks.get(blockNumber);\n if (!block) return undefined;\n\n const indexInBlock = nodeIndex % blockSize;\n return block[indexInBlock];\n}\n\nexport function isBlockLoaded(blockNumber: number, loadedBlocks: Map<number, unknown[]>): boolean {\n return loadedBlocks.has(blockNumber);\n}\n\nexport function isBlockLoading(blockNumber: number, loadingBlocks: Set<number>): boolean {\n return loadingBlocks.has(blockNumber);\n}\n","/**\n * Server-Side Data Plugin (Class-based)\n *\n * Central data orchestrator for the grid. Owns fetch + cache + row-model management.\n * Structural plugins (Tree, GroupingRows) claim data via events; core grid uses it\n * as flat rows when unclaimed.\n */\n\nimport {\n DATASOURCE_CHILD_FETCH_ERROR,\n DATASOURCE_FETCH_ERROR,\n DATASOURCE_NO_CHILD_HANDLER,\n DATASOURCE_THROTTLED,\n debugDiagnostic,\n errorDiagnostic,\n warnDiagnostic,\n} from '../../core/internal/diagnostics';\nimport { builtInSort } from '../../core/internal/sorting';\nimport { BaseGridPlugin, ScrollEvent, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig, GridHost } from '../../core/types';\nimport { getBlockNumber, getRequiredBlocks, getRowFromCache, loadBlock } from './datasource';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n DataSourceLoadingDetail,\n FetchChildrenQuery,\n GetRowsParams,\n GetRowsResult,\n ServerSideDataSource,\n ViewportMappingQuery,\n ViewportMappingResponse,\n} from './datasource-types';\nimport type { ServerSideConfig } from './types';\n\n/** Scroll debounce delay in ms */\nconst SCROLL_DEBOUNCE_MS = 100;\n\n/**\n * Server-Side Data Plugin for tbw-grid\n *\n * Central data orchestrator for the grid. Manages fetch, cache, and row-model for\n * server-side data loading. Structural plugins (Tree, GroupingRows) can claim data\n * via events; the core grid uses it as flat rows when unclaimed.\n *\n * ## Installation\n *\n * ```ts\n * import { ServerSidePlugin } from '@toolbox-web/grid/plugins/server-side';\n * ```\n *\n * ## DataSource Interface\n *\n * ```ts\n * interface ServerSideDataSource {\n * getRows(params: GetRowsParams): Promise<GetRowsResult>;\n * getChildRows?(params: GetChildRowsParams): Promise<GetChildRowsResult>;\n * }\n * ```\n *\n * @example Basic Server-Side Loading\n * ```ts\n * import '@toolbox-web/grid';\n * import '@toolbox-web/grid/features/server-side';\n *\n * grid.gridConfig = {\n * columns: [...],\n * features: {\n * serverSide: {\n * pageSize: 50,\n * dataSource: {\n * async getRows(params) {\n * const response = await fetch(\n * `/api/data?start=${params.startNode}&end=${params.endNode}`\n * );\n * const data = await response.json();\n * return { rows: data.rows, totalNodeCount: data.total };\n * },\n * },\n * },\n * },\n * };\n * ```\n *\n * @see {@link ServerSideConfig} for configuration options\n * @see {@link ServerSideDataSource} for data source interface\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class ServerSidePlugin extends BaseGridPlugin<ServerSideConfig> {\n /**\n * Plugin manifest declaring capabilities, hooks, events, and queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n hookPriority: {\n processRows: -10, // Run before structural plugins (Tree, GroupingRows)\n },\n incompatibleWith: [\n {\n name: 'pivot',\n reason:\n 'PivotPlugin requires the full dataset to compute aggregations. ' +\n 'ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side.',\n },\n ],\n events: [\n { type: 'datasource:data', description: 'Root data page/block loaded' },\n { type: 'datasource:children', description: 'Child data loaded for a parent context' },\n { type: 'datasource:loading', description: 'Loading state changed' },\n { type: 'datasource:error', description: 'Fetch operation failed' },\n ],\n queries: [\n { type: 'datasource:fetch-children', description: 'Request child rows for a parent context' },\n { type: 'datasource:is-active', description: 'Check if ServerSide plugin has an active data source' },\n ],\n };\n\n /** @internal */\n readonly name = 'serverSide';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ServerSideConfig> {\n return {\n maxConcurrentRequests: 2,\n };\n }\n\n // #region Internal State\n private dataSource: ServerSideDataSource | null = null;\n private totalNodeCount = 0;\n private infiniteScrollMode = false;\n private loadedBlocks = new Map<number, unknown[]>();\n private loadingBlocks = new Set<number>();\n /**\n * Per-block AbortControllers for in-flight requests. Aborted when a block\n * is superseded (sort/filter change, refresh, purgeCache, detach) so data\n * sources that honor `params.signal` (e.g. `fetch`, RxJS via `fromObservable`)\n * can cancel the underlying network call.\n */\n private blockControllers = new Map<number, AbortController>();\n private lastRequestId = 0;\n private scrollDebounceTimer?: ReturnType<typeof setTimeout>;\n /** Persistent node array with stable placeholder references to avoid unnecessary DOM rebuilds. */\n private managedNodes: unknown[] = [];\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 // Invalidate cache and refetch on sort/filter changes — gated by sortMode/filterMode.\n // 'local' (opt-in): keep cache; sort/filter the loaded rows in place via a re-render.\n // See getEnrichmentParams() — local-mode state is also omitted from block fetch params\n // so scroll-triggered loadRequiredBlocks() doesn't leak local state to the backend.\n this.on('sort-change', () => {\n if (this.config.sortMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n this.on('filter-change', () => {\n if (this.config.filterMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n\n // Auto-initialize from config when dataSource is provided declaratively\n if (this.config.dataSource) {\n this.setDataSource(this.config.dataSource);\n }\n }\n\n /** @internal */\n override detach(): void {\n this.dataSource = null;\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.abortAllBlocks();\n this.managedNodes = [];\n this.lastRequestId = 0;\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n this.scrollDebounceTimer = undefined;\n }\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Abort all in-flight block requests. Called when the plugin tears down,\n * the data source is replaced, the cache is purged, or the sort/filter\n * model changes (the previously loaded block coordinates no longer apply).\n */\n private abortAllBlocks(): void {\n for (const controller of this.blockControllers.values()) {\n controller.abort();\n }\n this.blockControllers.clear();\n }\n\n /**\n * Build enrichment params by querying sort/filter models from loaded plugins.\n *\n * When `sortMode === 'local'` the `sortModel` is omitted so scroll-triggered\n * block fetches don't ask the backend for an ordering it isn't applying.\n * Same for `filterMode === 'local'` and `filterModel`.\n */\n private getEnrichmentParams(): Partial<GetRowsParams> {\n const sortLocal = this.config.sortMode === 'local';\n const filterLocal = this.config.filterMode === 'local';\n const sortResults = sortLocal\n ? undefined\n : (this.grid?.query?.('sort:get-model', null) as\n | Array<{ field: string; direction: 'asc' | 'desc' }>[]\n | undefined);\n const filterResults = filterLocal\n ? undefined\n : (this.grid?.query?.('filter:get-model', null) as Record<string, unknown>[] | undefined);\n\n // Fallback to core single-column sort state when no plugin answers the\n // 'sort:get-model' query (e.g. MultiSortPlugin not loaded). Translate the\n // numeric direction (1/-1) to the public 'asc'/'desc' string form.\n let sortModel = sortResults?.[0];\n const host = this.grid as unknown as GridHost | undefined;\n if (!sortLocal && !sortModel && host?._sortState) {\n const { field, direction } = host._sortState;\n sortModel = [{ field, direction: direction === 1 ? 'asc' : 'desc' }];\n }\n\n return {\n sortModel,\n filterModel: filterResults?.[0],\n };\n }\n\n /**\n * Translate visible viewport indices to node-space indices via structural plugins.\n * Falls back to 1:1 mapping (flat data) when no structural plugin responds.\n */\n private getViewportMapping(viewportStart: number, viewportEnd: number): ViewportMappingResponse {\n const query: ViewportMappingQuery = { viewportStart, viewportEnd };\n const results = this.grid?.query?.('datasource:viewport-mapping', query) as ViewportMappingResponse[] | undefined;\n\n // Structural plugin responded — use its mapping\n if (results?.[0]) return results[0];\n\n // No structural plugin → 1:1 mapping (flat data)\n return {\n startNode: viewportStart,\n endNode: viewportEnd,\n totalLoadedNodes: this.totalNodeCount,\n };\n }\n\n /**\n * Handle sort or filter model changes.\n * Purge cache and refetch current viewport with new enrichment params.\n */\n private onModelChange(): void {\n if (!this.dataSource) return;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.requestRender();\n // Eagerly fetch the current viewport with the new enrichment params.\n // Without this, the table stays blank until the user scrolls (no other\n // path triggers a fetch — processRows just rebuilds from cached blocks).\n this.loadRequiredBlocks();\n }\n\n /**\n * Apply server response metadata: resolve totalNodeCount and infinite scroll mode.\n * When `lastNode` is provided, it takes priority and finalizes the total.\n * When `totalNodeCount` is -1, switch to infinite scroll (growing array).\n * When a block returns fewer rows than blockSize, detect end-of-data.\n */\n private applyServerResult(result: GetRowsResult, blockNum: number, blockSize: number): void {\n if (result.lastNode !== undefined) {\n // Server declared the exact end\n this.totalNodeCount = result.lastNode + 1;\n this.infiniteScrollMode = false;\n } else if (result.totalNodeCount === -1) {\n this.infiniteScrollMode = true;\n } else {\n this.totalNodeCount = result.totalNodeCount;\n this.infiniteScrollMode = false;\n }\n\n // Auto-detect end of data: short block means server has no more rows\n if (this.infiniteScrollMode && result.rows.length < blockSize) {\n this.totalNodeCount = blockNum * blockSize + result.rows.length;\n this.infiniteScrollMode = false;\n }\n }\n\n /**\n * Estimate the row count for infinite scroll mode.\n * Returns loaded rows + one extra block of placeholders to trigger next fetch.\n */\n private getInfiniteScrollEstimate(blockSize: number): number {\n let maxLoadedEnd = 0;\n for (const [block, rows] of this.loadedBlocks) {\n const end = block * blockSize + rows.length;\n if (end > maxLoadedEnd) maxLoadedEnd = end;\n }\n return maxLoadedEnd + blockSize;\n }\n\n /**\n * Check current viewport and load any missing blocks.\n */\n private loadRequiredBlocks(): void {\n if (!this.dataSource) return;\n\n const gridRef = this.grid as unknown as GridHost;\n const blockSize = this.config.pageSize ?? this.config.cacheBlockSize ?? 100;\n\n // Translate viewport to node space via structural plugins\n const viewport = this.getViewportMapping(gridRef._virtualization.start, gridRef._virtualization.end);\n\n // Expand the viewport by loadThreshold in both directions to prefetch\n // blocks the user is about to scroll into. The end is clamped to\n // totalNodeCount when known so we don't request blocks past the end of\n // data — but `totalNodeCount = 0` means \"not yet loaded\" (e.g. just after\n // purgeCache or before the first fetch resolves), in which case we leave\n // it unclamped so the initial block can be fetched.\n const threshold = Math.max(0, this.config.loadThreshold ?? 0);\n const expandedStart = Math.max(0, viewport.startNode - threshold);\n const knownTotal = this.totalNodeCount > 0 ? this.totalNodeCount : Infinity;\n const expandedEnd = Math.min(knownTotal, viewport.endNode + threshold);\n if (expandedEnd <= expandedStart) return;\n\n // Determine which blocks are needed for current viewport (in node space)\n const requiredBlocks = getRequiredBlocks(expandedStart, expandedEnd, blockSize);\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n // Load missing blocks\n for (const blockNum of requiredBlocks) {\n if (this.loadedBlocks.has(blockNum) || this.loadingBlocks.has(blockNum)) {\n continue;\n }\n\n // Check concurrent request limit\n if (this.loadingBlocks.size >= (this.config.maxConcurrentRequests ?? 2)) {\n debugDiagnostic(DATASOURCE_THROTTLED, 'Concurrent request limit reached, deferring block load', gridId);\n break;\n }\n\n this.loadingBlocks.add(blockNum);\n const controller = new AbortController();\n this.blockControllers.set(blockNum, controller);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(this.dataSource, blockNum, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.blockControllers.delete(blockNum);\n // Drop results from a request that was superseded after the await\n // resolved (data source ignored the abort signal). Without this guard\n // a stale block would land in the cache after a sort/filter change.\n if (controller.signal.aborted) {\n this.loadingBlocks.delete(blockNum);\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n this.loadedBlocks.set(blockNum, result.rows);\n // Capture pre-update length so we can detect whether processRows must\n // re-run to grow the managedNodes array (e.g. after onModelChange reset).\n const previousManagedLength = this.managedNodes.length;\n this.applyServerResult(result, blockNum, blockSize);\n this.loadingBlocks.delete(blockNum);\n\n // Update managed nodes in place for this block (avoids full processRows rebuild)\n const start = blockNum * blockSize;\n for (let i = 0; i < result.rows.length; i++) {\n if (start + i < this.managedNodes.length) {\n this.managedNodes[start + i] = result.rows[i];\n }\n }\n\n // Broadcast data event with claimed flag\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: start,\n endNode: start + result.rows.length,\n claimed: false,\n };\n this.broadcast('datasource:data', detail);\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n\n // If managedNodes still hasn't been sized for the (possibly newly known)\n // totalNodeCount — typically because onModelChange() reset it to 0 right\n // before this fetch — we MUST run processRows to grow the array. The\n // in-place writes above are no-ops in that case (length is 0).\n // Without this, sort/filter changes leave the grid permanently blank\n // until something else triggers a ROWS phase.\n const needsRowModelRebuild =\n previousManagedLength === 0 ||\n this.managedNodes.length < (Number.isFinite(this.totalNodeCount) ? this.totalNodeCount : 0);\n\n if (needsRowModelRebuild) {\n this.requestRender();\n } else {\n // Re-render visible rows without force geometry recalculation.\n // requestVirtualRefresh() skips spacer height writes that cause oscillation\n // with the scheduler's afterRender microtask. Node count hasn't changed —\n // only cached data replaced placeholders — so geometry is stable.\n this.requestVirtualRefresh();\n }\n\n // Re-check with fresh viewport: user may have scrolled further\n this.loadRequiredBlocks();\n })\n .catch((error: unknown) => {\n this.blockControllers.delete(blockNum);\n this.loadingBlocks.delete(blockNum);\n // A superseded request may surface as either an AbortError or as a\n // user-thrown error after the data source detected the abort —\n // suppress diagnostics in both cases. Real failures still surface.\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n });\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processRows(rows: readonly unknown[]): unknown[] {\n if (!this.dataSource) return [...rows];\n\n const blockSize = this.config.pageSize ?? this.config.cacheBlockSize ?? 100;\n\n // Guard against invalid totalNodeCount (e.g. undefined from a malformed datasource response).\n // In infinite scroll mode, estimate the total from loaded data + one extra block.\n const nodeCount = this.infiniteScrollMode\n ? this.getInfiniteScrollEstimate(blockSize)\n : Number.isFinite(this.totalNodeCount) && this.totalNodeCount >= 0\n ? this.totalNodeCount\n : 0;\n\n // Grow array with stable placeholder objects (created once, reused across renders)\n while (this.managedNodes.length < nodeCount) {\n const i = this.managedNodes.length;\n this.managedNodes.push({ __loading: true, __index: i });\n }\n // Shrink if total decreased\n this.managedNodes.length = nodeCount;\n\n // Replace placeholders with cached data (stable refs for unchanged entries)\n for (let i = 0; i < nodeCount; i++) {\n const cached = getRowFromCache(i, blockSize, this.loadedBlocks);\n if (cached) {\n this.managedNodes[i] = cached;\n }\n }\n\n // Local-mode sort: when sortMode === 'local' the plugin owns ordering of\n // the loaded rows itself (core sort ran on the input but we discarded it\n // by returning managedNodes). Apply the current core sort state on top of\n // managedNodes so the user sees in-place sorting without a refetch.\n // Note: any plugin sort that runs after us (priority > -10, e.g. multi-sort)\n // will further re-sort our output, which is the intended chain.\n const host = this.grid as unknown as GridHost | undefined;\n if (this.config.sortMode === 'local' && host?._sortState) {\n const columns = (host._columns ?? []) as ColumnConfig[];\n // Honor user's gridConfig.sortHandler when provided — same resolution\n // as core's reapplyCoreSort/applySort. processRows is synchronous, so\n // async handlers cannot be awaited here: keep the current managedNodes\n // order for this pass and swallow any rejection so it doesn't surface\n // as an unhandled promise rejection. The next core sort cycle (or the\n // next block load) will re-invoke this path with up-to-date state.\n const handler = host.effectiveConfig?.sortHandler ?? builtInSort;\n const result = handler(this.managedNodes, host._sortState, columns);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n void (result as Promise<unknown[]>).catch(() => undefined);\n return this.managedNodes;\n }\n return result as unknown[];\n }\n\n return this.managedNodes;\n }\n\n /** @internal */\n override onScroll(_event: ScrollEvent): void {\n if (!this.dataSource) return;\n\n // Immediate check for blocks\n this.loadRequiredBlocks();\n\n // Debounce: when scrolling stops, do a final check with fresh viewport\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n }\n this.scrollDebounceTimer = setTimeout(() => {\n this.loadRequiredBlocks();\n }, SCROLL_DEBOUNCE_MS);\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n switch (query.type) {\n case 'datasource:is-active':\n return this.dataSource != null;\n\n case 'datasource:fetch-children': {\n const { context } = query.context as FetchChildrenQuery;\n this.fetchChildren(context);\n return undefined;\n }\n }\n return undefined;\n }\n // #endregion\n\n // #region Child Data Fetching\n\n /**\n * Fetch child rows via the datasource and broadcast the result.\n */\n private fetchChildren(context: { source: string; [key: string]: unknown }): void {\n if (!this.dataSource) return;\n\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n if (!this.dataSource.getChildRows) {\n warnDiagnostic(\n DATASOURCE_NO_CHILD_HANDLER,\n `Plugin \"${context.source}\" requested child rows but getChildRows() is not implemented on the dataSource`,\n gridId,\n );\n return;\n }\n\n const enrichment = this.getEnrichmentParams();\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true, context });\n\n this.dataSource\n .getChildRows({ context, sortModel: enrichment.sortModel, filterModel: enrichment.filterModel })\n .then((result) => {\n const detail: DataSourceChildrenDetail = {\n rows: result.rows,\n context,\n claimed: false,\n };\n this.broadcast('datasource:children', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n })\n .catch((error: unknown) => {\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_CHILD_FETCH_ERROR, `getChildRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err, context });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Set the data source for server-side loading.\n * @param dataSource - Data source implementing the getRows method (and optionally getChildRows)\n */\n setDataSource(dataSource: ServerSideDataSource): void {\n this.abortAllBlocks();\n this.dataSource = dataSource;\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n\n // Load first block with enrichment params\n const blockSize = this.config.pageSize ?? this.config.cacheBlockSize ?? 100;\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n const controller = new AbortController();\n this.blockControllers.set(0, controller);\n this.loadingBlocks.add(0);\n\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(dataSource, 0, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.blockControllers.delete(0);\n this.loadingBlocks.delete(0);\n if (controller.signal.aborted) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n return;\n }\n this.loadedBlocks.set(0, result.rows);\n this.applyServerResult(result, 0, blockSize);\n\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: 0,\n endNode: result.rows.length,\n claimed: false,\n };\n this.broadcast('datasource:data', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n this.requestRender();\n\n // When loadThreshold is configured, re-check the viewport so the\n // prefetch can pull in additional blocks immediately rather than\n // waiting for the user's first scroll. Gated on the threshold to\n // preserve the historical \"first fetch loads block 0 only\" behavior.\n if ((this.config.loadThreshold ?? 0) > 0) {\n this.loadRequiredBlocks();\n }\n })\n .catch((error: unknown) => {\n this.blockControllers.delete(0);\n this.loadingBlocks.delete(0);\n if (controller.signal.aborted) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n });\n }\n\n /**\n * Refresh all data from the server.\n * Purges cache and refetches from block 0.\n */\n refresh(): void {\n if (!this.dataSource) return;\n const ds = this.dataSource;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n // Re-trigger load via setDataSource which handles enrichment and broadcasting\n this.setDataSource(ds);\n }\n\n /**\n * Clear all cached data without refreshing.\n */\n purgeCache(): void {\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.managedNodes = [];\n }\n\n /**\n * Get the total node count from the server.\n */\n getTotalNodeCount(): number {\n return this.totalNodeCount;\n }\n\n /**\n * @deprecated Use {@link getTotalNodeCount} instead. Will be removed in a future version.\n */\n getTotalRowCount(): number {\n return this.totalNodeCount;\n }\n\n /**\n * Check if a specific node is loaded in the cache.\n * @param nodeIndex - Node index to check\n */\n isNodeLoaded(nodeIndex: number): boolean {\n const blockSize = this.config.pageSize ?? this.config.cacheBlockSize ?? 100;\n const blockNum = getBlockNumber(nodeIndex, blockSize);\n return this.loadedBlocks.has(blockNum);\n }\n\n /**\n * @deprecated Use {@link isNodeLoaded} instead. Will be removed in a future version.\n */\n isRowLoaded(rowIndex: number): boolean {\n return this.isNodeLoaded(rowIndex);\n }\n\n /**\n * Get the number of loaded cache blocks.\n */\n getLoadedBlockCount(): number {\n return this.loadedBlocks.size;\n }\n // #endregion\n}\n"],"names":["getBlockNumber","nodeIndex","blockSize","Math","floor","makeAbortError","DOMException","loadBlock","dataSource","blockNumber","params","signal","range","start","end","getBlockRange","source","aborted","Promise","reject","value","subscribe","then","resolve","onAbort","addEventListener","once","v","removeEventListener","e","settled","subscription","next","unsubscribe","error","err","complete","Error","toResultPromise","getRows","startNode","endNode","pageSize","sortModel","filterModel","getRowFromCache","loadedBlocks","block","get","ServerSidePlugin","BaseGridPlugin","static","modifiesRowStructure","hookPriority","processRows","incompatibleWith","name","reason","events","type","description","queries","defaultConfig","maxConcurrentRequests","totalNodeCount","infiniteScrollMode","Map","loadingBlocks","Set","blockControllers","lastRequestId","scrollDebounceTimer","managedNodes","attach","grid","super","this","on","config","sortMode","requestRender","onModelChange","filterMode","setDataSource","detach","clear","abortAllBlocks","clearTimeout","controller","values","abort","getEnrichmentParams","sortLocal","filterLocal","sortResults","query","filterResults","host","_sortState","field","direction","getViewportMapping","viewportStart","viewportEnd","results","totalLoadedNodes","loadRequiredBlocks","applyServerResult","result","blockNum","lastNode","rows","length","getInfiniteScrollEstimate","maxLoadedEnd","gridRef","cacheBlockSize","viewport","_virtualization","threshold","max","loadThreshold","expandedStart","knownTotal","Infinity","expandedEnd","min","requiredBlocks","startBlock","endBlock","blocks","i","push","getRequiredBlocks","enrichment","gridId","getAttribute","has","size","debugDiagnostic","DATASOURCE_THROTTLED","add","AbortController","set","broadcast","loading","delete","previousManagedLength","detail","claimed","Number","isFinite","requestVirtualRefresh","catch","String","errorDiagnostic","DATASOURCE_FETCH_ERROR","message","nodeCount","__loading","__index","cached","columns","_columns","effectiveConfig","sortHandler","builtInSort","onScroll","_event","setTimeout","handleQuery","context","fetchChildren","getChildRows","warnDiagnostic","DATASOURCE_NO_CHILD_HANDLER","DATASOURCE_CHILD_FETCH_ERROR","refresh","ds","purgeCache","getTotalNodeCount","getTotalRowCount","isNodeLoaded","isRowLoaded","rowIndex","getLoadedBlockCount"],"mappings":"8fAEO,SAASA,EAAeC,EAAmBC,GAChD,OAAOC,KAAKC,MAAMH,EAAYC,EAChC,CA8BA,SAASG,IACP,OAAO,IAAIC,aAAa,UAAW,aACrC,CAgEO,SAASC,EACdC,EACAC,EACAP,EACAQ,EACAC,GAEA,MAAMC,EArGD,SAAuBH,EAAqBP,GACjD,MAAO,CACLW,MAAOJ,EAAcP,EACrBY,KAAML,EAAc,GAAKP,EAE7B,CAgGgBa,CAAcN,EAAaP,GAUzC,OAxEK,SAA4Bc,EAAsCL,GACvE,OAAIA,EAAOM,QACFC,QAAQC,OAAOd,KArBL,iBAFMe,EAyBFJ,IAtBX,OAAVI,GACwD,mBAAhDA,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A,uBAAwB,qBAAqBzH,EAAI0H,UAAWtB,GAC5E3D,KAAKoE,UAAiC,mBAAoB,CAAE9G,MAAOC,IACnEyC,KAAKoE,UAAmC,qBAAsB,CAAEC,SAAS,KAE/E,CAMA,OAAAgC,GACE,IAAKrG,KAAKpE,WAAY,OACtB,MAAM0K,EAAKtG,KAAKpE,WAChBoE,KAAKU,iBACLV,KAAK9B,aAAauC,QAClBT,KAAKT,cAAckB,QACnBT,KAAKJ,aAAe,GACpBI,KAAKZ,eAAiB,EACtBY,KAAKX,oBAAqB,EAE1BW,KAAKO,cAAc+F,EACrB,CAKA,UAAAC,GACEvG,KAAKU,iBACLV,KAAK9B,aAAauC,QAClBT,KAAKJ,aAAe,EACtB,CAKA,iBAAA4G,GACE,OAAOxG,KAAKZ,cACd,CAKA,gBAAAqH,GACE,OAAOzG,KAAKZ,cACd,CAMA,YAAAsH,CAAarL,GACX,MACM4G,EAAW7G,EAAeC,EADd2E,KAAKE,OAAOpC,UAAYkC,KAAKE,OAAOsC,gBAAkB,KAExE,OAAOxC,KAAK9B,aAAa2F,IAAI5B,EAC/B,CAKA,WAAA0E,CAAYC,GACV,OAAO5G,KAAK0G,aAAaE,EAC3B,CAKA,mBAAAC,GACE,OAAO7G,KAAK9B,aAAa4F,IAC3B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_visibility={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,i){"use strict";class r extends i.BaseGridPlugin{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';get defaultConfig(){return{allowHideAll:!1}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(e=>{e.classList.remove(t.GridClasses.DRAGGING,"drop-target","drop-before","drop-after")})}attach(e){super.attach(e),this.gridElement.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.lockVisible||i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:r.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(r.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(r.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(r.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const r=document.createElement("button");return r.type="button",r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(r),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}canMoveColumn(e){const t=this.grid.columns.find(t=>t.field===e.field);if(!t)return!1;const i=this.grid.query("canMoveColumn",t);return i.length>0&&!i.includes(!1)}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=this.grid.getAllColumns().filter(e=>!e.utility),r=this.grid.query("getColumnGrouping"),l=r?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===l.length)return void this.renderFlatColumnList(i,t,e);const s=new Map;for(const o of l)for(const e of o.fields)s.set(e,o);const n=this.computeFragments(i,s);for(const o of n)if(o.group)this.renderGroupSection(o.group,o.columns,t,e);else{const r=i.indexOf(o.columns[0]);e.appendChild(this.createColumnRow(o.columns[0],r,t,e))}}computeFragments(e,t){const i=[];let r=null,l=[];for(const s of e){const e=t.get(s.field)??null;e&&r&&e.id===r.id?l.push(s):(l.length>0&&i.push({group:r,columns:l}),r=e,l=[s])}return l.length>0&&i.push({group:r,columns:l}),i}renderGroupSection(e,t,i,r){const l=t.map(e=>e.field),s=document.createElement("div");s.className="tbw-visibility-group-header",s.setAttribute("data-group-id",e.id),i&&(s.draggable=!0,s.classList.add("reorderable"),this.setupGroupDragListeners(s,e,l,r));const n=document.createElement("label");n.className="tbw-visibility-label";const o=document.createElement("input");o.type="checkbox";const d=t.filter(e=>e.visible).length,a=t.every(e=>e.lockVisible);d===t.length?(o.checked=!0,o.indeterminate=!1):0===d?(o.checked=!1,o.indeterminate=!1):(o.checked=!1,o.indeterminate=!0),o.disabled=a,o.addEventListener("change",()=>{const e=o.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(r),0)});const g=document.createElement("span");if(g.textContent=e.label,n.appendChild(o),n.appendChild(g),s.appendChild(n),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,"dragHandle"),e.title="Drag to reorder group",s.insertBefore(e,n)}r.appendChild(s);const u=this.grid.getAllColumns().filter(e=>!e.utility);for(const c of t){const e=u.findIndex(e=>e.field===c.field),t=this.createColumnRow(c,e,i,r);t.classList.add("tbw-visibility-row--grouped"),r.appendChild(t)}}renderFlatColumnList(e,t,i){const r=this.grid.getAllColumns().filter(e=>!e.utility);for(const l of e){const e=r.findIndex(e=>e.field===l.field);i.appendChild(this.createColumnRow(l,e,t,i))}}createColumnRow(e,t,i,r){const l=e.header||e.field,s=document.createElement("div");s.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",s.setAttribute("data-field",e.field),s.setAttribute("data-index",String(t)),i&&this.canMoveColumn(e)&&(s.draggable=!0,s.classList.add("reorderable"),this.setupDragListeners(s,e.field,t,r));const n=document.createElement("label");n.className="tbw-visibility-label";const o=document.createElement("input");o.type="checkbox",o.checked=e.visible,o.disabled=e.lockVisible??!1,o.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(r),0)});const d=document.createElement("span");if(d.textContent=l,n.appendChild(o),n.appendChild(d),i&&this.canMoveColumn(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,"dragHandle"),e.title="Drag to reorder",s.appendChild(e)}return s.appendChild(n),s}setupGroupDragListeners(e,i,r,l){e.addEventListener("dragstart",s=>{this.isDragging=!0,this.draggedGroupId=i.id,this.draggedGroupFields=[...r],this.draggedField=null,this.draggedIndex=null,s.dataTransfer&&(s.dataTransfer.effectAllowed="move",s.dataTransfer.setData("text/plain",`group:${i.id}`)),e.classList.add(t.GridClasses.DRAGGING),l.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const i=e.getAttribute("data-field");i&&this.draggedGroupFields.includes(i)&&e.classList.add(t.GridClasses.DRAGGING)})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(l)}),e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length===r.length&&this.draggedGroupFields.every(e=>r.includes(e)))return;if(!this.draggedGroupId)return;const i=e.getBoundingClientRect(),s=i.top+i.height/2,n=t.clientY<s;this.clearDragClasses(l),e.classList.add("drop-target"),e.classList.toggle("drop-before",n),e.classList.toggle("drop-after",!n)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",t=>{if(t.preventDefault(),!this.isDragging||!this.draggedGroupId)return;if(this.draggedGroupFields.length===r.length&&this.draggedGroupFields.every(e=>r.includes(e)))return;const i=e.getBoundingClientRect(),l=t.clientY<i.top+i.height/2;this.executeGroupDrop(this.draggedGroupFields,r,l)})}executeGroupDrop(e,t,i){const r=this.grid.getAllColumns().map(e=>e.field),l=r.filter(t=>!e.includes(t)),s=i?t[0]:t[t.length-1],n=l.indexOf(s);if(-1===n)return;const o=i?n:n+1,d=r.filter(t=>e.includes(t));l.splice(o,0,...d);const a=this.grid.getPluginByName?.("reorder");a?.setColumnOrder&&a.gridElement?a.setColumnOrder(l):this.grid.setColumnOrder(l),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,i,r,l){e.addEventListener("dragstart",l=>{this.isDragging=!0,this.draggedField=i,this.draggedIndex=r,this.draggedGroupId=null,this.draggedGroupFields=[],l.dataTransfer&&(l.dataTransfer.effectAllowed="move",l.dataTransfer.setData("text/plain",i)),e.classList.add(t.GridClasses.DRAGGING)}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(l)}),e.addEventListener("dragover",s=>{if(s.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===i)return;const n=e.getBoundingClientRect(),o=n.top+n.height/2;this.dropIndex=s.clientY<o?r:r+1,this.clearDragClasses(l),this.draggedGroupId?(l.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add(t.GridClasses.DRAGGING),l.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const i=e.getAttribute("data-field");i&&this.draggedGroupFields.includes(i)&&e.classList.add(t.GridClasses.DRAGGING)})):this.draggedField&&l.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add(t.GridClasses.DRAGGING),e.classList.add("drop-target"),e.classList.toggle("drop-before",s.clientY<o),e.classList.toggle("drop-after",s.clientY>=o)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const r=e.getBoundingClientRect(),l=t.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[i],l)}const r=this.draggedField,l=this.draggedIndex,s=this.dropIndex;if(null===r||null===l||null===s)return;const n=s>l?s-1:s;if(n!==l){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[n]?.field,s={field:r,fromIndex:l,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",s)}})}}e.VisibilityPlugin=r,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("../../core/constants"),require("../../core/plugin/base-plugin")):"function"==typeof define&&define.amd?define(["exports","../../core/constants","../../core/plugin/base-plugin"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TbwGridPlugin_visibility={},e.TbwGrid,e.TbwGrid)}(this,function(e,t,i){"use strict";class r extends i.BaseGridPlugin{static dependencies=[{name:"reorder",required:!1,reason:"Enables drag-to-reorder columns in visibility panel"}];static manifest={queries:[{type:"getContextMenuItems",description:'Contributes "Hide column" item to the header context menu'}]};name="visibility";static PANEL_ID="columns";styles='@layer tbw-plugins{.tbw-visibility-content{display:flex;flex-direction:column;height:100%}.tbw-visibility-list{flex:1;overflow-y:auto;padding:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem))}.tbw-visibility-row{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));padding:var(--tbw-menu-item-padding, .375rem .25rem);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem);border-radius:var(--tbw-border-radius, .25rem);position:relative}.tbw-visibility-row:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-row input[type=checkbox]{cursor:pointer}.tbw-visibility-row.locked span{color:var(--tbw-color-fg-muted)}.tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-row.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-label{display:flex;align-items:center;gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem));flex:1;cursor:pointer}.tbw-visibility-row.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-row.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-show-all{margin:var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem));padding:var(--tbw-button-padding, .5rem .75rem);border:1px solid var(--tbw-visibility-border, var(--tbw-color-border));border-radius:var(--tbw-border-radius, .25rem);background:var(--tbw-visibility-btn-bg, var(--tbw-color-header-bg));color:var(--tbw-color-fg);cursor:pointer;font-size:var(--tbw-font-size-sm, .8125rem)}.tbw-visibility-show-all:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header{display:flex;align-items:center;padding:var(--tbw-menu-item-padding, .375rem .25rem);font-size:var(--tbw-font-size-sm, .8125rem);font-weight:600;color:var(--tbw-color-fg);border-bottom:1px solid var(--tbw-color-border);margin-top:var(--tbw-spacing-sm, .25rem);position:relative}.tbw-visibility-group-header:first-child{margin-top:0}.tbw-visibility-group-header .tbw-visibility-label{gap:var(--tbw-panel-gap, var(--tbw-spacing-md, .5rem))}.tbw-visibility-group-header.reorderable{cursor:grab}.tbw-visibility-group-header.reorderable:hover{background:var(--tbw-visibility-hover, var(--tbw-color-row-hover))}.tbw-visibility-group-header .tbw-visibility-handle{cursor:grab;color:var(--tbw-color-fg-muted);font-size:var(--tbw-font-size-2xs, .625rem);letter-spacing:-2px;-webkit-user-select:none;user-select:none;flex-shrink:0}.tbw-visibility-group-header.reorderable:hover .tbw-visibility-handle{color:var(--tbw-color-fg)}.tbw-visibility-group-header.dragging{opacity:.5;cursor:grabbing}.tbw-visibility-group-header.drop-before:before{content:"";position:absolute;left:0;right:0;top:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-group-header.drop-after:after{content:"";position:absolute;left:0;right:0;bottom:0;height:2px;background:var(--tbw-visibility-indicator, var(--tbw-color-accent))}.tbw-visibility-row--grouped{padding-left:calc(var(--tbw-panel-padding, var(--tbw-spacing-md, .5rem)) + .75rem)}}';get defaultConfig(){return{}}columnListElement=null;isDragging=!1;draggedField=null;draggedIndex=null;dropIndex=null;draggedGroupId=null;draggedGroupFields=[];clearDragClasses(e){e.querySelectorAll(".tbw-visibility-row, .tbw-visibility-group-header").forEach(e=>{e.classList.remove(t.GridClasses.DRAGGING,"drop-target","drop-before","drop-after")})}attach(e){super.attach(e),this.gridElement.addEventListener("column-move",()=>{this.columnListElement&&requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})},{signal:this.disconnectSignal})}detach(){this.columnListElement=null,this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null}handleQuery(e){if("getContextMenuItems"===e.type){const t=e.context;if(!t.isHeader)return;const i=t.column;if(!i?.field)return;if(i.lockVisible||i.meta?.lockVisibility)return;return[{id:"visibility/hide-column",label:"Hide Column",icon:"👁",order:30,action:()=>this.hideColumn(i.field)}]}}getToolPanel(){return{id:r.PANEL_ID,title:"Columns",icon:"☰",tooltip:"Column visibility",order:100,render:e=>this.renderPanelContent(e)}}show(){this.grid.openToolPanel(r.PANEL_ID)}hide(){this.grid.closeToolPanel()}toggle(){this.grid.isToolPanelOpen||this.grid.openToolPanel(),this.grid.toggleToolPanelSection(r.PANEL_ID)}isColumnVisible(e){return this.grid.isColumnVisible(e)}setColumnVisible(e,t){this.grid.setColumnVisible(e,t)}getVisibleColumns(){return this.grid.getAllColumns().filter(e=>e.visible).map(e=>e.field)}getHiddenColumns(){return this.grid.getAllColumns().filter(e=>!e.visible).map(e=>e.field)}showAll(){this.grid.showAllColumns()}toggleColumn(e){this.grid.toggleColumnVisibility(e)}showColumn(e){this.setColumnVisible(e,!0)}hideColumn(e){this.setColumnVisible(e,!1)}getAllColumns(){return this.grid.getAllColumns()}isPanelVisible(){return this.grid.isToolPanelOpen&&this.grid.expandedToolPanelSections.includes(r.PANEL_ID)}renderPanelContent(e){const t=document.createElement("div");t.className="tbw-visibility-content";const i=document.createElement("div");i.className="tbw-visibility-list",t.appendChild(i);const r=document.createElement("button");return r.type="button",r.className="tbw-visibility-show-all",r.textContent="Show All",r.addEventListener("click",()=>{this.grid.showAllColumns(),this.rebuildToggles(i)}),t.appendChild(r),this.columnListElement=i,this.rebuildToggles(i),e.appendChild(t),()=>{this.columnListElement=null,t.remove()}}hasReorderPlugin(){const e=this.grid?.getPluginByName?.("reorder");return!(!e||"function"!=typeof e.moveColumn)}canMoveColumn(e){const t=this.grid.columns.find(t=>t.field===e.field);if(!t)return!1;const i=this.grid.query("canMoveColumn",t);return i.length>0&&!i.includes(!1)}rebuildToggles(e){const t=this.hasReorderPlugin();e.innerHTML="";const i=this.grid.getAllColumns().filter(e=>!e.utility),r=this.grid.query("getColumnGrouping"),s=r?.flat().filter(e=>e&&e.fields.length>0)??[];if(0===s.length)return void this.renderFlatColumnList(i,t,e);const l=new Map;for(const o of s)for(const e of o.fields)l.set(e,o);const n=this.computeFragments(i,l);for(const o of n)if(o.group)this.renderGroupSection(o.group,o.columns,t,e);else{const r=i.indexOf(o.columns[0]);e.appendChild(this.createColumnRow(o.columns[0],r,t,e))}}computeFragments(e,t){const i=[];let r=null,s=[];for(const l of e){const e=t.get(l.field)??null;e&&r&&e.id===r.id?s.push(l):(s.length>0&&i.push({group:r,columns:s}),r=e,s=[l])}return s.length>0&&i.push({group:r,columns:s}),i}renderGroupSection(e,t,i,r){const s=t.map(e=>e.field),l=document.createElement("div");l.className="tbw-visibility-group-header",l.setAttribute("data-group-id",e.id),i&&(l.draggable=!0,l.classList.add("reorderable"),this.setupGroupDragListeners(l,e,s,r));const n=document.createElement("label");n.className="tbw-visibility-label";const o=document.createElement("input");o.type="checkbox";const d=t.filter(e=>e.visible).length,a=t.every(e=>e.lockVisible);d===t.length?(o.checked=!0,o.indeterminate=!1):0===d?(o.checked=!1,o.indeterminate=!1):(o.checked=!1,o.indeterminate=!0),o.disabled=a,o.addEventListener("change",()=>{const e=o.checked;for(const i of t)i.lockVisible||this.grid.setColumnVisible(i.field,e);setTimeout(()=>this.rebuildToggles(r),0)});const g=document.createElement("span");if(g.textContent=e.label,n.appendChild(o),n.appendChild(g),l.appendChild(n),i){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,"dragHandle"),e.title="Drag to reorder group",l.insertBefore(e,n)}r.appendChild(l);const u=this.grid.getAllColumns().filter(e=>!e.utility);for(const c of t){const e=u.findIndex(e=>e.field===c.field),t=this.createColumnRow(c,e,i,r);t.classList.add("tbw-visibility-row--grouped"),r.appendChild(t)}}renderFlatColumnList(e,t,i){const r=this.grid.getAllColumns().filter(e=>!e.utility);for(const s of e){const e=r.findIndex(e=>e.field===s.field);i.appendChild(this.createColumnRow(s,e,t,i))}}createColumnRow(e,t,i,r){const s=e.header||e.field,l=document.createElement("div");l.className=e.lockVisible?"tbw-visibility-row locked":"tbw-visibility-row",l.setAttribute("data-field",e.field),l.setAttribute("data-index",String(t)),i&&this.canMoveColumn(e)&&(l.draggable=!0,l.classList.add("reorderable"),this.setupDragListeners(l,e.field,t,r));const n=document.createElement("label");n.className="tbw-visibility-label";const o=document.createElement("input");o.type="checkbox",o.checked=e.visible,o.disabled=e.lockVisible??!1,o.addEventListener("change",()=>{this.grid.toggleColumnVisibility(e.field),setTimeout(()=>this.rebuildToggles(r),0)});const d=document.createElement("span");if(d.textContent=s,n.appendChild(o),n.appendChild(d),i&&this.canMoveColumn(e)){const e=document.createElement("span");e.className="tbw-visibility-handle",this.setIcon(e,"dragHandle"),e.title="Drag to reorder",l.appendChild(e)}return l.appendChild(n),l}setupGroupDragListeners(e,i,r,s){e.addEventListener("dragstart",l=>{this.isDragging=!0,this.draggedGroupId=i.id,this.draggedGroupFields=[...r],this.draggedField=null,this.draggedIndex=null,l.dataTransfer&&(l.dataTransfer.effectAllowed="move",l.dataTransfer.setData("text/plain",`group:${i.id}`)),e.classList.add(t.GridClasses.DRAGGING),s.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const i=e.getAttribute("data-field");i&&this.draggedGroupFields.includes(i)&&e.classList.add(t.GridClasses.DRAGGING)})}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedGroupId=null,this.draggedGroupFields=[],this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(s)}),e.addEventListener("dragover",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupFields.length===r.length&&this.draggedGroupFields.every(e=>r.includes(e)))return;if(!this.draggedGroupId)return;const i=e.getBoundingClientRect(),l=i.top+i.height/2,n=t.clientY<l;this.clearDragClasses(s),e.classList.add("drop-target"),e.classList.toggle("drop-before",n),e.classList.toggle("drop-after",!n)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",t=>{if(t.preventDefault(),!this.isDragging||!this.draggedGroupId)return;if(this.draggedGroupFields.length===r.length&&this.draggedGroupFields.every(e=>r.includes(e)))return;const i=e.getBoundingClientRect(),s=t.clientY<i.top+i.height/2;this.executeGroupDrop(this.draggedGroupFields,r,s)})}executeGroupDrop(e,t,i){const r=this.grid.getAllColumns().map(e=>e.field),s=r.filter(t=>!e.includes(t)),l=i?t[0]:t[t.length-1],n=s.indexOf(l);if(-1===n)return;const o=i?n:n+1,d=r.filter(t=>e.includes(t));s.splice(o,0,...d);const a=this.grid.getPluginByName?.("reorder");a?.setColumnOrder&&a.gridElement?a.setColumnOrder(s):this.grid.setColumnOrder(s),requestAnimationFrame(()=>{this.columnListElement&&this.rebuildToggles(this.columnListElement)})}setupDragListeners(e,i,r,s){e.addEventListener("dragstart",s=>{this.isDragging=!0,this.draggedField=i,this.draggedIndex=r,this.draggedGroupId=null,this.draggedGroupFields=[],s.dataTransfer&&(s.dataTransfer.effectAllowed="move",s.dataTransfer.setData("text/plain",i)),e.classList.add(t.GridClasses.DRAGGING)}),e.addEventListener("dragend",()=>{this.isDragging=!1,this.draggedField=null,this.draggedIndex=null,this.dropIndex=null,this.clearDragClasses(s)}),e.addEventListener("dragover",l=>{if(l.preventDefault(),!this.isDragging)return;if(this.draggedGroupId){if(e.classList.contains("tbw-visibility-row--grouped"))return}else if(this.draggedField===i)return;const n=e.getBoundingClientRect(),o=n.top+n.height/2;this.dropIndex=l.clientY<o?r:r+1,this.clearDragClasses(s),this.draggedGroupId?(s.querySelector(`.tbw-visibility-group-header[data-group-id="${this.draggedGroupId}"]`)?.classList.add(t.GridClasses.DRAGGING),s.querySelectorAll(".tbw-visibility-row--grouped").forEach(e=>{const i=e.getAttribute("data-field");i&&this.draggedGroupFields.includes(i)&&e.classList.add(t.GridClasses.DRAGGING)})):this.draggedField&&s.querySelector(`.tbw-visibility-row[data-field="${this.draggedField}"]`)?.classList.add(t.GridClasses.DRAGGING),e.classList.add("drop-target"),e.classList.toggle("drop-before",l.clientY<o),e.classList.toggle("drop-after",l.clientY>=o)}),e.addEventListener("dragleave",()=>{e.classList.remove("drop-target","drop-before","drop-after")}),e.addEventListener("drop",t=>{if(t.preventDefault(),!this.isDragging)return;if(this.draggedGroupId&&this.draggedGroupFields.length>0){if(e.classList.contains("tbw-visibility-row--grouped"))return;const r=e.getBoundingClientRect(),s=t.clientY<r.top+r.height/2;return void this.executeGroupDrop(this.draggedGroupFields,[i],s)}const r=this.draggedField,s=this.draggedIndex,l=this.dropIndex;if(null===r||null===s||null===l)return;const n=l>s?l-1:l;if(n!==s){const e=this.grid.getAllColumns(),t=e.filter(e=>!e.utility),i=t[n]?.field,l={field:r,fromIndex:s,toIndex:i?e.findIndex(e=>e.field===i):e.length};this.emit("column-reorder-request",l)}})}}e.VisibilityPlugin=r,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=visibility.umd.js.map
|