@aceshooting/lyra-ui 30.8.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/CHANGELOG.md +239 -329
  2. package/dist/ai/adapters/ag-ui.js +1 -1
  3. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  4. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  5. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  6. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  7. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  8. package/dist/components/charts/chart/box-plot-loader.js +1 -1
  9. package/dist/components/charts/chart/box-plot.class.js +2 -2
  10. package/dist/components/charts/chart/chart-core-loader.js +1 -1
  11. package/dist/components/charts/chart/chart-feature-loader.js +1 -1
  12. package/dist/components/charts/chart/chart-sync.js +1 -1
  13. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  14. package/dist/components/charts/chart/chart.class.js +4 -4
  15. package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
  16. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  17. package/dist/components/charts/chart-3d/chart-3d-engine.js +1 -1
  18. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
  19. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  20. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  21. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  22. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  23. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  24. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  25. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  26. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  27. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  28. package/dist/components/conversation/code-block/code-loader.js +1 -1
  29. package/dist/components/conversation/code-block/shiki-oniguruma.js +1 -1
  30. package/dist/components/conversation/code-block/shiki-types.js +1 -1
  31. package/dist/components/conversation/markdown/katex-loader.js +1 -1
  32. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  33. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  34. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  35. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  36. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  37. package/dist/components/conversation/markdown/markdown-loader.js +1 -1
  38. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  39. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  40. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  41. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  42. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  43. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  44. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
  45. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  46. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  47. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  48. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  49. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  50. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  51. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  52. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  53. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  54. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  55. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  56. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  57. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  58. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  59. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  60. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  61. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  62. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  63. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  64. package/dist/components/data/pagination/pagination.class.js +1 -1
  65. package/dist/components/data/table/table.class.d.ts +31 -2
  66. package/dist/components/data/table/table.class.js +3 -3
  67. package/dist/components/data/table/table.styles.js +1 -1
  68. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  69. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  70. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  71. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  72. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  73. package/dist/components/data/timeline/timeline.class.js +9 -5
  74. package/dist/components/data/tree/tree-item.class.js +1 -1
  75. package/dist/components/data/tree/tree.class.d.ts +2 -0
  76. package/dist/components/data/tree/tree.class.js +1 -1
  77. package/dist/components/forms/button/button.class.d.ts +8 -6
  78. package/dist/components/forms/button/button.class.js +2 -2
  79. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  80. package/dist/components/forms/color-picker/color-core.js +1 -1
  81. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  82. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  83. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  84. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  85. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  86. package/dist/components/forms/input/input-shared.js +2 -2
  87. package/dist/components/forms/input/number-input-locale.js +1 -0
  88. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  89. package/dist/components/forms/input/number-input.class.js +2 -2
  90. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  91. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  92. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  93. package/dist/components/layout/details/accordion-item.class.js +1 -1
  94. package/dist/components/layout/menu/menu.class.js +1 -1
  95. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  96. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  97. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  98. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  99. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  100. package/dist/components/layout/tab-group/tab.class.js +1 -1
  101. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  102. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  103. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  104. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  105. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  106. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  107. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  108. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  109. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  110. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  111. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  112. package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -1
  113. package/dist/components/media/flag/flag-peer-bulk.js +1 -1
  114. package/dist/components/media/flag/flag-peer.js +1 -1
  115. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  116. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  117. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  118. package/dist/components/media/map/map-feature-loader.js +1 -1
  119. package/dist/components/media/map/map-loader.js +1 -1
  120. package/dist/components/media/map/map-owned-features.js +1 -1
  121. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  122. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  123. package/dist/components/media/map/map.class.d.ts +5 -5
  124. package/dist/components/media/map/map.class.js +3 -3
  125. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  126. package/dist/components/media/qr-code/qr-code-loader.js +1 -1
  127. package/dist/components/media/video/video.class.d.ts +3 -3
  128. package/dist/components/media/video/video.class.js +3 -1
  129. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  130. package/dist/components/overlays/chip/chip.class.js +1 -1
  131. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  132. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  133. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  134. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  135. package/dist/components/retrieval/graph/graph-engine-adapter.js +1 -1
  136. package/dist/components/retrieval/graph/graph-loader.js +1 -1
  137. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  138. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  139. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  140. package/dist/components/retrieval/graph/graph.class.js +1 -1
  141. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  142. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  143. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  144. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  145. package/dist/components/utility/icon/dompurify-loader.js +1 -1
  146. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  147. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  148. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  149. package/dist/components/utility/known-date/known-date.class.js +1 -1
  150. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  151. package/dist/components/viewers/calendar-viewer/calendar-loader.js +1 -1
  152. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  153. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  154. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  155. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  156. package/dist/components/viewers/docx-viewer/docx-loader.js +1 -1
  157. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  158. package/dist/components/viewers/ebook-viewer/ebook-loader.js +1 -1
  159. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  160. package/dist/components/viewers/ebook-viewer/epub-unload-guard.js +1 -0
  161. package/dist/components/viewers/email-viewer/email-loader.js +1 -1
  162. package/dist/components/viewers/html-viewer/dompurify-loader.js +1 -1
  163. package/dist/components/viewers/include/include.class.js +1 -1
  164. package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
  165. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  166. package/dist/components/viewers/notebook-viewer/dompurify-loader.js +1 -1
  167. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  168. package/dist/components/viewers/pdf-viewer/pdf-loader.js +1 -1
  169. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  170. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  171. package/dist/components/viewers/pptx-viewer/pptx-loader.js +1 -1
  172. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-loader.js +1 -1
  173. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  174. package/dist/components/viewers/svg-viewer/dompurify-loader.js +1 -1
  175. package/dist/components/viewers/table-viewer-shared.js +4 -4
  176. package/dist/framework-types.d.ts +1 -1
  177. package/dist/internal/anchored-overlay-runtime.js +1 -1
  178. package/dist/internal/catalog-picker.js +1 -1
  179. package/dist/internal/document-tokens.js +2 -2
  180. package/dist/internal/dompurify-loader.js +1 -1
  181. package/dist/internal/drop-session-controller.js +1 -1
  182. package/dist/internal/engine-3d.js +1 -1
  183. package/dist/internal/icon-only-content.js +1 -1
  184. package/dist/internal/layered-layout.js +1 -1
  185. package/dist/internal/locale-loaders.generated.js +1 -1
  186. package/dist/internal/map-custom-layer-controller.js +1 -1
  187. package/dist/internal/map-scene-layer-runtime.js +1 -1
  188. package/dist/internal/media-panorama.js +1 -1
  189. package/dist/internal/package-metadata.js +1 -1
  190. package/dist/internal/papaparse-loader.js +1 -1
  191. package/dist/internal/safe-url.js +1 -1
  192. package/dist/internal/scoped-definitions.generated.js +1 -1
  193. package/dist/internal/scroll-overflow.js +1 -1
  194. package/dist/internal/source-window-controller.js +1 -1
  195. package/dist/internal/text-quote.js +1 -1
  196. package/dist/internal/viewer-search.js +1 -1
  197. package/dist/lyra.d.ts +1 -1
  198. package/dist/sequence-time-binding.js +1 -1
  199. package/dist/simulation-clock.js +1 -1
  200. package/dist/styles/reservations.css +1 -1
  201. package/dist/styles/reservations.styles.js +1 -1
  202. package/dist/testing/happy-dom-shims.js +1 -1
  203. package/dist/theme/theme.js +1 -1
  204. package/dist/theme-core.css +1 -0
  205. package/dist/utilities/scoped-registry.js +1 -1
  206. package/llms/components/lr-attachment-chip.md +27 -12
  207. package/llms/components/lr-attachment-trigger.md +27 -7
  208. package/llms/components/lr-button.md +6 -4
  209. package/llms/components/lr-chat-composer.md +13 -7
  210. package/llms/components/lr-chat-message.md +44 -3
  211. package/llms/components/lr-chat-viewport.md +39 -2
  212. package/llms/components/lr-data-grid.md +2 -0
  213. package/llms/components/lr-dialog.md +10 -0
  214. package/llms/components/lr-drop-zone.md +26 -2
  215. package/llms/components/lr-icon-button.md +2 -1
  216. package/llms/components/lr-json-viewer.md +17 -0
  217. package/llms/components/lr-locale-picker.md +5 -0
  218. package/llms/components/lr-markdown-core.md +2 -1
  219. package/llms/components/lr-markdown.md +20 -4
  220. package/llms/components/lr-menu.md +3 -1
  221. package/llms/components/lr-number-input.md +28 -1
  222. package/llms/components/lr-prompt-input.md +1 -1
  223. package/llms/components/lr-streaming-text-core.md +3 -2
  224. package/llms/components/lr-streaming-text.md +4 -1
  225. package/llms/components/lr-suggestion-chips.md +28 -5
  226. package/llms/components/lr-tab-group.md +13 -1
  227. package/llms/components/lr-tab.md +5 -0
  228. package/llms/components/lr-table.md +25 -4
  229. package/llms/components/lr-timeline-item.md +1 -1
  230. package/llms/components/lr-timeline.md +38 -4
  231. package/llms/components/lr-tooltip.md +3 -1
  232. package/llms/components/lr-tree.md +4 -0
  233. package/llms/components/lr-virtual-list.md +1 -0
  234. package/llms/peers.md +2 -2
  235. package/llms/shared/ai-and-peers.md +34 -0
  236. package/llms/shared/forms-and-accessibility.md +21 -4
  237. package/llms/shared/imports-and-registration.md +2 -0
  238. package/llms/shared/styles-and-tokens.md +47 -1
  239. package/llms/shared.md +104 -5
  240. package/package.json +25 -21
  241. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{ColumnResizePointerSession,columnResizeAriaValues,columnResizeKeyboardWidth,columnResizePointerWidth}from"../../../internal/column-resize.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteDuration,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{aggregateValues,columnId,columnValue,filterRows,textFilterCorpus,pathValue,rowsAsDelimited,searchRows,searchHaystacks,sortRows}from"./data-grid-processing.js";import{styles}from"./data-grid.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dataGridColumnMenu,LYRA_DEFAULT_dataGridPinEnd,LYRA_DEFAULT_dataGridPinStart,LYRA_DEFAULT_dataGridRowLimit,LYRA_DEFAULT_dataGridRowsPerPage,LYRA_DEFAULT_dataGridTreeLimitReached,LYRA_DEFAULT_dataGridUnpin,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_paginationJumpToPage,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_tableFilterLabel}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_next,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_paginationFirstPage,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_paginationLastPage,LYRA_DEFAULT_previous,LYRA_DEFAULT_resizeValuePixels,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";export*from"./data-grid-types.js";const selectableConverter={fromAttribute(value){return value===null?"none":value===""||value==="multiple"?"multiple":value==="single"||value==="none"?value:"none"},toAttribute(value){return value==="none"?null:value===""||value==="multiple"?"":value}},displayKeys=new WeakMap;function displayItemKey(item){let key=displayKeys.get(item);return key||(key=item.kind==="group"?`group:${item.key.length}:${item.key}`:`row:${typeof item.key}:${String(item.key)}`,displayKeys.set(item,key)),key}const DATA_GRID_COLUMN_PROPERTIES=["id","field","label","align","width","minWidth","maxWidth","flex","formatter","cellTitle","value","sortable","sortFn","comparator","sortDescFirst","sortUndefined","searchable","filterable","filterType","filterFn","hidden","hideable","resizable","movable","pinnable","pinned","footer","aggregation","aggregatedFormatter"],DATA_GRID_COLUMN_CALLBACK_PROPERTIES=new Set(["formatter","cellTitle","value","comparator","filterFn","aggregatedFormatter"]),DATA_GRID_SORT_ALGORITHMS=new Set(["alphanumeric","alphanumericCaseSensitive","text","textCaseSensitive","datetime","basic"]),DATA_GRID_FILTER_TYPES=new Set(["text","equals","number-range","date-range","set","includes-any","includes-all"]),DATA_GRID_AGGREGATIONS=new Set(["sum","min","max","mean","median","count","unique","uniqueCount","extent"]);function isSafeColumnPropertyValue(property2,value){if(value===void 0)return!0;if(DATA_GRID_COLUMN_CALLBACK_PROPERTIES.has(property2))return typeof value=="function";switch(property2){case"id":case"field":case"label":return typeof value=="string";case"width":case"minWidth":case"maxWidth":case"flex":return typeof value=="number"&&Number.isFinite(value);case"sortable":case"sortDescFirst":case"searchable":case"filterable":case"hidden":case"hideable":case"resizable":case"movable":case"pinnable":return typeof value=="boolean";case"align":return value==="left"||value==="center"||value==="right"||value==="start"||value==="end";case"sortFn":return typeof value=="string"&&DATA_GRID_SORT_ALGORITHMS.has(value);case"sortUndefined":return value==="first"||value==="last"||value===1||value===-1;case"filterType":return typeof value=="string"&&DATA_GRID_FILTER_TYPES.has(value);case"pinned":return value===!1||value==="left"||value==="right"||value==="start"||value==="end";case"footer":return typeof value=="string"||typeof value=="function";default:return typeof value=="function"||typeof value=="string"&&DATA_GRID_AGGREGATIONS.has(value)}}function snapshotColumns(value,occurrenceId){const output=[],seen=new Set;let length=0;try{if(!Array.isArray(value))return Object.freeze(output);const descriptor=getOwnDataDescriptor(value,"length"),sourceLength=descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;typeof sourceLength=="number"&&Number.isSafeInteger(sourceLength)&&sourceLength>=0&&(length=Math.min(sourceLength,MAX_DATA_GRID_COLUMN_ENTRIES))}catch{return Object.freeze(output)}for(let index=0;index<length;index+=1){const candidate=getOwnDataDescriptor(value,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const column=candidate.value;try{if(column===null||typeof column!="object"||Array.isArray(column))continue;const descriptors=new Map;for(const property2 of DATA_GRID_COLUMN_PROPERTIES)descriptors.set(property2,getOwnDataDescriptor(column,property2));const idDescriptor=descriptors.get("id")??MISSING_OWN_DATA_DESCRIPTOR,fieldDescriptor=descriptors.get("field")??MISSING_OWN_DATA_DESCRIPTOR;if(idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const hasId=idDescriptor!==MISSING_OWN_DATA_DESCRIPTOR,authoredId=hasId?idDescriptor.value:void 0,hasSafeId=typeof authoredId=="string"&&authoredId.trim()!=="";if(hasId&&authoredId!==void 0&&!hasSafeId)continue;const hasField=fieldDescriptor!==MISSING_OWN_DATA_DESCRIPTOR,authoredField=fieldDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!hasField?void 0:fieldDescriptor.value,hasSafeField=typeof authoredField=="string"&&authoredField.trim()!=="";if(!hasSafeId&&(fieldDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||hasField&&authoredField!==void 0&&!hasSafeField))continue;const identity=hasSafeId?authoredId:hasSafeField?authoredField:occurrenceId(column);if(seen.has(identity))continue;seen.add(identity);const snapshot=Object.create(null);for(const property2 of DATA_GRID_COLUMN_PROPERTIES){const descriptor=descriptors.get(property2);descriptor===void 0||descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||property2==="field"&&!hasSafeField||isSafeColumnPropertyValue(property2,descriptor.value)&&(snapshot[property2]=descriptor.value)}authoredId===void 0&&authoredField===void 0&&(snapshot.id=identity),output.push(Object.freeze(snapshot))}catch{}}return Object.freeze(output)}const INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"], [role="option"], [role="radio"], [role="separator"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"], [role="textbox"]',VIRTUALIZATION_THRESHOLD=80,VIRTUAL_OVERSCAN=5,DATA_GRID_TREE_NODE_LIMIT=1e4,DATA_GRID_TREE_DEPTH_LIMIT=64,MAX_DATA_GRID_COLUMN_ENTRIES=1e4,DATA_GRID_DRAG_TYPE="application/x-lyra-data-grid-column",REBIND_NO_SNAPSHOT=Symbol("no snapshot");function frozenArray(values){return Object.freeze([...values])}function sameFilterState(left,right){return left.length!==right.length?!1:left.every((filter,index)=>{const other=right[index];if(!other||filter.id!==other.id)return!1;const value=filter.value,otherValue=other.value;return Array.isArray(value)||Array.isArray(otherValue)?!Array.isArray(value)||!Array.isArray(otherValue)?!1:value.length===otherValue.length&&value.every((entry,position)=>Object.is(entry,otherValue[position])):Object.is(value,otherValue)})}function sameSortState(left,right){return left.length===right.length&&left.every((entry,index)=>{const other=right[index];return other!==void 0&&entry.id===other.id&&entry.desc===other.desc})}function serializableFilterValue(value){try{const serialized=JSON.stringify({value},(_key,nested)=>typeof nested=="bigint"?nested.toString():typeof nested=="number"&&!Number.isFinite(nested)?null:nested!==null&&typeof nested=="object"&&Object.prototype.toString.call(nested)==="[object Set]"?[...nested]:nested);if(!serialized)return null;const snapshot=JSON.parse(serialized).value??null,stack=[snapshot],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(!(current===null||typeof current!="object"||visited.has(current))){visited.add(current);for(const nested of Object.values(current))stack.push(nested);Object.freeze(current)}}return snapshot}catch{return null}}function isKey(value){return typeof value=="string"&&value.trim()!==""||typeof value=="number"&&Number.isFinite(value)}function snapshotKeys(value){if(!(Array.isArray(value)||value!==null&&typeof value=="object"&&typeof value[Symbol.iterator]=="function"))return Object.freeze([]);const output=[],seen=new Set;try{for(const key of value)!isKey(key)||seen.has(key)||(seen.add(key),output.push(key))}catch{}return frozenArray(output)}function keysEqual(left,right){return typeof left==typeof right&&left===right}function typedKey(key){return`${typeof key}:${String(key)}`}const frozenKeyIndexes=new WeakMap;function arrayHasKey(keys,key){let index=frozenKeyIndexes.get(keys);if(!index){if(!Object.isFrozen(keys))return keys.some(candidate=>keysEqual(candidate,key));index=new Set(keys.map(typedKey)),frozenKeyIndexes.set(keys,index)}return index.has(typedKey(key))}function isElementValue(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.closest=="function"}function valueControl(value){return!isElementValue(value)||typeof value.value!="string"?null:value}function checkableControl(value){return!isElementValue(value)||typeof value.checked!="boolean"?null:value}function dateText(value){try{const timestamp=Date.prototype.getTime.call(value);return Number.isFinite(timestamp)?Date.prototype.toISOString.call(value):""}catch{return}}function humanizeIdentifier(value,locale){const intlLocale=resolveIntlLocale(locale);return value.replaceAll(/[._-]+/gu," ").replaceAll(/([a-z\d])([A-Z])/gu,"$1 $2").replace(/^./u,first=>first.toLocaleUpperCase(intlLocale))}function safeText(value){if(value==null)return"";if(typeof value=="object"){const serializedDate=dateText(value);if(serializedDate!==void 0)return serializedDate}if(Array.isArray(value))return value.map(safeText).join(", ");if(typeof value=="object")try{return JSON.stringify(value,(_key,nested)=>typeof nested=="bigint"?nested.toString():nested)??""}catch{return""}return String(value)}function normalizePinSide(side){return side==="start"?"left":side==="end"?"right":side}function normalizedGroupBy(value){return typeof value!="string"?(value??[]).map(entry=>entry.trim()).filter(Boolean).slice(0,DATA_GRID_TREE_DEPTH_LIMIT):value.split(/[\s,]+/u).map(entry=>entry.trim()).filter(Boolean).slice(0,DATA_GRID_TREE_DEPTH_LIMIT)}class LyraDataGrid extends LyraElement{constructor(){super(...arguments),this.appearance="outlined",this.childRows=null,this.assignedSources=new CollectionSourceTracker,this._columnOrder=Object.freeze([]),this.columnOccurrenceIds=new WeakMap,this.nextColumnOccurrenceId=1,this.rowOccurrenceIds=new WeakMap,this.nextRowOccurrenceId=1,this._columns=Object.freeze([]),this.maxRows=1e4,this.dataAdmissionTruncated=!1,this.dataAdmissionLimit=1e4,this._data=Object.freeze([]),this.dataSource=null,this._expandedRowKeys=Object.freeze([]),this.filterDebounce=250,this.filterFromLeafRows=!1,this._filters=Object.freeze([]),this._groupBy=null,this.label=null,this.loading=!1,this.error=!1,this.errorDescription="",this.maxMultiSort=0,this.page=0,this.pageSize=20,this._pageSizeOptions=Object.freeze([10,20,50,100]),this.paginate=!1,this.pinnable=!1,this.reorderable=!1,this.resizable=!1,this.rowClass=null,this.rowDetail=null,this.rowKey=null,this.searchFn=null,this.searchTerm="",this.selectable="none",this.selectableRows=null,this._selectedRowKeys=Object.freeze([]),this.server=!1,this.size="m",this._sort=Object.freeze([]),this.sortDescFirst=!1,this.striped=!1,this.total=-1,this.withColumnMenu=!1,this.withColumnsMenu=!1,this.withoutSortRemoval=!1,this.withSearch=!1,this.columnWidths=new Map,this.columnVisibility=new Map,this.columnPinning=new Map,this.activeFilterColumn=null,this.columnsMenuOpen=!1,this.activeColumnMenu=null,this.liveText="",this.bodyScrollTop=0,this.bodyScrollInlineOffset=0,this.viewportHeight=0,this.focusedRow=-1,this.focusedColumn=0,this.dragGhost="",this.requestGeneration=0,this.requestDebounce=new DebounceController(0,owner=>{this.loadServerData(owner)},()=>this.ownerDocument.defaultView),this.ownsLoadingState=!1,this.resizePointer=new ColumnResizePointerSession(event=>this.onResizeMove(event),event=>this.onResizeEnd(event),event=>this.onResizeCancel(event)),this.columnDragSequence=0,this.managedOverlayOwner=null,this.lastSelectedIndex=-1,this.isMounting=!0,this.pipelineEpoch=0,this.contentRefreshPending=!1,this.pipelineMemo=new Map,this.measuredItemHeights=new Map,this.measuredOffsetTree=[0],this.measuredOffsetHeights=[],this.measuredItemOffsetSignature="",this.measuredItemOffsetEstimate=0,this.measuredItemOffsetsDirty=!0,this.measurementLocale="",this.measurementDisplaySignature="",this.measurementFontSignature="",this.measurementFontHasRendered=!1,this.bodyScrollbarInlineEndGutter=0,this.observedMeasurementElements=new Map,this.observedMeasurementBlockSizes=new Map,this.measurementUpdateQueued=!1,this.measurementScrollSyncQueued=!1,this.bodyScrollStateSyncQueued=!1,this.restoreCellFocus=!1,this.onClearSearch=()=>{this.searchTerm!==""&&(this.applySearchTermChange(""),this.emit("lr-search-change",Object.freeze({searchTerm:""})),this.renderRoot.querySelector('[part="search"]')?.focus())},this.onSearchInput=event=>{const before=this.searchTerm;this.applySearchTermChange(event),this.searchTerm!==before&&this.emit("lr-search-change",Object.freeze({searchTerm:this.searchTerm}))},this.signatureValue="",this.geometryCycle=!1,this.relayEditorFocus=event=>{relayNativeEvent(this,event)},this.relayEditorBlur=event=>{relayNativeEvent(this,event)},this.onErrorRetry=()=>{this.error=!1}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copyFailed:LYRA_DEFAULT_copyFailed,dataGridColumnMenu:LYRA_DEFAULT_dataGridColumnMenu,dataGridPinEnd:LYRA_DEFAULT_dataGridPinEnd,dataGridPinStart:LYRA_DEFAULT_dataGridPinStart,dataGridRowLimit:LYRA_DEFAULT_dataGridRowLimit,dataGridRowsPerPage:LYRA_DEFAULT_dataGridRowsPerPage,dataGridTreeLimitReached:LYRA_DEFAULT_dataGridTreeLimitReached,dataGridUnpin:LYRA_DEFAULT_dataGridUnpin,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,next:LYRA_DEFAULT_next,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,paginationFirstPage:LYRA_DEFAULT_paginationFirstPage,paginationJumpToPage:LYRA_DEFAULT_paginationJumpToPage,paginationLabel:LYRA_DEFAULT_paginationLabel,paginationLastPage:LYRA_DEFAULT_paginationLastPage,previous:LYRA_DEFAULT_previous,resizeColumn:LYRA_DEFAULT_resizeColumn,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showAllColumns:LYRA_DEFAULT_showAllColumns,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-request","request","lr-column-move","lr-data-error"])}static{this.identityEventDetailProperties=Object.freeze({"lr-request":Object.freeze(["signal"]),request:Object.freeze(["signal"]),"lr-data-error":Object.freeze(["error","request"])})}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}isRebind(name,value,current){return this.assignedSources.isRebind(name,value,current)}get columnOrder(){return this._columnOrder}set columnOrder(value){if(this.isRebind("columnOrder",value,this._columnOrder))return;const previous=this._columnOrder,seen=new Set;this._columnOrder=frozenArray(Array.isArray(value)?value.filter(id=>typeof id!="string"||id.trim()===""||seen.has(id)?!1:(seen.add(id),!0)):[]),this.requestUpdate("columnOrder",previous)}get columns(){return this._columns}set columns(value){if(this.isRebind("columns",value,this._columns))return;const previous=this._columns;this._columns=snapshotColumns(value,column=>{const current=this.columnOccurrenceIds.get(column);if(current)return current;const identity=`column-occurrence-${this.nextColumnOccurrenceId}`;return this.nextColumnOccurrenceId+=1,this.columnOccurrenceIds.set(column,identity),identity}),this.requestUpdate("columns",previous)}get rowLimit(){return Math.max(1,finiteCount(this.maxRows,DATA_GRID_TREE_NODE_LIMIT,1e5))}get data(){return this._data}set data(value){if(this.isRebind("data",value,this._data)&&this.dataAdmissionLimit===this.rowLimit)return;this.dataAdmissionLimit=this.rowLimit;const previous=this._data,admitted=[];let length=0;try{if(Array.isArray(value)){const descriptor=getOwnDataDescriptor(value,"length");descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=descriptor.value);const end=Math.min(length,this.rowLimit);for(let index=0;index<end;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const row=entry.value;row!==null&&(typeof row=="object"||typeof row=="function")&&admitted.push(row)}}}catch{}this.dataAdmissionTruncated=length>this.rowLimit,this._data=Object.freeze(admitted),this.requestUpdate("data",previous)}get expandedRowKeys(){return this._expandedRowKeys}set expandedRowKeys(value){if(this.isRebind("expandedRowKeys",value,this._expandedRowKeys))return;const previous=this._expandedRowKeys;this._expandedRowKeys=snapshotKeys(value),this.requestUpdate("expandedRowKeys",previous),this.requestUpdate("expandedKeys",previous)}get expandedKeys(){return this.expandedRowKeys}set expandedKeys(value){this.expandedRowKeys=value}get dataTruncated(){return this.sourceProjection().truncated}get filteredCount(){return this.processedClientRows.length}get filters(){return this._filters}set filters(value){const previous=this._filters,next=[];if(Array.isArray(value))for(const filter of value)try{if(!filter||typeof filter.id!="string")continue;const filterValue=filter.value instanceof Set||Array.isArray(filter.value)?frozenArray(filter.value):filter.value;next.push(Object.freeze({id:filter.id,value:filterValue}))}catch{}sameFilterState(previous,next)||(this._filters=Object.freeze(next),this.requestUpdate("filters",previous))}get groupBy(){return this._groupBy}set groupBy(value){if(this.isRebind("groupBy",value,this._groupBy))return;const previous=this._groupBy;this._groupBy=typeof value=="string"?value:Array.isArray(value)?frozenArray(value.filter(item=>typeof item=="string")):null,this.requestUpdate("groupBy",previous)}get pageCount(){const size=this.safePageSize;if(size===0)return 0;if(!this.usesServerData&&normalizedGroupBy(this.groupBy).length>0){const groups=this.topLevelGroupBuckets(this.processedClientRows).length;return groups<=0?0:Math.ceil(groups/size)}const count=this.safeTotal>=0?this.safeTotal:this.filteredCount;return count<=0?0:Math.ceil(count/size)}get pageSizeOptions(){return this._pageSizeOptions}set pageSizeOptions(value){if(this.isRebind("pageSizeOptions",value,this._pageSizeOptions))return;const previous=this._pageSizeOptions;this._pageSizeOptions=frozenArray(Array.isArray(value)?value:[]),this.requestUpdate("pageSizeOptions",previous)}get selectionMode(){return this.selectable===""?"multiple":this.selectable}set selectionMode(value){this.selectable=value}get selectedRowKeys(){return this._selectedRowKeys}set selectedRowKeys(value){if(this.isRebind("selectedRowKeys",value,this._selectedRowKeys))return;const previous=this._selectedRowKeys;this._selectedRowKeys=snapshotKeys(value),this.requestUpdate("selectedRowKeys",previous),this.requestUpdate("selectedKeys",previous)}get selectedKeys(){return this.selectedRowKeys}set selectedKeys(value){this.selectedRowKeys=value}get selectedRows(){const rows=this.allSourceRows;return this.memoize("selectedRows",[rows,this.selectedKeys],()=>{const byKey=this.canonicalRowIndex(),positions=this.sourceIndexMap();return frozenArray(this.selectedKeys.flatMap(key=>{const row=byKey.get(key);return row===void 0?[]:[row]}).sort((left,right)=>positions.get(left)-positions.get(right)))})}set selectedRows(next){if(this.isRebind("selectedRows",next,REBIND_NO_SNAPSHOT))return;const candidates=Array.isArray(next)?next:[];this.hasUpdated||(this.pendingInitialSelectedRows=candidates),this.resolveSelectedRowsAssignment(candidates)}resolveSelectedRowsAssignment(candidates){const source=this.allSourceRows,sourceSet=new Set(source),sourceIndexes=this.sourceIndexMap(source),seen=new Set,rows=candidates.filter(row=>!sourceSet.has(row)||seen.has(row)?!1:(seen.add(row),!0)),limited=this.selectionMode==="single"?rows.slice(0,1):rows;this.selectedKeys=limited.map(row=>this.keyForRow(row,this.sourceIndexFor(row,sourceIndexes)??0))}get sort(){return this._sort}set sort(value){const previous=this._sort,next=[];if(Array.isArray(value))for(const item of value)try{if(!item||typeof item.id!="string")continue;next.push(Object.freeze({id:item.id,desc:!!item.desc}))}catch{}sameSortState(previous,next)||(this._sort=Object.freeze(next),this.requestUpdate("sort",previous))}memoize(key,inputs,compute){const cached=this.pipelineMemo.get(key);if(cached&&cached.inputs.length===inputs.length&&cached.inputs.every((input,index)=>Object.is(input,inputs[index])))return cached.value;const value=compute();return this.pipelineMemo.set(key,{inputs,value}),value}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.syncMeasuredBodyWidth(),this.syncBodyScrollState(),this.syncRowMeasurementObserver(),this.correctMeasurementAnchor(),this.measureRenderedItems(),this.closeComposedColumnsMenu()),this.dataSource&&this.scheduleServerRequest(!1)}disconnectedCallback(){this.managedOverlay?.deactivate({restoreFocus:!1}),this.managedOverlay=void 0,this.managedOverlayOwner=null,this.requestGeneration+=1,this.requestController?.abort(),this.requestController=void 0,this.serverRequestInputs=void 0,this.ownsLoadingState&&(this.loading=!1),this.ownsLoadingState=!1,this.cancelRequestTimer(),this.resizeSession?.moved&&this.restoreResizeSession(this.resizeSession,!1),this.resizePointer.stop(),this.resizeSession=void 0,this.activeResizeColumn=void 0,this.activeFilterColumn=null,this.activeColumnMenu=null,this.columnsMenuOpen=!1,this.closeComposedColumnsMenu(),this.dragGhost="",this.columnDragSession=void 0,this.pendingVirtualScroll=void 0,this.expectedBodyScroll=void 0,this.resetRowMeasurementObserver(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.expectedBodyScroll=void 0,this.resetRowMeasurementObserver(),this.isConnected&&this.hasUpdated&&(this.syncMeasuredBodyWidth(),this.syncBodyScrollState(),this.syncRowMeasurementObserver(),this.correctMeasurementAnchor(),this.measureRenderedItems())}requestUpdate(...args){args[0]===void 0&&(this.contentRefreshPending=!0),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),changed.has("columns")){const activeFooters=new Set(this.columns.filter(column=>typeof column.footer=="function").map((column,index)=>`footer:${columnId(column,index)}`));for(const key of this.pipelineMemo.keys())key.startsWith("footer:")&&!activeFooters.has(key)&&this.pipelineMemo.delete(key)}this.resetGeometryCycle(),this.geometryCycle=!0;const contentRefresh=this.contentRefreshPending;this.contentRefreshPending=!1,contentRefresh&&(this.pipelineEpoch+=1),this.hasUpdated&&changed.has("loading")&&this.loading&&this.announce(this.localize("loading"));const sourceReplaced=changed.has("dataSource")&&changed.get("dataSource")!==void 0,serverDisabled=changed.has("server")&&!this.usesServerData;if((sourceReplaced||serverDisabled)&&!this.matchesCurrentServerRequest()&&(this.requestController||this.requestDebounce.pending)&&(this.requestGeneration+=1,this.requestController?.abort(),this.requestController=void 0,this.serverRequestInputs=void 0,this.cancelRequestTimer(),this.ownsLoadingState&&(this.loading=!1),this.ownsLoadingState=!1),this.resizeSession&&(changed.has("resizable")||changed.has("columns"))&&!this.columnCanResize(this.resizeSession.columnId)){const session=this.resizeSession;this.resizePointer.stop(),this.resizeSession=void 0,this.activeResizeColumn=void 0,session.moved&&this.restoreResizeSession(session,!0)}if(this.columnDragSession&&(changed.has("reorderable")||changed.has("columns"))&&!this.columnCanMove(this.columnDragSession.sourceId)&&(this.columnDragSession=void 0,this.dragGhost=""),changed.has("columns")&&this.handleColumnsChange(),this.reconcileRowMeasurementCache(changed,contentRefresh),!this.hasUpdated&&this.pendingInitialSelectedRows!==void 0){const pending=this.pendingInitialSelectedRows;this.pendingInitialSelectedRows=void 0,this.resolveSelectedRowsAssignment(pending)}if(!this.usesServerData&&!this.sourceProjection().truncated&&(changed.has("data")||changed.has("rowKey")||changed.has("childRows")||changed.has("server")||changed.has("dataSource"))){const validKeys=this.allSourceRows.map((row,index)=>this.keyForRow(row,index)),validKeySet=new Set(validKeys),selectedKeys=this.selectedKeys.filter(key=>validKeySet.has(key));(selectedKeys.length!==this.selectedKeys.length||selectedKeys.some((key,index)=>!keysEqual(key,this.selectedKeys[index])))&&(this.selectedKeys=selectedKeys,this.hasUpdated&&this.emitSelection()),this.lastSelectedIndex=-1}if(this.paginate&&(changed.has("data")||changed.has("filters")||changed.has("searchTerm")||changed.has("groupBy")||changed.has("pageSize")||changed.has("total")||changed.has("server")||changed.has("dataSource"))){const lastPage=Math.max(0,this.pageCount-1);this.page=finiteInteger(this.page,0,0,lastPage)}this.followRovingCell(),(changed.has("data")||changed.has("columns")||changed.has("filters")||changed.has("searchTerm")||changed.has("sort")||changed.has("expandedKeys")||changed.has("groupBy")||changed.has("page")||changed.has("pageSize")||changed.has("paginate")||changed.has("childRows"))&&(this.focusedRow=finiteInteger(this.focusedRow,-1,-1,Math.max(-1,this.displayItems.length-1)),this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1)))}followRovingCell(){const previousItems=this.renderedDisplayItems,items=this.displayItems;if(previousItems&&previousItems!==items&&this.focusedRow>=0){const previous=previousItems[this.focusedRow],current=items[this.focusedRow],key=previous?displayItemKey(previous):void 0;if(key!==void 0&&(!current||displayItemKey(current)!==key)){const index=this.displayIndexes.get(key)??-1;index>=0&&(this.focusedRow=index)}const active=shadowFocusTarget(this);this.restoreCellFocus=active?.getAttribute("role")==="gridcell"&&active.hasAttribute("data-focus-cell")}const previousColumns=this.renderedColumns,columns=this.visibleColumns;if(previousColumns&&previousColumns!==columns){const id=previousColumns[this.focusedColumn]?.id;if(id!==void 0&&columns[this.focusedColumn]?.id!==id){const index=columns.findIndex(entry=>entry.id===id);index>=0&&(this.focusedColumn=index)}}}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-data-grid-missing-accessible-name","<lr-data-grid> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){if(super.updated(changed),this.renderedDisplayItems=this.displayItems,this.renderedColumns=this.visibleColumns,this.restoreCellFocus&&(this.restoreCellFocus=!1,!shadowFocusTarget(this)&&this.focusedRow>=0&&this.focusCell(this.focusedRow,this.focusedColumn)),changed.has("dataSource")&&this.dataSource&&this.scheduleServerRequest(!1),(changed.has("sort")||changed.has("filters")||changed.has("searchTerm")||changed.has("page")||changed.has("pageSize")||changed.has("server"))&&(this.server||this.dataSource)){const delayed=changed.has("filters")||changed.has("searchTerm");this.scheduleServerRequest(delayed)}this.syncManagedOverlay(),this.syncMeasuredBodyWidth(),this.syncResolvedColumnWidths(),this.syncResizeHandleValues(),this.queueBodyScrollStateSync(),this.syncRowMeasurementObserver(),this.correctMeasurementAnchor(),this.measurementFontHasRendered||(this.cycleFontSignature=void 0,this.measurementFontHasRendered=!0),this.measureRenderedItems(),this.alignPendingVirtualScroll(),this.isMounting=!1,this.geometryCycle=!1}get currentManagedOverlayOwner(){return this.activeFilterColumn!==null?`filter:${this.activeFilterColumn}`:this.activeColumnMenu!==null?`column:${this.activeColumnMenu}`:null}managedOverlayElements(owner){const separator=owner.indexOf(":"),kind=owner.slice(0,separator),columnIdValue=owner.slice(separator+1),header=[...this.renderRoot.querySelectorAll('[part~="header-cell"][data-column-id]')].find(candidate=>candidate.getAttribute("data-column-id")===columnIdValue);return header?kind==="filter"?{panel:header.querySelector('[part="filter-panel"]'),trigger:header.querySelector('[part="filter-button"]')}:{panel:header.querySelector('[part="column-menu"] [role="group"]'),trigger:header.querySelector('[part="column-menu-button"]')}:{panel:null,trigger:null}}dismissManagedOverlay(owner){owner.startsWith("filter:")&&this.activeFilterColumn===owner.slice(7)?this.activeFilterColumn=null:owner.startsWith("column:")&&this.activeColumnMenu===owner.slice(7)&&(this.activeColumnMenu=null)}syncManagedOverlay(){const owner=this.currentManagedOverlayOwner;if(owner!==null&&owner===this.managedOverlayOwner&&this.managedOverlay?.isActive()&&this.managedOverlayElements(owner).panel||(this.managedOverlay?.deactivate({restoreFocus:owner===null}),this.managedOverlay=void 0,this.managedOverlayOwner=null,owner===null||!this.isConnected))return;const{panel}=this.managedOverlayElements(owner);panel&&(this.managedOverlayOwner=owner,this.managedOverlay=activateNonmodalOverlay({host:this,panel:()=>this.managedOverlayElements(owner).panel,onEscape:()=>this.dismissManagedOverlay(owner),restoreFocusTo:()=>this.managedOverlayElements(owner).trigger}))}closeComposedColumnsMenu(){const menu=this.renderRoot?.querySelector('[part="columns-menu"]');menu?.open&&(menu.open=!1)}openColumnsPanel(){this.columnsMenuOpen=!0,this.activeFilterColumn=null,this.activeColumnMenu=null}toggleFilterPanel(id){const next=this.activeFilterColumn===id?null:id;this.activeFilterColumn=next,next!==null&&(this.columnsMenuOpen=!1,this.activeColumnMenu=null)}toggleColumnPanel(id){const next=this.activeColumnMenu===id?null:id;this.activeColumnMenu=next,next!==null&&(this.columnsMenuOpen=!1,this.activeFilterColumn=null)}announce(text){this.sink?.announce(text),this.liveText=text}get usesServerData(){return this.server||this.dataSource!==null}get safePage(){return finiteInteger(this.page,0,0,Math.max(0,this.pageCount-1))}get safePageSize(){return finiteCount(this.pageSize)}get safeTotal(){return this.total===-1?-1:finiteCount(this.total)}sourceProjection(){return this.memoize("source",[this.pipelineEpoch,this.data,this.childRows,this.rowKey,this.rowLimit],()=>this.computeSourceProjection())}computeSourceProjection(){const result=[],visited=new Set,seenRowKeys=new Set,stack=[];for(let index=this.data.length-1;index>=0;index-=1)stack.push({row:this.data[index],depth:0});let truncated=this.dataAdmissionTruncated;for(;stack.length>0&&result.length<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(!trackIdentity||trackIdentity&&visited.has(current.row))continue;trackIdentity&&visited.add(current.row);const rowKey=this.rowIdentity(current.row);if(rowKey===void 0||seenRowKeys.has(rowKey))continue;seenRowKeys.add(rowKey),result.push(current.row);const children=this.childrenFor(current.row);if(children.length!==0){if(current.depth>=DATA_GRID_TREE_DEPTH_LIMIT){truncated=!0;continue}for(let index=children.length-1;index>=0;index-=1)stack.push({row:children[index],depth:current.depth+1})}}return stack.length>0&&(truncated=!0),{rows:Object.freeze(result),truncated}}get allSourceRows(){return this.sourceProjection().rows}get canonicalRootRows(){const source=this.allSourceRows;return this.memoize("roots",[source,this.data],()=>{const canonical=new Set(source);return this.data.filter(row=>canonical.delete(row))})}sourceIndexMap(rows=this.allSourceRows){const build=()=>{const indexes=new Map;return rows.forEach((row,index)=>{indexes.has(row)||indexes.set(row,index)}),indexes};return this.memoize("sourceIndex",[rows],build)}sourceIndexFor(row,indexes){return indexes.get(row)}canonicalRowIndex(rows=this.allSourceRows){const build=()=>{const byIdentity=new Map;for(const row of rows){const identity=this.rowIdentity(row);identity!==void 0&&!byIdentity.has(identity)&&byIdentity.set(identity,row)}return byIdentity};return this.memoize("canonicalIndex",[rows],build)}canonicalMembers(rows,byIdentity=this.canonicalRowIndex()){const output=[],seen=new Set;for(const candidate of rows){const identity=this.rowIdentity(candidate);if(identity===void 0||seen.has(identity))continue;const canonical=byIdentity.get(identity);canonical&&(seen.add(identity),output.push(canonical))}return output}get orderedColumns(){return this.memoize("ordered",[this.columns,this.columnOrder],()=>this.computeOrderedColumns())}computeOrderedColumns(){const entries=this.columns.map((column,naturalIndex)=>({column,id:columnId(column,naturalIndex),naturalIndex}));if(this.columnOrder.length===0)return entries;const rank=new Map(this.columnOrder.map((id,index)=>[id,index]));return entries.sort((left,right)=>{const leftRank=rank.get(left.id),rightRank=rank.get(right.id);return leftRank===void 0&&rightRank===void 0?left.naturalIndex-right.naturalIndex:leftRank===void 0?1:rightRank===void 0?-1:leftRank-rightRank})}get columnIndex(){const entries=this.orderedColumns;return this.memoize("columnIndex",[entries],()=>new Map(entries.map(entry=>[entry.id,entry])))}get visibleColumns(){const ordered=this.orderedColumns;return this.memoize("visible",[ordered,this.columnVisibility,this.columnPinning],()=>ordered.filter(({column,id})=>this.columnVisibility.get(id)??column.hidden!==!0).sort((left,right)=>{const leftPin=normalizePinSide(this.getColumnPin(left.id)),rightPin=normalizePinSide(this.getColumnPin(right.id));return leftPin===rightPin?0:leftPin==="left"||rightPin==="right"?-1:1}))}get processedClientRows(){const rows=this.canonicalRootRows;return this.memoize("processed",[rows,this.pipelineEpoch,this.usesServerData,this.childRows,this.filterFromLeafRows,this.columns,this.filters,this.searchTerm,this.searchFn,this.sort,this.effectiveLocale],()=>this.computeProcessedClientRows(rows))}get filterText(){return this.memoize("filterText",[this.allSourceRows,this.columns,this.effectiveLocale],()=>textFilterCorpus(this.effectiveLocale))}computeProcessedClientRows(rows){if(this.usesServerData)return[...rows];const sorted=this.memoize("sorted",[rows,this.pipelineEpoch,this.columns,this.sort,this.effectiveLocale],()=>sortRows(rows,this.columns,this.sort,this.effectiveLocale));if(this.childRows)return sorted.filter(row=>this.rowMatches(row)||this.filterFromLeafRows&&this.hasMatchingDescendant(row));const filtered=filterRows(sorted,this.columns,this.filters,this.effectiveLocale,this.filterText),haystacks=!this.searchFn&&this.searchTerm.trim()?this.memoize("searchHaystacks",[rows,this.pipelineEpoch,this.columns,this.effectiveLocale],()=>searchHaystacks(rows,this.columns,this.effectiveLocale)):void 0;return searchRows(filtered,this.columns,this.searchTerm,this.effectiveLocale,this.searchFn,haystacks)}childrenFor(row){const cache=this.memoize("children",[this.data,this.childRows,this.rowLimit,this.pipelineEpoch],()=>new Map),existing=cache.get(row);if(existing)return existing;const children=this.readChildren(row);return cache.set(row,children),children}readChildren(row){try{const children=typeof this.childRows=="function"?this.childRows(row):this.childRows?pathValue(row,this.childRows):void 0;return Array.isArray(children)?children.slice(0,this.rowLimit):[]}catch{return[]}}rowIdentity(row){if(!((typeof row!="object"||row===null)&&typeof row!="function"))try{if(this.rowKey){const candidate=typeof this.rowKey=="function"?this.rowKey(row):pathValue(row,this.rowKey);return isKey(candidate)?candidate:void 0}const object=row,current=this.rowOccurrenceIds.get(object);if(current)return current;const identity=`row-occurrence-${this.nextRowOccurrenceId}`;return this.nextRowOccurrenceId+=1,this.rowOccurrenceIds.set(object,identity),identity}catch{return}}keyForRow(row,_index){return this.rowIdentity(row)}renderedColumnElements(columnId2,role){const prefix=role?`[role="${role}"]`:"",ownerCss=this.ownerDocument.defaultView?.CSS,escape=ownerCss?.escape;if(typeof escape=="function")try{const matches=[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id="${escape.call(ownerCss,columnId2)}"]`)];if(matches.length>0)return matches}catch{}return[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id]`)].filter(element=>element.getAttribute("data-column-id")===columnId2)}computedToken(name,privateDefault){if(!this.isConnected)return"";const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.getComputedStyle!="function")return"";try{const style=owner.getComputedStyle(this);return style.getPropertyValue(name).trim()||(privateDefault?style.getPropertyValue(privateDefault).trim():"")}catch{return""}}autoSizeColumn(columnId2){const cells=this.renderedColumnElements(columnId2);if(cells.length===0)return;let width=0;for(const cell of cells)width=Math.max(width,cell.scrollWidth);const entry=this.columnIndex.get(columnId2);if(!entry)return;const{minimum,maximum}=this.columnBounds(entry.column);this.setColumnWidth(columnId2,finiteRange(width,minimum,minimum,maximum),!1)}autoSizeColumns(){for(const{id}of this.visibleColumns)this.autoSizeColumn(id)}collapseAllRows(){this.expandedKeys=[]}collapseRow(key){this.expandedKeys=this.expandedKeys.filter(candidate=>!keysEqual(candidate,key))}copySelectedRows(options={}){const rowsToCopy=this.selectedRows.length>0?this.selectedRows:this.getProcessedRows(),format=options.format??"tsv",text=this.delimitedRows(rowsToCopy,{...options,delimiter:options.delimiter??(format==="csv"?",":" ")});return this.copyAndReport(text),rowsToCopy.length}expandAllRows(){const keys=[];this.allSourceRows.forEach((row,index)=>{(this.childrenFor(row).length>0||this.rowDetail)&&keys.push(this.keyForRow(row,index))});for(const group of this.groupItems(this.processedClientRows))keys.push(group.key);this.expandedKeys=keys}expandRow(key){arrayHasKey(this.expandedKeys,key)||(this.expandedKeys=[...this.expandedKeys,key])}exportDataAsCsv(options={}){const text=this.getDataAsCsv(options),ownerDocument=this.ownerDocument,owner=ownerDocument.defaultView;if(!owner||typeof owner.URL.createObjectURL!="function")return;const url=owner.URL.createObjectURL(new owner.Blob([text],{type:"text/csv;charset=utf-8"}));try{const anchor=ownerDocument.createElement("a");anchor.href=url,anchor.download=options.fileName||"data.csv",anchor.hidden=!0,ownerDocument.body?.append(anchor),anchor.click(),anchor.remove()}finally{owner.URL.revokeObjectURL(url)}}focus(options={}){const selector=this.focusedRow<0?`[role="columnheader"][data-column-position="${this.focusedColumn}"]`:`[role="gridcell"][data-row-position="${this.focusedRow}"][data-column-position="${this.focusedColumn}"]`;this.renderRoot.querySelector(selector)?.focus(options)}getColumnFacets(columnId2){const uniqueValues=new Map;if(this.usesServerData)return Object.freeze({uniqueValues});const entry=this.columnIndex.get(columnId2);if(!entry)return Object.freeze({uniqueValues});const otherFilters=this.filters.filter(filter=>filter.id!==columnId2),rows=searchRows(filterRows(this.canonicalRootRows,this.columns,otherFilters,this.effectiveLocale),this.columns,this.searchTerm,this.effectiveLocale,this.searchFn);let minimum=Number.POSITIVE_INFINITY,maximum=Number.NEGATIVE_INFINITY;for(const row of rows){const value=columnValue(entry.column,row);uniqueValues.set(value,(uniqueValues.get(value)??0)+1);const number=typeof value=="number"?value:Number(value);Number.isFinite(number)&&(minimum=Math.min(minimum,number),maximum=Math.max(maximum,number))}return Number.isFinite(minimum)&&Number.isFinite(maximum)?Object.freeze({uniqueValues,minMax:Object.freeze([minimum,maximum])}):Object.freeze({uniqueValues})}getColumnPin(columnId2){return this.columnPinning.has(columnId2)?this.columnPinning.get(columnId2)??!1:this.columnIndex.get(columnId2)?.column.pinned??!1}getDataAsCsv(options={}){return this.delimitedRows(this.getProcessedRows(),options)}getProcessedRows(){const rows=this.processedClientRows;return this.memoize("publicProcessedRows",[rows],()=>frozenArray(rows))}getVisibleRows(){const rows=this.processedClientRows;return this.memoize("visibleRows",[rows,this.paginate,this.usesServerData,this.pageSize,this.page,this.total,this.groupBy,this.orderedColumns],()=>this.computeVisibleRows(rows))}computeVisibleRows(rows){if(!this.paginate||this.usesServerData)return frozenArray(rows);const size=this.safePageSize;if(size===0)return[];const start=this.safePage*size;return normalizedGroupBy(this.groupBy).length>0?frozenArray(this.topLevelGroupBuckets(rows).slice(start,start+size).flatMap(bucket=>bucket.rows)):frozenArray(rows.slice(start,start+size))}getState(){return Object.freeze({order:frozenArray(this.columnOrder),widths:Object.freeze(Object.fromEntries(this.columnWidths)),visibility:Object.freeze(Object.fromEntries(this.columnVisibility)),pinning:Object.freeze(Object.fromEntries(this.columnPinning)),sort:frozenArray(this.sort.map(item=>Object.freeze({...item}))),filters:frozenArray(this.filters.map(item=>Object.freeze({id:item.id,value:serializableFilterValue(item.value)}))),search:this.searchTerm,selectedRowKeys:frozenArray(this.selectedRowKeys),expandedRowKeys:frozenArray(this.expandedRowKeys),selectedKeys:frozenArray(this.selectedRowKeys),expandedKeys:frozenArray(this.expandedRowKeys),page:this.safePage,pageSize:this.safePageSize})}handleColumnsChange(){const valid=new Set(this.columns.map((column,index)=>columnId(column,index))),natural=[...valid],order=this.columnOrder.filter(id=>valid.has(id)),orderedIds=new Set(order);for(const id of natural)orderedIds.has(id)||order.push(id);this.columnOrder.length>0&&order.join("\0")!==this.columnOrder.join("\0")&&(this.columnOrder=order);const widths=[...this.columnWidths].filter(([id])=>valid.has(id)),visibility=[...this.columnVisibility].filter(([id])=>valid.has(id)),pinning=[...this.columnPinning].filter(([id])=>valid.has(id));widths.length!==this.columnWidths.size&&(this.columnWidths=new Map(widths)),visibility.length!==this.columnVisibility.size&&(this.columnVisibility=new Map(visibility)),pinning.length!==this.columnPinning.size&&(this.columnPinning=new Map(pinning))}handlePageChange(){this.applyPageChange(this.safePage)}applyPageChange(value){let requested;typeof value=="number"?requested=value:requested=Number(valueControl(value?.currentTarget)?.value??this.safePage);const last=Math.max(0,this.pageCount-1),next=finiteInteger(requested,this.safePage,0,last);this.page=next,this.emit("lr-page-change",Object.freeze({page:next,pageSize:this.safePageSize}))}handleSearchTermChange(){this.applySearchTermChange(this.searchTerm)}applySearchTermChange(value){const next=typeof value=="string"?value:valueControl(value?.currentTarget)?.value??this.searchTerm;this.searchTerm=next,this.page!==0&&(this.page=0)}pinColumn(columnId2,side){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnPinning);next.set(columnId2,side),this.columnPinning=next}async reload(){const owner=this.ownerDocument.defaultView;!this.isConnected||!owner||!this.usesServerData||(this.cancelRequestTimer(),await this.loadServerData(owner))}resetColumns(){this.columnOrder=[],this.columnWidths=new Map,this.columnVisibility=new Map,this.columnPinning=new Map}resetState(){this.resetColumns(),this.sort=[],this.filters=[],this.searchTerm="",this.expandedKeys=[]}scrollToIndex(index,options={}){this.pendingVirtualScroll=void 0,this.pendingMeasurementAnchor=void 0;const rows=this.getVisibleRows();if(rows.length===0)return;const requestedIndex=finiteInteger(index,0,0,rows.length-1),requestedRow=rows[requestedIndex],sourceIndexes=this.sourceIndexMap(),sourceIndex=this.sourceIndexFor(requestedRow,sourceIndexes),requestedKey=this.keyForRow(requestedRow,sourceIndex??requestedIndex),items=this.displayItems,target=this.displayIndexes.get(`row:${typeof requestedKey}:${String(requestedKey)}`)??-1;if(target<0)return;const body=this.bodyElement;if(!body)return;this.recordMeasurementRowHeight()&&this.invalidateRowMeasurements()&&this.queueMeasurementUpdate();const rendered=this.renderRoot?.querySelector(`[part~="row"][data-visible-index="${target}"]`),rowHeight=this.displayItemHeight(target,items),rowTop=this.displayItemOffset(target,items),currentTop=finiteRange(body.scrollTop,this.bodyScrollTop,0),viewportHeight=finiteRange(body.clientHeight,0,0),alignment=options.align??(rendered?"nearest":"start");let top=rowTop;if(alignment==="center")top-=(viewportHeight-rowHeight)/2;else if(alignment==="end")top-=viewportHeight-rowHeight;else if(alignment==="nearest"){const rowBottom=rowTop+rowHeight;rowTop>=currentTop&&rowBottom<=currentTop+viewportHeight?top=currentTop:rowTop<currentTop?top=rowTop:top=rowBottom-viewportHeight}const maximumTop=Math.max(0,this.displayItemOffset(items.length,items)-viewportHeight);if(top=finiteRange(top,0,0,maximumTop),rendered){const delta=this.renderedRowAlignmentDelta(rendered,body,alignment);if(top=finiteRange(currentTop+delta,currentTop,0,Math.max(0,body.scrollHeight-body.clientHeight)),body.scrollTo({top}),alignment==="start"){const correction=this.renderedStartPrecisionDelta(rendered,body);correction!==0&&(top=finiteRange(body.scrollTop+correction,body.scrollTop,0,Math.max(0,body.scrollHeight-body.clientHeight)),body.scrollTo({top}))}top=body.scrollTop,this.expectedBodyScroll=Object.freeze({body,top}),this.bodyScrollTop=top,this.lastMeasurementAnchor=this.measurementAnchorAtOffset(top,items);return}this.lastMeasurementAnchor=this.measurementAnchorAtOffset(top,items);const targetItem=items[target];targetItem&&(this.pendingVirtualScroll=Object.freeze({itemKey:displayItemKey(targetItem),align:alignment})),this.expectedBodyScroll=Object.freeze({body,top}),this.bodyScrollTop=top,body.scrollTo({top})}setState(state2){const known=new Set(this.columns.map((column,index)=>columnId(column,index)));state2.order&&(this.columnOrder=state2.order.filter(id=>known.has(id))),state2.widths&&(this.columnWidths=this.validColumnMap(state2.widths,known,width=>finiteRange(width,0,0))),state2.visibility&&(this.columnVisibility=this.validColumnMap(state2.visibility,known,Boolean)),state2.pinning&&(this.columnPinning=this.validColumnMap(state2.pinning,known,side=>side==="left"||side==="right"||side==="start"||side==="end"?side:!1)),state2.sort&&(this.sort=state2.sort.filter(item=>known.has(item.id)).map(item=>({id:item.id,desc:!!item.desc}))),state2.filters&&(this.filters=state2.filters.filter(item=>known.has(item.id)).map(item=>({...item}))),state2.search!==void 0&&(this.searchTerm=state2.search);const selectedRowKeys=state2.selectedRowKeys??state2.selectedKeys,expandedRowKeys=state2.expandedRowKeys??state2.expandedKeys;selectedRowKeys&&(this.selectedRowKeys=selectedRowKeys),expandedRowKeys&&(this.expandedRowKeys=expandedRowKeys),state2.page!==void 0&&(this.page=finiteCount(state2.page)),state2.pageSize!==void 0&&(this.pageSize=finiteCount(state2.pageSize))}sizeColumnsToFit(){const body=this.bodyElement;if(!body||this.visibleColumns.length===0)return;const selectionWidth=this.selectionEnabled?resolveCssTokenLength(this.computedToken("--lr-icon-button-size"),{host:this})??0:0,visible=this.visibleColumns,flexible=visible.filter(({column})=>finiteRange(column.flex??1,1,0)>0);if(flexible.length===0)return;const measuredWidths=new Map([...this.renderRoot.querySelectorAll('[role="columnheader"][data-column-id]')].map(header=>[header.dataset.columnId,resolveCssTokenLength(this.ownerDocument.defaultView?.getComputedStyle(header).width??"",{host:this})??0])),fixedWidth=visible.reduce((total,{column,id})=>{if(finiteRange(column.flex??1,1,0)>0)return total;const bounds=this.columnBounds(column),explicit=this.columnWidths.get(id)??column.width,fallback=explicit!==void 0&&explicit>0?this.estimatedColumnWidth(column,id):Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?bounds.maximum:bounds.minimum||this.estimatedColumnWidth(column,id);return total+finiteRange(measuredWidths.get(id)||fallback,fallback,0)},0),available=Math.max(0,body.clientWidth-selectionWidth-fixedWidth),flexValues=flexible.map(({column})=>finiteRange(column.flex??1,1,0)),flexScale=flexValues.reduce((largest,value)=>Math.max(largest,value),0),scaledFlex=flexValues.map(value=>flexScale>0?value/flexScale:value),totalFlex=scaledFlex.reduce((sum,value)=>sum+value,0)||flexible.length,next=new Map(this.columnWidths);for(const[index,{column,id}]of flexible.entries()){const share=available*((scaledFlex[index]??0)/totalFlex),{minimum,maximum}=this.columnBounds(column);next.set(id,finiteRange(share,minimum,minimum,maximum))}this.columnWidths=next}toggleColumn(columnId2,visible){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnVisibility);next.set(columnId2,visible),this.columnVisibility=next,this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1))}validColumnMap(record,known,convert){const result=new Map;for(const[id,value]of Object.entries(record))known.has(id)&&result.set(id,convert(value));return result}delimitedRows(rows,options){const active=this.visibleColumns.map(({column,id})=>({...column,id,value:row=>{const raw=columnValue(column,row),formatted=column.formatter?.(raw,row);return typeof formatted=="string"?formatted:raw},hidden:!1}));return rowsAsDelimited(rows,active,options)}async copyAndReport(text){const owner=this.isConnected?this.ownerDocument.defaultView:null,outcome=await this.writeClipboard(text,owner);if(!(!owner||!this.isConnected||this.ownerDocument.defaultView!==owner)){if(outcome.ok){this.isMounting||this.announce(this.localize("copied")),this.emit("lr-copy",outcome);return}this.isMounting||this.announce(this.localize("copyFailed")),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}}async writeClipboard(text,owner){const ownerDocument=this.ownerDocument,outcome=await writeClipboardText(owner,text);if(outcome.ok||!owner||ownerDocument.defaultView!==owner||!ownerDocument.body)return outcome;const textarea=ownerDocument.createElement("textarea");textarea.value=text,textarea.style.position="fixed",textarea.style.opacity="0",ownerDocument.body.append(textarea);try{if(textarea.select(),ownerDocument.execCommand?.("copy"))return Object.freeze({ok:!0,text})}finally{textarea.remove()}return outcome}setColumnWidth(columnIdValue,width,emit,finished=!0){const entry=this.columnIndex.get(columnIdValue);if(!entry)return;const{minimum,maximum}=this.columnBounds(entry.column),safeWidth=finiteRange(width,minimum,minimum,maximum),next=new Map(this.columnWidths);next.set(columnIdValue,safeWidth),this.columnWidths=next,emit&&this.emit("lr-column-resize",Object.freeze({columnId:columnIdValue,columnKey:columnIdValue,width:safeWidth,finished}))}cancelRequestTimer(){this.requestDebounce.cancel()}currentServerRequestInputs(){return[this.ownerDocument,this.dataSource,this.server,this.sort,this.filters,this.searchTerm,this.safePage,this.safePageSize]}matchesCurrentServerRequest(){const current=this.currentServerRequestInputs();return this.serverRequestInputs?.every((value,index)=>Object.is(value,current[index]))??!1}scheduleServerRequest(delayed){const owner=this.ownerDocument.defaultView;!this.isConnected||!owner||!this.usesServerData||this.matchesCurrentServerRequest()||(this.requestGeneration++,this.requestController?.abort(),this.requestController=void 0,this.serverRequestInputs=void 0,this.requestDebounce.delayMs=delayed?finiteDuration(this.filterDebounce,250):0,this.requestDebounce.push(owner))}async loadServerData(owner){if(!this.isConnected||this.ownerDocument.defaultView!==owner||!this.usesServerData)return;this.requestController?.abort(),this.serverRequestInputs=this.currentServerRequestInputs();const AbortControllerCtor=owner.AbortController;this.requestController=typeof AbortControllerCtor=="function"?new AbortControllerCtor:void 0;const generation=++this.requestGeneration,request=Object.freeze({sort:frozenArray(this.sort.map(item=>Object.freeze({...item}))),filters:frozenArray(this.filters.map(item=>Object.freeze({id:item.id,value:serializableFilterValue(item.value)}))),search:this.searchTerm,page:this.safePage,pageSize:this.safePageSize,signal:this.requestController?.signal}),requestDetail=()=>Object.freeze({...request,sort:frozenArray(request.sort.map(item=>Object.freeze({...item}))),filters:frozenArray(request.filters.map(item=>Object.freeze({id:item.id,value:serializableFilterValue(item.value)})))});if(this.emit("lr-request",requestDetail()),this.emit("request",requestDetail()),!!this.dataSource){this.ownsLoadingState=!0,this.loading=!0;try{const response=await this.dataSource(request);if(generation!==this.requestGeneration||request.signal?.aborted||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.data=Array.isArray(response.rows)?response.rows:[],this.total=finiteCount(response.total),this.loading=!1,this.ownsLoadingState=!1}catch(error){if(generation!==this.requestGeneration||request.signal?.aborted||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.loading=!1,this.ownsLoadingState=!1,this.emit("lr-data-error",Object.freeze({error,request:requestDetail()}))}}}get selectionEnabled(){return this.selectionMode!=="none"}get ariaColumnCount(){return Math.max(1,this.visibleColumns.length+(this.selectionEnabled?1:0))}rowIsSelectable(row){return this.selectionEnabled&&(this.selectableRows?.(row)??!0)}rowMatches(row){const source=this.allSourceRows;return this.memoize("rowMatches",[source,this.columns,this.filters,this.searchTerm,this.searchFn,this.effectiveLocale],()=>{const haystacks=!this.searchFn&&this.searchTerm.trim()?this.memoize("treeHaystacks",[source,this.columns,this.effectiveLocale],()=>searchHaystacks(source,this.columns,this.effectiveLocale)):void 0;return new Set(searchRows(filterRows(source,this.columns,this.filters,this.effectiveLocale,this.filterText),this.columns,this.searchTerm,this.effectiveLocale,this.searchFn,haystacks))}).has(row)}processedChildrenFor(row,byIdentity){const cache=this.memoize("sortedChildren",[this.allSourceRows,this.columns,this.sort,this.effectiveLocale,this.usesServerData],()=>new Map);let children=cache.get(row);if(!children){const canonical=this.canonicalMembers(this.childrenFor(row),byIdentity);children=this.usesServerData?canonical:sortRows(canonical,this.columns,this.sort,this.effectiveLocale),cache.set(row,children)}return this.usesServerData?children:children.filter(child=>this.rowMatches(child)||this.filterFromLeafRows&&this.hasMatchingDescendant(child))}hasMatchingDescendant(row){const stack=this.canonicalMembers(this.childrenFor(row)).map(child=>({row:child,depth:1})),visited=new Set;let inspected=0;for(;stack.length>0&&inspected<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(!(trackIdentity&&visited.has(current.row))){if(trackIdentity&&visited.add(current.row),inspected+=1,this.rowMatches(current.row))return!0;if(!(current.depth>=DATA_GRID_TREE_DEPTH_LIMIT))for(const child of this.canonicalMembers(this.childrenFor(current.row)))stack.push({row:child,depth:current.depth+1})}}return!1}get pageRows(){return this.getVisibleRows()}get currentPageSelectableRows(){return this.memoize("pageSelectable",[this.pageRows,this.allSourceRows,this.pipelineEpoch,this.childRows,this.selectable,this.selectableRows],()=>this.computeCurrentPageSelectableRows())}computeCurrentPageSelectableRows(){const result=[],sourceIndex=new Map(this.allSourceRows.map((row,index)=>[row,index])),visited=new Set,stack=[...this.pageRows].reverse().map(row=>({row,depth:0}));let inspected=0;for(;stack.length>0&&inspected<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(trackIdentity&&visited.has(current.row))continue;trackIdentity&&visited.add(current.row),inspected+=1;const index=this.sourceIndexFor(current.row,sourceIndex);if(index===void 0)continue;const key=this.keyForRow(current.row,index);if(this.rowIsSelectable(current.row)&&result.push({row:current.row,key}),current.depth>=DATA_GRID_TREE_DEPTH_LIMIT)continue;const children=this.canonicalMembers(this.childrenFor(current.row));for(let childIndex=children.length-1;childIndex>=0;childIndex-=1){const child=children[childIndex];stack.push({row:child,depth:current.depth+1})}}return result}groupMemberKey(rows){let first;for(const row of rows){const identity=this.rowIdentity(row);if(identity===void 0)continue;const candidate=`${typeof identity}:${safeText(identity)}`;(first===void 0||candidate<first)&&(first=candidate)}return first??"unknown"}groupKey(parent,id,value,rows){const valueType=typeof value;return valueType==="object"&&value!==null||valueType==="function"?`group:${parent}:${id}:${valueType}:member:${this.groupMemberKey(rows)}`:`group:${parent}:${id}:${valueType}:${safeText(value)}`}topLevelGroupBuckets(rows){return this.memoize("buckets",[rows,this.groupBy,this.orderedColumns],()=>this.computeTopLevelGroupBuckets(rows))}computeTopLevelGroupBuckets(rows){const field=normalizedGroupBy(this.groupBy)[0];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return[];const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row),bucket=buckets.get(value)??[];bucket.push(row),buckets.set(value,bucket)}return[...buckets].map(([value,bucketRows])=>({value,rows:bucketRows}))}groupItems(rows){const fields=normalizedGroupBy(this.groupBy);if(fields.length===0||this.usesServerData)return[];const result=[],visit=(groupRows,depth,parent)=>{const field=fields[depth];if(!field)return;const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return;const buckets=new Map;for(const row of groupRows){const value=columnValue(entry.column,row),bucket=buckets.get(value)??[];bucket.push(row),buckets.set(value,bucket)}for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value,bucket);result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth}),depth+1<fields.length&&visit(bucket,depth+1,key)}};return visit(rows,0,"root"),result}get displayItems(){return this.memoize("display",[this.pageRows,this.pipelineEpoch,this.processedClientRows,this.allSourceRows,this.childRows||this.groupBy?this.expandedKeys:null,this.groupBy,this.orderedColumns,this.usesServerData,this.childRows],()=>this.computeDisplayItems())}get displayIndexes(){const items=this.displayItems;return this.memoize("displayIndexes",[items],()=>new Map(items.map((item,index)=>[displayItemKey(item),index])))}computeDisplayItems(){for(const key of this.pipelineMemo.keys())(key.startsWith("eligible:")||key.startsWith("groupSelected:")||key.startsWith("aggregate:"))&&this.pipelineMemo.delete(key);const groups=normalizedGroupBy(this.groupBy);if(groups.length>0&&!this.usesServerData)return this.groupedDisplayItems(this.pageRows,groups,0,"root",this.sourceIndexMap());const result=[],sourceRows=this.allSourceRows,indexes=this.sourceIndexMap(sourceRows);let byIdentity;const visited=new Set,stack=[...this.pageRows].reverse().map(row=>({row,depth:0}));for(;stack.length>0&&result.length<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(trackIdentity&&visited.has(current.row))continue;trackIdentity&&visited.add(current.row);const sourceIndex=this.sourceIndexFor(current.row,indexes);if(sourceIndex===void 0)continue;const safeIndex=sourceIndex,key=this.keyForRow(current.row,safeIndex);if(result.push({kind:"row",row:current.row,key,depth:current.depth,sourceIndex:safeIndex}),!arrayHasKey(this.expandedKeys,key)||current.depth>=DATA_GRID_TREE_DEPTH_LIMIT)continue;const children=this.processedChildrenFor(current.row,byIdentity??=this.canonicalRowIndex(sourceRows));for(let index=children.length-1;index>=0;index-=1)stack.push({row:children[index],depth:current.depth+1})}return result}groupedDisplayItems(rows,fields,depth,parent,sourceIndexes){const field=fields[depth];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return rows.map((row,index)=>({kind:"row",row,key:this.keyForRow(row,this.sourceIndexFor(row,sourceIndexes)??index),depth,sourceIndex:this.sourceIndexFor(row,sourceIndexes)??index}));const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row),bucket=buckets.get(value)??[];bucket.push(row),buckets.set(value,bucket)}const result=[];for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value,bucket);if(result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth}),!!arrayHasKey(this.expandedKeys,key))if(depth+1<fields.length)result.push(...this.groupedDisplayItems(bucket,fields,depth+1,key,sourceIndexes));else for(const row of bucket){const sourceIndex=this.sourceIndexFor(row,sourceIndexes);result.push({kind:"row",row,key:this.keyForRow(row,sourceIndex??result.length),depth:depth+1,sourceIndex:sourceIndex??result.length})}}return result}measurementSignature(items){return items===this.signatureItems?this.signatureValue:(this.signatureItems=items,this.signatureValue=items.map(item=>{const key=displayItemKey(item);return`${key.length}:${key}`}).join("|"),this.signatureValue)}invalidateRowMeasurements(){const anchor=this.lastMeasurementAnchor??this.captureMeasurementAnchor();return this.measuredItemHeights.size===0?(this.measuredItemOffsetsDirty=!0,!1):(anchor&&(this.pendingMeasurementAnchor=anchor),this.measuredItemHeights.clear(),this.measuredItemOffsetsDirty=!0,!0)}reconcileRowMeasurementCache(changed,contentRefresh=changed.size===0){const items=this.displayItems,signature=this.measurementSignature(items),locale=this.effectiveLocale,changedGeometry=["columns","columnOrder","columnVisibility","columnWidths","data","filters","searchTerm","sort","expandedKeys","groupBy","page","pageSize","paginate","childRows","rowDetail","rowClass","selectable","strings"].some(property2=>changed.has(property2)),localeChanged=this.measurementLocale!==""&&this.measurementLocale!==locale,structureChanged=this.measurementDisplaySignature!==""&&this.measurementDisplaySignature!==signature,rowHeightChanged=this.recordMeasurementRowHeight();(contentRefresh||changedGeometry||localeChanged||structureChanged||rowHeightChanged)&&this.invalidateRowMeasurements(),this.measurementLocale=locale,this.measurementDisplaySignature=signature}recordMeasurementRowHeight(){const height=this.resolvedRowHeight,previous=this.measurementRowHeight,fontSignature=this.currentMeasurementFontSignature(),fontChanged=this.measurementFontSignature!==""&&this.measurementFontSignature!==fontSignature;return this.measurementRowHeight=height,this.measurementFontSignature=fontSignature,previous!==void 0&&previous!==height||fontChanged}currentMeasurementFontSignature(){if(this.geometryCycle&&this.cycleFontSignature!==void 0)return this.cycleFontSignature;if(!this.isConnected)return"";const owner=this.ownerDocument?.defaultView;if(!owner||typeof owner.getComputedStyle!="function")return"";try{const style=owner.getComputedStyle(this),cell=this.renderRoot?.querySelector('[part~="cell"], [part~="header-cell"], [part="group-value"]'),cellStyle=cell?owner.getComputedStyle(cell):void 0,cellPadding=cellStyle?[cellStyle.paddingBlockStart,cellStyle.paddingBlockEnd,cellStyle.paddingInlineStart,cellStyle.paddingInlineEnd].join(","):this.computedToken("--cell-padding","--_lr-data-grid-cell-padding");return this.cycleFontSignature=[style.fontFamily,style.fontSize,style.fontStretch,style.fontStyle,style.fontWeight,style.letterSpacing,style.lineHeight,style.wordSpacing,cellPadding].join("\0")}catch{return""}}recordMeasuredBodyWidth(width){if(typeof width!="number"||!Number.isFinite(width)||width<0)return!1;const previous=this.measuredBodyWidth;return this.measuredBodyWidth=width,previous===void 0||previous===width?!1:(this.invalidateRowMeasurements(),!0)}syncMeasuredBodyWidth(){const body=this.bodyElement;body&&(this.syncBodyScrollbarInlineEndGutter(body),this.recordMeasuredBodyWidth(body.clientWidth)&&this.queueMeasurementUpdate())}syncBodyScrollbarInlineEndGutter(body){const scrollbarGutter=finiteRange(body.offsetWidth-body.clientWidth,0,0);if(this.bodyScrollbarInlineEndGutter===scrollbarGutter)return;this.bodyScrollbarInlineEndGutter=scrollbarGutter;const value=`${scrollbarGutter}px`;this.renderRoot.querySelectorAll('[part="header"], [part="footer-row"]').forEach(element=>element.style.setProperty("--data-grid-body-inline-end-gutter",value))}queueMeasurementUpdate(){if(this.measurementUpdateQueued)return;this.measurementUpdateQueued=!0;const owner=this.ownerDocument.defaultView;(owner?.queueMicrotask?.bind(owner)??queueMicrotask)(()=>{this.measurementUpdateQueued=!1,this.isConnected&&super.requestUpdate()})}queueMeasuredScrollTop(body){if(this.measurementScrollSyncQueued)return;this.measurementScrollSyncQueued=!0;const owner=body.ownerDocument.defaultView;(owner?.queueMicrotask?.bind(owner)??queueMicrotask)(()=>{if(this.measurementScrollSyncQueued=!1,!this.isConnected||this.bodyElement!==body)return;const next=finiteRange(body.scrollTop,this.bodyScrollTop,0);this.bodyScrollTop!==next&&(this.bodyScrollTop=next),this.lastMeasurementAnchor=this.captureMeasurementAnchor()})}queueBodyScrollStateSync(){if(this.bodyScrollStateSyncQueued)return;this.bodyScrollStateSyncQueued=!0;const owner=this.ownerDocument.defaultView;(owner?.queueMicrotask?.bind(owner)??queueMicrotask)(()=>{this.bodyScrollStateSyncQueued=!1,this.isConnected&&this.syncBodyScrollState()})}scheduleMeasurementSync(){if(this.measurementFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{if(this.measurementFrame!==frame||(this.measurementFrame=void 0,!this.isConnected||this.ownerDocument.defaultView!==owner))return;const body=this.bodyElement;body&&this.syncBodyScrollbarInlineEndGutter(body),this.measureRenderedItems()}),this.measurementFrame=frame}cancelMeasurementFrame(){const frame=this.measurementFrame;frame&&(this.measurementFrame=void 0,frame.owner.cancelAnimationFrame(frame.handle))}resetRowMeasurementObserver(){this.rowMeasurementObserver?.disconnect(),this.rowMeasurementObserver=void 0,this.rowMeasurementObserverOwner=void 0,this.rowMeasurementObserverBody=void 0,this.observedMeasurementElements.clear(),this.observedMeasurementBlockSizes.clear(),this.cancelMeasurementFrame();const invalidated=this.invalidateRowMeasurements();this.lastMeasurementAnchor=void 0,invalidated&&this.isConnected&&this.queueMeasurementUpdate()}syncRowMeasurementObserver(){const body=this.bodyElement,owner=body?.ownerDocument.defaultView;if(!body||!owner||!this.isConnected||!owner.ResizeObserver){this.resetRowMeasurementObserver();return}if(this.rowMeasurementObserverOwner!==owner||this.rowMeasurementObserverBody!==body||!this.rowMeasurementObserver){this.resetRowMeasurementObserver();const observer2=new owner.ResizeObserver(entries=>{if(!(this.rowMeasurementObserver!==observer2||this.rowMeasurementObserverOwner!==owner||this.rowMeasurementObserverBody!==body||!this.isConnected||this.ownerDocument.defaultView!==owner)){for(const entry of entries){const target=entry.target;if(target!==body&&!this.observedMeasurementElements.has(target))continue;const blockSize=entry.borderBoxSize?.[0]?.blockSize;blockSize!==void 0&&Number.isFinite(blockSize)&&blockSize>0?this.observedMeasurementBlockSizes.set(target,blockSize):this.observedMeasurementBlockSizes.delete(target)}this.syncBodyScrollState(body);for(const entry of entries){if(entry.target!==body)continue;const width=entry.borderBoxSize?.[0]?.inlineSize??entry.contentRect.width;if(this.recordMeasuredBodyWidth(width)){this.queueMeasurementUpdate();return}}this.scheduleMeasurementSync()}});this.rowMeasurementObserver=observer2,this.rowMeasurementObserverOwner=owner,this.rowMeasurementObserverBody=body,observer2.observe(body,{box:"border-box"})}const observer=this.rowMeasurementObserver;if(!observer)return;const current=new Map;this.renderRoot.querySelectorAll("[data-virtual-item-key], [data-virtual-item-detail-for]").forEach(element=>{const key=element.dataset.virtualItemKey??element.dataset.virtualItemDetailFor;key&&current.set(element,key)});for(const element of this.observedMeasurementElements.keys())current.has(element)||(observer.unobserve(element),this.observedMeasurementElements.delete(element),this.observedMeasurementBlockSizes.delete(element));for(const[element,key]of current)this.observedMeasurementElements.get(element)!==key&&(this.observedMeasurementElements.has(element)&&observer.unobserve(element),this.observedMeasurementElements.set(element,key),observer.observe(element,{box:"border-box"}))}syncDisplayOffsets(items){const estimate=this.measurementRowHeight??this.resolvedRowHeight,signature=this.measurementSignature(items);if(!this.measuredItemOffsetsDirty&&this.measuredItemOffsetSignature===signature&&this.measuredItemOffsetEstimate===estimate)return;this.measuredOffsetHeights=items.map(item=>finiteRange(this.measuredItemHeights.get(displayItemKey(item))??estimate,estimate,1,Number.MAX_SAFE_INTEGER));const tree=[0,...this.measuredOffsetHeights];for(let index=1;index<tree.length;index+=1){const parent=index+(index&-index);parent<tree.length&&(tree[parent]+=tree[index])}this.measuredOffsetTree=tree,this.measuredItemOffsetSignature=signature,this.measuredItemOffsetEstimate=estimate,this.measuredItemOffsetsDirty=!1}offsetPrefix(index){let sum=0;for(let position=index;position>0;position-=position&-position)sum+=this.measuredOffsetTree[position]??0;return Math.min(sum,Number.MAX_SAFE_INTEGER)}updateOffsetHeight(key,height){if(this.measuredItemOffsetsDirty)return;const index=this.displayIndexes.get(key);if(index===void 0||this.measuredItemOffsetSignature!==this.measurementSignature(this.displayItems)){this.measuredItemOffsetsDirty=!0;return}const previous=this.measuredOffsetHeights[index];this.measuredOffsetHeights[index]=height;for(let position=index+1;position<this.measuredOffsetTree.length;position+=position&-position)this.measuredOffsetTree[position]+=height-previous}displayItemOffset(index,items){return this.syncDisplayOffsets(items),this.offsetPrefix(finiteInteger(index,0,0,items.length))}displayItemHeight(index,items){return this.syncDisplayOffsets(items),index<0||index>=items.length?0:Math.max(0,this.offsetPrefix(index+1)-this.offsetPrefix(index))}displayItemIndexAtOffset(offset,items){if(items.length===0)return-1;this.syncDisplayOffsets(items);const target=finiteRange(offset,0,0,Number.MAX_SAFE_INTEGER);let index=0,sum=0,step=1;for(;step*2<=items.length;)step*=2;for(;step>0;step>>>=1){const next=index+step;next<=items.length&&sum+this.measuredOffsetTree[next]<=target&&(sum+=this.measuredOffsetTree[next],index=next)}return Math.min(index,items.length-1)}captureMeasurementAnchor(){const body=this.bodyElement,items=this.displayItems;if(!body||items.length===0)return;const scrollTop=finiteRange(body.scrollTop,this.bodyScrollTop,0);return this.measurementAnchorAtOffset(scrollTop,items)}measurementAnchorAtOffset(scrollTop,items){if(items.length===0)return;const index=this.displayItemIndexAtOffset(scrollTop,items),item=items[index];if(!item)return;const offset=Math.max(0,scrollTop-this.displayItemOffset(index,items)),height=this.displayItemHeight(index,items);if(index+1<items.length&&height>1&&offset>=height-1){const next=items[index+1];return Object.freeze({itemKey:displayItemKey(next),offset:0})}return Object.freeze({itemKey:displayItemKey(item),offset})}correctMeasurementAnchor(){const anchor=this.pendingMeasurementAnchor,body=this.bodyElement;if(!anchor||!body)return;const items=this.displayItems,index=this.displayIndexes.get(anchor.itemKey)??-1;if(this.pendingMeasurementAnchor=void 0,index<0){this.lastMeasurementAnchor=void 0;return}const next=Math.max(0,this.displayItemOffset(index,items)+anchor.offset);this.expectedBodyScroll=Object.freeze({body,top:next}),body.scrollTop=next,this.lastMeasurementAnchor=anchor,this.queueMeasuredScrollTop(body)}measureRenderedItems(){const previous=this.geometryCycle;previous||this.resetGeometryCycle(),this.geometryCycle=!0;try{this.measureCurrentItems()}finally{this.geometryCycle=previous}}measureCurrentItems(){const rowHeightChanged=this.recordMeasurementRowHeight();rowHeightChanged&&this.invalidateRowMeasurements();const estimate=this.measurementRowHeight??this.resolvedRowHeight,grouped=new Map;if(this.renderRoot.querySelectorAll("[data-virtual-item-key], [data-virtual-item-detail-for]").forEach(element=>{const key=element.dataset.virtualItemKey??element.dataset.virtualItemDetailFor;if(!key)return;const entries=grouped.get(key)??[];entries.push(element),grouped.set(key,entries)}),grouped.size===0){rowHeightChanged&&this.queueMeasurementUpdate();return}const anchor=this.captureMeasurementAnchor();let changed=!1;for(const[key,elements]of grouped){let height=0,measurable=!0;for(const element of elements){let next;try{next=this.layoutBorderBoxHeight(element)}catch{measurable=!1;break}if(!Number.isFinite(next)||next<=0){measurable=!1;break}height+=next}if(!measurable||!Number.isFinite(height)||height<=0)continue;const previous=this.measuredItemHeights.get(key);if(Math.abs(estimate-height)<=1){previous!==void 0&&(this.measuredItemHeights.delete(key),this.updateOffsetHeight(key,estimate),changed=!0);continue}previous!==void 0&&Math.abs(previous-height)<=.1||(this.measuredItemHeights.set(key,height),this.updateOffsetHeight(key,height),changed=!0)}if(!changed){rowHeightChanged&&this.queueMeasurementUpdate();return}anchor&&this.pendingMeasurementAnchor===void 0&&(this.pendingMeasurementAnchor=anchor),this.queueMeasurementUpdate()}layoutBorderBoxHeight(element){if(!element.isConnected)return Number.NaN;const style=element.ownerDocument.defaultView?.getComputedStyle(element);if(!style||style.display==="none")return Number.NaN;const roundedHeight=element.offsetHeight;if(roundedHeight<=0)return Number.NaN;const observed=this.observedMeasurementBlockSizes.get(element);if(observed!==void 0&&Math.abs(observed-roundedHeight)<=.5)return observed;const height=Number.parseFloat(style.height);return style.boxSizing==="border-box"?height:height+Number.parseFloat(style.paddingTop)+Number.parseFloat(style.paddingBottom)+Number.parseFloat(style.borderTopWidth)+Number.parseFloat(style.borderBottomWidth)}renderedRowAlignmentDelta(target,body,alignment){let targetTop,targetBottom;const style=target.ownerDocument.defaultView?.getComputedStyle(target),visuallyTransformed=style&&(style.position==="sticky"||style.transform!=="none"||style.translate&&style.translate!=="none"||style.scale&&style.scale!=="none"||style.rotate&&style.rotate!=="none"||style.zoom&&style.zoom!=="1"&&style.zoom!=="normal");if(target.offsetParent===body&&!visuallyTransformed)targetTop=target.offsetTop-body.scrollTop,targetBottom=targetTop+target.offsetHeight;else{const targetRect=target.getBoundingClientRect(),bodyRect=body.getBoundingClientRect(),bodyLayoutHeight=this.layoutBorderBoxHeight(body),scaleY=bodyLayoutHeight>0&&bodyRect.height>0?finiteRange(bodyRect.height/bodyLayoutHeight,1,Number.EPSILON):1;targetTop=(targetRect.top-bodyRect.top)/scaleY-body.clientTop,targetBottom=(targetRect.bottom-bodyRect.top)/scaleY-body.clientTop}const viewportBottom=body.clientHeight;if(alignment==="center")return(targetTop+targetBottom-viewportBottom)/2;if(alignment==="end")return targetBottom-viewportBottom;if(alignment==="start")return targetTop;const outsideTop=targetTop<0,outsideBottom=targetBottom>viewportBottom;if(outsideTop===outsideBottom)return 0;const oversized=targetBottom-targetTop>body.clientHeight;return outsideTop?oversized?targetBottom-viewportBottom:targetTop:oversized?targetTop:targetBottom-viewportBottom}renderedStartPrecisionDelta(target,body){const bodyRect=body.getBoundingClientRect(),layoutHeight=this.layoutBorderBoxHeight(body),scaleY=bodyRect.height/layoutHeight;if(!Number.isFinite(scaleY)||scaleY<=0)return 0;const style=body.ownerDocument.defaultView?.getComputedStyle(body),borderTop=Number.parseFloat(style?.borderTopWidth??""),visualError=target.getBoundingClientRect().top-(bodyRect.top+borderTop*scaleY);return Math.abs(visualError)>1?visualError/scaleY:0}alignPendingVirtualScroll(){const pending=this.pendingVirtualScroll;if(!pending||this.measurementUpdateQueued||this.measurementScrollSyncQueued||this.pendingMeasurementAnchor!==void 0)return;if(!this.displayIndexes.has(pending.itemKey)){this.pendingVirtualScroll=void 0;return}const target=[...this.renderRoot.querySelectorAll('[part~="row"][data-virtual-item-key]')].find(element=>element.dataset.virtualItemKey===pending.itemKey),body=this.bodyElement;if(!target||!body)return;const layoutDelta=this.renderedRowAlignmentDelta(target,body,pending.align),precisionDelta=pending.align==="start"?this.renderedStartPrecisionDelta(target,body):0;if(Math.abs(layoutDelta)<=.5&&precisionDelta===0){this.pendingVirtualScroll=void 0;return}const alignmentDelta=Math.abs(layoutDelta)>.5?layoutDelta:precisionDelta,previousTop=body.scrollTop,nextTop=finiteRange(previousTop+alignmentDelta,previousTop,0,Math.max(0,body.scrollHeight-body.clientHeight));if(body.scrollTo({top:nextTop}),precisionDelta!==0){const remaining=this.renderedStartPrecisionDelta(target,body);Math.abs(remaining)>=Math.abs(precisionDelta)&&(body.scrollTo({top:previousTop}),this.pendingVirtualScroll=void 0)}body.scrollTop===previousTop?this.pendingVirtualScroll=void 0:(this.expectedBodyScroll=Object.freeze({body,top:body.scrollTop}),this.queueMeasurementUpdate()),this.queueBodyScrollStateSync()}resetGeometryCycle(){this.cycleRowHeight=void 0,this.cycleColumnEstimate=void 0,this.cycleFontSignature=void 0}get resolvedRowHeight(){if(this.geometryCycle&&this.cycleRowHeight!==void 0)return this.cycleRowHeight;const raw=this.computedToken("--row-height","--_lr-data-grid-row-height"),targetFloor=resolveCssTokenLength(this.computedToken("--_lr-density-target-min"),{host:this})??0;return this.cycleRowHeight=finiteRange(resolveCssTokenLength(raw,{host:this})??56,56,Math.max(24,targetFloor))}detailRowOffsets(items){return this.rowDetail?this.memoize("detailRowOffsets",[items,this.expandedKeys,this.rowDetail],()=>{const offsets=[0];for(const item of items)offsets.push(offsets[offsets.length-1]+(item.kind==="row"&&arrayHasKey(this.expandedKeys,item.key)?1:0));return offsets}):[0]}get virtualWindow(){const items=this.displayItems;if(items.length<VIRTUALIZATION_THRESHOLD||this.computedToken("--max-height","--_lr-data-grid-max-height")==="none")return{items,allItems:items,start:0,end:items.length};const height=this.resolvedRowHeight,viewport=Math.max(height,this.viewportHeight||height*10),firstVisible=this.displayItemIndexAtOffset(this.bodyScrollTop,items),lastVisible=this.displayItemIndexAtOffset(this.bodyScrollTop+viewport,items),start=Math.max(0,firstVisible-VIRTUAL_OVERSCAN),end=Math.min(items.length,lastVisible+VIRTUAL_OVERSCAN+1);return{items:items.slice(start,end),allItems:items,start,end}}columnGeometryInputs(){return[this.visibleColumns,this.columnWidths,this.measuredBodyWidth,this.selectionEnabled,this.currentMeasurementFontSignature(),this.pipelineEpoch,this.processedClientRows,this.estimatedColumnWidth({},"")]}sameColumnGeometry(left,right){return left?.length===right.length&&left.every((input,index)=>Object.is(input,right[index]))}get gridTemplate(){const inputs=this.columnGeometryInputs();return this.visibleColumns.length>50&&this.resolvedColumnWidths&&this.sameColumnGeometry(this.resolvedColumnInputs,inputs)?this.memoize("resolvedGridTemplate",[this.resolvedColumnWidths,this.selectionEnabled],()=>{const tracks=this.resolvedColumnWidths.map(width=>`${width}px`);return this.selectionEnabled&&tracks.unshift("var(--lr-icon-button-size)"),tracks.join(" ")}):(this.naturalColumnInputs=inputs,this.memoize("gridTemplate",[this.visibleColumns,this.columnWidths,this.selectionEnabled],()=>this.computeGridTemplate()))}computeGridTemplate(){const columns=this.visibleColumns.map(({column,id})=>{const bounds=this.columnBounds(column),width=this.columnWidths.get(id)??column.width;if(width!==void 0&&Number.isFinite(width)&&width>0)return`${finiteRange(width,bounds.minimum,bounds.minimum,bounds.maximum)}px`;const minimum=bounds.minimum>0?`${bounds.minimum}px`:Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?"0px":"var(--lr-size-7rem)",maximum=Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?`${bounds.maximum}px`:`${finiteRange(column.flex??1,1,0)}fr`;return`minmax(${minimum}, ${maximum})`});return this.selectionEnabled&&columns.unshift("var(--lr-icon-button-size)"),columns.length>0?columns.join(" "):"minmax(var(--lr-size-7rem), 1fr)"}syncResolvedColumnWidths(){const inputs=this.columnGeometryInputs();if(this.sameColumnGeometry(this.resolvedColumnInputs,inputs))return;if(!this.sameColumnGeometry(this.naturalColumnInputs,inputs)){this.queueMeasurementUpdate();return}const row=this.renderRoot.querySelector('[part~="row"]')??this.renderRoot.querySelector('[part="header"]'),owner=this.ownerDocument.defaultView;if(!row||typeof owner?.getComputedStyle!="function")return;let tracks;try{tracks=owner.getComputedStyle(row).gridTemplateColumns.split(/\s+/u).map(value=>Number.parseFloat(value))}catch{return}const widths=this.selectionEnabled?tracks.slice(1):tracks;widths.length!==this.visibleColumns.length||widths.some(width=>!Number.isFinite(width)||width<0)||(this.resolvedColumnInputs=inputs,this.queueMeasurementUpdate(),!(this.resolvedColumnWidths?.length===widths.length&&this.resolvedColumnWidths.every((width,index)=>Math.abs(width-widths[index])<.01))&&(this.resolvedColumnWidths=widths,this.queueMeasurementUpdate()))}get columnLayout(){const columns=this.visibleColumns,estimate=this.estimatedColumnWidth({},"");return this.memoize("columnLayout",[columns,this.columnWidths,estimate,this.selectionEnabled,this.resolvedColumnWidths],()=>{const offsets=[0],positions=new Map,pins=new Map,pinned=[];let left=0,right=0;columns.forEach(({column,id},position)=>{positions.set(id,position);const width=this.resolvedColumnWidths?.[position]??this.estimatedColumnWidth(column,id);offsets.push(offsets[position]+width),normalizePinSide(this.getColumnPin(id))==="left"&&(pins.set(id,left),left+=width,pinned.push(position))});for(let index=columns.length-1;index>=0;index-=1){const{column,id}=columns[index];normalizePinSide(this.getColumnPin(id))==="right"&&(pins.set(id,right),right+=this.resolvedColumnWidths?.[index]??this.estimatedColumnWidth(column,id),pinned.push(index))}return{offsets,positions,pins,pinned}})}get windowColumns(){const columns=this.visibleColumns,layout=this.columnLayout;if(columns.length<=50)return columns.map((entry,position)=>({...entry,position}));const at=offset=>{let low=0,high=columns.length-1;for(;low<high;){const middle=low+high>>>1;layout.offsets[middle+1]<=offset?low=middle+1:high=middle}return low},start=Math.max(0,at(this.bodyScrollInlineOffset)-2),end=Math.min(columns.length,at(this.bodyScrollInlineOffset+(this.measuredBodyWidth||1120))+3),positions=new Set(layout.pinned);positions.add(this.focusedColumn),(this.selectionEnabled||this.childRows||this.rowDetail)&&positions.add(0);for(let index=start;index<end;index+=1)positions.add(index);return[...positions].sort((a,b)=>a-b).flatMap(position=>{const entry=columns[position];return entry?[{...entry,position}]:[]})}get bodyScrollTranslation(){const logical=finiteRange(this.bodyScrollInlineOffset,0,0,Number.MAX_SAFE_INTEGER);return`${this.effectiveDirection==="rtl"?logical:-logical}px`}columnStyle(column,id){const cache=this.memoize("columnStyles",[this.columnLayout,this.selectionEnabled],()=>new Map),cached=cache.get(id);if(cached)return cached;const side=normalizePinSide(this.getColumnPin(id)),pinOffset=side?this.pinOffset(id,side):0,style={"grid-column":String((this.columnLayout.positions.get(id)??0)+1+(this.selectionEnabled?1:0)),...side?{"--pin-offset":`${pinOffset}px`}:{},...Number.isFinite(column.width)&&(column.width??0)>0&&!this.columnWidths.has(id)?{"--column-authored-width":`${column.width}px`}:{}};return cache.set(id,style),style}estimatedColumnWidth(column,id){const{minimum,maximum}=this.columnBounds(column),explicit=this.columnWidths.get(id)??column.width;return explicit!==void 0&&Number.isFinite(explicit)&&explicit>0?finiteRange(explicit,Math.max(112,minimum),minimum,maximum):(this.geometryCycle||(this.cycleColumnEstimate=void 0),this.cycleColumnEstimate??=resolveCssTokenLength(this.computedToken("--lr-size-7rem"),{host:this})??112,finiteRange(this.cycleColumnEstimate,Math.max(112,minimum),minimum,maximum))}columnBounds(column){const minimum=finiteRange(column.minWidth??0,0,0),authoredMaximum=finiteRange(column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0);return Object.freeze({minimum,maximum:Math.max(minimum,authoredMaximum)})}pinOffset(id,_side){return this.columnLayout.pins.get(id)??0}columnLabel(column,id){return column.label!==void 0&&column.label.trim().length>0?column.label:humanizeIdentifier(column.field??id,this.effectiveLocale)}columnIsSortable(column){return column.sortable!==!1&&!!(column.field||column.value)}sortFor(id){const index=this.sort.findIndex(item=>item.id===id);return{state:index>=0?this.sort[index]:void 0,index}}activateSort(id,additive){const entry=this.columnIndex.get(id);if(!entry||!this.columnIsSortable(entry.column))return;const existing=this.sortFor(id).state,descendingFirst=entry.column.sortDescFirst??this.sortDescFirst;let replacement;existing?existing.desc===descendingFirst?replacement={id,desc:!descendingFirst}:this.withoutSortRemoval&&(replacement={id,desc:descendingFirst}):replacement={id,desc:descendingFirst};let next=additive?this.sort.filter(item=>item.id!==id):[];replacement&&next.push(replacement);const limit=finiteCount(this.maxMultiSort);limit>0&&next.length>limit&&(next=next.slice(next.length-limit));const proposedSort=frozenArray(next.map(item=>Object.freeze({...item})));this.emit("lr-sort-request",Object.freeze({sort:proposedSort}),{cancelable:!0}).defaultPrevented||(this.sort=next,this.page=0,this.emit("lr-sort-change",Object.freeze({sort:proposedSort})))}onHeaderClick(event,id){const target=event.target,interactive=isElementValue(target)?target.closest(INTERACTIVE_SELECTOR):null;interactive&&interactive!==event.currentTarget||this.activateSort(id,event.shiftKey)}onFilterInput(event,id){const control=valueControl(event.currentTarget);control&&this.commitFilterValue(id,control.value)}commitFilterValue(id,value){const next=this.filters.filter(filter=>filter.id!==id);value&&next.push({id,value}),this.filters=next,this.page=0,this.emit("lr-filter-change",Object.freeze({filters:frozenArray(next.map(filter=>Object.freeze({...filter})))}))}onClearFilterInput(id){this.filters.some(filter=>filter.id===id)&&(this.commitFilterValue(id,""),this.renderRoot.querySelector('[part="filter-panel"] input[type="search"]')?.focus())}syncBodyScrollState(source=this.bodyElement){const target=source;if(!isElementValue(target)||typeof target.scrollTop!="number"||typeof target.clientHeight!="number"||typeof target.scrollLeft!="number")return;this.bodyScrollTop=finiteRange(target.scrollTop,this.bodyScrollTop,0),this.viewportHeight=finiteRange(target.clientHeight,this.viewportHeight,0);const inlineExtent=typeof target.scrollWidth=="number"&&typeof target.clientWidth=="number"&&Number.isFinite(target.scrollWidth)&&Number.isFinite(target.clientWidth)?Math.max(0,target.scrollWidth-target.clientWidth):Number.MAX_SAFE_INTEGER;this.bodyScrollInlineOffset=finiteRange(this.effectiveDirection==="rtl"?-target.scrollLeft:target.scrollLeft,0,0,inlineExtent)}onBodyScroll(event){const body=event.currentTarget;this.syncBodyScrollState(body);const expected=this.expectedBodyScroll;expected&&expected.body===body&&Math.abs(finiteRange(body.scrollTop,this.bodyScrollTop,0)-expected.top)<=1?this.expectedBodyScroll=void 0:(this.expectedBodyScroll=void 0,this.pendingMeasurementAnchor=void 0,this.pendingVirtualScroll=void 0),this.lastMeasurementAnchor=this.captureMeasurementAnchor()}onBodyCellEvent(event){const cell=event.composedPath().find(node=>isElementValue(node)&&node.hasAttribute("data-row-position")&&node.hasAttribute("data-column-id"));if(!cell)return;const rowPosition=Number(cell.dataset.rowPosition),columnPosition=Number(cell.dataset.columnPosition),item=this.displayItems[rowPosition],id=cell.dataset.columnId,entry=this.columnIndex.get(id);!item||item.kind!=="row"||!entry||(event.type==="focusin"?(this.focusedRow=rowPosition,this.focusedColumn=columnPosition):event.type==="click"?this.onCellClick(event,item,entry.column,id,rowPosition,cell):event.type==="contextmenu"?this.emitCellContextMenu(event,item,entry.column,id,rowPosition):event.type==="keydown"&&this.onGridKeyDown(event,rowPosition,columnPosition,item,entry.column,id,cell))}onCellClick(event,item,column,columnIdValue,index,cell=event.currentTarget){for(const target of event.composedPath()){if(target===cell)break;if(isElementValue(target)&&target.matches(INTERACTIVE_SELECTOR))return}this.emit("lr-cell-click",Object.freeze({rowKey:item.key,columnId:columnIdValue,column,value:columnValue(column,item.row),row:item.row,index}))}emitCellContextMenu(originalEvent,item,column,columnIdValue,index){const detail=Object.freeze({rowKey:item.key,columnId:columnIdValue,column,value:columnValue(column,item.row),row:item.row,index,originalEvent});this.emit("lr-cell-contextmenu",detail,{cancelable:!0}).defaultPrevented&&originalEvent.preventDefault()}descendantRows(row){const result=[],visited=new Set,stack=this.canonicalMembers(this.childrenFor(row)).reverse().map(child=>({row:child,depth:1}));for(;stack.length>0&&result.length<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(trackIdentity&&visited.has(current.row)||(trackIdentity&&visited.add(current.row),result.push(current.row),current.depth>=DATA_GRID_TREE_DEPTH_LIMIT))continue;const children=this.canonicalMembers(this.childrenFor(current.row));for(let index=children.length-1;index>=0;index-=1){const child=children[index];stack.push({row:child,depth:current.depth+1})}}return result}setRowSelected(item,selected,event){if(!this.rowIsSelectable(item.row))return;const{items:selectableItems,positions}=this.memoize("selectableDisplay",[this.displayItems,this.selectable,this.selectableRows],()=>{const items=this.displayItems.filter(candidate=>candidate.kind==="row"&&this.rowIsSelectable(candidate.row));return{items,positions:new Map(items.map((candidate,position2)=>[candidate.key,position2]))}}),position=positions.get(item.key)??-1;let affected=[item];if(event?.shiftKey&&this.selectionMode==="multiple"&&this.lastSelectedIndex>=0){const from=Math.min(this.lastSelectedIndex,position),to=Math.max(this.lastSelectedIndex,position);affected=selectableItems.slice(from,to+1)}const descendants=this.selectionMode==="multiple"?affected.flatMap(candidate=>this.descendantRows(candidate.row)).filter(row=>this.rowIsSelectable(row)):[],sourceIndexes=this.sourceIndexMap(),keys=[...affected.map(candidate=>candidate.key),...descendants.map((row,index)=>{const sourceIndex=this.sourceIndexFor(row,sourceIndexes);return this.keyForRow(row,sourceIndex??index)})],ordered=new Map;for(const key of keys){const typed=typedKey(key);ordered.delete(typed),ordered.set(typed,key)}const next=this.selectionMode==="single"?[]:this.selectedKeys.filter(candidate=>!ordered.has(typedKey(candidate)));selected&&next.push(...ordered.values()),this.selectedKeys=next,this.lastSelectedIndex=position,this.emitSelection()}selectCurrentPage(selected){const pageKeys=this.currentPageSelectableRows.map(item=>item.key),pageKeySet=new Set(pageKeys.map(typedKey));let next=this.selectedKeys.filter(key=>!pageKeySet.has(typedKey(key)));selected&&(next=[...next,...pageKeys]),this.selectedKeys=next,this.emitSelection()}emitSelection(){const selectedRowKeys=frozenArray(this.selectedRowKeys),selectedRows=frozenArray(this.selectedRows);this.emit("lr-row-select",Object.freeze({selectedRowKeys,selectedKeys:selectedRowKeys,selectedRows}))}rowSelectionState(item){const states=this.memoize("selectionStates",[this.allSourceRows,this.selectedKeys,this.selectable,this.selectableRows,this.childRows],()=>{const result=new Map;if(!this.childRows||this.selectionMode!=="multiple")return result;const byIdentity=this.canonicalRowIndex(),children=new Map,parentCounts=new Map;for(const row of this.allSourceRows){const nested=this.canonicalMembers(this.childrenFor(row),byIdentity);children.set(row,nested);for(const child of nested)parentCounts.set(child,(parentCounts.get(child)??0)+1)}if([...parentCounts.values()].some(count=>count>1))return result;const totals=new Map,visiting=new Set,visit=(row,depth)=>{if(totals.has(row))return!0;if(visiting.has(row)||depth>DATA_GRID_TREE_DEPTH_LIMIT)return!1;visiting.add(row);let count=0,selected=0;for(const child of children.get(row)??[]){if(!visit(child,depth+1))return!1;const total=totals.get(child);count+=total.count,selected+=total.selected}const own=arrayHasKey(this.selectedKeys,this.rowIdentity(row)),checked=own&&selected===count;result.set(row,{checked,indeterminate:!checked&&(own||selected>0)});const eligible=this.rowIsSelectable(row);return totals.set(row,{count:count+(eligible?1:0),selected:selected+(eligible&&own?1:0)}),visiting.delete(row),!0};for(const row of this.allSourceRows)if(!visit(row,0)){result.clear();break}return result});let state2=states.get(item.row);return state2||(state2=this.computeRowSelectionState(item),states.set(item.row,state2)),state2}computeRowSelectionState(item){const own=arrayHasKey(this.selectedKeys,item.key);if(this.selectionMode!=="multiple")return{checked:own,indeterminate:!1};const descendants=this.descendantRows(item.row).filter(row=>this.rowIsSelectable(row));if(descendants.length===0)return{checked:own,indeterminate:!1};const sourceIndexes=this.sourceIndexMap(),selected=descendants.filter((row,index)=>{const sourceIndex=this.sourceIndexFor(row,sourceIndexes);return arrayHasKey(this.selectedKeys,this.keyForRow(row,sourceIndex??index))}).length,checked=own&&selected===descendants.length;return{checked,indeterminate:!checked&&(own||selected>0)}}toggleRowExpanded(item,emitUserEvent){const expanded=arrayHasKey(this.expandedKeys,item.key);expanded?this.collapseRow(item.key):this.expandRow(item.key),emitUserEvent&&this.emit(expanded?"lr-row-collapse":"lr-row-expand",Object.freeze({rowKey:item.key,key:item.key,row:item.row}))}toggleGroupExpanded(item){const expanded=arrayHasKey(this.expandedKeys,item.key);expanded?this.collapseRow(item.key):this.expandRow(item.key);const detail=Object.freeze({key:item.key,columnId:item.columnId,value:item.value,rows:frozenArray(item.rows)});this.emit(expanded?"lr-group-collapse":"lr-group-expand",detail)}moveColumn(id,delta,emitUserEvent){const order=this.orderedColumns.map(entry=>entry.id),from=order.indexOf(id);if(from<0)return;const to=finiteInteger(from+delta,from,0,order.length-1);from!==to&&(order.splice(from,1),order.splice(to,0,id),this.columnOrder=order,emitUserEvent&&this.emit("lr-column-move",Object.freeze({columnOrder:frozenArray(order),columnId:id,finished:!0})))}columnCanMove(id){const entry=this.columnIndex.get(id);return!!(entry&&(this.reorderable||entry.column.movable))}columnCanResize(id){const entry=this.columnIndex.get(id);return!!(entry&&(this.resizable||entry.column.resizable))}onDragStart(event,id){const entry=this.columnIndex.get(id);if(!entry||!this.columnCanMove(id)||!event.dataTransfer){event.preventDefault();return}const token=`${++this.columnDragSequence}:${id}`;this.columnDragSession=Object.freeze({sourceId:id,token}),event.dataTransfer.setData(DATA_GRID_DRAG_TYPE,token),event.dataTransfer.setData("text/plain",id),event.dataTransfer.effectAllowed="move",this.dragGhost=this.columnLabel(entry.column,id)}onDrop(event,targetId){event.preventDefault();const session=this.columnDragSession,token=event.dataTransfer?.getData(DATA_GRID_DRAG_TYPE),sourceId=session?.sourceId;if(this.columnDragSession=void 0,this.dragGhost="",!session||token!==session.token||!sourceId||sourceId===targetId||!this.columnCanMove(sourceId)||!this.columnCanMove(targetId))return;const order=this.orderedColumns.map(entry=>entry.id),source=order.indexOf(sourceId),target=order.indexOf(targetId);source<0||target<0||(order.splice(source,1),order.splice(target,0,sourceId),this.columnOrder=order,this.emit("lr-column-move",Object.freeze({columnOrder:frozenArray(order),columnId:sourceId,finished:!0})))}onResizeStart(event,id){const entry=this.columnIndex.get(id);if(!entry||!this.columnCanResize(id))return;this.resizePointer.stop(),this.resizeSession?.moved&&this.restoreResizeSession(this.resizeSession,!0);const header=this.renderedColumnElements(id,"columnheader")[0];this.resizeSession={columnId:id,startClientX:event.clientX,startWidth:header?.getBoundingClientRect().width??this.estimatedColumnWidth(entry.column,id),initialStateWidth:this.columnWidths.get(id),pointerId:event.pointerId,moved:!1,direction:this.effectiveDirection},this.activeResizeColumn=id,this.resizePointer.start(event,event.currentTarget),event.preventDefault()}onResizeMove(event){const session=this.resizeSession;if(!session||event.pointerId!==session.pointerId)return;if(!this.columnCanResize(session.columnId)){this.resizePointer.stop(),this.resizeSession=void 0,this.activeResizeColumn=void 0,session.moved&&this.restoreResizeSession(session,!0);return}const{minimum,maximum}=this.columnBounds(this.columnIndex.get(session.columnId).column);this.setColumnWidth(session.columnId,columnResizePointerWidth(session.startWidth,session.startClientX,event.clientX,session.direction==="rtl",minimum,maximum),!0,!1),session.moved=!0}takeResizeSession(event){const session=this.resizeSession;if(!(!session||event.pointerId!==session.pointerId))return this.resizeSession=void 0,this.activeResizeColumn=void 0,this.resizePointer.stop(),session}restoreResizeSession(session,emit){const next=new Map(this.columnWidths);session.initialStateWidth===void 0?next.delete(session.columnId):next.set(session.columnId,session.initialStateWidth),this.columnWidths=next,emit&&this.emit("lr-column-resize",Object.freeze({columnId:session.columnId,columnKey:session.columnId,width:session.startWidth,finished:!1}))}onResizeEnd(event){const session=this.takeResizeSession(event);if(!session)return;if(!this.columnCanResize(session.columnId)){session.moved&&this.restoreResizeSession(session,!0);return}const width=this.columnWidths.get(session.columnId)??session.startWidth;let committed=!1;requestThenCommit({requestDetail:Object.freeze({columnId:session.columnId,columnKey:session.columnId,width}),emitRequest:(detail,init)=>this.emit("lr-column-resize-request",detail,init),commit:()=>{committed=!0,this.emit("lr-column-resize",Object.freeze({columnId:session.columnId,columnKey:session.columnId,width,finished:!0}))}}),committed||this.restoreResizeSession(session,!0)}onResizeCancel(event){const session=this.takeResizeSession(event);!session||!session.moved||this.restoreResizeSession(session,!0)}onResizeKey(event,id,fromHandle=!1){const entry=this.columnIndex.get(id);if(!entry||!this.columnCanResize(id))return;const arrow=event.key==="ArrowLeft"||event.key==="ArrowRight",jump=fromHandle&&(event.key==="Home"||event.key==="End"&&entry.column.maxWidth!==void 0);if(!arrow&&!jump)return;event.preventDefault();const{minimum,maximum}=this.columnBounds(entry.column),current=this.columnWidths.get(id)??this.renderedColumnWidth(id)??this.estimatedColumnWidth(entry.column,id),width=columnResizeKeyboardWidth(event,current,minimum,maximum,this.effectiveDirection==="rtl",fromHandle);width!==void 0&&requestThenCommit({requestDetail:Object.freeze({columnId:id,columnKey:id,width}),emitRequest:(detail,init)=>this.emit("lr-column-resize-request",detail,init),commit:()=>this.setColumnWidth(id,width,!0,!0)})}renderedColumnWidth(id){const width=this.renderedColumnElements(id,"columnheader")[0]?.getBoundingClientRect().width;return width!==void 0&&Number.isFinite(width)&&width>0?width:void 0}syncResizeHandleValues(){for(const handle of this.renderRoot.querySelectorAll('[part="resize-handle"]')){const header=handle.closest('[role="columnheader"][data-column-id]'),id=header?.getAttribute("data-column-id");if(!header||!id||this.columnWidths.has(id))continue;const entry=this.columnIndex.get(id);if(!entry||entry.column.width!==void 0)continue;const rendered=header.getBoundingClientRect().width;if(!Number.isFinite(rendered)||rendered<=0)continue;const width=Math.round(rendered);handle.getAttribute("aria-valuenow")!==String(width)&&(handle.setAttribute("aria-valuenow",String(width)),handle.setAttribute("aria-valuetext",this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(width)})))}}onPageSizeChange(event){const control=valueControl(event.currentTarget);control&&(this.pageSize=finiteCount(Number(control.value)),this.page=0,this.emit("lr-page-change",Object.freeze({page:0,pageSize:this.safePageSize})))}focusCell(row,column){const rowLimit=Math.max(-1,this.displayItems.length-1),columnLimit=Math.max(0,this.visibleColumns.length-1);this.focusedRow=finiteInteger(row,this.focusedRow,-1,rowLimit),this.focusedColumn=finiteInteger(column,this.focusedColumn,0,columnLimit);let pendingScrollTop;if(this.focusedRow>=0){const selector=`[role="gridcell"][data-row-position="${this.focusedRow}"]`;if(!this.renderRoot.querySelector(selector)){const top=this.displayItemOffset(this.focusedRow,this.displayItems);pendingScrollTop=top,this.bodyScrollTop=top,this.bodyElement&&(this.bodyElement.scrollTop=top)}}this.updateComplete.then(()=>{pendingScrollTop!==void 0&&this.bodyElement&&(this.bodyElement.scrollTop=pendingScrollTop),this.focus()})}handleDisclosureKey(direction,rowPosition){const items=this.displayItems,item=items[rowPosition];if(!item)return!1;const expanded=arrayHasKey(this.expandedKeys,item.key);if(item.kind==="group")return direction>0===expanded?!1:(this.toggleGroupExpanded(item),!0);if((this.childrenFor(item.row).length>0||this.rowDetail!==null)&&direction>0!==expanded)return this.toggleRowExpanded(item,!0),!0;if(direction>0||!this.childRows||item.depth===0)return!1;let parent=rowPosition-1;for(;parent>0&&(items[parent]?.depth??0)>=item.depth;)parent-=1;return this.focusCell(parent,0),!0}onGridKeyDown(event,rowPosition,columnPosition,item,column,columnIdValue,cell=event.currentTarget){const target=event.target;if(isElementValue(target)&&target!==cell&&target.closest(INTERACTIVE_SELECTOR))return;const rtlMultiplier=this.effectiveDirection==="rtl"?-1:1;if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="a"&&this.selectionMode==="multiple"){this.selectCurrentPage(!0),event.preventDefault();return}if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="c"){this.copySelectedRows(),event.preventDefault();return}if(event.shiftKey&&event.key==="F10"&&item&&column&&columnIdValue){this.emitCellContextMenu(event,item,column,columnIdValue,rowPosition);return}const headerEntry=columnIdValue?this.columnIndex.get(columnIdValue):void 0;if(rowPosition<0&&columnIdValue&&headerEntry&&(this.reorderable||headerEntry.column.movable)&&event.shiftKey&&!event.altKey&&(event.key==="ArrowLeft"||event.key==="ArrowRight")){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.moveColumn(columnIdValue,delta,!0),event.preventDefault();return}if(!((event.altKey||event.metaKey)&&event.key.startsWith("Arrow"))){if(rowPosition>=0&&columnPosition===0&&(event.key==="ArrowLeft"||event.key==="ArrowRight")&&!event.altKey&&!event.ctrlKey&&!event.metaKey&&!event.shiftKey&&this.handleDisclosureKey((event.key==="ArrowRight"?1:-1)*rtlMultiplier,rowPosition)){event.preventDefault();return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.focusCell(rowPosition,columnPosition+delta),event.preventDefault()}else if(event.key==="ArrowUp")this.focusCell(rowPosition-1,columnPosition),event.preventDefault();else if(event.key==="ArrowDown")this.focusCell(rowPosition+1,columnPosition),event.preventDefault();else if(event.key==="Home")this.focusCell(event.ctrlKey||event.metaKey?-1:rowPosition,0),event.preventDefault();else if(event.key==="End")this.focusCell(event.ctrlKey||event.metaKey?this.displayItems.length-1:rowPosition,this.visibleColumns.length-1),event.preventDefault();else if(event.key==="PageUp"||event.key==="PageDown"){const delta=event.key==="PageDown"?this.safePageSize||10:-(this.safePageSize||10);this.focusCell(rowPosition+delta,columnPosition),event.preventDefault()}else if(event.key==="Enter")rowPosition<0&&columnIdValue?this.activateSort(columnIdValue,event.shiftKey):item&&column&&columnIdValue&&this.emit("lr-cell-click",Object.freeze({rowKey:item.key,columnId:columnIdValue,column,value:columnValue(column,item.row),row:item.row,index:rowPosition})),event.preventDefault();else if(event.key===" "&&item){const selected=!arrayHasKey(this.selectedKeys,item.key);this.setRowSelected(item,selected,event),event.preventDefault()}else if(event.key===" "&&rowPosition>=0){const group=this.displayItems[rowPosition];if(group?.kind==="group"&&this.selectionMode==="multiple"){const eligible=group.rows.filter(row=>this.rowIsSelectable(row)),sourceIndexes=this.sourceIndexMap(),allSelected=eligible.length>0&&eligible.every((row,index)=>arrayHasKey(this.selectedKeys,this.keyForRow(row,this.sourceIndexFor(row,sourceIndexes)??index)));this.setGroupSelected(group,!allSelected),event.preventDefault()}}}}setGroupSelected(group,selected){const eligible=group.rows.filter(row=>this.rowIsSelectable(row)),sourceIndexes=this.sourceIndexMap(),groupKeys=eligible.map((row,index)=>{const sourceIndex=this.sourceIndexFor(row,sourceIndexes);return this.keyForRow(row,sourceIndex??index)}),groupKeySet=new Set(groupKeys.map(typedKey));let next=this.selectedKeys.filter(key=>!groupKeySet.has(typedKey(key)));selected&&(next=[...next,...groupKeys]),this.selectedKeys=next,this.emitSelection()}userPinColumn(id,side){this.pinColumn(id,side),this.emit("lr-column-pin",Object.freeze({columnId:id,side}))}userToggleColumn(id,visible){this.toggleColumn(id,visible),this.emit("lr-column-visibility-change",Object.freeze({columnId:id,visible}))}renderToolbar(){return!this.withSearch&&!this.withColumnsMenu?nothing:html`
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{ColumnResizePointerSession,columnResizeAriaValues,columnResizeKeyboardWidth,columnResizePointerWidth}from"../../../internal/column-resize.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteDuration,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{aggregateValues,columnId,columnValue,filterRows,textFilterCorpus,pathValue,rowsAsDelimited,searchRows,searchHaystacks,sortRows}from"./data-grid-processing.js";import{styles}from"./data-grid.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dataGridColumnMenu,LYRA_DEFAULT_dataGridPinEnd,LYRA_DEFAULT_dataGridPinStart,LYRA_DEFAULT_dataGridRowLimit,LYRA_DEFAULT_dataGridRowsPerPage,LYRA_DEFAULT_dataGridTreeLimitReached,LYRA_DEFAULT_dataGridUnpin,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_paginationJumpToPage,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_tableFilterLabel}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_next,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_paginationFirstPage,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_paginationLastPage,LYRA_DEFAULT_previous,LYRA_DEFAULT_resizeValuePixels,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";export*from"./data-grid-types.js";const selectableConverter={fromAttribute(value){return value===null?"none":value===""||value==="multiple"?"multiple":value==="single"||value==="none"?value:"none"},toAttribute(value){return value==="none"?null:value===""||value==="multiple"?"":value}},displayKeys=new WeakMap;function displayItemKey(item){let key=displayKeys.get(item);return key||(key=item.kind==="group"?`group:${item.key.length}:${item.key}`:`row:${typeof item.key}:${String(item.key)}`,displayKeys.set(item,key)),key}const DATA_GRID_COLUMN_PROPERTIES=["id","field","label","align","width","minWidth","maxWidth","flex","formatter","cellTitle","value","sortable","sortFn","comparator","sortDescFirst","sortUndefined","searchable","filterable","filterType","filterFn","hidden","hideable","resizable","movable","pinnable","pinned","footer","aggregation","aggregatedFormatter"],DATA_GRID_COLUMN_CALLBACK_PROPERTIES=new Set(["formatter","cellTitle","value","comparator","filterFn","aggregatedFormatter"]),DATA_GRID_SORT_ALGORITHMS=new Set(["alphanumeric","alphanumericCaseSensitive","text","textCaseSensitive","datetime","basic"]),DATA_GRID_FILTER_TYPES=new Set(["text","equals","number-range","date-range","set","includes-any","includes-all"]),DATA_GRID_AGGREGATIONS=new Set(["sum","min","max","mean","median","count","unique","uniqueCount","extent"]);function isSafeColumnPropertyValue(property2,value){if(value===void 0)return!0;if(DATA_GRID_COLUMN_CALLBACK_PROPERTIES.has(property2))return typeof value=="function";switch(property2){case"id":case"field":case"label":return typeof value=="string";case"width":case"minWidth":case"maxWidth":case"flex":return typeof value=="number"&&Number.isFinite(value);case"sortable":case"sortDescFirst":case"searchable":case"filterable":case"hidden":case"hideable":case"resizable":case"movable":case"pinnable":return typeof value=="boolean";case"align":return value==="left"||value==="center"||value==="right"||value==="start"||value==="end";case"sortFn":return typeof value=="string"&&DATA_GRID_SORT_ALGORITHMS.has(value);case"sortUndefined":return value==="first"||value==="last"||value===1||value===-1;case"filterType":return typeof value=="string"&&DATA_GRID_FILTER_TYPES.has(value);case"pinned":return value===!1||value==="left"||value==="right"||value==="start"||value==="end";case"footer":return typeof value=="string"||typeof value=="function";default:return typeof value=="function"||typeof value=="string"&&DATA_GRID_AGGREGATIONS.has(value)}}function snapshotColumns(value,occurrenceId){const output=[],seen=new Set;let length=0;try{if(!Array.isArray(value))return Object.freeze(output);const descriptor=getOwnDataDescriptor(value,"length"),sourceLength=descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;typeof sourceLength=="number"&&Number.isSafeInteger(sourceLength)&&sourceLength>=0&&(length=Math.min(sourceLength,MAX_DATA_GRID_COLUMN_ENTRIES))}catch{return Object.freeze(output)}for(let index=0;index<length;index+=1){const candidate=getOwnDataDescriptor(value,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const column=candidate.value;try{if(column===null||typeof column!="object"||Array.isArray(column))continue;const descriptors=new Map;for(const property2 of DATA_GRID_COLUMN_PROPERTIES)descriptors.set(property2,getOwnDataDescriptor(column,property2));const idDescriptor=descriptors.get("id")??MISSING_OWN_DATA_DESCRIPTOR,fieldDescriptor=descriptors.get("field")??MISSING_OWN_DATA_DESCRIPTOR;if(idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const hasId=idDescriptor!==MISSING_OWN_DATA_DESCRIPTOR,authoredId=hasId?idDescriptor.value:void 0,hasSafeId=typeof authoredId=="string"&&authoredId.trim()!=="";if(hasId&&authoredId!==void 0&&!hasSafeId)continue;const hasField=fieldDescriptor!==MISSING_OWN_DATA_DESCRIPTOR,authoredField=fieldDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!hasField?void 0:fieldDescriptor.value,hasSafeField=typeof authoredField=="string"&&authoredField.trim()!=="";if(!hasSafeId&&(fieldDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||hasField&&authoredField!==void 0&&!hasSafeField))continue;const identity=hasSafeId?authoredId:hasSafeField?authoredField:occurrenceId(column);if(seen.has(identity))continue;seen.add(identity);const snapshot=Object.create(null);for(const property2 of DATA_GRID_COLUMN_PROPERTIES){const descriptor=descriptors.get(property2);descriptor===void 0||descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||property2==="field"&&!hasSafeField||isSafeColumnPropertyValue(property2,descriptor.value)&&(snapshot[property2]=descriptor.value)}authoredId===void 0&&authoredField===void 0&&(snapshot.id=identity),output.push(Object.freeze(snapshot))}catch{}}return Object.freeze(output)}const INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"], [role="option"], [role="radio"], [role="separator"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"], [role="textbox"]',VIRTUALIZATION_THRESHOLD=80,VIRTUAL_OVERSCAN=5,DATA_GRID_TREE_NODE_LIMIT=1e4,DATA_GRID_TREE_DEPTH_LIMIT=64,MAX_DATA_GRID_COLUMN_ENTRIES=1e4,DATA_GRID_DRAG_TYPE="application/x-lyra-data-grid-column",REBIND_NO_SNAPSHOT=Symbol("no snapshot");function frozenArray(values){return Object.freeze([...values])}function sameFilterState(left,right){return left.length!==right.length?!1:left.every((filter,index)=>{const other=right[index];if(!other||filter.id!==other.id)return!1;const value=filter.value,otherValue=other.value;return Array.isArray(value)||Array.isArray(otherValue)?!Array.isArray(value)||!Array.isArray(otherValue)?!1:value.length===otherValue.length&&value.every((entry,position)=>Object.is(entry,otherValue[position])):Object.is(value,otherValue)})}function sameSortState(left,right){return left.length===right.length&&left.every((entry,index)=>{const other=right[index];return other!==void 0&&entry.id===other.id&&entry.desc===other.desc})}function serializableFilterValue(value){try{const serialized=JSON.stringify({value},(_key,nested)=>typeof nested=="bigint"?nested.toString():typeof nested=="number"&&!Number.isFinite(nested)?null:nested!==null&&typeof nested=="object"&&Object.prototype.toString.call(nested)==="[object Set]"?[...nested]:nested);if(!serialized)return null;const snapshot=JSON.parse(serialized).value??null,stack=[snapshot],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(!(current===null||typeof current!="object"||visited.has(current))){visited.add(current);for(const nested of Object.values(current))stack.push(nested);Object.freeze(current)}}return snapshot}catch{return null}}function isKey(value){return typeof value=="string"&&value.trim()!==""||typeof value=="number"&&Number.isFinite(value)}function snapshotKeys(value){if(!(Array.isArray(value)||value!==null&&typeof value=="object"&&typeof value[Symbol.iterator]=="function"))return Object.freeze([]);const output=[],seen=new Set;try{for(const key of value)!isKey(key)||seen.has(key)||(seen.add(key),output.push(key))}catch{}return frozenArray(output)}function keysEqual(left,right){return typeof left==typeof right&&left===right}function typedKey(key){return`${typeof key}:${String(key)}`}const frozenKeyIndexes=new WeakMap;function arrayHasKey(keys,key){let index=frozenKeyIndexes.get(keys);if(!index){if(!Object.isFrozen(keys))return keys.some(candidate=>keysEqual(candidate,key));index=new Set(keys.map(typedKey)),frozenKeyIndexes.set(keys,index)}return index.has(typedKey(key))}function isElementValue(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.closest=="function"}function valueControl(value){return!isElementValue(value)||typeof value.value!="string"?null:value}function checkableControl(value){return!isElementValue(value)||typeof value.checked!="boolean"?null:value}function dateText(value){try{const timestamp=Date.prototype.getTime.call(value);return Number.isFinite(timestamp)?Date.prototype.toISOString.call(value):""}catch{return}}function humanizeIdentifier(value,locale){const intlLocale=resolveIntlLocale(locale);return value.replaceAll(/[._-]+/gu," ").replaceAll(/([a-z\d])([A-Z])/gu,"$1 $2").replace(/^./u,first=>first.toLocaleUpperCase(intlLocale))}function safeText(value){if(value==null)return"";if(typeof value=="object"){const serializedDate=dateText(value);if(serializedDate!==void 0)return serializedDate}if(Array.isArray(value))return value.map(safeText).join(", ");if(typeof value=="object")try{return JSON.stringify(value,(_key,nested)=>typeof nested=="bigint"?nested.toString():nested)??""}catch{return""}return String(value)}function normalizePinSide(side){return side==="start"?"left":side==="end"?"right":side}function normalizedGroupBy(value){return typeof value!="string"?(value??[]).map(entry=>entry.trim()).filter(Boolean).slice(0,DATA_GRID_TREE_DEPTH_LIMIT):value.split(/[\s,]+/u).map(entry=>entry.trim()).filter(Boolean).slice(0,DATA_GRID_TREE_DEPTH_LIMIT)}class LyraDataGrid extends LyraElement{constructor(){super(...arguments),this.appearance="outlined",this.childRows=null,this.assignedSources=new CollectionSourceTracker,this._columnOrder=Object.freeze([]),this.columnOrderAssignment=0,this.columnOccurrenceIds=new WeakMap,this.nextColumnOccurrenceId=1,this.rowOccurrenceIds=new WeakMap,this.nextRowOccurrenceId=1,this._columns=Object.freeze([]),this.columnsAssignment=0,this.maxRows=1e4,this.dataAdmissionTruncated=!1,this.dataAdmissionLimit=1e4,this._data=Object.freeze([]),this.dataAssignment=0,this.dataSource=null,this._expandedRowKeys=Object.freeze([]),this.expandedRowKeysAssignment=0,this.filterDebounce=250,this.filterFromLeafRows=!1,this._filters=Object.freeze([]),this.filterAssignment=0,this._groupBy=null,this.groupByAssignment=0,this.label=null,this.loading=!1,this.error=!1,this.errorDescription="",this.maxMultiSort=0,this.page=0,this.pageSize=20,this._pageSizeOptions=Object.freeze([10,20,50,100]),this.pageSizeOptionsAssignment=0,this.paginate=!1,this.pinnable=!1,this.reorderable=!1,this.resizable=!1,this.rowClass=null,this.rowDetail=null,this.rowKey=null,this.searchFn=null,this.searchTerm="",this.selectable="none",this.selectableRows=null,this._selectedRowKeys=Object.freeze([]),this.selectionAssignment=0,this.server=!1,this.size="m",this._sort=Object.freeze([]),this.sortAssignment=0,this.sortDescFirst=!1,this.striped=!1,this.total=-1,this.withColumnMenu=!1,this.withColumnsMenu=!1,this.withoutSortRemoval=!1,this.withSearch=!1,this.columnWidths=new Map,this.columnVisibility=new Map,this.columnPinning=new Map,this.activeFilterColumn=null,this.columnsMenuOpen=!1,this.activeColumnMenu=null,this.liveText="",this.bodyScrollTop=0,this.bodyScrollInlineOffset=0,this.viewportHeight=0,this.focusedRow=-1,this.focusedColumn=0,this.dragGhost="",this.requestGeneration=0,this.requestDebounce=new DebounceController(0,owner=>{this.loadServerData(owner)},()=>this.ownerDocument.defaultView),this.ownsLoadingState=!1,this.resizePointer=new ColumnResizePointerSession(event=>this.onResizeMove(event),event=>this.onResizeEnd(event),event=>this.onResizeCancel(event)),this.columnDragSequence=0,this.managedOverlayOwner=null,this.lastSelectedIndex=-1,this.isMounting=!0,this.pipelineEpoch=0,this.contentRefreshPending=!1,this.pipelineMemo=new Map,this.measuredItemHeights=new Map,this.measuredOffsetTree=[0],this.measuredOffsetHeights=[],this.measuredItemOffsetSignature="",this.measuredItemOffsetEstimate=0,this.measuredItemOffsetsDirty=!0,this.measurementLocale="",this.measurementDisplaySignature="",this.measurementFontSignature="",this.measurementFontHasRendered=!1,this.bodyScrollbarInlineEndGutter=0,this.observedMeasurementElements=new Map,this.observedMeasurementBlockSizes=new Map,this.measurementUpdateQueued=!1,this.measurementScrollSyncQueued=!1,this.bodyScrollStateSyncQueued=!1,this.restoreCellFocus=!1,this.onClearSearch=()=>{this.searchTerm!==""&&(this.applySearchTermChange(""),this.emit("lr-search-change",Object.freeze({searchTerm:""})),this.renderRoot.querySelector('[part="search"]')?.focus())},this.onSearchInput=event=>{const before=this.searchTerm;this.applySearchTermChange(event),this.searchTerm!==before&&this.emit("lr-search-change",Object.freeze({searchTerm:this.searchTerm}))},this.signatureValue="",this.geometryCycle=!1,this.relayEditorFocus=event=>{relayNativeEvent(this,event)},this.relayEditorBlur=event=>{relayNativeEvent(this,event)},this.onErrorRetry=()=>{this.error=!1}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copyFailed:LYRA_DEFAULT_copyFailed,dataGridColumnMenu:LYRA_DEFAULT_dataGridColumnMenu,dataGridPinEnd:LYRA_DEFAULT_dataGridPinEnd,dataGridPinStart:LYRA_DEFAULT_dataGridPinStart,dataGridRowLimit:LYRA_DEFAULT_dataGridRowLimit,dataGridRowsPerPage:LYRA_DEFAULT_dataGridRowsPerPage,dataGridTreeLimitReached:LYRA_DEFAULT_dataGridTreeLimitReached,dataGridUnpin:LYRA_DEFAULT_dataGridUnpin,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,next:LYRA_DEFAULT_next,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,paginationFirstPage:LYRA_DEFAULT_paginationFirstPage,paginationJumpToPage:LYRA_DEFAULT_paginationJumpToPage,paginationLabel:LYRA_DEFAULT_paginationLabel,paginationLastPage:LYRA_DEFAULT_paginationLastPage,previous:LYRA_DEFAULT_previous,resizeColumn:LYRA_DEFAULT_resizeColumn,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showAllColumns:LYRA_DEFAULT_showAllColumns,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-request","request","lr-column-move","lr-data-error"])}static{this.identityEventDetailProperties=Object.freeze({"lr-request":Object.freeze(["signal"]),request:Object.freeze(["signal"]),"lr-data-error":Object.freeze(["error","request"])})}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}isRebind(name,value,current){return this.assignedSources.isRebind(name,value,current)}get columnOrder(){return this._columnOrder}set columnOrder(value){const assignment=++this.columnOrderAssignment;if(this.isRebind("columnOrder",value,this._columnOrder))return;const previous=this._columnOrder,seen=new Set,next=frozenArray(Array.isArray(value)?value.filter(id=>typeof id!="string"||id.trim()===""||seen.has(id)?!1:(seen.add(id),!0)):[]);assignment===this.columnOrderAssignment&&(this._columnOrder=next,this.requestUpdate("columnOrder",previous))}get columns(){return this._columns}set columns(value){const assignment=++this.columnsAssignment;if(this.isRebind("columns",value,this._columns))return;const previous=this._columns,next=snapshotColumns(value,column=>{const current=this.columnOccurrenceIds.get(column);if(current)return current;const identity=`column-occurrence-${this.nextColumnOccurrenceId}`;return this.nextColumnOccurrenceId+=1,this.columnOccurrenceIds.set(column,identity),identity});assignment===this.columnsAssignment&&(this._columns=next,this.requestUpdate("columns",previous))}get rowLimit(){return Math.max(1,finiteCount(this.maxRows,DATA_GRID_TREE_NODE_LIMIT,1e5))}get data(){return this._data}set data(value){const assignment=++this.dataAssignment,limit=this.rowLimit;if(this.isRebind("data",value,this._data)&&this.dataAdmissionLimit===limit)return;const previous=this._data,admitted=[];let length=0;try{if(Array.isArray(value)){const descriptor=getOwnDataDescriptor(value,"length");descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=descriptor.value);const end=Math.min(length,limit);for(let index=0;index<end;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const row=entry.value;row!==null&&(typeof row=="object"||typeof row=="function")&&admitted.push(row)}}}catch{}assignment===this.dataAssignment&&(this.dataAdmissionLimit=limit,this.dataAdmissionTruncated=length>limit,this._data=Object.freeze(admitted),this.requestUpdate("data",previous))}get expandedRowKeys(){return this._expandedRowKeys}set expandedRowKeys(value){const assignment=++this.expandedRowKeysAssignment;if(this.isRebind("expandedRowKeys",value,this._expandedRowKeys))return;const previous=this._expandedRowKeys,next=snapshotKeys(value);assignment===this.expandedRowKeysAssignment&&(this._expandedRowKeys=next,this.requestUpdate("expandedRowKeys",previous),this.requestUpdate("expandedKeys",previous))}get expandedKeys(){return this.expandedRowKeys}set expandedKeys(value){this.expandedRowKeys=value}get dataTruncated(){return this.sourceProjection().truncated}get filteredCount(){return this.processedClientRows.length}get filters(){return this._filters}set filters(value){const assignment=++this.filterAssignment,previous=this._filters,next=[];if(Array.isArray(value))for(const filter of value)try{if(!filter||typeof filter.id!="string")continue;const filterValue=filter.value instanceof Set||Array.isArray(filter.value)?frozenArray(filter.value):filter.value;next.push(Object.freeze({id:filter.id,value:filterValue}))}catch{}assignment!==this.filterAssignment||sameFilterState(previous,next)||(this._filters=Object.freeze(next),this.requestUpdate("filters",previous))}get groupBy(){return this._groupBy}set groupBy(value){const assignment=++this.groupByAssignment;if(this.isRebind("groupBy",value,this._groupBy))return;const previous=this._groupBy,next=typeof value=="string"?value:Array.isArray(value)?frozenArray(value.filter(item=>typeof item=="string")):null;assignment===this.groupByAssignment&&(this._groupBy=next,this.requestUpdate("groupBy",previous))}get pageCount(){const size=this.safePageSize;if(size===0)return 0;if(!this.usesServerData&&normalizedGroupBy(this.groupBy).length>0){const groups=this.topLevelGroupBuckets(this.processedClientRows).length;return groups<=0?0:Math.ceil(groups/size)}const count=this.safeTotal>=0?this.safeTotal:this.filteredCount;return count<=0?0:Math.ceil(count/size)}get pageSizeOptions(){return this._pageSizeOptions}set pageSizeOptions(value){const assignment=++this.pageSizeOptionsAssignment;if(this.isRebind("pageSizeOptions",value,this._pageSizeOptions))return;const previous=this._pageSizeOptions,next=frozenArray(Array.isArray(value)?value:[]);assignment===this.pageSizeOptionsAssignment&&(this._pageSizeOptions=next,this.requestUpdate("pageSizeOptions",previous))}get selectionMode(){return this.selectable===""?"multiple":this.selectable}set selectionMode(value){this.selectable=value}get selectedRowKeys(){return this._selectedRowKeys}set selectedRowKeys(value){const assignment=++this.selectionAssignment;this.pendingInitialSelectedRows=void 0,this.assignSelectedRowKeys(value,assignment)}assignSelectedRowKeys(value,assignment){if(this.isRebind("selectedRowKeys",value,this._selectedRowKeys))return;const previous=this._selectedRowKeys,next=snapshotKeys(value);assignment===this.selectionAssignment&&(this._selectedRowKeys=next,this.requestUpdate("selectedRowKeys",previous),this.requestUpdate("selectedKeys",previous))}get selectedKeys(){return this.selectedRowKeys}set selectedKeys(value){this.selectedRowKeys=value}get selectedRows(){const rows=this.allSourceRows;return this.memoize("selectedRows",[rows,this.selectedKeys],()=>{const byKey=this.canonicalRowIndex(),positions=this.sourceIndexMap();return frozenArray(this.selectedKeys.flatMap(key=>{const row=byKey.get(key);return row===void 0?[]:[row]}).sort((left,right)=>positions.get(left)-positions.get(right)))})}set selectedRows(next){const assignment=++this.selectionAssignment;if(this.isRebind("selectedRows",next,REBIND_NO_SNAPSHOT)){this.pendingInitialSelectedRows&&(this.pendingInitialSelectedRows.assignment=assignment);return}const candidates=Array.isArray(next)?next:[];this.hasUpdated||(this.pendingInitialSelectedRows={candidates,assignment}),this.resolveSelectedRowsAssignment(candidates,assignment)}resolveSelectedRowsAssignment(candidates,assignment){const source=this.allSourceRows,sourceSet=new Set(source),sourceIndexes=this.sourceIndexMap(source),seen=new Set,rows=candidates.filter(row=>!sourceSet.has(row)||seen.has(row)?!1:(seen.add(row),!0)),keys=(this.selectionMode==="single"?rows.slice(0,1):rows).map(row=>this.keyForRow(row,this.sourceIndexFor(row,sourceIndexes)??0));assignment===this.selectionAssignment&&this.assignSelectedRowKeys(keys,assignment)}get sort(){return this._sort}set sort(value){const assignment=++this.sortAssignment,previous=this._sort,next=[];if(Array.isArray(value))for(const item of value)try{if(!item||typeof item.id!="string")continue;next.push(Object.freeze({id:item.id,desc:!!item.desc}))}catch{}assignment!==this.sortAssignment||sameSortState(previous,next)||(this._sort=Object.freeze(next),this.requestUpdate("sort",previous))}memoize(key,inputs,compute){const cached=this.pipelineMemo.get(key);if(cached&&cached.inputs.length===inputs.length&&cached.inputs.every((input,index)=>Object.is(input,inputs[index])))return cached.value;const value=compute();return this.pipelineMemo.set(key,{inputs,value}),value}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.syncMeasuredBodyWidth(),this.syncBodyScrollState(),this.syncRowMeasurementObserver(),this.correctMeasurementAnchor(),this.measureRenderedItems(),this.closeComposedColumnsMenu()),this.dataSource&&this.scheduleServerRequest(!1)}disconnectedCallback(){this.managedOverlay?.deactivate({restoreFocus:!1}),this.managedOverlay=void 0,this.managedOverlayOwner=null,this.requestGeneration+=1,this.requestController?.abort(),this.requestController=void 0,this.serverRequestInputs=void 0,this.ownsLoadingState&&(this.loading=!1),this.ownsLoadingState=!1,this.cancelRequestTimer(),this.resizeSession?.moved&&this.restoreResizeSession(this.resizeSession,!1),this.resizePointer.stop(),this.resizeSession=void 0,this.activeResizeColumn=void 0,this.activeFilterColumn=null,this.activeColumnMenu=null,this.columnsMenuOpen=!1,this.closeComposedColumnsMenu(),this.dragGhost="",this.columnDragSession=void 0,this.pendingVirtualScroll=void 0,this.expectedBodyScroll=void 0,this.resetRowMeasurementObserver(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.expectedBodyScroll=void 0,this.resetRowMeasurementObserver(),this.isConnected&&this.hasUpdated&&(this.syncMeasuredBodyWidth(),this.syncBodyScrollState(),this.syncRowMeasurementObserver(),this.correctMeasurementAnchor(),this.measureRenderedItems())}requestUpdate(...args){args[0]===void 0&&(this.contentRefreshPending=!0),super.requestUpdate(...args)}willUpdate(changed){if(super.willUpdate(changed),changed.has("columns")){const activeFooters=new Set(this.columns.filter(column=>typeof column.footer=="function").map((column,index)=>`footer:${columnId(column,index)}`));for(const key of this.pipelineMemo.keys())key.startsWith("footer:")&&!activeFooters.has(key)&&this.pipelineMemo.delete(key)}this.resetGeometryCycle(),this.geometryCycle=!0;const contentRefresh=this.contentRefreshPending;this.contentRefreshPending=!1,contentRefresh&&(this.pipelineEpoch+=1),this.hasUpdated&&changed.has("loading")&&this.loading&&this.announce(this.localize("loading"));const sourceReplaced=changed.has("dataSource")&&changed.get("dataSource")!==void 0,serverDisabled=changed.has("server")&&!this.usesServerData;if((sourceReplaced||serverDisabled)&&!this.matchesCurrentServerRequest()&&(this.requestController||this.requestDebounce.pending)&&(this.requestGeneration+=1,this.requestController?.abort(),this.requestController=void 0,this.serverRequestInputs=void 0,this.cancelRequestTimer(),this.ownsLoadingState&&(this.loading=!1),this.ownsLoadingState=!1),this.resizeSession&&(changed.has("resizable")||changed.has("columns"))&&!this.columnCanResize(this.resizeSession.columnId)){const session=this.resizeSession;this.resizePointer.stop(),this.resizeSession=void 0,this.activeResizeColumn=void 0,session.moved&&this.restoreResizeSession(session,!0)}if(this.columnDragSession&&(changed.has("reorderable")||changed.has("columns"))&&!this.columnCanMove(this.columnDragSession.sourceId)&&(this.columnDragSession=void 0,this.dragGhost=""),changed.has("columns")&&this.handleColumnsChange(),this.reconcileRowMeasurementCache(changed,contentRefresh),!this.hasUpdated&&this.pendingInitialSelectedRows!==void 0){const pending=this.pendingInitialSelectedRows;this.pendingInitialSelectedRows=void 0,pending.assignment===this.selectionAssignment&&this.resolveSelectedRowsAssignment(pending.candidates,pending.assignment)}if(!this.usesServerData&&!this.sourceProjection().truncated&&(changed.has("data")||changed.has("rowKey")||changed.has("childRows")||changed.has("server")||changed.has("dataSource"))){const validKeys=this.allSourceRows.map((row,index)=>this.keyForRow(row,index)),validKeySet=new Set(validKeys),selectedKeys=this.selectedKeys.filter(key=>validKeySet.has(key));(selectedKeys.length!==this.selectedKeys.length||selectedKeys.some((key,index)=>!keysEqual(key,this.selectedKeys[index])))&&(this.selectedKeys=selectedKeys,this.hasUpdated&&this.emitSelection()),this.lastSelectedIndex=-1}if(this.paginate&&(changed.has("data")||changed.has("filters")||changed.has("searchTerm")||changed.has("groupBy")||changed.has("pageSize")||changed.has("total")||changed.has("server")||changed.has("dataSource"))){const lastPage=Math.max(0,this.pageCount-1);this.page=finiteInteger(this.page,0,0,lastPage)}this.followRovingCell(),(changed.has("data")||changed.has("columns")||changed.has("filters")||changed.has("searchTerm")||changed.has("sort")||changed.has("expandedKeys")||changed.has("groupBy")||changed.has("page")||changed.has("pageSize")||changed.has("paginate")||changed.has("childRows"))&&(this.focusedRow=finiteInteger(this.focusedRow,-1,-1,Math.max(-1,this.displayItems.length-1)),this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1)))}followRovingCell(){const previousItems=this.renderedDisplayItems,items=this.displayItems;if(previousItems&&previousItems!==items&&this.focusedRow>=0){const previous=previousItems[this.focusedRow],current=items[this.focusedRow],key=previous?displayItemKey(previous):void 0;if(key!==void 0&&(!current||displayItemKey(current)!==key)){const index=this.displayIndexes.get(key)??-1;index>=0&&(this.focusedRow=index)}const active=shadowFocusTarget(this);this.restoreCellFocus=active?.getAttribute("role")==="gridcell"&&active.hasAttribute("data-focus-cell")}const previousColumns=this.renderedColumns,columns=this.visibleColumns;if(previousColumns&&previousColumns!==columns){const id=previousColumns[this.focusedColumn]?.id;if(id!==void 0&&columns[this.focusedColumn]?.id!==id){const index=columns.findIndex(entry=>entry.id===id);index>=0&&(this.focusedColumn=index)}}}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-data-grid-missing-accessible-name","<lr-data-grid> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){if(super.updated(changed),this.renderedDisplayItems=this.displayItems,this.renderedColumns=this.visibleColumns,this.restoreCellFocus&&(this.restoreCellFocus=!1,!shadowFocusTarget(this)&&this.focusedRow>=0&&this.focusCell(this.focusedRow,this.focusedColumn)),changed.has("dataSource")&&this.dataSource&&this.scheduleServerRequest(!1),(changed.has("sort")||changed.has("filters")||changed.has("searchTerm")||changed.has("page")||changed.has("pageSize")||changed.has("server"))&&(this.server||this.dataSource)){const delayed=changed.has("filters")||changed.has("searchTerm");this.scheduleServerRequest(delayed)}this.syncManagedOverlay(),this.syncMeasuredBodyWidth(),this.syncResolvedColumnWidths(),this.syncResizeHandleValues(),this.queueBodyScrollStateSync(),this.syncRowMeasurementObserver(),this.correctMeasurementAnchor(),this.measurementFontHasRendered||(this.cycleFontSignature=void 0,this.measurementFontHasRendered=!0),this.measureRenderedItems(),this.alignPendingVirtualScroll(),this.isMounting=!1,this.geometryCycle=!1}get currentManagedOverlayOwner(){return this.activeFilterColumn!==null?`filter:${this.activeFilterColumn}`:this.activeColumnMenu!==null?`column:${this.activeColumnMenu}`:null}managedOverlayElements(owner){const separator=owner.indexOf(":"),kind=owner.slice(0,separator),columnIdValue=owner.slice(separator+1),header=[...this.renderRoot.querySelectorAll('[part~="header-cell"][data-column-id]')].find(candidate=>candidate.getAttribute("data-column-id")===columnIdValue);return header?kind==="filter"?{panel:header.querySelector('[part="filter-panel"]'),trigger:header.querySelector('[part="filter-button"]')}:{panel:header.querySelector('[part="column-menu"] [role="group"]'),trigger:header.querySelector('[part="column-menu-button"]')}:{panel:null,trigger:null}}dismissManagedOverlay(owner){owner.startsWith("filter:")&&this.activeFilterColumn===owner.slice(7)?this.activeFilterColumn=null:owner.startsWith("column:")&&this.activeColumnMenu===owner.slice(7)&&(this.activeColumnMenu=null)}syncManagedOverlay(){const owner=this.currentManagedOverlayOwner;if(owner!==null&&owner===this.managedOverlayOwner&&this.managedOverlay?.isActive()&&this.managedOverlayElements(owner).panel||(this.managedOverlay?.deactivate({restoreFocus:owner===null}),this.managedOverlay=void 0,this.managedOverlayOwner=null,owner===null||!this.isConnected))return;const{panel}=this.managedOverlayElements(owner);panel&&(this.managedOverlayOwner=owner,this.managedOverlay=activateNonmodalOverlay({host:this,panel:()=>this.managedOverlayElements(owner).panel,onEscape:()=>this.dismissManagedOverlay(owner),restoreFocusTo:()=>this.managedOverlayElements(owner).trigger}))}closeComposedColumnsMenu(){const menu=this.renderRoot?.querySelector('[part="columns-menu"]');menu?.open&&(menu.open=!1)}openColumnsPanel(){this.columnsMenuOpen=!0,this.activeFilterColumn=null,this.activeColumnMenu=null}toggleFilterPanel(id){const next=this.activeFilterColumn===id?null:id;this.activeFilterColumn=next,next!==null&&(this.columnsMenuOpen=!1,this.activeColumnMenu=null)}toggleColumnPanel(id){const next=this.activeColumnMenu===id?null:id;this.activeColumnMenu=next,next!==null&&(this.columnsMenuOpen=!1,this.activeFilterColumn=null)}announce(text){this.sink?.announce(text),this.liveText=text}get usesServerData(){return this.server||this.dataSource!==null}get safePage(){return finiteInteger(this.page,0,0,Math.max(0,this.pageCount-1))}get safePageSize(){return finiteCount(this.pageSize)}get safeTotal(){return this.total===-1?-1:finiteCount(this.total)}sourceProjection(){return this.memoize("source",[this.pipelineEpoch,this.data,this.childRows,this.rowKey,this.rowLimit],()=>this.computeSourceProjection())}computeSourceProjection(){const result=[],visited=new Set,seenRowKeys=new Set,stack=[];for(let index=this.data.length-1;index>=0;index-=1)stack.push({row:this.data[index],depth:0});let truncated=this.dataAdmissionTruncated;for(;stack.length>0&&result.length<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(!trackIdentity||trackIdentity&&visited.has(current.row))continue;trackIdentity&&visited.add(current.row);const rowKey=this.rowIdentity(current.row);if(rowKey===void 0||seenRowKeys.has(rowKey))continue;seenRowKeys.add(rowKey),result.push(current.row);const children=this.childrenFor(current.row);if(children.length!==0){if(current.depth>=DATA_GRID_TREE_DEPTH_LIMIT){truncated=!0;continue}for(let index=children.length-1;index>=0;index-=1)stack.push({row:children[index],depth:current.depth+1})}}return stack.length>0&&(truncated=!0),{rows:Object.freeze(result),truncated}}get allSourceRows(){return this.sourceProjection().rows}get canonicalRootRows(){const source=this.allSourceRows;return this.memoize("roots",[source,this.data],()=>{const canonical=new Set(source);return this.data.filter(row=>canonical.delete(row))})}sourceIndexMap(rows=this.allSourceRows){const build=()=>{const indexes=new Map;return rows.forEach((row,index)=>{indexes.has(row)||indexes.set(row,index)}),indexes};return this.memoize("sourceIndex",[rows],build)}sourceIndexFor(row,indexes){return indexes.get(row)}canonicalRowIndex(rows=this.allSourceRows){const build=()=>{const byIdentity=new Map;for(const row of rows){const identity=this.rowIdentity(row);identity!==void 0&&!byIdentity.has(identity)&&byIdentity.set(identity,row)}return byIdentity};return this.memoize("canonicalIndex",[rows],build)}canonicalMembers(rows,byIdentity=this.canonicalRowIndex()){const output=[],seen=new Set;for(const candidate of rows){const identity=this.rowIdentity(candidate);if(identity===void 0||seen.has(identity))continue;const canonical=byIdentity.get(identity);canonical&&(seen.add(identity),output.push(canonical))}return output}get orderedColumns(){return this.memoize("ordered",[this.columns,this.columnOrder],()=>this.computeOrderedColumns())}computeOrderedColumns(){const entries=this.columns.map((column,naturalIndex)=>({column,id:columnId(column,naturalIndex),naturalIndex}));if(this.columnOrder.length===0)return entries;const rank=new Map(this.columnOrder.map((id,index)=>[id,index]));return entries.sort((left,right)=>{const leftRank=rank.get(left.id),rightRank=rank.get(right.id);return leftRank===void 0&&rightRank===void 0?left.naturalIndex-right.naturalIndex:leftRank===void 0?1:rightRank===void 0?-1:leftRank-rightRank})}get columnIndex(){const entries=this.orderedColumns;return this.memoize("columnIndex",[entries],()=>new Map(entries.map(entry=>[entry.id,entry])))}get visibleColumns(){const ordered=this.orderedColumns;return this.memoize("visible",[ordered,this.columnVisibility,this.columnPinning],()=>ordered.filter(({column,id})=>this.columnVisibility.get(id)??column.hidden!==!0).sort((left,right)=>{const leftPin=normalizePinSide(this.getColumnPin(left.id)),rightPin=normalizePinSide(this.getColumnPin(right.id));return leftPin===rightPin?0:leftPin==="left"||rightPin==="right"?-1:1}))}get processedClientRows(){const rows=this.canonicalRootRows;return this.memoize("processed",[rows,this.pipelineEpoch,this.usesServerData,this.childRows,this.filterFromLeafRows,this.columns,this.filters,this.searchTerm,this.searchFn,this.sort,this.effectiveLocale],()=>this.computeProcessedClientRows(rows))}get filterText(){return this.memoize("filterText",[this.allSourceRows,this.columns,this.effectiveLocale],()=>textFilterCorpus(this.effectiveLocale))}computeProcessedClientRows(rows){if(this.usesServerData)return[...rows];const sorted=this.memoize("sorted",[rows,this.pipelineEpoch,this.columns,this.sort,this.effectiveLocale],()=>sortRows(rows,this.columns,this.sort,this.effectiveLocale));if(this.childRows)return sorted.filter(row=>this.rowMatches(row)||this.filterFromLeafRows&&this.hasMatchingDescendant(row));const filtered=filterRows(sorted,this.columns,this.filters,this.effectiveLocale,this.filterText),haystacks=!this.searchFn&&this.searchTerm.trim()?this.memoize("searchHaystacks",[rows,this.pipelineEpoch,this.columns,this.effectiveLocale],()=>searchHaystacks(rows,this.columns,this.effectiveLocale)):void 0;return searchRows(filtered,this.columns,this.searchTerm,this.effectiveLocale,this.searchFn,haystacks)}childrenFor(row){const cache=this.memoize("children",[this.data,this.childRows,this.rowLimit,this.pipelineEpoch],()=>new Map),existing=cache.get(row);if(existing)return existing;const children=this.readChildren(row);return cache.set(row,children),children}readChildren(row){try{const children=typeof this.childRows=="function"?this.childRows(row):this.childRows?pathValue(row,this.childRows):void 0;return Array.isArray(children)?children.slice(0,this.rowLimit):[]}catch{return[]}}rowIdentity(row){if(!((typeof row!="object"||row===null)&&typeof row!="function"))try{if(this.rowKey){const candidate=typeof this.rowKey=="function"?this.rowKey(row):pathValue(row,this.rowKey);return isKey(candidate)?candidate:void 0}const object=row,current=this.rowOccurrenceIds.get(object);if(current)return current;const identity=`row-occurrence-${this.nextRowOccurrenceId}`;return this.nextRowOccurrenceId+=1,this.rowOccurrenceIds.set(object,identity),identity}catch{return}}keyForRow(row,_index){return this.rowIdentity(row)}renderedColumnElements(columnId2,role){const prefix=role?`[role="${role}"]`:"",ownerCss=this.ownerDocument.defaultView?.CSS,escape=ownerCss?.escape;if(typeof escape=="function")try{const matches=[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id="${escape.call(ownerCss,columnId2)}"]`)];if(matches.length>0)return matches}catch{}return[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id]`)].filter(element=>element.getAttribute("data-column-id")===columnId2)}computedToken(name,privateDefault){if(!this.isConnected)return"";const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.getComputedStyle!="function")return"";try{const style=owner.getComputedStyle(this);return style.getPropertyValue(name).trim()||(privateDefault?style.getPropertyValue(privateDefault).trim():"")}catch{return""}}autoSizeColumn(columnId2){const cells=this.renderedColumnElements(columnId2);if(cells.length===0)return;let width=0;for(const cell of cells)width=Math.max(width,cell.scrollWidth);const entry=this.columnIndex.get(columnId2);if(!entry)return;const{minimum,maximum}=this.columnBounds(entry.column);this.setColumnWidth(columnId2,finiteRange(width,minimum,minimum,maximum),!1)}autoSizeColumns(){for(const{id}of this.visibleColumns)this.autoSizeColumn(id)}collapseAllRows(){this.expandedKeys=[]}collapseRow(key){this.expandedKeys=this.expandedKeys.filter(candidate=>!keysEqual(candidate,key))}copySelectedRows(options={}){const rowsToCopy=this.selectedRows.length>0?this.selectedRows:this.getProcessedRows(),format=options.format??"tsv",text=this.delimitedRows(rowsToCopy,{...options,delimiter:options.delimiter??(format==="csv"?",":" ")});return this.copyAndReport(text),rowsToCopy.length}expandAllRows(){const keys=[];this.allSourceRows.forEach((row,index)=>{(this.childrenFor(row).length>0||this.rowDetail)&&keys.push(this.keyForRow(row,index))});for(const group of this.groupItems(this.processedClientRows))keys.push(group.key);this.expandedKeys=keys}expandRow(key){arrayHasKey(this.expandedKeys,key)||(this.expandedKeys=[...this.expandedKeys,key])}exportDataAsCsv(options={}){const text=this.getDataAsCsv(options),ownerDocument=this.ownerDocument,owner=ownerDocument.defaultView;if(!owner||typeof owner.URL.createObjectURL!="function")return;const url=owner.URL.createObjectURL(new owner.Blob([text],{type:"text/csv;charset=utf-8"}));try{const anchor=ownerDocument.createElement("a");anchor.href=url,anchor.download=options.fileName||"data.csv",anchor.hidden=!0,ownerDocument.body?.append(anchor),anchor.click(),anchor.remove()}finally{owner.URL.revokeObjectURL(url)}}focus(options={}){const selector=this.focusedRow<0?`[role="columnheader"][data-column-position="${this.focusedColumn}"]`:`[role="gridcell"][data-row-position="${this.focusedRow}"][data-column-position="${this.focusedColumn}"]`;this.renderRoot?.querySelector(selector)?.focus(options)}getColumnFacets(columnId2){const uniqueValues=new Map;if(this.usesServerData)return Object.freeze({uniqueValues});const entry=this.columnIndex.get(columnId2);if(!entry)return Object.freeze({uniqueValues});const otherFilters=this.filters.filter(filter=>filter.id!==columnId2),rows=searchRows(filterRows(this.canonicalRootRows,this.columns,otherFilters,this.effectiveLocale),this.columns,this.searchTerm,this.effectiveLocale,this.searchFn);let minimum=Number.POSITIVE_INFINITY,maximum=Number.NEGATIVE_INFINITY;for(const row of rows){const value=columnValue(entry.column,row);uniqueValues.set(value,(uniqueValues.get(value)??0)+1);const number=typeof value=="number"?value:Number(value);Number.isFinite(number)&&(minimum=Math.min(minimum,number),maximum=Math.max(maximum,number))}return Number.isFinite(minimum)&&Number.isFinite(maximum)?Object.freeze({uniqueValues,minMax:Object.freeze([minimum,maximum])}):Object.freeze({uniqueValues})}getColumnPin(columnId2){return this.columnPinning.has(columnId2)?this.columnPinning.get(columnId2)??!1:this.columnIndex.get(columnId2)?.column.pinned??!1}getDataAsCsv(options={}){return this.delimitedRows(this.getProcessedRows(),options)}getProcessedRows(){const rows=this.processedClientRows;return this.memoize("publicProcessedRows",[rows],()=>frozenArray(rows))}getVisibleRows(){const rows=this.processedClientRows;return this.memoize("visibleRows",[rows,this.paginate,this.usesServerData,this.pageSize,this.page,this.total,this.groupBy,this.orderedColumns],()=>this.computeVisibleRows(rows))}computeVisibleRows(rows){if(!this.paginate||this.usesServerData)return frozenArray(rows);const size=this.safePageSize;if(size===0)return[];const start=this.safePage*size;return normalizedGroupBy(this.groupBy).length>0?frozenArray(this.topLevelGroupBuckets(rows).slice(start,start+size).flatMap(bucket=>bucket.rows)):frozenArray(rows.slice(start,start+size))}getState(){return Object.freeze({order:frozenArray(this.columnOrder),widths:Object.freeze(Object.fromEntries(this.columnWidths)),visibility:Object.freeze(Object.fromEntries(this.columnVisibility)),pinning:Object.freeze(Object.fromEntries(this.columnPinning)),sort:frozenArray(this.sort.map(item=>Object.freeze({...item}))),filters:frozenArray(this.filters.map(item=>Object.freeze({id:item.id,value:serializableFilterValue(item.value)}))),search:this.searchTerm,selectedRowKeys:frozenArray(this.selectedRowKeys),expandedRowKeys:frozenArray(this.expandedRowKeys),selectedKeys:frozenArray(this.selectedRowKeys),expandedKeys:frozenArray(this.expandedRowKeys),page:this.safePage,pageSize:this.safePageSize})}handleColumnsChange(){const valid=new Set(this.columns.map((column,index)=>columnId(column,index))),natural=[...valid],order=this.columnOrder.filter(id=>valid.has(id)),orderedIds=new Set(order);for(const id of natural)orderedIds.has(id)||order.push(id);this.columnOrder.length>0&&order.join("\0")!==this.columnOrder.join("\0")&&(this.columnOrder=order);const widths=[...this.columnWidths].filter(([id])=>valid.has(id)),visibility=[...this.columnVisibility].filter(([id])=>valid.has(id)),pinning=[...this.columnPinning].filter(([id])=>valid.has(id));widths.length!==this.columnWidths.size&&(this.columnWidths=new Map(widths)),visibility.length!==this.columnVisibility.size&&(this.columnVisibility=new Map(visibility)),pinning.length!==this.columnPinning.size&&(this.columnPinning=new Map(pinning))}handlePageChange(){this.applyPageChange(this.safePage)}applyPageChange(value){let requested;typeof value=="number"?requested=value:requested=Number(valueControl(value?.currentTarget)?.value??this.safePage);const last=Math.max(0,this.pageCount-1),next=finiteInteger(requested,this.safePage,0,last);this.page=next,this.emit("lr-page-change",Object.freeze({page:next,pageSize:this.safePageSize}))}handleSearchTermChange(){this.applySearchTermChange(this.searchTerm)}applySearchTermChange(value){const next=typeof value=="string"?value:valueControl(value?.currentTarget)?.value??this.searchTerm;this.searchTerm=next,this.page!==0&&(this.page=0)}pinColumn(columnId2,side){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnPinning);next.set(columnId2,side),this.columnPinning=next}async reload(){const owner=this.ownerDocument.defaultView;!this.isConnected||!owner||!this.usesServerData||(this.cancelRequestTimer(),await this.loadServerData(owner))}resetColumns(){this.columnOrder=[],this.columnWidths=new Map,this.columnVisibility=new Map,this.columnPinning=new Map}resetState(){this.resetColumns(),this.sort=[],this.filters=[],this.searchTerm="",this.expandedKeys=[]}scrollToIndex(index,options={}){this.pendingVirtualScroll=void 0,this.pendingMeasurementAnchor=void 0;const rows=this.getVisibleRows();if(rows.length===0)return;const requestedIndex=finiteInteger(index,0,0,rows.length-1),requestedRow=rows[requestedIndex],sourceIndexes=this.sourceIndexMap(),sourceIndex=this.sourceIndexFor(requestedRow,sourceIndexes),requestedKey=this.keyForRow(requestedRow,sourceIndex??requestedIndex),items=this.displayItems,target=this.displayIndexes.get(`row:${typeof requestedKey}:${String(requestedKey)}`)??-1;if(target<0)return;const body=this.bodyElement;if(!body)return;this.recordMeasurementRowHeight()&&this.invalidateRowMeasurements()&&this.queueMeasurementUpdate();const rendered=this.renderRoot?.querySelector(`[part~="row"][data-visible-index="${target}"]`),rowHeight=this.displayItemHeight(target,items),rowTop=this.displayItemOffset(target,items),currentTop=finiteRange(body.scrollTop,this.bodyScrollTop,0),viewportHeight=finiteRange(body.clientHeight,0,0),alignment=options.align??(rendered?"nearest":"start");let top=rowTop;if(alignment==="center")top-=(viewportHeight-rowHeight)/2;else if(alignment==="end")top-=viewportHeight-rowHeight;else if(alignment==="nearest"){const rowBottom=rowTop+rowHeight;rowTop>=currentTop&&rowBottom<=currentTop+viewportHeight?top=currentTop:rowTop<currentTop?top=rowTop:top=rowBottom-viewportHeight}const maximumTop=Math.max(0,this.displayItemOffset(items.length,items)-viewportHeight);if(top=finiteRange(top,0,0,maximumTop),rendered){const delta=this.renderedRowAlignmentDelta(rendered,body,alignment);if(top=finiteRange(currentTop+delta,currentTop,0,Math.max(0,body.scrollHeight-body.clientHeight)),body.scrollTo({top}),alignment==="start"){const correction=this.renderedStartPrecisionDelta(rendered,body);correction!==0&&(top=finiteRange(body.scrollTop+correction,body.scrollTop,0,Math.max(0,body.scrollHeight-body.clientHeight)),body.scrollTo({top}))}top=body.scrollTop,this.expectedBodyScroll=Object.freeze({body,top}),this.bodyScrollTop=top,this.lastMeasurementAnchor=this.measurementAnchorAtOffset(top,items);return}this.lastMeasurementAnchor=this.measurementAnchorAtOffset(top,items);const targetItem=items[target];targetItem&&(this.pendingVirtualScroll=Object.freeze({itemKey:displayItemKey(targetItem),align:alignment})),this.expectedBodyScroll=Object.freeze({body,top}),this.bodyScrollTop=top,body.scrollTo({top})}setState(state2){const known=new Set(this.columns.map((column,index)=>columnId(column,index)));state2.order&&(this.columnOrder=state2.order.filter(id=>known.has(id))),state2.widths&&(this.columnWidths=this.validColumnMap(state2.widths,known,width=>finiteRange(width,0,0))),state2.visibility&&(this.columnVisibility=this.validColumnMap(state2.visibility,known,Boolean)),state2.pinning&&(this.columnPinning=this.validColumnMap(state2.pinning,known,side=>side==="left"||side==="right"||side==="start"||side==="end"?side:!1)),state2.sort&&(this.sort=state2.sort.filter(item=>known.has(item.id)).map(item=>({id:item.id,desc:!!item.desc}))),state2.filters&&(this.filters=state2.filters.filter(item=>known.has(item.id)).map(item=>({...item}))),state2.search!==void 0&&(this.searchTerm=state2.search);const selectedRowKeys=state2.selectedRowKeys??state2.selectedKeys,expandedRowKeys=state2.expandedRowKeys??state2.expandedKeys;selectedRowKeys&&(this.selectedRowKeys=selectedRowKeys),expandedRowKeys&&(this.expandedRowKeys=expandedRowKeys),state2.page!==void 0&&(this.page=finiteCount(state2.page)),state2.pageSize!==void 0&&(this.pageSize=finiteCount(state2.pageSize))}sizeColumnsToFit(){const body=this.bodyElement;if(!body||this.visibleColumns.length===0)return;const selectionWidth=this.selectionEnabled?resolveCssTokenLength(this.computedToken("--lr-icon-button-size"),{host:this})??0:0,visible=this.visibleColumns,flexible=visible.filter(({column})=>finiteRange(column.flex??1,1,0)>0);if(flexible.length===0)return;const measuredWidths=new Map([...this.renderRoot.querySelectorAll('[role="columnheader"][data-column-id]')].map(header=>[header.dataset.columnId,resolveCssTokenLength(this.ownerDocument.defaultView?.getComputedStyle(header).width??"",{host:this})??0])),fixedWidth=visible.reduce((total,{column,id})=>{if(finiteRange(column.flex??1,1,0)>0)return total;const bounds=this.columnBounds(column),explicit=this.columnWidths.get(id)??column.width,fallback=explicit!==void 0&&explicit>0?this.estimatedColumnWidth(column,id):Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?bounds.maximum:bounds.minimum||this.estimatedColumnWidth(column,id);return total+finiteRange(measuredWidths.get(id)||fallback,fallback,0)},0),available=Math.max(0,body.clientWidth-selectionWidth-fixedWidth),flexValues=flexible.map(({column})=>finiteRange(column.flex??1,1,0)),flexScale=flexValues.reduce((largest,value)=>Math.max(largest,value),0),scaledFlex=flexValues.map(value=>flexScale>0?value/flexScale:value),totalFlex=scaledFlex.reduce((sum,value)=>sum+value,0)||flexible.length,next=new Map(this.columnWidths);for(const[index,{column,id}]of flexible.entries()){const share=available*((scaledFlex[index]??0)/totalFlex),{minimum,maximum}=this.columnBounds(column);next.set(id,finiteRange(share,minimum,minimum,maximum))}this.columnWidths=next}toggleColumn(columnId2,visible){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnVisibility);next.set(columnId2,visible),this.columnVisibility=next,this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1))}validColumnMap(record,known,convert){const result=new Map;for(const[id,value]of Object.entries(record))known.has(id)&&result.set(id,convert(value));return result}delimitedRows(rows,options){const active=this.visibleColumns.map(({column,id})=>({...column,id,value:row=>{const raw=columnValue(column,row),formatted=column.formatter?.(raw,row);return typeof formatted=="string"?formatted:raw},hidden:!1}));return rowsAsDelimited(rows,active,options)}async copyAndReport(text){const owner=this.isConnected?this.ownerDocument.defaultView:null,outcome=await this.writeClipboard(text,owner);if(!(!owner||!this.isConnected||this.ownerDocument.defaultView!==owner)){if(outcome.ok){this.isMounting||this.announce(this.localize("copied")),this.emit("lr-copy",outcome);return}this.isMounting||this.announce(this.localize("copyFailed")),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}}async writeClipboard(text,owner){const ownerDocument=this.ownerDocument,outcome=await writeClipboardText(owner,text);if(outcome.ok||!owner||ownerDocument.defaultView!==owner||!ownerDocument.body)return outcome;const textarea=ownerDocument.createElement("textarea");textarea.value=text,textarea.style.position="fixed",textarea.style.opacity="0",ownerDocument.body.append(textarea);try{if(textarea.select(),ownerDocument.execCommand?.("copy"))return Object.freeze({ok:!0,text})}finally{textarea.remove()}return outcome}setColumnWidth(columnIdValue,width,emit,finished=!0){const entry=this.columnIndex.get(columnIdValue);if(!entry)return;const{minimum,maximum}=this.columnBounds(entry.column),safeWidth=finiteRange(width,minimum,minimum,maximum),next=new Map(this.columnWidths);next.set(columnIdValue,safeWidth),this.columnWidths=next,emit&&this.emit("lr-column-resize",Object.freeze({columnId:columnIdValue,columnKey:columnIdValue,width:safeWidth,finished}))}cancelRequestTimer(){this.requestDebounce.cancel()}currentServerRequestInputs(){return[this.ownerDocument,this.dataSource,this.server,this.sort,this.filters,this.searchTerm,this.safePage,this.safePageSize]}matchesCurrentServerRequest(){const current=this.currentServerRequestInputs();return this.serverRequestInputs?.every((value,index)=>Object.is(value,current[index]))??!1}scheduleServerRequest(delayed){const owner=this.ownerDocument.defaultView;!this.isConnected||!owner||!this.usesServerData||this.matchesCurrentServerRequest()||(this.requestGeneration++,this.requestController?.abort(),this.requestController=void 0,this.serverRequestInputs=void 0,this.requestDebounce.delayMs=delayed?finiteDuration(this.filterDebounce,250):0,this.requestDebounce.push(owner))}async loadServerData(owner){if(!this.isConnected||this.ownerDocument.defaultView!==owner||!this.usesServerData)return;this.requestController?.abort(),this.serverRequestInputs=this.currentServerRequestInputs();const AbortControllerCtor=owner.AbortController;this.requestController=typeof AbortControllerCtor=="function"?new AbortControllerCtor:void 0;const generation=++this.requestGeneration,request=Object.freeze({sort:frozenArray(this.sort.map(item=>Object.freeze({...item}))),filters:frozenArray(this.filters.map(item=>Object.freeze({id:item.id,value:serializableFilterValue(item.value)}))),search:this.searchTerm,page:this.safePage,pageSize:this.safePageSize,signal:this.requestController?.signal}),current=()=>generation===this.requestGeneration&&!request.signal?.aborted&&this.isConnected&&this.ownerDocument.defaultView===owner&&this.matchesCurrentServerRequest(),requestDetail=()=>Object.freeze({...request,sort:frozenArray(request.sort.map(item=>Object.freeze({...item}))),filters:frozenArray(request.filters.map(item=>Object.freeze({id:item.id,value:serializableFilterValue(item.value)})))});if(this.emit("lr-request",requestDetail()),!!current()&&(this.emit("request",requestDetail()),!!current()&&this.dataSource)){this.ownsLoadingState=!0,this.loading=!0;try{const response=await this.dataSource(request);if(!current())return;this.data=Array.isArray(response.rows)?response.rows:[],this.total=finiteCount(response.total),this.loading=!1,this.ownsLoadingState=!1}catch(error){if(!current())return;this.loading=!1,this.ownsLoadingState=!1,this.emit("lr-data-error",Object.freeze({error,request:requestDetail()}))}}}get selectionEnabled(){return this.selectionMode!=="none"}get ariaColumnCount(){return Math.max(1,this.visibleColumns.length+(this.selectionEnabled?1:0))}rowIsSelectable(row){return this.selectionEnabled&&(this.selectableRows?.(row)??!0)}rowMatches(row){const source=this.allSourceRows;return this.memoize("rowMatches",[source,this.columns,this.filters,this.searchTerm,this.searchFn,this.effectiveLocale],()=>{const haystacks=!this.searchFn&&this.searchTerm.trim()?this.memoize("treeHaystacks",[source,this.columns,this.effectiveLocale],()=>searchHaystacks(source,this.columns,this.effectiveLocale)):void 0;return new Set(searchRows(filterRows(source,this.columns,this.filters,this.effectiveLocale,this.filterText),this.columns,this.searchTerm,this.effectiveLocale,this.searchFn,haystacks))}).has(row)}processedChildrenFor(row,byIdentity){const cache=this.memoize("sortedChildren",[this.allSourceRows,this.columns,this.sort,this.effectiveLocale,this.usesServerData],()=>new Map);let children=cache.get(row);if(!children){const canonical=this.canonicalMembers(this.childrenFor(row),byIdentity);children=this.usesServerData?canonical:sortRows(canonical,this.columns,this.sort,this.effectiveLocale),cache.set(row,children)}return this.usesServerData?children:children.filter(child=>this.rowMatches(child)||this.filterFromLeafRows&&this.hasMatchingDescendant(child))}hasMatchingDescendant(row){const stack=this.canonicalMembers(this.childrenFor(row)).map(child=>({row:child,depth:1})),visited=new Set;let inspected=0;for(;stack.length>0&&inspected<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(!(trackIdentity&&visited.has(current.row))){if(trackIdentity&&visited.add(current.row),inspected+=1,this.rowMatches(current.row))return!0;if(!(current.depth>=DATA_GRID_TREE_DEPTH_LIMIT))for(const child of this.canonicalMembers(this.childrenFor(current.row)))stack.push({row:child,depth:current.depth+1})}}return!1}get pageRows(){return this.getVisibleRows()}get currentPageSelectableRows(){return this.memoize("pageSelectable",[this.pageRows,this.allSourceRows,this.pipelineEpoch,this.childRows,this.selectable,this.selectableRows],()=>this.computeCurrentPageSelectableRows())}computeCurrentPageSelectableRows(){const result=[],sourceIndex=new Map(this.allSourceRows.map((row,index)=>[row,index])),visited=new Set,stack=[...this.pageRows].reverse().map(row=>({row,depth:0}));let inspected=0;for(;stack.length>0&&inspected<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(trackIdentity&&visited.has(current.row))continue;trackIdentity&&visited.add(current.row),inspected+=1;const index=this.sourceIndexFor(current.row,sourceIndex);if(index===void 0)continue;const key=this.keyForRow(current.row,index);if(this.rowIsSelectable(current.row)&&result.push({row:current.row,key}),current.depth>=DATA_GRID_TREE_DEPTH_LIMIT)continue;const children=this.canonicalMembers(this.childrenFor(current.row));for(let childIndex=children.length-1;childIndex>=0;childIndex-=1){const child=children[childIndex];stack.push({row:child,depth:current.depth+1})}}return result}groupMemberKey(rows){let first;for(const row of rows){const identity=this.rowIdentity(row);if(identity===void 0)continue;const candidate=`${typeof identity}:${safeText(identity)}`;(first===void 0||candidate<first)&&(first=candidate)}return first??"unknown"}groupKey(parent,id,value,rows){const valueType=typeof value;return valueType==="object"&&value!==null||valueType==="function"?`group:${parent}:${id}:${valueType}:member:${this.groupMemberKey(rows)}`:`group:${parent}:${id}:${valueType}:${safeText(value)}`}topLevelGroupBuckets(rows){return this.memoize("buckets",[rows,this.groupBy,this.orderedColumns],()=>this.computeTopLevelGroupBuckets(rows))}computeTopLevelGroupBuckets(rows){const field=normalizedGroupBy(this.groupBy)[0];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return[];const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row),bucket=buckets.get(value)??[];bucket.push(row),buckets.set(value,bucket)}return[...buckets].map(([value,bucketRows])=>({value,rows:bucketRows}))}groupItems(rows){const fields=normalizedGroupBy(this.groupBy);if(fields.length===0||this.usesServerData)return[];const result=[],visit=(groupRows,depth,parent)=>{const field=fields[depth];if(!field)return;const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return;const buckets=new Map;for(const row of groupRows){const value=columnValue(entry.column,row),bucket=buckets.get(value)??[];bucket.push(row),buckets.set(value,bucket)}for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value,bucket);result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth}),depth+1<fields.length&&visit(bucket,depth+1,key)}};return visit(rows,0,"root"),result}get displayItems(){return this.memoize("display",[this.pageRows,this.pipelineEpoch,this.processedClientRows,this.allSourceRows,this.childRows||this.groupBy?this.expandedKeys:null,this.groupBy,this.orderedColumns,this.usesServerData,this.childRows],()=>this.computeDisplayItems())}get displayIndexes(){const items=this.displayItems;return this.memoize("displayIndexes",[items],()=>new Map(items.map((item,index)=>[displayItemKey(item),index])))}computeDisplayItems(){for(const key of this.pipelineMemo.keys())(key.startsWith("eligible:")||key.startsWith("groupSelected:")||key.startsWith("aggregate:"))&&this.pipelineMemo.delete(key);const groups=normalizedGroupBy(this.groupBy);if(groups.length>0&&!this.usesServerData)return this.groupedDisplayItems(this.pageRows,groups,0,"root",this.sourceIndexMap());const result=[],sourceRows=this.allSourceRows,indexes=this.sourceIndexMap(sourceRows);let byIdentity;const visited=new Set,stack=[...this.pageRows].reverse().map(row=>({row,depth:0}));for(;stack.length>0&&result.length<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(trackIdentity&&visited.has(current.row))continue;trackIdentity&&visited.add(current.row);const sourceIndex=this.sourceIndexFor(current.row,indexes);if(sourceIndex===void 0)continue;const safeIndex=sourceIndex,key=this.keyForRow(current.row,safeIndex);if(result.push({kind:"row",row:current.row,key,depth:current.depth,sourceIndex:safeIndex}),!arrayHasKey(this.expandedKeys,key)||current.depth>=DATA_GRID_TREE_DEPTH_LIMIT)continue;const children=this.processedChildrenFor(current.row,byIdentity??=this.canonicalRowIndex(sourceRows));for(let index=children.length-1;index>=0;index-=1)stack.push({row:children[index],depth:current.depth+1})}return result}groupedDisplayItems(rows,fields,depth,parent,sourceIndexes){const field=fields[depth];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return rows.map((row,index)=>({kind:"row",row,key:this.keyForRow(row,this.sourceIndexFor(row,sourceIndexes)??index),depth,sourceIndex:this.sourceIndexFor(row,sourceIndexes)??index}));const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row),bucket=buckets.get(value)??[];bucket.push(row),buckets.set(value,bucket)}const result=[];for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value,bucket);if(result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth}),!!arrayHasKey(this.expandedKeys,key))if(depth+1<fields.length)result.push(...this.groupedDisplayItems(bucket,fields,depth+1,key,sourceIndexes));else for(const row of bucket){const sourceIndex=this.sourceIndexFor(row,sourceIndexes);result.push({kind:"row",row,key:this.keyForRow(row,sourceIndex??result.length),depth:depth+1,sourceIndex:sourceIndex??result.length})}}return result}measurementSignature(items){return items===this.signatureItems?this.signatureValue:(this.signatureItems=items,this.signatureValue=items.map(item=>{const key=displayItemKey(item);return`${key.length}:${key}`}).join("|"),this.signatureValue)}invalidateRowMeasurements(){const anchor=this.lastMeasurementAnchor??this.captureMeasurementAnchor();return this.measuredItemHeights.size===0?(this.measuredItemOffsetsDirty=!0,!1):(anchor&&(this.pendingMeasurementAnchor=anchor),this.measuredItemHeights.clear(),this.measuredItemOffsetsDirty=!0,!0)}reconcileRowMeasurementCache(changed,contentRefresh=changed.size===0){const items=this.displayItems,signature=this.measurementSignature(items),locale=this.effectiveLocale,changedGeometry=["columns","columnOrder","columnVisibility","columnWidths","data","filters","searchTerm","sort","expandedKeys","groupBy","page","pageSize","paginate","childRows","rowDetail","rowClass","selectable","strings"].some(property2=>changed.has(property2)),localeChanged=this.measurementLocale!==""&&this.measurementLocale!==locale,structureChanged=this.measurementDisplaySignature!==""&&this.measurementDisplaySignature!==signature,rowHeightChanged=this.recordMeasurementRowHeight();(contentRefresh||changedGeometry||localeChanged||structureChanged||rowHeightChanged)&&this.invalidateRowMeasurements(),this.measurementLocale=locale,this.measurementDisplaySignature=signature}recordMeasurementRowHeight(){const height=this.resolvedRowHeight,previous=this.measurementRowHeight,fontSignature=this.currentMeasurementFontSignature(),fontChanged=this.measurementFontSignature!==""&&this.measurementFontSignature!==fontSignature;return this.measurementRowHeight=height,this.measurementFontSignature=fontSignature,previous!==void 0&&previous!==height||fontChanged}currentMeasurementFontSignature(){if(this.geometryCycle&&this.cycleFontSignature!==void 0)return this.cycleFontSignature;if(!this.isConnected)return"";const owner=this.ownerDocument?.defaultView;if(!owner||typeof owner.getComputedStyle!="function")return"";try{const style=owner.getComputedStyle(this),cell=this.renderRoot?.querySelector('[part~="cell"], [part~="header-cell"], [part="group-value"]'),cellStyle=cell?owner.getComputedStyle(cell):void 0,cellPadding=cellStyle?[cellStyle.paddingBlockStart,cellStyle.paddingBlockEnd,cellStyle.paddingInlineStart,cellStyle.paddingInlineEnd].join(","):this.computedToken("--cell-padding","--_lr-data-grid-cell-padding");return this.cycleFontSignature=[style.fontFamily,style.fontSize,style.fontStretch,style.fontStyle,style.fontWeight,style.letterSpacing,style.lineHeight,style.wordSpacing,cellPadding].join("\0")}catch{return""}}recordMeasuredBodyWidth(width){if(typeof width!="number"||!Number.isFinite(width)||width<0)return!1;const previous=this.measuredBodyWidth;return this.measuredBodyWidth=width,previous===void 0||previous===width?!1:(this.invalidateRowMeasurements(),!0)}syncMeasuredBodyWidth(){const body=this.bodyElement;body&&(this.syncBodyScrollbarInlineEndGutter(body),this.recordMeasuredBodyWidth(body.clientWidth)&&this.queueMeasurementUpdate())}syncBodyScrollbarInlineEndGutter(body){const scrollbarGutter=finiteRange(body.offsetWidth-body.clientWidth,0,0);if(this.bodyScrollbarInlineEndGutter===scrollbarGutter)return;this.bodyScrollbarInlineEndGutter=scrollbarGutter;const value=`${scrollbarGutter}px`;this.renderRoot.querySelectorAll('[part="header"], [part="footer-row"]').forEach(element=>element.style.setProperty("--data-grid-body-inline-end-gutter",value))}queueMeasurementUpdate(){if(this.measurementUpdateQueued)return;this.measurementUpdateQueued=!0;const owner=this.ownerDocument.defaultView;(owner?.queueMicrotask?.bind(owner)??queueMicrotask)(()=>{this.measurementUpdateQueued=!1,this.isConnected&&super.requestUpdate()})}queueMeasuredScrollTop(body){if(this.measurementScrollSyncQueued)return;this.measurementScrollSyncQueued=!0;const owner=body.ownerDocument.defaultView;(owner?.queueMicrotask?.bind(owner)??queueMicrotask)(()=>{if(this.measurementScrollSyncQueued=!1,!this.isConnected||this.bodyElement!==body)return;const next=finiteRange(body.scrollTop,this.bodyScrollTop,0);this.bodyScrollTop!==next&&(this.bodyScrollTop=next),this.lastMeasurementAnchor=this.captureMeasurementAnchor()})}queueBodyScrollStateSync(){if(this.bodyScrollStateSyncQueued)return;this.bodyScrollStateSyncQueued=!0;const owner=this.ownerDocument.defaultView;(owner?.queueMicrotask?.bind(owner)??queueMicrotask)(()=>{this.bodyScrollStateSyncQueued=!1,this.isConnected&&this.syncBodyScrollState()})}scheduleMeasurementSync(){if(this.measurementFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{if(this.measurementFrame!==frame||(this.measurementFrame=void 0,!this.isConnected||this.ownerDocument.defaultView!==owner))return;const body=this.bodyElement;body&&this.syncBodyScrollbarInlineEndGutter(body),this.measureRenderedItems()}),this.measurementFrame=frame}cancelMeasurementFrame(){const frame=this.measurementFrame;frame&&(this.measurementFrame=void 0,frame.owner.cancelAnimationFrame(frame.handle))}resetRowMeasurementObserver(){this.rowMeasurementObserver?.disconnect(),this.rowMeasurementObserver=void 0,this.rowMeasurementObserverOwner=void 0,this.rowMeasurementObserverBody=void 0,this.observedMeasurementElements.clear(),this.observedMeasurementBlockSizes.clear(),this.cancelMeasurementFrame();const invalidated=this.invalidateRowMeasurements();this.lastMeasurementAnchor=void 0,invalidated&&this.isConnected&&this.queueMeasurementUpdate()}syncRowMeasurementObserver(){const body=this.bodyElement,owner=body?.ownerDocument.defaultView;if(!body||!owner||!this.isConnected||!owner.ResizeObserver){this.resetRowMeasurementObserver();return}if(this.rowMeasurementObserverOwner!==owner||this.rowMeasurementObserverBody!==body||!this.rowMeasurementObserver){this.resetRowMeasurementObserver();const observer2=new owner.ResizeObserver(entries=>{if(!(this.rowMeasurementObserver!==observer2||this.rowMeasurementObserverOwner!==owner||this.rowMeasurementObserverBody!==body||!this.isConnected||this.ownerDocument.defaultView!==owner)){for(const entry of entries){const target=entry.target;if(target!==body&&!this.observedMeasurementElements.has(target))continue;const blockSize=entry.borderBoxSize?.[0]?.blockSize;blockSize!==void 0&&Number.isFinite(blockSize)&&blockSize>0?this.observedMeasurementBlockSizes.set(target,blockSize):this.observedMeasurementBlockSizes.delete(target)}this.syncBodyScrollState(body);for(const entry of entries){if(entry.target!==body)continue;const width=entry.borderBoxSize?.[0]?.inlineSize??entry.contentRect.width;if(this.recordMeasuredBodyWidth(width)){this.queueMeasurementUpdate();return}}this.scheduleMeasurementSync()}});this.rowMeasurementObserver=observer2,this.rowMeasurementObserverOwner=owner,this.rowMeasurementObserverBody=body,observer2.observe(body,{box:"border-box"})}const observer=this.rowMeasurementObserver;if(!observer)return;const current=new Map;this.renderRoot.querySelectorAll("[data-virtual-item-key], [data-virtual-item-detail-for]").forEach(element=>{const key=element.dataset.virtualItemKey??element.dataset.virtualItemDetailFor;key&&current.set(element,key)});for(const element of this.observedMeasurementElements.keys())current.has(element)||(observer.unobserve(element),this.observedMeasurementElements.delete(element),this.observedMeasurementBlockSizes.delete(element));for(const[element,key]of current)this.observedMeasurementElements.get(element)!==key&&(this.observedMeasurementElements.has(element)&&observer.unobserve(element),this.observedMeasurementElements.set(element,key),observer.observe(element,{box:"border-box"}))}syncDisplayOffsets(items){const estimate=this.measurementRowHeight??this.resolvedRowHeight,signature=this.measurementSignature(items);if(!this.measuredItemOffsetsDirty&&this.measuredItemOffsetSignature===signature&&this.measuredItemOffsetEstimate===estimate)return;this.measuredOffsetHeights=items.map(item=>finiteRange(this.measuredItemHeights.get(displayItemKey(item))??estimate,estimate,1,Number.MAX_SAFE_INTEGER));const tree=[0,...this.measuredOffsetHeights];for(let index=1;index<tree.length;index+=1){const parent=index+(index&-index);parent<tree.length&&(tree[parent]+=tree[index])}this.measuredOffsetTree=tree,this.measuredItemOffsetSignature=signature,this.measuredItemOffsetEstimate=estimate,this.measuredItemOffsetsDirty=!1}offsetPrefix(index){let sum=0;for(let position=index;position>0;position-=position&-position)sum+=this.measuredOffsetTree[position]??0;return Math.min(sum,Number.MAX_SAFE_INTEGER)}updateOffsetHeight(key,height){if(this.measuredItemOffsetsDirty)return;const index=this.displayIndexes.get(key);if(index===void 0||this.measuredItemOffsetSignature!==this.measurementSignature(this.displayItems)){this.measuredItemOffsetsDirty=!0;return}const previous=this.measuredOffsetHeights[index];this.measuredOffsetHeights[index]=height;for(let position=index+1;position<this.measuredOffsetTree.length;position+=position&-position)this.measuredOffsetTree[position]+=height-previous}displayItemOffset(index,items){return this.syncDisplayOffsets(items),this.offsetPrefix(finiteInteger(index,0,0,items.length))}displayItemHeight(index,items){return this.syncDisplayOffsets(items),index<0||index>=items.length?0:Math.max(0,this.offsetPrefix(index+1)-this.offsetPrefix(index))}displayItemIndexAtOffset(offset,items){if(items.length===0)return-1;this.syncDisplayOffsets(items);const target=finiteRange(offset,0,0,Number.MAX_SAFE_INTEGER);let index=0,sum=0,step=1;for(;step*2<=items.length;)step*=2;for(;step>0;step>>>=1){const next=index+step;next<=items.length&&sum+this.measuredOffsetTree[next]<=target&&(sum+=this.measuredOffsetTree[next],index=next)}return Math.min(index,items.length-1)}captureMeasurementAnchor(){const body=this.bodyElement,items=this.displayItems;if(!body||items.length===0)return;const scrollTop=finiteRange(body.scrollTop,this.bodyScrollTop,0);return this.measurementAnchorAtOffset(scrollTop,items)}measurementAnchorAtOffset(scrollTop,items){if(items.length===0)return;const index=this.displayItemIndexAtOffset(scrollTop,items),item=items[index];if(!item)return;const offset=Math.max(0,scrollTop-this.displayItemOffset(index,items)),height=this.displayItemHeight(index,items);if(index+1<items.length&&height>1&&offset>=height-1){const next=items[index+1];return Object.freeze({itemKey:displayItemKey(next),offset:0})}return Object.freeze({itemKey:displayItemKey(item),offset})}correctMeasurementAnchor(){const anchor=this.pendingMeasurementAnchor,body=this.bodyElement;if(!anchor||!body)return;const items=this.displayItems,index=this.displayIndexes.get(anchor.itemKey)??-1;if(this.pendingMeasurementAnchor=void 0,index<0){this.lastMeasurementAnchor=void 0;return}const next=Math.max(0,this.displayItemOffset(index,items)+anchor.offset);this.expectedBodyScroll=Object.freeze({body,top:next}),body.scrollTop=next,this.lastMeasurementAnchor=anchor,this.queueMeasuredScrollTop(body)}measureRenderedItems(){const previous=this.geometryCycle;previous||this.resetGeometryCycle(),this.geometryCycle=!0;try{this.measureCurrentItems()}finally{this.geometryCycle=previous}}measureCurrentItems(){const rowHeightChanged=this.recordMeasurementRowHeight();rowHeightChanged&&this.invalidateRowMeasurements();const estimate=this.measurementRowHeight??this.resolvedRowHeight,grouped=new Map;if(this.renderRoot.querySelectorAll("[data-virtual-item-key], [data-virtual-item-detail-for]").forEach(element=>{const key=element.dataset.virtualItemKey??element.dataset.virtualItemDetailFor;if(!key)return;const entries=grouped.get(key)??[];entries.push(element),grouped.set(key,entries)}),grouped.size===0){rowHeightChanged&&this.queueMeasurementUpdate();return}const anchor=this.captureMeasurementAnchor();let changed=!1;for(const[key,elements]of grouped){let height=0,measurable=!0;for(const element of elements){let next;try{next=this.layoutBorderBoxHeight(element)}catch{measurable=!1;break}if(!Number.isFinite(next)||next<=0){measurable=!1;break}height+=next}if(!measurable||!Number.isFinite(height)||height<=0)continue;const previous=this.measuredItemHeights.get(key);if(Math.abs(estimate-height)<=1){previous!==void 0&&(this.measuredItemHeights.delete(key),this.updateOffsetHeight(key,estimate),changed=!0);continue}previous!==void 0&&Math.abs(previous-height)<=.1||(this.measuredItemHeights.set(key,height),this.updateOffsetHeight(key,height),changed=!0)}if(!changed){rowHeightChanged&&this.queueMeasurementUpdate();return}anchor&&this.pendingMeasurementAnchor===void 0&&(this.pendingMeasurementAnchor=anchor),this.queueMeasurementUpdate()}layoutBorderBoxHeight(element){if(!element.isConnected)return Number.NaN;const style=element.ownerDocument.defaultView?.getComputedStyle(element);if(!style||style.display==="none")return Number.NaN;const roundedHeight=element.offsetHeight;if(roundedHeight<=0)return Number.NaN;const observed=this.observedMeasurementBlockSizes.get(element);if(observed!==void 0&&Math.abs(observed-roundedHeight)<=.5)return observed;const height=Number.parseFloat(style.height);return style.boxSizing==="border-box"?height:height+Number.parseFloat(style.paddingTop)+Number.parseFloat(style.paddingBottom)+Number.parseFloat(style.borderTopWidth)+Number.parseFloat(style.borderBottomWidth)}renderedRowAlignmentDelta(target,body,alignment){let targetTop,targetBottom;const style=target.ownerDocument.defaultView?.getComputedStyle(target),visuallyTransformed=style&&(style.position==="sticky"||style.transform!=="none"||style.translate&&style.translate!=="none"||style.scale&&style.scale!=="none"||style.rotate&&style.rotate!=="none"||style.zoom&&style.zoom!=="1"&&style.zoom!=="normal");if(target.offsetParent===body&&!visuallyTransformed)targetTop=target.offsetTop-body.scrollTop,targetBottom=targetTop+target.offsetHeight;else{const targetRect=target.getBoundingClientRect(),bodyRect=body.getBoundingClientRect(),bodyLayoutHeight=this.layoutBorderBoxHeight(body),scaleY=bodyLayoutHeight>0&&bodyRect.height>0?finiteRange(bodyRect.height/bodyLayoutHeight,1,Number.EPSILON):1;targetTop=(targetRect.top-bodyRect.top)/scaleY-body.clientTop,targetBottom=(targetRect.bottom-bodyRect.top)/scaleY-body.clientTop}const viewportBottom=body.clientHeight;if(alignment==="center")return(targetTop+targetBottom-viewportBottom)/2;if(alignment==="end")return targetBottom-viewportBottom;if(alignment==="start")return targetTop;const outsideTop=targetTop<0,outsideBottom=targetBottom>viewportBottom;if(outsideTop===outsideBottom)return 0;const oversized=targetBottom-targetTop>body.clientHeight;return outsideTop?oversized?targetBottom-viewportBottom:targetTop:oversized?targetTop:targetBottom-viewportBottom}renderedStartPrecisionDelta(target,body){const bodyRect=body.getBoundingClientRect(),layoutHeight=this.layoutBorderBoxHeight(body),scaleY=bodyRect.height/layoutHeight;if(!Number.isFinite(scaleY)||scaleY<=0)return 0;const style=body.ownerDocument.defaultView?.getComputedStyle(body),borderTop=Number.parseFloat(style?.borderTopWidth??""),visualError=target.getBoundingClientRect().top-(bodyRect.top+borderTop*scaleY);return Math.abs(visualError)>1?visualError/scaleY:0}alignPendingVirtualScroll(){const pending=this.pendingVirtualScroll;if(!pending||this.measurementUpdateQueued||this.measurementScrollSyncQueued||this.pendingMeasurementAnchor!==void 0)return;if(!this.displayIndexes.has(pending.itemKey)){this.pendingVirtualScroll=void 0;return}const target=[...this.renderRoot.querySelectorAll('[part~="row"][data-virtual-item-key]')].find(element=>element.dataset.virtualItemKey===pending.itemKey),body=this.bodyElement;if(!target||!body)return;const layoutDelta=this.renderedRowAlignmentDelta(target,body,pending.align),precisionDelta=pending.align==="start"?this.renderedStartPrecisionDelta(target,body):0;if(Math.abs(layoutDelta)<=.5&&precisionDelta===0){this.pendingVirtualScroll=void 0;return}const alignmentDelta=Math.abs(layoutDelta)>.5?layoutDelta:precisionDelta,previousTop=body.scrollTop,nextTop=finiteRange(previousTop+alignmentDelta,previousTop,0,Math.max(0,body.scrollHeight-body.clientHeight));if(body.scrollTo({top:nextTop}),precisionDelta!==0){const remaining=this.renderedStartPrecisionDelta(target,body);Math.abs(remaining)>=Math.abs(precisionDelta)&&(body.scrollTo({top:previousTop}),this.pendingVirtualScroll=void 0)}body.scrollTop===previousTop?this.pendingVirtualScroll=void 0:(this.expectedBodyScroll=Object.freeze({body,top:body.scrollTop}),this.queueMeasurementUpdate()),this.queueBodyScrollStateSync()}resetGeometryCycle(){this.cycleRowHeight=void 0,this.cycleColumnEstimate=void 0,this.cycleFontSignature=void 0}get resolvedRowHeight(){if(this.geometryCycle&&this.cycleRowHeight!==void 0)return this.cycleRowHeight;const raw=this.computedToken("--row-height","--_lr-data-grid-row-height"),targetFloor=resolveCssTokenLength(this.computedToken("--_lr-density-target-min"),{host:this})??0;return this.cycleRowHeight=finiteRange(resolveCssTokenLength(raw,{host:this})??56,56,Math.max(24,targetFloor))}detailRowOffsets(items){return this.rowDetail?this.memoize("detailRowOffsets",[items,this.expandedKeys,this.rowDetail],()=>{const offsets=[0];for(const item of items)offsets.push(offsets[offsets.length-1]+(item.kind==="row"&&arrayHasKey(this.expandedKeys,item.key)?1:0));return offsets}):[0]}get virtualWindow(){const items=this.displayItems;if(items.length<VIRTUALIZATION_THRESHOLD||this.computedToken("--max-height","--_lr-data-grid-max-height")==="none")return{items,allItems:items,start:0,end:items.length};const height=this.resolvedRowHeight,viewport=Math.max(height,this.viewportHeight||height*10),firstVisible=this.displayItemIndexAtOffset(this.bodyScrollTop,items),lastVisible=this.displayItemIndexAtOffset(this.bodyScrollTop+viewport,items),start=Math.max(0,firstVisible-VIRTUAL_OVERSCAN),end=Math.min(items.length,lastVisible+VIRTUAL_OVERSCAN+1);return{items:items.slice(start,end),allItems:items,start,end}}columnGeometryInputs(){return[this.visibleColumns,this.columnWidths,this.measuredBodyWidth,this.selectionEnabled,this.currentMeasurementFontSignature(),this.pipelineEpoch,this.processedClientRows,this.estimatedColumnWidth({},"")]}sameColumnGeometry(left,right){return left?.length===right.length&&left.every((input,index)=>Object.is(input,right[index]))}get gridTemplate(){const inputs=this.columnGeometryInputs();return this.visibleColumns.length>50&&this.resolvedColumnWidths&&this.sameColumnGeometry(this.resolvedColumnInputs,inputs)?this.memoize("resolvedGridTemplate",[this.resolvedColumnWidths,this.selectionEnabled],()=>{const tracks=this.resolvedColumnWidths.map(width=>`${width}px`);return this.selectionEnabled&&tracks.unshift("var(--lr-icon-button-size)"),tracks.join(" ")}):(this.naturalColumnInputs=inputs,this.memoize("gridTemplate",[this.visibleColumns,this.columnWidths,this.selectionEnabled],()=>this.computeGridTemplate()))}computeGridTemplate(){const columns=this.visibleColumns.map(({column,id})=>{const bounds=this.columnBounds(column),width=this.columnWidths.get(id)??column.width;if(width!==void 0&&Number.isFinite(width)&&width>0)return`${finiteRange(width,bounds.minimum,bounds.minimum,bounds.maximum)}px`;const minimum=bounds.minimum>0?`${bounds.minimum}px`:Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?"0px":"var(--lr-size-7rem)",maximum=Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?`${bounds.maximum}px`:`${finiteRange(column.flex??1,1,0)}fr`;return`minmax(${minimum}, ${maximum})`});return this.selectionEnabled&&columns.unshift("var(--lr-icon-button-size)"),columns.length>0?columns.join(" "):"minmax(var(--lr-size-7rem), 1fr)"}syncResolvedColumnWidths(){const inputs=this.columnGeometryInputs();if(this.sameColumnGeometry(this.resolvedColumnInputs,inputs))return;if(!this.sameColumnGeometry(this.naturalColumnInputs,inputs)){this.queueMeasurementUpdate();return}const row=this.renderRoot.querySelector('[part~="row"]')??this.renderRoot.querySelector('[part="header"]'),owner=this.ownerDocument.defaultView;if(!row||typeof owner?.getComputedStyle!="function")return;let tracks;try{tracks=owner.getComputedStyle(row).gridTemplateColumns.split(/\s+/u).map(value=>Number.parseFloat(value))}catch{return}const widths=this.selectionEnabled?tracks.slice(1):tracks;widths.length!==this.visibleColumns.length||widths.some(width=>!Number.isFinite(width)||width<0)||(this.resolvedColumnInputs=inputs,this.queueMeasurementUpdate(),!(this.resolvedColumnWidths?.length===widths.length&&this.resolvedColumnWidths.every((width,index)=>Math.abs(width-widths[index])<.01))&&(this.resolvedColumnWidths=widths,this.queueMeasurementUpdate()))}get columnLayout(){const columns=this.visibleColumns,estimate=this.estimatedColumnWidth({},"");return this.memoize("columnLayout",[columns,this.columnWidths,estimate,this.selectionEnabled,this.resolvedColumnWidths],()=>{const offsets=[0],positions=new Map,pins=new Map,pinned=[];let left=0,right=0;columns.forEach(({column,id},position)=>{positions.set(id,position);const width=this.resolvedColumnWidths?.[position]??this.estimatedColumnWidth(column,id);offsets.push(offsets[position]+width),normalizePinSide(this.getColumnPin(id))==="left"&&(pins.set(id,left),left+=width,pinned.push(position))});for(let index=columns.length-1;index>=0;index-=1){const{column,id}=columns[index];normalizePinSide(this.getColumnPin(id))==="right"&&(pins.set(id,right),right+=this.resolvedColumnWidths?.[index]??this.estimatedColumnWidth(column,id),pinned.push(index))}return{offsets,positions,pins,pinned}})}get windowColumns(){const columns=this.visibleColumns,layout=this.columnLayout;if(columns.length<=50)return columns.map((entry,position)=>({...entry,position}));const at=offset=>{let low=0,high=columns.length-1;for(;low<high;){const middle=low+high>>>1;layout.offsets[middle+1]<=offset?low=middle+1:high=middle}return low},start=Math.max(0,at(this.bodyScrollInlineOffset)-2),end=Math.min(columns.length,at(this.bodyScrollInlineOffset+(this.measuredBodyWidth||1120))+3),positions=new Set(layout.pinned);positions.add(this.focusedColumn),(this.selectionEnabled||this.childRows||this.rowDetail)&&positions.add(0);for(let index=start;index<end;index+=1)positions.add(index);return[...positions].sort((a,b)=>a-b).flatMap(position=>{const entry=columns[position];return entry?[{...entry,position}]:[]})}get bodyScrollTranslation(){const logical=finiteRange(this.bodyScrollInlineOffset,0,0,Number.MAX_SAFE_INTEGER);return`${this.effectiveDirection==="rtl"?logical:-logical}px`}columnStyle(column,id){const cache=this.memoize("columnStyles",[this.columnLayout,this.selectionEnabled],()=>new Map),cached=cache.get(id);if(cached)return cached;const side=normalizePinSide(this.getColumnPin(id)),pinOffset=side?this.pinOffset(id,side):0,style={"grid-column":String((this.columnLayout.positions.get(id)??0)+1+(this.selectionEnabled?1:0)),...side?{"--pin-offset":`${pinOffset}px`}:{},...Number.isFinite(column.width)&&(column.width??0)>0&&!this.columnWidths.has(id)?{"--column-authored-width":`${column.width}px`}:{}};return cache.set(id,style),style}estimatedColumnWidth(column,id){const{minimum,maximum}=this.columnBounds(column),explicit=this.columnWidths.get(id)??column.width;return explicit!==void 0&&Number.isFinite(explicit)&&explicit>0?finiteRange(explicit,Math.max(112,minimum),minimum,maximum):(this.geometryCycle||(this.cycleColumnEstimate=void 0),this.cycleColumnEstimate??=resolveCssTokenLength(this.computedToken("--lr-size-7rem"),{host:this})??112,finiteRange(this.cycleColumnEstimate,Math.max(112,minimum),minimum,maximum))}columnBounds(column){const minimum=finiteRange(column.minWidth??0,0,0),authoredMaximum=finiteRange(column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0);return Object.freeze({minimum,maximum:Math.max(minimum,authoredMaximum)})}pinOffset(id,_side){return this.columnLayout.pins.get(id)??0}columnLabel(column,id){return column.label!==void 0&&column.label.trim().length>0?column.label:humanizeIdentifier(column.field??id,this.effectiveLocale)}columnIsSortable(column){return column.sortable!==!1&&!!(column.field||column.value)}sortFor(id){const index=this.sort.findIndex(item=>item.id===id);return{state:index>=0?this.sort[index]:void 0,index}}activateSort(id,additive){const entry=this.columnIndex.get(id);if(!entry||!this.columnIsSortable(entry.column))return;const existing=this.sortFor(id).state,descendingFirst=entry.column.sortDescFirst??this.sortDescFirst;let replacement;existing?existing.desc===descendingFirst?replacement={id,desc:!descendingFirst}:this.withoutSortRemoval&&(replacement={id,desc:descendingFirst}):replacement={id,desc:descendingFirst};let next=additive?this.sort.filter(item=>item.id!==id):[];replacement&&next.push(replacement);const limit=finiteCount(this.maxMultiSort);limit>0&&next.length>limit&&(next=next.slice(next.length-limit));const proposedSort=frozenArray(next.map(item=>Object.freeze({...item})));this.emit("lr-sort-request",Object.freeze({sort:proposedSort}),{cancelable:!0}).defaultPrevented||(this.sort=next,this.page=0,this.emit("lr-sort-change",Object.freeze({sort:proposedSort})))}onHeaderClick(event,id){const target=event.target,interactive=isElementValue(target)?target.closest(INTERACTIVE_SELECTOR):null;interactive&&interactive!==event.currentTarget||this.activateSort(id,event.shiftKey)}onFilterInput(event,id){const control=valueControl(event.currentTarget);control&&this.commitFilterValue(id,control.value)}commitFilterValue(id,value){const next=this.filters.filter(filter=>filter.id!==id);value&&next.push({id,value}),this.filters=next,this.page=0,this.emit("lr-filter-change",Object.freeze({filters:frozenArray(next.map(filter=>Object.freeze({...filter})))}))}onClearFilterInput(id){this.filters.some(filter=>filter.id===id)&&(this.commitFilterValue(id,""),this.renderRoot.querySelector('[part="filter-panel"] input[type="search"]')?.focus())}syncBodyScrollState(source=this.bodyElement){const target=source;if(!isElementValue(target)||typeof target.scrollTop!="number"||typeof target.clientHeight!="number"||typeof target.scrollLeft!="number")return;this.bodyScrollTop=finiteRange(target.scrollTop,this.bodyScrollTop,0),this.viewportHeight=finiteRange(target.clientHeight,this.viewportHeight,0);const inlineExtent=typeof target.scrollWidth=="number"&&typeof target.clientWidth=="number"&&Number.isFinite(target.scrollWidth)&&Number.isFinite(target.clientWidth)?Math.max(0,target.scrollWidth-target.clientWidth):Number.MAX_SAFE_INTEGER;this.bodyScrollInlineOffset=finiteRange(this.effectiveDirection==="rtl"?-target.scrollLeft:target.scrollLeft,0,0,inlineExtent)}onBodyScroll(event){const body=event.currentTarget;this.syncBodyScrollState(body);const expected=this.expectedBodyScroll;expected&&expected.body===body&&Math.abs(finiteRange(body.scrollTop,this.bodyScrollTop,0)-expected.top)<=1?this.expectedBodyScroll=void 0:(this.expectedBodyScroll=void 0,this.pendingMeasurementAnchor=void 0,this.pendingVirtualScroll=void 0),this.lastMeasurementAnchor=this.captureMeasurementAnchor()}onBodyCellEvent(event){const cell=event.composedPath().find(node=>isElementValue(node)&&node.hasAttribute("data-row-position")&&node.hasAttribute("data-column-id"));if(!cell)return;const rowPosition=Number(cell.dataset.rowPosition),columnPosition=Number(cell.dataset.columnPosition),item=this.displayItems[rowPosition],id=cell.dataset.columnId,entry=this.columnIndex.get(id);!item||item.kind!=="row"||!entry||(event.type==="focusin"?(this.focusedRow=rowPosition,this.focusedColumn=columnPosition):event.type==="click"?this.onCellClick(event,item,entry.column,id,rowPosition,cell):event.type==="contextmenu"?this.emitCellContextMenu(event,item,entry.column,id,rowPosition):event.type==="keydown"&&this.onGridKeyDown(event,rowPosition,columnPosition,item,entry.column,id,cell))}onCellClick(event,item,column,columnIdValue,index,cell=event.currentTarget){for(const target of event.composedPath()){if(target===cell)break;if(isElementValue(target)&&target.matches(INTERACTIVE_SELECTOR))return}this.emit("lr-cell-click",Object.freeze({rowKey:item.key,columnId:columnIdValue,column,value:columnValue(column,item.row),row:item.row,index}))}emitCellContextMenu(originalEvent,item,column,columnIdValue,index){const detail=Object.freeze({rowKey:item.key,columnId:columnIdValue,column,value:columnValue(column,item.row),row:item.row,index,originalEvent});this.emit("lr-cell-contextmenu",detail,{cancelable:!0}).defaultPrevented&&originalEvent.preventDefault()}descendantRows(row){const result=[],visited=new Set,stack=this.canonicalMembers(this.childrenFor(row)).reverse().map(child=>({row:child,depth:1}));for(;stack.length>0&&result.length<this.rowLimit;){const current=stack.pop(),trackIdentity=typeof current.row=="object"&&current.row!==null||typeof current.row=="function";if(trackIdentity&&visited.has(current.row)||(trackIdentity&&visited.add(current.row),result.push(current.row),current.depth>=DATA_GRID_TREE_DEPTH_LIMIT))continue;const children=this.canonicalMembers(this.childrenFor(current.row));for(let index=children.length-1;index>=0;index-=1){const child=children[index];stack.push({row:child,depth:current.depth+1})}}return result}setRowSelected(item,selected,event){if(!this.rowIsSelectable(item.row))return;const{items:selectableItems,positions}=this.memoize("selectableDisplay",[this.displayItems,this.selectable,this.selectableRows],()=>{const items=this.displayItems.filter(candidate=>candidate.kind==="row"&&this.rowIsSelectable(candidate.row));return{items,positions:new Map(items.map((candidate,position2)=>[candidate.key,position2]))}}),position=positions.get(item.key)??-1;let affected=[item];if(event?.shiftKey&&this.selectionMode==="multiple"&&this.lastSelectedIndex>=0){const from=Math.min(this.lastSelectedIndex,position),to=Math.max(this.lastSelectedIndex,position);affected=selectableItems.slice(from,to+1)}const descendants=this.selectionMode==="multiple"?affected.flatMap(candidate=>this.descendantRows(candidate.row)).filter(row=>this.rowIsSelectable(row)):[],sourceIndexes=this.sourceIndexMap(),keys=[...affected.map(candidate=>candidate.key),...descendants.map((row,index)=>{const sourceIndex=this.sourceIndexFor(row,sourceIndexes);return this.keyForRow(row,sourceIndex??index)})],ordered=new Map;for(const key of keys){const typed=typedKey(key);ordered.delete(typed),ordered.set(typed,key)}const next=this.selectionMode==="single"?[]:this.selectedKeys.filter(candidate=>!ordered.has(typedKey(candidate)));selected&&next.push(...ordered.values()),this.selectedKeys=next,this.lastSelectedIndex=position,this.emitSelection()}selectCurrentPage(selected){const pageKeys=this.currentPageSelectableRows.map(item=>item.key),pageKeySet=new Set(pageKeys.map(typedKey));let next=this.selectedKeys.filter(key=>!pageKeySet.has(typedKey(key)));selected&&(next=[...next,...pageKeys]),this.selectedKeys=next,this.emitSelection()}emitSelection(){const selectedRowKeys=frozenArray(this.selectedRowKeys),selectedRows=frozenArray(this.selectedRows);this.emit("lr-row-select",Object.freeze({selectedRowKeys,selectedKeys:selectedRowKeys,selectedRows}))}rowSelectionState(item){const states=this.memoize("selectionStates",[this.allSourceRows,this.selectedKeys,this.selectable,this.selectableRows,this.childRows],()=>{const result=new Map;if(!this.childRows||this.selectionMode!=="multiple")return result;const byIdentity=this.canonicalRowIndex(),children=new Map,parentCounts=new Map;for(const row of this.allSourceRows){const nested=this.canonicalMembers(this.childrenFor(row),byIdentity);children.set(row,nested);for(const child of nested)parentCounts.set(child,(parentCounts.get(child)??0)+1)}if([...parentCounts.values()].some(count=>count>1))return result;const totals=new Map,visiting=new Set,visit=(row,depth)=>{if(totals.has(row))return!0;if(visiting.has(row)||depth>DATA_GRID_TREE_DEPTH_LIMIT)return!1;visiting.add(row);let count=0,selected=0;for(const child of children.get(row)??[]){if(!visit(child,depth+1))return!1;const total=totals.get(child);count+=total.count,selected+=total.selected}const own=arrayHasKey(this.selectedKeys,this.rowIdentity(row)),checked=own&&selected===count;result.set(row,{checked,indeterminate:!checked&&(own||selected>0)});const eligible=this.rowIsSelectable(row);return totals.set(row,{count:count+(eligible?1:0),selected:selected+(eligible&&own?1:0)}),visiting.delete(row),!0};for(const row of this.allSourceRows)if(!visit(row,0)){result.clear();break}return result});let state2=states.get(item.row);return state2||(state2=this.computeRowSelectionState(item),states.set(item.row,state2)),state2}computeRowSelectionState(item){const own=arrayHasKey(this.selectedKeys,item.key);if(this.selectionMode!=="multiple")return{checked:own,indeterminate:!1};const descendants=this.descendantRows(item.row).filter(row=>this.rowIsSelectable(row));if(descendants.length===0)return{checked:own,indeterminate:!1};const sourceIndexes=this.sourceIndexMap(),selected=descendants.filter((row,index)=>{const sourceIndex=this.sourceIndexFor(row,sourceIndexes);return arrayHasKey(this.selectedKeys,this.keyForRow(row,sourceIndex??index))}).length,checked=own&&selected===descendants.length;return{checked,indeterminate:!checked&&(own||selected>0)}}toggleRowExpanded(item,emitUserEvent){const expanded=arrayHasKey(this.expandedKeys,item.key);expanded?this.collapseRow(item.key):this.expandRow(item.key),emitUserEvent&&this.emit(expanded?"lr-row-collapse":"lr-row-expand",Object.freeze({rowKey:item.key,key:item.key,row:item.row}))}toggleGroupExpanded(item){const expanded=arrayHasKey(this.expandedKeys,item.key);expanded?this.collapseRow(item.key):this.expandRow(item.key);const detail=Object.freeze({key:item.key,columnId:item.columnId,value:item.value,rows:frozenArray(item.rows)});this.emit(expanded?"lr-group-collapse":"lr-group-expand",detail)}moveColumn(id,delta,emitUserEvent){const order=this.orderedColumns.map(entry=>entry.id),from=order.indexOf(id);if(from<0)return;const to=finiteInteger(from+delta,from,0,order.length-1);from!==to&&(order.splice(from,1),order.splice(to,0,id),this.columnOrder=order,emitUserEvent&&this.emit("lr-column-move",Object.freeze({columnOrder:frozenArray(order),columnId:id,finished:!0})))}columnCanMove(id){const entry=this.columnIndex.get(id);return!!(entry&&(this.reorderable||entry.column.movable))}columnCanResize(id){const entry=this.columnIndex.get(id);return!!(entry&&(this.resizable||entry.column.resizable))}onDragStart(event,id){const entry=this.columnIndex.get(id);if(!entry||!this.columnCanMove(id)||!event.dataTransfer){event.preventDefault();return}const token=`${++this.columnDragSequence}:${id}`;this.columnDragSession=Object.freeze({sourceId:id,token}),event.dataTransfer.setData(DATA_GRID_DRAG_TYPE,token),event.dataTransfer.setData("text/plain",id),event.dataTransfer.effectAllowed="move",this.dragGhost=this.columnLabel(entry.column,id)}onDrop(event,targetId){event.preventDefault();const session=this.columnDragSession,token=event.dataTransfer?.getData(DATA_GRID_DRAG_TYPE),sourceId=session?.sourceId;if(this.columnDragSession=void 0,this.dragGhost="",!session||token!==session.token||!sourceId||sourceId===targetId||!this.columnCanMove(sourceId)||!this.columnCanMove(targetId))return;const order=this.orderedColumns.map(entry=>entry.id),source=order.indexOf(sourceId),target=order.indexOf(targetId);source<0||target<0||(order.splice(source,1),order.splice(target,0,sourceId),this.columnOrder=order,this.emit("lr-column-move",Object.freeze({columnOrder:frozenArray(order),columnId:sourceId,finished:!0})))}onResizeStart(event,id){const entry=this.columnIndex.get(id);if(!entry||!this.columnCanResize(id))return;this.resizePointer.stop(),this.resizeSession?.moved&&this.restoreResizeSession(this.resizeSession,!0);const header=this.renderedColumnElements(id,"columnheader")[0];this.resizeSession={columnId:id,startClientX:event.clientX,startWidth:header?.getBoundingClientRect().width??this.estimatedColumnWidth(entry.column,id),initialStateWidth:this.columnWidths.get(id),pointerId:event.pointerId,moved:!1,direction:this.effectiveDirection},this.activeResizeColumn=id,this.resizePointer.start(event,event.currentTarget),event.preventDefault()}onResizeMove(event){const session=this.resizeSession;if(!session||event.pointerId!==session.pointerId)return;if(!this.columnCanResize(session.columnId)){this.resizePointer.stop(),this.resizeSession=void 0,this.activeResizeColumn=void 0,session.moved&&this.restoreResizeSession(session,!0);return}const{minimum,maximum}=this.columnBounds(this.columnIndex.get(session.columnId).column);this.setColumnWidth(session.columnId,columnResizePointerWidth(session.startWidth,session.startClientX,event.clientX,session.direction==="rtl",minimum,maximum),!0,!1),session.moved=!0}takeResizeSession(event){const session=this.resizeSession;if(!(!session||event.pointerId!==session.pointerId))return this.resizeSession=void 0,this.activeResizeColumn=void 0,this.resizePointer.stop(),session}restoreResizeSession(session,emit){const next=new Map(this.columnWidths);session.initialStateWidth===void 0?next.delete(session.columnId):next.set(session.columnId,session.initialStateWidth),this.columnWidths=next,emit&&this.emit("lr-column-resize",Object.freeze({columnId:session.columnId,columnKey:session.columnId,width:session.startWidth,finished:!1}))}onResizeEnd(event){const session=this.takeResizeSession(event);if(!session)return;if(!this.columnCanResize(session.columnId)){session.moved&&this.restoreResizeSession(session,!0);return}const width=this.columnWidths.get(session.columnId)??session.startWidth;let committed=!1;requestThenCommit({requestDetail:Object.freeze({columnId:session.columnId,columnKey:session.columnId,width}),emitRequest:(detail,init)=>this.emit("lr-column-resize-request",detail,init),commit:()=>{committed=!0,this.emit("lr-column-resize",Object.freeze({columnId:session.columnId,columnKey:session.columnId,width,finished:!0}))}}),committed||this.restoreResizeSession(session,!0)}onResizeCancel(event){const session=this.takeResizeSession(event);!session||!session.moved||this.restoreResizeSession(session,!0)}onResizeKey(event,id,fromHandle=!1){const entry=this.columnIndex.get(id);if(!entry||!this.columnCanResize(id))return;const arrow=event.key==="ArrowLeft"||event.key==="ArrowRight",jump=fromHandle&&(event.key==="Home"||event.key==="End"&&entry.column.maxWidth!==void 0);if(!arrow&&!jump)return;event.preventDefault();const{minimum,maximum}=this.columnBounds(entry.column),current=this.columnWidths.get(id)??this.renderedColumnWidth(id)??this.estimatedColumnWidth(entry.column,id),width=columnResizeKeyboardWidth(event,current,minimum,maximum,this.effectiveDirection==="rtl",fromHandle);width!==void 0&&requestThenCommit({requestDetail:Object.freeze({columnId:id,columnKey:id,width}),emitRequest:(detail,init)=>this.emit("lr-column-resize-request",detail,init),commit:()=>this.setColumnWidth(id,width,!0,!0)})}renderedColumnWidth(id){const width=this.renderedColumnElements(id,"columnheader")[0]?.getBoundingClientRect().width;return width!==void 0&&Number.isFinite(width)&&width>0?width:void 0}syncResizeHandleValues(){for(const handle of this.renderRoot.querySelectorAll('[part="resize-handle"]')){const header=handle.closest('[role="columnheader"][data-column-id]'),id=header?.getAttribute("data-column-id");if(!header||!id||this.columnWidths.has(id))continue;const entry=this.columnIndex.get(id);if(!entry||entry.column.width!==void 0)continue;const rendered=header.getBoundingClientRect().width;if(!Number.isFinite(rendered)||rendered<=0)continue;const width=Math.round(rendered);handle.getAttribute("aria-valuenow")!==String(width)&&(handle.setAttribute("aria-valuenow",String(width)),handle.setAttribute("aria-valuetext",this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(width)})))}}onPageSizeChange(event){const control=valueControl(event.currentTarget);control&&(this.pageSize=finiteCount(Number(control.value)),this.page=0,this.emit("lr-page-change",Object.freeze({page:0,pageSize:this.safePageSize})))}focusCell(row,column){const rowLimit=Math.max(-1,this.displayItems.length-1),columnLimit=Math.max(0,this.visibleColumns.length-1);this.focusedRow=finiteInteger(row,this.focusedRow,-1,rowLimit),this.focusedColumn=finiteInteger(column,this.focusedColumn,0,columnLimit);let pendingScrollTop;if(this.focusedRow>=0){const selector=`[role="gridcell"][data-row-position="${this.focusedRow}"]`;if(!this.renderRoot.querySelector(selector)){const top=this.displayItemOffset(this.focusedRow,this.displayItems);pendingScrollTop=top,this.bodyScrollTop=top,this.bodyElement&&(this.bodyElement.scrollTop=top)}}this.updateComplete.then(()=>{pendingScrollTop!==void 0&&this.bodyElement&&(this.bodyElement.scrollTop=pendingScrollTop),this.focus()})}handleDisclosureKey(direction,rowPosition){const items=this.displayItems,item=items[rowPosition];if(!item)return!1;const expanded=arrayHasKey(this.expandedKeys,item.key);if(item.kind==="group")return direction>0===expanded?!1:(this.toggleGroupExpanded(item),!0);if((this.childrenFor(item.row).length>0||this.rowDetail!==null)&&direction>0!==expanded)return this.toggleRowExpanded(item,!0),!0;if(direction>0||!this.childRows||item.depth===0)return!1;let parent=rowPosition-1;for(;parent>0&&(items[parent]?.depth??0)>=item.depth;)parent-=1;return this.focusCell(parent,0),!0}onGridKeyDown(event,rowPosition,columnPosition,item,column,columnIdValue,cell=event.currentTarget){const target=event.target;if(isElementValue(target)&&target!==cell&&target.closest(INTERACTIVE_SELECTOR))return;const rtlMultiplier=this.effectiveDirection==="rtl"?-1:1;if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="a"&&this.selectionMode==="multiple"){this.selectCurrentPage(!0),event.preventDefault();return}if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="c"){this.copySelectedRows(),event.preventDefault();return}if(event.shiftKey&&event.key==="F10"&&item&&column&&columnIdValue){this.emitCellContextMenu(event,item,column,columnIdValue,rowPosition);return}const headerEntry=columnIdValue?this.columnIndex.get(columnIdValue):void 0;if(rowPosition<0&&columnIdValue&&headerEntry&&(this.reorderable||headerEntry.column.movable)&&event.shiftKey&&!event.altKey&&(event.key==="ArrowLeft"||event.key==="ArrowRight")){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.moveColumn(columnIdValue,delta,!0),event.preventDefault();return}if(!((event.altKey||event.metaKey)&&event.key.startsWith("Arrow"))){if(rowPosition>=0&&columnPosition===0&&(event.key==="ArrowLeft"||event.key==="ArrowRight")&&!event.altKey&&!event.ctrlKey&&!event.metaKey&&!event.shiftKey&&this.handleDisclosureKey((event.key==="ArrowRight"?1:-1)*rtlMultiplier,rowPosition)){event.preventDefault();return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.focusCell(rowPosition,columnPosition+delta),event.preventDefault()}else if(event.key==="ArrowUp")this.focusCell(rowPosition-1,columnPosition),event.preventDefault();else if(event.key==="ArrowDown")this.focusCell(rowPosition+1,columnPosition),event.preventDefault();else if(event.key==="Home")this.focusCell(event.ctrlKey||event.metaKey?-1:rowPosition,0),event.preventDefault();else if(event.key==="End")this.focusCell(event.ctrlKey||event.metaKey?this.displayItems.length-1:rowPosition,this.visibleColumns.length-1),event.preventDefault();else if(event.key==="PageUp"||event.key==="PageDown"){const delta=event.key==="PageDown"?this.safePageSize||10:-(this.safePageSize||10);this.focusCell(rowPosition+delta,columnPosition),event.preventDefault()}else if(event.key==="Enter")rowPosition<0&&columnIdValue?this.activateSort(columnIdValue,event.shiftKey):item&&column&&columnIdValue&&this.emit("lr-cell-click",Object.freeze({rowKey:item.key,columnId:columnIdValue,column,value:columnValue(column,item.row),row:item.row,index:rowPosition})),event.preventDefault();else if(event.key===" "&&item){const selected=!arrayHasKey(this.selectedKeys,item.key);this.setRowSelected(item,selected,event),event.preventDefault()}else if(event.key===" "&&rowPosition>=0){const group=this.displayItems[rowPosition];if(group?.kind==="group"&&this.selectionMode==="multiple"){const eligible=group.rows.filter(row=>this.rowIsSelectable(row)),sourceIndexes=this.sourceIndexMap(),allSelected=eligible.length>0&&eligible.every((row,index)=>arrayHasKey(this.selectedKeys,this.keyForRow(row,this.sourceIndexFor(row,sourceIndexes)??index)));this.setGroupSelected(group,!allSelected),event.preventDefault()}}}}setGroupSelected(group,selected){const eligible=group.rows.filter(row=>this.rowIsSelectable(row)),sourceIndexes=this.sourceIndexMap(),groupKeys=eligible.map((row,index)=>{const sourceIndex=this.sourceIndexFor(row,sourceIndexes);return this.keyForRow(row,sourceIndex??index)}),groupKeySet=new Set(groupKeys.map(typedKey));let next=this.selectedKeys.filter(key=>!groupKeySet.has(typedKey(key)));selected&&(next=[...next,...groupKeys]),this.selectedKeys=next,this.emitSelection()}userPinColumn(id,side){this.pinColumn(id,side),this.emit("lr-column-pin",Object.freeze({columnId:id,side}))}userToggleColumn(id,visible){this.toggleColumn(id,visible),this.emit("lr-column-visibility-change",Object.freeze({columnId:id,visible}))}renderToolbar(){return!this.withSearch&&!this.withColumnsMenu?nothing:html`
2
2
  <div part="toolbar">
