@ds-mo/ui 15.8.0 → 15.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.package-ready.json +1 -1
- package/dist/agent-patterns.json +1 -1
- package/dist/agent.json +6 -2
- package/dist/angular/ds-table.d.ts +10 -1
- package/dist/angular/ds-table.js +5 -2
- package/dist/components/ds-table.js +1 -1
- package/dist/components/ds-table.js.map +1 -1
- package/dist/docs/components.json +15 -1
- package/dist/mcp-data/registry/registry.json +5 -1
- package/dist/mcp-data/registry/table.json +19 -3
- package/dist/react/ds-table.d.ts +3 -0
- package/dist/react/ds-table.js +1 -0
- package/dist/types/components/Table/Table.d.ts +5 -0
- package/dist/types/components/Table/table-viewport-fit-controller.d.ts +3 -0
- package/dist/types/components.d.ts +5 -0
- package/dist/vue/ds-table.js +2 -0
- package/package.json +1 -1
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"accessibility": [
|
|
50
50
|
"The rendered structure uses a native table, caption, column headers, row groups, and data cells; keep the caption non-empty. The native caption remains visually hidden as the table's accessible name. When caption visibility is enabled, a 48px header bar renders as component chrome outside the data scrollport. It defaults to a presentational caption title that does not duplicate the accessible name. Application-owned labeled controls supplied through the single named header slot replace that fallback and share one horizontal caption overflow row with table-owned actions inside the component-owned 8px inset. Table caption buttons keep pressed interaction paint without physically scaling. When columnCustomizer is enabled, the table adds a trailing Customize control named Customize table. Its label uses regular weight and its resting foreground remains neutral when hidden or reordered columns differ from the catalog default. The control is icon-label at typical widths and the icon-only Customize menu button below 900px, where a tooltip preserves the Customize label. The always-icon-only table-variant control also exposes its label through a tooltip. Otherwise the header slot receives the complete content width.",
|
|
51
51
|
"The data-mode switcher is the shared Menu of the table's supported infinite, pagination, and virtual modes. It uses an Ellipses trigger. When the column customizer is also present, a decorative vertical divider separates the two controls. The optional caption-trailing slot follows table-owned caption actions for application-owned presentation controls; the application supplies its own divider when needed. dataMode remains controlled, and the application responds to change intent by supplying the matching records, pagination state, loading behavior, and query consequences. Escape, dismissal, and selection return focus to the trigger.",
|
|
52
|
-
"When alternateView is enabled, the alternate-view slot replaces the table frame body while the shared caption and footer remain mounted. The application owns the replacement content's accessible name, filtering, and interaction. Do not render a hidden duplicate semantic table behind that content.",
|
|
52
|
+
"When alternateView is enabled, the alternate-view slot replaces the table frame body while the shared caption and footer remain mounted. The application owns the replacement content's accessible name, filtering, and interaction. An adjacent presentation control or footer label should commit when the replacement frame and footer have rendered, so the old and new presentations are never painted together. Do not render a hidden duplicate semantic table behind that content.",
|
|
53
53
|
"The column customizer is the shared Menu surface of composite preference rows. Data columns can be shown, hidden, left-pinned, and reordered. Visibility and pin state are independent, so hidden pinned columns retain their pin state. A tertiary divider separates the visibility switch from an unbordered Pin toggle. Pinned and unpinned sections constrain drag reorder to their own partition; a single pinned row keeps its drag handle visible but inactive in quaternary foreground. Action columns and the selection checkbox remain system-managed and never appear in the menu. Escape and outside click restore focus to the trigger. Persistence stays in the application.",
|
|
54
54
|
"Sorting controls remain buttons inside column headers and expose the table's one controlled member-row sort through aria-sort. ds-data-sort in the toolbar trailing cluster is the matching menu of Data and Order sections; it emits the same dsSortChange shape so header clicks and menu choices stay in sync. Grouping never adds a second sort indicator or header control; ds-data-group controls the grouping data point and ascending or descending group-section order while the application supplies the resulting groups. Optional column help underlines the header label with the shared dotted decoration and shows ds-tooltip from that label; it does not add a second header control or replace the column name.",
|
|
55
55
|
"Selection controls expose checkbox semantics and explicit row names; select-all affects selectable loaded rows only and preserves selected identities outside the loaded window. In virtual mode the supplied in-memory rows are that loaded set, including rows whose DOM is recycled. When grouping is active with multi-selection, each group section header also exposes a checkbox that selects or clears that group's selectable loaded rows.",
|
|
@@ -833,6 +833,14 @@
|
|
|
833
833
|
}
|
|
834
834
|
},
|
|
835
835
|
"events": [
|
|
836
|
+
{
|
|
837
|
+
"name": "dsAlternateViewRendered",
|
|
838
|
+
"detail": "{ alternateView: boolean }",
|
|
839
|
+
"bubbles": true,
|
|
840
|
+
"cancelable": true,
|
|
841
|
+
"composed": true,
|
|
842
|
+
"description": "Fires after a table/alternate-view switch has patched the frame and footer."
|
|
843
|
+
},
|
|
836
844
|
{
|
|
837
845
|
"name": "dsCellAction",
|
|
838
846
|
"detail": "TableCellActionDetail",
|
|
@@ -1529,6 +1537,14 @@
|
|
|
1529
1537
|
}
|
|
1530
1538
|
},
|
|
1531
1539
|
"events": [
|
|
1540
|
+
{
|
|
1541
|
+
"name": "dsAlternateViewRendered",
|
|
1542
|
+
"detail": "{ alternateView: boolean }",
|
|
1543
|
+
"bubbles": true,
|
|
1544
|
+
"cancelable": true,
|
|
1545
|
+
"composed": true,
|
|
1546
|
+
"description": "Fires after a table/alternate-view switch has patched the frame and footer."
|
|
1547
|
+
},
|
|
1532
1548
|
{
|
|
1533
1549
|
"name": "dsCellAction",
|
|
1534
1550
|
"detail": "TableCellActionDetail",
|
|
@@ -1697,7 +1713,7 @@
|
|
|
1697
1713
|
},
|
|
1698
1714
|
{
|
|
1699
1715
|
"path": "src/wc/components/Table/Table.tsx",
|
|
1700
|
-
"content": "import {\n Component,\n Element,\n Event,\n EventEmitter,\n h,\n Host,\n Listen,\n Method,\n Prop,\n State,\n Watch,\n} from '@stencil/core';\nimport {\n deriveTableSelectionState,\n formatTableResultSummary,\n formatTableTotalSummary,\n hasOwnedTableFooterSlot,\n isTableCellAction,\n nextDataSortState,\n tableColumnSize,\n tableModelIssues,\n TABLE_GROUP_HERO_SCORE_PRESENTATION,\n tableRows,\n toggleAllLoadedTableRows,\n toggleTableGroupCollapsed,\n toggleTableGroupSelection,\n nextTableGroupsCollapsed,\n toggleTableRowSelection,\n} from './table-model';\nimport { createTableRenderModel, type TableRenderModel } from './table-render-model';\nimport {\n isRenderableTableActionMenu,\n nextTableActionMenuElementId,\n tableActionMenuSections,\n tableActionTriggerId,\n} from './table-action-menu';\nimport {\n nextTableColumnCustomizerElementId,\n reorderTableColumnPartition,\n resolveTableFieldsConfiguration,\n resolveTableVisibleColumns,\n tableColumnCustomizerSections,\n toggleTableColumnHidden,\n toggleTableColumnPinned,\n} from './table-column-customizer';\nimport {\n nextTableDataModeSwitcherElementId,\n tableDataModeFromMenuItem,\n tableDataModeMenuItems,\n} from './table-data-mode-switcher';\nimport { resolveTableTruncateTrack, tableTruncateLabel } from './table-truncate';\nimport { renderTableRow as renderTableRowView } from './table-row-view';\nimport { TableBodyRenderer } from './table-body-renderer';\nimport { tableHeaderBands, tablePinnedColumns, tableSpanModel } from './table-structure';\nimport {\n tableGridModel,\n tableRangeBounds,\n tableEditable,\n tableEditValue,\n tablePasteChanges,\n tableNextEditable,\n} from './table-grid-model';\nimport { renderTableCellEditor } from './table-cell-editor';\nimport type {\n TableCellSpan,\n TableCellRange,\n TableCellAddress,\n TableCellsChangeDetail,\n} from './table-types';\nimport { renderTableSkeletonBody } from './table-skeleton-view';\nimport { renderTableLoadContent } from './table-load-view';\nimport {\n isTableCardViewport,\n TABLE_CARD_VIEWPORT_BREAKPOINT,\n TableLayoutController,\n} from './table-layout-controller';\nimport { TableLoadController } from './table-load-controller';\nimport { TableGroupLoadController } from './table-group-load-controller';\nimport {\n estimateTableRowBlockSize,\n flattenTableVirtualItems,\n resolveTableVirtualPlan,\n TABLE_VIRTUAL_TOTAL_SUMMARY_LABEL,\n TABLE_VIRTUAL_VIEWPORT_REQUIRED_BODY,\n TABLE_VIRTUAL_VIEWPORT_REQUIRED_HEADING,\n type TableVirtualItem,\n type TableVirtualPlan,\n} from './table-virtual-model';\nimport { TableVirtualController } from './table-virtual-controller';\nimport type { PaginationChangeDetail } from '../Pagination/pagination-types';\nimport type { MenuItemData, MenuItemToggleDetail, MenuReorderDetail } from '../Menu/menu-types';\nimport { resolvePaginationState } from '../Pagination/pagination-model';\nimport { resolveCssLengthPx } from '../../utils/resolve-css-length-px';\nimport { isElementTruncated } from '../../utils/is-element-truncated';\nimport { observeTableCaptionCompact } from '../../utils/table-caption-compact';\nimport { resolveTableFitPageSize } from './table-pagination-fit';\nimport { createTableHighlightMatcher, type TableHighlightMatcher } from './table-highlight';\nimport {\n paginationShortcutBlockedByPath,\n shouldHandleContainingPagePaginationShortcut,\n} from './table-pagination-shortcut';\nimport {\n TableViewportFitController,\n type TableViewportFitMetrics,\n} from './table-viewport-fit-controller';\nimport type {\n TableCaptionVisibility,\n TableChromeLayout,\n TableCellActionDetail,\n TableColumn,\n DataFieldsConfigChangeDetail,\n TableDataMode,\n TableDataModeChangeDetail,\n DataGroup,\n TableGroupCollapseChangeDetail,\n TableGroupLoadMoreDetail,\n DataGroupingState,\n TableLoadMoreDetail,\n TableLoadMoreMode,\n TablePaginationState,\n TableRow,\n TableRowActivateDetail,\n TableSelectionChangeDetail,\n TableSelectionMode,\n DataSortChangeDetail,\n DataSortState,\n} from './table-types';\n\nconst TABLE_FOOTER_SLOT_LEADING = 1;\nconst TABLE_FOOTER_SLOT_COPY = 2;\nconst TABLE_FOOTER_SLOT_TRAILING = 4;\nconst TABLE_NON_VIRTUAL_WINDOW_THRESHOLD = 50;\n\n@Component({\n tag: 'ds-table',\n styleUrls: ['../../utils/focus-ring.css', '../../utils/interaction-fill.css', 'Table.css'],\n scoped: true,\n})\nexport class Table {\n @Element() el!: HTMLElement;\n /** Stable column definitions. Assign through JavaScript. */\n @Prop() columns: TableColumn[] = [];\n /** Opt-in native card presentation below the 768px browser viewport breakpoint. */\n @Prop() responsiveLayout: 'scroll' | 'cards' = 'scroll';\n /** Keep all table chrome contained, or let the caption and footer span edge to edge around an inset data frame. */\n @Prop() chromeLayout: TableChromeLayout = 'contained';\n /** Explicit report merges; invalid combinations leave the original cells visible. */\n @Prop() cellSpans: TableCellSpan[] = [];\n /** Table is read-only; edit uses per-cell pencil buttons; grid adds cell selection and keyboard navigation. Grouped tables remain read-only. */\n @Prop() interactionMode: 'table' | 'edit' | 'grid' = 'table';\n /** Controlled rectangular cell selection, independent of row checkbox selection. */\n @Prop() cellRange: TableCellRange | null = null;\n @Event() dsCellRangeChange!: EventEmitter<TableCellRange>;\n @Event() dsCellsChange!: EventEmitter<TableCellsChangeDetail>;\n /** Additional toggle options in the column customizer. */\n @Prop() customizeOptions: MenuItemData[] = [];\n @Event() dsCustomizeOptionChange!: EventEmitter<string>;\n /** Ungrouped row data. Ignored while grouping is active. Assign through JavaScript. */\n @Prop() rows: TableRow[] = [];\n /** One level of application-owned grouped data. Assign through JavaScript. */\n @Prop() groups: DataGroup[] = [];\n /** Controlled grouping column. Applications supply groups in their final fixed order. */\n @Prop() grouping: DataGroupingState | null = null;\n /** Controlled member-row sort state. */\n @Prop() sort: DataSortState | null = null;\n /** Controlled collapsed group identities. Groups not listed remain expanded. */\n @Prop() collapsedGroupIds: string[] = [];\n /** Literal terms to highlight in table-owned text cells. Applications still own filtering. */\n @Prop() highlightTerms: string[] = [];\n /** Optional DataSearch field identities that restrict which data-point tracks are highlighted. */\n @Prop() highlightFieldIds: string[] = [];\n\n /** Required accessible table name, retained as a native caption. */\n @Prop() caption!: string;\n /** Shows a matching presentational title bar above the native table frame. */\n @Prop() captionVisibility: TableCaptionVisibility = 'hidden';\n /** Replace only the data frame with application-owned content; caption and footer remain shared. */\n @Prop() alternateView: boolean = false;\n /**\n * Opt in to the table-owned column customizer. The `columns` prop remains the\n * catalog; hidden and ordered columns are controlled separately. The trigger\n * opens the shared Menu of live show/hide switch rows.\n */\n @Prop() columnCustomizer: boolean = false;\n /** Hide only the built-in Customize trigger when an external preferences surface owns it. */\n /** Remove borders from table-owned caption controls. */\n @Prop() captionControlsBorderless: boolean = false;\n @Prop() hideColumnCustomizerTrigger: boolean = false;\n /** Controlled hidden data-column identities. Action ids are ignored. */\n @Prop() hiddenFieldIds: string[] = [];\n /** Controlled data-column identities in display order. Omitted ids append in catalog order. */\n @Prop() fieldOrder: string[] = [];\n /** Controlled user-pinned data-column identities. Hidden columns retain their pin state. */\n @Prop() pinnedFieldIds: string[] = [];\n /**\n * Optional result summary footer. When both `displayedCount` and `totalCount`\n * are finite numbers, infinite mode shows “Displaying {displayed} of {total}”.\n * Virtual mode ignores `displayedCount` and derives its total from the\n * complete supplied rows; a mismatched `totalCount` emits a warning.\n */\n @Prop() displayedCount: number | undefined;\n @Prop() totalCount: number | undefined;\n /** Supports {displayed} and {total} placeholders. */\n @Prop() resultSummaryLabel: string = 'Displaying {displayed} of {total}';\n /** Supports the {total} placeholder. Used when dataMode is virtual. */\n @Prop() resultTotalSummaryLabel: string = TABLE_VIRTUAL_TOTAL_SUMMARY_LABEL;\n @Prop() stickyHeader: boolean = false;\n /** Maximum scroll-region height. Numbers resolve to CSS pixels. */\n @Prop() maxHeight: string | number | undefined;\n /** Fixed height for the complete header, table frame, and footer composition. */\n @Prop() height: string | number | undefined;\n /** Fit the complete table composition to its nearest vertical scrollport. */\n @Prop() fitViewport: boolean = false;\n /** Reserved space above a viewport-fitted table once surrounding chrome is compact. */\n @Prop() viewportInsetBlockStart: string | number = 0;\n /** Reserved space below a viewport-fitted table. */\n @Prop() viewportInsetBlockEnd: string | number = 0;\n /** Optional explicit label for the horizontal/vertical scroll region. */\n @Prop() scrollLabel: string | undefined;\n\n @Prop() selectionMode: TableSelectionMode = 'none';\n /** Controlled selected row identities. IDs outside the loaded rows are preserved. */\n @Prop() selectedRowIds: string[] = [];\n\n /**\n * Identity of the interactive row whose associated surface is visible.\n * Holds its pressed wash independently of checkbox selection. Keep the ID\n * through exit motion and clear it after close; the application owns toggling\n * and switching the surface. Off-window identities survive virtualization.\n */\n @Prop() surfaceOpenRowId: string | undefined;\n\n /** Initial loading state. Existing rows stay visible; incremental loading uses loadingMore. */\n @Prop() loading: boolean = false;\n /** Replace opted-in table-owned caption controls with same-size visual skeletons. */\n @Prop() chromeLoading: boolean = false;\n /** Initial-loading rows. Defaults to ten so bounded tables retain a useful filled viewport. */\n @Prop() skeletonRows: number = 10;\n @Prop() emptyHeading: string = 'No results';\n @Prop() emptyBody: string = 'No data is available.';\n /** Initial error state. Existing rows stay visible; incremental failures use loadMoreError. */\n @Prop() error: boolean = false;\n @Prop() errorHeading: string = 'Unable to load data';\n @Prop() errorBody: string = 'The data could not be loaded.';\n @Prop() emptyCellLabel: string = 'Not available';\n\n /** Top-level data-window strategy. Virtual mode recycles row DOM only. */\n @Prop() dataMode: TableDataMode = 'infinite';\n /** Opt in to the table-owned control for choosing between supported data modes. */\n @Prop() dataModeSwitcher: boolean = false;\n @Prop() dataModeSwitcherLabel: string = 'Change table variation';\n @Prop() dataModeMenuLabel: string = 'Table variation';\n @Prop() infiniteModeLabel: string = 'Infinite scroll';\n @Prop() paginationModeLabel: string = 'Pagination + Infinite groups';\n @Prop() virtualModeLabel: string = 'Virtual scroll';\n /** Controlled top-level pagination state. Required when dataMode is pagination. */\n @Prop() pagination: TablePaginationState | null = null;\n @Prop() loadMoreMode: TableLoadMoreMode = 'auto';\n @Prop() hasMore: boolean = false;\n @Prop() loadingMore: boolean = false;\n @Prop() loadMoreError: string | undefined;\n /** Reset key for a new query/group/sort dataset. */\n @Prop() loadIdentity: string | number = 'default';\n /** IntersectionObserver root margin in CSS pixels. */\n @Prop() loadMoreThreshold: number = 0;\n @Prop() loadMoreLabel: string = 'Load more';\n @Prop() retryLabel: string = 'Retry';\n @Prop() loadingMoreLabel: string = 'Loading more items';\n @Prop() endOfResultsLabel: string = 'All results loaded';\n /** Supports {count} and {total} placeholders. */\n @Prop() rowsLoadedLabel: string = '{count} more rows loaded. {total} rows loaded.';\n @Prop() groupLoadMoreLabel: string = 'Load more';\n /** Supports the {group} placeholder. */\n @Prop() groupLoadMoreAriaLabel: string = 'Load more {group} results';\n /** Supports the {group} placeholder. */\n @Prop() groupRetryLabel: string = 'Retry loading {group} results';\n /** Supports the {group} placeholder. */\n @Prop() groupLoadingMoreLabel: string = 'Loading more items';\n /** Supports the {group} placeholder. */\n @Prop() groupEndOfResultsLabel: string = 'All {group} results loaded';\n /** Supports {group}, {count}, {loaded}, and {total} placeholders. */\n @Prop() groupRowsLoadedLabel: string =\n '{count} more rows loaded in {group}. {loaded} of {total} rows loaded.';\n\n @Event() dsSortChange!: EventEmitter<DataSortChangeDetail>;\n @Event() dsGroupCollapseChange!: EventEmitter<TableGroupCollapseChangeDetail>;\n @Event() dsSelectionChange!: EventEmitter<TableSelectionChangeDetail>;\n @Event() dsLoadMore!: EventEmitter<TableLoadMoreDetail>;\n @Event() dsGroupLoadMore!: EventEmitter<TableGroupLoadMoreDetail>;\n @Event() dsPaginationChange!: EventEmitter<PaginationChangeDetail>;\n @Event() dsCellAction!: EventEmitter<TableCellActionDetail>;\n @Event() dsRowActivate!: EventEmitter<TableRowActivateDetail>;\n @Event() dsFieldsConfigChange!: EventEmitter<DataFieldsConfigChangeDetail>;\n @Event() dsDataModeChange!: EventEmitter<TableDataModeChangeDetail>;\n\n @State() private overflowStart = false;\n @State() private overflowEnd = false;\n @State() private scrollable = false;\n @State() private announcement = '';\n @State() private activeStickyGroupId: string | null = null;\n @State() private viewportFitSettled = false;\n @State() private headerPresent = false;\n @State() private headerUsesToolbar = false;\n @State() private captionTrailingPresent = false;\n @State() private footerSlotPresence = 0;\n @State() private fitPageSize: number | undefined;\n @State() private actionMenu: { rowId: string; columnId: string } | null = null;\n @State() private actionMenuInitialFocusVisible = false;\n @State() private actionMenuSurface: { rowId: string; columnId: string } | null = null;\n @State() private truncateTooltipLabel = '';\n @State() private captionCompact = false;\n @State() private narrowViewport = false;\n @State() private columnCustomizerOpen = false;\n @State() private columnCustomizerSurfaceOpen = false;\n @State() private columnCustomizerInitialFocusVisible = false;\n @State() private dataModeSwitcherOpen = false;\n @State() private dataModeSwitcherSurfaceOpen = false;\n @State() private dataModeSwitcherInitialFocusVisible = false;\n @State() private virtualWindow: TableVirtualPlan | null = null;\n @State() private activeCell: TableCellAddress | null = null;\n @State() private editingCell: TableCellAddress | null = null;\n private editDraft = '';\n private gridModelCache?: ReturnType<typeof tableGridModel>;\n private get gridEnabled(): boolean {\n return this.interactionMode === 'grid' && !this.grouped;\n }\n private get editingEnabled(): boolean {\n return this.interactionMode !== 'table' && !this.grouped;\n }\n private get gridModel() {\n if (\n !this.gridModelCache ||\n this.gridModelCache.rows !== this.rows ||\n this.gridModelCache.columns !== this.visibleColumns\n ) {\n this.gridModelCache = tableGridModel(this.rows, this.visibleColumns);\n }\n return this.gridModelCache;\n }\n private gridAddress(event: Event): TableCellAddress | null {\n if (\n !this.gridEnabled ||\n !(event.target instanceof HTMLElement) ||\n !event.target.matches('td[role=\"gridcell\"][data-cell-editable=\"true\"]')\n )\n return null;\n const rowId = event.target.closest<HTMLElement>('[data-row-id]')?.dataset.rowId;\n const columnId = event.target.dataset.columnId;\n return rowId && columnId ? { rowId, columnId } : null;\n }\n private selectCell(address: TableCellAddress, extend = false): void {\n if (!this.isEditableAddress(address)) return;\n this.activeCell = address;\n this.dsCellRangeChange.emit({\n anchor: extend ? (this.cellRange?.anchor ?? address) : address,\n focus: address,\n });\n }\n private async focusCell(address: TableCellAddress): Promise<void> {\n if (!this.isEditableAddress(address)) return;\n this.activeCell = address;\n this.focusedRowId = address.rowId;\n await this.scrollRowIntoView(address.rowId);\n await this.nextAnimationFrame();\n const cell = this.findRenderedRow(address.rowId)?.querySelector<HTMLElement>(\n `[data-column-id=\"${CSS.escape(address.columnId)}\"]`\n );\n if (this.gridEnabled) cell?.focus();\n else\n await cell\n ?.querySelector<HTMLDsButtonUnfilledElement>('.ds-table__edit-trigger ds-button-unfilled')\n ?.setFocus();\n }\n private isEditableAddress(address: TableCellAddress): boolean {\n const model = this.gridModel;\n const row = model.rows[model.rowIndices.get(address.rowId) ?? -1];\n const column = model.columns[model.columnIndices.get(address.columnId) ?? -1];\n return this.editingEnabled && !this.loading && !!row && !!column && tableEditable(row, column);\n }\n private beginCellEdit(address: TableCellAddress, initial?: string): void {\n const model = this.gridModel;\n const row = model.rows[model.rowIndices.get(address.rowId) ?? -1];\n const column = model.columns[model.columnIndices.get(address.columnId) ?? -1];\n if (!this.editingEnabled || this.loading || !row || !column || !tableEditable(row, column))\n return;\n this.activeCell = address;\n this.focusedRowId = address.rowId;\n this.editDraft = initial ?? String(row.cells[column.id] ?? '');\n this.editingCell = address;\n requestAnimationFrame(async () => {\n const control = this.el.querySelector<HTMLDsInputElement>('.ds-table__cell-editor > *');\n await control?.componentOnReady?.();\n if (this.editingCell !== address || !control?.isConnected) return;\n await control.setFocus();\n const input = control.querySelector<HTMLInputElement | HTMLTextAreaElement>('input,textarea');\n if (initial == null && input?.type !== 'number') input?.select();\n });\n }\n private handleGridKeyDown(event: KeyboardEvent): void {\n const address = this.gridAddress(event);\n if (!address || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) return;\n if (event.key === 'Enter' || event.key === 'F2' || event.key.length === 1) {\n event.preventDefault();\n this.beginCellEdit(address, event.key.length === 1 ? event.key : undefined);\n return;\n }\n if (!['ArrowDown', 'ArrowUp', 'ArrowRight', 'ArrowLeft', 'Home', 'End'].includes(event.key))\n return;\n event.preventDefault();\n const next = tableNextEditable(this.gridModel, address, event.key);\n if (!next) return;\n this.selectCell(next, event.shiftKey);\n void this.focusCell(next);\n }\n private handleGridClipboard(event: ClipboardEvent): void {\n const address = this.gridAddress(event);\n if (!address || !event.clipboardData) return;\n if (event.type === 'paste') {\n event.preventDefault();\n if (this.loading) return;\n const changes = tablePasteChanges(\n this.gridModel,\n address,\n event.clipboardData.getData('text/plain')\n );\n if (!changes) {\n this.announcement =\n 'Paste rejected. Use a rectangular set of valid values in editable cells.';\n return;\n }\n this.dsCellsChange.emit({ changes, reason: 'paste' });\n this.announcement = `${changes.length} cell changes proposed.`;\n } else {\n const model = this.gridModel;\n const bounds = tableRangeBounds(model, this.cellRange ?? { anchor: address, focus: address });\n if (\n !bounds ||\n (bounds.lastRow - bounds.firstRow + 1) * (bounds.lastColumn - bounds.firstColumn + 1) >\n 10000\n )\n return;\n const text = model.rows\n .slice(bounds.firstRow, bounds.lastRow + 1)\n .map(row =>\n model.columns\n .slice(bounds.firstColumn, bounds.lastColumn + 1)\n .map(column => {\n if (!tableEditable(row, column)) return '';\n const value = row.cells[column.id];\n return typeof value === 'object' ? '' : String(value ?? '').replace(/[\\t\\r\\n]/g, ' ');\n })\n .join('\\t')\n )\n .join('\\n');\n event.preventDefault();\n event.clipboardData.setData('text/plain', text);\n }\n }\n private renderCellEditor(row: TableRow, column: TableColumn) {\n if (\n this.editingCell?.rowId !== row.id ||\n this.editingCell.columnId !== column.id ||\n !tableEditable(row, column) ||\n this.loading\n )\n return null;\n const address = this.editingCell;\n const editor = column.editor!;\n const cell = this.findRenderedRow(row.id)?.querySelector<HTMLElement>(\n `[data-column-id=\"${CSS.escape(column.id)}\"]`\n );\n const commit = (text: string, next = address) => {\n if (this.editingCell !== address || !this.isEditableAddress(address)) return false;\n const value = tableEditValue(text, column);\n if (value === undefined) {\n this.announcement = `Enter a valid value for ${column.label}.`;\n return false;\n }\n this.editingCell = null;\n this.dsCellsChange.emit({ changes: [{ ...address, value }], reason: 'edit' });\n void this.focusCell(next);\n return true;\n };\n return (\n <div\n class=\"ds-table__cell-editor\"\n key={`${row.id}:${column.id}`}\n onClick={event => event.stopPropagation()}\n onFocusout={event => {\n const wrapper = event.currentTarget as HTMLElement;\n requestAnimationFrame(() => {\n const root = wrapper.getRootNode() as Document | ShadowRoot;\n if (this.editingCell === address && !wrapper.contains(root.activeElement))\n this.editingCell = null;\n });\n }}\n onKeyDown={event => {\n event.stopPropagation();\n if (event.isComposing || event.defaultPrevented) return;\n const wrapper = event.currentTarget as HTMLElement;\n if (event.key === 'Escape') {\n event.preventDefault();\n this.editingCell = null;\n void this.focusCell(address);\n return;\n }\n if (event.key !== 'Enter' && event.key !== 'Tab') return;\n // Picker keyboard interactions belong to the picker, including its internal Tab stops.\n if ((event.target as HTMLElement).closest('[popover]')) return;\n if (\n event.key === 'Enter' &&\n editor.type === 'textarea' &&\n !event.ctrlKey &&\n !event.metaKey\n )\n return;\n event.preventDefault();\n const input =\n editor.type === 'select'\n ? null\n : wrapper.querySelector<HTMLInputElement | HTMLTextAreaElement>('input,textarea');\n // Unconstrained numeric columns retain decimal support; explicit steps use the\n // shared control's native step validity as well as the paste validator.\n if (\n input &&\n !input.checkValidity() &&\n !(editor.type === 'number' && editor.step == null && input.validity.stepMismatch)\n ) {\n input.reportValidity();\n return;\n }\n const next =\n event.key === 'Tab'\n ? (tableNextEditable(this.gridModel, address, 'Tab', event.shiftKey) ?? address)\n : address;\n commit(input?.value ?? this.editDraft, next);\n }}\n >\n {renderTableCellEditor(\n editor,\n this.editDraft,\n `Edit ${column.label} for ${row.selectionLabel ?? row.id}`,\n cell ?? undefined,\n value => {\n this.editDraft = value;\n // A single-select choice is a complete edit; let its selection handler finish first.\n if (editor.type === 'select') queueMicrotask(() => commit(value));\n }\n )}\n </div>\n );\n }\n\n private renderCellEditTrigger(row: TableRow, column: TableColumn) {\n if (\n this.interactionMode !== 'edit' ||\n !tableEditable(row, column) ||\n this.loading ||\n (this.editingCell?.rowId === row.id && this.editingCell.columnId === column.id)\n )\n return null;\n return (\n <span class=\"ds-table__edit-trigger\">\n <ds-button-unfilled\n variant=\"icon\"\n icon=\"Pencil\"\n size=\"sm\"\n aria-label={`Edit ${column.label} for ${row.selectionLabel ?? row.id}`}\n pressScale={false}\n onDsClick={event => {\n event.stopPropagation();\n this.beginCellEdit({ rowId: row.id, columnId: column.id });\n }}\n />\n </span>\n );\n }\n\n private gridCellAttributes(row: TableRow, column: TableColumn): Record<string, unknown> {\n const model = this.gridModel;\n const bounds = tableRangeBounds(model, this.cellRange);\n const ri = model.rowIndices.get(row.id)!,\n ci = model.columnIndices.get(column.id)!;\n const editable = tableEditable(row, column) && !this.loading;\n const editing =\n editable && this.editingCell?.rowId === row.id && this.editingCell.columnId === column.id;\n const active =\n this.activeCell && this.isEditableAddress(this.activeCell)\n ? this.activeCell\n : model.firstEditable;\n if (!this.gridEnabled)\n return {\n 'data-cell-editable': String(editable),\n 'data-cell-editing': String(editing),\n 'aria-disabled': editable ? undefined : 'true',\n };\n return {\n role: 'gridcell',\n tabIndex: editable\n ? active?.rowId === row.id && active.columnId === column.id\n ? 0\n : -1\n : undefined,\n 'data-cell-editable': String(editable),\n 'data-cell-editing': String(editing),\n 'aria-readonly': String(!editable),\n 'aria-disabled': editable ? undefined : 'true',\n 'aria-selected': String(\n editable &&\n !!bounds &&\n ri >= bounds.firstRow &&\n ri <= bounds.lastRow &&\n ci >= bounds.firstColumn &&\n ci <= bounds.lastColumn\n ),\n onClick: (event: MouseEvent) => {\n if (\n event.target !== event.currentTarget &&\n (event.target as HTMLElement).closest(\n 'button,a,input,textarea,ds-button-unfilled,.ds-table__cell-editor'\n )\n )\n return;\n event.stopPropagation();\n if (!editable) return;\n this.selectCell({ rowId: row.id, columnId: column.id }, event.shiftKey);\n (event.currentTarget as HTMLElement).focus();\n if (!event.shiftKey) this.beginCellEdit({ rowId: row.id, columnId: column.id });\n },\n };\n }\n\n private readonly actionMenuElementId = nextTableActionMenuElementId();\n private structureCache?: {\n columns: TableColumn[];\n rows: TableRow[];\n spans: TableCellSpan[];\n selectable: boolean;\n grouped: boolean;\n windowed: boolean;\n grid: boolean;\n pins: ReturnType<typeof tablePinnedColumns>;\n bands: ReturnType<typeof tableHeaderBands>;\n merges: ReturnType<typeof tableSpanModel>;\n };\n\n private get structure() {\n const columns = this.visibleColumns;\n const model = this.createRenderModel();\n const cached = this.structureCache;\n const windowed = this.rowWindowingEnabled;\n const grid = this.interactionMode !== 'table';\n if (\n cached &&\n cached.columns === columns &&\n cached.rows === this.rows &&\n cached.spans === this.cellSpans &&\n cached.selectable === model.selectable &&\n cached.grouped === model.grouped &&\n cached.windowed === windowed &&\n cached.grid === grid\n )\n return cached;\n return (this.structureCache = {\n columns,\n rows: this.rows,\n spans: this.cellSpans,\n selectable: model.selectable,\n grouped: model.grouped,\n windowed,\n grid,\n pins: tablePinnedColumns(columns, model.selectable),\n bands: tableHeaderBands(columns, model.selectable, model.elasticSpacerIndex),\n merges: tableSpanModel(this.cellSpans, this.rows, columns, {\n windowed,\n grouped: model.grouped,\n grid,\n selectable: model.selectable,\n spacer: model.elasticSpacerIndex,\n }),\n });\n }\n\n private headerId(columnId: string): string {\n return `${this.actionMenuElementId}-header-${encodeURIComponent(columnId)}`;\n }\n\n private columnBandId(columnId: string): string | undefined {\n const model = this.createRenderModel();\n const index = this.visibleColumns.findIndex(column => column.id === columnId);\n const lane =\n index +\n 1 +\n Number(model.selectable) +\n Number(model.elasticSpacerIndex != null && index >= model.elasticSpacerIndex);\n const band = this.structure.bands.find(\n band => band.label && lane >= band.start && lane < band.start + band.span\n );\n return band ? `${this.actionMenuElementId}-${band.key}` : undefined;\n }\n private readonly columnCustomizerElementId = nextTableColumnCustomizerElementId();\n private readonly dataModeSwitcherElementId = nextTableDataModeSwitcherElementId();\n private truncateTooltipEl?: HTMLDsTooltipElement;\n private truncateAnchor: HTMLElement | null = null;\n private truncateTooltipBound = false;\n private focusedRowId: string | null = null;\n private virtualRenderFocus: HTMLElement | null = null;\n private virtualItems: TableVirtualItem[] = [];\n private visibleColumnsCache: {\n columns: TableColumn[];\n columnCustomizer: boolean;\n hiddenFieldIds: string[];\n fieldOrder: string[];\n pinnedFieldIds: string[];\n value: TableColumn[];\n } | null = null;\n private renderModelCache: {\n columns: TableColumn[];\n rows: TableRow[];\n groups: DataGroup[];\n grouped: boolean;\n selectionMode: TableSelectionMode;\n selectedRowIds: string[];\n collapsedGroupIds: string[];\n virtualCounts: boolean;\n value: TableRenderModel;\n } | null = null;\n private highlightMatcherCache: {\n terms: string[];\n value: TableHighlightMatcher;\n } | null = null;\n private virtualItemsCache: {\n columns: TableColumn[];\n rows: TableRow[];\n groups: DataGroup[];\n grouped: boolean;\n collapsedGroupIds: string[];\n } | null = null;\n private rootEl: HTMLElement | null = null;\n private viewportEl: HTMLElement | null = null;\n private frameEl: HTMLElement | null = null;\n private interactiveHeadEl: HTMLTableSectionElement | null = null;\n private collapseAllOverlayEl: HTMLElement | null = null;\n private stickyHeaderTableEl: HTMLTableElement | null = null;\n private tableEl: HTMLTableElement | null = null;\n private sentinelEl: HTMLElement | null = null;\n private incrementalWindowActive = false;\n private readonly groupSentinelEls = new Map<string, HTMLElement>();\n private previousModelWarning = '';\n private modelWarningQueued = false;\n private initialModelWarningFrame: number | undefined;\n private hasLoaded = false;\n private renderedModel: TableRenderModel | null = null;\n private stickyGroupConnected = false;\n private headerSlotObserver: MutationObserver | null = null;\n private footerSlotObserver: MutationObserver | null = null;\n private captionCompactDisconnect: (() => void) | undefined;\n private fitResizeObserver: ResizeObserver | null = null;\n private fitObservedViewport: HTMLElement | null = null;\n private fitObservedTable: HTMLTableElement | null = null;\n private fitMeasurementPending = false;\n private cardViewportQuery: MediaQueryList | null = null;\n private readonly bodyRenderer = new TableBodyRenderer();\n private readonly layoutController = new TableLayoutController({\n elements: () => ({\n viewport: this.viewportEl,\n contentTable: this.tableEl,\n stickyHeaderTable: this.stickyHeaderTableEl,\n collapseAllOverlay: this.collapseAllOverlayEl,\n frame: this.frameEl,\n interactiveHead: this.interactiveHeadEl,\n }),\n mode: () => ({\n documentStickyHeader: this.documentStickyHeader,\n floatingCollapseAll: this.renderedModel?.collapseAllHost?.mode === 'floating',\n clampVerticalOverscroll: this.fitViewport && this.viewportFitSettled,\n }),\n verticalEdgeWheel: deltaY => this.viewportFitController.scrollOuterBy(deltaY),\n overflowChanged: state => {\n if (state.start !== this.overflowStart) this.overflowStart = state.start;\n if (state.end !== this.overflowEnd) this.overflowEnd = state.end;\n if (state.scrollable !== this.scrollable) this.scrollable = state.scrollable;\n },\n });\n private readonly loadController = new TableLoadController({\n state: () => ({\n lazyLoading: this.dataMode === 'infinite' && !this.grouped,\n loadMoreMode: this.loadMoreMode,\n hasMore: this.hasMore,\n loadingMore: this.loadingMore,\n loadMoreError: this.loadMoreError,\n loadIdentity: this.loadIdentity,\n loadMoreThreshold: this.loadMoreThreshold,\n containedScroll: this.containedScroll,\n loadingMoreLabel: this.loadingMoreLabel,\n endOfResultsLabel: this.endOfResultsLabel,\n rowsLoadedLabel: this.rowsLoadedLabel,\n loadedRowCount: this.currentLoadedRowCount(),\n viewport: this.viewportEl,\n sentinel: this.sentinelEl,\n }),\n announce: message => {\n this.announcement = message;\n },\n request: detail => {\n this.dsLoadMore.emit(detail);\n },\n });\n private readonly groupLoadController = new TableGroupLoadController({\n state: () => ({\n enabled: this.grouped && this.dataMode !== 'virtual',\n loadMoreMode: this.loadMoreMode,\n loadMoreThreshold: this.loadMoreThreshold,\n containedScroll: this.containedScroll,\n groups: this.groups,\n viewport: this.viewportEl,\n sentinels: this.groupSentinelEls,\n loadingMoreLabel: this.groupLoadingMoreLabel,\n endOfResultsLabel: this.groupEndOfResultsLabel,\n rowsLoadedLabel: this.groupRowsLoadedLabel,\n }),\n announce: message => {\n this.announcement = message;\n },\n request: detail => {\n this.dsGroupLoadMore.emit(detail);\n },\n });\n private readonly virtualController = new TableVirtualController({\n state: () => ({\n enabled: this.rowWindowingEnabled,\n items: this.virtualItems,\n pinnedRowIds: this.virtualPinnedRowIds(),\n viewport: this.viewportEl,\n viewportSize: this.estimateVirtualViewportSize(),\n }),\n windowChanged: plan => {\n this.virtualWindow = plan;\n },\n });\n private readonly viewportFitController = new TableViewportFitController({\n enabled: () => this.fitViewport,\n elements: () => ({ host: this.el, surface: this.rootEl }),\n insets: () => ({\n blockStart: this.viewportInsetBlockStart,\n blockEnd: this.viewportInsetBlockEnd,\n }),\n fitChanged: (metrics: TableViewportFitMetrics | null) => {\n const settled = metrics?.settled ?? false;\n if (settled !== this.viewportFitSettled) this.viewportFitSettled = settled;\n },\n });\n\n componentWillLoad(): void {\n this.connectCardViewportQuery();\n // Reserve the final viewport-fit height before the first paint. The fitted\n // surface is connected after render, but the host can already resolve its\n // owning scrollport and prevent an initial auto-height frame.\n this.viewportFitController.connect();\n this.incrementalWindowActive = this.hasIncrementalState;\n this.syncHeaderSlotPresence();\n this.syncFooterSlotPresence();\n this.loadController.initialize();\n this.groupLoadController.initialize();\n }\n\n componentDidLoad(): void {\n this.hasLoaded = true;\n this.layoutController.connect();\n this.loadController.connect();\n this.groupLoadController.connect();\n this.virtualController.connect();\n this.viewportFitController.connect();\n this.syncStickyGroupConnection();\n this.connectHeaderSlotObserver();\n this.connectFooterSlotObserver();\n this.connectFitObserver();\n this.connectCaptionCompactObserver();\n this.syncFitPageSize();\n this.connectTruncateTooltip();\n this.scheduleInitialModelIssueWarning();\n }\n\n componentWillRender(): void {\n const root = this.el.getRootNode() as Document | ShadowRoot;\n const active = root.activeElement;\n this.virtualRenderFocus =\n this.rowWindowingEnabled &&\n active instanceof HTMLElement &&\n this.tableEl?.contains(active) &&\n active.closest('[data-row-id]')\n ? active\n : null;\n }\n\n componentDidRender(): void {\n // Moving a retained pooled row can clear native focus in Firefox. Restore\n // only the same connected node, without scrolling or stealing external focus.\n const retainedFocus = this.virtualRenderFocus;\n this.virtualRenderFocus = null;\n if (retainedFocus?.isConnected) {\n const root = retainedFocus.getRootNode() as Document | ShadowRoot;\n if (!root.activeElement || root.activeElement === this.el.ownerDocument.body) {\n // Resolve the moved rows' scroll geometry before restoring native focus.\n // WebKit otherwise may reveal the caret using the pre-patch layout even\n // with preventScroll. Preserve both axes within the resulting bounds.\n const viewport = this.viewportEl;\n const top = viewport?.scrollTop ?? 0;\n const left = viewport?.scrollLeft ?? 0;\n retainedFocus.focus({ preventScroll: true });\n if (viewport) {\n if (viewport.scrollTop !== top) viewport.scrollTop = top;\n if (viewport.scrollLeft !== left) viewport.scrollLeft = left;\n }\n }\n }\n this.layoutController.refresh(false);\n this.loadController.refresh();\n this.groupLoadController.refresh();\n this.virtualController.refresh();\n this.virtualController.collectMeasurements(this.tableEl);\n if (\n this.rowWindowingEnabled &&\n this.truncateAnchor &&\n this.tableEl &&\n !this.tableEl.contains(this.truncateAnchor)\n ) {\n this.dismissTruncateTooltip();\n }\n this.viewportFitController.refresh(false);\n this.syncStickyGroupConnection();\n this.connectFitObserver();\n this.connectCaptionCompactObserver();\n this.syncFitPageSize();\n if (this.stickyGroupConnected) this.updateStickyGroup();\n }\n\n /**\n * Scroll the nearest vertical owner only enough to reveal a supplied row.\n * Resolves false when the row is absent from the supplied, expanded table model.\n * This method never moves focus.\n */\n @Method()\n async scrollRowIntoView(rowId: string): Promise<boolean> {\n if (!rowId) return false;\n\n if (this.rowWindowingEnabled) {\n const headerSize = this.tableEl?.tHead?.getBoundingClientRect().height ?? 0;\n const revealed = this.virtualController.scrollRowIntoView(\n rowId,\n headerSize,\n this.stickyHeader ? headerSize : 0\n );\n if (!revealed) return false;\n await this.nextAnimationFrame();\n }\n\n const row = this.findRenderedRow(rowId);\n if (!row) return false;\n this.revealRenderedRow(row);\n return true;\n }\n\n connectedCallback(): void {\n if (!this.hasLoaded) return;\n this.connectCardViewportQuery();\n this.layoutController.connect();\n this.loadController.connect();\n this.groupLoadController.connect();\n this.virtualController.connect();\n this.viewportFitController.connect();\n this.syncStickyGroupConnection();\n this.connectHeaderSlotObserver();\n this.connectFooterSlotObserver();\n this.connectFitObserver();\n this.connectCaptionCompactObserver();\n this.connectTruncateTooltip();\n }\n\n disconnectedCallback(): void {\n this.editingCell = null;\n this.layoutController.disconnect();\n this.loadController.disconnect();\n this.groupLoadController.disconnect();\n this.virtualController.disconnect();\n this.viewportFitController.disconnect();\n this.disconnectStickyGroup();\n this.headerSlotObserver?.disconnect();\n this.headerSlotObserver = null;\n this.footerSlotObserver?.disconnect();\n this.footerSlotObserver = null;\n this.disconnectFitObserver();\n this.disconnectCaptionCompactObserver();\n this.disconnectTruncateTooltip();\n this.disconnectCardViewportQuery();\n this.closeColumnCustomizer();\n if (this.initialModelWarningFrame !== undefined) {\n cancelAnimationFrame(this.initialModelWarningFrame);\n this.initialModelWarningFrame = undefined;\n }\n }\n\n private readonly handleCardViewportChange = (event: MediaQueryListEvent): void => {\n if (this.narrowViewport !== event.matches) this.narrowViewport = event.matches;\n };\n\n private connectCardViewportQuery(): void {\n if (\n this.cardViewportQuery ||\n typeof window === 'undefined' ||\n typeof window.matchMedia !== 'function'\n )\n return;\n const query = window.matchMedia(`(max-width: ${TABLE_CARD_VIEWPORT_BREAKPOINT - 1}px)`);\n this.cardViewportQuery = query;\n const narrow = isTableCardViewport(window.innerWidth);\n if (this.narrowViewport !== narrow) this.narrowViewport = narrow;\n query.addEventListener('change', this.handleCardViewportChange);\n }\n\n private disconnectCardViewportQuery(): void {\n this.cardViewportQuery?.removeEventListener('change', this.handleCardViewportChange);\n this.cardViewportQuery = null;\n }\n\n private syncHeaderSlotPresence = () => {\n const header = this.el.querySelector<HTMLElement>('[slot=\"header\"]');\n this.headerPresent = !!header;\n this.headerUsesToolbar = header?.tagName === 'DS-DATA-TOOLBAR';\n this.captionTrailingPresent = !!this.el.querySelector('[slot=\"caption-trailing\"]');\n };\n\n private connectHeaderSlotObserver(): void {\n if (this.headerSlotObserver || typeof MutationObserver === 'undefined') return;\n this.headerSlotObserver = new MutationObserver(this.syncHeaderSlotPresence);\n this.headerSlotObserver.observe(this.el, { childList: true });\n this.syncHeaderSlotPresence();\n }\n\n private syncFooterSlotPresence = () => {\n let presence = 0;\n if (hasOwnedTableFooterSlot(this.el, 'footer-leading')) presence |= TABLE_FOOTER_SLOT_LEADING;\n if (hasOwnedTableFooterSlot(this.el, 'footer')) presence |= TABLE_FOOTER_SLOT_COPY;\n if (hasOwnedTableFooterSlot(this.el, 'footer-trailing')) presence |= TABLE_FOOTER_SLOT_TRAILING;\n if (presence !== this.footerSlotPresence) this.footerSlotPresence = presence;\n };\n\n private connectFooterSlotObserver(): void {\n if (this.footerSlotObserver || typeof MutationObserver === 'undefined') return;\n this.footerSlotObserver = new MutationObserver(this.syncFooterSlotPresence);\n this.footerSlotObserver.observe(this.el, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['slot'],\n });\n this.syncFooterSlotPresence();\n }\n\n private connectStickyGroup(): void {\n if (this.stickyGroupConnected || typeof window === 'undefined') return;\n this.stickyGroupConnected = true;\n document.addEventListener('scroll', this.updateStickyGroup, {\n capture: true,\n passive: true,\n });\n window.addEventListener('resize', this.updateStickyGroup, { passive: true });\n this.updateStickyGroup();\n }\n\n private syncStickyGroupConnection(): void {\n if (this.documentStickyHeader && this.grouped) {\n this.connectStickyGroup();\n return;\n }\n\n this.disconnectStickyGroup();\n this.frameEl?.style.removeProperty('--_table-sticky-group-top');\n if (this.activeStickyGroupId !== null) {\n this.activeStickyGroupId = null;\n }\n }\n\n private disconnectStickyGroup(): void {\n if (!this.stickyGroupConnected || typeof window === 'undefined') return;\n this.stickyGroupConnected = false;\n document.removeEventListener('scroll', this.updateStickyGroup, true);\n window.removeEventListener('resize', this.updateStickyGroup);\n }\n\n private readonly updateStickyGroup = (): void => {\n if (!this.documentStickyHeader || !this.grouped || !this.frameEl || !this.tableEl) {\n if (this.activeStickyGroupId !== null) this.activeStickyGroupId = null;\n return;\n }\n\n const stickyHeader = this.frameEl.querySelector<HTMLElement>(\n '.ds-table__document-sticky-header'\n );\n if (!stickyHeader) return;\n const threshold = stickyHeader.getBoundingClientRect().bottom;\n let activeGroupId: string | null = null;\n let activeGroupTop = threshold;\n for (const body of this.tableEl.querySelectorAll<HTMLElement>('tbody[data-group-id]')) {\n const source = body.querySelector<HTMLElement>('.ds-table__group-cell');\n if (!source) continue;\n const sourceRect = source.getBoundingClientRect();\n const bodyRect = body.getBoundingClientRect();\n if (sourceRect.top <= threshold && bodyRect.bottom > threshold) {\n activeGroupId = body.dataset.groupId ?? null;\n // A sticky section is bounded by its own row group. As that boundary\n // approaches the sticky lane, move the outgoing section bar with it so\n // the incoming source bar pushes it away instead of rendering beneath it.\n activeGroupTop = Math.min(threshold, bodyRect.bottom - sourceRect.height);\n }\n }\n\n const frameRect = this.frameEl.getBoundingClientRect();\n this.frameEl.style.setProperty(\n '--_table-sticky-group-top',\n `${activeGroupTop - frameRect.top}px`\n );\n\n if (activeGroupId !== this.activeStickyGroupId) {\n this.activeStickyGroupId = activeGroupId;\n return;\n }\n };\n\n @Watch('columns')\n @Watch('grouping')\n @Watch('hiddenFieldIds')\n @Watch('fieldOrder')\n @Watch('pinnedFieldIds')\n @Watch('columnCustomizer')\n @Watch('cellSpans')\n @Watch('interactionMode')\n @Watch('responsiveLayout')\n handleStructureChange(): void {\n this.virtualItemsCache = null;\n this.scheduleModelIssueWarning();\n this.loadController.structureChanged();\n this.groupLoadController.structureChanged();\n this.virtualController.invalidateMeasures();\n }\n\n @Watch('rows')\n @Watch('groups')\n handleDataChange(): void {\n if (this.grouped) this.groupLoadController.dataChanged();\n else this.loadController.dataChanged();\n this.scheduleModelIssueWarning();\n this.syncActionMenu();\n this.virtualController.invalidateMeasures();\n }\n\n @Watch('totalCount')\n handleTotalCountChange(): void {\n this.scheduleModelIssueWarning();\n }\n\n @Watch('caption')\n handleCaptionChange(): void {\n this.scheduleModelIssueWarning();\n }\n\n @Watch('loadIdentity')\n handleLoadIdentityChange(): void {\n this.incrementalWindowActive = this.hasIncrementalState;\n this.loadController.identityChanged();\n this.virtualController.resetToTop();\n }\n\n @Watch('sort')\n @Watch('grouping')\n handleVirtualIndexReset(): void {\n this.virtualController.resetToTop();\n }\n\n @Watch('loadMoreMode')\n @Watch('loadMoreThreshold')\n handleLazyConfigurationChange(): void {\n this.loadController.configurationChanged();\n this.groupLoadController.configurationChanged();\n }\n\n @Watch('dataMode')\n handleDataModeChange(): void {\n this.incrementalWindowActive = this.hasIncrementalState;\n this.scheduleModelIssueWarning();\n this.handleLazyConfigurationChange();\n this.virtualController.resetToTop();\n }\n\n @Watch('pagination')\n handlePaginationChange(\n pagination: TablePaginationState | null,\n previous: TablePaginationState | null\n ): void {\n if (pagination?.pageSizeMode === 'fit' && pagination.fitIdentity !== previous?.fitIdentity) {\n this.fitMeasurementPending = true;\n }\n }\n\n @Watch('loadingMore')\n handleLoadingMoreChange(loading: boolean): void {\n if (loading) this.incrementalWindowActive = true;\n if (!this.grouped) this.loadController.loadingChanged(loading);\n }\n\n @Watch('loadMoreError')\n handleLoadMoreErrorChange(error: string | undefined): void {\n if (error?.trim()) this.incrementalWindowActive = true;\n if (!this.grouped) this.loadController.errorChanged(error);\n }\n\n @Watch('hasMore')\n handleHasMoreChange(hasMore: boolean, hadMore: boolean): void {\n if (hasMore) this.incrementalWindowActive = true;\n if (!this.grouped) this.loadController.hasMoreChanged(hasMore, hadMore);\n }\n\n @Watch('columnCustomizer')\n @Watch('captionVisibility')\n handleColumnCustomizerAvailability(): void {\n if (!this.showsColumnCustomizer) {\n this.closeColumnCustomizer();\n this.columnCustomizerSurfaceOpen = false;\n }\n }\n\n @Watch('dataModeSwitcher')\n @Watch('captionVisibility')\n handleDataModeSwitcherAvailability(): void {\n if (!this.showsDataModeSwitcher) {\n this.closeDataModeSwitcher();\n this.dataModeSwitcherSurfaceOpen = false;\n }\n }\n\n @Watch('chromeLoading')\n handleChromeLoadingChange(loading: boolean): void {\n if (!loading) return;\n this.closeColumnCustomizer();\n this.closeDataModeSwitcher();\n this.columnCustomizerSurfaceOpen = false;\n this.dataModeSwitcherSurfaceOpen = false;\n }\n\n private get grouped(): boolean {\n return this.grouping !== null;\n }\n\n private get hasIncrementalState(): boolean {\n return (\n this.dataMode === 'infinite' &&\n (this.hasMore || this.loadingMore || !!this.loadMoreError?.trim())\n );\n }\n\n private get selectable(): boolean {\n return this.selectionMode === 'multiple';\n }\n\n private get visibleColumns(): TableColumn[] {\n const cached = this.visibleColumnsCache;\n if (\n cached &&\n cached.columns === this.columns &&\n cached.columnCustomizer === this.columnCustomizer &&\n cached.hiddenFieldIds === this.hiddenFieldIds &&\n cached.fieldOrder === this.fieldOrder &&\n cached.pinnedFieldIds === this.pinnedFieldIds\n ) {\n return cached.value;\n }\n const value = resolveTableVisibleColumns(this.columns, {\n columnCustomizer: this.columnCustomizer,\n hiddenFieldIds: this.hiddenFieldIds,\n fieldOrder: this.fieldOrder,\n pinnedFieldIds: this.pinnedFieldIds,\n });\n this.visibleColumnsCache = {\n columns: this.columns,\n columnCustomizer: this.columnCustomizer,\n hiddenFieldIds: this.hiddenFieldIds,\n fieldOrder: this.fieldOrder,\n pinnedFieldIds: this.pinnedFieldIds,\n value,\n };\n return value;\n }\n\n private get showsColumnCustomizer(): boolean {\n return this.columnCustomizer && this.captionVisibility === 'visible';\n }\n\n private get showsDataModeSwitcher(): boolean {\n return this.dataModeSwitcher && this.captionVisibility === 'visible';\n }\n\n private get showsCaptionTrailing(): boolean {\n return (\n this.showsDataModeSwitcher ||\n (this.showsColumnCustomizer && !this.hideColumnCustomizerTrigger) ||\n this.captionTrailingPresent\n );\n }\n\n private get documentStickyHeader(): boolean {\n return this.stickyHeader && !this.containedScroll && this.responsiveLayout !== 'cards';\n }\n\n private get fixedHeight(): boolean {\n return !this.fitViewport && this.resolvedHeight !== undefined;\n }\n\n private get boundedComposition(): boolean {\n return this.fitViewport || this.fixedHeight;\n }\n\n private get containedScroll(): boolean {\n return this.boundedComposition || this.resolvedMaxHeight !== undefined;\n }\n\n private connectFitObserver(): void {\n if (typeof ResizeObserver === 'undefined') return;\n if (this.fitObservedViewport === this.viewportEl && this.fitObservedTable === this.tableEl) {\n return;\n }\n this.disconnectFitObserver();\n this.fitObservedViewport = this.viewportEl;\n this.fitObservedTable = this.tableEl;\n this.fitResizeObserver = new ResizeObserver(this.syncFitPageSize);\n if (this.fitObservedViewport) this.fitResizeObserver.observe(this.fitObservedViewport);\n if (this.fitObservedTable) this.fitResizeObserver.observe(this.fitObservedTable);\n }\n\n private disconnectFitObserver(): void {\n this.fitResizeObserver?.disconnect();\n this.fitResizeObserver = null;\n this.fitObservedViewport = null;\n this.fitObservedTable = null;\n }\n\n private connectCaptionCompactObserver(): void {\n if (this.captionCompactDisconnect) return;\n this.captionCompactDisconnect = observeTableCaptionCompact(this.el, compact => {\n if (this.captionCompact !== compact) this.captionCompact = compact;\n });\n }\n\n private disconnectCaptionCompactObserver(): void {\n this.captionCompactDisconnect?.();\n this.captionCompactDisconnect = undefined;\n }\n\n private readonly syncFitPageSize = (): void => {\n const pagination = this.dataMode === 'pagination' ? this.pagination : null;\n if (\n !pagination?.fitToPage ||\n pagination.fitToPageInactive ||\n !this.containedScroll ||\n !this.viewportEl ||\n !this.tableEl\n ) {\n if (this.fitPageSize !== undefined) this.fitPageSize = undefined;\n this.fitMeasurementPending = false;\n return;\n }\n const header = this.tableEl.querySelector<HTMLElement>('.ds-table__head');\n const item = this.tableEl.querySelector<HTMLElement>(\n this.grouped ? '.ds-table__group-row' : '.ds-table__body .ds-table__row'\n );\n const itemBlockSize =\n item?.getBoundingClientRect().height ||\n resolveCssLengthPx(\n 'var(--ds-table-row-min-block-size, var(--dimension-size-500))',\n 0,\n this.rootEl ?? this.el\n );\n const next = resolveTableFitPageSize({\n viewportBlockSize: this.viewportEl.clientHeight,\n headerBlockSize: header?.getBoundingClientRect().height ?? 0,\n itemBlockSize,\n });\n if (next !== this.fitPageSize) this.fitPageSize = next;\n if (!this.fitMeasurementPending || pagination.pageSizeMode !== 'fit' || next === undefined) {\n return;\n }\n this.fitMeasurementPending = false;\n if (next === pagination.pageSize && pagination.pageIndex === 0) return;\n this.dsPaginationChange.emit({\n pageIndex: 0,\n pageSize: next,\n pageSizeMode: 'fit',\n totalItems: pagination.totalItems,\n pageSizeOptions: pagination.pageSizeOptions ?? [25, 50, 100, 200],\n fitToPage: true,\n fitToPageInactive: false,\n fitPageSize: next,\n fitPageSizeLabel: pagination.fitPageSizeLabel ?? 'Fit to page',\n fitPageSizeTriggerLabel: pagination.fitPageSizeTriggerLabel ?? 'Fit',\n itemLabel: pagination.itemLabel ?? 'items',\n pageSizeLabel: pagination.pageSizeLabel ?? 'Items',\n ariaLabel: pagination.ariaLabel ?? `${this.caption} pagination`,\n showFirstLastButtons: pagination.showFirstLastButtons ?? false,\n previousPageIndex: pagination.pageIndex,\n previousPageSize: pagination.pageSize,\n previousPageSizeMode: 'fit',\n reason: 'fit',\n });\n };\n\n @Listen('keydown', { target: 'window' })\n handleWindowPaginationKeyDown(event: KeyboardEvent): void {\n this.handlePaginationKeyDown(event, true);\n }\n\n private handlePaginationKeyDown(event: KeyboardEvent, fromWindow = false): void {\n const pagination = this.dataMode === 'pagination' ? this.pagination : null;\n if (\n !pagination ||\n this.loading ||\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey ||\n (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')\n ) {\n return;\n }\n\n if (paginationShortcutBlockedByPath(event.composedPath())) return;\n\n if (fromWindow) {\n const origin = event.composedPath()[0];\n const originNode = origin instanceof Text ? origin.parentNode : origin;\n if (\n !shouldHandleContainingPagePaginationShortcut({\n origin: originNode,\n table: this.el,\n eventPath: event.composedPath(),\n })\n ) {\n return;\n }\n }\n\n const state = resolvePaginationState(pagination);\n const pageIndex = event.key === 'ArrowLeft' ? state.pageIndex - 1 : state.pageIndex + 1;\n if (pageIndex < 0 || pageIndex >= state.totalPages) return;\n\n event.preventDefault();\n this.dsPaginationChange.emit({\n pageIndex,\n pageSize: state.pageSize,\n pageSizeMode: state.pageSizeMode,\n totalItems: state.totalItems,\n pageSizeOptions: state.pageSizeOptions,\n fitToPage: pagination.fitToPage ?? false,\n fitToPageInactive: pagination.fitToPageInactive ?? false,\n fitPageSize: this.fitPageSize ?? pagination.fitPageSize,\n fitPageSizeLabel: pagination.fitPageSizeLabel ?? 'Fit to page',\n fitPageSizeTriggerLabel: pagination.fitPageSizeTriggerLabel ?? 'Fit',\n itemLabel: pagination.itemLabel ?? 'items',\n pageSizeLabel: pagination.pageSizeLabel ?? 'Items',\n ariaLabel: pagination.ariaLabel ?? `${this.caption} pagination`,\n showFirstLastButtons: pagination.showFirstLastButtons ?? false,\n previousPageIndex: state.pageIndex,\n previousPageSize: state.pageSize,\n previousPageSizeMode: state.pageSizeMode,\n reason: 'page',\n });\n }\n\n private currentLoadedRows(): TableRow[] {\n return tableRows(this.rows, this.groups, this.grouped);\n }\n\n private currentLoadedRowCount(): number {\n return this.grouped\n ? this.groups.reduce((count, group) => count + group.rows.length, 0)\n : this.rows.length;\n }\n\n private createRenderModel(): TableRenderModel {\n const columns = this.visibleColumns;\n const grouped = this.grouped;\n const virtualCounts = this.dataMode === 'virtual';\n const cached = this.renderModelCache;\n if (\n cached &&\n cached.columns === columns &&\n cached.rows === this.rows &&\n cached.groups === this.groups &&\n cached.grouped === grouped &&\n cached.selectionMode === this.selectionMode &&\n cached.selectedRowIds === this.selectedRowIds &&\n cached.collapsedGroupIds === this.collapsedGroupIds &&\n cached.virtualCounts === virtualCounts\n ) {\n return cached.value;\n }\n const value = createTableRenderModel({\n columns,\n rows: this.rows,\n groups: this.groups,\n grouped,\n selectionMode: this.selectionMode,\n selectedRowIds: this.selectedRowIds,\n collapsedGroupIds: this.collapsedGroupIds,\n groupCountPresentation: virtualCounts ? 'total' : 'loaded-progress',\n });\n this.renderModelCache = {\n columns,\n rows: this.rows,\n groups: this.groups,\n grouped,\n selectionMode: this.selectionMode,\n selectedRowIds: this.selectedRowIds,\n collapsedGroupIds: this.collapsedGroupIds,\n virtualCounts,\n value,\n };\n return value;\n }\n\n private get highlightMatcher(): TableHighlightMatcher {\n if (this.highlightMatcherCache?.terms === this.highlightTerms) {\n return this.highlightMatcherCache.value;\n }\n const value = createTableHighlightMatcher(this.highlightTerms);\n this.highlightMatcherCache = { terms: this.highlightTerms, value };\n return value;\n }\n\n private get rowWindowingEnabled(): boolean {\n if (!this.hasVirtualViewportBounds) return false;\n if (this.dataMode === 'virtual') return true;\n return !this.grouped && this.currentLoadedRowCount() > TABLE_NON_VIRTUAL_WINDOW_THRESHOLD;\n }\n\n private get virtualViewportMissing(): boolean {\n return this.dataMode === 'virtual' && !this.hasVirtualViewportBounds;\n }\n\n private get hasVirtualViewportBounds(): boolean {\n return this.containedScroll && this.estimateVirtualViewportSize() > 0;\n }\n\n private estimateVirtualViewportSize(): number {\n const measured =\n this.virtualController.currentViewportSize() || this.viewportEl?.clientHeight || 0;\n const chrome =\n (this.captionVisibility === 'visible' ? 48 : 0) + (this.hasResultFooter ? 48 : 0);\n if (this.fixedHeight && this.resolvedHeight) {\n if (measured > 0) return measured;\n return Math.max(\n 0,\n resolveCssLengthPx(this.resolvedHeight, 0, this.rootEl ?? this.el) - chrome\n );\n }\n if (this.fitViewport) return Math.max(0, measured);\n if (this.resolvedMaxHeight) {\n if (this.resolvedMaxHeight.trim().toLowerCase() === 'none') return 0;\n return resolveCssLengthPx(this.resolvedMaxHeight, 0, this.rootEl ?? this.el);\n }\n return 0;\n }\n\n private virtualPinnedRowIds(): Set<string> {\n const pinned = new Set<string>();\n if (this.focusedRowId) pinned.add(this.focusedRowId);\n if (this.actionMenu?.rowId) pinned.add(this.actionMenu.rowId);\n return pinned;\n }\n\n private findRenderedRow(rowId: string): HTMLElement | null {\n return (\n [...this.el.querySelectorAll<HTMLElement>('[data-row-id]')].find(\n candidate => candidate.dataset.rowId === rowId\n ) ?? null\n );\n }\n\n private revealRenderedRow(row: HTMLElement): void {\n if (!this.containedScroll || !this.viewportEl) {\n row.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n return;\n }\n\n const viewportRect = this.viewportEl.getBoundingClientRect();\n const rowRect = row.getBoundingClientRect();\n let visibleStart = viewportRect.top;\n if (this.stickyHeader) {\n visibleStart = Math.max(\n visibleStart,\n this.tableEl?.tHead?.getBoundingClientRect().bottom ?? visibleStart\n );\n }\n const groupRow = row.closest('tbody')?.querySelector<HTMLElement>('.ds-table__group-row');\n if (groupRow && getComputedStyle(groupRow).position === 'sticky') {\n visibleStart = Math.max(visibleStart, groupRow.getBoundingClientRect().bottom);\n }\n\n if (rowRect.top < visibleStart) {\n this.viewportEl.scrollTop += rowRect.top - visibleStart;\n } else if (rowRect.bottom > viewportRect.bottom) {\n this.viewportEl.scrollTop += rowRect.bottom - viewportRect.bottom;\n }\n }\n\n private nextAnimationFrame(): Promise<void> {\n return new Promise(resolve => requestAnimationFrame(() => resolve()));\n }\n\n private syncVirtualItems(model: TableRenderModel): void {\n if (!this.rowWindowingEnabled) {\n this.virtualItems = [];\n this.virtualItemsCache = null;\n this.bodyRenderer.resetVirtualState();\n return;\n }\n const columns = this.visibleColumns;\n const cached = this.virtualItemsCache;\n if (\n cached &&\n cached.columns === columns &&\n cached.rows === this.rows &&\n cached.groups === this.groups &&\n cached.grouped === model.grouped &&\n cached.collapsedGroupIds === this.collapsedGroupIds\n ) {\n return;\n }\n this.virtualItems = flattenTableVirtualItems({\n grouped: model.grouped,\n rows: this.rows,\n groups: this.groups,\n collapsedGroupIds: this.collapsedGroupIds,\n columns,\n });\n if (this.responsiveLayout === 'cards') {\n this.virtualItems = this.virtualItems.map(item => ({ ...item, variableSize: true }));\n }\n this.virtualItemsCache = {\n columns,\n rows: this.rows,\n groups: this.groups,\n grouped: model.grouped,\n collapsedGroupIds: this.collapsedGroupIds,\n };\n }\n\n private shouldWindowRows(model: TableRenderModel): boolean {\n return (\n this.rowWindowingEnabled && (model.hasData || (model.grouped && model.groups.length > 0))\n );\n }\n\n private get resolvedMaxHeight(): string | undefined {\n if (this.maxHeight == null || this.maxHeight === '') return undefined;\n return typeof this.maxHeight === 'number' ? `${Math.max(0, this.maxHeight)}px` : this.maxHeight;\n }\n\n private get resolvedHeight(): string | undefined {\n if (this.height == null || this.height === '') return undefined;\n return typeof this.height === 'number' ? `${Math.max(0, this.height)}px` : this.height;\n }\n\n private warnModelIssues(): void {\n const issues = tableModelIssues(this.columns, this.rows, this.groups, this.grouped);\n const visibleColumns = this.visibleColumns;\n if (!this.caption?.trim()) issues.unshift('A non-empty caption is required.');\n if (this.grouping) {\n const groupingColumn = this.columns.find(column => column.id === this.grouping!.fieldId);\n if (!groupingColumn) {\n issues.push(`Grouping references unknown column id: ${this.grouping.fieldId}`);\n } else if (!visibleColumns.some(column => column.id === groupingColumn.id)) {\n issues.push(`Grouping references hidden column id: ${this.grouping.fieldId}`);\n }\n }\n if (this.sort) {\n const sortColumn = this.columns.find(\n column =>\n column.id === this.sort!.fieldId ||\n column.segments?.some(segment => segment.sortKey === this.sort!.fieldId)\n );\n if (!sortColumn) {\n issues.push(`Sorting references unknown column id: ${this.sort.fieldId}`);\n } else if (!visibleColumns.some(column => column.id === sortColumn.id)) {\n issues.push(`Sorting references hidden column id: ${this.sort.fieldId}`);\n }\n }\n if (\n this.dataMode === 'virtual' &&\n Number.isFinite(this.totalCount) &&\n Math.max(0, Math.trunc(this.totalCount!)) !== this.currentLoadedRowCount()\n ) {\n issues.push('Virtual mode requires totalCount to match the complete supplied row count.');\n }\n const stickyStart = visibleColumns.filter(column => column.sticky === 'start');\n const stickyEnd = visibleColumns.filter(column => column.sticky === 'end');\n issues.push(...this.structure.merges.issues);\n if (this.interactionMode === 'grid' && this.grouped)\n issues.push('Grid interaction requires ungrouped rows.');\n for (const column of [...stickyStart, ...stickyEnd]) {\n if (!tableColumnSize(column))\n issues.push(`Sticky column ${column.id} requires an explicit size.`);\n }\n const message = issues.join(' ');\n if (!message) {\n this.previousModelWarning = '';\n return;\n }\n if (message === this.previousModelWarning) return;\n this.previousModelWarning = message;\n console.warn(`[ds-table] ${message}`);\n }\n\n private scheduleModelIssueWarning(): void {\n if (this.modelWarningQueued) return;\n this.modelWarningQueued = true;\n queueMicrotask(() => {\n this.modelWarningQueued = false;\n this.warnModelIssues();\n });\n }\n\n private scheduleInitialModelIssueWarning(): void {\n if (this.initialModelWarningFrame !== undefined) {\n cancelAnimationFrame(this.initialModelWarningFrame);\n }\n this.initialModelWarningFrame = requestAnimationFrame(() => {\n this.initialModelWarningFrame = undefined;\n this.warnModelIssues();\n });\n }\n\n private emitSort(column: TableColumn, sortKey = column.id): void {\n if (!column.sortable) return;\n this.dsSortChange.emit({ sort: nextDataSortState(this.sort, sortKey) });\n }\n\n private sortButtonLabel(column: TableColumn, sortKey = column.id, label = column.label): string {\n if (this.sort?.fieldId !== sortKey) return `Sort ${label} ascending`;\n if (this.sort.direction === 'asc') return `Sort ${label} descending. Currently ascending.`;\n return `Sort ${label} ascending. Currently descending.`;\n }\n\n private emitRowSelection(row: TableRow): void {\n const next = toggleTableRowSelection(this.selectedRowIds, row);\n const selected = next.includes(row.id);\n this.dsSelectionChange.emit({\n selectedRowIds: next,\n scope: 'row',\n changedRowId: row.id,\n selected,\n });\n }\n\n private emitAllSelection(): void {\n const loadedRows = this.currentLoadedRows();\n const selection = deriveTableSelectionState(loadedRows, this.selectedRowIds);\n this.dsSelectionChange.emit({\n selectedRowIds: toggleAllLoadedTableRows(this.selectedRowIds, loadedRows),\n scope: 'all-loaded',\n selected: !selection.allSelected,\n });\n }\n\n private emitGroupSelection(group: DataGroup): void {\n const state = deriveTableSelectionState(group.rows, this.selectedRowIds);\n this.dsSelectionChange.emit({\n selectedRowIds: toggleTableGroupSelection(this.selectedRowIds, group.rows),\n scope: 'group',\n groupId: group.id,\n selected: !state.allSelected,\n });\n }\n\n private rowEventOwnsActivation(event: Event): boolean {\n const currentTarget = event.currentTarget;\n return !event.composedPath().some(target => {\n if (!(target instanceof HTMLElement) || target === currentTarget) return false;\n return target.matches(\n 'button, a, input, select, textarea, [role=\"button\"], [role=\"checkbox\"], [popover], ds-button-unfilled, ds-menu'\n );\n });\n }\n\n private groupRowEventOwnsCollapse(event: Event): boolean {\n const currentTarget = event.currentTarget;\n return !event.composedPath().some(target => {\n if (!(target instanceof HTMLElement) || target === currentTarget) return false;\n return target.matches(\n 'input, select, textarea, [role=\"checkbox\"], .ds-table__selection-control, .ds-table__group-selection, ds-tooltip'\n );\n });\n }\n\n private handleGroupRowClick(group: DataGroup, event: Event): void {\n if (!this.groupRowEventOwnsCollapse(event)) return;\n this.emitGroupCollapse(group);\n }\n\n private emitRowActivation(row: TableRow, event: Event): void {\n if (this.gridEnabled || row.disabled || !this.rowEventOwnsActivation(event)) return;\n if (this.selectionMode === 'multiple' && this.selectedRowIds.length > 0) {\n if (row.selectable !== false) this.emitRowSelection(row);\n return;\n }\n if (row.interactive) this.dsRowActivate.emit({ rowId: row.id });\n }\n\n private syncActionMenu(): void {\n if (!this.actionMenu) return;\n const row = tableRows(this.rows, this.groups, this.grouped).find(\n candidate => candidate.id === this.actionMenu?.rowId\n );\n const value = row && !row.disabled ? row.cells[this.actionMenu.columnId] : undefined;\n if (!isTableCellAction(value) || !isRenderableTableActionMenu(value)) {\n this.actionMenu = null;\n }\n }\n\n private closeActionMenu(): void {\n this.actionMenu = null;\n }\n\n private handleActionMenuSelect(item: MenuItemData): void {\n const open = this.actionMenu;\n const actionId = item.value;\n if (!open || !actionId || item.isInactive) return;\n this.dsCellAction.emit({\n actionId,\n rowId: open.rowId,\n columnId: open.columnId,\n });\n const triggerId = tableActionTriggerId(this.actionMenuElementId, open.rowId, open.columnId);\n this.closeActionMenu();\n requestAnimationFrame(() => {\n const trigger = this.el.querySelector<HTMLElement & { setFocus?: () => void }>(\n `#${CSS.escape(triggerId)}`\n );\n trigger?.setFocus?.();\n });\n }\n\n private toggleActionMenu(row: TableRow, column: TableColumn, event: MouseEvent): void {\n if (row.disabled) return;\n const open = this.actionMenu?.rowId === row.id && this.actionMenu?.columnId === column.id;\n this.actionMenuInitialFocusVisible = event.detail === 0;\n this.actionMenu = open ? null : { rowId: row.id, columnId: column.id };\n if (this.actionMenu) this.actionMenuSurface = this.actionMenu;\n }\n\n private renderOverflowActionMenu() {\n const open = this.actionMenu ?? this.actionMenuSurface;\n const row = open\n ? tableRows(this.rows, this.groups, this.grouped).find(\n candidate => candidate.id === open.rowId\n )\n : undefined;\n const value = row && open ? row.cells[open.columnId] : undefined;\n const menu = isTableCellAction(value) && isRenderableTableActionMenu(value) ? value : undefined;\n const sections = menu ? tableActionMenuSections(menu.items) : [];\n const triggerId = open\n ? tableActionTriggerId(this.actionMenuElementId, open.rowId, open.columnId)\n : undefined;\n\n return (\n <ds-menu\n id={this.actionMenuElementId}\n open={Boolean(this.actionMenu && sections.length)}\n anchorId={triggerId}\n align=\"end\"\n side=\"bottom\"\n menuLabel={menu?.ariaLabel ?? 'More actions'}\n initialFocusVisible={this.actionMenuInitialFocusVisible}\n sections={sections}\n onDsClose={() => this.closeActionMenu()}\n onDsAfterClose={() => {\n if (!this.actionMenu) this.actionMenuSurface = null;\n }}\n onDsSelect={event => this.handleActionMenuSelect(event.detail)}\n />\n );\n }\n\n private connectTruncateTooltip(): void {\n if (this.truncateTooltipBound) return;\n this.el.addEventListener('pointerover', this.onTruncatePointerOver);\n this.el.addEventListener('pointerout', this.onTruncatePointerOut);\n this.el.addEventListener('focusin', this.onTruncateFocusIn);\n this.el.addEventListener('focusout', this.onTruncateFocusOut);\n this.truncateTooltipBound = true;\n }\n\n private disconnectTruncateTooltip(): void {\n if (!this.truncateTooltipBound) return;\n this.el.removeEventListener('pointerover', this.onTruncatePointerOver);\n this.el.removeEventListener('pointerout', this.onTruncatePointerOut);\n this.el.removeEventListener('focusin', this.onTruncateFocusIn);\n this.el.removeEventListener('focusout', this.onTruncateFocusOut);\n this.truncateTooltipBound = false;\n this.dismissTruncateTooltip();\n }\n\n private onTruncatePointerOver = (event: PointerEvent) => {\n if (event.pointerType === 'touch') return;\n const track = resolveTableTruncateTrack(event.target);\n if (!track) return;\n this.presentOrDismissTruncateTrack(track);\n };\n\n private onTruncatePointerOut = (event: PointerEvent) => {\n if (event.pointerType === 'touch') return;\n if (resolveTableTruncateTrack(event.relatedTarget)) return;\n const next = event.relatedTarget;\n const cell = this.truncateAnchor?.closest('.ds-table__cell');\n if (cell && next instanceof Node && cell.contains(next)) return;\n this.dismissTruncateTooltip();\n };\n\n private onTruncateFocusIn = (event: FocusEvent) => {\n const track = resolveTableTruncateTrack(event.target);\n if (!track) {\n this.dismissTruncateTooltip();\n return;\n }\n this.presentOrDismissTruncateTrack(track);\n };\n\n private onTruncateFocusOut = (event: FocusEvent) => {\n if (resolveTableTruncateTrack(event.relatedTarget)) return;\n this.dismissTruncateTooltip();\n };\n\n private presentOrDismissTruncateTrack(track: HTMLElement): void {\n if (!isElementTruncated(track)) {\n this.dismissTruncateTooltip();\n return;\n }\n const label = tableTruncateLabel(track);\n if (!label) {\n this.dismissTruncateTooltip();\n return;\n }\n this.truncateAnchor = track;\n this.truncateTooltipLabel = label;\n void this.truncateTooltipEl?.presentFrom(track, label);\n }\n\n private dismissTruncateTooltip(): void {\n this.truncateAnchor = null;\n if (!this.truncateTooltipLabel && !this.truncateTooltipEl) return;\n this.truncateTooltipLabel = '';\n void this.truncateTooltipEl?.dismiss();\n }\n\n private renderTruncateTooltip() {\n return (\n <ds-tooltip\n ref={element => {\n this.truncateTooltipEl = element;\n }}\n label={this.truncateTooltipLabel}\n describedBy={false}\n wrapLabel={true}\n size=\"sm\"\n delay={0}\n side=\"top\"\n />\n );\n }\n\n private handleRowKeydown(row: TableRow, event: KeyboardEvent): void {\n if (event.target !== event.currentTarget || (event.key !== 'Enter' && event.key !== ' '))\n return;\n event.preventDefault();\n this.emitRowActivation(row, event);\n }\n\n private onVirtualFocusIn = (event: FocusEvent): void => {\n const target = event.target;\n if (!(target instanceof HTMLElement)) return;\n const row = target.closest('[data-row-id]');\n const id = row?.getAttribute('data-row-id') ?? null;\n if (id === this.focusedRowId) return;\n this.focusedRowId = id;\n if (this.rowWindowingEnabled) this.virtualController.schedule();\n };\n\n private renderSelectionControl(\n label: string,\n checked: boolean,\n indeterminate: boolean,\n disabled: boolean,\n onActivate: () => void\n ) {\n return (\n <button\n class=\"ds-table__selection-control ds-focus-ring ds-interaction-fill__content\"\n type=\"button\"\n role=\"checkbox\"\n aria-label={label}\n aria-checked={indeterminate ? 'mixed' : String(checked)}\n disabled={disabled}\n onClick={onActivate}\n >\n <ds-checkbox\n label=\"\"\n size=\"md\"\n checked={checked}\n indeterminate={indeterminate}\n presentation={true}\n />\n </button>\n );\n }\n\n private renderStickyEdge(sticky: TableColumn['sticky'], shadow = true) {\n if (!sticky) return null;\n return (\n <span\n class={{\n 'ds-table__sticky-edge': true,\n [`ds-table__sticky-edge--${sticky}`]: true,\n 'ds-table__sticky-edge--internal': !shadow,\n }}\n aria-hidden=\"true\"\n />\n );\n }\n\n private renderCollapseAllButton() {\n return (\n <ds-button-unfilled\n class=\"ds-table__collapse-all\"\n variant=\"icon\"\n icon=\"ChevronDownUp\"\n size=\"xs\"\n style={{ width: 'var(--dimension-size-300)' }}\n aria-label=\"Collapse all groups\"\n hasBorder={false}\n activeFill={false}\n pressScale={false}\n onDsClick={event => {\n event.stopPropagation();\n this.emitAllGroupsCollapse();\n }}\n />\n );\n }\n\n private renderFloatingCollapseAll(model: TableRenderModel) {\n if (model.collapseAllHost?.mode !== 'floating') return null;\n return (\n <span\n class=\"ds-table__collapse-all-overlay\"\n ref={element => {\n this.collapseAllOverlayEl = element ?? null;\n }}\n >\n <span class=\"ds-table__collapse-all-surface ds-control-elevation ds-control-elevation--md\">\n {this.renderCollapseAllButton()}\n </span>\n </span>\n );\n }\n\n private renderColumnHeader(\n column: TableColumn,\n model: TableRenderModel,\n interactive = true,\n presentational = false,\n headerLane?: { start: number; spanning: boolean }\n ) {\n const groupedColumn = this.grouping?.fieldId === column.id;\n const previousColumn = headerLane\n ? this.visibleColumns[this.visibleColumns.indexOf(column) - 1]\n : undefined;\n const segments = column.segments?.length\n ? column.segments\n : [{ label: column.label, sortKey: column.id }];\n const activeMemberSegment = segments.find(segment => segment.sortKey === this.sort?.fieldId);\n const activeMemberSort = !!activeMemberSegment;\n const activeSort = activeMemberSort;\n const align = column.align ?? 'start';\n const direction = activeMemberSort ? this.sort!.direction : undefined;\n const memberAriaSort = activeMemberSort\n ? this.sort!.direction === 'asc'\n ? 'ascending'\n : 'descending'\n : undefined;\n\n const help = column.help?.trim();\n const labels = (\n <span\n class=\"ds-table__header-labels\"\n tabIndex={interactive && help && !column.sortable ? 0 : undefined}\n data-header-help={help ? '' : undefined}\n >\n {segments.map((segment, index) => {\n const segmentActive = activeMemberSegment?.sortKey === segment.sortKey;\n const segmentInteractive = interactive && !!column.sortable;\n const label = (\n <ds-text\n class=\"ds-table__header-label-box ds-control-label-box\"\n as=\"span\"\n variant=\"text-caption\"\n emphasis={segmentActive}\n color=\"inherit\"\n decoration={help ? 'dotted-underline' : undefined}\n lineTruncation={1}\n >\n {segment.label}\n </ds-text>\n );\n const control = segmentInteractive ? (\n <button\n class=\"ds-table__header-label ds-table__header-label--interactive ds-focus-ring\"\n type=\"button\"\n aria-label={this.sortButtonLabel(\n column,\n segment.sortKey,\n segment.dataLabel?.trim() || segment.label\n )}\n data-sort-control=\"label\"\n data-sort-key={segment.sortKey}\n data-sort-active={segmentActive ? 'true' : undefined}\n onClick={() => this.emitSort(column, segment.sortKey)}\n >\n {label}\n </button>\n ) : (\n <span class=\"ds-table__header-label ds-table__header-static\">{label}</span>\n );\n\n return (\n <span class=\"ds-table__header-segment\" key={segment.sortKey}>\n {control}\n {index < segments.length - 1 && (\n <ds-text\n class=\"ds-table__header-separator\"\n as=\"span\"\n variant=\"text-caption\"\n color=\"tertiary\"\n aria-hidden=\"true\"\n >\n {segment.separator ?? '/'}\n </ds-text>\n )}\n </span>\n );\n })}\n </span>\n );\n const labelControl =\n interactive && help ? (\n <ds-tooltip label={help} side=\"top\" size=\"sm\" wrapLabel={true}>\n {labels}\n </ds-tooltip>\n ) : (\n labels\n );\n const sortControl = interactive ? (\n <span class=\"ds-table__sort-slot\">\n {activeSort && (\n <ds-button-unfilled\n class=\"ds-table__sort-direction\"\n variant=\"icon\"\n icon={direction === 'asc' ? 'ArrowUp' : 'ArrowDown'}\n size=\"xs\"\n aria-label={this.sortButtonLabel(\n column,\n activeMemberSegment?.sortKey ?? column.id,\n activeMemberSegment?.label ?? column.label\n )}\n hasBorder={false}\n activeFill={false}\n isActive={true}\n pressScale={false}\n data-sort-control=\"direction\"\n onDsClick={() => this.emitSort(column, activeMemberSegment?.sortKey ?? column.id)}\n />\n )}\n </span>\n ) : null;\n const collapseHost = model.collapseAllHost;\n const actionCollapseHost =\n collapseHost?.mode === 'action' && collapseHost.columnId === column.id;\n const blankActionCollapseHost =\n actionCollapseHost && !column.label.trim() && !column.segments?.length;\n const collapseControl =\n interactive && actionCollapseHost ? (\n <span class=\"ds-table__collapse-slot\">{this.renderCollapseAllButton()}</span>\n ) : null;\n\n return (\n <th\n key={column.id}\n id={presentational ? undefined : this.headerId(column.id)}\n headers={presentational ? undefined : this.columnBandId(column.id)}\n rowSpan={headerLane?.spanning ? 2 : undefined}\n style={{\n ...this.structure.pins.get(column.id)?.style,\n ...(headerLane\n ? {\n gridColumn: String(headerLane.start),\n gridRow: headerLane.spanning ? '1 / span 2' : '2',\n }\n : {}),\n }}\n class={{\n 'ds-table__header-cell': true,\n 'ds-table__header-cell--rowspan': !!headerLane?.spanning,\n 'ds-table__header-cell--after-rowspan':\n !!headerLane &&\n !headerLane.spanning &&\n !!previousColumn &&\n !previousColumn.group &&\n !this.structure.pins.has(previousColumn.id),\n [`ds-table__cell--align-${align}`]: true,\n 'ds-table__cell--sticky-start':\n column.sticky === 'start' && this.structure.pins.has(column.id),\n 'ds-table__cell--sticky-end':\n column.sticky === 'end' && this.structure.pins.has(column.id),\n 'ds-table__header-cell--collapse-all': actionCollapseHost,\n }}\n scope={presentational ? undefined : 'col'}\n aria-sort={presentational ? undefined : memberAriaSort}\n data-column-id={column.id}\n data-grouped={groupedColumn ? 'true' : undefined}\n data-sort-active={activeSort ? 'true' : undefined}\n >\n {!column.label.trim() && column.accessibleLabel?.trim() && (\n <span class=\"ds-visually-hidden\">{column.accessibleLabel}</span>\n )}\n {blankActionCollapseHost ? (\n <span class=\"ds-table__header-content ds-table__header-content--collapse-all\">\n {collapseControl}\n </span>\n ) : (\n <span class=\"ds-table__header-content\">\n {align === 'end' && sortControl}\n {align === 'center' && (\n <span\n class=\"ds-table__sort-slot ds-table__sort-slot--balance\"\n data-sort-balance=\"true\"\n aria-hidden=\"true\"\n />\n )}\n {labelControl}\n {align !== 'end' && sortControl}\n {collapseControl}\n </span>\n )}\n {this.renderStickyEdge(\n this.structure.pins.has(column.id) ? column.sticky : undefined,\n !!this.structure.pins.get(column.id)?.edge\n )}\n </th>\n );\n }\n\n private renderColgroup(model: TableRenderModel) {\n const beforeSpacer =\n model.elasticSpacerIndex == null\n ? this.visibleColumns\n : this.visibleColumns.slice(0, model.elasticSpacerIndex);\n const afterSpacer =\n model.elasticSpacerIndex == null ? [] : this.visibleColumns.slice(model.elasticSpacerIndex);\n const renderColumn = (column: TableColumn) => {\n const width = tableColumnSize(column);\n return (\n <col\n key={column.id}\n class={{ 'ds-table__action-column': column.kind === 'action' }}\n style={width ? { width } : undefined}\n />\n );\n };\n return (\n <colgroup>\n {model.selectable && <col class=\"ds-table__selection-column\" />}\n {beforeSpacer.map(renderColumn)}\n {model.elasticSpacerIndex != null && <col class=\"ds-table__elastic-spacer-column\" />}\n {afterSpacer.map(renderColumn)}\n </colgroup>\n );\n }\n\n private renderHeader(\n model: TableRenderModel,\n interactive = true,\n presentational = false,\n ariaRowIndex?: number\n ) {\n const selection = model.selection;\n const bands = this.structure.bands;\n const multirow = bands.length > 0;\n const controls =\n interactive &&\n !(\n this.responsiveLayout === 'cards' &&\n this.narrowViewport &&\n this.interactionMode !== 'grid' &&\n !this.cellSpans.length\n );\n const selectionHeader = model.selectable && (\n <th\n class={{\n 'ds-table__header-cell': true,\n 'ds-table__selection-cell': true,\n 'ds-table__cell--sticky-start': true,\n 'ds-table__header-cell--rowspan': multirow,\n }}\n rowSpan={multirow ? 2 : undefined}\n style={multirow ? { gridColumn: '1', gridRow: '1 / span 2' } : undefined}\n scope={presentational ? undefined : 'col'}\n >\n {controls ? (\n this.renderSelectionControl(\n selection.allSelected ? 'Deselect all loaded rows' : 'Select all loaded rows',\n selection.allSelected,\n selection.indeterminate,\n selection.selectableRowIds.length === 0,\n () => this.emitAllSelection()\n )\n ) : (\n <span class=\"ds-visually-hidden\">Select rows</span>\n )}\n {this.renderStickyEdge(\n 'start',\n ![...this.structure.pins.values()].some(pin => pin.edge === 'start')\n )}\n </th>\n );\n const lanes: (TableColumn | undefined)[] = [...this.visibleColumns];\n if (model.elasticSpacerIndex != null) lanes.splice(model.elasticSpacerIndex, 0, undefined);\n const renderLane = (column: TableColumn | undefined, index: number) => {\n const start = index + 1 + Number(model.selectable);\n if (column)\n return this.renderColumnHeader(\n column,\n model,\n controls,\n presentational,\n multirow ? { start, spanning: !column.group } : undefined\n );\n return (\n <th\n class=\"ds-table__header-cell ds-table__elastic-spacer-cell\"\n rowSpan={multirow ? 2 : undefined}\n style={multirow ? { gridColumn: String(start), gridRow: '1 / span 2' } : undefined}\n aria-hidden=\"true\"\n role=\"presentation\"\n data-elastic-spacer=\"true\"\n />\n );\n };\n return (\n <thead\n class={{\n 'ds-table__head': true,\n 'ds-table__head--multirow': multirow,\n 'ds-table__head--semantic-copy': !interactive,\n }}\n ref={element => {\n if (interactive) this.interactiveHeadEl = element ?? null;\n }}\n >\n {multirow && (\n <tr class=\"ds-table__header-row ds-table__super-header-row\" aria-rowindex={ariaRowIndex}>\n {selectionHeader}\n {bands.map(band =>\n !band.label ? (\n lanes.map((column, index) => {\n const start = index + 1 + Number(model.selectable);\n return start >= band.start && start < band.start + band.span\n ? renderLane(column, index)\n : null;\n })\n ) : (\n <th\n key={band.key}\n id={presentational ? undefined : `${this.actionMenuElementId}-${band.key}`}\n class={{\n 'ds-table__header-cell': true,\n 'ds-table__super-header-cell': true,\n 'ds-table__cell--sticky-start': band.sticky === 'start',\n 'ds-table__cell--sticky-end': band.sticky === 'end',\n }}\n scope={presentational || !band.label ? undefined : 'colgroup'}\n colSpan={band.span}\n style={{\n gridColumn: `${band.start} / span ${band.span}`,\n gridRow: '1',\n ...this.structure.pins.get(\n (band.sticky === 'end' ? band.lastColumnId : band.firstColumnId) ?? ''\n )?.style,\n }}\n aria-hidden={!band.label ? 'true' : undefined}\n >\n <span class=\"ds-table__header-content\">\n <span class=\"ds-table__header-labels\">\n <span class=\"ds-table__header-segment\">\n {/* eslint-disable-next-line compomo/prefer-direct-ds-text -- Match the normal header's structural label canvas and inner text inset. */}\n <span class=\"ds-table__header-label ds-table__header-static\">\n <ds-text\n class=\"ds-table__header-label-box ds-control-label-box\"\n as=\"span\"\n variant=\"text-caption\"\n color=\"inherit\"\n lineTruncation={1}\n >\n {band.label}\n </ds-text>\n </span>\n </span>\n </span>\n </span>\n {this.renderStickyEdge(\n band.sticky,\n !!this.structure.pins.get(\n (band.sticky === 'end' ? band.firstColumnId : band.lastColumnId) ?? ''\n )?.edge\n )}\n </th>\n )\n )}\n </tr>\n )}\n <tr\n class=\"ds-table__header-row\"\n aria-rowindex={\n ariaRowIndex == null\n ? undefined\n : ariaRowIndex + Number(this.structure.bands.length > 0)\n }\n >\n {!multirow && selectionHeader}\n {lanes.map((column, index) => (!multirow || column?.group) && renderLane(column, index))}\n </tr>\n </thead>\n );\n }\n\n private renderRow(\n row: TableRow,\n model: TableRenderModel,\n ariaRowIndex?: number,\n variableVirtualSize = false,\n rowKey = row.id\n ) {\n return renderTableRowView({\n grid: this.gridEnabled,\n cellAttributes: this.editingEnabled\n ? (targetRow, column) => this.gridCellAttributes(targetRow, column)\n : undefined,\n renderEditor: this.editingEnabled\n ? (targetRow, column) => this.renderCellEditor(targetRow, column)\n : undefined,\n renderEditTrigger: this.editingEnabled\n ? (targetRow, column) => this.renderCellEditTrigger(targetRow, column)\n : undefined,\n pins: this.structure.pins,\n spans: this.structure.merges.cells.get(row.id),\n headerId: id => this.headerId(id),\n responsiveCards: this.responsiveLayout === 'cards',\n row,\n model,\n visibleColumns: this.visibleColumns,\n emptyCellLabel: this.emptyCellLabel,\n actionMenuElementId: this.actionMenuElementId,\n actionMenu: this.actionMenu,\n actionMenuSurface: this.actionMenuSurface,\n surfaceOpenRowId: this.surfaceOpenRowId,\n highlightMatcher: this.highlightMatcher,\n highlightFieldIds: this.highlightFieldIds,\n ariaRowIndex:\n ariaRowIndex == null ? undefined : ariaRowIndex + Number(this.structure.bands.length > 0),\n variableVirtualSize,\n intrinsicBlockSize:\n this.dataMode !== 'virtual'\n ? estimateTableRowBlockSize(row, this.visibleColumns)\n : undefined,\n rowKey,\n renderSelectionControl: (label, checked, indeterminate, disabled, onActivate) =>\n this.renderSelectionControl(label, checked, indeterminate, disabled, onActivate),\n renderStickyEdge: (sticky, shadow) => this.renderStickyEdge(sticky, shadow),\n onRowActivate: (targetRow, event) => this.emitRowActivation(targetRow, event),\n onRowKeyDown: (targetRow, event) => this.handleRowKeydown(targetRow, event),\n onRowSelection: targetRow => this.emitRowSelection(targetRow),\n onCellAction: detail => this.dsCellAction.emit(detail),\n onActionMenuToggle: (targetRow, column, event) =>\n this.toggleActionMenu(targetRow, column, event),\n });\n }\n\n private emitGroupCollapse(group: DataGroup) {\n const collapsedGroupIds = toggleTableGroupCollapsed(this.collapsedGroupIds, group.id);\n this.dsGroupCollapseChange.emit({\n scope: 'group',\n groupId: group.id,\n collapsed: collapsedGroupIds.includes(group.id),\n collapsedGroupIds,\n });\n }\n\n private emitAllGroupsCollapse() {\n const groupIds = this.groups.map(group => group.id);\n const collapsedGroupIds = nextTableGroupsCollapsed(this.collapsedGroupIds, groupIds);\n this.dsGroupCollapseChange.emit({\n scope: 'all',\n collapsed: collapsedGroupIds.length > 0,\n collapsedGroupIds,\n });\n }\n\n private renderGroupAccessory(\n item: TableRenderModel['groups'][number]['accessories'][number],\n index: number\n ) {\n const text = (\n <ds-text\n key={`acc-${index}`}\n class=\"ds-table__group-accessory\"\n as=\"span\"\n variant=\"text-body-small\"\n color=\"secondary\"\n decoration={item.help ? 'dotted-underline' : undefined}\n lineTruncation={1}\n >\n {item.text}\n </ds-text>\n );\n if (!item.help) return text;\n return (\n <ds-tooltip\n key={`acc-${index}`}\n label={item.help}\n side=\"bottom\"\n align=\"start\"\n size=\"sm\"\n wrapLabel={true}\n >\n <span class=\"ds-table__group-accessory-tip\" tabIndex={0}>\n {text}\n </span>\n </ds-tooltip>\n );\n }\n\n private renderGroupContent(groupModel: TableRenderModel['groups'][number]) {\n const {\n group,\n countLabel,\n collapsed: isCollapsed,\n labelColor,\n selection: groupSelection,\n accessories,\n hero,\n } = groupModel;\n const heroTracks = hero?.kind === 'score' && hero.tracks === 2 ? 2 : 1;\n const heroPresentation = TABLE_GROUP_HERO_SCORE_PRESENTATION[heroTracks];\n return (\n <span\n class={{\n 'ds-table__group-content': true,\n 'ds-table__group-content--multi': accessories.length > 0 || heroTracks === 2,\n 'ds-table__group-content--hero': Boolean(hero),\n 'ds-table__group-content--hero-two-track': Boolean(hero) && heroTracks === 2,\n }}\n onClick={event => this.handleGroupRowClick(group, event)}\n >\n {groupSelection && (\n <span class=\"ds-table__group-selection\">\n {this.renderSelectionControl(\n groupSelection.allSelected\n ? `Deselect loaded rows in ${group.label} group`\n : `Select loaded rows in ${group.label} group`,\n groupSelection.allSelected,\n groupSelection.indeterminate,\n groupSelection.selectableRowIds.length === 0,\n () => this.emitGroupSelection(group)\n )}\n </span>\n )}\n {hero?.kind === 'score' && (\n <span class=\"ds-table__group-hero\">\n <ds-score\n size={heroPresentation.size}\n variant={heroPresentation.variant}\n value={hero.value}\n level={hero.level}\n label={hero.label ?? 'Safety score'}\n isLoading={hero.isLoading === true}\n />\n </span>\n )}\n <span class=\"ds-table__group-copy\">\n <span class=\"ds-table__group-primary\">\n <ds-text\n class=\"ds-table__group-label\"\n as=\"span\"\n variant=\"text-body-medium\"\n emphasis={true}\n color={labelColor}\n >\n {group.label}\n </ds-text>\n <span class=\"ds-visually-hidden\">{countLabel}</span>\n </span>\n {accessories.length > 0 && (\n <span class=\"ds-table__group-accessories\">\n {accessories.flatMap((item, index) => [\n ...(index > 0\n ? [\n <ds-text\n key={`sep-${index}`}\n class=\"ds-table__group-accessory-separator\"\n as=\"span\"\n variant=\"text-body-small\"\n color=\"secondary\"\n aria-hidden=\"true\"\n >\n ·\n </ds-text>,\n ]\n : []),\n this.renderGroupAccessory(item, index),\n ])}\n </span>\n )}\n </span>\n <span class=\"ds-table__group-trailing\">\n <ds-text\n class=\"ds-table__group-count\"\n as=\"span\"\n variant=\"text-body-medium\"\n color=\"secondary\"\n aria-hidden=\"true\"\n >\n {groupModel.visibleCountText}\n </ds-text>\n <span class=\"ds-table__group-action\">\n <ds-button-unfilled\n class=\"ds-table__group-toggle\"\n variant=\"icon\"\n size=\"md\"\n isInset={true}\n insetDepth=\"double\"\n icon={isCollapsed ? 'ChevronDown' : 'ChevronUp'}\n expanded={!isCollapsed}\n aria-label={\n isCollapsed ? `Expand ${group.label} group` : `Collapse ${group.label} group`\n }\n hasBorder={false}\n pressScale={false}\n />\n </span>\n </span>\n </span>\n );\n }\n\n private formatGroupLoadLabel(template: string, group: DataGroup): string {\n return template.split('{group}').join(group.label);\n }\n\n private renderGroupLoadRow(group: DataGroup, totalColumns: number) {\n const error = group.loadMoreError?.trim();\n if (!error && !group.loadingMore && !group.hasMore) return null;\n const manualFallback =\n this.loadMoreMode === 'manual' || !this.groupLoadController.intersectionSupported;\n\n return (\n <tr\n class=\"ds-table__load-row ds-table__group-load-row\"\n data-group-id={group.id}\n ref={element => {\n if (element) this.groupSentinelEls.set(group.id, element);\n else this.groupSentinelEls.delete(group.id);\n }}\n >\n <td class=\"ds-table__load-cell\" colSpan={totalColumns}>\n <div class=\"ds-table__viewport-band ds-table__load-band\">\n {renderTableLoadContent({\n error,\n loading: !!group.loadingMore,\n hasMore: !!group.hasMore,\n manualFallback,\n retryLabel: this.formatGroupLoadLabel(this.groupRetryLabel, group),\n loadingLabel: this.formatGroupLoadLabel(this.groupLoadingMoreLabel, group),\n loadMoreLabel: this.groupLoadMoreLabel,\n loadMoreAriaLabel: this.formatGroupLoadLabel(this.groupLoadMoreAriaLabel, group),\n onRetry: () => this.groupLoadController.request(group.id, 'retry'),\n onLoadMore: () => this.groupLoadController.request(group.id, 'manual'),\n })}\n </div>\n </td>\n </tr>\n );\n }\n\n private renderStickyGroup(model: TableRenderModel) {\n if (!this.documentStickyHeader || !this.activeStickyGroupId) return null;\n const groupModel = model.groups.find(item => item.group.id === this.activeStickyGroupId);\n if (!groupModel) return null;\n return (\n <div\n class={{\n 'ds-table__sticky-group': true,\n 'ds-table__sticky-group--selectable': model.selectable,\n [groupModel.intentClass ?? '']: !!groupModel.intentClass,\n }}\n data-group-id={groupModel.group.id}\n data-group-intent={groupModel.intent}\n >\n {this.renderGroupContent(groupModel)}\n </div>\n );\n }\n\n private renderDataBodies(model: TableRenderModel, plan: TableVirtualPlan | null) {\n return this.bodyRenderer.render({\n headerRowCount: 1 + Number(this.structure.bands.length > 0),\n model,\n plan,\n rows: this.rows,\n stickyHeader: this.stickyHeader,\n documentStickyHeader: this.documentStickyHeader,\n activeStickyGroupId: this.activeStickyGroupId,\n renderRow: (row, renderModel, ariaRowIndex, variableVirtualSize, rowKey) =>\n this.renderRow(row, renderModel, ariaRowIndex, variableVirtualSize, rowKey),\n renderGroupContent: groupModel => this.renderGroupContent(groupModel),\n renderGroupLoadRow: (group, totalColumns) => this.renderGroupLoadRow(group, totalColumns),\n });\n }\n\n private renderSkeletonBody(model: TableRenderModel) {\n return renderTableSkeletonBody({\n pins: this.structure.pins,\n model,\n visibleColumns: this.visibleColumns,\n skeletonRows: this.skeletonRows,\n renderStickyEdge: (sticky, shadow) => this.renderStickyEdge(sticky, shadow),\n });\n }\n\n private renderStateBody(kind: 'empty' | 'error' | 'virtual-viewport', totalColumns: number) {\n const error = kind !== 'empty';\n const heading =\n kind === 'virtual-viewport'\n ? TABLE_VIRTUAL_VIEWPORT_REQUIRED_HEADING\n : error\n ? this.errorHeading\n : this.emptyHeading;\n const body =\n kind === 'virtual-viewport'\n ? TABLE_VIRTUAL_VIEWPORT_REQUIRED_BODY\n : error\n ? this.errorBody\n : this.emptyBody;\n return (\n <tbody class=\"ds-table__body ds-table__state-body\">\n <tr class=\"ds-table__state-row\">\n <td class=\"ds-table__state-cell\" colSpan={totalColumns}>\n <div class=\"ds-table__viewport-band ds-table__state-band\">\n <ds-empty-state\n icon={error ? 'ExclamationTriangle' : 'Inbox'}\n heading={heading}\n body={body}\n />\n </div>\n </td>\n </tr>\n </tbody>\n );\n }\n\n private renderLazyBody(model: TableRenderModel) {\n if (\n this.dataMode !== 'infinite' ||\n !this.incrementalWindowActive ||\n !model.hasData ||\n model.grouped\n )\n return null;\n const error = this.loadMoreError?.trim();\n const manualFallback =\n this.loadMoreMode === 'manual' || !this.loadController.intersectionSupported;\n\n return (\n <tbody class=\"ds-table__body ds-table__load-body\">\n <tr\n class=\"ds-table__load-row\"\n ref={element => {\n this.sentinelEl = element ?? null;\n }}\n >\n <td class=\"ds-table__load-cell\" colSpan={model.totalColumns}>\n <div class=\"ds-table__viewport-band ds-table__load-band\">\n {renderTableLoadContent({\n error,\n loading: this.loadingMore,\n hasMore: this.hasMore,\n manualFallback,\n retryLabel: this.retryLabel,\n loadingLabel: this.loadingMoreLabel,\n loadMoreLabel: this.loadMoreLabel,\n endOfResultsLabel: this.endOfResultsLabel,\n onRetry: () => this.loadController.request('retry'),\n onLoadMore: () => this.loadController.request('manual'),\n })}\n </div>\n </td>\n </tr>\n </tbody>\n );\n }\n\n private renderDocumentStickyHeader(model: TableRenderModel) {\n if (!this.documentStickyHeader) return null;\n return (\n <div class=\"ds-table__document-sticky-header\">\n <table\n class={{\n 'ds-table__table': true,\n 'ds-table__sticky-header-table': true,\n 'ds-table__table--selectable': model.selectable,\n 'ds-table__table--grouped': model.grouped,\n }}\n style={model.tableStyle}\n role=\"presentation\"\n ref={element => {\n this.stickyHeaderTableEl = element ?? null;\n }}\n >\n {this.renderColgroup(model)}\n {this.renderHeader(model, true, true)}\n </table>\n {this.renderFloatingCollapseAll(model)}\n </div>\n );\n }\n\n private get resultSummary(): string | null {\n if (this.dataMode === 'pagination') return null;\n if (this.dataMode === 'virtual') {\n return formatTableTotalSummary(this.currentLoadedRowCount(), this.resultTotalSummaryLabel);\n }\n return formatTableResultSummary(this.displayedCount, this.totalCount, this.resultSummaryLabel);\n }\n\n private get hasResultFooter(): boolean {\n return (\n (this.dataMode === 'pagination' && !!this.pagination) ||\n !!this.resultSummary ||\n this.footerSlotPresence !== 0\n );\n }\n\n private renderResultFooter() {\n const summary = this.resultSummary;\n const hasLeading = (this.footerSlotPresence & TABLE_FOOTER_SLOT_LEADING) !== 0;\n const hasCopy = (this.footerSlotPresence & TABLE_FOOTER_SLOT_COPY) !== 0;\n const hasTrailing = (this.footerSlotPresence & TABLE_FOOTER_SLOT_TRAILING) !== 0;\n const pagination = this.dataMode === 'pagination' ? this.pagination : null;\n if (!this.hasResultFooter) return null;\n return (\n <div class=\"ds-table__footer ds-table__bar ds-chrome-header ds-control--md\">\n <div class=\"ds-table__bar-copy ds-chrome-header__copy ds-control--md\">\n {hasLeading && (\n <div class=\"ds-table__bar-status ds-chrome-header__heading\">\n <slot name=\"footer-leading\" onSlotchange={this.syncFooterSlotPresence} />\n </div>\n )}\n {hasCopy ? (\n <slot name=\"footer\" onSlotchange={this.syncFooterSlotPresence} />\n ) : summary ? (\n <ds-text\n class=\"ds-table__footer-summary ds-table__bar-text\"\n as=\"span\"\n variant=\"text-body-medium\"\n color=\"secondary\"\n lineTruncation={1}\n >\n {summary}\n </ds-text>\n ) : null}\n </div>\n {(pagination || hasTrailing) && (\n <div class=\"ds-table__bar-trailing ds-chrome-header__trailing\">\n {pagination && (\n <ds-pagination\n pageIndex={pagination.pageIndex}\n pageSize={pagination.pageSize}\n pageSizeMode={pagination.pageSizeMode ?? 'fixed'}\n totalItems={pagination.totalItems}\n pageSizeOptions={pagination.pageSizeOptions ?? [25, 50, 100, 200]}\n fitToPage={pagination.fitToPage ?? false}\n {...{ fitToPageInactive: pagination.fitToPageInactive ?? false }}\n fitPageSize={this.fitPageSize ?? pagination.fitPageSize}\n fitPageSizeLabel={pagination.fitPageSizeLabel ?? 'Fit to page'}\n fitPageSizeTriggerLabel={pagination.fitPageSizeTriggerLabel ?? 'Fit'}\n itemLabel={pagination.itemLabel ?? 'items'}\n pageSizeLabel={pagination.pageSizeLabel ?? 'Items'}\n label={pagination.ariaLabel ?? `${this.caption} pagination`}\n showFirstLastButtons={pagination.showFirstLastButtons ?? false}\n loading={this.loading}\n onDsChange={(event: CustomEvent<PaginationChangeDetail>) =>\n this.dsPaginationChange.emit(event.detail)\n }\n />\n )}\n <slot name=\"footer-trailing\" onSlotchange={this.syncFooterSlotPresence} />\n </div>\n )}\n </div>\n );\n }\n\n private renderCaptionBar() {\n if (this.captionVisibility !== 'visible') return null;\n return (\n <div class=\"ds-table__caption-bar ds-table__bar ds-control--md\">\n <div\n class={{\n 'ds-table__caption-content': true,\n 'ds-table__caption-content--trailing': this.showsCaptionTrailing,\n }}\n >\n <div\n class={{\n 'ds-table__caption-leading': true,\n 'ds-table__caption-leading--toolbar': this.headerUsesToolbar,\n }}\n >\n <slot name=\"header\" onSlotchange={this.syncHeaderSlotPresence} />\n {!this.headerPresent ? (\n <ds-text\n class=\"ds-table__caption-title ds-table__bar-text\"\n as=\"div\"\n variant=\"text-title-small\"\n emphasis={true}\n color=\"primary\"\n aria-hidden=\"true\"\n >\n {this.caption}\n </ds-text>\n ) : null}\n </div>\n {this.renderCaptionTrailing()}\n </div>\n <slot name=\"header-after\" />\n </div>\n );\n }\n\n private renderCaptionTrailing() {\n if (!this.showsCaptionTrailing) return null;\n return (\n <div class=\"ds-table__caption-trailing\">\n {this.renderColumnCustomizerTrigger()}\n {this.showsColumnCustomizer &&\n !this.hideColumnCustomizerTrigger &&\n this.showsDataModeSwitcher ? (\n <ds-divider orientation=\"vertical\" length=\"32px\" />\n ) : null}\n {this.renderDataModeSwitcherTrigger()}\n <slot name=\"caption-trailing\" />\n </div>\n );\n }\n\n private renderDataModeSwitcherTrigger() {\n if (!this.showsDataModeSwitcher) return null;\n if (this.chromeLoading) {\n return <ds-skeleton variant=\"control\" controlSize=\"md\" width=\"var(--dimension-size-400)\" />;\n }\n return (\n <span class=\"ds-table__caption-mode-switcher\">\n <ds-tooltip label={this.dataModeSwitcherLabel} side=\"top\" size=\"sm\">\n <ds-button-unfilled\n hasBorder={!this.captionControlsBorderless}\n id={`${this.dataModeSwitcherElementId}-trigger`}\n variant=\"icon\"\n size=\"md\"\n icon=\"Ellipses\"\n aria-label={this.dataModeSwitcherLabel}\n hasMenu={true}\n expanded={this.dataModeSwitcherOpen}\n surfaceOpen={this.dataModeSwitcherSurfaceOpen}\n controls={this.dataModeSwitcherElementId}\n activeFill={false}\n pressScale={false}\n onDsClick={(event: CustomEvent<MouseEvent>) => {\n this.toggleDataModeSwitcher(event.detail.detail === 0);\n }}\n />\n </ds-tooltip>\n </span>\n );\n }\n\n private renderDataModeSwitcherMenu() {\n if (!this.showsDataModeSwitcher || this.chromeLoading) return null;\n return (\n <ds-menu\n id={this.dataModeSwitcherElementId}\n open={this.dataModeSwitcherOpen}\n anchorId={`${this.dataModeSwitcherElementId}-trigger`}\n align=\"end\"\n side=\"bottom\"\n menuLabel={this.dataModeMenuLabel}\n initialFocusVisible={this.dataModeSwitcherInitialFocusVisible}\n items={tableDataModeMenuItems(this.dataMode, {\n infinite: this.infiniteModeLabel,\n pagination: this.paginationModeLabel,\n virtual: this.virtualModeLabel,\n })}\n onDsClose={() => this.closeDataModeSwitcher()}\n onDsAfterClose={() => {\n if (!this.dataModeSwitcherOpen) this.dataModeSwitcherSurfaceOpen = false;\n }}\n onDsSelect={event => this.handleDataModeSwitcherSelect(event.detail)}\n />\n );\n }\n\n private toggleDataModeSwitcher(fromKeyboard = false): void {\n if (this.dataModeSwitcherOpen) this.closeDataModeSwitcher();\n else this.openDataModeSwitcher(fromKeyboard);\n }\n\n private openDataModeSwitcher(fromKeyboard = false): void {\n if (!this.showsDataModeSwitcher || this.dataModeSwitcherOpen) return;\n this.closeColumnCustomizer();\n this.dataModeSwitcherInitialFocusVisible = fromKeyboard;\n this.dataModeSwitcherOpen = true;\n this.dataModeSwitcherSurfaceOpen = true;\n }\n\n private closeDataModeSwitcher(): void {\n this.dataModeSwitcherOpen = false;\n }\n\n private handleDataModeSwitcherSelect(item: MenuItemData): void {\n const dataMode = tableDataModeFromMenuItem(item);\n if (!dataMode) return;\n this.closeDataModeSwitcher();\n if (dataMode !== this.dataMode) this.dsDataModeChange.emit({ dataMode });\n requestAnimationFrame(() => {\n this.el\n .querySelector<\n HTMLElement & { setFocus?: () => void }\n >(`#${CSS.escape(`${this.dataModeSwitcherElementId}-trigger`)}`)\n ?.setFocus?.();\n });\n }\n\n private renderColumnCustomizerTrigger() {\n if (this.hideColumnCustomizerTrigger) return null;\n if (!this.showsColumnCustomizer) return null;\n return (\n <div\n class={{\n 'ds-table__caption-customizer': true,\n 'ds-table__caption-customizer--loading': this.chromeLoading,\n }}\n aria-hidden={this.chromeLoading ? 'true' : undefined}\n >\n <ds-tooltip label={this.captionCompact ? 'Customize' : ''} side=\"top\" size=\"sm\">\n <ds-button-unfilled\n hasBorder={!this.captionControlsBorderless}\n id={`${this.columnCustomizerElementId}-trigger`}\n variant={this.captionCompact ? 'icon' : 'icon-label'}\n size=\"md\"\n icon=\"Preferences\"\n label=\"Customize\"\n labelEmphasis={false}\n pressScale={false}\n aria-label=\"Customize table\"\n haspopup=\"menu\"\n expanded={this.columnCustomizerOpen}\n surfaceOpen={this.columnCustomizerSurfaceOpen}\n controls={this.columnCustomizerElementId}\n onDsClick={(event: CustomEvent<MouseEvent>) => {\n if (this.chromeLoading) return;\n this.toggleColumnCustomizer(event.detail.detail === 0);\n }}\n />\n </ds-tooltip>\n {this.chromeLoading ? (\n <ds-skeleton variant=\"control\" controlSize=\"md\" width=\"100%\" />\n ) : null}\n </div>\n );\n }\n\n private renderColumnCustomizerMenu() {\n if (!this.showsColumnCustomizer || this.chromeLoading) return null;\n return (\n <ds-menu\n id={this.columnCustomizerElementId}\n open={this.columnCustomizerOpen}\n anchorId={`${this.columnCustomizerElementId}-trigger`}\n align=\"end\"\n side=\"bottom\"\n menuLabel=\"Customize table\"\n initialFocusVisible={this.columnCustomizerInitialFocusVisible}\n sections={[\n ...tableColumnCustomizerSections(\n this.columns,\n this.hiddenFieldIds,\n this.fieldOrder,\n this.pinnedFieldIds\n ),\n ...(this.customizeOptions.length\n ? [{ header: 'Options', items: this.customizeOptions }]\n : []),\n ]}\n onDsClose={() => this.closeColumnCustomizer()}\n onDsAfterClose={() => {\n if (!this.columnCustomizerOpen) this.columnCustomizerSurfaceOpen = false;\n }}\n onDsSelect={event => {\n if (this.customizeOptions.some(option => option.value === event.detail.value)) {\n this.dsCustomizeOptionChange.emit(event.detail.value!);\n } else this.handleColumnCustomizerSelect(event.detail);\n }}\n onDsItemToggle={(event: CustomEvent<MenuItemToggleDetail>) =>\n this.handleColumnCustomizerAction(event.detail)\n }\n onDsReorder={event => this.handleColumnCustomizerReorder(event.detail)}\n />\n );\n }\n\n private toggleColumnCustomizer(fromKeyboard = false): void {\n if (this.columnCustomizerOpen) this.closeColumnCustomizer();\n else this.openColumnCustomizer(fromKeyboard);\n }\n\n private openColumnCustomizer(fromKeyboard = false): void {\n if (!this.showsColumnCustomizer || this.columnCustomizerOpen) return;\n this.closeDataModeSwitcher();\n this.columnCustomizerInitialFocusVisible = fromKeyboard;\n this.columnCustomizerOpen = true;\n this.columnCustomizerSurfaceOpen = true;\n }\n\n private closeColumnCustomizer(): void {\n this.columnCustomizerOpen = false;\n }\n\n private emitColumnsConfigChange(\n hiddenFieldIds: string[],\n fieldOrder: string[],\n pinnedFieldIds: string[] = this.pinnedFieldIds\n ): void {\n this.dsFieldsConfigChange.emit(\n resolveTableFieldsConfiguration(this.columns, hiddenFieldIds, fieldOrder, pinnedFieldIds)\n );\n }\n\n private handleColumnCustomizerReorder(detail: MenuReorderDetail): void {\n const order = detail.items\n .filter(item => item.reorderable)\n .map(item => item.value)\n .filter((id): id is string => !!id);\n this.dsFieldsConfigChange.emit(\n reorderTableColumnPartition(\n this.columns,\n this.hiddenFieldIds,\n this.fieldOrder,\n this.pinnedFieldIds,\n order\n )\n );\n }\n\n private handleColumnCustomizerAction(detail: MenuItemToggleDetail): void {\n if (detail.action?.id === 'visibility') {\n this.handleColumnCustomizerSelect(detail.item);\n return;\n }\n if (detail.action?.id !== 'pin') return;\n const fieldId = detail.item.value;\n if (!fieldId) return;\n this.dsFieldsConfigChange.emit(\n toggleTableColumnPinned(\n this.columns,\n this.hiddenFieldIds,\n this.fieldOrder,\n this.pinnedFieldIds,\n fieldId\n )\n );\n }\n\n private handleColumnCustomizerSelect(item: MenuItemData): void {\n const fieldId = item.value;\n if (!fieldId || item.isInactive) return;\n this.emitColumnsConfigChange(\n toggleTableColumnHidden(this.columns, this.hiddenFieldIds, fieldId),\n this.fieldOrder\n );\n }\n\n render() {\n this.groupSentinelEls.clear();\n const model = this.createRenderModel();\n this.syncVirtualItems(model);\n this.renderedModel = model;\n const regionLabel = this.scrollLabel?.trim() || `${this.caption} scroll area`;\n const initialLoading = this.loading && !model.hasData;\n const initialError = !model.hasData && this.error;\n const hasGroupedStructure = model.grouped && model.groups.length > 0;\n const windowRows = this.shouldWindowRows(model);\n const virtualViewportMissing =\n this.virtualViewportMissing && !initialLoading && (model.hasData || hasGroupedStructure);\n const virtualPlan = windowRows\n ? (this.virtualWindow ??\n resolveTableVirtualPlan({\n items: this.virtualItems,\n sizes: this.virtualItems.map(item => this.virtualController.sizeFor(item)),\n scrollOffset: this.viewportEl?.scrollTop ?? 0,\n viewportSize: this.estimateVirtualViewportSize(),\n pinnedRowIds: this.virtualPinnedRowIds(),\n }))\n : null;\n const groupLoadingMore = hasGroupedStructure && this.groups.some(group => group.loadingMore);\n const viewportStyle =\n !this.boundedComposition && this.resolvedMaxHeight\n ? { '--ds-table-max-block-size': this.resolvedMaxHeight }\n : undefined;\n const hostStyle = this.fixedHeight\n ? { '--_table-fixed-block-size': this.resolvedHeight }\n : undefined;\n\n return (\n <Host\n class={{\n 'table-host': true,\n 'table-host--bounded': this.boundedComposition,\n 'table-host--fixed-height': this.fixedHeight,\n 'table-host--viewport-fit': this.fitViewport,\n }}\n style={hostStyle}\n onKeyDown={(event: KeyboardEvent) => {\n this.handleGridKeyDown(event);\n this.handlePaginationKeyDown(event);\n }}\n onCopy={(event: ClipboardEvent) => this.handleGridClipboard(event)}\n onPaste={(event: ClipboardEvent) => this.handleGridClipboard(event)}\n onFocusin={this.onVirtualFocusIn}\n >\n <div\n class={{\n 'ds-table': true,\n 'ds-table--bounded': this.boundedComposition,\n 'ds-table--contained-scroll': this.containedScroll,\n 'ds-table--fixed-height': this.fixedHeight,\n 'ds-table--viewport-fit': this.fitViewport,\n 'ds-table--viewport-fit-pending': this.fitViewport && !this.viewportFitSettled,\n 'ds-table--viewport-fit-settled': this.fitViewport && this.viewportFitSettled,\n 'ds-table--sticky-header': this.stickyHeader,\n 'ds-table--document-sticky-header': this.documentStickyHeader,\n 'ds-table--contained-sticky-header': this.stickyHeader && !this.documentStickyHeader,\n 'ds-table--caption-visible': this.captionVisibility === 'visible',\n 'ds-table--chrome-edge-to-edge': this.chromeLayout === 'edge-to-edge',\n 'ds-table--super-headers': this.structure.bands.length > 0,\n 'ds-table--responsive-cards':\n this.responsiveLayout === 'cards' &&\n this.interactionMode !== 'grid' &&\n this.cellSpans.length === 0,\n 'ds-table--cards-active':\n this.narrowViewport &&\n this.responsiveLayout === 'cards' &&\n this.interactionMode !== 'grid' &&\n this.cellSpans.length === 0,\n 'ds-table--footer-visible': this.hasResultFooter,\n 'ds-table--state-fill':\n !initialLoading &&\n (initialError || virtualViewportMissing || !(model.hasData || hasGroupedStructure)),\n }}\n ref={element => {\n this.rootEl = element ?? null;\n }}\n >\n {this.renderCaptionBar()}\n <div\n class={{\n 'ds-table__frame': true,\n 'ds-table__frame--overflow-start': this.overflowStart,\n 'ds-table__frame--overflow-end': this.overflowEnd,\n }}\n data-narrow={String(this.narrowViewport)}\n ref={element => {\n this.frameEl = element ?? null;\n }}\n >\n {this.alternateView ? <slot name=\"alternate-view\" /> : null}\n {!this.alternateView && this.renderDocumentStickyHeader(model)}\n {!this.alternateView && this.renderStickyGroup(model)}\n {!this.alternateView &&\n !this.documentStickyHeader &&\n this.renderFloatingCollapseAll(model)}\n {!this.alternateView && (\n <div\n class={{\n 'ds-table__viewport': true,\n 'ds-focus-ring': this.scrollable,\n }}\n style={viewportStyle}\n ref={element => {\n this.viewportEl = element ?? null;\n }}\n role={this.scrollable ? 'region' : undefined}\n aria-label={this.scrollable ? regionLabel : undefined}\n tabIndex={this.scrollable ? 0 : undefined}\n >\n <table\n class={{\n 'ds-table__table': true,\n 'ds-table__table--selectable': model.selectable,\n 'ds-table__table--grouped': model.grouped,\n 'ds-table__table--deferred-rows':\n this.dataMode !== 'virtual' && !this.structure.merges.hasRowSpans,\n 'ds-table__table--windowed': windowRows,\n 'ds-table__table--virtual': this.dataMode === 'virtual' && windowRows,\n 'ds-table__table--native-group-sticky':\n (model.grouped && this.stickyHeader && !this.documentStickyHeader) ||\n windowRows,\n }}\n style={model.tableStyle}\n role={this.gridEnabled ? 'grid' : 'table'}\n aria-multiselectable={this.gridEnabled ? 'true' : undefined}\n aria-rowcount={\n windowRows\n ? 1 + Number(this.structure.bands.length > 0) + this.virtualItems.length\n : undefined\n }\n aria-busy={\n initialLoading ||\n (this.dataMode === 'infinite' && (this.loadingMore || groupLoadingMore))\n ? 'true'\n : undefined\n }\n ref={element => {\n this.tableEl = element ?? null;\n }}\n >\n <caption class=\"ds-table__caption ds-visually-hidden\">\n <ds-text as=\"span\" variant=\"text-title-small\" emphasis={true} color=\"primary\">\n {this.caption}\n </ds-text>\n </caption>\n {this.renderColgroup(model)}\n {this.renderHeader(\n model,\n !this.documentStickyHeader,\n false,\n windowRows ? 1 : undefined\n )}\n {initialLoading\n ? this.renderSkeletonBody(model)\n : initialError\n ? this.renderStateBody('error', model.totalColumns)\n : virtualViewportMissing\n ? this.renderStateBody('virtual-viewport', model.totalColumns)\n : model.hasData || hasGroupedStructure\n ? this.renderDataBodies(model, virtualPlan)\n : this.renderStateBody('empty', model.totalColumns)}\n {!initialLoading &&\n !initialError &&\n this.dataMode !== 'virtual' &&\n this.renderLazyBody(model)}\n </table>\n </div>\n )}\n </div>\n {this.renderResultFooter()}\n {this.renderOverflowActionMenu()}\n {this.renderDataModeSwitcherMenu()}\n {this.renderColumnCustomizerMenu()}\n {this.renderTruncateTooltip()}\n <div class=\"ds-visually-hidden\" role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">\n {this.announcement}\n </div>\n </div>\n </Host>\n );\n }\n}\n",
|
|
1716
|
+
"content": "import {\n Component,\n Element,\n Event,\n EventEmitter,\n h,\n Host,\n Listen,\n Method,\n Prop,\n State,\n Watch,\n} from '@stencil/core';\nimport {\n deriveTableSelectionState,\n formatTableResultSummary,\n formatTableTotalSummary,\n hasOwnedTableFooterSlot,\n isTableCellAction,\n nextDataSortState,\n tableColumnSize,\n tableModelIssues,\n TABLE_GROUP_HERO_SCORE_PRESENTATION,\n tableRows,\n toggleAllLoadedTableRows,\n toggleTableGroupCollapsed,\n toggleTableGroupSelection,\n nextTableGroupsCollapsed,\n toggleTableRowSelection,\n} from './table-model';\nimport { createTableRenderModel, type TableRenderModel } from './table-render-model';\nimport {\n isRenderableTableActionMenu,\n nextTableActionMenuElementId,\n tableActionMenuSections,\n tableActionTriggerId,\n} from './table-action-menu';\nimport {\n nextTableColumnCustomizerElementId,\n reorderTableColumnPartition,\n resolveTableFieldsConfiguration,\n resolveTableVisibleColumns,\n tableColumnCustomizerSections,\n toggleTableColumnHidden,\n toggleTableColumnPinned,\n} from './table-column-customizer';\nimport {\n nextTableDataModeSwitcherElementId,\n tableDataModeFromMenuItem,\n tableDataModeMenuItems,\n} from './table-data-mode-switcher';\nimport { resolveTableTruncateTrack, tableTruncateLabel } from './table-truncate';\nimport { renderTableRow as renderTableRowView } from './table-row-view';\nimport { TableBodyRenderer } from './table-body-renderer';\nimport { tableHeaderBands, tablePinnedColumns, tableSpanModel } from './table-structure';\nimport {\n tableGridModel,\n tableRangeBounds,\n tableEditable,\n tableEditValue,\n tablePasteChanges,\n tableNextEditable,\n} from './table-grid-model';\nimport { renderTableCellEditor } from './table-cell-editor';\nimport type {\n TableCellSpan,\n TableCellRange,\n TableCellAddress,\n TableCellsChangeDetail,\n} from './table-types';\nimport { renderTableSkeletonBody } from './table-skeleton-view';\nimport { renderTableLoadContent } from './table-load-view';\nimport {\n isTableCardViewport,\n TABLE_CARD_VIEWPORT_BREAKPOINT,\n TableLayoutController,\n} from './table-layout-controller';\nimport { TableLoadController } from './table-load-controller';\nimport { TableGroupLoadController } from './table-group-load-controller';\nimport {\n estimateTableRowBlockSize,\n flattenTableVirtualItems,\n resolveTableVirtualPlan,\n TABLE_VIRTUAL_TOTAL_SUMMARY_LABEL,\n TABLE_VIRTUAL_VIEWPORT_REQUIRED_BODY,\n TABLE_VIRTUAL_VIEWPORT_REQUIRED_HEADING,\n type TableVirtualItem,\n type TableVirtualPlan,\n} from './table-virtual-model';\nimport { TableVirtualController } from './table-virtual-controller';\nimport type { PaginationChangeDetail } from '../Pagination/pagination-types';\nimport type { MenuItemData, MenuItemToggleDetail, MenuReorderDetail } from '../Menu/menu-types';\nimport { resolvePaginationState } from '../Pagination/pagination-model';\nimport { resolveCssLengthPx } from '../../utils/resolve-css-length-px';\nimport { isElementTruncated } from '../../utils/is-element-truncated';\nimport { observeTableCaptionCompact } from '../../utils/table-caption-compact';\nimport { resolveTableFitPageSize } from './table-pagination-fit';\nimport { createTableHighlightMatcher, type TableHighlightMatcher } from './table-highlight';\nimport {\n paginationShortcutBlockedByPath,\n shouldHandleContainingPagePaginationShortcut,\n} from './table-pagination-shortcut';\nimport {\n TableViewportFitController,\n type TableViewportFitMetrics,\n} from './table-viewport-fit-controller';\nimport type {\n TableCaptionVisibility,\n TableChromeLayout,\n TableCellActionDetail,\n TableColumn,\n DataFieldsConfigChangeDetail,\n TableDataMode,\n TableDataModeChangeDetail,\n DataGroup,\n TableGroupCollapseChangeDetail,\n TableGroupLoadMoreDetail,\n DataGroupingState,\n TableLoadMoreDetail,\n TableLoadMoreMode,\n TablePaginationState,\n TableRow,\n TableRowActivateDetail,\n TableSelectionChangeDetail,\n TableSelectionMode,\n DataSortChangeDetail,\n DataSortState,\n} from './table-types';\n\nconst TABLE_FOOTER_SLOT_LEADING = 1;\nconst TABLE_FOOTER_SLOT_COPY = 2;\nconst TABLE_FOOTER_SLOT_TRAILING = 4;\nconst TABLE_NON_VIRTUAL_WINDOW_THRESHOLD = 50;\n\n@Component({\n tag: 'ds-table',\n styleUrls: ['../../utils/focus-ring.css', '../../utils/interaction-fill.css', 'Table.css'],\n scoped: true,\n})\nexport class Table {\n @Element() el!: HTMLElement;\n /** Stable column definitions. Assign through JavaScript. */\n @Prop() columns: TableColumn[] = [];\n /** Opt-in native card presentation below the 768px browser viewport breakpoint. */\n @Prop() responsiveLayout: 'scroll' | 'cards' = 'scroll';\n /** Keep all table chrome contained, or let the caption and footer span edge to edge around an inset data frame. */\n @Prop() chromeLayout: TableChromeLayout = 'contained';\n /** Explicit report merges; invalid combinations leave the original cells visible. */\n @Prop() cellSpans: TableCellSpan[] = [];\n /** Table is read-only; edit uses per-cell pencil buttons; grid adds cell selection and keyboard navigation. Grouped tables remain read-only. */\n @Prop() interactionMode: 'table' | 'edit' | 'grid' = 'table';\n /** Controlled rectangular cell selection, independent of row checkbox selection. */\n @Prop() cellRange: TableCellRange | null = null;\n @Event() dsCellRangeChange!: EventEmitter<TableCellRange>;\n @Event() dsCellsChange!: EventEmitter<TableCellsChangeDetail>;\n /** Additional toggle options in the column customizer. */\n @Prop() customizeOptions: MenuItemData[] = [];\n @Event() dsCustomizeOptionChange!: EventEmitter<string>;\n /** Ungrouped row data. Ignored while grouping is active. Assign through JavaScript. */\n @Prop() rows: TableRow[] = [];\n /** One level of application-owned grouped data. Assign through JavaScript. */\n @Prop() groups: DataGroup[] = [];\n /** Controlled grouping column. Applications supply groups in their final fixed order. */\n @Prop() grouping: DataGroupingState | null = null;\n /** Controlled member-row sort state. */\n @Prop() sort: DataSortState | null = null;\n /** Controlled collapsed group identities. Groups not listed remain expanded. */\n @Prop() collapsedGroupIds: string[] = [];\n /** Literal terms to highlight in table-owned text cells. Applications still own filtering. */\n @Prop() highlightTerms: string[] = [];\n /** Optional DataSearch field identities that restrict which data-point tracks are highlighted. */\n @Prop() highlightFieldIds: string[] = [];\n\n /** Required accessible table name, retained as a native caption. */\n @Prop() caption!: string;\n /** Shows a matching presentational title bar above the native table frame. */\n @Prop() captionVisibility: TableCaptionVisibility = 'hidden';\n /** Replace only the data frame with application-owned content; caption and footer remain shared. */\n @Prop() alternateView: boolean = false;\n /** Fires after a table/alternate-view switch has patched the frame and footer. */\n @Event() dsAlternateViewRendered!: EventEmitter<{ alternateView: boolean }>;\n /**\n * Opt in to the table-owned column customizer. The `columns` prop remains the\n * catalog; hidden and ordered columns are controlled separately. The trigger\n * opens the shared Menu of live show/hide switch rows.\n */\n @Prop() columnCustomizer: boolean = false;\n /** Hide only the built-in Customize trigger when an external preferences surface owns it. */\n /** Remove borders from table-owned caption controls. */\n @Prop() captionControlsBorderless: boolean = false;\n @Prop() hideColumnCustomizerTrigger: boolean = false;\n /** Controlled hidden data-column identities. Action ids are ignored. */\n @Prop() hiddenFieldIds: string[] = [];\n /** Controlled data-column identities in display order. Omitted ids append in catalog order. */\n @Prop() fieldOrder: string[] = [];\n /** Controlled user-pinned data-column identities. Hidden columns retain their pin state. */\n @Prop() pinnedFieldIds: string[] = [];\n /**\n * Optional result summary footer. When both `displayedCount` and `totalCount`\n * are finite numbers, infinite mode shows “Displaying {displayed} of {total}”.\n * Virtual mode ignores `displayedCount` and derives its total from the\n * complete supplied rows; a mismatched `totalCount` emits a warning.\n */\n @Prop() displayedCount: number | undefined;\n @Prop() totalCount: number | undefined;\n /** Supports {displayed} and {total} placeholders. */\n @Prop() resultSummaryLabel: string = 'Displaying {displayed} of {total}';\n /** Supports the {total} placeholder. Used when dataMode is virtual. */\n @Prop() resultTotalSummaryLabel: string = TABLE_VIRTUAL_TOTAL_SUMMARY_LABEL;\n @Prop() stickyHeader: boolean = false;\n /** Maximum scroll-region height. Numbers resolve to CSS pixels. */\n @Prop() maxHeight: string | number | undefined;\n /** Fixed height for the complete header, table frame, and footer composition. */\n @Prop() height: string | number | undefined;\n /** Fit the complete table composition to its nearest vertical scrollport. */\n @Prop() fitViewport: boolean = false;\n /** Reserved space above a viewport-fitted table once surrounding chrome is compact. */\n @Prop() viewportInsetBlockStart: string | number = 0;\n /** Reserved space below a viewport-fitted table. */\n @Prop() viewportInsetBlockEnd: string | number = 0;\n /** Optional explicit label for the horizontal/vertical scroll region. */\n @Prop() scrollLabel: string | undefined;\n\n @Prop() selectionMode: TableSelectionMode = 'none';\n /** Controlled selected row identities. IDs outside the loaded rows are preserved. */\n @Prop() selectedRowIds: string[] = [];\n\n /**\n * Identity of the interactive row whose associated surface is visible.\n * Holds its pressed wash independently of checkbox selection. Keep the ID\n * through exit motion and clear it after close; the application owns toggling\n * and switching the surface. Off-window identities survive virtualization.\n */\n @Prop() surfaceOpenRowId: string | undefined;\n\n /** Initial loading state. Existing rows stay visible; incremental loading uses loadingMore. */\n @Prop() loading: boolean = false;\n /** Replace opted-in table-owned caption controls with same-size visual skeletons. */\n @Prop() chromeLoading: boolean = false;\n /** Initial-loading rows. Defaults to ten so bounded tables retain a useful filled viewport. */\n @Prop() skeletonRows: number = 10;\n @Prop() emptyHeading: string = 'No results';\n @Prop() emptyBody: string = 'No data is available.';\n /** Initial error state. Existing rows stay visible; incremental failures use loadMoreError. */\n @Prop() error: boolean = false;\n @Prop() errorHeading: string = 'Unable to load data';\n @Prop() errorBody: string = 'The data could not be loaded.';\n @Prop() emptyCellLabel: string = 'Not available';\n\n /** Top-level data-window strategy. Virtual mode recycles row DOM only. */\n @Prop() dataMode: TableDataMode = 'infinite';\n /** Opt in to the table-owned control for choosing between supported data modes. */\n @Prop() dataModeSwitcher: boolean = false;\n @Prop() dataModeSwitcherLabel: string = 'Change table variation';\n @Prop() dataModeMenuLabel: string = 'Table variation';\n @Prop() infiniteModeLabel: string = 'Infinite scroll';\n @Prop() paginationModeLabel: string = 'Pagination + Infinite groups';\n @Prop() virtualModeLabel: string = 'Virtual scroll';\n /** Controlled top-level pagination state. Required when dataMode is pagination. */\n @Prop() pagination: TablePaginationState | null = null;\n @Prop() loadMoreMode: TableLoadMoreMode = 'auto';\n @Prop() hasMore: boolean = false;\n @Prop() loadingMore: boolean = false;\n @Prop() loadMoreError: string | undefined;\n /** Reset key for a new query/group/sort dataset. */\n @Prop() loadIdentity: string | number = 'default';\n /** IntersectionObserver root margin in CSS pixels. */\n @Prop() loadMoreThreshold: number = 0;\n @Prop() loadMoreLabel: string = 'Load more';\n @Prop() retryLabel: string = 'Retry';\n @Prop() loadingMoreLabel: string = 'Loading more items';\n @Prop() endOfResultsLabel: string = 'All results loaded';\n /** Supports {count} and {total} placeholders. */\n @Prop() rowsLoadedLabel: string = '{count} more rows loaded. {total} rows loaded.';\n @Prop() groupLoadMoreLabel: string = 'Load more';\n /** Supports the {group} placeholder. */\n @Prop() groupLoadMoreAriaLabel: string = 'Load more {group} results';\n /** Supports the {group} placeholder. */\n @Prop() groupRetryLabel: string = 'Retry loading {group} results';\n /** Supports the {group} placeholder. */\n @Prop() groupLoadingMoreLabel: string = 'Loading more items';\n /** Supports the {group} placeholder. */\n @Prop() groupEndOfResultsLabel: string = 'All {group} results loaded';\n /** Supports {group}, {count}, {loaded}, and {total} placeholders. */\n @Prop() groupRowsLoadedLabel: string =\n '{count} more rows loaded in {group}. {loaded} of {total} rows loaded.';\n\n @Event() dsSortChange!: EventEmitter<DataSortChangeDetail>;\n @Event() dsGroupCollapseChange!: EventEmitter<TableGroupCollapseChangeDetail>;\n @Event() dsSelectionChange!: EventEmitter<TableSelectionChangeDetail>;\n @Event() dsLoadMore!: EventEmitter<TableLoadMoreDetail>;\n @Event() dsGroupLoadMore!: EventEmitter<TableGroupLoadMoreDetail>;\n @Event() dsPaginationChange!: EventEmitter<PaginationChangeDetail>;\n @Event() dsCellAction!: EventEmitter<TableCellActionDetail>;\n @Event() dsRowActivate!: EventEmitter<TableRowActivateDetail>;\n @Event() dsFieldsConfigChange!: EventEmitter<DataFieldsConfigChangeDetail>;\n @Event() dsDataModeChange!: EventEmitter<TableDataModeChangeDetail>;\n\n @State() private overflowStart = false;\n @State() private overflowEnd = false;\n @State() private scrollable = false;\n @State() private announcement = '';\n @State() private activeStickyGroupId: string | null = null;\n @State() private viewportFitSettled = false;\n @State() private headerPresent = false;\n @State() private headerUsesToolbar = false;\n @State() private captionTrailingPresent = false;\n @State() private footerSlotPresence = 0;\n @State() private fitPageSize: number | undefined;\n @State() private actionMenu: { rowId: string; columnId: string } | null = null;\n @State() private actionMenuInitialFocusVisible = false;\n @State() private actionMenuSurface: { rowId: string; columnId: string } | null = null;\n @State() private truncateTooltipLabel = '';\n @State() private captionCompact = false;\n @State() private narrowViewport = false;\n @State() private columnCustomizerOpen = false;\n @State() private columnCustomizerSurfaceOpen = false;\n @State() private columnCustomizerInitialFocusVisible = false;\n @State() private dataModeSwitcherOpen = false;\n @State() private dataModeSwitcherSurfaceOpen = false;\n @State() private dataModeSwitcherInitialFocusVisible = false;\n @State() private virtualWindow: TableVirtualPlan | null = null;\n @State() private activeCell: TableCellAddress | null = null;\n @State() private editingCell: TableCellAddress | null = null;\n private editDraft = '';\n private gridModelCache?: ReturnType<typeof tableGridModel>;\n private get gridEnabled(): boolean {\n return this.interactionMode === 'grid' && !this.grouped;\n }\n private get editingEnabled(): boolean {\n return this.interactionMode !== 'table' && !this.grouped;\n }\n private get gridModel() {\n if (\n !this.gridModelCache ||\n this.gridModelCache.rows !== this.rows ||\n this.gridModelCache.columns !== this.visibleColumns\n ) {\n this.gridModelCache = tableGridModel(this.rows, this.visibleColumns);\n }\n return this.gridModelCache;\n }\n private gridAddress(event: Event): TableCellAddress | null {\n if (\n !this.gridEnabled ||\n !(event.target instanceof HTMLElement) ||\n !event.target.matches('td[role=\"gridcell\"][data-cell-editable=\"true\"]')\n )\n return null;\n const rowId = event.target.closest<HTMLElement>('[data-row-id]')?.dataset.rowId;\n const columnId = event.target.dataset.columnId;\n return rowId && columnId ? { rowId, columnId } : null;\n }\n private selectCell(address: TableCellAddress, extend = false): void {\n if (!this.isEditableAddress(address)) return;\n this.activeCell = address;\n this.dsCellRangeChange.emit({\n anchor: extend ? (this.cellRange?.anchor ?? address) : address,\n focus: address,\n });\n }\n private async focusCell(address: TableCellAddress): Promise<void> {\n if (!this.isEditableAddress(address)) return;\n this.activeCell = address;\n this.focusedRowId = address.rowId;\n await this.scrollRowIntoView(address.rowId);\n await this.nextAnimationFrame();\n const cell = this.findRenderedRow(address.rowId)?.querySelector<HTMLElement>(\n `[data-column-id=\"${CSS.escape(address.columnId)}\"]`\n );\n if (this.gridEnabled) cell?.focus();\n else\n await cell\n ?.querySelector<HTMLDsButtonUnfilledElement>('.ds-table__edit-trigger ds-button-unfilled')\n ?.setFocus();\n }\n private isEditableAddress(address: TableCellAddress): boolean {\n const model = this.gridModel;\n const row = model.rows[model.rowIndices.get(address.rowId) ?? -1];\n const column = model.columns[model.columnIndices.get(address.columnId) ?? -1];\n return this.editingEnabled && !this.loading && !!row && !!column && tableEditable(row, column);\n }\n private beginCellEdit(address: TableCellAddress, initial?: string): void {\n const model = this.gridModel;\n const row = model.rows[model.rowIndices.get(address.rowId) ?? -1];\n const column = model.columns[model.columnIndices.get(address.columnId) ?? -1];\n if (!this.editingEnabled || this.loading || !row || !column || !tableEditable(row, column))\n return;\n this.activeCell = address;\n this.focusedRowId = address.rowId;\n this.editDraft = initial ?? String(row.cells[column.id] ?? '');\n this.editingCell = address;\n requestAnimationFrame(async () => {\n const control = this.el.querySelector<HTMLDsInputElement>('.ds-table__cell-editor > *');\n await control?.componentOnReady?.();\n if (this.editingCell !== address || !control?.isConnected) return;\n await control.setFocus();\n const input = control.querySelector<HTMLInputElement | HTMLTextAreaElement>('input,textarea');\n if (initial == null && input?.type !== 'number') input?.select();\n });\n }\n private handleGridKeyDown(event: KeyboardEvent): void {\n const address = this.gridAddress(event);\n if (!address || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) return;\n if (event.key === 'Enter' || event.key === 'F2' || event.key.length === 1) {\n event.preventDefault();\n this.beginCellEdit(address, event.key.length === 1 ? event.key : undefined);\n return;\n }\n if (!['ArrowDown', 'ArrowUp', 'ArrowRight', 'ArrowLeft', 'Home', 'End'].includes(event.key))\n return;\n event.preventDefault();\n const next = tableNextEditable(this.gridModel, address, event.key);\n if (!next) return;\n this.selectCell(next, event.shiftKey);\n void this.focusCell(next);\n }\n private handleGridClipboard(event: ClipboardEvent): void {\n const address = this.gridAddress(event);\n if (!address || !event.clipboardData) return;\n if (event.type === 'paste') {\n event.preventDefault();\n if (this.loading) return;\n const changes = tablePasteChanges(\n this.gridModel,\n address,\n event.clipboardData.getData('text/plain')\n );\n if (!changes) {\n this.announcement =\n 'Paste rejected. Use a rectangular set of valid values in editable cells.';\n return;\n }\n this.dsCellsChange.emit({ changes, reason: 'paste' });\n this.announcement = `${changes.length} cell changes proposed.`;\n } else {\n const model = this.gridModel;\n const bounds = tableRangeBounds(model, this.cellRange ?? { anchor: address, focus: address });\n if (\n !bounds ||\n (bounds.lastRow - bounds.firstRow + 1) * (bounds.lastColumn - bounds.firstColumn + 1) >\n 10000\n )\n return;\n const text = model.rows\n .slice(bounds.firstRow, bounds.lastRow + 1)\n .map(row =>\n model.columns\n .slice(bounds.firstColumn, bounds.lastColumn + 1)\n .map(column => {\n if (!tableEditable(row, column)) return '';\n const value = row.cells[column.id];\n return typeof value === 'object' ? '' : String(value ?? '').replace(/[\\t\\r\\n]/g, ' ');\n })\n .join('\\t')\n )\n .join('\\n');\n event.preventDefault();\n event.clipboardData.setData('text/plain', text);\n }\n }\n private renderCellEditor(row: TableRow, column: TableColumn) {\n if (\n this.editingCell?.rowId !== row.id ||\n this.editingCell.columnId !== column.id ||\n !tableEditable(row, column) ||\n this.loading\n )\n return null;\n const address = this.editingCell;\n const editor = column.editor!;\n const cell = this.findRenderedRow(row.id)?.querySelector<HTMLElement>(\n `[data-column-id=\"${CSS.escape(column.id)}\"]`\n );\n const commit = (text: string, next = address) => {\n if (this.editingCell !== address || !this.isEditableAddress(address)) return false;\n const value = tableEditValue(text, column);\n if (value === undefined) {\n this.announcement = `Enter a valid value for ${column.label}.`;\n return false;\n }\n this.editingCell = null;\n this.dsCellsChange.emit({ changes: [{ ...address, value }], reason: 'edit' });\n void this.focusCell(next);\n return true;\n };\n return (\n <div\n class=\"ds-table__cell-editor\"\n key={`${row.id}:${column.id}`}\n onClick={event => event.stopPropagation()}\n onFocusout={event => {\n const wrapper = event.currentTarget as HTMLElement;\n requestAnimationFrame(() => {\n const root = wrapper.getRootNode() as Document | ShadowRoot;\n if (this.editingCell === address && !wrapper.contains(root.activeElement))\n this.editingCell = null;\n });\n }}\n onKeyDown={event => {\n event.stopPropagation();\n if (event.isComposing || event.defaultPrevented) return;\n const wrapper = event.currentTarget as HTMLElement;\n if (event.key === 'Escape') {\n event.preventDefault();\n this.editingCell = null;\n void this.focusCell(address);\n return;\n }\n if (event.key !== 'Enter' && event.key !== 'Tab') return;\n // Picker keyboard interactions belong to the picker, including its internal Tab stops.\n if ((event.target as HTMLElement).closest('[popover]')) return;\n if (\n event.key === 'Enter' &&\n editor.type === 'textarea' &&\n !event.ctrlKey &&\n !event.metaKey\n )\n return;\n event.preventDefault();\n const input =\n editor.type === 'select'\n ? null\n : wrapper.querySelector<HTMLInputElement | HTMLTextAreaElement>('input,textarea');\n // Unconstrained numeric columns retain decimal support; explicit steps use the\n // shared control's native step validity as well as the paste validator.\n if (\n input &&\n !input.checkValidity() &&\n !(editor.type === 'number' && editor.step == null && input.validity.stepMismatch)\n ) {\n input.reportValidity();\n return;\n }\n const next =\n event.key === 'Tab'\n ? (tableNextEditable(this.gridModel, address, 'Tab', event.shiftKey) ?? address)\n : address;\n commit(input?.value ?? this.editDraft, next);\n }}\n >\n {renderTableCellEditor(\n editor,\n this.editDraft,\n `Edit ${column.label} for ${row.selectionLabel ?? row.id}`,\n cell ?? undefined,\n value => {\n this.editDraft = value;\n // A single-select choice is a complete edit; let its selection handler finish first.\n if (editor.type === 'select') queueMicrotask(() => commit(value));\n }\n )}\n </div>\n );\n }\n\n private renderCellEditTrigger(row: TableRow, column: TableColumn) {\n if (\n this.interactionMode !== 'edit' ||\n !tableEditable(row, column) ||\n this.loading ||\n (this.editingCell?.rowId === row.id && this.editingCell.columnId === column.id)\n )\n return null;\n return (\n <span class=\"ds-table__edit-trigger\">\n <ds-button-unfilled\n variant=\"icon\"\n icon=\"Pencil\"\n size=\"sm\"\n aria-label={`Edit ${column.label} for ${row.selectionLabel ?? row.id}`}\n pressScale={false}\n onDsClick={event => {\n event.stopPropagation();\n this.beginCellEdit({ rowId: row.id, columnId: column.id });\n }}\n />\n </span>\n );\n }\n\n private gridCellAttributes(row: TableRow, column: TableColumn): Record<string, unknown> {\n const model = this.gridModel;\n const bounds = tableRangeBounds(model, this.cellRange);\n const ri = model.rowIndices.get(row.id)!,\n ci = model.columnIndices.get(column.id)!;\n const editable = tableEditable(row, column) && !this.loading;\n const editing =\n editable && this.editingCell?.rowId === row.id && this.editingCell.columnId === column.id;\n const active =\n this.activeCell && this.isEditableAddress(this.activeCell)\n ? this.activeCell\n : model.firstEditable;\n if (!this.gridEnabled)\n return {\n 'data-cell-editable': String(editable),\n 'data-cell-editing': String(editing),\n 'aria-disabled': editable ? undefined : 'true',\n };\n return {\n role: 'gridcell',\n tabIndex: editable\n ? active?.rowId === row.id && active.columnId === column.id\n ? 0\n : -1\n : undefined,\n 'data-cell-editable': String(editable),\n 'data-cell-editing': String(editing),\n 'aria-readonly': String(!editable),\n 'aria-disabled': editable ? undefined : 'true',\n 'aria-selected': String(\n editable &&\n !!bounds &&\n ri >= bounds.firstRow &&\n ri <= bounds.lastRow &&\n ci >= bounds.firstColumn &&\n ci <= bounds.lastColumn\n ),\n onClick: (event: MouseEvent) => {\n if (\n event.target !== event.currentTarget &&\n (event.target as HTMLElement).closest(\n 'button,a,input,textarea,ds-button-unfilled,.ds-table__cell-editor'\n )\n )\n return;\n event.stopPropagation();\n if (!editable) return;\n this.selectCell({ rowId: row.id, columnId: column.id }, event.shiftKey);\n (event.currentTarget as HTMLElement).focus();\n if (!event.shiftKey) this.beginCellEdit({ rowId: row.id, columnId: column.id });\n },\n };\n }\n\n private readonly actionMenuElementId = nextTableActionMenuElementId();\n private structureCache?: {\n columns: TableColumn[];\n rows: TableRow[];\n spans: TableCellSpan[];\n selectable: boolean;\n grouped: boolean;\n windowed: boolean;\n grid: boolean;\n pins: ReturnType<typeof tablePinnedColumns>;\n bands: ReturnType<typeof tableHeaderBands>;\n merges: ReturnType<typeof tableSpanModel>;\n };\n\n private get structure() {\n const columns = this.visibleColumns;\n const model = this.createRenderModel();\n const cached = this.structureCache;\n const windowed = this.rowWindowingEnabled;\n const grid = this.interactionMode !== 'table';\n if (\n cached &&\n cached.columns === columns &&\n cached.rows === this.rows &&\n cached.spans === this.cellSpans &&\n cached.selectable === model.selectable &&\n cached.grouped === model.grouped &&\n cached.windowed === windowed &&\n cached.grid === grid\n )\n return cached;\n return (this.structureCache = {\n columns,\n rows: this.rows,\n spans: this.cellSpans,\n selectable: model.selectable,\n grouped: model.grouped,\n windowed,\n grid,\n pins: tablePinnedColumns(columns, model.selectable),\n bands: tableHeaderBands(columns, model.selectable, model.elasticSpacerIndex),\n merges: tableSpanModel(this.cellSpans, this.rows, columns, {\n windowed,\n grouped: model.grouped,\n grid,\n selectable: model.selectable,\n spacer: model.elasticSpacerIndex,\n }),\n });\n }\n\n private headerId(columnId: string): string {\n return `${this.actionMenuElementId}-header-${encodeURIComponent(columnId)}`;\n }\n\n private columnBandId(columnId: string): string | undefined {\n const model = this.createRenderModel();\n const index = this.visibleColumns.findIndex(column => column.id === columnId);\n const lane =\n index +\n 1 +\n Number(model.selectable) +\n Number(model.elasticSpacerIndex != null && index >= model.elasticSpacerIndex);\n const band = this.structure.bands.find(\n band => band.label && lane >= band.start && lane < band.start + band.span\n );\n return band ? `${this.actionMenuElementId}-${band.key}` : undefined;\n }\n private readonly columnCustomizerElementId = nextTableColumnCustomizerElementId();\n private readonly dataModeSwitcherElementId = nextTableDataModeSwitcherElementId();\n private truncateTooltipEl?: HTMLDsTooltipElement;\n private truncateAnchor: HTMLElement | null = null;\n private truncateTooltipBound = false;\n private focusedRowId: string | null = null;\n private virtualRenderFocus: HTMLElement | null = null;\n private renderedAlternateView: boolean | null = null;\n private virtualItems: TableVirtualItem[] = [];\n private visibleColumnsCache: {\n columns: TableColumn[];\n columnCustomizer: boolean;\n hiddenFieldIds: string[];\n fieldOrder: string[];\n pinnedFieldIds: string[];\n value: TableColumn[];\n } | null = null;\n private renderModelCache: {\n columns: TableColumn[];\n rows: TableRow[];\n groups: DataGroup[];\n grouped: boolean;\n selectionMode: TableSelectionMode;\n selectedRowIds: string[];\n collapsedGroupIds: string[];\n virtualCounts: boolean;\n value: TableRenderModel;\n } | null = null;\n private highlightMatcherCache: {\n terms: string[];\n value: TableHighlightMatcher;\n } | null = null;\n private virtualItemsCache: {\n columns: TableColumn[];\n rows: TableRow[];\n groups: DataGroup[];\n grouped: boolean;\n collapsedGroupIds: string[];\n } | null = null;\n private rootEl: HTMLElement | null = null;\n private viewportEl: HTMLElement | null = null;\n private frameEl: HTMLElement | null = null;\n private interactiveHeadEl: HTMLTableSectionElement | null = null;\n private collapseAllOverlayEl: HTMLElement | null = null;\n private stickyHeaderTableEl: HTMLTableElement | null = null;\n private tableEl: HTMLTableElement | null = null;\n private sentinelEl: HTMLElement | null = null;\n private incrementalWindowActive = false;\n private readonly groupSentinelEls = new Map<string, HTMLElement>();\n private previousModelWarning = '';\n private modelWarningQueued = false;\n private initialModelWarningFrame: number | undefined;\n private hasLoaded = false;\n private renderedModel: TableRenderModel | null = null;\n private stickyGroupConnected = false;\n private headerSlotObserver: MutationObserver | null = null;\n private footerSlotObserver: MutationObserver | null = null;\n private captionCompactDisconnect: (() => void) | undefined;\n private fitResizeObserver: ResizeObserver | null = null;\n private fitObservedViewport: HTMLElement | null = null;\n private fitObservedTable: HTMLTableElement | null = null;\n private fitMeasurementPending = false;\n private cardViewportQuery: MediaQueryList | null = null;\n private readonly bodyRenderer = new TableBodyRenderer();\n private readonly layoutController = new TableLayoutController({\n elements: () => ({\n viewport: this.viewportEl,\n contentTable: this.tableEl,\n stickyHeaderTable: this.stickyHeaderTableEl,\n collapseAllOverlay: this.collapseAllOverlayEl,\n frame: this.frameEl,\n interactiveHead: this.interactiveHeadEl,\n }),\n mode: () => ({\n documentStickyHeader: this.documentStickyHeader,\n floatingCollapseAll: this.renderedModel?.collapseAllHost?.mode === 'floating',\n clampVerticalOverscroll: this.fitViewport && this.viewportFitSettled,\n }),\n verticalEdgeWheel: deltaY => this.viewportFitController.scrollOuterBy(deltaY),\n overflowChanged: state => {\n if (state.start !== this.overflowStart) this.overflowStart = state.start;\n if (state.end !== this.overflowEnd) this.overflowEnd = state.end;\n if (state.scrollable !== this.scrollable) this.scrollable = state.scrollable;\n },\n });\n private readonly loadController = new TableLoadController({\n state: () => ({\n lazyLoading: this.dataMode === 'infinite' && !this.grouped,\n loadMoreMode: this.loadMoreMode,\n hasMore: this.hasMore,\n loadingMore: this.loadingMore,\n loadMoreError: this.loadMoreError,\n loadIdentity: this.loadIdentity,\n loadMoreThreshold: this.loadMoreThreshold,\n containedScroll: this.containedScroll,\n loadingMoreLabel: this.loadingMoreLabel,\n endOfResultsLabel: this.endOfResultsLabel,\n rowsLoadedLabel: this.rowsLoadedLabel,\n loadedRowCount: this.currentLoadedRowCount(),\n viewport: this.viewportEl,\n sentinel: this.sentinelEl,\n }),\n announce: message => {\n this.announcement = message;\n },\n request: detail => {\n this.dsLoadMore.emit(detail);\n },\n });\n private readonly groupLoadController = new TableGroupLoadController({\n state: () => ({\n enabled: this.grouped && this.dataMode !== 'virtual',\n loadMoreMode: this.loadMoreMode,\n loadMoreThreshold: this.loadMoreThreshold,\n containedScroll: this.containedScroll,\n groups: this.groups,\n viewport: this.viewportEl,\n sentinels: this.groupSentinelEls,\n loadingMoreLabel: this.groupLoadingMoreLabel,\n endOfResultsLabel: this.groupEndOfResultsLabel,\n rowsLoadedLabel: this.groupRowsLoadedLabel,\n }),\n announce: message => {\n this.announcement = message;\n },\n request: detail => {\n this.dsGroupLoadMore.emit(detail);\n },\n });\n private readonly virtualController = new TableVirtualController({\n state: () => ({\n enabled: this.rowWindowingEnabled,\n items: this.virtualItems,\n pinnedRowIds: this.virtualPinnedRowIds(),\n viewport: this.viewportEl,\n viewportSize: this.estimateVirtualViewportSize(),\n }),\n windowChanged: plan => {\n this.virtualWindow = plan;\n },\n });\n private readonly viewportFitController = new TableViewportFitController({\n enabled: () => this.fitViewport,\n elements: () => ({ host: this.el, surface: this.rootEl }),\n insets: () => ({\n blockStart: this.viewportInsetBlockStart,\n blockEnd: this.viewportInsetBlockEnd,\n }),\n fitChanged: (metrics: TableViewportFitMetrics | null) => {\n const settled = metrics?.settled ?? false;\n if (settled !== this.viewportFitSettled) this.viewportFitSettled = settled;\n },\n });\n\n componentWillLoad(): void {\n this.connectCardViewportQuery();\n // Reserve the final viewport-fit height before the first paint. The fitted\n // surface is connected after render, but the host can already resolve its\n // owning scrollport and prevent an initial auto-height frame.\n this.viewportFitController.connect();\n this.incrementalWindowActive = this.hasIncrementalState;\n this.syncHeaderSlotPresence();\n this.syncFooterSlotPresence();\n this.loadController.initialize();\n this.groupLoadController.initialize();\n }\n\n componentDidLoad(): void {\n this.hasLoaded = true;\n this.layoutController.connect();\n this.loadController.connect();\n this.groupLoadController.connect();\n this.virtualController.connect();\n this.viewportFitController.connect();\n this.syncStickyGroupConnection();\n this.connectHeaderSlotObserver();\n this.connectFooterSlotObserver();\n this.connectFitObserver();\n this.connectCaptionCompactObserver();\n this.syncFitPageSize();\n this.connectTruncateTooltip();\n this.scheduleInitialModelIssueWarning();\n }\n\n componentWillRender(): void {\n const root = this.el.getRootNode() as Document | ShadowRoot;\n const active = root.activeElement;\n this.virtualRenderFocus =\n this.rowWindowingEnabled &&\n active instanceof HTMLElement &&\n this.tableEl?.contains(active) &&\n active.closest('[data-row-id]')\n ? active\n : null;\n }\n\n componentDidRender(): void {\n // Moving a retained pooled row can clear native focus in Firefox. Restore\n // only the same connected node, without scrolling or stealing external focus.\n const retainedFocus = this.virtualRenderFocus;\n this.virtualRenderFocus = null;\n if (retainedFocus?.isConnected) {\n const root = retainedFocus.getRootNode() as Document | ShadowRoot;\n if (!root.activeElement || root.activeElement === this.el.ownerDocument.body) {\n // Resolve the moved rows' scroll geometry before restoring native focus.\n // WebKit otherwise may reveal the caret using the pre-patch layout even\n // with preventScroll. Preserve both axes within the resulting bounds.\n const viewport = this.viewportEl;\n const top = viewport?.scrollTop ?? 0;\n const left = viewport?.scrollLeft ?? 0;\n retainedFocus.focus({ preventScroll: true });\n if (viewport) {\n if (viewport.scrollTop !== top) viewport.scrollTop = top;\n if (viewport.scrollLeft !== left) viewport.scrollLeft = left;\n }\n }\n }\n this.layoutController.refresh(false);\n this.loadController.refresh();\n this.groupLoadController.refresh();\n this.virtualController.refresh();\n this.virtualController.collectMeasurements(this.tableEl);\n if (\n this.rowWindowingEnabled &&\n this.truncateAnchor &&\n this.tableEl &&\n !this.tableEl.contains(this.truncateAnchor)\n ) {\n this.dismissTruncateTooltip();\n }\n this.viewportFitController.refresh(false);\n this.syncStickyGroupConnection();\n this.connectFitObserver();\n this.connectCaptionCompactObserver();\n this.syncFitPageSize();\n if (this.stickyGroupConnected) this.updateStickyGroup();\n if (this.renderedAlternateView !== this.alternateView) {\n this.renderedAlternateView = this.alternateView;\n this.dsAlternateViewRendered.emit({ alternateView: this.alternateView });\n }\n }\n\n /**\n * Scroll the nearest vertical owner only enough to reveal a supplied row.\n * Resolves false when the row is absent from the supplied, expanded table model.\n * This method never moves focus.\n */\n @Method()\n async scrollRowIntoView(rowId: string): Promise<boolean> {\n if (!rowId) return false;\n\n if (this.rowWindowingEnabled) {\n const headerSize = this.tableEl?.tHead?.getBoundingClientRect().height ?? 0;\n const revealed = this.virtualController.scrollRowIntoView(\n rowId,\n headerSize,\n this.stickyHeader ? headerSize : 0\n );\n if (!revealed) return false;\n await this.nextAnimationFrame();\n }\n\n const row = this.findRenderedRow(rowId);\n if (!row) return false;\n this.revealRenderedRow(row);\n return true;\n }\n\n connectedCallback(): void {\n if (!this.hasLoaded) return;\n this.connectCardViewportQuery();\n this.layoutController.connect();\n this.loadController.connect();\n this.groupLoadController.connect();\n this.virtualController.connect();\n this.viewportFitController.connect();\n this.syncStickyGroupConnection();\n this.connectHeaderSlotObserver();\n this.connectFooterSlotObserver();\n this.connectFitObserver();\n this.connectCaptionCompactObserver();\n this.connectTruncateTooltip();\n }\n\n disconnectedCallback(): void {\n this.editingCell = null;\n this.layoutController.disconnect();\n this.loadController.disconnect();\n this.groupLoadController.disconnect();\n this.virtualController.disconnect();\n this.viewportFitController.disconnect();\n this.disconnectStickyGroup();\n this.headerSlotObserver?.disconnect();\n this.headerSlotObserver = null;\n this.footerSlotObserver?.disconnect();\n this.footerSlotObserver = null;\n this.disconnectFitObserver();\n this.disconnectCaptionCompactObserver();\n this.disconnectTruncateTooltip();\n this.disconnectCardViewportQuery();\n this.closeColumnCustomizer();\n if (this.initialModelWarningFrame !== undefined) {\n cancelAnimationFrame(this.initialModelWarningFrame);\n this.initialModelWarningFrame = undefined;\n }\n }\n\n private readonly handleCardViewportChange = (event: MediaQueryListEvent): void => {\n if (this.narrowViewport !== event.matches) this.narrowViewport = event.matches;\n };\n\n private connectCardViewportQuery(): void {\n if (\n this.cardViewportQuery ||\n typeof window === 'undefined' ||\n typeof window.matchMedia !== 'function'\n )\n return;\n const query = window.matchMedia(`(max-width: ${TABLE_CARD_VIEWPORT_BREAKPOINT - 1}px)`);\n this.cardViewportQuery = query;\n const narrow = isTableCardViewport(window.innerWidth);\n if (this.narrowViewport !== narrow) this.narrowViewport = narrow;\n query.addEventListener('change', this.handleCardViewportChange);\n }\n\n private disconnectCardViewportQuery(): void {\n this.cardViewportQuery?.removeEventListener('change', this.handleCardViewportChange);\n this.cardViewportQuery = null;\n }\n\n private syncHeaderSlotPresence = () => {\n const header = this.el.querySelector<HTMLElement>('[slot=\"header\"]');\n this.headerPresent = !!header;\n this.headerUsesToolbar = header?.tagName === 'DS-DATA-TOOLBAR';\n this.captionTrailingPresent = !!this.el.querySelector('[slot=\"caption-trailing\"]');\n };\n\n private connectHeaderSlotObserver(): void {\n if (this.headerSlotObserver || typeof MutationObserver === 'undefined') return;\n this.headerSlotObserver = new MutationObserver(this.syncHeaderSlotPresence);\n this.headerSlotObserver.observe(this.el, { childList: true });\n this.syncHeaderSlotPresence();\n }\n\n private syncFooterSlotPresence = () => {\n let presence = 0;\n if (hasOwnedTableFooterSlot(this.el, 'footer-leading')) presence |= TABLE_FOOTER_SLOT_LEADING;\n if (hasOwnedTableFooterSlot(this.el, 'footer')) presence |= TABLE_FOOTER_SLOT_COPY;\n if (hasOwnedTableFooterSlot(this.el, 'footer-trailing')) presence |= TABLE_FOOTER_SLOT_TRAILING;\n if (presence !== this.footerSlotPresence) this.footerSlotPresence = presence;\n };\n\n private connectFooterSlotObserver(): void {\n if (this.footerSlotObserver || typeof MutationObserver === 'undefined') return;\n this.footerSlotObserver = new MutationObserver(this.syncFooterSlotPresence);\n this.footerSlotObserver.observe(this.el, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['slot'],\n });\n this.syncFooterSlotPresence();\n }\n\n private connectStickyGroup(): void {\n if (this.stickyGroupConnected || typeof window === 'undefined') return;\n this.stickyGroupConnected = true;\n document.addEventListener('scroll', this.updateStickyGroup, {\n capture: true,\n passive: true,\n });\n window.addEventListener('resize', this.updateStickyGroup, { passive: true });\n this.updateStickyGroup();\n }\n\n private syncStickyGroupConnection(): void {\n if (this.documentStickyHeader && this.grouped) {\n this.connectStickyGroup();\n return;\n }\n\n this.disconnectStickyGroup();\n this.frameEl?.style.removeProperty('--_table-sticky-group-top');\n if (this.activeStickyGroupId !== null) {\n this.activeStickyGroupId = null;\n }\n }\n\n private disconnectStickyGroup(): void {\n if (!this.stickyGroupConnected || typeof window === 'undefined') return;\n this.stickyGroupConnected = false;\n document.removeEventListener('scroll', this.updateStickyGroup, true);\n window.removeEventListener('resize', this.updateStickyGroup);\n }\n\n private readonly updateStickyGroup = (): void => {\n if (!this.documentStickyHeader || !this.grouped || !this.frameEl || !this.tableEl) {\n if (this.activeStickyGroupId !== null) this.activeStickyGroupId = null;\n return;\n }\n\n const stickyHeader = this.frameEl.querySelector<HTMLElement>(\n '.ds-table__document-sticky-header'\n );\n if (!stickyHeader) return;\n const threshold = stickyHeader.getBoundingClientRect().bottom;\n let activeGroupId: string | null = null;\n let activeGroupTop = threshold;\n for (const body of this.tableEl.querySelectorAll<HTMLElement>('tbody[data-group-id]')) {\n const source = body.querySelector<HTMLElement>('.ds-table__group-cell');\n if (!source) continue;\n const sourceRect = source.getBoundingClientRect();\n const bodyRect = body.getBoundingClientRect();\n if (sourceRect.top <= threshold && bodyRect.bottom > threshold) {\n activeGroupId = body.dataset.groupId ?? null;\n // A sticky section is bounded by its own row group. As that boundary\n // approaches the sticky lane, move the outgoing section bar with it so\n // the incoming source bar pushes it away instead of rendering beneath it.\n activeGroupTop = Math.min(threshold, bodyRect.bottom - sourceRect.height);\n }\n }\n\n const frameRect = this.frameEl.getBoundingClientRect();\n this.frameEl.style.setProperty(\n '--_table-sticky-group-top',\n `${activeGroupTop - frameRect.top}px`\n );\n\n if (activeGroupId !== this.activeStickyGroupId) {\n this.activeStickyGroupId = activeGroupId;\n return;\n }\n };\n\n @Watch('columns')\n @Watch('grouping')\n @Watch('hiddenFieldIds')\n @Watch('fieldOrder')\n @Watch('pinnedFieldIds')\n @Watch('columnCustomizer')\n @Watch('cellSpans')\n @Watch('interactionMode')\n @Watch('responsiveLayout')\n handleStructureChange(): void {\n this.virtualItemsCache = null;\n this.scheduleModelIssueWarning();\n this.loadController.structureChanged();\n this.groupLoadController.structureChanged();\n this.virtualController.invalidateMeasures();\n }\n\n @Watch('rows')\n @Watch('groups')\n handleDataChange(): void {\n if (this.grouped) this.groupLoadController.dataChanged();\n else this.loadController.dataChanged();\n this.scheduleModelIssueWarning();\n this.syncActionMenu();\n this.virtualController.invalidateMeasures();\n }\n\n @Watch('totalCount')\n handleTotalCountChange(): void {\n this.scheduleModelIssueWarning();\n }\n\n @Watch('caption')\n handleCaptionChange(): void {\n this.scheduleModelIssueWarning();\n }\n\n @Watch('loadIdentity')\n handleLoadIdentityChange(): void {\n this.incrementalWindowActive = this.hasIncrementalState;\n this.loadController.identityChanged();\n this.virtualController.resetToTop();\n }\n\n @Watch('sort')\n @Watch('grouping')\n handleVirtualIndexReset(): void {\n this.virtualController.resetToTop();\n }\n\n @Watch('loadMoreMode')\n @Watch('loadMoreThreshold')\n handleLazyConfigurationChange(): void {\n this.loadController.configurationChanged();\n this.groupLoadController.configurationChanged();\n }\n\n @Watch('dataMode')\n handleDataModeChange(): void {\n this.incrementalWindowActive = this.hasIncrementalState;\n this.scheduleModelIssueWarning();\n this.handleLazyConfigurationChange();\n this.virtualController.resetToTop();\n }\n\n @Watch('pagination')\n handlePaginationChange(\n pagination: TablePaginationState | null,\n previous: TablePaginationState | null\n ): void {\n if (pagination?.pageSizeMode === 'fit' && pagination.fitIdentity !== previous?.fitIdentity) {\n this.fitMeasurementPending = true;\n }\n }\n\n @Watch('loadingMore')\n handleLoadingMoreChange(loading: boolean): void {\n if (loading) this.incrementalWindowActive = true;\n if (!this.grouped) this.loadController.loadingChanged(loading);\n }\n\n @Watch('loadMoreError')\n handleLoadMoreErrorChange(error: string | undefined): void {\n if (error?.trim()) this.incrementalWindowActive = true;\n if (!this.grouped) this.loadController.errorChanged(error);\n }\n\n @Watch('hasMore')\n handleHasMoreChange(hasMore: boolean, hadMore: boolean): void {\n if (hasMore) this.incrementalWindowActive = true;\n if (!this.grouped) this.loadController.hasMoreChanged(hasMore, hadMore);\n }\n\n @Watch('columnCustomizer')\n @Watch('captionVisibility')\n handleColumnCustomizerAvailability(): void {\n if (!this.showsColumnCustomizer) {\n this.closeColumnCustomizer();\n this.columnCustomizerSurfaceOpen = false;\n }\n }\n\n @Watch('dataModeSwitcher')\n @Watch('captionVisibility')\n handleDataModeSwitcherAvailability(): void {\n if (!this.showsDataModeSwitcher) {\n this.closeDataModeSwitcher();\n this.dataModeSwitcherSurfaceOpen = false;\n }\n }\n\n @Watch('chromeLoading')\n handleChromeLoadingChange(loading: boolean): void {\n if (!loading) return;\n this.closeColumnCustomizer();\n this.closeDataModeSwitcher();\n this.columnCustomizerSurfaceOpen = false;\n this.dataModeSwitcherSurfaceOpen = false;\n }\n\n private get grouped(): boolean {\n return this.grouping !== null;\n }\n\n private get hasIncrementalState(): boolean {\n return (\n this.dataMode === 'infinite' &&\n (this.hasMore || this.loadingMore || !!this.loadMoreError?.trim())\n );\n }\n\n private get selectable(): boolean {\n return this.selectionMode === 'multiple';\n }\n\n private get visibleColumns(): TableColumn[] {\n const cached = this.visibleColumnsCache;\n if (\n cached &&\n cached.columns === this.columns &&\n cached.columnCustomizer === this.columnCustomizer &&\n cached.hiddenFieldIds === this.hiddenFieldIds &&\n cached.fieldOrder === this.fieldOrder &&\n cached.pinnedFieldIds === this.pinnedFieldIds\n ) {\n return cached.value;\n }\n const value = resolveTableVisibleColumns(this.columns, {\n columnCustomizer: this.columnCustomizer,\n hiddenFieldIds: this.hiddenFieldIds,\n fieldOrder: this.fieldOrder,\n pinnedFieldIds: this.pinnedFieldIds,\n });\n this.visibleColumnsCache = {\n columns: this.columns,\n columnCustomizer: this.columnCustomizer,\n hiddenFieldIds: this.hiddenFieldIds,\n fieldOrder: this.fieldOrder,\n pinnedFieldIds: this.pinnedFieldIds,\n value,\n };\n return value;\n }\n\n private get showsColumnCustomizer(): boolean {\n return this.columnCustomizer && this.captionVisibility === 'visible';\n }\n\n private get showsDataModeSwitcher(): boolean {\n return this.dataModeSwitcher && this.captionVisibility === 'visible';\n }\n\n private get showsCaptionTrailing(): boolean {\n return (\n this.showsDataModeSwitcher ||\n (this.showsColumnCustomizer && !this.hideColumnCustomizerTrigger) ||\n this.captionTrailingPresent\n );\n }\n\n private get documentStickyHeader(): boolean {\n return this.stickyHeader && !this.containedScroll && this.responsiveLayout !== 'cards';\n }\n\n private get fixedHeight(): boolean {\n return !this.fitViewport && this.resolvedHeight !== undefined;\n }\n\n private get boundedComposition(): boolean {\n return this.fitViewport || this.fixedHeight;\n }\n\n private get containedScroll(): boolean {\n return this.boundedComposition || this.resolvedMaxHeight !== undefined;\n }\n\n private connectFitObserver(): void {\n if (typeof ResizeObserver === 'undefined') return;\n if (this.fitObservedViewport === this.viewportEl && this.fitObservedTable === this.tableEl) {\n return;\n }\n this.disconnectFitObserver();\n this.fitObservedViewport = this.viewportEl;\n this.fitObservedTable = this.tableEl;\n this.fitResizeObserver = new ResizeObserver(this.syncFitPageSize);\n if (this.fitObservedViewport) this.fitResizeObserver.observe(this.fitObservedViewport);\n if (this.fitObservedTable) this.fitResizeObserver.observe(this.fitObservedTable);\n }\n\n private disconnectFitObserver(): void {\n this.fitResizeObserver?.disconnect();\n this.fitResizeObserver = null;\n this.fitObservedViewport = null;\n this.fitObservedTable = null;\n }\n\n private connectCaptionCompactObserver(): void {\n if (this.captionCompactDisconnect) return;\n this.captionCompactDisconnect = observeTableCaptionCompact(this.el, compact => {\n if (this.captionCompact !== compact) this.captionCompact = compact;\n });\n }\n\n private disconnectCaptionCompactObserver(): void {\n this.captionCompactDisconnect?.();\n this.captionCompactDisconnect = undefined;\n }\n\n private readonly syncFitPageSize = (): void => {\n const pagination = this.dataMode === 'pagination' ? this.pagination : null;\n if (\n !pagination?.fitToPage ||\n pagination.fitToPageInactive ||\n !this.containedScroll ||\n !this.viewportEl ||\n !this.tableEl\n ) {\n if (this.fitPageSize !== undefined) this.fitPageSize = undefined;\n this.fitMeasurementPending = false;\n return;\n }\n const header = this.tableEl.querySelector<HTMLElement>('.ds-table__head');\n const item = this.tableEl.querySelector<HTMLElement>(\n this.grouped ? '.ds-table__group-row' : '.ds-table__body .ds-table__row'\n );\n const itemBlockSize =\n item?.getBoundingClientRect().height ||\n resolveCssLengthPx(\n 'var(--ds-table-row-min-block-size, var(--dimension-size-500))',\n 0,\n this.rootEl ?? this.el\n );\n const next = resolveTableFitPageSize({\n viewportBlockSize: this.viewportEl.clientHeight,\n headerBlockSize: header?.getBoundingClientRect().height ?? 0,\n itemBlockSize,\n });\n if (next !== this.fitPageSize) this.fitPageSize = next;\n if (!this.fitMeasurementPending || pagination.pageSizeMode !== 'fit' || next === undefined) {\n return;\n }\n this.fitMeasurementPending = false;\n if (next === pagination.pageSize && pagination.pageIndex === 0) return;\n this.dsPaginationChange.emit({\n pageIndex: 0,\n pageSize: next,\n pageSizeMode: 'fit',\n totalItems: pagination.totalItems,\n pageSizeOptions: pagination.pageSizeOptions ?? [25, 50, 100, 200],\n fitToPage: true,\n fitToPageInactive: false,\n fitPageSize: next,\n fitPageSizeLabel: pagination.fitPageSizeLabel ?? 'Fit to page',\n fitPageSizeTriggerLabel: pagination.fitPageSizeTriggerLabel ?? 'Fit',\n itemLabel: pagination.itemLabel ?? 'items',\n pageSizeLabel: pagination.pageSizeLabel ?? 'Items',\n ariaLabel: pagination.ariaLabel ?? `${this.caption} pagination`,\n showFirstLastButtons: pagination.showFirstLastButtons ?? false,\n previousPageIndex: pagination.pageIndex,\n previousPageSize: pagination.pageSize,\n previousPageSizeMode: 'fit',\n reason: 'fit',\n });\n };\n\n @Listen('keydown', { target: 'window' })\n handleWindowPaginationKeyDown(event: KeyboardEvent): void {\n this.handlePaginationKeyDown(event, true);\n }\n\n private handlePaginationKeyDown(event: KeyboardEvent, fromWindow = false): void {\n const pagination = this.dataMode === 'pagination' ? this.pagination : null;\n if (\n !pagination ||\n this.loading ||\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey ||\n (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')\n ) {\n return;\n }\n\n if (paginationShortcutBlockedByPath(event.composedPath())) return;\n\n if (fromWindow) {\n const origin = event.composedPath()[0];\n const originNode = origin instanceof Text ? origin.parentNode : origin;\n if (\n !shouldHandleContainingPagePaginationShortcut({\n origin: originNode,\n table: this.el,\n eventPath: event.composedPath(),\n })\n ) {\n return;\n }\n }\n\n const state = resolvePaginationState(pagination);\n const pageIndex = event.key === 'ArrowLeft' ? state.pageIndex - 1 : state.pageIndex + 1;\n if (pageIndex < 0 || pageIndex >= state.totalPages) return;\n\n event.preventDefault();\n this.dsPaginationChange.emit({\n pageIndex,\n pageSize: state.pageSize,\n pageSizeMode: state.pageSizeMode,\n totalItems: state.totalItems,\n pageSizeOptions: state.pageSizeOptions,\n fitToPage: pagination.fitToPage ?? false,\n fitToPageInactive: pagination.fitToPageInactive ?? false,\n fitPageSize: this.fitPageSize ?? pagination.fitPageSize,\n fitPageSizeLabel: pagination.fitPageSizeLabel ?? 'Fit to page',\n fitPageSizeTriggerLabel: pagination.fitPageSizeTriggerLabel ?? 'Fit',\n itemLabel: pagination.itemLabel ?? 'items',\n pageSizeLabel: pagination.pageSizeLabel ?? 'Items',\n ariaLabel: pagination.ariaLabel ?? `${this.caption} pagination`,\n showFirstLastButtons: pagination.showFirstLastButtons ?? false,\n previousPageIndex: state.pageIndex,\n previousPageSize: state.pageSize,\n previousPageSizeMode: state.pageSizeMode,\n reason: 'page',\n });\n }\n\n private currentLoadedRows(): TableRow[] {\n return tableRows(this.rows, this.groups, this.grouped);\n }\n\n private currentLoadedRowCount(): number {\n return this.grouped\n ? this.groups.reduce((count, group) => count + group.rows.length, 0)\n : this.rows.length;\n }\n\n private createRenderModel(): TableRenderModel {\n const columns = this.visibleColumns;\n const grouped = this.grouped;\n const virtualCounts = this.dataMode === 'virtual';\n const cached = this.renderModelCache;\n if (\n cached &&\n cached.columns === columns &&\n cached.rows === this.rows &&\n cached.groups === this.groups &&\n cached.grouped === grouped &&\n cached.selectionMode === this.selectionMode &&\n cached.selectedRowIds === this.selectedRowIds &&\n cached.collapsedGroupIds === this.collapsedGroupIds &&\n cached.virtualCounts === virtualCounts\n ) {\n return cached.value;\n }\n const value = createTableRenderModel({\n columns,\n rows: this.rows,\n groups: this.groups,\n grouped,\n selectionMode: this.selectionMode,\n selectedRowIds: this.selectedRowIds,\n collapsedGroupIds: this.collapsedGroupIds,\n groupCountPresentation: virtualCounts ? 'total' : 'loaded-progress',\n });\n this.renderModelCache = {\n columns,\n rows: this.rows,\n groups: this.groups,\n grouped,\n selectionMode: this.selectionMode,\n selectedRowIds: this.selectedRowIds,\n collapsedGroupIds: this.collapsedGroupIds,\n virtualCounts,\n value,\n };\n return value;\n }\n\n private get highlightMatcher(): TableHighlightMatcher {\n if (this.highlightMatcherCache?.terms === this.highlightTerms) {\n return this.highlightMatcherCache.value;\n }\n const value = createTableHighlightMatcher(this.highlightTerms);\n this.highlightMatcherCache = { terms: this.highlightTerms, value };\n return value;\n }\n\n private get rowWindowingEnabled(): boolean {\n if (!this.hasVirtualViewportBounds) return false;\n if (this.dataMode === 'virtual') return true;\n return !this.grouped && this.currentLoadedRowCount() > TABLE_NON_VIRTUAL_WINDOW_THRESHOLD;\n }\n\n private get virtualViewportMissing(): boolean {\n return this.dataMode === 'virtual' && !this.hasVirtualViewportBounds;\n }\n\n private get hasVirtualViewportBounds(): boolean {\n return this.containedScroll && this.estimateVirtualViewportSize() > 0;\n }\n\n private estimateVirtualViewportSize(): number {\n const measured =\n this.virtualController.currentViewportSize() || this.viewportEl?.clientHeight || 0;\n const chrome =\n (this.captionVisibility === 'visible' ? 48 : 0) + (this.hasResultFooter ? 48 : 0);\n if (this.fixedHeight && this.resolvedHeight) {\n if (measured > 0) return measured;\n return Math.max(\n 0,\n resolveCssLengthPx(this.resolvedHeight, 0, this.rootEl ?? this.el) - chrome\n );\n }\n if (this.fitViewport) return Math.max(0, measured);\n if (this.resolvedMaxHeight) {\n if (this.resolvedMaxHeight.trim().toLowerCase() === 'none') return 0;\n return resolveCssLengthPx(this.resolvedMaxHeight, 0, this.rootEl ?? this.el);\n }\n return 0;\n }\n\n private virtualPinnedRowIds(): Set<string> {\n const pinned = new Set<string>();\n if (this.focusedRowId) pinned.add(this.focusedRowId);\n if (this.actionMenu?.rowId) pinned.add(this.actionMenu.rowId);\n return pinned;\n }\n\n private findRenderedRow(rowId: string): HTMLElement | null {\n return (\n [...this.el.querySelectorAll<HTMLElement>('[data-row-id]')].find(\n candidate => candidate.dataset.rowId === rowId\n ) ?? null\n );\n }\n\n private revealRenderedRow(row: HTMLElement): void {\n if (!this.containedScroll || !this.viewportEl) {\n row.scrollIntoView({ block: 'nearest', inline: 'nearest' });\n return;\n }\n\n const viewportRect = this.viewportEl.getBoundingClientRect();\n const rowRect = row.getBoundingClientRect();\n let visibleStart = viewportRect.top;\n if (this.stickyHeader) {\n visibleStart = Math.max(\n visibleStart,\n this.tableEl?.tHead?.getBoundingClientRect().bottom ?? visibleStart\n );\n }\n const groupRow = row.closest('tbody')?.querySelector<HTMLElement>('.ds-table__group-row');\n if (groupRow && getComputedStyle(groupRow).position === 'sticky') {\n visibleStart = Math.max(visibleStart, groupRow.getBoundingClientRect().bottom);\n }\n\n if (rowRect.top < visibleStart) {\n this.viewportEl.scrollTop += rowRect.top - visibleStart;\n } else if (rowRect.bottom > viewportRect.bottom) {\n this.viewportEl.scrollTop += rowRect.bottom - viewportRect.bottom;\n }\n }\n\n private nextAnimationFrame(): Promise<void> {\n return new Promise(resolve => requestAnimationFrame(() => resolve()));\n }\n\n private syncVirtualItems(model: TableRenderModel): void {\n if (!this.rowWindowingEnabled) {\n this.virtualItems = [];\n this.virtualItemsCache = null;\n this.bodyRenderer.resetVirtualState();\n return;\n }\n const columns = this.visibleColumns;\n const cached = this.virtualItemsCache;\n if (\n cached &&\n cached.columns === columns &&\n cached.rows === this.rows &&\n cached.groups === this.groups &&\n cached.grouped === model.grouped &&\n cached.collapsedGroupIds === this.collapsedGroupIds\n ) {\n return;\n }\n this.virtualItems = flattenTableVirtualItems({\n grouped: model.grouped,\n rows: this.rows,\n groups: this.groups,\n collapsedGroupIds: this.collapsedGroupIds,\n columns,\n });\n if (this.responsiveLayout === 'cards') {\n this.virtualItems = this.virtualItems.map(item => ({ ...item, variableSize: true }));\n }\n this.virtualItemsCache = {\n columns,\n rows: this.rows,\n groups: this.groups,\n grouped: model.grouped,\n collapsedGroupIds: this.collapsedGroupIds,\n };\n }\n\n private shouldWindowRows(model: TableRenderModel): boolean {\n return (\n this.rowWindowingEnabled && (model.hasData || (model.grouped && model.groups.length > 0))\n );\n }\n\n private get resolvedMaxHeight(): string | undefined {\n if (this.maxHeight == null || this.maxHeight === '') return undefined;\n return typeof this.maxHeight === 'number' ? `${Math.max(0, this.maxHeight)}px` : this.maxHeight;\n }\n\n private get resolvedHeight(): string | undefined {\n if (this.height == null || this.height === '') return undefined;\n return typeof this.height === 'number' ? `${Math.max(0, this.height)}px` : this.height;\n }\n\n private warnModelIssues(): void {\n const issues = tableModelIssues(this.columns, this.rows, this.groups, this.grouped);\n const visibleColumns = this.visibleColumns;\n if (!this.caption?.trim()) issues.unshift('A non-empty caption is required.');\n if (this.grouping) {\n const groupingColumn = this.columns.find(column => column.id === this.grouping!.fieldId);\n if (!groupingColumn) {\n issues.push(`Grouping references unknown column id: ${this.grouping.fieldId}`);\n } else if (!visibleColumns.some(column => column.id === groupingColumn.id)) {\n issues.push(`Grouping references hidden column id: ${this.grouping.fieldId}`);\n }\n }\n if (this.sort) {\n const sortColumn = this.columns.find(\n column =>\n column.id === this.sort!.fieldId ||\n column.segments?.some(segment => segment.sortKey === this.sort!.fieldId)\n );\n if (!sortColumn) {\n issues.push(`Sorting references unknown column id: ${this.sort.fieldId}`);\n } else if (!visibleColumns.some(column => column.id === sortColumn.id)) {\n issues.push(`Sorting references hidden column id: ${this.sort.fieldId}`);\n }\n }\n if (\n this.dataMode === 'virtual' &&\n Number.isFinite(this.totalCount) &&\n Math.max(0, Math.trunc(this.totalCount!)) !== this.currentLoadedRowCount()\n ) {\n issues.push('Virtual mode requires totalCount to match the complete supplied row count.');\n }\n const stickyStart = visibleColumns.filter(column => column.sticky === 'start');\n const stickyEnd = visibleColumns.filter(column => column.sticky === 'end');\n issues.push(...this.structure.merges.issues);\n if (this.interactionMode === 'grid' && this.grouped)\n issues.push('Grid interaction requires ungrouped rows.');\n for (const column of [...stickyStart, ...stickyEnd]) {\n if (!tableColumnSize(column))\n issues.push(`Sticky column ${column.id} requires an explicit size.`);\n }\n const message = issues.join(' ');\n if (!message) {\n this.previousModelWarning = '';\n return;\n }\n if (message === this.previousModelWarning) return;\n this.previousModelWarning = message;\n console.warn(`[ds-table] ${message}`);\n }\n\n private scheduleModelIssueWarning(): void {\n if (this.modelWarningQueued) return;\n this.modelWarningQueued = true;\n queueMicrotask(() => {\n this.modelWarningQueued = false;\n this.warnModelIssues();\n });\n }\n\n private scheduleInitialModelIssueWarning(): void {\n if (this.initialModelWarningFrame !== undefined) {\n cancelAnimationFrame(this.initialModelWarningFrame);\n }\n this.initialModelWarningFrame = requestAnimationFrame(() => {\n this.initialModelWarningFrame = undefined;\n this.warnModelIssues();\n });\n }\n\n private emitSort(column: TableColumn, sortKey = column.id): void {\n if (!column.sortable) return;\n this.dsSortChange.emit({ sort: nextDataSortState(this.sort, sortKey) });\n }\n\n private sortButtonLabel(column: TableColumn, sortKey = column.id, label = column.label): string {\n if (this.sort?.fieldId !== sortKey) return `Sort ${label} ascending`;\n if (this.sort.direction === 'asc') return `Sort ${label} descending. Currently ascending.`;\n return `Sort ${label} ascending. Currently descending.`;\n }\n\n private emitRowSelection(row: TableRow): void {\n const next = toggleTableRowSelection(this.selectedRowIds, row);\n const selected = next.includes(row.id);\n this.dsSelectionChange.emit({\n selectedRowIds: next,\n scope: 'row',\n changedRowId: row.id,\n selected,\n });\n }\n\n private emitAllSelection(): void {\n const loadedRows = this.currentLoadedRows();\n const selection = deriveTableSelectionState(loadedRows, this.selectedRowIds);\n this.dsSelectionChange.emit({\n selectedRowIds: toggleAllLoadedTableRows(this.selectedRowIds, loadedRows),\n scope: 'all-loaded',\n selected: !selection.allSelected,\n });\n }\n\n private emitGroupSelection(group: DataGroup): void {\n const state = deriveTableSelectionState(group.rows, this.selectedRowIds);\n this.dsSelectionChange.emit({\n selectedRowIds: toggleTableGroupSelection(this.selectedRowIds, group.rows),\n scope: 'group',\n groupId: group.id,\n selected: !state.allSelected,\n });\n }\n\n private rowEventOwnsActivation(event: Event): boolean {\n const currentTarget = event.currentTarget;\n return !event.composedPath().some(target => {\n if (!(target instanceof HTMLElement) || target === currentTarget) return false;\n return target.matches(\n 'button, a, input, select, textarea, [role=\"button\"], [role=\"checkbox\"], [popover], ds-button-unfilled, ds-menu'\n );\n });\n }\n\n private groupRowEventOwnsCollapse(event: Event): boolean {\n const currentTarget = event.currentTarget;\n return !event.composedPath().some(target => {\n if (!(target instanceof HTMLElement) || target === currentTarget) return false;\n return target.matches(\n 'input, select, textarea, [role=\"checkbox\"], .ds-table__selection-control, .ds-table__group-selection, ds-tooltip'\n );\n });\n }\n\n private handleGroupRowClick(group: DataGroup, event: Event): void {\n if (!this.groupRowEventOwnsCollapse(event)) return;\n this.emitGroupCollapse(group);\n }\n\n private emitRowActivation(row: TableRow, event: Event): void {\n if (this.gridEnabled || row.disabled || !this.rowEventOwnsActivation(event)) return;\n if (this.selectionMode === 'multiple' && this.selectedRowIds.length > 0) {\n if (row.selectable !== false) this.emitRowSelection(row);\n return;\n }\n if (row.interactive) this.dsRowActivate.emit({ rowId: row.id });\n }\n\n private syncActionMenu(): void {\n if (!this.actionMenu) return;\n const row = tableRows(this.rows, this.groups, this.grouped).find(\n candidate => candidate.id === this.actionMenu?.rowId\n );\n const value = row && !row.disabled ? row.cells[this.actionMenu.columnId] : undefined;\n if (!isTableCellAction(value) || !isRenderableTableActionMenu(value)) {\n this.actionMenu = null;\n }\n }\n\n private closeActionMenu(): void {\n this.actionMenu = null;\n }\n\n private handleActionMenuSelect(item: MenuItemData): void {\n const open = this.actionMenu;\n const actionId = item.value;\n if (!open || !actionId || item.isInactive) return;\n this.dsCellAction.emit({\n actionId,\n rowId: open.rowId,\n columnId: open.columnId,\n });\n const triggerId = tableActionTriggerId(this.actionMenuElementId, open.rowId, open.columnId);\n this.closeActionMenu();\n requestAnimationFrame(() => {\n const trigger = this.el.querySelector<HTMLElement & { setFocus?: () => void }>(\n `#${CSS.escape(triggerId)}`\n );\n trigger?.setFocus?.();\n });\n }\n\n private toggleActionMenu(row: TableRow, column: TableColumn, event: MouseEvent): void {\n if (row.disabled) return;\n const open = this.actionMenu?.rowId === row.id && this.actionMenu?.columnId === column.id;\n this.actionMenuInitialFocusVisible = event.detail === 0;\n this.actionMenu = open ? null : { rowId: row.id, columnId: column.id };\n if (this.actionMenu) this.actionMenuSurface = this.actionMenu;\n }\n\n private renderOverflowActionMenu() {\n const open = this.actionMenu ?? this.actionMenuSurface;\n const row = open\n ? tableRows(this.rows, this.groups, this.grouped).find(\n candidate => candidate.id === open.rowId\n )\n : undefined;\n const value = row && open ? row.cells[open.columnId] : undefined;\n const menu = isTableCellAction(value) && isRenderableTableActionMenu(value) ? value : undefined;\n const sections = menu ? tableActionMenuSections(menu.items) : [];\n const triggerId = open\n ? tableActionTriggerId(this.actionMenuElementId, open.rowId, open.columnId)\n : undefined;\n\n return (\n <ds-menu\n id={this.actionMenuElementId}\n open={Boolean(this.actionMenu && sections.length)}\n anchorId={triggerId}\n align=\"end\"\n side=\"bottom\"\n menuLabel={menu?.ariaLabel ?? 'More actions'}\n initialFocusVisible={this.actionMenuInitialFocusVisible}\n sections={sections}\n onDsClose={() => this.closeActionMenu()}\n onDsAfterClose={() => {\n if (!this.actionMenu) this.actionMenuSurface = null;\n }}\n onDsSelect={event => this.handleActionMenuSelect(event.detail)}\n />\n );\n }\n\n private connectTruncateTooltip(): void {\n if (this.truncateTooltipBound) return;\n this.el.addEventListener('pointerover', this.onTruncatePointerOver);\n this.el.addEventListener('pointerout', this.onTruncatePointerOut);\n this.el.addEventListener('focusin', this.onTruncateFocusIn);\n this.el.addEventListener('focusout', this.onTruncateFocusOut);\n this.truncateTooltipBound = true;\n }\n\n private disconnectTruncateTooltip(): void {\n if (!this.truncateTooltipBound) return;\n this.el.removeEventListener('pointerover', this.onTruncatePointerOver);\n this.el.removeEventListener('pointerout', this.onTruncatePointerOut);\n this.el.removeEventListener('focusin', this.onTruncateFocusIn);\n this.el.removeEventListener('focusout', this.onTruncateFocusOut);\n this.truncateTooltipBound = false;\n this.dismissTruncateTooltip();\n }\n\n private onTruncatePointerOver = (event: PointerEvent) => {\n if (event.pointerType === 'touch') return;\n const track = resolveTableTruncateTrack(event.target);\n if (!track) return;\n this.presentOrDismissTruncateTrack(track);\n };\n\n private onTruncatePointerOut = (event: PointerEvent) => {\n if (event.pointerType === 'touch') return;\n if (resolveTableTruncateTrack(event.relatedTarget)) return;\n const next = event.relatedTarget;\n const cell = this.truncateAnchor?.closest('.ds-table__cell');\n if (cell && next instanceof Node && cell.contains(next)) return;\n this.dismissTruncateTooltip();\n };\n\n private onTruncateFocusIn = (event: FocusEvent) => {\n const track = resolveTableTruncateTrack(event.target);\n if (!track) {\n this.dismissTruncateTooltip();\n return;\n }\n this.presentOrDismissTruncateTrack(track);\n };\n\n private onTruncateFocusOut = (event: FocusEvent) => {\n if (resolveTableTruncateTrack(event.relatedTarget)) return;\n this.dismissTruncateTooltip();\n };\n\n private presentOrDismissTruncateTrack(track: HTMLElement): void {\n if (!isElementTruncated(track)) {\n this.dismissTruncateTooltip();\n return;\n }\n const label = tableTruncateLabel(track);\n if (!label) {\n this.dismissTruncateTooltip();\n return;\n }\n this.truncateAnchor = track;\n this.truncateTooltipLabel = label;\n void this.truncateTooltipEl?.presentFrom(track, label);\n }\n\n private dismissTruncateTooltip(): void {\n this.truncateAnchor = null;\n if (!this.truncateTooltipLabel && !this.truncateTooltipEl) return;\n this.truncateTooltipLabel = '';\n void this.truncateTooltipEl?.dismiss();\n }\n\n private renderTruncateTooltip() {\n return (\n <ds-tooltip\n ref={element => {\n this.truncateTooltipEl = element;\n }}\n label={this.truncateTooltipLabel}\n describedBy={false}\n wrapLabel={true}\n size=\"sm\"\n delay={0}\n side=\"top\"\n />\n );\n }\n\n private handleRowKeydown(row: TableRow, event: KeyboardEvent): void {\n if (event.target !== event.currentTarget || (event.key !== 'Enter' && event.key !== ' '))\n return;\n event.preventDefault();\n this.emitRowActivation(row, event);\n }\n\n private onVirtualFocusIn = (event: FocusEvent): void => {\n const target = event.target;\n if (!(target instanceof HTMLElement)) return;\n const row = target.closest('[data-row-id]');\n const id = row?.getAttribute('data-row-id') ?? null;\n if (id === this.focusedRowId) return;\n this.focusedRowId = id;\n if (this.rowWindowingEnabled) this.virtualController.schedule();\n };\n\n private renderSelectionControl(\n label: string,\n checked: boolean,\n indeterminate: boolean,\n disabled: boolean,\n onActivate: () => void\n ) {\n return (\n <button\n class=\"ds-table__selection-control ds-focus-ring ds-interaction-fill__content\"\n type=\"button\"\n role=\"checkbox\"\n aria-label={label}\n aria-checked={indeterminate ? 'mixed' : String(checked)}\n disabled={disabled}\n onClick={onActivate}\n >\n <ds-checkbox\n label=\"\"\n size=\"md\"\n checked={checked}\n indeterminate={indeterminate}\n presentation={true}\n />\n </button>\n );\n }\n\n private renderStickyEdge(sticky: TableColumn['sticky'], shadow = true) {\n if (!sticky) return null;\n return (\n <span\n class={{\n 'ds-table__sticky-edge': true,\n [`ds-table__sticky-edge--${sticky}`]: true,\n 'ds-table__sticky-edge--internal': !shadow,\n }}\n aria-hidden=\"true\"\n />\n );\n }\n\n private renderCollapseAllButton() {\n return (\n <ds-button-unfilled\n class=\"ds-table__collapse-all\"\n variant=\"icon\"\n icon=\"ChevronDownUp\"\n size=\"xs\"\n style={{ width: 'var(--dimension-size-300)' }}\n aria-label=\"Collapse all groups\"\n hasBorder={false}\n activeFill={false}\n pressScale={false}\n onDsClick={event => {\n event.stopPropagation();\n this.emitAllGroupsCollapse();\n }}\n />\n );\n }\n\n private renderFloatingCollapseAll(model: TableRenderModel) {\n if (model.collapseAllHost?.mode !== 'floating') return null;\n return (\n <span\n class=\"ds-table__collapse-all-overlay\"\n ref={element => {\n this.collapseAllOverlayEl = element ?? null;\n }}\n >\n <span class=\"ds-table__collapse-all-surface ds-control-elevation ds-control-elevation--md\">\n {this.renderCollapseAllButton()}\n </span>\n </span>\n );\n }\n\n private renderColumnHeader(\n column: TableColumn,\n model: TableRenderModel,\n interactive = true,\n presentational = false,\n headerLane?: { start: number; spanning: boolean }\n ) {\n const groupedColumn = this.grouping?.fieldId === column.id;\n const previousColumn = headerLane\n ? this.visibleColumns[this.visibleColumns.indexOf(column) - 1]\n : undefined;\n const segments = column.segments?.length\n ? column.segments\n : [{ label: column.label, sortKey: column.id }];\n const activeMemberSegment = segments.find(segment => segment.sortKey === this.sort?.fieldId);\n const activeMemberSort = !!activeMemberSegment;\n const activeSort = activeMemberSort;\n const align = column.align ?? 'start';\n const direction = activeMemberSort ? this.sort!.direction : undefined;\n const memberAriaSort = activeMemberSort\n ? this.sort!.direction === 'asc'\n ? 'ascending'\n : 'descending'\n : undefined;\n\n const help = column.help?.trim();\n const labels = (\n <span\n class=\"ds-table__header-labels\"\n tabIndex={interactive && help && !column.sortable ? 0 : undefined}\n data-header-help={help ? '' : undefined}\n >\n {segments.map((segment, index) => {\n const segmentActive = activeMemberSegment?.sortKey === segment.sortKey;\n const segmentInteractive = interactive && !!column.sortable;\n const label = (\n <ds-text\n class=\"ds-table__header-label-box ds-control-label-box\"\n as=\"span\"\n variant=\"text-caption\"\n emphasis={segmentActive}\n color=\"inherit\"\n decoration={help ? 'dotted-underline' : undefined}\n lineTruncation={1}\n >\n {segment.label}\n </ds-text>\n );\n const control = segmentInteractive ? (\n <button\n class=\"ds-table__header-label ds-table__header-label--interactive ds-focus-ring\"\n type=\"button\"\n aria-label={this.sortButtonLabel(\n column,\n segment.sortKey,\n segment.dataLabel?.trim() || segment.label\n )}\n data-sort-control=\"label\"\n data-sort-key={segment.sortKey}\n data-sort-active={segmentActive ? 'true' : undefined}\n onClick={() => this.emitSort(column, segment.sortKey)}\n >\n {label}\n </button>\n ) : (\n <span class=\"ds-table__header-label ds-table__header-static\">{label}</span>\n );\n\n return (\n <span class=\"ds-table__header-segment\" key={segment.sortKey}>\n {control}\n {index < segments.length - 1 && (\n <ds-text\n class=\"ds-table__header-separator\"\n as=\"span\"\n variant=\"text-caption\"\n color=\"tertiary\"\n aria-hidden=\"true\"\n >\n {segment.separator ?? '/'}\n </ds-text>\n )}\n </span>\n );\n })}\n </span>\n );\n const labelControl =\n interactive && help ? (\n <ds-tooltip label={help} side=\"top\" size=\"sm\" wrapLabel={true}>\n {labels}\n </ds-tooltip>\n ) : (\n labels\n );\n const sortControl = interactive ? (\n <span class=\"ds-table__sort-slot\">\n {activeSort && (\n <ds-button-unfilled\n class=\"ds-table__sort-direction\"\n variant=\"icon\"\n icon={direction === 'asc' ? 'ArrowUp' : 'ArrowDown'}\n size=\"xs\"\n aria-label={this.sortButtonLabel(\n column,\n activeMemberSegment?.sortKey ?? column.id,\n activeMemberSegment?.label ?? column.label\n )}\n hasBorder={false}\n activeFill={false}\n isActive={true}\n pressScale={false}\n data-sort-control=\"direction\"\n onDsClick={() => this.emitSort(column, activeMemberSegment?.sortKey ?? column.id)}\n />\n )}\n </span>\n ) : null;\n const collapseHost = model.collapseAllHost;\n const actionCollapseHost =\n collapseHost?.mode === 'action' && collapseHost.columnId === column.id;\n const blankActionCollapseHost =\n actionCollapseHost && !column.label.trim() && !column.segments?.length;\n const collapseControl =\n interactive && actionCollapseHost ? (\n <span class=\"ds-table__collapse-slot\">{this.renderCollapseAllButton()}</span>\n ) : null;\n\n return (\n <th\n key={column.id}\n id={presentational ? undefined : this.headerId(column.id)}\n headers={presentational ? undefined : this.columnBandId(column.id)}\n rowSpan={headerLane?.spanning ? 2 : undefined}\n style={{\n ...this.structure.pins.get(column.id)?.style,\n ...(headerLane\n ? {\n gridColumn: String(headerLane.start),\n gridRow: headerLane.spanning ? '1 / span 2' : '2',\n }\n : {}),\n }}\n class={{\n 'ds-table__header-cell': true,\n 'ds-table__header-cell--rowspan': !!headerLane?.spanning,\n 'ds-table__header-cell--after-rowspan':\n !!headerLane &&\n !headerLane.spanning &&\n !!previousColumn &&\n !previousColumn.group &&\n !this.structure.pins.has(previousColumn.id),\n [`ds-table__cell--align-${align}`]: true,\n 'ds-table__cell--sticky-start':\n column.sticky === 'start' && this.structure.pins.has(column.id),\n 'ds-table__cell--sticky-end':\n column.sticky === 'end' && this.structure.pins.has(column.id),\n 'ds-table__header-cell--collapse-all': actionCollapseHost,\n }}\n scope={presentational ? undefined : 'col'}\n aria-sort={presentational ? undefined : memberAriaSort}\n data-column-id={column.id}\n data-grouped={groupedColumn ? 'true' : undefined}\n data-sort-active={activeSort ? 'true' : undefined}\n >\n {!column.label.trim() && column.accessibleLabel?.trim() && (\n <span class=\"ds-visually-hidden\">{column.accessibleLabel}</span>\n )}\n {blankActionCollapseHost ? (\n <span class=\"ds-table__header-content ds-table__header-content--collapse-all\">\n {collapseControl}\n </span>\n ) : (\n <span class=\"ds-table__header-content\">\n {align === 'end' && sortControl}\n {align === 'center' && (\n <span\n class=\"ds-table__sort-slot ds-table__sort-slot--balance\"\n data-sort-balance=\"true\"\n aria-hidden=\"true\"\n />\n )}\n {labelControl}\n {align !== 'end' && sortControl}\n {collapseControl}\n </span>\n )}\n {this.renderStickyEdge(\n this.structure.pins.has(column.id) ? column.sticky : undefined,\n !!this.structure.pins.get(column.id)?.edge\n )}\n </th>\n );\n }\n\n private renderColgroup(model: TableRenderModel) {\n const beforeSpacer =\n model.elasticSpacerIndex == null\n ? this.visibleColumns\n : this.visibleColumns.slice(0, model.elasticSpacerIndex);\n const afterSpacer =\n model.elasticSpacerIndex == null ? [] : this.visibleColumns.slice(model.elasticSpacerIndex);\n const renderColumn = (column: TableColumn) => {\n const width = tableColumnSize(column);\n return (\n <col\n key={column.id}\n class={{ 'ds-table__action-column': column.kind === 'action' }}\n style={width ? { width } : undefined}\n />\n );\n };\n return (\n <colgroup>\n {model.selectable && <col class=\"ds-table__selection-column\" />}\n {beforeSpacer.map(renderColumn)}\n {model.elasticSpacerIndex != null && <col class=\"ds-table__elastic-spacer-column\" />}\n {afterSpacer.map(renderColumn)}\n </colgroup>\n );\n }\n\n private renderHeader(\n model: TableRenderModel,\n interactive = true,\n presentational = false,\n ariaRowIndex?: number\n ) {\n const selection = model.selection;\n const bands = this.structure.bands;\n const multirow = bands.length > 0;\n const controls =\n interactive &&\n !(\n this.responsiveLayout === 'cards' &&\n this.narrowViewport &&\n this.interactionMode !== 'grid' &&\n !this.cellSpans.length\n );\n const selectionHeader = model.selectable && (\n <th\n class={{\n 'ds-table__header-cell': true,\n 'ds-table__selection-cell': true,\n 'ds-table__cell--sticky-start': true,\n 'ds-table__header-cell--rowspan': multirow,\n }}\n rowSpan={multirow ? 2 : undefined}\n style={multirow ? { gridColumn: '1', gridRow: '1 / span 2' } : undefined}\n scope={presentational ? undefined : 'col'}\n >\n {controls ? (\n this.renderSelectionControl(\n selection.allSelected ? 'Deselect all loaded rows' : 'Select all loaded rows',\n selection.allSelected,\n selection.indeterminate,\n selection.selectableRowIds.length === 0,\n () => this.emitAllSelection()\n )\n ) : (\n <span class=\"ds-visually-hidden\">Select rows</span>\n )}\n {this.renderStickyEdge(\n 'start',\n ![...this.structure.pins.values()].some(pin => pin.edge === 'start')\n )}\n </th>\n );\n const lanes: (TableColumn | undefined)[] = [...this.visibleColumns];\n if (model.elasticSpacerIndex != null) lanes.splice(model.elasticSpacerIndex, 0, undefined);\n const renderLane = (column: TableColumn | undefined, index: number) => {\n const start = index + 1 + Number(model.selectable);\n if (column)\n return this.renderColumnHeader(\n column,\n model,\n controls,\n presentational,\n multirow ? { start, spanning: !column.group } : undefined\n );\n return (\n <th\n class=\"ds-table__header-cell ds-table__elastic-spacer-cell\"\n rowSpan={multirow ? 2 : undefined}\n style={multirow ? { gridColumn: String(start), gridRow: '1 / span 2' } : undefined}\n aria-hidden=\"true\"\n role=\"presentation\"\n data-elastic-spacer=\"true\"\n />\n );\n };\n return (\n <thead\n class={{\n 'ds-table__head': true,\n 'ds-table__head--multirow': multirow,\n 'ds-table__head--semantic-copy': !interactive,\n }}\n ref={element => {\n if (interactive) this.interactiveHeadEl = element ?? null;\n }}\n >\n {multirow && (\n <tr class=\"ds-table__header-row ds-table__super-header-row\" aria-rowindex={ariaRowIndex}>\n {selectionHeader}\n {bands.map(band =>\n !band.label ? (\n lanes.map((column, index) => {\n const start = index + 1 + Number(model.selectable);\n return start >= band.start && start < band.start + band.span\n ? renderLane(column, index)\n : null;\n })\n ) : (\n <th\n key={band.key}\n id={presentational ? undefined : `${this.actionMenuElementId}-${band.key}`}\n class={{\n 'ds-table__header-cell': true,\n 'ds-table__super-header-cell': true,\n 'ds-table__cell--sticky-start': band.sticky === 'start',\n 'ds-table__cell--sticky-end': band.sticky === 'end',\n }}\n scope={presentational || !band.label ? undefined : 'colgroup'}\n colSpan={band.span}\n style={{\n gridColumn: `${band.start} / span ${band.span}`,\n gridRow: '1',\n ...this.structure.pins.get(\n (band.sticky === 'end' ? band.lastColumnId : band.firstColumnId) ?? ''\n )?.style,\n }}\n aria-hidden={!band.label ? 'true' : undefined}\n >\n <span class=\"ds-table__header-content\">\n <span class=\"ds-table__header-labels\">\n <span class=\"ds-table__header-segment\">\n {/* eslint-disable-next-line compomo/prefer-direct-ds-text -- Match the normal header's structural label canvas and inner text inset. */}\n <span class=\"ds-table__header-label ds-table__header-static\">\n <ds-text\n class=\"ds-table__header-label-box ds-control-label-box\"\n as=\"span\"\n variant=\"text-caption\"\n color=\"inherit\"\n lineTruncation={1}\n >\n {band.label}\n </ds-text>\n </span>\n </span>\n </span>\n </span>\n {this.renderStickyEdge(\n band.sticky,\n !!this.structure.pins.get(\n (band.sticky === 'end' ? band.firstColumnId : band.lastColumnId) ?? ''\n )?.edge\n )}\n </th>\n )\n )}\n </tr>\n )}\n <tr\n class=\"ds-table__header-row\"\n aria-rowindex={\n ariaRowIndex == null\n ? undefined\n : ariaRowIndex + Number(this.structure.bands.length > 0)\n }\n >\n {!multirow && selectionHeader}\n {lanes.map((column, index) => (!multirow || column?.group) && renderLane(column, index))}\n </tr>\n </thead>\n );\n }\n\n private renderRow(\n row: TableRow,\n model: TableRenderModel,\n ariaRowIndex?: number,\n variableVirtualSize = false,\n rowKey = row.id\n ) {\n return renderTableRowView({\n grid: this.gridEnabled,\n cellAttributes: this.editingEnabled\n ? (targetRow, column) => this.gridCellAttributes(targetRow, column)\n : undefined,\n renderEditor: this.editingEnabled\n ? (targetRow, column) => this.renderCellEditor(targetRow, column)\n : undefined,\n renderEditTrigger: this.editingEnabled\n ? (targetRow, column) => this.renderCellEditTrigger(targetRow, column)\n : undefined,\n pins: this.structure.pins,\n spans: this.structure.merges.cells.get(row.id),\n headerId: id => this.headerId(id),\n responsiveCards: this.responsiveLayout === 'cards',\n row,\n model,\n visibleColumns: this.visibleColumns,\n emptyCellLabel: this.emptyCellLabel,\n actionMenuElementId: this.actionMenuElementId,\n actionMenu: this.actionMenu,\n actionMenuSurface: this.actionMenuSurface,\n surfaceOpenRowId: this.surfaceOpenRowId,\n highlightMatcher: this.highlightMatcher,\n highlightFieldIds: this.highlightFieldIds,\n ariaRowIndex:\n ariaRowIndex == null ? undefined : ariaRowIndex + Number(this.structure.bands.length > 0),\n variableVirtualSize,\n intrinsicBlockSize:\n this.dataMode !== 'virtual'\n ? estimateTableRowBlockSize(row, this.visibleColumns)\n : undefined,\n rowKey,\n renderSelectionControl: (label, checked, indeterminate, disabled, onActivate) =>\n this.renderSelectionControl(label, checked, indeterminate, disabled, onActivate),\n renderStickyEdge: (sticky, shadow) => this.renderStickyEdge(sticky, shadow),\n onRowActivate: (targetRow, event) => this.emitRowActivation(targetRow, event),\n onRowKeyDown: (targetRow, event) => this.handleRowKeydown(targetRow, event),\n onRowSelection: targetRow => this.emitRowSelection(targetRow),\n onCellAction: detail => this.dsCellAction.emit(detail),\n onActionMenuToggle: (targetRow, column, event) =>\n this.toggleActionMenu(targetRow, column, event),\n });\n }\n\n private emitGroupCollapse(group: DataGroup) {\n const collapsedGroupIds = toggleTableGroupCollapsed(this.collapsedGroupIds, group.id);\n this.dsGroupCollapseChange.emit({\n scope: 'group',\n groupId: group.id,\n collapsed: collapsedGroupIds.includes(group.id),\n collapsedGroupIds,\n });\n }\n\n private emitAllGroupsCollapse() {\n const groupIds = this.groups.map(group => group.id);\n const collapsedGroupIds = nextTableGroupsCollapsed(this.collapsedGroupIds, groupIds);\n this.dsGroupCollapseChange.emit({\n scope: 'all',\n collapsed: collapsedGroupIds.length > 0,\n collapsedGroupIds,\n });\n }\n\n private renderGroupAccessory(\n item: TableRenderModel['groups'][number]['accessories'][number],\n index: number\n ) {\n const text = (\n <ds-text\n key={`acc-${index}`}\n class=\"ds-table__group-accessory\"\n as=\"span\"\n variant=\"text-body-small\"\n color=\"secondary\"\n decoration={item.help ? 'dotted-underline' : undefined}\n lineTruncation={1}\n >\n {item.text}\n </ds-text>\n );\n if (!item.help) return text;\n return (\n <ds-tooltip\n key={`acc-${index}`}\n label={item.help}\n side=\"bottom\"\n align=\"start\"\n size=\"sm\"\n wrapLabel={true}\n >\n <span class=\"ds-table__group-accessory-tip\" tabIndex={0}>\n {text}\n </span>\n </ds-tooltip>\n );\n }\n\n private renderGroupContent(groupModel: TableRenderModel['groups'][number]) {\n const {\n group,\n countLabel,\n collapsed: isCollapsed,\n labelColor,\n selection: groupSelection,\n accessories,\n hero,\n } = groupModel;\n const heroTracks = hero?.kind === 'score' && hero.tracks === 2 ? 2 : 1;\n const heroPresentation = TABLE_GROUP_HERO_SCORE_PRESENTATION[heroTracks];\n return (\n <span\n class={{\n 'ds-table__group-content': true,\n 'ds-table__group-content--multi': accessories.length > 0 || heroTracks === 2,\n 'ds-table__group-content--hero': Boolean(hero),\n 'ds-table__group-content--hero-two-track': Boolean(hero) && heroTracks === 2,\n }}\n onClick={event => this.handleGroupRowClick(group, event)}\n >\n {groupSelection && (\n <span class=\"ds-table__group-selection\">\n {this.renderSelectionControl(\n groupSelection.allSelected\n ? `Deselect loaded rows in ${group.label} group`\n : `Select loaded rows in ${group.label} group`,\n groupSelection.allSelected,\n groupSelection.indeterminate,\n groupSelection.selectableRowIds.length === 0,\n () => this.emitGroupSelection(group)\n )}\n </span>\n )}\n {hero?.kind === 'score' && (\n <span class=\"ds-table__group-hero\">\n <ds-score\n size={heroPresentation.size}\n variant={heroPresentation.variant}\n value={hero.value}\n level={hero.level}\n label={hero.label ?? 'Safety score'}\n isLoading={hero.isLoading === true}\n />\n </span>\n )}\n <span class=\"ds-table__group-copy\">\n <span class=\"ds-table__group-primary\">\n <ds-text\n class=\"ds-table__group-label\"\n as=\"span\"\n variant=\"text-body-medium\"\n emphasis={true}\n color={labelColor}\n >\n {group.label}\n </ds-text>\n <span class=\"ds-visually-hidden\">{countLabel}</span>\n </span>\n {accessories.length > 0 && (\n <span class=\"ds-table__group-accessories\">\n {accessories.flatMap((item, index) => [\n ...(index > 0\n ? [\n <ds-text\n key={`sep-${index}`}\n class=\"ds-table__group-accessory-separator\"\n as=\"span\"\n variant=\"text-body-small\"\n color=\"secondary\"\n aria-hidden=\"true\"\n >\n ·\n </ds-text>,\n ]\n : []),\n this.renderGroupAccessory(item, index),\n ])}\n </span>\n )}\n </span>\n <span class=\"ds-table__group-trailing\">\n <ds-text\n class=\"ds-table__group-count\"\n as=\"span\"\n variant=\"text-body-medium\"\n color=\"secondary\"\n aria-hidden=\"true\"\n >\n {groupModel.visibleCountText}\n </ds-text>\n <span class=\"ds-table__group-action\">\n <ds-button-unfilled\n class=\"ds-table__group-toggle\"\n variant=\"icon\"\n size=\"md\"\n isInset={true}\n insetDepth=\"double\"\n icon={isCollapsed ? 'ChevronDown' : 'ChevronUp'}\n expanded={!isCollapsed}\n aria-label={\n isCollapsed ? `Expand ${group.label} group` : `Collapse ${group.label} group`\n }\n hasBorder={false}\n pressScale={false}\n />\n </span>\n </span>\n </span>\n );\n }\n\n private formatGroupLoadLabel(template: string, group: DataGroup): string {\n return template.split('{group}').join(group.label);\n }\n\n private renderGroupLoadRow(group: DataGroup, totalColumns: number) {\n const error = group.loadMoreError?.trim();\n if (!error && !group.loadingMore && !group.hasMore) return null;\n const manualFallback =\n this.loadMoreMode === 'manual' || !this.groupLoadController.intersectionSupported;\n\n return (\n <tr\n class=\"ds-table__load-row ds-table__group-load-row\"\n data-group-id={group.id}\n ref={element => {\n if (element) this.groupSentinelEls.set(group.id, element);\n else this.groupSentinelEls.delete(group.id);\n }}\n >\n <td class=\"ds-table__load-cell\" colSpan={totalColumns}>\n <div class=\"ds-table__viewport-band ds-table__load-band\">\n {renderTableLoadContent({\n error,\n loading: !!group.loadingMore,\n hasMore: !!group.hasMore,\n manualFallback,\n retryLabel: this.formatGroupLoadLabel(this.groupRetryLabel, group),\n loadingLabel: this.formatGroupLoadLabel(this.groupLoadingMoreLabel, group),\n loadMoreLabel: this.groupLoadMoreLabel,\n loadMoreAriaLabel: this.formatGroupLoadLabel(this.groupLoadMoreAriaLabel, group),\n onRetry: () => this.groupLoadController.request(group.id, 'retry'),\n onLoadMore: () => this.groupLoadController.request(group.id, 'manual'),\n })}\n </div>\n </td>\n </tr>\n );\n }\n\n private renderStickyGroup(model: TableRenderModel) {\n if (!this.documentStickyHeader || !this.activeStickyGroupId) return null;\n const groupModel = model.groups.find(item => item.group.id === this.activeStickyGroupId);\n if (!groupModel) return null;\n return (\n <div\n class={{\n 'ds-table__sticky-group': true,\n 'ds-table__sticky-group--selectable': model.selectable,\n [groupModel.intentClass ?? '']: !!groupModel.intentClass,\n }}\n data-group-id={groupModel.group.id}\n data-group-intent={groupModel.intent}\n >\n {this.renderGroupContent(groupModel)}\n </div>\n );\n }\n\n private renderDataBodies(model: TableRenderModel, plan: TableVirtualPlan | null) {\n return this.bodyRenderer.render({\n headerRowCount: 1 + Number(this.structure.bands.length > 0),\n model,\n plan,\n rows: this.rows,\n stickyHeader: this.stickyHeader,\n documentStickyHeader: this.documentStickyHeader,\n activeStickyGroupId: this.activeStickyGroupId,\n renderRow: (row, renderModel, ariaRowIndex, variableVirtualSize, rowKey) =>\n this.renderRow(row, renderModel, ariaRowIndex, variableVirtualSize, rowKey),\n renderGroupContent: groupModel => this.renderGroupContent(groupModel),\n renderGroupLoadRow: (group, totalColumns) => this.renderGroupLoadRow(group, totalColumns),\n });\n }\n\n private renderSkeletonBody(model: TableRenderModel) {\n return renderTableSkeletonBody({\n pins: this.structure.pins,\n model,\n visibleColumns: this.visibleColumns,\n skeletonRows: this.skeletonRows,\n renderStickyEdge: (sticky, shadow) => this.renderStickyEdge(sticky, shadow),\n });\n }\n\n private renderStateBody(kind: 'empty' | 'error' | 'virtual-viewport', totalColumns: number) {\n const error = kind !== 'empty';\n const heading =\n kind === 'virtual-viewport'\n ? TABLE_VIRTUAL_VIEWPORT_REQUIRED_HEADING\n : error\n ? this.errorHeading\n : this.emptyHeading;\n const body =\n kind === 'virtual-viewport'\n ? TABLE_VIRTUAL_VIEWPORT_REQUIRED_BODY\n : error\n ? this.errorBody\n : this.emptyBody;\n return (\n <tbody class=\"ds-table__body ds-table__state-body\">\n <tr class=\"ds-table__state-row\">\n <td class=\"ds-table__state-cell\" colSpan={totalColumns}>\n <div class=\"ds-table__viewport-band ds-table__state-band\">\n <ds-empty-state\n icon={error ? 'ExclamationTriangle' : 'Inbox'}\n heading={heading}\n body={body}\n />\n </div>\n </td>\n </tr>\n </tbody>\n );\n }\n\n private renderLazyBody(model: TableRenderModel) {\n if (\n this.dataMode !== 'infinite' ||\n !this.incrementalWindowActive ||\n !model.hasData ||\n model.grouped\n )\n return null;\n const error = this.loadMoreError?.trim();\n const manualFallback =\n this.loadMoreMode === 'manual' || !this.loadController.intersectionSupported;\n\n return (\n <tbody class=\"ds-table__body ds-table__load-body\">\n <tr\n class=\"ds-table__load-row\"\n ref={element => {\n this.sentinelEl = element ?? null;\n }}\n >\n <td class=\"ds-table__load-cell\" colSpan={model.totalColumns}>\n <div class=\"ds-table__viewport-band ds-table__load-band\">\n {renderTableLoadContent({\n error,\n loading: this.loadingMore,\n hasMore: this.hasMore,\n manualFallback,\n retryLabel: this.retryLabel,\n loadingLabel: this.loadingMoreLabel,\n loadMoreLabel: this.loadMoreLabel,\n endOfResultsLabel: this.endOfResultsLabel,\n onRetry: () => this.loadController.request('retry'),\n onLoadMore: () => this.loadController.request('manual'),\n })}\n </div>\n </td>\n </tr>\n </tbody>\n );\n }\n\n private renderDocumentStickyHeader(model: TableRenderModel) {\n if (!this.documentStickyHeader) return null;\n return (\n <div class=\"ds-table__document-sticky-header\">\n <table\n class={{\n 'ds-table__table': true,\n 'ds-table__sticky-header-table': true,\n 'ds-table__table--selectable': model.selectable,\n 'ds-table__table--grouped': model.grouped,\n }}\n style={model.tableStyle}\n role=\"presentation\"\n ref={element => {\n this.stickyHeaderTableEl = element ?? null;\n }}\n >\n {this.renderColgroup(model)}\n {this.renderHeader(model, true, true)}\n </table>\n {this.renderFloatingCollapseAll(model)}\n </div>\n );\n }\n\n private get resultSummary(): string | null {\n if (this.dataMode === 'pagination') return null;\n if (this.dataMode === 'virtual') {\n return formatTableTotalSummary(this.currentLoadedRowCount(), this.resultTotalSummaryLabel);\n }\n return formatTableResultSummary(this.displayedCount, this.totalCount, this.resultSummaryLabel);\n }\n\n private get hasResultFooter(): boolean {\n return (\n (this.dataMode === 'pagination' && !!this.pagination) ||\n !!this.resultSummary ||\n this.footerSlotPresence !== 0\n );\n }\n\n private renderResultFooter() {\n const summary = this.resultSummary;\n const hasLeading = (this.footerSlotPresence & TABLE_FOOTER_SLOT_LEADING) !== 0;\n const hasCopy = (this.footerSlotPresence & TABLE_FOOTER_SLOT_COPY) !== 0;\n const hasTrailing = (this.footerSlotPresence & TABLE_FOOTER_SLOT_TRAILING) !== 0;\n const pagination = this.dataMode === 'pagination' ? this.pagination : null;\n if (!this.hasResultFooter) return null;\n return (\n <div class=\"ds-table__footer ds-table__bar ds-chrome-header ds-control--md\">\n <div class=\"ds-table__bar-copy ds-chrome-header__copy ds-control--md\">\n {hasLeading && (\n <div class=\"ds-table__bar-status ds-chrome-header__heading\">\n <slot name=\"footer-leading\" onSlotchange={this.syncFooterSlotPresence} />\n </div>\n )}\n {hasCopy ? (\n <slot name=\"footer\" onSlotchange={this.syncFooterSlotPresence} />\n ) : summary ? (\n <ds-text\n class=\"ds-table__footer-summary ds-table__bar-text\"\n as=\"span\"\n variant=\"text-body-medium\"\n color=\"secondary\"\n lineTruncation={1}\n >\n {summary}\n </ds-text>\n ) : null}\n </div>\n {(pagination || hasTrailing) && (\n <div class=\"ds-table__bar-trailing ds-chrome-header__trailing\">\n {pagination && (\n <ds-pagination\n pageIndex={pagination.pageIndex}\n pageSize={pagination.pageSize}\n pageSizeMode={pagination.pageSizeMode ?? 'fixed'}\n totalItems={pagination.totalItems}\n pageSizeOptions={pagination.pageSizeOptions ?? [25, 50, 100, 200]}\n fitToPage={pagination.fitToPage ?? false}\n {...{ fitToPageInactive: pagination.fitToPageInactive ?? false }}\n fitPageSize={this.fitPageSize ?? pagination.fitPageSize}\n fitPageSizeLabel={pagination.fitPageSizeLabel ?? 'Fit to page'}\n fitPageSizeTriggerLabel={pagination.fitPageSizeTriggerLabel ?? 'Fit'}\n itemLabel={pagination.itemLabel ?? 'items'}\n pageSizeLabel={pagination.pageSizeLabel ?? 'Items'}\n label={pagination.ariaLabel ?? `${this.caption} pagination`}\n showFirstLastButtons={pagination.showFirstLastButtons ?? false}\n loading={this.loading}\n onDsChange={(event: CustomEvent<PaginationChangeDetail>) =>\n this.dsPaginationChange.emit(event.detail)\n }\n />\n )}\n <slot name=\"footer-trailing\" onSlotchange={this.syncFooterSlotPresence} />\n </div>\n )}\n </div>\n );\n }\n\n private renderCaptionBar() {\n if (this.captionVisibility !== 'visible') return null;\n return (\n <div class=\"ds-table__caption-bar ds-table__bar ds-control--md\">\n <div\n class={{\n 'ds-table__caption-content': true,\n 'ds-table__caption-content--trailing': this.showsCaptionTrailing,\n }}\n >\n <div\n class={{\n 'ds-table__caption-leading': true,\n 'ds-table__caption-leading--toolbar': this.headerUsesToolbar,\n }}\n >\n <slot name=\"header\" onSlotchange={this.syncHeaderSlotPresence} />\n {!this.headerPresent ? (\n <ds-text\n class=\"ds-table__caption-title ds-table__bar-text\"\n as=\"div\"\n variant=\"text-title-small\"\n emphasis={true}\n color=\"primary\"\n aria-hidden=\"true\"\n >\n {this.caption}\n </ds-text>\n ) : null}\n </div>\n {this.renderCaptionTrailing()}\n </div>\n <slot name=\"header-after\" />\n </div>\n );\n }\n\n private renderCaptionTrailing() {\n if (!this.showsCaptionTrailing) return null;\n return (\n <div class=\"ds-table__caption-trailing\">\n {this.renderColumnCustomizerTrigger()}\n {this.showsColumnCustomizer &&\n !this.hideColumnCustomizerTrigger &&\n this.showsDataModeSwitcher ? (\n <ds-divider orientation=\"vertical\" length=\"32px\" />\n ) : null}\n {this.renderDataModeSwitcherTrigger()}\n <slot name=\"caption-trailing\" />\n </div>\n );\n }\n\n private renderDataModeSwitcherTrigger() {\n if (!this.showsDataModeSwitcher) return null;\n if (this.chromeLoading) {\n return <ds-skeleton variant=\"control\" controlSize=\"md\" width=\"var(--dimension-size-400)\" />;\n }\n return (\n <span class=\"ds-table__caption-mode-switcher\">\n <ds-tooltip label={this.dataModeSwitcherLabel} side=\"top\" size=\"sm\">\n <ds-button-unfilled\n hasBorder={!this.captionControlsBorderless}\n id={`${this.dataModeSwitcherElementId}-trigger`}\n variant=\"icon\"\n size=\"md\"\n icon=\"Ellipses\"\n aria-label={this.dataModeSwitcherLabel}\n hasMenu={true}\n expanded={this.dataModeSwitcherOpen}\n surfaceOpen={this.dataModeSwitcherSurfaceOpen}\n controls={this.dataModeSwitcherElementId}\n activeFill={false}\n pressScale={false}\n onDsClick={(event: CustomEvent<MouseEvent>) => {\n this.toggleDataModeSwitcher(event.detail.detail === 0);\n }}\n />\n </ds-tooltip>\n </span>\n );\n }\n\n private renderDataModeSwitcherMenu() {\n if (!this.showsDataModeSwitcher || this.chromeLoading) return null;\n return (\n <ds-menu\n id={this.dataModeSwitcherElementId}\n open={this.dataModeSwitcherOpen}\n anchorId={`${this.dataModeSwitcherElementId}-trigger`}\n align=\"end\"\n side=\"bottom\"\n menuLabel={this.dataModeMenuLabel}\n initialFocusVisible={this.dataModeSwitcherInitialFocusVisible}\n items={tableDataModeMenuItems(this.dataMode, {\n infinite: this.infiniteModeLabel,\n pagination: this.paginationModeLabel,\n virtual: this.virtualModeLabel,\n })}\n onDsClose={() => this.closeDataModeSwitcher()}\n onDsAfterClose={() => {\n if (!this.dataModeSwitcherOpen) this.dataModeSwitcherSurfaceOpen = false;\n }}\n onDsSelect={event => this.handleDataModeSwitcherSelect(event.detail)}\n />\n );\n }\n\n private toggleDataModeSwitcher(fromKeyboard = false): void {\n if (this.dataModeSwitcherOpen) this.closeDataModeSwitcher();\n else this.openDataModeSwitcher(fromKeyboard);\n }\n\n private openDataModeSwitcher(fromKeyboard = false): void {\n if (!this.showsDataModeSwitcher || this.dataModeSwitcherOpen) return;\n this.closeColumnCustomizer();\n this.dataModeSwitcherInitialFocusVisible = fromKeyboard;\n this.dataModeSwitcherOpen = true;\n this.dataModeSwitcherSurfaceOpen = true;\n }\n\n private closeDataModeSwitcher(): void {\n this.dataModeSwitcherOpen = false;\n }\n\n private handleDataModeSwitcherSelect(item: MenuItemData): void {\n const dataMode = tableDataModeFromMenuItem(item);\n if (!dataMode) return;\n this.closeDataModeSwitcher();\n if (dataMode !== this.dataMode) this.dsDataModeChange.emit({ dataMode });\n requestAnimationFrame(() => {\n this.el\n .querySelector<\n HTMLElement & { setFocus?: () => void }\n >(`#${CSS.escape(`${this.dataModeSwitcherElementId}-trigger`)}`)\n ?.setFocus?.();\n });\n }\n\n private renderColumnCustomizerTrigger() {\n if (this.hideColumnCustomizerTrigger) return null;\n if (!this.showsColumnCustomizer) return null;\n return (\n <div\n class={{\n 'ds-table__caption-customizer': true,\n 'ds-table__caption-customizer--loading': this.chromeLoading,\n }}\n aria-hidden={this.chromeLoading ? 'true' : undefined}\n >\n <ds-tooltip label={this.captionCompact ? 'Customize' : ''} side=\"top\" size=\"sm\">\n <ds-button-unfilled\n hasBorder={!this.captionControlsBorderless}\n id={`${this.columnCustomizerElementId}-trigger`}\n variant={this.captionCompact ? 'icon' : 'icon-label'}\n size=\"md\"\n icon=\"Preferences\"\n label=\"Customize\"\n labelEmphasis={false}\n pressScale={false}\n aria-label=\"Customize table\"\n haspopup=\"menu\"\n expanded={this.columnCustomizerOpen}\n surfaceOpen={this.columnCustomizerSurfaceOpen}\n controls={this.columnCustomizerElementId}\n onDsClick={(event: CustomEvent<MouseEvent>) => {\n if (this.chromeLoading) return;\n this.toggleColumnCustomizer(event.detail.detail === 0);\n }}\n />\n </ds-tooltip>\n {this.chromeLoading ? (\n <ds-skeleton variant=\"control\" controlSize=\"md\" width=\"100%\" />\n ) : null}\n </div>\n );\n }\n\n private renderColumnCustomizerMenu() {\n if (!this.showsColumnCustomizer || this.chromeLoading) return null;\n return (\n <ds-menu\n id={this.columnCustomizerElementId}\n open={this.columnCustomizerOpen}\n anchorId={`${this.columnCustomizerElementId}-trigger`}\n align=\"end\"\n side=\"bottom\"\n menuLabel=\"Customize table\"\n initialFocusVisible={this.columnCustomizerInitialFocusVisible}\n sections={[\n ...tableColumnCustomizerSections(\n this.columns,\n this.hiddenFieldIds,\n this.fieldOrder,\n this.pinnedFieldIds\n ),\n ...(this.customizeOptions.length\n ? [{ header: 'Options', items: this.customizeOptions }]\n : []),\n ]}\n onDsClose={() => this.closeColumnCustomizer()}\n onDsAfterClose={() => {\n if (!this.columnCustomizerOpen) this.columnCustomizerSurfaceOpen = false;\n }}\n onDsSelect={event => {\n if (this.customizeOptions.some(option => option.value === event.detail.value)) {\n this.dsCustomizeOptionChange.emit(event.detail.value!);\n } else this.handleColumnCustomizerSelect(event.detail);\n }}\n onDsItemToggle={(event: CustomEvent<MenuItemToggleDetail>) =>\n this.handleColumnCustomizerAction(event.detail)\n }\n onDsReorder={event => this.handleColumnCustomizerReorder(event.detail)}\n />\n );\n }\n\n private toggleColumnCustomizer(fromKeyboard = false): void {\n if (this.columnCustomizerOpen) this.closeColumnCustomizer();\n else this.openColumnCustomizer(fromKeyboard);\n }\n\n private openColumnCustomizer(fromKeyboard = false): void {\n if (!this.showsColumnCustomizer || this.columnCustomizerOpen) return;\n this.closeDataModeSwitcher();\n this.columnCustomizerInitialFocusVisible = fromKeyboard;\n this.columnCustomizerOpen = true;\n this.columnCustomizerSurfaceOpen = true;\n }\n\n private closeColumnCustomizer(): void {\n this.columnCustomizerOpen = false;\n }\n\n private emitColumnsConfigChange(\n hiddenFieldIds: string[],\n fieldOrder: string[],\n pinnedFieldIds: string[] = this.pinnedFieldIds\n ): void {\n this.dsFieldsConfigChange.emit(\n resolveTableFieldsConfiguration(this.columns, hiddenFieldIds, fieldOrder, pinnedFieldIds)\n );\n }\n\n private handleColumnCustomizerReorder(detail: MenuReorderDetail): void {\n const order = detail.items\n .filter(item => item.reorderable)\n .map(item => item.value)\n .filter((id): id is string => !!id);\n this.dsFieldsConfigChange.emit(\n reorderTableColumnPartition(\n this.columns,\n this.hiddenFieldIds,\n this.fieldOrder,\n this.pinnedFieldIds,\n order\n )\n );\n }\n\n private handleColumnCustomizerAction(detail: MenuItemToggleDetail): void {\n if (detail.action?.id === 'visibility') {\n this.handleColumnCustomizerSelect(detail.item);\n return;\n }\n if (detail.action?.id !== 'pin') return;\n const fieldId = detail.item.value;\n if (!fieldId) return;\n this.dsFieldsConfigChange.emit(\n toggleTableColumnPinned(\n this.columns,\n this.hiddenFieldIds,\n this.fieldOrder,\n this.pinnedFieldIds,\n fieldId\n )\n );\n }\n\n private handleColumnCustomizerSelect(item: MenuItemData): void {\n const fieldId = item.value;\n if (!fieldId || item.isInactive) return;\n this.emitColumnsConfigChange(\n toggleTableColumnHidden(this.columns, this.hiddenFieldIds, fieldId),\n this.fieldOrder\n );\n }\n\n render() {\n this.groupSentinelEls.clear();\n const model = this.createRenderModel();\n this.syncVirtualItems(model);\n this.renderedModel = model;\n const regionLabel = this.scrollLabel?.trim() || `${this.caption} scroll area`;\n const initialLoading = this.loading && !model.hasData;\n const initialError = !model.hasData && this.error;\n const hasGroupedStructure = model.grouped && model.groups.length > 0;\n const windowRows = this.shouldWindowRows(model);\n const virtualViewportMissing =\n this.virtualViewportMissing && !initialLoading && (model.hasData || hasGroupedStructure);\n const virtualPlan = windowRows\n ? (this.virtualWindow ??\n resolveTableVirtualPlan({\n items: this.virtualItems,\n sizes: this.virtualItems.map(item => this.virtualController.sizeFor(item)),\n scrollOffset: this.viewportEl?.scrollTop ?? 0,\n viewportSize: this.estimateVirtualViewportSize(),\n pinnedRowIds: this.virtualPinnedRowIds(),\n }))\n : null;\n const groupLoadingMore = hasGroupedStructure && this.groups.some(group => group.loadingMore);\n const viewportStyle =\n !this.boundedComposition && this.resolvedMaxHeight\n ? { '--ds-table-max-block-size': this.resolvedMaxHeight }\n : undefined;\n const hostStyle = this.fixedHeight\n ? { '--_table-fixed-block-size': this.resolvedHeight }\n : undefined;\n\n return (\n <Host\n class={{\n 'table-host': true,\n 'table-host--bounded': this.boundedComposition,\n 'table-host--fixed-height': this.fixedHeight,\n 'table-host--viewport-fit': this.fitViewport,\n }}\n style={hostStyle}\n onKeyDown={(event: KeyboardEvent) => {\n this.handleGridKeyDown(event);\n this.handlePaginationKeyDown(event);\n }}\n onCopy={(event: ClipboardEvent) => this.handleGridClipboard(event)}\n onPaste={(event: ClipboardEvent) => this.handleGridClipboard(event)}\n onFocusin={this.onVirtualFocusIn}\n >\n <div\n class={{\n 'ds-table': true,\n 'ds-table--bounded': this.boundedComposition,\n 'ds-table--contained-scroll': this.containedScroll,\n 'ds-table--fixed-height': this.fixedHeight,\n 'ds-table--viewport-fit': this.fitViewport,\n 'ds-table--viewport-fit-pending': this.fitViewport && !this.viewportFitSettled,\n 'ds-table--viewport-fit-settled': this.fitViewport && this.viewportFitSettled,\n 'ds-table--sticky-header': this.stickyHeader,\n 'ds-table--document-sticky-header': this.documentStickyHeader,\n 'ds-table--contained-sticky-header': this.stickyHeader && !this.documentStickyHeader,\n 'ds-table--caption-visible': this.captionVisibility === 'visible',\n 'ds-table--chrome-edge-to-edge': this.chromeLayout === 'edge-to-edge',\n 'ds-table--super-headers': this.structure.bands.length > 0,\n 'ds-table--responsive-cards':\n this.responsiveLayout === 'cards' &&\n this.interactionMode !== 'grid' &&\n this.cellSpans.length === 0,\n 'ds-table--cards-active':\n this.narrowViewport &&\n this.responsiveLayout === 'cards' &&\n this.interactionMode !== 'grid' &&\n this.cellSpans.length === 0,\n 'ds-table--footer-visible': this.hasResultFooter,\n 'ds-table--state-fill':\n !initialLoading &&\n (initialError || virtualViewportMissing || !(model.hasData || hasGroupedStructure)),\n }}\n ref={element => {\n this.rootEl = element ?? null;\n }}\n >\n {this.renderCaptionBar()}\n <div\n class={{\n 'ds-table__frame': true,\n 'ds-table__frame--overflow-start': this.overflowStart,\n 'ds-table__frame--overflow-end': this.overflowEnd,\n }}\n data-narrow={String(this.narrowViewport)}\n ref={element => {\n this.frameEl = element ?? null;\n }}\n >\n {this.alternateView ? <slot name=\"alternate-view\" /> : null}\n {!this.alternateView && this.renderDocumentStickyHeader(model)}\n {!this.alternateView && this.renderStickyGroup(model)}\n {!this.alternateView &&\n !this.documentStickyHeader &&\n this.renderFloatingCollapseAll(model)}\n {!this.alternateView && (\n <div\n class={{\n 'ds-table__viewport': true,\n 'ds-focus-ring': this.scrollable,\n }}\n style={viewportStyle}\n ref={element => {\n this.viewportEl = element ?? null;\n }}\n role={this.scrollable ? 'region' : undefined}\n aria-label={this.scrollable ? regionLabel : undefined}\n tabIndex={this.scrollable ? 0 : undefined}\n >\n <table\n class={{\n 'ds-table__table': true,\n 'ds-table__table--selectable': model.selectable,\n 'ds-table__table--grouped': model.grouped,\n 'ds-table__table--deferred-rows':\n this.dataMode !== 'virtual' && !this.structure.merges.hasRowSpans,\n 'ds-table__table--windowed': windowRows,\n 'ds-table__table--virtual': this.dataMode === 'virtual' && windowRows,\n 'ds-table__table--native-group-sticky':\n (model.grouped && this.stickyHeader && !this.documentStickyHeader) ||\n windowRows,\n }}\n style={model.tableStyle}\n role={this.gridEnabled ? 'grid' : 'table'}\n aria-multiselectable={this.gridEnabled ? 'true' : undefined}\n aria-rowcount={\n windowRows\n ? 1 + Number(this.structure.bands.length > 0) + this.virtualItems.length\n : undefined\n }\n aria-busy={\n initialLoading ||\n (this.dataMode === 'infinite' && (this.loadingMore || groupLoadingMore))\n ? 'true'\n : undefined\n }\n ref={element => {\n this.tableEl = element ?? null;\n }}\n >\n <caption class=\"ds-table__caption ds-visually-hidden\">\n <ds-text as=\"span\" variant=\"text-title-small\" emphasis={true} color=\"primary\">\n {this.caption}\n </ds-text>\n </caption>\n {this.renderColgroup(model)}\n {this.renderHeader(\n model,\n !this.documentStickyHeader,\n false,\n windowRows ? 1 : undefined\n )}\n {initialLoading\n ? this.renderSkeletonBody(model)\n : initialError\n ? this.renderStateBody('error', model.totalColumns)\n : virtualViewportMissing\n ? this.renderStateBody('virtual-viewport', model.totalColumns)\n : model.hasData || hasGroupedStructure\n ? this.renderDataBodies(model, virtualPlan)\n : this.renderStateBody('empty', model.totalColumns)}\n {!initialLoading &&\n !initialError &&\n this.dataMode !== 'virtual' &&\n this.renderLazyBody(model)}\n </table>\n </div>\n )}\n </div>\n {this.renderResultFooter()}\n {this.renderOverflowActionMenu()}\n {this.renderDataModeSwitcherMenu()}\n {this.renderColumnCustomizerMenu()}\n {this.renderTruncateTooltip()}\n <div class=\"ds-visually-hidden\" role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">\n {this.announcement}\n </div>\n </div>\n </Host>\n );\n }\n}\n",
|
|
1701
1717
|
"type": "registry:ui"
|
|
1702
1718
|
},
|
|
1703
1719
|
{
|
|
@@ -1812,7 +1828,7 @@
|
|
|
1812
1828
|
},
|
|
1813
1829
|
{
|
|
1814
1830
|
"path": "src/wc/components/Table/table-viewport-fit-controller.ts",
|
|
1815
|
-
"content": "import { resolveCssLengthPx } from '../../utils/resolve-css-length-px';\n\nexport interface TableViewportFitMetricInput {\n scrollportBlockStart: number;\n scrollportBlockSize: number;\n hostBlockStart: number;\n insetBlockStart: number;\n insetBlockEnd: number;\n}\n\nexport interface TableViewportFitMetrics {\n reservedBlockSize: number;\n currentBlockSize: number;\n settled: boolean;\n}\n\nexport interface TableViewportFitElements {\n host: HTMLElement | null;\n surface: HTMLElement | null;\n}\n\nexport interface TableViewportFitControllerOptions {\n enabled: () => boolean;\n elements: () => TableViewportFitElements;\n insets: () => { blockStart: string | number; blockEnd: string | number };\n fitChanged: (metrics: TableViewportFitMetrics | null) => void;\n}\n\n/** Resolve the reserved compact-state height and the height currently visible. */\nexport function resolveTableViewportFitMetrics(\n input: TableViewportFitMetricInput\n): TableViewportFitMetrics {\n const insetBlockStart = Math.max(0, input.insetBlockStart);\n const insetBlockEnd = Math.max(0, input.insetBlockEnd);\n const scrollportBlockEnd = input.scrollportBlockStart + input.scrollportBlockSize;\n const settledBlockStart = input.scrollportBlockStart + insetBlockStart;\n const reservedBlockSize = Math.max(\n 0,\n input.scrollportBlockSize - insetBlockStart - insetBlockEnd\n );\n const currentBlockStart = Math.max(input.hostBlockStart, settledBlockStart);\n const currentBlockSize = Math.min(\n reservedBlockSize,\n Math.max(0, scrollportBlockEnd - insetBlockEnd - currentBlockStart)\n );\n\n return {\n reservedBlockSize,\n currentBlockSize,\n settled: input.hostBlockStart <= settledBlockStart + 0.5,\n };\n}\n\n/**\n * Fits the complete table chrome to its nearest vertical scrollport. The host\n * reserves its compact-state height so the outer page can consume collapsing\n * header travel without changing document height. The visible table surface\n * grows into that reservation until it reaches the supplied sticky inset.\n */\nexport class TableViewportFitController {\n private connected = false;\n private connectedHost: HTMLElement | null = null;\n private connectedSurface: HTMLElement | null = null;\n private scrollRoot: HTMLElement | Window | null = null;\n private resizeObserver: ResizeObserver | null = null;\n private metrics: TableViewportFitMetrics | null = null;\n private insetBlockStart: string | number | null = null;\n private insetBlockEnd: string | number | null = null;\n\n constructor(private readonly options: TableViewportFitControllerOptions) {}\n\n connect(): void {\n this.connected = true;\n this.refresh();\n }\n\n disconnect(): void {\n this.connected = false;\n this.disconnectRuntime();\n this.clearGeometry();\n }\n\n refresh(forceGeometry = true): void {\n if (!this.connected) return;\n if (!this.options.enabled()) {\n this.disconnectRuntime();\n this.clearGeometry();\n return;\n }\n\n const { host, surface } = this.options.elements();\n if (!host) return;\n const elementsChanged = host !== this.connectedHost || surface !== this.connectedSurface;\n const nextScrollRoot =\n elementsChanged || !this.scrollRoot ? this.findScrollRoot(host) : this.scrollRoot;\n const rootChanged = nextScrollRoot !== this.scrollRoot;\n if (nextScrollRoot !== this.scrollRoot) {\n this.disconnectRuntime();\n this.scrollRoot = nextScrollRoot;\n this.scrollRoot.addEventListener('scroll', this.sync, { passive: true });\n window.addEventListener('resize', this.sync, { passive: true });\n if (typeof ResizeObserver !== 'undefined' && this.scrollRoot instanceof HTMLElement) {\n this.resizeObserver = new ResizeObserver(this.sync);\n this.resizeObserver.observe(this.scrollRoot);\n }\n }\n this.connectedHost = host;\n this.connectedSurface = surface;\n const insets = this.options.insets();\n const insetsChanged =\n insets.blockStart !== this.insetBlockStart || insets.blockEnd !== this.insetBlockEnd;\n this.insetBlockStart = insets.blockStart;\n this.insetBlockEnd = insets.blockEnd;\n if (forceGeometry || elementsChanged || rootChanged || insetsChanged) this.sync();\n }\n\n /** Pass a fitted table's boundary wheel delta to its owning page scrollport. */\n scrollOuterBy(delta: number): boolean {\n if (!this.scrollRoot || delta === 0) return false;\n if (this.scrollRoot instanceof HTMLElement) {\n const previous = this.scrollRoot.scrollTop;\n const max = Math.max(0, this.scrollRoot.scrollHeight - this.scrollRoot.clientHeight);\n this.scrollRoot.scrollTop = Math.min(max, Math.max(0, previous + delta));\n return this.scrollRoot.scrollTop !== previous;\n }\n\n const scrollingElement = document.scrollingElement;\n const previous = window.scrollY;\n const max = Math.max(\n 0,\n (scrollingElement?.scrollHeight ?? document.documentElement.scrollHeight) - window.innerHeight\n );\n const next = Math.min(max, Math.max(0, previous + delta));\n if (next !== previous) window.scrollTo({ top: next, behavior: 'auto' });\n return next !== previous;\n }\n\n private disconnectRuntime(): void {\n this.scrollRoot?.removeEventListener('scroll', this.sync);\n window.removeEventListener('resize', this.sync);\n this.scrollRoot = null;\n this.connectedHost = null;\n this.connectedSurface = null;\n this.resizeObserver?.disconnect();\n this.resizeObserver = null;\n this.insetBlockStart = null;\n this.insetBlockEnd = null;\n }\n\n private clearGeometry(): void {\n const { host, surface } = this.options.elements();\n host?.style.removeProperty('--_table-viewport-fit-reserved-block-size');\n surface?.style.removeProperty('--_table-viewport-fit-current-block-size');\n if (this.metrics !== null) {\n this.metrics = null;\n this.options.fitChanged(null);\n }\n }\n\n private readonly sync = (): void => {\n if (!this.connected || !this.options.enabled() || !this.scrollRoot) return;\n const { host, surface } = this.options.elements();\n if (!host) return;\n\n const hostRect = host.getBoundingClientRect();\n const scrollportRect =\n this.scrollRoot instanceof HTMLElement\n ? this.scrollRoot.getBoundingClientRect()\n : { top: 0, height: window.innerHeight };\n const insets = this.options.insets();\n const next = resolveTableViewportFitMetrics({\n scrollportBlockStart: scrollportRect.top,\n scrollportBlockSize: scrollportRect.height,\n hostBlockStart: hostRect.top,\n insetBlockStart: resolveCssLengthPx(insets.blockStart, 0, host),\n insetBlockEnd: resolveCssLengthPx(insets.blockEnd, 0, host),\n });\n\n this.setProperty(\n host,\n '--_table-viewport-fit-reserved-block-size',\n `${next.reservedBlockSize}px`\n );\n if (surface) {\n this.setProperty(\n surface,\n '--_table-viewport-fit-current-block-size',\n `${next.currentBlockSize}px`\n );\n }\n if (\n !this.metrics ||\n this.metrics.reservedBlockSize !== next.reservedBlockSize ||\n this.metrics.currentBlockSize !== next.currentBlockSize ||\n this.metrics.settled !== next.settled\n ) {\n this.metrics = next;\n this.options.fitChanged(next);\n }\n };\n\n private findScrollRoot(host: HTMLElement): HTMLElement | Window {\n let ancestor = this.composedParent(host);\n while (ancestor && ancestor !== document.documentElement) {\n const overflow = getComputedStyle(ancestor).overflowY;\n if (overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay') {\n return ancestor as HTMLElement;\n }\n ancestor = this.composedParent(ancestor);\n }\n return window;\n }\n\n private composedParent(element: Element): Element | null {\n return (element as HTMLElement).assignedSlot?.parentElement ?? element.parentElement;\n }\n\n private setProperty(element: HTMLElement, property: string, value: string): void {\n if (element.style.getPropertyValue(property) !== value) {\n element.style.setProperty(property, value);\n }\n }\n}\n",
|
|
1831
|
+
"content": "import { resolveCssLengthPx } from '../../utils/resolve-css-length-px';\n\nexport interface TableViewportFitMetricInput {\n scrollportBlockStart: number;\n scrollportBlockSize: number;\n hostBlockStart: number;\n insetBlockStart: number;\n insetBlockEnd: number;\n}\n\nexport interface TableViewportFitMetrics {\n reservedBlockSize: number;\n currentBlockSize: number;\n settled: boolean;\n}\n\nexport interface TableViewportFitElements {\n host: HTMLElement | null;\n surface: HTMLElement | null;\n}\n\nexport interface TableViewportFitControllerOptions {\n enabled: () => boolean;\n elements: () => TableViewportFitElements;\n insets: () => { blockStart: string | number; blockEnd: string | number };\n fitChanged: (metrics: TableViewportFitMetrics | null) => void;\n}\n\n/** Resolve the reserved compact-state height and the height currently visible. */\nexport function resolveTableViewportFitMetrics(\n input: TableViewportFitMetricInput\n): TableViewportFitMetrics {\n const insetBlockStart = Math.max(0, input.insetBlockStart);\n const insetBlockEnd = Math.max(0, input.insetBlockEnd);\n const scrollportBlockEnd = input.scrollportBlockStart + input.scrollportBlockSize;\n const settledBlockStart = input.scrollportBlockStart + insetBlockStart;\n const reservedBlockSize = Math.max(\n 0,\n input.scrollportBlockSize - insetBlockStart - insetBlockEnd\n );\n const currentBlockStart = Math.max(input.hostBlockStart, settledBlockStart);\n const currentBlockSize = Math.min(\n reservedBlockSize,\n Math.max(0, scrollportBlockEnd - insetBlockEnd - currentBlockStart)\n );\n\n return {\n reservedBlockSize,\n currentBlockSize,\n settled: input.hostBlockStart <= settledBlockStart + 0.5,\n };\n}\n\n/**\n * Fits the complete table chrome to its nearest vertical scrollport. The host\n * reserves its compact-state height so the outer page can consume collapsing\n * header travel without changing document height. The visible table surface\n * grows into that reservation until it reaches the supplied sticky inset.\n */\nexport class TableViewportFitController {\n private connected = false;\n private connectedHost: HTMLElement | null = null;\n private connectedSurface: HTMLElement | null = null;\n private scrollRoot: HTMLElement | Window | null = null;\n private resizeObserver: ResizeObserver | null = null;\n private ancestorMutationObserver: MutationObserver | null = null;\n private connectionFrame: number | null = null;\n private metrics: TableViewportFitMetrics | null = null;\n private insetBlockStart: string | number | null = null;\n private insetBlockEnd: string | number | null = null;\n\n constructor(private readonly options: TableViewportFitControllerOptions) {}\n\n connect(): void {\n this.connected = true;\n this.refresh();\n // WebKit can finish attaching an upgraded custom element after its first\n // layout read. Verify the owning scrollport on the next animation frame.\n if (this.connectionFrame === null && typeof requestAnimationFrame !== 'undefined') {\n this.connectionFrame = requestAnimationFrame(() => {\n this.connectionFrame = null;\n this.refresh();\n });\n }\n }\n\n disconnect(): void {\n this.connected = false;\n if (this.connectionFrame !== null) cancelAnimationFrame(this.connectionFrame);\n this.connectionFrame = null;\n this.disconnectRuntime();\n this.clearGeometry();\n }\n\n refresh(forceGeometry = true): void {\n if (!this.connected) return;\n if (!this.options.enabled()) {\n this.disconnectRuntime();\n this.clearGeometry();\n return;\n }\n\n const { host, surface } = this.options.elements();\n if (!host) return;\n const elementsChanged = host !== this.connectedHost || surface !== this.connectedSurface;\n // A web component can be reconnected under a different scroll owner while\n // retaining the same host and rendered surface nodes.\n const nextScrollRoot =\n elementsChanged || forceGeometry || !this.scrollRoot\n ? this.findScrollRoot(host)\n : this.scrollRoot;\n const rootChanged = nextScrollRoot !== this.scrollRoot;\n if (nextScrollRoot !== this.scrollRoot) {\n this.disconnectRuntime();\n this.scrollRoot = nextScrollRoot;\n this.scrollRoot.addEventListener('scroll', this.sync, { passive: true });\n window.addEventListener('resize', this.sync, { passive: true });\n if (typeof ResizeObserver !== 'undefined' && this.scrollRoot instanceof HTMLElement) {\n this.resizeObserver = new ResizeObserver(this.sync);\n this.resizeObserver.observe(this.scrollRoot);\n }\n }\n this.connectedHost = host;\n this.connectedSurface = surface;\n if (elementsChanged || rootChanged || forceGeometry) this.observeAncestorInsets(host);\n const insets = this.options.insets();\n const insetsChanged =\n insets.blockStart !== this.insetBlockStart || insets.blockEnd !== this.insetBlockEnd;\n this.insetBlockStart = insets.blockStart;\n this.insetBlockEnd = insets.blockEnd;\n if (forceGeometry || elementsChanged || rootChanged || insetsChanged) this.sync();\n }\n\n /** Pass a fitted table's boundary wheel delta to its owning page scrollport. */\n scrollOuterBy(delta: number): boolean {\n if (!this.scrollRoot || delta === 0) return false;\n if (this.scrollRoot instanceof HTMLElement) {\n const previous = this.scrollRoot.scrollTop;\n const max = Math.max(0, this.scrollRoot.scrollHeight - this.scrollRoot.clientHeight);\n this.scrollRoot.scrollTop = Math.min(max, Math.max(0, previous + delta));\n return this.scrollRoot.scrollTop !== previous;\n }\n\n const scrollingElement = document.scrollingElement;\n const previous = window.scrollY;\n const max = Math.max(\n 0,\n (scrollingElement?.scrollHeight ?? document.documentElement.scrollHeight) - window.innerHeight\n );\n const next = Math.min(max, Math.max(0, previous + delta));\n if (next !== previous) window.scrollTo({ top: next, behavior: 'auto' });\n return next !== previous;\n }\n\n private disconnectRuntime(): void {\n this.scrollRoot?.removeEventListener('scroll', this.sync);\n window.removeEventListener('resize', this.sync);\n this.scrollRoot = null;\n this.connectedHost = null;\n this.connectedSurface = null;\n this.resizeObserver?.disconnect();\n this.resizeObserver = null;\n this.ancestorMutationObserver?.disconnect();\n this.ancestorMutationObserver = null;\n this.insetBlockStart = null;\n this.insetBlockEnd = null;\n }\n\n private observeAncestorInsets(host: HTMLElement): void {\n this.ancestorMutationObserver?.disconnect();\n this.ancestorMutationObserver = null;\n if (typeof MutationObserver === 'undefined') return;\n\n // A page shell can replace its inset class after the table first measures.\n // Its inherited CSS variable then changes without resizing the scrollport,\n // so ResizeObserver alone cannot update the reserved table height.\n const observer = new MutationObserver(this.sync);\n let ancestor = this.composedParent(host);\n while (ancestor) {\n observer.observe(ancestor, { attributes: true });\n if (ancestor === document.documentElement) break;\n ancestor = this.composedParent(ancestor);\n }\n this.ancestorMutationObserver = observer;\n }\n\n private clearGeometry(): void {\n const { host, surface } = this.options.elements();\n host?.style.removeProperty('--_table-viewport-fit-reserved-block-size');\n surface?.style.removeProperty('--_table-viewport-fit-current-block-size');\n if (this.metrics !== null) {\n this.metrics = null;\n this.options.fitChanged(null);\n }\n }\n\n private readonly sync = (): void => {\n if (!this.connected || !this.options.enabled() || !this.scrollRoot) return;\n const { host, surface } = this.options.elements();\n if (!host) return;\n\n const hostRect = host.getBoundingClientRect();\n const scrollportRect =\n this.scrollRoot instanceof HTMLElement\n ? this.scrollRoot.getBoundingClientRect()\n : { top: 0, height: window.innerHeight };\n const insets = this.options.insets();\n const next = resolveTableViewportFitMetrics({\n scrollportBlockStart: scrollportRect.top,\n scrollportBlockSize: scrollportRect.height,\n hostBlockStart: hostRect.top,\n insetBlockStart: resolveCssLengthPx(insets.blockStart, 0, host),\n insetBlockEnd: resolveCssLengthPx(insets.blockEnd, 0, host),\n });\n\n this.setProperty(\n host,\n '--_table-viewport-fit-reserved-block-size',\n `${next.reservedBlockSize}px`\n );\n if (surface) {\n this.setProperty(\n surface,\n '--_table-viewport-fit-current-block-size',\n `${next.currentBlockSize}px`\n );\n }\n if (\n !this.metrics ||\n this.metrics.reservedBlockSize !== next.reservedBlockSize ||\n this.metrics.currentBlockSize !== next.currentBlockSize ||\n this.metrics.settled !== next.settled\n ) {\n this.metrics = next;\n this.options.fitChanged(next);\n }\n };\n\n private findScrollRoot(host: HTMLElement): HTMLElement | Window {\n let ancestor = this.composedParent(host);\n while (ancestor && ancestor !== document.documentElement) {\n const overflow = getComputedStyle(ancestor).overflowY;\n if (overflow === 'auto' || overflow === 'scroll' || overflow === 'overlay') {\n return ancestor as HTMLElement;\n }\n ancestor = this.composedParent(ancestor);\n }\n return window;\n }\n\n private composedParent(element: Element): Element | null {\n return (element as HTMLElement).assignedSlot?.parentElement ?? element.parentElement;\n }\n\n private setProperty(element: HTMLElement, property: string, value: string): void {\n if (element.style.getPropertyValue(property) !== value) {\n element.style.setProperty(property, value);\n }\n }\n}\n",
|
|
1816
1832
|
"type": "registry:ui"
|
|
1817
1833
|
},
|
|
1818
1834
|
{
|