3
3
  ${this.withSearch?html`
4
4
  <div part="search-wrapper">
@@ -2,7 +2,7 @@ import{__decorate}from"tslib";import{HierarchySourceController,hierarchyField,hi
2
2
  mime-type=${node.mimeType??""}
3
3
  name=${node.name??baseName(node.path)}
4
4
  decorative
5
- ></lr-file-icon>`}}willUpdate(changed){if(super.willUpdate(changed),this.hierarchy.update(this.treeSource,this.effectiveLocale),this.treeSource===void 0){this.sourceMode=!1,this.sourceAnnouncement=void 0;return}const entering=!this.sourceMode;this.sourceMode=!0;const reset=this.sourceControlledEpoch!==this.hierarchy.epoch;if(this.sourceControlledEpoch=this.hierarchy.epoch,changed.has("selectedPath")||entering||reset){const next=this.selectedPath,previous=this.sourceControlledPath;if(this.sourceControlledPath=next,!reset&&next===this.sourceSelectedWrite){this.sourceSelectedWrite=void 0;return}this.sourceSelectedWrite=void 0;const key=next??previous;key!==null&&this.applyControlledSelection(key,next!==null)}}async applyControlledSelection(key,selected){try{hierarchyKey(key)}catch{return}const epoch=this.hierarchy.epoch,source=this.treeSource,owner=this.ownerDocument;await this.updateComplete,await this.hierarchy.whenReady(),!(!this.isConnected||this.ownerDocument!==owner||this.hierarchy.epoch!==epoch||this.treeSource!==source||source===void 0||this.selectedPath!==(selected?key:null))&&this.hierarchy.project({type:"select",key,selected,scope:"item"})}updated(changed){super.updated(changed),this.treeSource!==void 0&&this.announceSource()}adoptedCallback(){super.adoptedCallback(),this.sourceModeEpoch++,this.revokeLegacyReveals(),this.sourceAnnouncement=void 0,this.hierarchy.adopted()}disconnectedCallback(){super.disconnectedCallback(),this.sourceModeEpoch++,this.revokeLegacyReveals(),this.sourceAnnouncement=void 0}requestUpdate(name,oldValue){name===void 0&&(this.projectionKey=void 0,this._treeSource!==void 0&&this.hierarchy?.update(this._treeSource,this.effectiveLocale,!0)),super.requestUpdate(name,oldValue)}get treeItems(){const key=[this.nodes,this.effectiveLocale,this.strings,this.effectiveMaxNodes];if(!this.projectionKey||key.some((value,index)=>value!==this.projectionKey[index]))this.projectionKey=key,this.projectedItems=this.nodes.map(node=>this.toTreeItem(node));else if(this.projectedSelection!==this.selectedPath){const affected=new Set;for(const selected of[this.projectedSelection,this.selectedPath])for(let path=selected??void 0;path!==void 0;path=this.parentPathByPath.get(path))affected.add(path);const patch=items=>items.map(item=>affected.has(item.id)?{...item,selected:item.id===this.selectedPath,...item.children?{children:patch(item.children)}:{}}:item);this.projectedItems=patch(this.projectedItems)}return this.projectedSelection=this.selectedPath,this.projectedItems}setChildren(path,children){const target=this.nodesByPath.get(path);if(!target)return;let currentPath=path,replacement={...target,children:normalizeFileTreeNodes(children)};for(;;){const parentPath=this.parentPathByPath.get(currentPath);if(parentPath===void 0)break;const parent=this.nodesByPath.get(parentPath);replacement={...parent,children:parent.children?.map(child=>child.path===currentPath?replacement:child)},currentPath=parentPath}this.nodes=this.nodes.map(node=>node.path===currentPath?replacement:node)}ancestorChain(path){if(!this.nodesByPath.has(path))return[];const chain=[];let current=path;for(;current!==void 0;)chain.push(current),current=this.parentPathByPath.get(current);return chain.reverse()}async revealPath(path){if(this.treeSource!==void 0)return this.revealSourceKey(path);const epoch=this.sourceModeEpoch,owner=this.ownerDocument,nodes=this.nodes,current=()=>this.isConnected&&this.ownerDocument===owner&&this.sourceModeEpoch===epoch&&this.treeSource===void 0&&this.nodes===nodes;if(!current())return!1;const treeEl=this.renderRoot.querySelector(tag("tree"));if(!treeEl)return!1;const chain=this.ancestorChain(path);if(chain.length===0)return!1;let revoke=()=>{};const revoked=new Promise(resolve=>{revoke=resolve});this.pendingLegacyReveals.add(revoke);const settled=async update=>(await Promise.race([update,revoked]),current());try{if(!this.projectsAllNodes&&chain.slice(0,-1).some(id=>!this.expandedPaths.has(id))){for(const id of chain.slice(0,-1))this.expandedPaths.add(id);if(this.requestUpdate(),!await settled(this.updateComplete)||!await settled(treeEl.updateComplete))return!1}let container=treeEl,node=null;for(const id of chain){if(node=(container instanceof LyraTreeItem?[...container.shadowRoot?.querySelectorAll(tag("tree-item"))??[]]:[...container.querySelectorAll(tag("tree-item"))]).find(n=>n.item?.id===id)??null,!node||id!==chain[chain.length-1]&&(node.expanded||node.expand(),!await settled(node.updateComplete)))return!1;container=node}return await settled(treeEl.updateComplete)?(node?.focus(),!0):!1}finally{this.pendingLegacyReveals.delete(revoke)}}expandAll(){if(this.treeSource!==void 0)return;const expandTree=()=>this.renderRoot.querySelector(tag("tree"))?.expandAll();if(this.projectsAllNodes)return expandTree();for(const[path,node]of this.nodesByPath)node.children?.length&&this.expandedPaths.add(path);return this.requestUpdate(),this.updateComplete.then(()=>expandTree())}collapseAll(){this.treeSource===void 0&&this.renderRoot.querySelector(tag("tree"))?.collapseAll()}render(){if(this.treeSource!==void 0)return hierarchySourceView(this.hierarchy,{label:this.getAttribute("aria-label")??this.label??this.localize("fileTreeLabel"),rtl:this.effectiveDirection==="rtl",multiple:!1,loading:this.localize("loading"),error:this.localize("treeSourceError"),empty:this.localize("noData"),retry:this.localize("retry"),expand:this.localize("expand"),collapse:this.localize("collapse"),summary:this.sourceSummary(),name:value=>value.name||value.path,content:value=>{const display=this.toTreeItem(value);return html`${display.icon??nothing}${display.label}${display.description}${display.badges?.map(badge=>html`<span aria-label=${badge.label||nothing}>${badge.text}</span>`)}`},select:row=>{this.hierarchy.project({type:"select",key:row.key,selected:!0,scope:"item"},!0,row)}});const hostLabel=this.getAttribute("aria-label");return html`
5
+ ></lr-file-icon>`}}willUpdate(changed){if(super.willUpdate(changed),this.hierarchy.update(this.treeSource,this.effectiveLocale),this.treeSource===void 0){this.sourceMode=!1,this.sourceAnnouncement=void 0;return}const entering=!this.sourceMode;this.sourceMode=!0;const reset=this.sourceControlledEpoch!==this.hierarchy.epoch;if(this.sourceControlledEpoch=this.hierarchy.epoch,changed.has("selectedPath")||entering||reset){const next=this.selectedPath,previous=this.sourceControlledPath;if(this.sourceControlledPath=next,!reset&&next===this.sourceSelectedWrite){this.sourceSelectedWrite=void 0;return}this.sourceSelectedWrite=void 0;const key=next??previous;key!==null&&this.applyControlledSelection(key,next!==null)}}async applyControlledSelection(key,selected){try{hierarchyKey(key)}catch{return}const epoch=this.hierarchy.epoch,source=this.treeSource,owner=this.ownerDocument;await this.updateComplete,await this.hierarchy.whenReady(),!(!this.isConnected||this.ownerDocument!==owner||this.hierarchy.epoch!==epoch||this.treeSource!==source||source===void 0||this.selectedPath!==(selected?key:null))&&this.hierarchy.project({type:"select",key,selected,scope:"item"})}updated(changed){super.updated(changed),this.treeSource!==void 0&&this.announceSource()}adoptedCallback(){super.adoptedCallback(),this.sourceModeEpoch++,this.revokeLegacyReveals(),this.sourceAnnouncement=void 0,this.hierarchy.adopted()}disconnectedCallback(){super.disconnectedCallback(),this.sourceModeEpoch++,this.revokeLegacyReveals(),this.sourceAnnouncement=void 0}requestUpdate(name,oldValue){name===void 0&&(this.projectionKey=void 0,this._treeSource!==void 0&&this.hierarchy?.update(this._treeSource,this.effectiveLocale,!0)),super.requestUpdate(name,oldValue)}get treeItems(){const key=[this.nodes,this.effectiveLocale,this.strings,this.effectiveMaxNodes];if(!this.projectionKey||key.some((value,index)=>value!==this.projectionKey[index]))this.projectionKey=key,this.projectedItems=this.nodes.map(node=>this.toTreeItem(node));else if(this.projectedSelection!==this.selectedPath){const affected=new Set;for(const selected of[this.projectedSelection,this.selectedPath])for(let path=selected??void 0;path!==void 0;path=this.parentPathByPath.get(path))affected.add(path);const patch=items=>items.map(item=>affected.has(item.id)?{...item,selected:item.id===this.selectedPath,...item.children?{children:patch(item.children)}:{}}:item);this.projectedItems=patch(this.projectedItems)}return this.projectedSelection=this.selectedPath,this.projectedItems}setChildren(path,children){const target=this.nodesByPath.get(path);if(!target)return;let currentPath=path,replacement={...target,children:normalizeFileTreeNodes(children)};for(;;){const parentPath=this.parentPathByPath.get(currentPath);if(parentPath===void 0)break;const parent=this.nodesByPath.get(parentPath);replacement={...parent,children:parent.children?.map(child=>child.path===currentPath?replacement:child)},currentPath=parentPath}this.nodes=this.nodes.map(node=>node.path===currentPath?replacement:node)}ancestorChain(path){if(!this.nodesByPath.has(path))return[];const chain=[];let current=path;for(;current!==void 0;)chain.push(current),current=this.parentPathByPath.get(current);return chain.reverse()}async revealPath(path){if(this.treeSource!==void 0)return this.revealSourceKey(path);const epoch=this.sourceModeEpoch,owner=this.ownerDocument,nodes=this.nodes,current=()=>this.isConnected&&this.ownerDocument===owner&&this.sourceModeEpoch===epoch&&this.treeSource===void 0&&this.nodes===nodes;if(!current())return!1;const treeEl=this.renderRoot.querySelector(tag("tree"));if(!treeEl)return!1;const chain=this.ancestorChain(path);if(chain.length===0)return!1;let revoke=()=>{};const revoked=new Promise(resolve=>{revoke=resolve});this.pendingLegacyReveals.add(revoke);const settled=async update=>(await Promise.race([update,revoked]),current());try{if(!this.projectsAllNodes&&chain.slice(0,-1).some(id=>!this.expandedPaths.has(id))){for(const id of chain.slice(0,-1))this.expandedPaths.add(id);if(this.requestUpdate(),!await settled(this.updateComplete)||!await settled(treeEl.updateComplete))return!1}let container=treeEl,node=null;for(const id of chain){if(node=(container instanceof LyraTreeItem?[...container.shadowRoot?.querySelectorAll(tag("tree-item"))??[]]:[...container.querySelectorAll(tag("tree-item"))]).find(n=>n.item?.id===id)??null,!node||id!==chain[chain.length-1]&&(node.expanded||node.expand(),!await settled(node.updateComplete)))return!1;container=node}return await settled(treeEl.updateComplete)?(node?.focus(),!0):!1}finally{this.pendingLegacyReveals.delete(revoke)}}expandAll(){if(this.treeSource!==void 0)return;const expandTree=()=>this.renderRoot?.querySelector(tag("tree"))?.expandAll();if(this.projectsAllNodes)return expandTree();for(const[path,node]of this.nodesByPath)node.children?.length&&this.expandedPaths.add(path);return this.requestUpdate(),this.updateComplete.then(()=>expandTree())}collapseAll(){this.treeSource===void 0&&this.renderRoot?.querySelector(tag("tree"))?.collapseAll()}render(){if(this.treeSource!==void 0)return hierarchySourceView(this.hierarchy,{label:this.getAttribute("aria-label")??this.label??this.localize("fileTreeLabel"),rtl:this.effectiveDirection==="rtl",multiple:!1,loading:this.localize("loading"),error:this.localize("treeSourceError"),empty:this.localize("noData"),retry:this.localize("retry"),expand:this.localize("expand"),collapse:this.localize("collapse"),summary:this.sourceSummary(),name:value=>value.name||value.path,content:value=>{const display=this.toTreeItem(value);return html`${display.icon??nothing}${display.label}${display.description}${display.badges?.map(badge=>html`<span aria-label=${badge.label||nothing}>${badge.text}</span>`)}`},select:row=>{this.hierarchy.project({type:"select",key:row.key,selected:!0,scope:"item"},!0,row)}});const hostLabel=this.getAttribute("aria-label");return html`
6
6
  <div part="base">
7
7
  <lr-tree
8
8
  .maxNodes=${this.effectiveMaxNodes}